feat(shipping-notice): 落地 XFA 统一视觉拆分确认门禁与处理投影收敛
闭合拆分预览令牌单次消费、样本 checksum 绑定与确认审计;正式提取改为 bindings-only。 同步统一标注工作台交互,并补齐进度投影/任务中心与迁移文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
d2b3d74def
commit
84a881b554
195 files changed
+20269
-3463
No files matched your search
@@ -91,6 +91,14 @@ export type ShippingAuditFilters = {
|
||||
owner_user_id?: string;
|
||||
/** 稳定业务原因码;与后端 audit_query_service.reason_code 对齐 */
|
||||
reason_code?: string;
|
||||
/** 订单模板 Profile ID;匹配 aggregate_id */
|
||||
profile_id?: string;
|
||||
/** 统一 binding_id;匹配 metadata/context_refs */
|
||||
binding_id?: string;
|
||||
/** Draft Revision 序号 */
|
||||
revision_no?: string;
|
||||
/** 拆分 segment_id */
|
||||
segment_id?: string;
|
||||
result?: string;
|
||||
created_from?: string;
|
||||
created_to?: string;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/admin/api/shipping-order-document-profile.api.ts
|
||||
* 用途:订单文档 Profile 管理、MinerU 样本选择和发布 API。
|
||||
* 用途:订单文档 Profile 管理、MinerU 样本选择、XFA 统一建议/视觉绑定与发布 API。
|
||||
* 依赖:shared/api/client、auth headers、Profile DTO。
|
||||
* 逻辑:页面只使用结构化接口;结构指纹和 HTML 始终由后端持有。
|
||||
* 逻辑:页面只使用结构化接口;结构指纹和 HTML 始终由后端持有;XFA suggest/preview 零写 Draft。
|
||||
*/
|
||||
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
@@ -36,6 +36,14 @@ import type {
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
/** 为盲测独立样本重新创建版面解析版本;仅触发布局处理,不修改模板或盲测真值。 */
|
||||
export const reparseOrderProfileSampleLayout = (documentId: number) => requestJson<{
|
||||
id: number; status: string; document_id: number; payload_checksum?: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/documents/${documentId}/layout-reparse`,
|
||||
{ method: 'POST', ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 列出全部 Profile 版本。 */
|
||||
export const listOrderDocumentProfiles = () =>
|
||||
requestJson<ShippingOrderDocumentProfile[]>('/api/admin/shipping-notice/order-document-profiles', auth());
|
||||
@@ -70,6 +78,8 @@ export const saveOrderDocumentProfileDraft = (profileId: number, payload: {
|
||||
profile_code: string; display_name: string; schema_version_id: number;
|
||||
definition: ShippingOrderDocumentProfile['definition']; change_note?: string;
|
||||
expected_lock_version: number; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
/** path_id → 服务端签发的拆分预览确认令牌;confirmed 规则必须携带 */
|
||||
split_rule_confirmation_tokens?: Record<string, string>;
|
||||
}) => requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}`,
|
||||
{ method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
@@ -270,14 +280,18 @@ export const getOrderProfileSampleXfaCollections = (documentId: number) =>
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 按 path_id 读取分级样本值;reveal=true 要求敏感读权限并产生完整访问审计。 */
|
||||
export const previewOrderProfileSampleXfaValue = (documentId: number, pathId: string, reveal = false) =>
|
||||
/** 按 path_id 读取样本值;reveal=true 时需敏感读权限并留痕。 */
|
||||
export const previewOrderProfileSampleXfaValue = (
|
||||
documentId: number,
|
||||
pathId: string,
|
||||
options?: { reveal?: boolean },
|
||||
) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaValuePreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/value-preview`,
|
||||
{ method: 'POST', body: JSON.stringify({ path_id: pathId, reveal }), ...jsonAuth() },
|
||||
{ method: 'POST', body: JSON.stringify({ path_id: pathId, reveal: Boolean(options?.reveal) }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 预览拆分规则执行结果;reveal=true 需 audit_sensitive_read,返回完整值并写访问审计。 */
|
||||
/** 预览拆分规则并签发确认令牌;默认脱敏,reveal 需敏感读权限。 */
|
||||
export const previewOrderProfileSampleXfaSplitRules = (
|
||||
documentId: number,
|
||||
payload: { path_id: string; rule_set: Record<string, unknown>; profile_id?: number; reveal?: boolean },
|
||||
@@ -295,6 +309,147 @@ export const validateOrderProfileXfaSplitRules = (
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 生成 MATNR 类拆分规则建议;不写 Draft。 */
|
||||
export const suggestOrderProfileXfaSplitRules = (
|
||||
profileId: number,
|
||||
payload: { document_id: number; path_id?: string | null },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSplitRulesSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/split-rules/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 统一返回视觉 + 拆分规则建议;不写 Draft。 */
|
||||
export const suggestOrderProfileXfaUnifiedMapping = (
|
||||
profileId: number,
|
||||
payload: {
|
||||
document_id: number;
|
||||
page_no: number;
|
||||
normalized_bbox: import('../types/shipping-order-document-profile.types').XfaNormalizedBBox;
|
||||
path_id?: string | null;
|
||||
include_visual?: boolean;
|
||||
include_split?: boolean;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaUnifiedMappingSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/unified-mapping/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 为页面区域生成 XFA 视觉绑定候选;歧义不自动确认。 */
|
||||
export const suggestOrderProfileXfaVisualBindings = (
|
||||
profileId: number,
|
||||
payload: {
|
||||
document_id: number;
|
||||
page_no: number;
|
||||
normalized_bbox: import('../types/shipping-order-document-profile.types').XfaNormalizedBBox;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingsSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 确认视觉绑定;须携带 Lease / operation_id。 */
|
||||
export const confirmOrderProfileXfaVisualBinding = (
|
||||
profileId: number,
|
||||
bindingId: string,
|
||||
payload: {
|
||||
visual_binding: import('../types/shipping-order-document-profile.types').XfaVisualBinding;
|
||||
path_id?: string | null;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingMutationResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/${encodeURIComponent(bindingId)}/confirm`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 驳回视觉绑定建议;须携带 Lease / operation_id。 */
|
||||
export const rejectOrderProfileXfaVisualBinding = (
|
||||
profileId: number,
|
||||
bindingId: string,
|
||||
payload: {
|
||||
reason_code?: string | null;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingMutationResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/${encodeURIComponent(bindingId)}/reject`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** Dry Run 统一 binding 迁移:只产出报告,不改 definition。 */
|
||||
export const dryRunOrderProfileUnifiedMigration = (profileId: number) =>
|
||||
requestJson<{
|
||||
profile_id: number;
|
||||
dry_run: true;
|
||||
report: {
|
||||
path_preserve_rate: number;
|
||||
field_diff_count: number;
|
||||
pending_visual_count: number;
|
||||
binding_count: number;
|
||||
};
|
||||
binding_preview_count: number;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/unified-migration/dry-run`,
|
||||
{ method: 'POST', body: JSON.stringify({}), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** Execute 统一 binding 迁移:写入 Draft Revision。 */
|
||||
export const executeOrderProfileUnifiedMigration = (
|
||||
profileId: number,
|
||||
payload?: { operation_id?: string },
|
||||
) => requestJson<{
|
||||
profile_id: number;
|
||||
draft_profile_id: number;
|
||||
revision_no: number;
|
||||
dry_run: false;
|
||||
report: {
|
||||
path_preserve_rate: number;
|
||||
field_diff_count: number;
|
||||
pending_visual_count: number;
|
||||
binding_count: number;
|
||||
};
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/unified-migration/execute`,
|
||||
{ method: 'POST', body: JSON.stringify(payload || {}), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取最近一次统一迁移报告(来自审计)。 */
|
||||
export const getOrderProfileUnifiedMigrationReport = (profileId: number) =>
|
||||
requestJson<{
|
||||
profile_id: number;
|
||||
report: Record<string, unknown> | null;
|
||||
event_type: string | null;
|
||||
created_at: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/unified-migration/report`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 扫描全部模板族统一 binding 迁移状态(内存预览,不写 definition)。 */
|
||||
export const scanOrderProfileUnifiedMigration = () =>
|
||||
requestJson<{
|
||||
totals: {
|
||||
total_families: number;
|
||||
needs_migration: number;
|
||||
pending_visual: number;
|
||||
ready: number;
|
||||
pending_visual_bindings: number;
|
||||
};
|
||||
items: Array<{
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
target_profile_id: number;
|
||||
unified_binding_status: 'needs_migration' | 'pending_visual' | 'ready';
|
||||
pending_visual_count: number;
|
||||
needs_migration: boolean;
|
||||
}>;
|
||||
}>(
|
||||
'/api/admin/shipping-notice/order-document-profiles/unified-migration/scan',
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 冻结建议决定;接受后的实际区域修改仍由当前草稿保存接口统一写入 Revision。 */
|
||||
export const decideOrderDocumentProfileSuggestion = (profileId: number, payload: {
|
||||
suggestion_id: string;
|
||||
|
||||
@@ -55,6 +55,10 @@ const filters = ref<ShippingAuditFilters>({
|
||||
gate_code: '',
|
||||
conversation_id: '',
|
||||
owner_user_id: '',
|
||||
profile_id: '',
|
||||
binding_id: '',
|
||||
revision_no: '',
|
||||
segment_id: '',
|
||||
operation_id: '',
|
||||
request_id: '',
|
||||
reason_code: '',
|
||||
@@ -370,8 +374,29 @@ onMounted(() => {
|
||||
<option value="process_gate">{{ t('admin.shippingAudit.filters.eventTypeGroupProcessGate') }}</option>
|
||||
<option value="candidate_qualification">{{ t('admin.shippingAudit.filters.eventTypeGroupQualification') }}</option>
|
||||
<option value="workflow_node">{{ t('admin.shippingAudit.filters.eventTypeGroupWorkflowNode') }}</option>
|
||||
<option value="xfa_visual">{{ t('admin.shippingAudit.filters.eventTypeGroupXfaVisual') }}</option>
|
||||
<option value="xfa_split">{{ t('admin.shippingAudit.filters.eventTypeGroupXfaSplit') }}</option>
|
||||
<option value="xfa_unified">{{ t('admin.shippingAudit.filters.eventTypeGroupXfaUnified') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.profileId') }}</span>
|
||||
<input
|
||||
v-model="filters.profile_id"
|
||||
class="input-field text-sm"
|
||||
data-testid="shipping-audit-filter-profile-id"
|
||||
@keyup.enter="applyFilters"
|
||||
>
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.bindingId') }}</span>
|
||||
<input
|
||||
v-model="filters.binding_id"
|
||||
class="input-field text-sm"
|
||||
data-testid="shipping-audit-filter-binding-id"
|
||||
@keyup.enter="applyFilters"
|
||||
>
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.eventType') }}</span>
|
||||
<input v-model="filters.event_type" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
|
||||
+47
-1
@@ -4,7 +4,7 @@
|
||||
依赖:shipping-audit.api 类型、shippingAuditDisplay、Vue I18n、useMessage。
|
||||
逻辑:由 ShippingAuditCenterPage 传入 detail;事件/动作/结果与列表同源业务标签;
|
||||
展示 before/after checksum 与 XFA snapshot_ref;技术编号以复制芯片展示;
|
||||
关闭时 emit close;不自行拉接口。
|
||||
若快照/metadata 含视觉绑定前后摘要则单独渲染;关闭时 emit close;不自行拉接口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -68,6 +68,33 @@ const techRefs = computed(() => {
|
||||
.filter((item) => Boolean(item.value));
|
||||
});
|
||||
|
||||
/**
|
||||
* 从 before/after 快照或 metadata 提取视觉绑定前后摘要。
|
||||
*/
|
||||
const visualBindingDiff = computed(() => {
|
||||
const d = props.detail as (ShippingAuditEventDetail & {
|
||||
before_snapshot?: Record<string, unknown> | null;
|
||||
after_snapshot?: Record<string, unknown> | null;
|
||||
metadata?: Record<string, unknown>;
|
||||
}) | null;
|
||||
if (!d) return null;
|
||||
const meta = d.metadata && typeof d.metadata === 'object' ? d.metadata : {};
|
||||
const beforeSnap = d.before_snapshot && typeof d.before_snapshot === 'object' ? d.before_snapshot : {};
|
||||
const afterSnap = d.after_snapshot && typeof d.after_snapshot === 'object' ? d.after_snapshot : {};
|
||||
const before =
|
||||
meta.before_visual_binding
|
||||
?? beforeSnap.visual_binding
|
||||
?? beforeSnap.before_visual_binding
|
||||
?? null;
|
||||
const after =
|
||||
meta.after_visual_binding
|
||||
?? afterSnap.visual_binding
|
||||
?? afterSnap.after_visual_binding
|
||||
?? null;
|
||||
if (before == null && after == null) return null;
|
||||
return { before, after };
|
||||
});
|
||||
|
||||
/**
|
||||
* 关闭抽屉。
|
||||
*/
|
||||
@@ -176,6 +203,25 @@ function onClose() {
|
||||
</dl>
|
||||
</details>
|
||||
|
||||
<section
|
||||
v-if="visualBindingDiff"
|
||||
class="mt-5"
|
||||
data-testid="shipping-audit-visual-binding-diff"
|
||||
>
|
||||
<h3 class="text-sm font-semibold">{{ t('admin.shippingAudit.visualBindingDiff') }}</h3>
|
||||
<p class="mt-1 text-[11px] text-muted">{{ t('admin.shippingAudit.visualBindingDiffHint') }}</p>
|
||||
<div class="mt-2 space-y-2 rounded-lg border border-default p-3 text-xs">
|
||||
<div>
|
||||
<div class="font-medium text-muted">{{ t('admin.shippingAudit.before') }}</div>
|
||||
<pre class="mt-1 whitespace-pre-wrap break-all">{{ visualBindingDiff.before == null ? '—' : JSON.stringify(visualBindingDiff.before, null, 2) }}</pre>
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-medium text-muted">{{ t('admin.shippingAudit.after') }}</div>
|
||||
<pre class="mt-1 whitespace-pre-wrap break-all">{{ visualBindingDiff.after == null ? '—' : JSON.stringify(visualBindingDiff.after, null, 2) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="detail.xfa_snapshot_refs?.length"
|
||||
class="mt-5"
|
||||
|
||||
+37
-1
@@ -22,6 +22,7 @@ import {
|
||||
listOrderProfileBlindTestAvailableSamples,
|
||||
listOrderProfileBoundSamples,
|
||||
previewOrderProfileBlindTestCandidate,
|
||||
reparseOrderProfileSampleLayout,
|
||||
removeOrderProfileTestSample,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
@@ -276,6 +277,21 @@ async function previewSample(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 为缺少坐标证据的样本重新触发布局解析;完成后刷新候选状态再进入复核。 */
|
||||
async function reprocessSelectedSample(): Promise<void> {
|
||||
if (!selectedSample.value || selectedSample.value.review_mode !== 'preparing') return;
|
||||
working.value = true;
|
||||
try {
|
||||
await reparseOrderProfileSampleLayout(selectedSample.value.document_id);
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.layoutReparseStarted'));
|
||||
await loadAvailableSamples(true);
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
working.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 将错误明细的管理员更正解析为字段对象;正确项由服务端以候选值固化。 */
|
||||
function reviewedRows(): Array<Record<string, unknown>> | null {
|
||||
const reviews: Array<Record<string, unknown>> = [];
|
||||
@@ -390,6 +406,12 @@ function goToPublishCheck(): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfilePublishCheck', params: route.params, query: { editorSessionId: sessionId } });
|
||||
}
|
||||
|
||||
/** 格式化盲测统一指标百分比。 */
|
||||
function formatMetricRate(value: number | null | undefined): string {
|
||||
if (value == null || Number.isNaN(value)) return '—';
|
||||
return `${Math.round(value * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
onMounted(loadSuite);
|
||||
onBeforeUnmount(() => {
|
||||
stopUploadPolling();
|
||||
@@ -412,6 +434,16 @@ onBeforeUnmount(() => {
|
||||
<template v-else-if="suite">
|
||||
<section class="card suite-summary"><div><h2>{{ t('admin.shippingOrderProfiles.blindTest.samples', { count: suite.sample_count, required: 1, status: t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }) }}</h2><p v-if="suite.latest_run">{{ t('admin.shippingOrderProfiles.blindTest.latestResult', { status: suite.latest_run.status, passed: suite.latest_run.passed_sample_count, count: suite.latest_run.sample_count }) }}</p><p v-else>{{ t('admin.shippingOrderProfiles.blindTest.notRun') }}</p></div><span :class="`status ${suite.status}`">{{ t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }}</span></section>
|
||||
|
||||
<section v-if="suite.latest_run?.metrics" class="card metrics-card">
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.metricsTitle') }}</h2>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.visualCoverage') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.visual_coverage_rate) }}</dd></div>
|
||||
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.evidenceRetention') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.evidence_retention_rate) }}</dd></div>
|
||||
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.mirrorConsistency') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.mirror_consistency_rate) }}</dd></div>
|
||||
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.keyFieldAccuracy') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.key_field_accuracy_rate) }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="failureDetails.length" class="card failure-details">
|
||||
<div><h2>{{ t('admin.shippingOrderProfiles.blindTest.failure.title') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.failure.hint') }}</p></div>
|
||||
<ul><li v-for="failure in failureDetails" :key="failure.code"><span>{{ failure.message }}</span><code>{{ failure.code }}</code></li></ul>
|
||||
@@ -420,7 +452,7 @@ onBeforeUnmount(() => {
|
||||
<section v-if="suite.status === 'draft'" class="card">
|
||||
<div class="sample-heading"><h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2><label class="btn-secondary upload-sample"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploadingSample" @change="uploadIndependentSample"><span>{{ uploadingSample ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.blindTest.uploadSample') }}</span></label></div>
|
||||
<p v-if="availableSamplesLoaded && !availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
|
||||
<div class="sample-picker"><button v-if="!availableSamplesLoaded" type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples()">{{ availableSamplesLoading ? t('admin.shippingOrderProfiles.blindTest.loadingIndependentSamples') : t('admin.shippingOrderProfiles.blindTest.loadIndependentSamples') }}</button><template v-else-if="availableSamples.length"><select v-model="selectedSampleKey" class="select-field"><option value="">{{ t('admin.shippingOrderProfiles.blindTest.selectSamplePlaceholder') }}</option><option v-for="sample in availableSamples" :key="`${sample.document_id}:${sample.table_id}`" :value="`${sample.document_id}:${sample.table_id}`">{{ sampleLabel(sample) }}</option></select><button type="button" class="btn-primary" :disabled="!selectedSample || selectedSample.review_mode === 'preparing' || working" @click="previewSample">{{ selectedSample?.review_mode === 'preparing' ? t('admin.shippingOrderProfiles.blindTest.reviewPreparing') : selectedSample?.review_mode === 'diagnostic' ? t('admin.shippingOrderProfiles.blindTest.viewDiagnostic') : t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button><button type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples(true)">{{ t('admin.shippingOrderProfiles.blindTest.refreshSamples') }}</button></template></div>
|
||||
<div class="sample-picker"><button v-if="!availableSamplesLoaded" type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples()">{{ availableSamplesLoading ? t('admin.shippingOrderProfiles.blindTest.loadingIndependentSamples') : t('admin.shippingOrderProfiles.blindTest.loadIndependentSamples') }}</button><template v-else-if="availableSamples.length"><select v-model="selectedSampleKey" class="select-field"><option value="">{{ t('admin.shippingOrderProfiles.blindTest.selectSamplePlaceholder') }}</option><option v-for="sample in availableSamples" :key="`${sample.document_id}:${sample.table_id}`" :value="`${sample.document_id}:${sample.table_id}`">{{ sampleLabel(sample) }}</option></select><button v-if="selectedSample?.review_mode === 'preparing'" type="button" class="btn-primary" :disabled="working" @click="reprocessSelectedSample">{{ t('admin.shippingOrderProfiles.blindTest.reprocessLayout') }}</button><button v-else type="button" class="btn-primary" :disabled="!selectedSample || working" @click="previewSample">{{ selectedSample?.review_mode === 'diagnostic' ? t('admin.shippingOrderProfiles.blindTest.viewDiagnostic') : t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button><button type="button" class="btn-secondary" :disabled="availableSamplesLoading || working" @click="() => void loadAvailableSamples(true)">{{ t('admin.shippingOrderProfiles.blindTest.refreshSamples') }}</button></template></div>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'materializing' ? t('admin.shippingOrderProfiles.blindTest.sampleMaterializing') : sampleFailureMessage() }}</p>
|
||||
</section>
|
||||
|
||||
@@ -455,6 +487,10 @@ onBeforeUnmount(() => {
|
||||
header, .suite-summary, .execution, .actions, .sample-heading, .sample-picker, li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
header { align-items: flex-start; margin-bottom: 24px; } h1, h2, h3, p { margin: 0; } h2 { font-size: 16px; } h3 { font-size: 14px; } p:not(.section-desc) { margin-top: 6px; color: var(--text-muted); font-size: 13px; line-height: 1.5; }
|
||||
.card { display: grid; gap: 14px; margin-top: 14px; border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); padding: 18px; }
|
||||
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin: 0; }
|
||||
.metrics div { display: grid; gap: 4px; }
|
||||
.metrics dt { color: var(--text-muted); font-size: 12px; }
|
||||
.metrics dd { margin: 0; color: var(--text-primary); font-size: 14px; font-weight: 600; }
|
||||
.status { color: var(--status-warning-fg); font-weight: 700; } .status.approved { color: var(--status-success-fg); } .status.superseded { color: var(--status-error-fg); }
|
||||
.sample-heading { align-items: center; }.sample-picker { justify-content: flex-start; }.sample-picker .select-field { flex: 1; min-width: 0; } .sample-picker button, .upload-sample { flex: 0 0 auto; white-space: nowrap; } .candidate-card .input-field { padding: 8px; border-radius: 6px; } textarea.input-field { min-height: 72px; font-family: ui-monospace, monospace; }
|
||||
.upload-sample { position: relative; cursor: pointer; }.upload-sample input { position: absolute; width: 1px; height: 1px; opacity: 0; }.upload-status { margin: 10px 0 0; color: var(--status-info-fg); font-size: .85rem; }.upload-status.failed { color: var(--status-error-fg); }
|
||||
|
||||
+156
-14
@@ -1,9 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue
|
||||
用途:订单坐标 Profile 的独立草稿标注编辑页。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、shippingOrderField.utils。
|
||||
逻辑:仅编辑由向导创建的草稿;起行锚点默认 customer_po_line_no(内部项次 line_no 亦可绑定);
|
||||
撤销/重做、自动保存和建议决定均受当前标签租约保护。
|
||||
用途:订单文档 Profile 统一草稿标注编辑页(普通 PDF 坐标 + XFA 画布)。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、OrderProfileXfaWorkbench、shippingOrderField.utils。
|
||||
逻辑:template_mode 只决定 desk/右侧数据源能力;XFA 嵌入统一 bench-header/desk,坐标路径零回归。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
@@ -26,6 +25,7 @@ import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
decideOrderDocumentProfileSuggestion,
|
||||
generateOrderProfileOcrCoordinateEvidence,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleTables,
|
||||
listOrderProfileBoundSamples,
|
||||
listOrderProfileSamples,
|
||||
@@ -51,12 +51,16 @@ import type {
|
||||
OrderProfileRowReconstructionMode,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import { asCoordinateProfileDefinition } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import {
|
||||
asCoordinateProfileDefinition,
|
||||
isXfaDatasetProfileDefinition,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import type {
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderSchemaVersion,
|
||||
} from "@/features/admin/types/shipping-order-schema.types";
|
||||
import OrderProfileDocumentCanvas from "./components/OrderProfileDocumentCanvas.vue";
|
||||
import OrderProfileXfaWorkbench from "./OrderProfileXfaWorkbench.vue";
|
||||
import {
|
||||
restoreOrderProfileRegionPageNo,
|
||||
suggestFieldCodeFromHeaders,
|
||||
@@ -70,6 +74,38 @@ const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
/** XFA 草稿走统一编辑器外壳;探测失败 fail-closed,禁止静默进入坐标编辑器。 */
|
||||
const editorMode = ref<'detecting' | 'coordinate' | 'xfa' | 'error'>('detecting');
|
||||
const editorModeError = ref<string | null>(null);
|
||||
const isXfaTemplate = computed(() => editorMode.value === 'xfa');
|
||||
const xfaWorkbenchRef = ref<InstanceType<typeof OrderProfileXfaWorkbench> | null>(null);
|
||||
const xfaDirty = ref(false);
|
||||
const xfaValidateBlocked = ref(false);
|
||||
|
||||
/**
|
||||
* 根据草稿 template_mode / definition 选择统一编辑器分支。
|
||||
* 核心逻辑:仅读取详情鉴别联合;请求失败时阻断并展示重试,不回退到坐标工作台。
|
||||
*/
|
||||
async function detectEditorMode(): Promise<void> {
|
||||
editorMode.value = 'detecting';
|
||||
editorModeError.value = null;
|
||||
try {
|
||||
const profileId = Number(route.params.profileId);
|
||||
if (!Number.isFinite(profileId) || profileId <= 0) {
|
||||
editorMode.value = 'error';
|
||||
editorModeError.value = 'invalid_profile';
|
||||
return;
|
||||
}
|
||||
const profile = await getOrderDocumentProfileDetail(profileId);
|
||||
editorMode.value = (
|
||||
isXfaDatasetProfileDefinition(profile.definition)
|
||||
|| profile.template_mode === 'xfa_dataset'
|
||||
) ? 'xfa' : 'coordinate';
|
||||
} catch {
|
||||
editorMode.value = 'error';
|
||||
editorModeError.value = 'load_failed';
|
||||
}
|
||||
}
|
||||
const profiles = ref<ShippingOrderDocumentProfile[]>([]);
|
||||
const samples = ref<
|
||||
Array<{
|
||||
@@ -254,6 +290,7 @@ const selectedRegionKindLabel = computed(() => {
|
||||
order_anchor: 'orderAnchor', order_field: 'orderField', header_field: 'header',
|
||||
header: 'header', line: 'line', field: 'field', exclusion: 'exclusion',
|
||||
document_anchor_label: 'documentMatchAnchorLabel', document_anchor_value: 'documentMatchAnchorValue',
|
||||
xfa_visual: 'orderField',
|
||||
};
|
||||
const translationKey = translationKeys[kind];
|
||||
return t(`admin.shippingOrderProfiles.workbench.${translationKey}`);
|
||||
@@ -315,7 +352,11 @@ const selectedFieldHeaderSuggestion = computed(() => {
|
||||
)
|
||||
: null;
|
||||
});
|
||||
const dirty = computed(() => history.value.length > 0 || documentMatchDirty.value);
|
||||
const dirty = computed(() => (
|
||||
isXfaTemplate.value
|
||||
? xfaDirty.value
|
||||
: history.value.length > 0 || documentMatchDirty.value
|
||||
));
|
||||
/** 当前标注样本可同时作为训练证据;盲测样本仍由独立工作台维护。 */
|
||||
const currentSampleIsTraining = computed(() => boundSamples.value.some(
|
||||
(item) => item.sample_role === 'training' && item.document_id === form.documentId && item.table_id === form.tableId,
|
||||
@@ -1013,6 +1054,25 @@ const definition = () => {
|
||||
* @returns 保存完成后的最新草稿状态。
|
||||
*/
|
||||
const save = async (automatic = false) => {
|
||||
if (isXfaTemplate.value) {
|
||||
if (saving.value) return;
|
||||
if (!automatic && !xfaDirty.value) return;
|
||||
saving.value = true;
|
||||
saveState.value = 'saving';
|
||||
try {
|
||||
const ok = await xfaWorkbenchRef.value?.saveDraft() ?? false;
|
||||
if (ok) {
|
||||
saveState.value = 'saved';
|
||||
xfaDirty.value = false;
|
||||
if (!automatic) message.success(t('admin.shippingOrderProfiles.xfaWorkbench.saved'));
|
||||
} else if (saveState.value === 'saving') {
|
||||
saveState.value = 'failed';
|
||||
}
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (issues.value.length || saving.value) return;
|
||||
saving.value = true;
|
||||
saveState.value = 'saving';
|
||||
@@ -1724,8 +1784,29 @@ const stopLeaseRenewal = (): void => {
|
||||
const renewLeaseOnVisibility = (): void => {
|
||||
if (document.visibilityState === 'visible') void renewEditLease();
|
||||
};
|
||||
/** 打开路由指定草稿并恢复冻结的标注上下文。 */
|
||||
/** 打开路由指定草稿并恢复冻结的标注上下文;XFA 仅恢复元数据与租约,desk 由 XfaWorkbench 加载。 */
|
||||
const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
const isXfa = isXfaDatasetProfileDefinition(profile.definition)
|
||||
|| profile.template_mode === 'xfa_dataset';
|
||||
if (isXfa) {
|
||||
active.value = profile;
|
||||
form.profileCode = profile.profile_code;
|
||||
form.displayName = profile.display_name;
|
||||
form.schemaId = profile.schema_version_id;
|
||||
form.changeNote = profile.change_note || '';
|
||||
xfaDirty.value = false;
|
||||
try {
|
||||
await acquireEditLease(profile.id);
|
||||
saveState.value = 'saved';
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT') {
|
||||
saveState.value = 'readonly';
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Suppress document/table watchers until both restored canvas regions and the
|
||||
// bound sample are ready; otherwise an old preview request can win the race.
|
||||
restoringProfile = true;
|
||||
@@ -1899,6 +1980,7 @@ const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||
const updateCompactEditor = () => { compactEditor.value = window.innerWidth < 768; };
|
||||
/** 处理不与输入控件冲突的工作台快捷键,让标注、缩放和草稿操作无需离开画布。 */
|
||||
const handleShortcut = (event: KeyboardEvent) => {
|
||||
if (isXfaTemplate.value) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.matches('input, textarea, select, [contenteditable="true"]'))
|
||||
return;
|
||||
@@ -1969,7 +2051,18 @@ const resolveLeave = (allowed: boolean) => {
|
||||
resolveRouteLeave?.(allowed);
|
||||
resolveRouteLeave = null;
|
||||
};
|
||||
const onXfaSaveStateChange = (state: 'saved' | 'saving' | 'failed' | 'readonly') => {
|
||||
saveState.value = state;
|
||||
};
|
||||
const onXfaProfileSaved = (payload: { lockVersion: number }) => {
|
||||
if (!active.value) return;
|
||||
active.value = { ...active.value, lock_version: payload.lockVersion };
|
||||
profiles.value = profiles.value.map((item) => (
|
||||
item.id === active.value?.id ? { ...item, lock_version: payload.lockVersion } : item
|
||||
));
|
||||
};
|
||||
onMounted(async () => {
|
||||
await detectEditorMode();
|
||||
window.addEventListener("beforeunload", beforeUnload);
|
||||
window.addEventListener("keydown", handleShortcut);
|
||||
window.addEventListener("resize", updateCompactEditor);
|
||||
@@ -2004,24 +2097,34 @@ onBeforeUnmount(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="workbench editor-workbench">
|
||||
<p v-if="editorMode === 'detecting'" class="loading">{{ t('admin.shippingOrderProfiles.xfaWorkbench.loading') }}</p>
|
||||
<section v-else-if="editorMode === 'error'" class="editor-mode-error" role="alert">
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.modeDetectFailed') }}</p>
|
||||
<button type="button" class="btn-primary" @click="() => void detectEditorMode()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.retryLoad') }}
|
||||
</button>
|
||||
</section>
|
||||
<section v-else class="workbench editor-workbench">
|
||||
<header class="bench-header">
|
||||
<div class="editor-title">
|
||||
<div>
|
||||
<h1 class="section-title">{{ `${form.displayName || t("admin.shippingOrderProfiles.title")} · ${t("admin.shippingOrderProfiles.updateDraft")}` }}</h1>
|
||||
<p>{{ form.profileCode }}</p>
|
||||
<p>
|
||||
{{ form.profileCode }}
|
||||
<span v-if="isXfaTemplate" class="template-mode-badge">{{ t('admin.shippingOrderProfiles.templateModes.xfa_dataset') }}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<output class="save-status" :class="`save-status--${saveState}`">{{ t(`admin.shippingOrderProfiles.workbench.saveStatus.${saveState}`) }}</output>
|
||||
<div v-if="saveState === 'readonly'" class="header-actions__lease">
|
||||
<button type="button" class="btn-secondary" @click="downloadLocalDraft">{{ t('admin.shippingOrderProfiles.workbench.headerExport') }}</button>
|
||||
<button v-if="!isXfaTemplate" type="button" class="btn-secondary" @click="downloadLocalDraft">{{ t('admin.shippingOrderProfiles.workbench.headerExport') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease()">{{ t('admin.shippingOrderProfiles.workbench.headerRecoverLease') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease(true)">{{ t('admin.shippingOrderProfiles.workbench.headerTakeOverLease') }}</button>
|
||||
</div>
|
||||
<output v-if="active && currentSampleIsTraining" class="training-sample-status">{{ t('admin.shippingOrderProfiles.workbench.headerTrainingSample') }}</output>
|
||||
<output v-if="active && currentSampleIsTraining && !isXfaTemplate" class="training-sample-status">{{ t('admin.shippingOrderProfiles.workbench.headerTrainingSample') }}</output>
|
||||
<button
|
||||
v-else-if="active"
|
||||
v-else-if="active && !isXfaTemplate"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
:disabled="!form.documentId || !form.tableId || saveState === 'readonly'"
|
||||
@@ -2031,7 +2134,9 @@ onBeforeUnmount(() => {
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
:disabled="issues.length > 0 || saving || saveState === 'readonly'"
|
||||
:disabled="isXfaTemplate
|
||||
? (!xfaDirty || saving || saveState === 'readonly')
|
||||
: (issues.length > 0 || saving || saveState === 'readonly')"
|
||||
class="btn-primary"
|
||||
@click="() => void save()"
|
||||
>{{ saving ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.workbench.headerSaveDraft") }}</button>
|
||||
@@ -2039,13 +2144,28 @@ onBeforeUnmount(() => {
|
||||
v-if="active"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
:disabled="isXfaTemplate && (xfaDirty || xfaValidateBlocked)"
|
||||
@click="validateProfile(active)"
|
||||
>{{ t('admin.shippingOrderProfiles.workbench.headerValidate') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">{{ t('admin.shippingOrderProfiles.workbench.headerReturnToLibrary') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="desk editor-desk">
|
||||
<div class="desk editor-desk" :class="{ 'editor-desk--xfa': isXfaTemplate }">
|
||||
<OrderProfileXfaWorkbench
|
||||
v-if="isXfaTemplate && active"
|
||||
ref="xfaWorkbenchRef"
|
||||
:profile-id="active.id"
|
||||
:lease-token="editLeaseToken || ''"
|
||||
:save-state="saveState"
|
||||
:editor-session-id="editorSessionId"
|
||||
@dirty-change="xfaDirty = $event"
|
||||
@save-state-change="onXfaSaveStateChange"
|
||||
@save-request="() => void save()"
|
||||
@profile-saved="onXfaProfileSaved"
|
||||
@validate-blocked-change="xfaValidateBlocked = $event"
|
||||
/>
|
||||
<template v-else-if="!isXfaTemplate">
|
||||
<main>
|
||||
<div v-if="canvasUnavailable" class="canvas-warning">
|
||||
<span>{{
|
||||
@@ -2333,6 +2453,7 @@ onBeforeUnmount(() => {
|
||||
</section>
|
||||
|
||||
</aside>
|
||||
</template>
|
||||
</div>
|
||||
<DeleteConfirmDialog v-model="leaveConfirmOpen" :message="t('admin.shippingOrderProfiles.workbench.leaveConfirm')" confirm-tone="primary" @update:model-value="(visible: boolean) => { if (!visible) resolveLeave(false); }" @confirm="() => resolveLeave(true)" @cancel="() => resolveLeave(false)" />
|
||||
</section>
|
||||
@@ -2361,6 +2482,23 @@ onBeforeUnmount(() => {
|
||||
color: #64748b;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
.template-mode-badge {
|
||||
margin-left: 0.5rem;
|
||||
color: #0369a1;
|
||||
font-weight: 700;
|
||||
}
|
||||
.editor-desk--xfa {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: calc(100dvh - 120px);
|
||||
height: calc(100dvh - 120px);
|
||||
overflow: hidden;
|
||||
}
|
||||
.editor-desk--xfa :deep(.xfa-workbench) {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
.schema-warning,
|
||||
.schema-hint {
|
||||
display: block;
|
||||
@@ -2727,6 +2865,10 @@ onBeforeUnmount(() => {
|
||||
.save-status--saving { background: #dbeafe; color: #1d4ed8; }.save-status--failed,.save-status--readonly { background: #fee2e2; color: #b91c1c; }.save-status--saved { background: #dcfce7; color: #166534; }
|
||||
.training-sample-status { background: #dcfce7; color: #166534; }
|
||||
.editor-workbench { padding: 0; background: #0f172a; }
|
||||
.editor-mode-error {
|
||||
display: flex; flex-direction: column; gap: 12px; align-items: flex-start;
|
||||
margin: 24px; padding: 20px; border: 1px solid #fecaca; border-radius: 0.75rem; background: #fef2f2; color: #991b1b;
|
||||
}
|
||||
.editor-workbench .bench-header { max-width: none; padding: .7rem 1rem; color: #e2e8f0; }
|
||||
.editor-workbench .bench-header p { color: #94a3b8; }
|
||||
.editor-title { min-width: 0; }
|
||||
|
||||
+4
-35
@@ -1,44 +1,13 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorRoutePage.vue
|
||||
用途:按 template_mode 路由 Coordinate 编辑器或 XFA 映射工作台。
|
||||
依赖:Vue Router、Profile 详情 API、OrderProfileEditorPage、XfaProfileMappingPage。
|
||||
逻辑:加载草稿后鉴别联合;coordinate 保持原编辑器,xfa_dataset 进入映射页。
|
||||
用途:订单文档模板草稿编辑入口;普通 PDF 与 XFA 统一进入 OrderProfileEditorPage。
|
||||
依赖:OrderProfileEditorPage。
|
||||
逻辑:不再按 template_mode 分流至 XfaProfileMappingPage;模式差异由统一编辑器内部处理。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getOrderDocumentProfileDetail } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import OrderProfileEditorPage from './OrderProfileEditorPage.vue';
|
||||
import XfaProfileMappingPage from './XfaProfileMappingPage.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const message = useMessage();
|
||||
const ready = ref(false);
|
||||
const isXfa = ref(false);
|
||||
|
||||
/**
|
||||
* 读取草稿 template_mode 后选择编辑器。
|
||||
*/
|
||||
async function prepareEditor(): Promise<void> {
|
||||
try {
|
||||
const profileId = Number(route.params.profileId);
|
||||
const profile = await getOrderDocumentProfileDetail(profileId);
|
||||
isXfa.value = isXfaDatasetProfileDefinition(profile.definition) || profile.template_mode === 'xfa_dataset';
|
||||
ready.value = true;
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(prepareEditor);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<XfaProfileMappingPage v-if="ready && isXfa" />
|
||||
<OrderProfileEditorPage v-else-if="ready" />
|
||||
<OrderProfileEditorPage />
|
||||
</template>
|
||||
+135
-5
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileLibraryPage.vue
|
||||
用途:按 profile_code 聚合展示订单文档模板族,是创建和继续编辑的唯一首页。
|
||||
依赖:Profile family API、Vue Router、Vue I18n。
|
||||
逻辑:列表只选择下一步路由;草稿可继续编辑或删除,已发布版本创建新草稿,历史版本进入只读版本中心。
|
||||
依赖:Profile family API、统一 binding 迁移 scan/dry-run API、Vue Router、Vue I18n。
|
||||
逻辑:列表只选择下一步路由;展示统一 binding 迁移状态与待补框筛选;支持批量 Dry Run。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -11,14 +11,21 @@ import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { cloneOrderDocumentProfile, deleteOrderDocumentProfile, listOrderDocumentProfileFamilies } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import {
|
||||
cloneOrderDocumentProfile,
|
||||
deleteOrderDocumentProfile,
|
||||
dryRunOrderProfileUnifiedMigration,
|
||||
listOrderDocumentProfileFamilies,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileVersionFamilySummary } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const batchDryRunLoading = ref(false);
|
||||
const query = ref('');
|
||||
const migrationFilter = ref<'all' | 'needs_migration' | 'pending_visual'>('all');
|
||||
const families = ref<OrderProfileVersionFamilySummary[]>([]);
|
||||
const deletingDraft = ref<OrderProfileVersionFamilySummary | null>(null);
|
||||
const deleteConfirmOpen = computed({
|
||||
@@ -30,8 +37,27 @@ const deleteConfirmOpen = computed({
|
||||
|
||||
const filteredFamilies = computed(() => {
|
||||
const keyword = query.value.trim().toLowerCase();
|
||||
if (!keyword) return families.value;
|
||||
return families.value.filter((item) => `${item.profile_code} ${item.display_name}`.toLowerCase().includes(keyword));
|
||||
return families.value.filter((item) => {
|
||||
const matchesKeyword = !keyword || `${item.profile_code} ${item.display_name}`.toLowerCase().includes(keyword);
|
||||
if (!matchesKeyword) return false;
|
||||
if (migrationFilter.value === 'needs_migration') {
|
||||
return item.unified_binding_status === 'needs_migration' || item.unified_needs_migration === true;
|
||||
}
|
||||
if (migrationFilter.value === 'pending_visual') {
|
||||
return (item.unified_pending_visual_count ?? 0) > 0 || item.unified_binding_status === 'pending_visual';
|
||||
}
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
const migrationTotals = computed(() => {
|
||||
const needsMigration = families.value.filter(
|
||||
(item) => item.unified_binding_status === 'needs_migration' || item.unified_needs_migration,
|
||||
).length;
|
||||
const pendingVisual = families.value.filter(
|
||||
(item) => (item.unified_pending_visual_count ?? 0) > 0 || item.unified_binding_status === 'pending_visual',
|
||||
).length;
|
||||
return { needsMigration, pendingVisual, total: families.value.length };
|
||||
});
|
||||
|
||||
/** 仅以服务端返回的不可变 Schema 身份决定复制或迁移,列表页不猜测兼容性。 */
|
||||
@@ -105,6 +131,47 @@ function openSchemaMigration(item: OrderProfileVersionFamilySummary): void {
|
||||
});
|
||||
}
|
||||
|
||||
/** 打开版本详情中的统一 binding 迁移 Dry Run 入口。 */
|
||||
function openUnifiedMigration(item: OrderProfileVersionFamilySummary): void {
|
||||
const version = item.draft_version ?? item.published_version ?? item.default_version;
|
||||
router.push({
|
||||
name: 'AdminShippingOrderDocumentProfileVersionDetail',
|
||||
params: { profileCode: item.profile_code, version },
|
||||
query: { unifiedMigration: '1' },
|
||||
});
|
||||
}
|
||||
|
||||
/** 对需迁移模板族批量 Dry Run(只写审计报告,不改 definition)。 */
|
||||
async function runBatchUnifiedMigrationDryRun(): Promise<void> {
|
||||
const targets = families.value.filter(
|
||||
(item) => item.unified_binding_status === 'needs_migration' || item.unified_needs_migration,
|
||||
);
|
||||
if (!targets.length) {
|
||||
message.info(t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunEmpty'));
|
||||
return;
|
||||
}
|
||||
batchDryRunLoading.value = true;
|
||||
let failed = 0;
|
||||
try {
|
||||
for (const item of targets) {
|
||||
const profileId = item.draft_profile_id ?? item.published_profile_id ?? item.default_profile_id;
|
||||
try {
|
||||
await dryRunOrderProfileUnifiedMigration(profileId);
|
||||
} catch {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
await loadFamilies();
|
||||
if (failed) {
|
||||
message.warning(t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunPartial', { failed, total: targets.length }));
|
||||
} else {
|
||||
message.success(t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunDone', { count: targets.length }));
|
||||
}
|
||||
} finally {
|
||||
batchDryRunLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadFamilies);
|
||||
</script>
|
||||
|
||||
@@ -122,8 +189,36 @@ onMounted(loadFamilies);
|
||||
|
||||
<div class="toolbar">
|
||||
<input v-model="query" class="toolbar-input" :placeholder="t('admin.shippingOrderProfiles.library.search')" type="search">
|
||||
<select v-model="migrationFilter" class="toolbar-select" data-testid="order-profile-unified-migration-filter">
|
||||
<option value="all">{{ t('admin.shippingOrderProfiles.unifiedMigration.filterAll') }}</option>
|
||||
<option value="needs_migration">{{ t('admin.shippingOrderProfiles.unifiedMigration.filterNeedsMigration') }}</option>
|
||||
<option value="pending_visual">{{ t('admin.shippingOrderProfiles.unifiedMigration.filterPendingVisual') }}</option>
|
||||
</select>
|
||||
<button
|
||||
class="btn-secondary btn-sm"
|
||||
type="button"
|
||||
data-testid="order-profile-unified-migration-batch-dry-run"
|
||||
:disabled="batchDryRunLoading || migrationTotals.needsMigration === 0"
|
||||
@click="runBatchUnifiedMigrationDryRun"
|
||||
>
|
||||
{{
|
||||
batchDryRunLoading
|
||||
? t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunRunning')
|
||||
: t('admin.shippingOrderProfiles.unifiedMigration.batchDryRun', { count: migrationTotals.needsMigration })
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="families.length" class="migration-summary" data-testid="order-profile-unified-migration-summary">
|
||||
{{
|
||||
t('admin.shippingOrderProfiles.unifiedMigration.librarySummary', {
|
||||
total: migrationTotals.total,
|
||||
needs: migrationTotals.needsMigration,
|
||||
pending: migrationTotals.pendingVisual,
|
||||
})
|
||||
}}
|
||||
</p>
|
||||
|
||||
<section class="library-card" :aria-busy="loading">
|
||||
<p v-if="loading" class="library-state">{{ t('admin.shippingOrderProfiles.library.loading') }}</p>
|
||||
<p v-else-if="!filteredFamilies.length" class="library-state">{{ t('admin.shippingOrderProfiles.library.empty') }}</p>
|
||||
@@ -134,6 +229,7 @@ onMounted(loadFamilies);
|
||||
<th>{{ t('admin.shippingOrderProfiles.name') }}</th>
|
||||
<th>{{ t('admin.shippingOrderProfiles.code') }}</th>
|
||||
<th>{{ t('admin.shippingOrderProfiles.library.status') }}</th>
|
||||
<th>{{ t('admin.shippingOrderProfiles.unifiedMigration.columnTitle') }}</th>
|
||||
<th class="actions-heading">{{ t('admin.shippingOrderProfiles.library.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -151,12 +247,34 @@ onMounted(loadFamilies);
|
||||
: t('admin.shippingOrderProfiles.schemaMigration.versionMatched', { version: item.current_schema_version }) }}
|
||||
</small>
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
v-if="item.unified_binding_status"
|
||||
class="unified-migration-badge"
|
||||
:class="item.unified_binding_status"
|
||||
data-testid="order-profile-unified-migration-status"
|
||||
>
|
||||
{{ t(`admin.shippingOrderProfiles.unifiedMigration.status.${item.unified_binding_status}`) }}
|
||||
</span>
|
||||
<small v-if="(item.unified_pending_visual_count ?? 0) > 0" class="schema-status warning">
|
||||
{{ t('admin.shippingOrderProfiles.unifiedMigration.pendingVisualShort', { count: item.unified_pending_visual_count }) }}
|
||||
</small>
|
||||
</td>
|
||||
<td class="profile-library__actions">
|
||||
<button v-if="item.draft_profile_id" class="btn-ghost btn-sm" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button>
|
||||
<button v-if="item.draft_profile_id" class="btn-danger btn-sm" type="button" @click="requestDeleteDraft(item)">{{ t('admin.delete') }}</button>
|
||||
<button v-else-if="item.published_profile_id && !schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button v-if="!item.draft_profile_id && item.published_profile_id && schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="openSchemaMigration(item)">{{ t('admin.shippingOrderProfiles.schemaMigration.listAction') }}</button>
|
||||
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
|
||||
<button
|
||||
v-if="item.unified_binding_status === 'needs_migration' || item.unified_needs_migration"
|
||||
class="btn-ghost btn-sm"
|
||||
type="button"
|
||||
data-testid="order-profile-unified-migration-open"
|
||||
@click="openUnifiedMigration(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.unifiedMigration.open') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -176,6 +294,18 @@ onMounted(loadFamilies);
|
||||
.page-header h1 { margin: 0; }
|
||||
.page-header p { margin: 0; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.toolbar-select {
|
||||
min-width: 180px; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff;
|
||||
padding: 7px 9px; color: #334155; font: inherit; font-size: 12px;
|
||||
}
|
||||
.migration-summary { margin: 0; color: #64748b; font-size: 12px; }
|
||||
.unified-migration-badge {
|
||||
display: inline-flex; border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc;
|
||||
padding: 3px 8px; color: #64748b; font-size: 11px; font-weight: 600; white-space: nowrap;
|
||||
}
|
||||
.unified-migration-badge.needs_migration { border-color: #fde68a; background: #fffbeb; color: #b45309; }
|
||||
.unified-migration-badge.pending_visual { border-color: #fecaca; background: #fef2f2; color: #b91c1c; }
|
||||
.unified-migration-badge.ready { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
|
||||
.toolbar-input {
|
||||
min-width: 220px; flex: 1 1 220px; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff;
|
||||
padding: 7px 9px; color: #334155; font: inherit; font-size: 12px; outline: none;
|
||||
|
||||
+38
@@ -47,6 +47,30 @@ const gateStatus = computed<'pass' | 'blocked' | 'pending'>(() => {
|
||||
return report.value.blocking_items.length ? 'blocked' : 'pass';
|
||||
});
|
||||
|
||||
/** XFA 统一验证指标:来自 current_sample 运行 summary(阶段 5–6)。 */
|
||||
const xfaValidationMetrics = computed<{
|
||||
visual: number | null;
|
||||
mirror: number | null;
|
||||
evidence: number | null;
|
||||
} | null>(() => {
|
||||
if (!isXfaReport.value) return null;
|
||||
const summary = validationRun.value?.summary;
|
||||
if (!summary || typeof summary !== 'object') return null;
|
||||
const asRate = (value: unknown): number | null => (
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
);
|
||||
const visual = asRate(summary.visual_coverage_rate);
|
||||
const mirror = asRate(summary.mirror_consistency_rate);
|
||||
const evidence = asRate(summary.evidence_retention_rate);
|
||||
if (visual == null && mirror == null && evidence == null) return null;
|
||||
return { visual, mirror, evidence };
|
||||
});
|
||||
|
||||
/** 安全格式化 XFA 指标,避免 template 对 Record 字段推断为 unknown。 */
|
||||
function formatXfaMetric(value: number | null | undefined): string {
|
||||
return formatRate(value);
|
||||
}
|
||||
|
||||
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
|
||||
function fail(error: unknown): void {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.orderProfilePublishCheck.failed'));
|
||||
@@ -140,6 +164,11 @@ function itemMessage(item: Record<string, unknown>): string {
|
||||
cross_template_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
|
||||
sample_role_pollution: t('admin.orderProfilePublishCheck.sampleRolePollution'),
|
||||
cross_template_conflict_profiles: t('admin.orderProfilePublishCheck.crossTemplateConflictProfiles'),
|
||||
xfa_visual_bindings_required: t('admin.orderProfilePublishCheck.xfaVisualBindingsRequired'),
|
||||
xfa_visual_binding_incomplete: t('admin.orderProfilePublishCheck.xfaVisualBindingIncomplete'),
|
||||
xfa_visual_coverage_insufficient: t('admin.orderProfilePublishCheck.xfaVisualCoverageInsufficient'),
|
||||
xfa_evidence_retention_insufficient: t('admin.orderProfilePublishCheck.xfaEvidenceRetentionInsufficient'),
|
||||
xfa_mirror_consistency_insufficient: t('admin.orderProfilePublishCheck.xfaMirrorConsistencyInsufficient'),
|
||||
};
|
||||
return map[key] || String(item.message || t('admin.orderProfilePublishCheck.unknownIssue'));
|
||||
}
|
||||
@@ -237,6 +266,15 @@ onMounted(loadRuns);
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="xfaValidationMetrics" class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.xfaUnifiedMetricsTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaVisualCoverage') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.visual) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaMirrorConsistency') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.mirror) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaEvidenceRetention') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.evidence) }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="conflictProfiles.length" class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.conflictsTitle') }}</h3>
|
||||
<article v-for="conflict in conflictProfiles" :key="`${conflict.profile_code}-${conflict.version}`" class="conflict-card">
|
||||
|
||||
+16
-5
@@ -2,7 +2,7 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue
|
||||
用途:验证当前订单模板草稿,并按“基础验证、盲测、发布检查”顺序引导管理员。
|
||||
依赖:Profile 验证 API、编辑租约、Vue Router、统一消息提示。
|
||||
逻辑:一次动作依次执行结构检查和当前样本试读;XFA 从验证摘要展示脱敏字段级结果;
|
||||
逻辑:一次动作依次执行结构检查和当前样本试读;XFA 从验证摘要展示完整字段级结果;
|
||||
盲测批准前不解锁发布检查入口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -139,6 +139,19 @@ const xfaCrossCheckEntries = computed(() => {
|
||||
const hintKey = `admin.orderProfileValidation.xfaCheckHint.${key}.${status}`;
|
||||
detail = te(hintKey) ? t(hintKey) : '';
|
||||
}
|
||||
if (key === 'acroform_status' && Array.isArray(map.acroform_mismatches) && map.acroform_mismatches.length) {
|
||||
detail = map.acroform_mismatches.map((item) => {
|
||||
const mismatch = item as Record<string, unknown>;
|
||||
const row = mismatch.row_index ? ` #${mismatch.row_index}` : '';
|
||||
return `${String(mismatch.field_code || '-')}${row}: ${String(mismatch.dataset_value ?? '-')} ≠ ${String(mismatch.acroform_value ?? '-')}`;
|
||||
}).join(';');
|
||||
}
|
||||
if (key === 'line_amount_status' && Array.isArray(map.line_amount_failures) && map.line_amount_failures.length) {
|
||||
detail = map.line_amount_failures.map((item) => {
|
||||
const failure = item as Record<string, unknown>;
|
||||
return `#${String(failure.row_index || '-')}: ${String(failure.quantity ?? '-')} × ${String(failure.unit_price ?? '-')} ÷ ${String(failure.price_unit ?? '1')} = ${String(failure.expected_amount ?? '?')},amount=${String(failure.amount ?? '-')}`;
|
||||
}).join(';');
|
||||
}
|
||||
return { key, label, statusLabel, detail, status };
|
||||
});
|
||||
});
|
||||
@@ -344,8 +357,6 @@ onMounted(async () => {
|
||||
<template v-if="isXfa">
|
||||
<dl class="header-results">
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaTemplateMode') }}</dt><dd>XFA</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaRequiredMissing') }}</dt><dd>{{ xfaSummary?.header_required_missing_count ?? '-' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaAutoCreateMissing') }}</dt><dd>{{ xfaSummary?.auto_create_key_missing_count ?? '-' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaLineRows') }}</dt><dd>{{ xfaSummary?.line_row_count ?? '-' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaCrossChecks') }}</dt><dd>{{ Array.isArray(xfaSummary?.cross_check_failures) && xfaSummary.cross_check_failures.length ? xfaSummary.cross_check_failures.join(', ') : t('admin.orderProfileValidation.xfaCrossChecksPassed') }}</dd></div>
|
||||
</dl>
|
||||
@@ -372,7 +383,7 @@ onMounted(async () => {
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
@@ -390,7 +401,7 @@ onMounted(async () => {
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
+94
-3
@@ -1,9 +1,10 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue
|
||||
用途:订单模板版本中心详情页,支持刷新恢复与分享。
|
||||
依赖:版本详情 composable、配置概览组件、版本中心 API。
|
||||
依赖:版本详情 composable、配置概览组件、版本中心 API、统一迁移 API。
|
||||
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;
|
||||
Schema 迁移弹窗按模态语义提供初始焦点、Tab 陷阱、Escape 关闭与焦点恢复。
|
||||
Schema 迁移弹窗按模态语义提供初始焦点、Tab 陷阱、Escape 关闭与焦点恢复;
|
||||
统一 binding 迁移提供 Dry Run 状态徽章入口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
@@ -13,6 +14,8 @@ import { BusinessError } from "@/shared/api/client";
|
||||
import { useMessage } from "@/shared/composables/useMessage";
|
||||
import {
|
||||
cloneOrderDocumentProfile,
|
||||
dryRunOrderProfileUnifiedMigration,
|
||||
getOrderProfileUnifiedMigrationReport,
|
||||
migrateOrderDocumentProfileSchema,
|
||||
} from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
|
||||
@@ -33,6 +36,13 @@ const router = useRouter();
|
||||
const message = useMessage();
|
||||
const cloning = ref(false);
|
||||
const migrating = ref(false);
|
||||
const unifiedMigrating = ref(false);
|
||||
const unifiedMigrationReport = ref<{
|
||||
path_preserve_rate?: number;
|
||||
field_diff_count?: number;
|
||||
pending_visual_count?: number;
|
||||
binding_count?: number;
|
||||
} | null>(null);
|
||||
const migrationOpen = ref(false);
|
||||
const publishedSchema = ref<ShippingOrderSchemaVersion | null>(null);
|
||||
const migrationResolutions = ref<Record<string, { action: "unbind" } | { replacement_field_id: string }>>({});
|
||||
@@ -302,6 +312,51 @@ const createNewVersion = async () => {
|
||||
cloning.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 加载最近一次统一 binding 迁移报告(若有)。
|
||||
*/
|
||||
async function loadUnifiedMigrationReport(): Promise<void> {
|
||||
if (!detail.value?.id) {
|
||||
unifiedMigrationReport.value = null;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const payload = await getOrderProfileUnifiedMigrationReport(detail.value.id);
|
||||
unifiedMigrationReport.value = (payload.report as typeof unifiedMigrationReport.value) || null;
|
||||
} catch {
|
||||
unifiedMigrationReport.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dry Run 统一 binding 迁移并刷新状态徽章。
|
||||
*/
|
||||
async function runUnifiedMigrationDryRun(): Promise<void> {
|
||||
if (!detail.value?.id || unifiedMigrating.value) return;
|
||||
unifiedMigrating.value = true;
|
||||
try {
|
||||
const result = await dryRunOrderProfileUnifiedMigration(detail.value.id);
|
||||
unifiedMigrationReport.value = result.report;
|
||||
message.success(t("admin.shippingOrderProfiles.unifiedMigration.dryRunDone"));
|
||||
} catch (error) {
|
||||
message.error(
|
||||
error instanceof BusinessError
|
||||
? error.message
|
||||
: t("admin.shippingOrderProfiles.unifiedMigration.dryRunFailed"),
|
||||
);
|
||||
} finally {
|
||||
unifiedMigrating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => detail.value?.id,
|
||||
() => {
|
||||
void loadUnifiedMigrationReport();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -346,6 +401,31 @@ const createNewVersion = async () => {
|
||||
>
|
||||
{{ t("admin.shippingOrderProfiles.schemaMigration.action", { version: publishedSchema?.version }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-ghost"
|
||||
data-testid="order-profile-unified-migration-dry-run"
|
||||
:disabled="unifiedMigrating"
|
||||
@click="runUnifiedMigrationDryRun"
|
||||
>
|
||||
{{
|
||||
unifiedMigrating
|
||||
? t("admin.shippingOrderProfiles.unifiedMigration.running")
|
||||
: t("admin.shippingOrderProfiles.unifiedMigration.dryRun")
|
||||
}}
|
||||
</button>
|
||||
<span
|
||||
v-if="unifiedMigrationReport"
|
||||
class="unified-migration-badge"
|
||||
data-testid="order-profile-unified-migration-badge"
|
||||
>
|
||||
{{
|
||||
t("admin.shippingOrderProfiles.unifiedMigration.badge", {
|
||||
pending: unifiedMigrationReport.pending_visual_count ?? 0,
|
||||
diff: unifiedMigrationReport.field_diff_count ?? 0,
|
||||
})
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -503,7 +583,18 @@ const createNewVersion = async () => {
|
||||
.header-kicker { margin-bottom: 0.25rem; }
|
||||
.header-meta { margin-top: 0.35rem; overflow-wrap: anywhere; }
|
||||
|
||||
.header-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 0.5rem; }
|
||||
.header-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 0.5rem; align-items: center; }
|
||||
|
||||
.unified-migration-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 999px;
|
||||
padding: 0.25rem 0.7rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-muted, transparent);
|
||||
}
|
||||
|
||||
.tab-button,
|
||||
.version-item {
|
||||
|
||||
+86
-122
@@ -1,13 +1,12 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/XfaProfileMappingPage.spec.ts
|
||||
* 用途:挂载 XFA 映射页并验证四栏布局加载。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaProfileMappingPage。
|
||||
* features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.spec.ts
|
||||
* 用途:挂载统一编辑器 desk 内 XFA 片段并验证布局与诊断抽屉(无独立 Header)。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaProfileMappingPage from './XfaProfileMappingPage.vue';
|
||||
import XfaSplitRulePanel from './components/XfaSplitRulePanel.vue';
|
||||
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
|
||||
|
||||
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
|
||||
saveDraftMock: vi.fn(),
|
||||
@@ -15,6 +14,13 @@ const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => (
|
||||
detailDefinition: { value: null as Record<string, unknown> | null },
|
||||
}));
|
||||
|
||||
const defaultProps = {
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved' as const,
|
||||
editorSessionId: 'editor-session',
|
||||
};
|
||||
|
||||
const baseDefinition = {
|
||||
template_mode: 'xfa_dataset' as const,
|
||||
source_contract: {
|
||||
@@ -38,7 +44,6 @@ const baseDefinition = {
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({ params: { profileId: '52', profileCode: 'ODP-TEST' }, query: {} }),
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
onBeforeRouteLeave: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
@@ -77,6 +82,13 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderProfileSampleXfaCollections: vi.fn(async () => ({
|
||||
collection_candidates: [{ path_id: 'items-data', collection_path_hash: 'h', row_count: 1 }],
|
||||
})),
|
||||
authorizeOrderProfilePreviewPages: vi.fn(async () => ({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
})),
|
||||
suggestOrderProfileXfaUnifiedMapping: vi.fn(),
|
||||
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
|
||||
renewOrderDocumentProfileEditLease: vi.fn(),
|
||||
releaseOrderDocumentProfileEditLease: vi.fn(),
|
||||
@@ -111,33 +123,13 @@ vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/auth/stores/auth.store', () => ({
|
||||
useAuthStore: () => ({
|
||||
user: {
|
||||
feature_permissions: {
|
||||
'shipping_notice.xfa_split_rule_edit': true,
|
||||
'shipping_notice.xfa_split_rule_preview': true,
|
||||
'shipping_notice.audit_sensitive_read': true,
|
||||
},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('pinia', async () => {
|
||||
const actual = await vi.importActual<typeof import('pinia')>('pinia');
|
||||
return {
|
||||
...actual,
|
||||
storeToRefs: (store: { user: unknown }) => ({ user: { value: store.user } }),
|
||||
};
|
||||
});
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
fallbackLocale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
common: { yes: '是', no: '否' },
|
||||
common: { yes: '是', no: '否', close: '关闭' },
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
templateModes: { xfa_dataset: 'XFA' },
|
||||
@@ -149,6 +141,23 @@ const i18n = createI18n({
|
||||
headerTakeOverLease: '接管',
|
||||
saveStatus: { saved: '已保存', saving: '保存中', failed: '失败', readonly: '只读' },
|
||||
leaveConfirm: '离开?',
|
||||
annotationCanvasAriaLabel: '画布',
|
||||
loadingPage: '加载',
|
||||
selectBoundPdf: '选择 PDF',
|
||||
zoomIn: '+', zoomOut: '-', fitPage: '适合',
|
||||
pageNavigation: '页',
|
||||
},
|
||||
xfaUnified: {
|
||||
drawFieldBox: '画框',
|
||||
suggesting: '分析中',
|
||||
openDiagnostics: '高级诊断',
|
||||
diagnosticsDrawerTitle: '诊断',
|
||||
diagnosticsSummary: '{mapped}/{total}',
|
||||
candidatePanelTitle: '候选',
|
||||
acceptCandidate: '采用',
|
||||
confirmVisual: '确认',
|
||||
rejectVisual: '驳回',
|
||||
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
|
||||
},
|
||||
xfaWorkbench: {
|
||||
loading: '加载', loadFailed: '失败', saved: '已保存', saveFailed: '失败', scopeMismatch: 'scope',
|
||||
@@ -169,125 +178,80 @@ const i18n = createI18n({
|
||||
collectionsTitle: '集合', authoritativeCollection: '权威', selectAuthoritative: '选择',
|
||||
mirrorCollections: '镜像', rowCount: '{count} 行',
|
||||
},
|
||||
xfaUnified: {
|
||||
drawFieldBox: '画字段框', suggesting: '匹配中', suggestFailed: '建议失败',
|
||||
candidatePanelTitle: '候选', acceptCandidate: '采用',
|
||||
confirmVisual: '确认', rejectVisual: '驳回',
|
||||
confirmSuccess: '确认成功', confirmFailed: '确认失败',
|
||||
rejectSuccess: '驳回成功', rejectFailed: '驳回失败',
|
||||
diagnosticsSummary: '{mapped}/{total}', openDiagnostics: '高级诊断',
|
||||
diagnosticsDrawerTitle: '诊断',
|
||||
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
|
||||
},
|
||||
xfaSplit: {
|
||||
title: '拆分', addRule: '新增', deleteConfirm: '删除?', deleteRule: '删', ruleLabel: '规则 {index}', unnamedRule: '未命名',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaProfileMappingPage', () => {
|
||||
describe('OrderProfileXfaWorkbench', () => {
|
||||
beforeEach(() => {
|
||||
saveDraftMock.mockReset();
|
||||
splitPreviewMock.mockReset();
|
||||
detailDefinition.value = null;
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
blob: async () => new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }),
|
||||
})));
|
||||
vi.stubGlobal('URL', {
|
||||
...URL,
|
||||
createObjectURL: vi.fn(() => 'blob:mock-page'),
|
||||
revokeObjectURL: vi.fn(),
|
||||
});
|
||||
});
|
||||
|
||||
const mountPage = async () => {
|
||||
const wrapper = mount(XfaProfileMappingPage, { global: { plugins: [i18n] } });
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
const wrapper = mount(OrderProfileXfaWorkbench, {
|
||||
props: defaultProps,
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
await flushPromises();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
if (wrapper.find('.xfa-workbench__grid').exists()) break;
|
||||
if (wrapper.find('.xfa-workbench__desk').exists()) break;
|
||||
}
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
it('mounts four-column grid after bootstrap', async () => {
|
||||
it('mounts canvas-first desk after bootstrap without standalone header', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.find('.xfa-workbench__grid').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-tree').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-schema__filters').text()).not.toContain('必填');
|
||||
expect(wrapper.find('.xfa-workbench__desk').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-workbench__header').exists()).toBe(false);
|
||||
expect(wrapper.find('.xfa-workbench__canvas').exists()).toBe(true);
|
||||
expect(wrapper.find('.canvas-shell').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-tree').exists()).toBe(false);
|
||||
|
||||
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
|
||||
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(true);
|
||||
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
|
||||
expect(wrapper.find('.diagnostics-drawer .xfa-tree').exists()).toBe(true);
|
||||
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
|
||||
}, 15000);
|
||||
|
||||
it('opens readonly diagnostics drawer from panel footer', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(true);
|
||||
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
|
||||
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('persists confirmed rules and renders them below the source tree node', async () => {
|
||||
saveDraftMock.mockResolvedValueOnce({
|
||||
id: 52, profile_code: 'ODP-TEST', display_name: 'Fox PO', schema_version_id: 1, lock_version: 2,
|
||||
template_mode: 'xfa_dataset',
|
||||
definition: {
|
||||
...structuredClone(baseDefinition),
|
||||
split_rules: [{
|
||||
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
|
||||
strategy: 'pipeline', status: 'confirmed', requires_confirmation: false, source: 'user',
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1,
|
||||
stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'mapped', target_field_id: 'f1', target_field_code: 'customer_po_no' },
|
||||
}],
|
||||
}],
|
||||
},
|
||||
});
|
||||
splitPreviewMock.mockResolvedValueOnce({
|
||||
preview: {
|
||||
segments: [{ rule_id: 'rule-1', normalized_text: 'TEMP••922', raw_text: 'TEMP-922' }],
|
||||
},
|
||||
});
|
||||
it('emits dirty-change when local definition diverges from saved snapshot', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const rules = [{
|
||||
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
|
||||
strategy: 'pipeline' as const, status: 'confirmed' as const, requires_confirmation: false, source: 'user' as const,
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1,
|
||||
stages: [{ stage_id: 'stage-1', type: 'select_line' as const, line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'mapped' as const, target_field_id: 'f1', target_field_code: 'customer_po_no' },
|
||||
}],
|
||||
}];
|
||||
wrapper.findComponent(XfaSplitRulePanel).vm.$emit('confirmed', rules);
|
||||
await flushPromises();
|
||||
|
||||
expect(saveDraftMock).toHaveBeenCalledWith(52, expect.objectContaining({
|
||||
definition: expect.objectContaining({ split_rules: rules }),
|
||||
}));
|
||||
expect(wrapper.find('[data-xfa-path-id="material-path"] + .xfa-tree__rules').text()).toContain('客户料号');
|
||||
expect(wrapper.find('.xfa-schema').text()).toContain('TEMP••922');
|
||||
expect(wrapper.findAll('.field__value').map((item) => item.text())).not.toContain('TEMP-S');
|
||||
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the rule dialog open when confirmed rules fail to save', async () => {
|
||||
saveDraftMock.mockRejectedValueOnce(new Error('save failed'));
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
|
||||
await flushPromises();
|
||||
const rules = [{
|
||||
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
|
||||
strategy: 'pipeline' as const, status: 'confirmed' as const, requires_confirmation: false,
|
||||
rules: [],
|
||||
}];
|
||||
wrapper.findComponent(XfaSplitRulePanel).vm.$emit('confirmed', rules);
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('allows a header source split rule to map a header field only', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
split_rules: [{
|
||||
rule_id: 'header-rules', rule_version: 1, source_path_id: 'invoiced-to-path', source_field_code: 'INVOICED_TO',
|
||||
strategy: 'pipeline', status: 'confirmed', requires_confirmation: false, source: 'user',
|
||||
rules: [{
|
||||
rule_id: 'bill-rule', order: 1,
|
||||
stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-bill', segment_code: 'bill_customer', display_name: '账款客户', handling: 'evidence_only' },
|
||||
}],
|
||||
}],
|
||||
};
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.find('[data-xfa-path-id="invoiced-to-path"] + .xfa-tree__rules .xfa-tree__rule-main').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const billButton = wrapper.findAll('button.field').find((item) => item.text().includes('bill_to_customer'));
|
||||
const lineButton = wrapper.findAll('button.field').find((item) => item.text().includes('part_number'));
|
||||
expect(billButton?.attributes('disabled')).toBeUndefined();
|
||||
expect(lineButton?.attributes('disabled')).toBeDefined();
|
||||
await billButton?.trigger('click');
|
||||
expect((wrapper.vm as unknown as { definition: typeof baseDefinition }).definition.split_rules?.[0].rules[0].segment)
|
||||
.toMatchObject({ handling: 'mapped', target_field_id: 'f-bill', target_field_code: 'bill_to_customer' });
|
||||
expect(wrapper.emitted('dirty-change')?.[0]).toEqual([false]);
|
||||
});
|
||||
});
|
||||
+1198
File diff suppressed because it is too large.
Load diff
-748
@@ -1,748 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/XfaProfileMappingPage.vue
|
||||
用途:XFA 四栏映射工作台(数据树 / 拆分规则 / Schema / 预览),复用 Lease/Revision/operation_id。
|
||||
依赖:Profile/XFA API、Schema API、Xfa* 组件、xfaProfileMapping.utils。
|
||||
逻辑:加载草稿与样本树;权威集合必选后可保存;租约 409 进入只读;脏状态离开确认。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
previewOrderProfileSampleXfaSplitRules,
|
||||
previewOrderProfileSampleXfaValue,
|
||||
listOrderProfileBoundSamples,
|
||||
releaseOrderDocumentProfileEditLease,
|
||||
renewOrderDocumentProfileEditLease,
|
||||
saveOrderDocumentProfileDraft,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaCollectionCandidate,
|
||||
XfaFieldTreeNode,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
import XfaDatasetTree from './components/XfaDatasetTree.vue';
|
||||
import XfaSchemaMappingPanel from './components/XfaSchemaMappingPanel.vue';
|
||||
import XfaSplitRulePanel from './components/XfaSplitRulePanel.vue';
|
||||
import {
|
||||
bindXfaSchemaField,
|
||||
buildXfaPathLabel,
|
||||
computeXfaMappingCoverage,
|
||||
flattenXfaTreeNodes,
|
||||
isSameXfaDefinition,
|
||||
resolveAuthoritativePathId,
|
||||
resolveMirrorPathIds,
|
||||
resolveXfaNodeScope,
|
||||
summarizeXfaMappingBlockers,
|
||||
unbindXfaSchemaField,
|
||||
} from './xfaProfileMapping.utils';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
|
||||
const profileId = computed(() => Number(route.params.profileId));
|
||||
const editorSessionId = String(route.query.editorSessionId || crypto.randomUUID());
|
||||
const loading = ref(true);
|
||||
const loadError = ref(false);
|
||||
const saving = ref(false);
|
||||
const saveState = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
const editLeaseToken = ref('');
|
||||
const lockVersion = ref(0);
|
||||
const schemaFields = ref<ShippingOrderFieldConfig[]>([]);
|
||||
const definition = ref<OrderXfaDatasetProfileDefinition | null>(null);
|
||||
const savedSnapshot = ref<OrderXfaDatasetProfileDefinition | null>(null);
|
||||
const tree = ref<XfaFieldTreeNode | null>(null);
|
||||
const collections = ref<XfaCollectionCandidate[]>([]);
|
||||
const excludedCollections = ref<XfaCollectionCandidate[]>([]);
|
||||
const annotationDocumentId = ref(0);
|
||||
const selectedPathId = ref<string | null>(null);
|
||||
const selectedPathIsLeaf = ref(false);
|
||||
const selectedRuleId = ref<string | null>(null);
|
||||
const splitRuleDialogOpen = ref(false);
|
||||
const splitRuleDialogAutoAdd = ref(false);
|
||||
const splitRulePanel = ref<{ addRule: () => void; runPreview: () => void; confirmRules: () => void } | null>(null);
|
||||
const dialogDefinition = ref<OrderXfaDatasetProfileDefinition | null>(null);
|
||||
const revealedValues = ref<Record<string, string>>({});
|
||||
const splitRulePreviewValues = ref<Record<string, string>>({});
|
||||
const revealingPathId = ref('');
|
||||
const revealTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const authoritativePathId = ref('');
|
||||
const mirrorPathIds = ref<string[]>([]);
|
||||
const displayName = ref('');
|
||||
const profileCode = ref('');
|
||||
const schemaVersionId = ref(0);
|
||||
let renewTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const flatNodes = computed(() => flattenXfaTreeNodes(tree.value));
|
||||
const selectedPathLabel = computed(() => (
|
||||
selectedPathId.value ? buildXfaPathLabel(selectedPathId.value, flatNodes.value) : ''
|
||||
));
|
||||
const selectedFieldCode = computed(() => {
|
||||
if (!selectedPathId.value) return '';
|
||||
return flatNodes.value.find((item) => item.pathId === selectedPathId.value)?.localName || '';
|
||||
});
|
||||
const selectedIsMultiline = computed(() => {
|
||||
if (!selectedPathId.value) return false;
|
||||
const node = flatNodes.value.find((item) => item.pathId === selectedPathId.value);
|
||||
return (node?.lineCount || 0) > 1;
|
||||
});
|
||||
const selectedSourceScope = computed(() => (
|
||||
selectedPathId.value
|
||||
? resolveXfaNodeScope(selectedPathId.value, authoritativePathId.value, flatNodes.value)
|
||||
: null
|
||||
));
|
||||
const canEditSplitRules = computed(() => saveState.value !== 'readonly');
|
||||
const canPreviewSplitRules = computed(() => true);
|
||||
const canRevealSensitiveSplit = computed(() => true);
|
||||
const splitRulePersistedConfirmed = computed(() => {
|
||||
const pathId = selectedPathId.value;
|
||||
if (!pathId || !definition.value || !savedSnapshot.value) return true;
|
||||
const current = (definition.value.split_rules || []).find((item) => item.source_path_id === pathId);
|
||||
if (!current || current.status !== 'confirmed') return true;
|
||||
const saved = (savedSnapshot.value.split_rules || []).find((item) => item.source_path_id === pathId);
|
||||
return !!saved && JSON.stringify(current) === JSON.stringify(saved);
|
||||
});
|
||||
const mappedFieldPreviews = computed(() => {
|
||||
if (!definition.value) return { header: [], line: [] };
|
||||
const byPath = new Map(flatNodes.value.map((item) => [item.pathId, item]));
|
||||
const mapItems = (items: Array<{ mapping_id: string; field_code: string; path_id: string }>) =>
|
||||
items.map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: byPath.get(item.path_id)
|
||||
? buildXfaPathLabel(item.path_id, flatNodes.value)
|
||||
: item.path_id,
|
||||
maskedValue: revealedValues.value[item.path_id] || byPath.get(item.path_id)?.sampleValueDisplay || null,
|
||||
}));
|
||||
const splitItems = (definition.value.split_rules || []).flatMap((ruleSet) =>
|
||||
[...ruleSet.rules]
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.filter((rule) => rule.segment.handling === 'mapped' && rule.segment.target_field_code)
|
||||
.map((rule, index) => ({
|
||||
mappingId: rule.segment.segment_id,
|
||||
fieldCode: String(rule.segment.target_field_code),
|
||||
pathId: ruleSet.source_path_id,
|
||||
pathLabel: `${buildXfaPathLabel(ruleSet.source_path_id, flatNodes.value)} / ${t('admin.shippingOrderProfiles.xfaSplit.ruleLabel', { index: index + 1 })} · ${rule.segment.display_name || rule.segment.segment_code}`,
|
||||
maskedValue: splitRulePreviewValues.value[rule.rule_id] || null,
|
||||
})),
|
||||
);
|
||||
const splitItemsByScope = splitItems.reduce((groups, item) => {
|
||||
const scope = resolveXfaNodeScope(item.pathId, authoritativePathId.value, flatNodes.value);
|
||||
if (scope) groups[scope].push(item);
|
||||
return groups;
|
||||
}, { header: [] as typeof splitItems, line: [] as typeof splitItems });
|
||||
return {
|
||||
header: [...mapItems(definition.value.header_mappings || []), ...splitItemsByScope.header],
|
||||
line: [...mapItems(definition.value.line_mapping?.fields || []), ...splitItemsByScope.line],
|
||||
};
|
||||
});
|
||||
|
||||
const dirty = computed(() => !isSameXfaDefinition(definition.value, savedSnapshot.value)
|
||||
|| Boolean(authoritativePathId.value && definition.value
|
||||
&& authoritativePathId.value !== savedAuthoritativePathId.value)
|
||||
|| JSON.stringify([...mirrorPathIds.value].sort()) !== JSON.stringify([...savedMirrorPathIds.value].sort()));
|
||||
const savedAuthoritativePathId = ref('');
|
||||
const savedMirrorPathIds = ref<string[]>([]);
|
||||
|
||||
/**
|
||||
* 将 XFA JSON 契约数据复制为不含 Vue Proxy 的普通对象。
|
||||
* 核心逻辑:定义和规则契约只包含可序列化字段;JSON 快照可安全跨越组件事件与保存 payload。
|
||||
* @param value 当前响应式或普通 JSON 契约数据
|
||||
* @returns 可独立编辑和持久化的纯对象副本
|
||||
*/
|
||||
function cloneXfaData<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
const coverage = computed(() => computeXfaMappingCoverage(
|
||||
schemaFields.value,
|
||||
definition.value || undefined,
|
||||
authoritativePathId.value,
|
||||
));
|
||||
const blockers = computed(() => summarizeXfaMappingBlockers(coverage.value));
|
||||
const mappedPathIds = computed(() => {
|
||||
if (!definition.value) return [];
|
||||
return [
|
||||
...definition.value.header_mappings.map((item) => item.path_id),
|
||||
...definition.value.line_mapping.fields.map((item) => item.path_id),
|
||||
];
|
||||
});
|
||||
const splitRuleSets = computed(() => definition.value?.split_rules || []);
|
||||
const dialogHasRules = computed(() => Boolean(
|
||||
selectedPathId.value
|
||||
&& dialogDefinition.value?.split_rules?.find((item) => item.source_path_id === selectedPathId.value)?.rules.length,
|
||||
));
|
||||
|
||||
/**
|
||||
* 获取或恢复编辑租约。
|
||||
*/
|
||||
async function acquireLease(confirmTakeover = false): Promise<void> {
|
||||
try {
|
||||
const lease = await acquireOrderDocumentProfileEditLease(profileId.value, {
|
||||
browser_session_id: editorSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
confirm_takeover: confirmTakeover,
|
||||
});
|
||||
editLeaseToken.value = lease.lease_token;
|
||||
saveState.value = 'saved';
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && String(error.code || '').includes('LEASE')) {
|
||||
saveState.value = 'readonly';
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已保存 definition 恢复权威/镜像集合选择(按路径哈希精确匹配)。
|
||||
*/
|
||||
async function restoreCollectionSelection(def: OrderXfaDatasetProfileDefinition): Promise<void> {
|
||||
const flat = flattenXfaTreeNodes(tree.value);
|
||||
const restoredAuth = await resolveAuthoritativePathId(def, collections.value, flat);
|
||||
authoritativePathId.value = restoredAuth;
|
||||
savedAuthoritativePathId.value = restoredAuth;
|
||||
const restoredMirrors = await resolveMirrorPathIds(def, collections.value, restoredAuth);
|
||||
mirrorPathIds.value = restoredMirrors;
|
||||
savedMirrorPathIds.value = [...restoredMirrors];
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 Profile、Schema、XFA 树与集合,并恢复已保存权威/镜像选择。
|
||||
*/
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
loadError.value = false;
|
||||
try {
|
||||
const [profile, schemaState, samples] = await Promise.all([
|
||||
getOrderDocumentProfileDetail(profileId.value),
|
||||
getShippingOrderSchemaState(),
|
||||
listOrderProfileBoundSamples(profileId.value),
|
||||
]);
|
||||
if (!isXfaDatasetProfileDefinition(profile.definition)) {
|
||||
throw new Error('not_xfa');
|
||||
}
|
||||
definition.value = structuredClone(profile.definition);
|
||||
savedSnapshot.value = structuredClone(profile.definition);
|
||||
lockVersion.value = profile.lock_version;
|
||||
displayName.value = profile.display_name;
|
||||
profileCode.value = profile.profile_code;
|
||||
schemaVersionId.value = profile.schema_version_id;
|
||||
const schema = (schemaState.versions || []).find((item) => item.id === profile.schema_version_id);
|
||||
schemaFields.value = (schema?.definition?.fields || []) as ShippingOrderFieldConfig[];
|
||||
const annotation = samples.find((item) => item.sample_role === 'annotation') || samples[0];
|
||||
annotationDocumentId.value = annotation?.document_id || 0;
|
||||
if (!annotationDocumentId.value) throw new Error('missing_sample');
|
||||
const [treeRes, collRes] = await Promise.all([
|
||||
getOrderProfileSampleXfaFieldTree(annotationDocumentId.value),
|
||||
getOrderProfileSampleXfaCollections(annotationDocumentId.value),
|
||||
]);
|
||||
tree.value = (treeRes.tree && 'path_id' in treeRes.tree) ? treeRes.tree as XfaFieldTreeNode : null;
|
||||
collections.value = collRes.collection_candidates || [];
|
||||
excludedCollections.value = collRes.excluded_collection_candidates || [];
|
||||
await restoreCollectionSelection(profile.definition);
|
||||
await refreshSplitRulePreviews(profile.definition.split_rules || []);
|
||||
await acquireLease(false);
|
||||
startRenewal();
|
||||
} catch (error) {
|
||||
loadError.value = true;
|
||||
definition.value = null;
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行各字段拆分规则并按 rule_id 缓存脱敏结果。
|
||||
* 核心逻辑:规则预览失败时保持空值,禁止回退到源字段整段内容造成错误映射认知。
|
||||
* @param ruleSets 当前已保存或待展示的规则集合
|
||||
*/
|
||||
async function refreshSplitRulePreviews(
|
||||
ruleSets: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
|
||||
): Promise<void> {
|
||||
if (!annotationDocumentId.value) {
|
||||
splitRulePreviewValues.value = {};
|
||||
return;
|
||||
}
|
||||
const next: Record<string, string> = {};
|
||||
await Promise.allSettled(ruleSets.map(async (ruleSet) => {
|
||||
if (!ruleSet.rules?.length) return;
|
||||
const response = await previewOrderProfileSampleXfaSplitRules(annotationDocumentId.value, {
|
||||
path_id: ruleSet.source_path_id,
|
||||
rule_set: ruleSet as unknown as Record<string, unknown>,
|
||||
profile_id: profileId.value,
|
||||
reveal: false,
|
||||
});
|
||||
for (const segment of response.preview?.segments || []) {
|
||||
const value = String(segment.normalized_text || segment.raw_text || '').trim();
|
||||
if (segment.rule_id && value) next[segment.rule_id] = value;
|
||||
}
|
||||
}));
|
||||
splitRulePreviewValues.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定选中叶子或规则结果到同作用域 Schema 字段。
|
||||
* 规则继承源节点作用域,避免 Header 源规则被错误限制为明细字段。
|
||||
*/
|
||||
function onBindField(field: ShippingOrderFieldConfig, scope: 'header' | 'line'): void {
|
||||
if (!definition.value || !selectedPathId.value) return;
|
||||
if (selectedRuleId.value) {
|
||||
if (!selectedSourceScope.value || scope !== selectedSourceScope.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.scopeMismatch'));
|
||||
return;
|
||||
}
|
||||
const selectedId = selectedRuleId.value;
|
||||
const nextDefinition = unbindXfaSchemaField(definition.value, field.field_id);
|
||||
definition.value = {
|
||||
...nextDefinition,
|
||||
split_rules: (nextDefinition.split_rules || []).map((ruleSet) => ({
|
||||
...ruleSet,
|
||||
rules: ruleSet.rules.map((rule) => {
|
||||
const segment = rule.segment;
|
||||
if (rule.rule_id === selectedId) {
|
||||
return {
|
||||
...rule,
|
||||
segment: {
|
||||
...segment,
|
||||
handling: 'mapped',
|
||||
target_field_id: field.field_id,
|
||||
target_field_code: field.field_code,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (segment.target_field_id === field.field_id) {
|
||||
return {
|
||||
...rule,
|
||||
segment: { ...segment, handling: 'evidence_only', target_field_id: null, target_field_code: null },
|
||||
};
|
||||
}
|
||||
return rule;
|
||||
}),
|
||||
})),
|
||||
};
|
||||
return;
|
||||
}
|
||||
const current = [
|
||||
...(definition.value.header_mappings || []),
|
||||
...(definition.value.line_mapping?.fields || []),
|
||||
].find((item) => item.field_id === field.field_id);
|
||||
if (current && current.path_id !== selectedPathId.value) {
|
||||
const oldLabel = buildXfaPathLabel(current.path_id, flatNodes.value) || current.path_id;
|
||||
const newLabel = buildXfaPathLabel(selectedPathId.value, flatNodes.value) || selectedPathId.value;
|
||||
if (!window.confirm(t('admin.shippingOrderProfiles.xfaWorkbench.replaceConfirm', { old: oldLabel, next: newLabel }))) return;
|
||||
}
|
||||
try {
|
||||
const definitionWithoutSplitTarget = {
|
||||
...definition.value,
|
||||
split_rules: (definition.value.split_rules || []).map((ruleSet) => ({
|
||||
...ruleSet,
|
||||
rules: ruleSet.rules.map((rule) => rule.segment.target_field_id === field.field_id
|
||||
? { ...rule, segment: { ...rule.segment, handling: 'evidence_only' as const, target_field_id: null, target_field_code: null } }
|
||||
: rule),
|
||||
})),
|
||||
};
|
||||
definition.value = bindXfaSchemaField({
|
||||
definition: definitionWithoutSplitTarget,
|
||||
scope,
|
||||
field,
|
||||
pathId: selectedPathId.value,
|
||||
});
|
||||
} catch {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.scopeMismatch'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按管理员敏感读权限临时查看当前字段完整值。
|
||||
* 核心逻辑:只保存在当前页面内存;后端对每次读取写入敏感审计与加密快照。
|
||||
*/
|
||||
async function revealSelectedValue(): Promise<void> {
|
||||
if (!selectedPathId.value || !annotationDocumentId.value) return;
|
||||
const pathId = selectedPathId.value;
|
||||
revealingPathId.value = pathId;
|
||||
try {
|
||||
const result = await previewOrderProfileSampleXfaValue(annotationDocumentId.value, pathId, true);
|
||||
const previousTimer = revealTimers.get(pathId);
|
||||
if (previousTimer) clearTimeout(previousTimer);
|
||||
revealedValues.value = { ...revealedValues.value, [pathId]: result.display_value };
|
||||
revealTimers.set(pathId, setTimeout(() => {
|
||||
const next = { ...revealedValues.value };
|
||||
delete next[pathId];
|
||||
revealedValues.value = next;
|
||||
revealTimers.delete(pathId);
|
||||
}, 60_000));
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.revealFailed'));
|
||||
} finally {
|
||||
revealingPathId.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解除字段映射。
|
||||
*/
|
||||
function onUnbindField(fieldId: string): void {
|
||||
if (!definition.value) return;
|
||||
const next = unbindXfaSchemaField(definition.value, fieldId);
|
||||
definition.value = {
|
||||
...next,
|
||||
split_rules: (next.split_rules || []).map((ruleSet) => ({
|
||||
...ruleSet,
|
||||
rules: ruleSet.rules.map((rule) => rule.segment.target_field_id === fieldId
|
||||
? { ...rule, segment: { ...rule.segment, handling: 'evidence_only', target_field_id: null, target_field_code: null } }
|
||||
: rule),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存映射:要求权威集合;Lease/lock_version/operation_id 复用坐标治理。
|
||||
*/
|
||||
async function save(): Promise<boolean> {
|
||||
if (!definition.value || saveState.value === 'readonly') return false;
|
||||
if (!authoritativePathId.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
|
||||
return false;
|
||||
}
|
||||
saving.value = true;
|
||||
saveState.value = 'saving';
|
||||
try {
|
||||
const payloadDefinition: OrderXfaDatasetProfileDefinition & Record<string, unknown> = {
|
||||
...definition.value,
|
||||
authoritative_collection_path_id: authoritativePathId.value,
|
||||
mirror_collection_path_ids: mirrorPathIds.value,
|
||||
};
|
||||
const saved = await saveOrderDocumentProfileDraft(profileId.value, {
|
||||
profile_code: profileCode.value,
|
||||
display_name: displayName.value,
|
||||
schema_version_id: schemaVersionId.value,
|
||||
expected_lock_version: lockVersion.value,
|
||||
definition: payloadDefinition as OrderXfaDatasetProfileDefinition,
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
if (!isXfaDatasetProfileDefinition(saved.definition)) throw new Error('bad_mode');
|
||||
definition.value = structuredClone(saved.definition);
|
||||
savedSnapshot.value = structuredClone(saved.definition);
|
||||
lockVersion.value = saved.lock_version;
|
||||
await restoreCollectionSelection(saved.definition);
|
||||
await refreshSplitRulePreviews(saved.definition.split_rules || []);
|
||||
saveState.value = 'saved';
|
||||
message.success(t('admin.shippingOrderProfiles.xfaWorkbench.saved'));
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && (
|
||||
String(error.code || '').includes('LEASE')
|
||||
|| String(error.code || '').includes('VERSION_CONFLICT')
|
||||
)) {
|
||||
saveState.value = 'readonly';
|
||||
message.error(error.message);
|
||||
return false;
|
||||
}
|
||||
saveState.value = 'failed';
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.saveFailed'));
|
||||
return false;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startRenewal(): void {
|
||||
stopRenewal();
|
||||
renewTimer = setInterval(async () => {
|
||||
if (!editLeaseToken.value || saveState.value === 'readonly') return;
|
||||
try {
|
||||
await renewOrderDocumentProfileEditLease(profileId.value, {
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && String(error.code || '').includes('LEASE')) {
|
||||
saveState.value = 'readonly';
|
||||
}
|
||||
}
|
||||
}, 90_000);
|
||||
}
|
||||
|
||||
function stopRenewal(): void {
|
||||
if (renewTimer) clearInterval(renewTimer);
|
||||
renewTimer = null;
|
||||
}
|
||||
|
||||
onBeforeRouteLeave(async () => {
|
||||
if (!dirty.value) return true;
|
||||
return window.confirm(t('admin.shippingOrderProfiles.workbench.leaveConfirm'));
|
||||
});
|
||||
|
||||
/**
|
||||
* 更新 definition.split_rules 并标记脏状态。
|
||||
*/
|
||||
function onSplitRulesUpdate(rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[]): void {
|
||||
if (!definition.value) return;
|
||||
definition.value = { ...definition.value, split_rules: rules };
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹窗内只更新临时 definition;关闭弹窗不会污染页面草稿。
|
||||
*/
|
||||
function onDialogSplitRulesUpdate(
|
||||
rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
|
||||
): void {
|
||||
if (!dialogDefinition.value) return;
|
||||
dialogDefinition.value = { ...dialogDefinition.value, split_rules: rules };
|
||||
}
|
||||
|
||||
/**
|
||||
* 放弃本次弹窗编辑,恢复到打开弹窗前的页面状态。
|
||||
*/
|
||||
function closeSplitRuleDialog(): void {
|
||||
dialogDefinition.value = null;
|
||||
splitRuleDialogAutoAdd.value = false;
|
||||
splitRuleDialogOpen.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认拆分规则后立即刷新树并保存整个 XFA 定义。
|
||||
* 核心逻辑:使用子组件传回的最终规则消除事件时序差异;保存成功才关闭弹窗,失败保留编辑现场。
|
||||
* @param rules 已标记为 confirmed 的完整拆分规则数组
|
||||
*/
|
||||
async function commitDialogSplitRules(
|
||||
rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
|
||||
): Promise<void> {
|
||||
if (!dialogDefinition.value) return;
|
||||
const confirmedDefinition = {
|
||||
...cloneXfaData(dialogDefinition.value),
|
||||
split_rules: cloneXfaData(rules),
|
||||
};
|
||||
dialogDefinition.value = confirmedDefinition;
|
||||
definition.value = structuredClone(confirmedDefinition);
|
||||
const saved = await save();
|
||||
if (saved) closeSplitRuleDialog();
|
||||
}
|
||||
|
||||
function openSplitRuleDialog(autoAdd = false): void {
|
||||
if (!definition.value) return;
|
||||
dialogDefinition.value = cloneXfaData(definition.value);
|
||||
splitRuleDialogAutoAdd.value = autoAdd;
|
||||
splitRuleDialogOpen.value = true;
|
||||
}
|
||||
|
||||
function addRuleForPath(pathId: string): void {
|
||||
selectedPathId.value = pathId;
|
||||
selectedPathIsLeaf.value = true;
|
||||
selectedRuleId.value = null;
|
||||
openSplitRuleDialog(true);
|
||||
}
|
||||
|
||||
/** 选择规则作为 Schema 映射来源,不打开编辑弹窗。 */
|
||||
function selectRule(pathId: string, ruleId: string): void {
|
||||
selectedPathId.value = pathId;
|
||||
selectedPathIsLeaf.value = true;
|
||||
selectedRuleId.value = ruleId;
|
||||
}
|
||||
|
||||
/** 仅由规则行编辑图标打开维护弹窗。 */
|
||||
function editRule(pathId: string, ruleId: string): void {
|
||||
selectRule(pathId, ruleId);
|
||||
openSplitRuleDialog();
|
||||
}
|
||||
|
||||
function deleteRule(pathId: string, ruleId: string): void {
|
||||
const current = definition.value?.split_rules?.find((item) => item.source_path_id === pathId);
|
||||
if (!current || !window.confirm(t('admin.shippingOrderProfiles.xfaSplit.deleteConfirm'))) return;
|
||||
onSplitRulesUpdate((definition.value?.split_rules || []).map((item) => item.source_path_id === pathId
|
||||
? { ...item, rules: item.rules.filter((rule) => rule.rule_id !== ruleId).map((rule, index) => ({ ...rule, order: index + 1 })) }
|
||||
: item));
|
||||
}
|
||||
|
||||
watch(authoritativePathId, (pathId) => {
|
||||
if (!definition.value || !pathId) return;
|
||||
// 本地标记权威已选;真正路径由后端按 path_id 重写。
|
||||
mirrorPathIds.value = mirrorPathIds.value.filter((item) => item !== pathId);
|
||||
});
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(async () => {
|
||||
revealTimers.forEach((timer) => clearTimeout(timer));
|
||||
revealTimers.clear();
|
||||
stopRenewal();
|
||||
if (editLeaseToken.value) {
|
||||
try {
|
||||
await releaseOrderDocumentProfileEditLease(profileId.value, {
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
} catch { /* ignore release errors on unload */ }
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-workbench" v-if="!loading && definition">
|
||||
<header class="xfa-workbench__header">
|
||||
<div>
|
||||
<button type="button" class="link" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">
|
||||
← {{ t('admin.shippingOrderProfiles.workbench.headerReturnToLibrary') }}
|
||||
</button>
|
||||
<h1>{{ displayName }} · {{ profileCode }}</h1>
|
||||
<p>
|
||||
<span class="mode">{{ t('admin.shippingOrderProfiles.templateModes.xfa_dataset') }}</span>
|
||||
<span>{{ t(`admin.shippingOrderProfiles.workbench.saveStatus.${saveState}`) }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button v-if="saveState === 'readonly'" type="button" class="btn-secondary" @click="acquireLease(false)">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerRecoverLease') }}
|
||||
</button>
|
||||
<button v-if="saveState === 'readonly'" type="button" class="btn-secondary" @click="acquireLease(true)">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerTakeOverLease') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" :disabled="saving || !dirty" @click="save()">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerSaveDraft') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
:disabled="dirty || blockers.includes('authoritative_collection_required')"
|
||||
@click="router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: { profileCode, profileId } })"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerValidate') }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="xfa-workbench__grid">
|
||||
<XfaDatasetTree
|
||||
:tree="tree"
|
||||
:selected-path-id="selectedPathId"
|
||||
:selected-rule-id="selectedRuleId"
|
||||
:mapped-path-ids="mappedPathIds"
|
||||
:revealed-values="revealedValues"
|
||||
:revealing-path-id="revealingPathId"
|
||||
:split-rule-sets="splitRuleSets"
|
||||
@select-path="(pathId, isLeaf) => { selectedPathId = pathId; selectedPathIsLeaf = isLeaf; selectedRuleId = null; }"
|
||||
@reveal-path="(pathId) => { selectedPathId = pathId; void revealSelectedValue(); }"
|
||||
@add-rule="addRuleForPath"
|
||||
@select-rule="selectRule"
|
||||
@edit-rule="editRule"
|
||||
@delete-rule="deleteRule"
|
||||
/>
|
||||
<div class="xfa-workbench__mapping-column">
|
||||
<XfaSchemaMappingPanel
|
||||
:schema-fields="schemaFields"
|
||||
:definition="definition"
|
||||
:mapped-field-previews="mappedFieldPreviews"
|
||||
:selected-path-id="selectedPathId"
|
||||
:selected-path-is-leaf="selectedPathIsLeaf"
|
||||
:selected-rule-id="selectedRuleId"
|
||||
:selected-source-scope="selectedSourceScope"
|
||||
@bind-field="onBindField"
|
||||
@unbind-field="onUnbindField"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="splitRuleDialogOpen" class="xfa-rule-dialog" role="dialog" aria-modal="true">
|
||||
<div class="xfa-rule-dialog__backdrop" @click="closeSplitRuleDialog" />
|
||||
<section class="xfa-rule-dialog__panel">
|
||||
<header class="xfa-rule-dialog__header">
|
||||
<div><strong>{{ t('admin.shippingOrderProfiles.xfaSplit.title') }}</strong><p>{{ selectedPathLabel }}</p></div>
|
||||
<div class="xfa-rule-dialog__actions">
|
||||
<button type="button" class="btn-secondary" :disabled="saveState === 'readonly'" @click="splitRulePanel?.addRule()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.addRule') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" :disabled="!dialogHasRules" @click="splitRulePanel?.runPreview()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.preview') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" :disabled="saveState === 'readonly' || !dialogHasRules" @click="splitRulePanel?.confirmRules()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.confirm') }}
|
||||
</button>
|
||||
<button type="button" class="xfa-rule-dialog__close" :aria-label="t('common.close')" @click="closeSplitRuleDialog">×</button>
|
||||
</div>
|
||||
</header>
|
||||
<XfaSplitRulePanel
|
||||
ref="splitRulePanel"
|
||||
:definition="dialogDefinition || definition"
|
||||
:selected-path-id="selectedPathIsLeaf ? selectedPathId : null"
|
||||
:selected-path-label="selectedPathLabel"
|
||||
:selected-field-code="selectedFieldCode"
|
||||
:selected-is-multiline="selectedIsMultiline"
|
||||
:document-id="annotationDocumentId"
|
||||
:profile-id="profileId"
|
||||
:readonly="saveState === 'readonly'"
|
||||
:can-edit="canEditSplitRules"
|
||||
:can-preview="canPreviewSplitRules"
|
||||
:can-reveal-sensitive="canRevealSensitiveSplit"
|
||||
:dirty-unsaved="false"
|
||||
:persisted-confirmed="splitRulePersistedConfirmed"
|
||||
:auto-add-rule="splitRuleDialogAutoAdd"
|
||||
@update:split-rules="onDialogSplitRulesUpdate"
|
||||
@confirmed="commitDialogSplitRules"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
</section>
|
||||
<p v-else-if="loading" class="loading">{{ t('admin.shippingOrderProfiles.xfaWorkbench.loading') }}</p>
|
||||
<section v-else-if="loadError" class="xfa-workbench__error" role="alert">
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed') }}</p>
|
||||
<button type="button" class="btn-primary" @click="load()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.retryLoad') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-workbench { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 12px; height: calc(100dvh - 24px); min-height: 0; padding: 12px 16px; overflow: hidden; background: var(--bg-page); }
|
||||
.xfa-workbench__header { display: flex; justify-content: space-between; gap: 16px; align-items: start; padding: 12px 16px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); color: var(--text-primary); }
|
||||
.xfa-workbench__header h1 { margin: 4px 0; font-size: 1.15rem; }
|
||||
.xfa-workbench__header p { display: flex; gap: 12px; margin: 0; color: var(--text-muted); }
|
||||
.mode { color: var(--status-info-fg); font-weight: 700; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.xfa-workbench__grid { display: grid; grid-template-columns: 360px minmax(0, 1fr); gap: 12px; min-height: 0; min-width: 0; width: 100%; overflow: hidden; }
|
||||
.xfa-workbench__grid > * { min-width: 0; max-width: 100%; overflow: hidden; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); min-height: 0; }
|
||||
.xfa-workbench__grid > .xfa-workbench__mapping-column { display: grid; grid-template-rows: minmax(0, 1fr); gap: 10px; padding: 0; border: 0; background: transparent; }
|
||||
.xfa-workbench__mapping-column > * { min-width: 0; min-height: 0; overflow: auto; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); }
|
||||
.xfa-workbench__split-column > .xfa-split { height: 100%; overflow: auto; }
|
||||
.xfa-collections-inline { padding: 8px 12px !important; }
|
||||
.xfa-collections-inline summary { cursor: pointer; color: var(--text-secondary); font-size: .78rem; font-weight: 700; }
|
||||
.xfa-rule-dialog { position: fixed; z-index: 50; inset: 0; display: grid; place-items: center; padding: 24px; }
|
||||
.xfa-rule-dialog__backdrop { position: absolute; inset: 0; background: rgb(15 23 42 / .42); }
|
||||
.xfa-rule-dialog__panel { position: relative; display: flex; width: min(860px, 94vw); max-height: min(820px, 90vh); flex-direction: column; overflow: hidden; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); box-shadow: 0 24px 70px rgb(15 23 42 / .24); }
|
||||
.xfa-rule-dialog__header { display: flex; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--border-default); }
|
||||
.xfa-rule-dialog__header p { margin: 3px 0 0; color: var(--text-muted); font-size: .76rem; }
|
||||
.xfa-rule-dialog__actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||
.xfa-rule-dialog__actions button { min-height: 34px; }
|
||||
.xfa-rule-dialog__close { display: inline-grid; width: 34px; padding: 0; place-items: center; border: 0; border-radius: var(--radius-control); background: transparent; color: var(--text-muted); cursor: pointer; font-size: 1.15rem; }
|
||||
.xfa-rule-dialog__close:hover { background: var(--bg-page); color: var(--text-primary); }
|
||||
.xfa-rule-dialog__panel > .xfa-split { min-height: 0; overflow: auto; padding: 14px 16px 18px; }
|
||||
.link { border: 0; background: transparent; color: var(--status-info-fg); cursor: pointer; }
|
||||
.loading { padding: 24px; }
|
||||
.xfa-workbench__error {
|
||||
display: flex; flex-direction: column; gap: 12px; align-items: flex-start;
|
||||
margin: 24px; padding: 20px; border: 1px solid var(--status-error-border); border-radius: var(--radius-surface); background: var(--status-error-bg); color: var(--status-error-fg);
|
||||
}
|
||||
@media (max-width: 1400px) {
|
||||
.xfa-workbench__grid { grid-template-columns: 240px minmax(420px, 1fr); }
|
||||
.xfa-workbench__grid > :last-child { grid-column: 1 / -1; max-height: 36vh; }
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.xfa-workbench__grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
+75
-4
@@ -3,7 +3,8 @@
|
||||
用途:展示订单模板版本中心的治理审计时间线(含 XFA operation_id / checksum)。
|
||||
依赖:版本中心审计 API、版本详情 DTO、Vue I18n。
|
||||
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,
|
||||
以及 XFA 变更前后 definition checksum 与 operation_id;不展示 PDF、正文或盲测真值。
|
||||
以及 XFA 变更前后 definition checksum 与 operation_id;不展示 PDF、正文或盲测真值;
|
||||
对视觉绑定 / 拆分 / 统一迁移事件渲染分组标签与 visual before/after 摘要。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
@@ -31,6 +32,30 @@ const filters = reactive({
|
||||
createdTo: "",
|
||||
});
|
||||
|
||||
const VISUAL_EVENT_PREFIXES = ["xfa_visual_binding_", "xfa_split_", "order_profile_unified_migration_"];
|
||||
|
||||
/**
|
||||
* 判断是否为统一视觉 / 拆分 / 迁移审计事件。
|
||||
*/
|
||||
function isUnifiedVisualOrSplitEvent(eventType: string): boolean {
|
||||
const value = String(eventType || "");
|
||||
return VISUAL_EVENT_PREFIXES.some((prefix) => value.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 detail 提取视觉 before/after 摘要(若存在)。
|
||||
*/
|
||||
function visualPayload(detail: Record<string, unknown> | null | undefined): {
|
||||
before: unknown;
|
||||
after: unknown;
|
||||
} | null {
|
||||
if (!detail || typeof detail !== "object") return null;
|
||||
const before = detail.before_visual_binding ?? detail.before;
|
||||
const after = detail.after_visual_binding ?? detail.after;
|
||||
if (before == null && after == null) return null;
|
||||
return { before, after };
|
||||
}
|
||||
|
||||
const formatTime = (value?: string | null) => value ? new Date(value).toLocaleString() : "-";
|
||||
const formatJson = (value: unknown) => {
|
||||
try {
|
||||
@@ -172,7 +197,14 @@ watch(
|
||||
>
|
||||
<header>
|
||||
<div>
|
||||
<p class="timeline-type">{{ item.event_type }}</p>
|
||||
<p class="timeline-type">
|
||||
{{ item.event_type }}
|
||||
<span
|
||||
v-if="isUnifiedVisualOrSplitEvent(item.event_type)"
|
||||
class="event-tag"
|
||||
data-testid="order-profile-audit-visual-tag"
|
||||
>visual/split</span>
|
||||
</p>
|
||||
<h4>{{ item.actor.display_name }}</h4>
|
||||
</div>
|
||||
<div class="meta">
|
||||
@@ -198,6 +230,14 @@ watch(
|
||||
<dd><code>{{ item.definition_checksum }}</code></dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div
|
||||
v-if="visualPayload(item.detail as Record<string, unknown>)"
|
||||
class="visual-diff"
|
||||
data-testid="order-profile-audit-visual-diff"
|
||||
>
|
||||
<p class="visual-diff-title">{{ t("admin.shippingOrderProfiles.versionCenter.audit.visualDiff") }}</p>
|
||||
<pre>{{ formatJson(visualPayload(item.detail as Record<string, unknown>)) }}</pre>
|
||||
</div>
|
||||
<pre>{{ formatJson(item.detail) }}</pre>
|
||||
</article>
|
||||
</div>
|
||||
@@ -249,13 +289,44 @@ watch(
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.toolbar p,
|
||||
.timeline-type {
|
||||
.toolbar p {
|
||||
margin: 0.25rem 0 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.timeline-type {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
margin: 0.25rem 0 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.event-tag {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 999px;
|
||||
padding: 0.05rem 0.45rem;
|
||||
font-size: 0.65rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.visual-diff {
|
||||
margin-top: 0.65rem;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border: 1px dashed var(--border-default);
|
||||
border-radius: 0.75rem;
|
||||
}
|
||||
|
||||
.visual-diff-title {
|
||||
margin: 0 0 0.35rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.toolbar-actions,
|
||||
.pager {
|
||||
display: flex;
|
||||
|
||||
+26
-3
@@ -34,9 +34,12 @@ const props = defineProps<{
|
||||
pendingSuggestionCount?: number;
|
||||
orderFieldValues?: Record<string, string | null>;
|
||||
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
|
||||
/** full=坐标全工具;xfa_visual=仅 XFA 画框。 */
|
||||
annotationToolSet?: 'full' | 'xfa_visual';
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const readonlyMode = computed(() => props.mode === 'readonly');
|
||||
const xfaVisualTools = computed(() => props.annotationToolSet === 'xfa_visual');
|
||||
const emit = defineEmits<{
|
||||
select: [regionId: string];
|
||||
start: [regionId: string];
|
||||
@@ -177,7 +180,13 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
if (readonlyMode.value && !['line', 'exclusion'].includes(region.kind)) {
|
||||
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
|
||||
}
|
||||
if (region.kind !== 'order_field') return region.label;
|
||||
if (region.kind !== 'order_field') {
|
||||
if (region.kind === 'xfa_visual' && region.visualBindingStatus) {
|
||||
const statusKey = `admin.shippingOrderProfiles.xfaUnified.visualStatus.${region.visualBindingStatus}`;
|
||||
return `${region.label} · ${t(statusKey)}`;
|
||||
}
|
||||
return region.label;
|
||||
}
|
||||
const state = props.orderFieldValueState || 'idle';
|
||||
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
|
||||
const suffix = state === 'loading'
|
||||
@@ -247,6 +256,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</div>
|
||||
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
|
||||
<aside v-if="!readonlyMode" class="annotation-tools">
|
||||
<template v-if="xfaVisualTools">
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :title="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :class="{ active: creationKind === 'xfa_visual' }" @click="emit('draw', 'xfa_visual')"><TextCursorInput /></button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :class="{ active: creationKind === 'document_anchor_label' || creationKind === 'document_anchor_value' }" @click="emit('draw', 'document_anchor_label')"><Anchor /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><Tag /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><TextCursorInput /></button>
|
||||
@@ -255,19 +268,21 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><Columns3 /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /></button>
|
||||
<button type="button" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
|
||||
</template>
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</aside>
|
||||
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
|
||||
<div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind && !readonlyMode }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
|
||||
<img :src="imageUrl" alt="Controlled document page preview" draggable="false" />
|
||||
<img :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
|
||||
<div
|
||||
v-for="region in regions"
|
||||
:key="region.id"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="region"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }]"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
:aria-label="displayRegionLabel(region)"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@keydown.enter="emit('select', region.id)"
|
||||
@keydown.space.prevent="emit('select', region.id)"
|
||||
@@ -359,6 +374,14 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.line-hit-w { left: -6px; }
|
||||
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }
|
||||
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region-xfa_visual { z-index: 2; border: 1.5px solid #38bdf8; background: rgb(14 165 233 / .12); }
|
||||
.region-xfa_visual .region-label, .region-xfa_visual .resize-handle { background: #0369a1; }
|
||||
.region-visual--suggested { border-color: #f59e0b; background: rgb(245 158 11 / .14); }
|
||||
.region-visual--suggested .region-label { background: #b45309; }
|
||||
.region-visual--confirmed { border-color: #22c55e; background: rgb(34 197 94 / .12); }
|
||||
.region-visual--confirmed .region-label { background: #15803d; }
|
||||
.region-visual--rejected, .region-visual--needs_review { border-color: #f87171; background: rgb(248 113 113 / .1); }
|
||||
.region-visual--rejected .region-label, .region-visual--needs_review .region-label { background: #b91c1c; }
|
||||
.region:not(.selected) .resize-handle { display: none; }
|
||||
.region.selected { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region.selected:not(.region-line) { z-index: 4; }
|
||||
|
||||
+21
@@ -36,6 +36,19 @@ const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollec
|
||||
const flatNodes = ref(flattenXfaTreeNodes(null));
|
||||
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
|
||||
|
||||
/** 创建草稿前的阻断摘要(权威集合必选等)。 */
|
||||
const createBlockers = computed(() => {
|
||||
const items: string[] = [];
|
||||
const selectable = (collections.value?.collection_candidates || []).filter((item) => item.selectable !== false);
|
||||
if (!props.authoritativePathId && selectable.length) {
|
||||
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
|
||||
}
|
||||
if (!selectable.length && !props.authoritativePathId) {
|
||||
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.allCandidatesExcluded'));
|
||||
}
|
||||
return items;
|
||||
});
|
||||
|
||||
const documentKindLabel = computed(() => {
|
||||
const kind = props.sample?.document_kind || collections.value?.document_kind || 'xfa_hybrid';
|
||||
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
|
||||
@@ -83,6 +96,12 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
</ul>
|
||||
</article>
|
||||
<p v-if="loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.loading') }}</p>
|
||||
<aside v-else-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
|
||||
<ul>
|
||||
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
<XfaCollectionSelector
|
||||
v-else-if="collections && (collections.collection_candidates?.length || excludedCollections.length)"
|
||||
:candidates="collections.collection_candidates || []"
|
||||
@@ -103,4 +122,6 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
.xfa-confirm-step__badge { padding: 2px 8px; border-radius: 999px; background: var(--status-info-bg); color: var(--status-info-fg); font-size: .72rem; font-weight: 700; }
|
||||
.xfa-confirm-step__checks { margin: 8px 0 0; padding-left: 18px; color: var(--text-secondary); font-size: .86rem; }
|
||||
.xfa-confirm-step__loading { margin: 0; color: var(--text-muted); }
|
||||
.xfa-confirm-step__blockers { padding: 12px 14px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); font-size: .84rem; }
|
||||
.xfa-confirm-step__blockers ul { margin: 6px 0 0; padding-left: 18px; }
|
||||
</style>
|
||||
+8
-5
@@ -3,7 +3,7 @@
|
||||
用途:权威明细集合与镜像对账集合选择。
|
||||
依赖:vue-i18n、XfaCollectionCandidate。
|
||||
逻辑:以候选卡片直接展示完整路径、字段覆盖与样本证据;权威单选强制,镜像多选仅用于对账;
|
||||
全部候选被排除时仍展示排除原因,禁止只显示“没有集合”。
|
||||
selectable=false 的无效集合禁选;全部候选被排除时仍展示排除原因。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -22,10 +22,11 @@ const emit = defineEmits<{
|
||||
'update:mirrorPathIds': [pathIds: string[]];
|
||||
}>();
|
||||
const { t, te } = useI18n();
|
||||
const mirrors = computed(() => listMirrorCollectionCandidates(props.candidates, props.authoritativePathId));
|
||||
const selectedAuthoritative = computed(() => props.candidates.find((item) => item.path_id === props.authoritativePathId));
|
||||
const hasSelectable = computed(() => props.candidates.length > 0);
|
||||
const hasSelectable = computed(() => props.candidates.some((item) => item.selectable !== false));
|
||||
const selectableCandidates = computed(() => props.candidates.filter((item) => item.selectable !== false));
|
||||
const hasExcludedOnly = computed(() => !hasSelectable.value && Boolean(props.excludedCandidates?.length));
|
||||
const mirrors = computed(() => listMirrorCollectionCandidates(selectableCandidates.value, props.authoritativePathId));
|
||||
const selectedAuthoritative = computed(() => selectableCandidates.value.find((item) => item.path_id === props.authoritativePathId));
|
||||
|
||||
/** 将非空率转为管理员可读百分比。 */
|
||||
function percent(value?: number): string {
|
||||
@@ -70,12 +71,13 @@ function reasonLabels(reasons?: string[]): string {
|
||||
<fieldset v-if="hasSelectable" class="auth-cards" :aria-invalid="!authoritativePathId">
|
||||
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.authoritativeCollection') }}</legend>
|
||||
<label
|
||||
v-for="item in candidates"
|
||||
v-for="item in selectableCandidates"
|
||||
:key="item.path_id"
|
||||
class="candidate-card"
|
||||
:class="{
|
||||
selected: authoritativePathId === item.path_id,
|
||||
recommended: item.recommended_role === 'authoritative',
|
||||
disabled: item.selectable === false,
|
||||
}"
|
||||
>
|
||||
<input
|
||||
@@ -83,6 +85,7 @@ function reasonLabels(reasons?: string[]): string {
|
||||
name="xfa-authoritative-collection"
|
||||
:value="item.path_id"
|
||||
:checked="authoritativePathId === item.path_id"
|
||||
:disabled="item.selectable === false"
|
||||
@change="emit('update:authoritativePathId', item.path_id)"
|
||||
/>
|
||||
<span class="candidate-body">
|
||||
|
||||
+30
-2
@@ -17,7 +17,6 @@ const i18n = createI18n({
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
treeTitle: '树', searchPaths: '搜索', collectionBadge: '集合', treeEmpty: '空',
|
||||
revealValue: '查看 {field}',
|
||||
},
|
||||
xfaSplit: { addRule: '新增规则', ruleLabel: '规则 {index}', unnamedRule: '未命名规则', deleteRule: '删除' },
|
||||
},
|
||||
@@ -37,7 +36,7 @@ describe('XfaDatasetTree', () => {
|
||||
is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'leaf', local_name: 'EBELN', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_masked: '451***',
|
||||
is_leaf: true, sample_value_display: '4510000227', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
@@ -166,4 +165,33 @@ describe('XfaDatasetTree', () => {
|
||||
const ruleIndentValue = Number.parseFloat(wrapper.find('.xfa-tree__rules').attributes('style').match(/--rule-indent:\s*([\d.]+)px/)?.[1] || '0');
|
||||
expect(ruleIndentValue).toBeGreaterThan(parentPadding);
|
||||
});
|
||||
|
||||
it('hides rule edit controls when readonly is true', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
readonly: true,
|
||||
selectedPathId: 'leaf',
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
splitRuleSets: [{
|
||||
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
|
||||
}],
|
||||
}],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('.add-rule').exists()).toBe(false);
|
||||
expect(wrapper.find('.rule-edit').exists()).toBe(false);
|
||||
expect(wrapper.find('.rule-delete').exists()).toBe(false);
|
||||
await wrapper.find('[data-xfa-path-id="leaf"]').trigger('click');
|
||||
expect(wrapper.emitted('select-path')?.[0]).toEqual(['leaf', true]);
|
||||
});
|
||||
});
|
||||
+11
-22
@@ -1,12 +1,12 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.vue
|
||||
用途:XFA 映射工作台左侧受控数据树(仅分析记录节点)。
|
||||
用途:XFA 受控数据树;主工作台用于绑定导航,高级诊断抽屉内只读展示。
|
||||
依赖:vue-i18n、xfaProfileMapping.utils。
|
||||
逻辑:支持展开折叠、方向键导航与分级样本展示;叶子展示父路径提示区分同名来源。
|
||||
逻辑:支持展开折叠、方向键导航与完整样本值展示;readonly 时隐藏增删改规则动作。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref } from 'vue';
|
||||
import { ChevronDown, ChevronRight, Eye, Pencil } from 'lucide-vue-next';
|
||||
import { ChevronDown, ChevronRight, Pencil } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { XfaSplitRuleSet } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
@@ -22,13 +22,12 @@ const props = defineProps<{
|
||||
selectedPathId?: string | null;
|
||||
selectedRuleId?: string | null;
|
||||
mappedPathIds?: string[];
|
||||
revealedValues?: Record<string, string>;
|
||||
revealingPathId?: string;
|
||||
splitRuleSets?: XfaSplitRuleSet[];
|
||||
/** 为 true 时隐藏新增/编辑/删除规则操作,仅保留选择与诊断。 */
|
||||
readonly?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'select-path': [pathId: string, isLeaf: boolean];
|
||||
'reveal-path': [pathId: string];
|
||||
'add-rule': [pathId: string];
|
||||
'select-rule': [pathId: string, ruleId: string];
|
||||
'edit-rule': [pathId: string, ruleId: string];
|
||||
@@ -40,6 +39,7 @@ const query = ref('');
|
||||
const flat = computed(() => flattenXfaTreeNodes(props.tree || undefined));
|
||||
const collapsed = ref(new Set<string>());
|
||||
const focusedPathId = ref('');
|
||||
const isReadonly = computed(() => Boolean(props.readonly));
|
||||
const visible = computed(() => {
|
||||
const filtered = filterXfaTreeNodes(flat.value, query.value);
|
||||
if (query.value.trim()) return filtered;
|
||||
@@ -190,7 +190,7 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
</span>
|
||||
<span v-if="node.isCollectionCandidate" class="badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionBadge') }}</span>
|
||||
<button
|
||||
v-if="node.isLeaf"
|
||||
v-if="node.isLeaf && !isReadonly"
|
||||
type="button"
|
||||
class="add-rule"
|
||||
:class="{ 'add-rule--active': selectedPathId === node.pathId }"
|
||||
@@ -198,19 +198,9 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
|
||||
@click.stop="emit('add-rule', node.pathId)"
|
||||
>+</button>
|
||||
<span v-if="revealedValues?.[node.pathId] || node.sampleValueDisplay" class="sample">
|
||||
{{ revealedValues?.[node.pathId] || node.sampleValueDisplay }}
|
||||
<span v-if="node.sampleValueDisplay" class="sample">
|
||||
{{ node.sampleValueDisplay }}
|
||||
</span>
|
||||
<button
|
||||
v-if="node.isLeaf && node.canReveal && !revealedValues?.[node.pathId]"
|
||||
type="button"
|
||||
class="reveal"
|
||||
:disabled="revealingPathId === node.pathId"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.revealValue', { field: pathTitle(node) })"
|
||||
@click.stop="emit('reveal-path', node.pathId)"
|
||||
>
|
||||
<Eye :size="14" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<ul
|
||||
v-if="node.isLeaf && rulesFor(node.pathId).length"
|
||||
@@ -229,13 +219,14 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
<span class="rule-label">{{ t('admin.shippingOrderProfiles.xfaSplit.ruleLabel', { index: ruleIndex + 1 }) }} · {{ rule.segment.display_name || rule.segment.segment_code || t('admin.shippingOrderProfiles.xfaSplit.unnamedRule') }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="!isReadonly"
|
||||
type="button"
|
||||
class="rule-edit"
|
||||
:title="t('common.edit')"
|
||||
:aria-label="t('common.edit')"
|
||||
@click.stop="emit('edit-rule', node.pathId, rule.rule_id)"
|
||||
><Pencil :size="12" aria-hidden="true" /></button>
|
||||
<button type="button" class="rule-delete" :title="t('admin.shippingOrderProfiles.xfaSplit.deleteRule')" @click.stop="emit('delete-rule', node.pathId, rule.rule_id)">×</button>
|
||||
<button v-if="!isReadonly" type="button" class="rule-delete" :title="t('admin.shippingOrderProfiles.xfaSplit.deleteRule')" @click.stop="emit('delete-rule', node.pathId, rule.rule_id)">×</button>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
@@ -261,7 +252,6 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
.xfa-tree__node .sample { min-width: 3.2rem; margin-left: auto; max-width: 30%; overflow: hidden; color: var(--text-muted); font-size: .68rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .badge { color: var(--status-warning-fg); font-size: .72rem; font-weight: 700; }
|
||||
.toggle, .toggle-spacer { display: inline-flex; width: 16px; flex: 0 0 16px; }
|
||||
.reveal { display: inline-flex; padding: 3px; border: 0; border-radius: 6px; background: transparent; color: var(--status-info-fg); cursor: pointer; }
|
||||
.add-rule { display: none; position: relative; z-index: 1; min-width: 24px; min-height: 24px; align-items: center; justify-content: center; margin-left: 2px; border: 1px solid transparent; border-radius: 5px; background: transparent; color: var(--status-info-fg); font-size: 1rem; line-height: 1; cursor: pointer; }
|
||||
.add-rule--active { display: inline-flex; border-color: var(--status-info-border); background: var(--status-info-bg); }
|
||||
.xfa-tree__node:hover .add-rule, .xfa-tree__node:focus-within .add-rule { display: inline-flex; }
|
||||
@@ -276,7 +266,6 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
.rule-edit { color: var(--status-info-fg); }
|
||||
.rule-delete { color: var(--status-error-fg); font-size: .9rem; }
|
||||
.rule-edit:hover, .rule-delete:hover { background: var(--bg-page); }
|
||||
.reveal:focus-visible { outline: 2px solid var(--focus-ring); }
|
||||
.xfa-tree__empty { color: var(--text-muted); font-size: .85rem; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; }
|
||||
</style>
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSchemaMappingPanel.spec.ts
|
||||
* 用途:验证 XFA Schema 映射面板渲染与 bind-field 事件。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaSchemaMappingPanel。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaSchemaMappingPanel from './XfaSchemaMappingPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
schemaTitle: 'Schema',
|
||||
filter: { all: '全部', unmapped: '未映射' },
|
||||
scope: { header: '表头', line: '明细' },
|
||||
selectLeafFirst: '选叶子',
|
||||
unbind: '解除',
|
||||
requiredCoverage: '{mapped}/{total}',
|
||||
currentNode: '节点',
|
||||
noneSelected: '无',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const definition = {
|
||||
template_mode: 'xfa_dataset' as const,
|
||||
source_contract: {
|
||||
template_packet_checksum: 'a', dataset_structure_fingerprint: 'b', dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS', mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true,
|
||||
mirror_collection_policy: 'must_match_when_present' as const,
|
||||
line_amount_formula: 'quantity_times_unit_price' as const,
|
||||
total_amount_policy: 'must_equal_line_sum' as const,
|
||||
},
|
||||
};
|
||||
|
||||
describe('XfaSchemaMappingPanel', () => {
|
||||
it('emits bind-field when a schema field is clicked with leaf selected', async () => {
|
||||
const wrapper = mount(XfaSchemaMappingPanel, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
schemaFields: [{
|
||||
field_id: 'f1', field_code: 'customer_po_no', scope: 'header', display_name: 'PO', required: true,
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}],
|
||||
definition,
|
||||
selectedPathId: 'leaf-path',
|
||||
selectedPathIsLeaf: true,
|
||||
selectedSourceScope: 'header',
|
||||
},
|
||||
});
|
||||
await wrapper.find('button.field').trigger('click');
|
||||
expect(wrapper.emitted('bind-field')?.[0]?.[0]).toMatchObject({ field_code: 'customer_po_no' });
|
||||
});
|
||||
});
|
||||
+3
-3
@@ -19,8 +19,8 @@ const props = defineProps<{
|
||||
selectedSourceScope?: 'header' | 'line' | null;
|
||||
filterMode?: 'all' | 'unmapped';
|
||||
mappedFieldPreviews?: {
|
||||
header: Array<{ fieldCode: string; pathLabel: string; maskedValue: string | null }>;
|
||||
line: Array<{ fieldCode: string; pathLabel: string; maskedValue: string | null }>;
|
||||
header: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
|
||||
line: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
|
||||
};
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
@@ -117,7 +117,7 @@ function setFilter(mode: 'all' | 'unmapped'): void {
|
||||
</span>
|
||||
<span v-if="mappingFor(field)" class="field__mapping">
|
||||
<span class="field__path">← {{ mappingFor(field)?.pathLabel }}</span>
|
||||
<strong v-if="mappingFor(field)?.maskedValue" class="field__value">{{ mappingFor(field)?.maskedValue }}</strong>
|
||||
<strong v-if="mappingFor(field)?.value" class="field__value">{{ mappingFor(field)?.value }}</strong>
|
||||
</span>
|
||||
<span v-else class="field__empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.unmappedValue') }}</span>
|
||||
<strong v-if="boundIds.has(field.field_id)" class="field__check">✓</strong>
|
||||
|
||||
+9
-8
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts
|
||||
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与 reveal 传参。
|
||||
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与完整值预览。
|
||||
* 依赖:Vitest、@vue/test-utils、shipping-order-document-profile API mock。
|
||||
*/
|
||||
|
||||
@@ -74,7 +74,6 @@ const xfaSplitMessages = {
|
||||
substringStart: '起始',
|
||||
substringEnd: '结束',
|
||||
unmatchedPolicy: '未匹配',
|
||||
revealFullValues: '完整值',
|
||||
noRules: '无规则',
|
||||
confirmNeedsPreview: '需先预览',
|
||||
confirmBlockedDiagnostics: '诊断阻断',
|
||||
@@ -200,7 +199,6 @@ function mountPanel(overrides: Record<string, unknown> = {}) {
|
||||
}],
|
||||
canEdit: true,
|
||||
canPreview: true,
|
||||
canRevealSensitive: true,
|
||||
persistedConfirmed: true,
|
||||
dirtyUnsaved: false,
|
||||
...overrides,
|
||||
@@ -235,8 +233,9 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(emitted?.length).toBeGreaterThan(0);
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const ruleSet = last?.find((item) => item.source_path_id === 'path-matnr');
|
||||
expect(ruleSet?.strategy).toBe('pipeline');
|
||||
expect(ruleSet?.strategy).toBe('matcher');
|
||||
expect(ruleSet?.rules?.length).toBe(1);
|
||||
expect(ruleSet?.rules?.[0]?.matcher?.type).toBe('position');
|
||||
expect(ruleSet?.rules?.[0]?.stages?.length).toBe(2);
|
||||
expect(ruleSet?.rules?.[0]?.stages?.[0]?.type).toBe('split_lines');
|
||||
expect(ruleSet?.rules?.[0]?.stages?.[1]?.type).toBe('select_line');
|
||||
@@ -274,6 +273,7 @@ describe('XfaSplitRulePanel', () => {
|
||||
|
||||
it('blocks confirm when preview has diagnostics', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-diag',
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
@@ -322,6 +322,7 @@ describe('XfaSplitRulePanel', () => {
|
||||
|
||||
it('emits the final confirmed rules for parent persistence', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-preview-1',
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
@@ -342,9 +343,11 @@ describe('XfaSplitRulePanel', () => {
|
||||
|
||||
const confirmed = wrapper.emitted('confirmed');
|
||||
const rules = confirmed?.[0]?.[0] as typeof baseDefinition.split_rules;
|
||||
const tokens = confirmed?.[0]?.[1] as Record<string, string>;
|
||||
expect(rules?.[0]?.status).toBe('confirmed');
|
||||
expect(rules?.[0]?.requires_confirmation).toBe(false);
|
||||
expect(rules?.[0]?.source_path_id).toBe('path-matnr');
|
||||
expect(tokens?.['path-matnr']).toBe('tok-preview-1');
|
||||
expect(() => JSON.parse(JSON.stringify(rules))).not.toThrow();
|
||||
});
|
||||
|
||||
@@ -443,7 +446,7 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(rules?.[0]?.rules).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('passes reveal:true to preview API when checkbox enabled and canRevealSensitive', async () => {
|
||||
it('previews full values without a reveal permission parameter', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
@@ -459,11 +462,9 @@ describe('XfaSplitRulePanel', () => {
|
||||
split_rules: [makePipelineRuleSet({ rules: [] })],
|
||||
},
|
||||
});
|
||||
const revealCheckbox = wrapper.find('.xfa-split__reveal input[type="checkbox"]');
|
||||
await revealCheckbox.setValue(true);
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({ reveal: true }));
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() }));
|
||||
});
|
||||
|
||||
it('ignores exposed edit actions when canEdit is false', () => {
|
||||
|
||||
+116
-45
@@ -1,9 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue
|
||||
用途:XFA 多行字段拆分规则工作台——多阶段 pipeline 编辑、预览、确认与 segment 映射。
|
||||
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表、权限 props。
|
||||
逻辑:编辑 definition.split_rules(strategy=pipeline);确认前须预览当前 rule_set 哈希;
|
||||
编辑规则/阶段/归一化/策略均回退 draft 并失效预览;reveal 仅在有 audit_sensitive_read 时传递。
|
||||
用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。
|
||||
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。
|
||||
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 保留供 UI 与兼容预览;
|
||||
确认前须预览当前 rule_set 哈希;预览直接返回完整识别值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaSplitMatcher,
|
||||
XfaSplitNormalization,
|
||||
XfaSplitPreviewResult,
|
||||
XfaSplitRule,
|
||||
@@ -24,10 +25,11 @@ import type {
|
||||
XfaSplitStageType,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
/** updateRule 局部补丁:segment/stages 允许浅合并字段 */
|
||||
type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages'> & {
|
||||
/** updateRule 局部补丁:segment/stages/matcher 允许浅合并字段 */
|
||||
type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages' | 'matcher'> & {
|
||||
segment?: Partial<XfaSplitSegment>;
|
||||
stages?: XfaSplitStage[];
|
||||
matcher?: XfaSplitMatcher;
|
||||
};
|
||||
|
||||
type XfaSplitStagePatch = Partial<XfaSplitStage>;
|
||||
@@ -44,7 +46,6 @@ const props = defineProps<{
|
||||
readonly?: boolean;
|
||||
canEdit?: boolean;
|
||||
canPreview?: boolean;
|
||||
canRevealSensitive?: boolean;
|
||||
dirtyUnsaved?: boolean;
|
||||
persistedConfirmed?: boolean;
|
||||
autoAddRule?: boolean;
|
||||
@@ -52,7 +53,8 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:split-rules': [rules: XfaSplitRuleSet[]];
|
||||
confirmed: [rules: XfaSplitRuleSet[]];
|
||||
/** 确认时附带 path_id → preview_token,供父级保存时提交服务端校验 */
|
||||
confirmed: [rules: XfaSplitRuleSet[], confirmationTokens: Record<string, string>];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -60,7 +62,8 @@ const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const preview = ref<XfaSplitPreviewResult | null>(null);
|
||||
const previewRuleSetHash = ref<string | null>(null);
|
||||
const revealFullValues = ref(false);
|
||||
/** 最近一次成功预览签发的确认令牌 */
|
||||
const previewConfirmationToken = ref<string | null>(null);
|
||||
const collapsedRules = ref(new Set<string>());
|
||||
const advancedRules = ref(new Set<string>());
|
||||
|
||||
@@ -75,7 +78,7 @@ const activeRuleSet = computed(() => {
|
||||
|
||||
const sortedRules = computed(() => {
|
||||
if (!activeRuleSet.value) return [];
|
||||
return [...activeRuleSet.value.rules].sort((a, b) => a.order - b.order);
|
||||
return [...activeRuleSet.value.rules].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
||||
});
|
||||
|
||||
const showUnsavedConfirmBanner = computed(() => (
|
||||
@@ -128,7 +131,7 @@ function markRuleSetDirty(ruleSet: XfaSplitRuleSet): XfaSplitRuleSet {
|
||||
*/
|
||||
function normalizeRuleOrders(rules: XfaSplitRule[]): XfaSplitRule[] {
|
||||
return [...rules]
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
||||
.map((rule, index) => ({ ...rule, order: index + 1 }));
|
||||
}
|
||||
|
||||
@@ -183,6 +186,32 @@ function createDefaultPipelineStages(lineIndex = 1): XfaSplitStage[] {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 由提取模式与阶段参数生成正式 matcher(prefix > regex > position)。
|
||||
*/
|
||||
function matcherFromExtraction(mode: ExtractionMode, stage: Partial<XfaSplitStage>, order: number): XfaSplitMatcher {
|
||||
if (mode === 'extract_prefix') {
|
||||
return {
|
||||
type: 'prefix',
|
||||
value: String(stage.value || ''),
|
||||
separators: (stage.separators && stage.separators.length) ? stage.separators : [':', ':'],
|
||||
case_sensitive: Boolean(stage.case_sensitive),
|
||||
};
|
||||
}
|
||||
if (mode === 'regex_capture') {
|
||||
return {
|
||||
type: 'regex',
|
||||
pattern: String(stage.pattern || ''),
|
||||
capture_group: stage.capture_group ?? 1,
|
||||
case_sensitive: Boolean(stage.case_sensitive),
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'position',
|
||||
line_index: Number(stage.line_index || stage.line_start || order || 1),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保存在可编辑的规则集;无则创建 Draft 空壳(strategy=pipeline)。
|
||||
*/
|
||||
@@ -219,6 +248,7 @@ function ensureRuleSet(): XfaSplitRuleSet {
|
||||
function invalidatePreview(): void {
|
||||
preview.value = null;
|
||||
previewRuleSetHash.value = null;
|
||||
previewConfirmationToken.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -231,21 +261,20 @@ function applyRuleSetChange(updater: (ruleSet: XfaSplitRuleSet) => XfaSplitRuleS
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览当前规则集执行结果;reveal 仅在有敏感读权限时传给后端。
|
||||
* 预览当前规则集执行结果;返回脱敏预览与确认令牌(完整值需 reveal)。
|
||||
*/
|
||||
async function runPreview(): Promise<void> {
|
||||
if (!props.selectedPathId || !activeRuleSet.value || props.canPreview === false) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const reveal = revealFullValues.value && Boolean(props.canRevealSensitive);
|
||||
const result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
|
||||
path_id: props.selectedPathId,
|
||||
rule_set: activeRuleSet.value as unknown as Record<string, unknown>,
|
||||
profile_id: props.profileId,
|
||||
reveal,
|
||||
});
|
||||
preview.value = result.preview;
|
||||
previewRuleSetHash.value = hashRuleSet(activeRuleSet.value);
|
||||
previewConfirmationToken.value = String(result.preview_token || '') || null;
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaSplit.previewFailed'));
|
||||
} finally {
|
||||
@@ -255,12 +284,12 @@ async function runPreview(): Promise<void> {
|
||||
|
||||
/**
|
||||
* 管理员确认规则:须已预览当前 rule_set;诊断或 needs_review 时阻断。
|
||||
* 核心逻辑:确认事件携带完整规则数组,由父页面立即刷新树并完成持久化,避免依赖异步 props 回写。
|
||||
* 核心逻辑:确认事件携带完整规则数组与 preview_token,由父页面保存时交服务端校验。
|
||||
*/
|
||||
function confirmRules(): void {
|
||||
if (!activeRuleSet.value || isReadonly.value) return;
|
||||
const currentHash = hashRuleSet(activeRuleSet.value);
|
||||
if (!preview.value || previewRuleSetHash.value !== currentHash) {
|
||||
if (!preview.value || previewRuleSetHash.value !== currentHash || !previewConfirmationToken.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmNeedsPreview'));
|
||||
return;
|
||||
}
|
||||
@@ -289,20 +318,24 @@ function confirmRules(): void {
|
||||
),
|
||||
confirmedRuleSet,
|
||||
];
|
||||
const tokens = { [confirmedRuleSet.source_path_id]: previewConfirmationToken.value };
|
||||
emit('update:split-rules', confirmedRules);
|
||||
emit('confirmed', confirmedRules);
|
||||
emit('confirmed', confirmedRules, tokens);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增一条拆分规则(segment + 默认 pipeline stages)。
|
||||
* 新增一条拆分规则(matcher 优先,并投影兼容 stages[])。
|
||||
*/
|
||||
function addRule(): void {
|
||||
if (isReadonly.value || !props.selectedPathId) return;
|
||||
const ruleSet = ensureRuleSet();
|
||||
const order = (ruleSet.rules?.length || 0) + 1;
|
||||
const stages = createDefaultPipelineStages(order);
|
||||
const nextRule: XfaSplitRule = {
|
||||
rule_id: newClientId('rule'),
|
||||
order: (ruleSet.rules?.length || 0) + 1,
|
||||
stages: createDefaultPipelineStages((ruleSet.rules?.length || 0) + 1),
|
||||
order,
|
||||
matcher: matcherFromExtraction('select_line', stages[1] || {}, order),
|
||||
stages,
|
||||
segment: {
|
||||
segment_id: newClientId('seg'),
|
||||
segment_code: '',
|
||||
@@ -313,6 +346,7 @@ function addRule(): void {
|
||||
};
|
||||
upsertRuleSet(markRuleSetDirty({
|
||||
...ruleSet,
|
||||
strategy: 'matcher',
|
||||
rules: normalizeRuleOrders([...(ruleSet.rules || []), nextRule]),
|
||||
}));
|
||||
collapsedRules.value = new Set([...collapsedRules.value].filter((id) => id !== nextRule.rule_id));
|
||||
@@ -352,40 +386,75 @@ function toggleAdvanced(ruleId: string): void {
|
||||
advancedRules.value = next;
|
||||
}
|
||||
|
||||
/** 返回规则的业务提取步骤;兼容历史 pipeline。 */
|
||||
/** 返回规则的业务提取步骤;优先由 matcher 合成,兼容历史 pipeline stages。 */
|
||||
function extractionStage(rule: XfaSplitRule): XfaSplitStage {
|
||||
return rule.stages.find((stage) => (
|
||||
if (rule.matcher?.type === 'prefix') {
|
||||
return {
|
||||
...createDefaultStage('extract_prefix'),
|
||||
value: rule.matcher.value,
|
||||
separators: rule.matcher.separators,
|
||||
case_sensitive: rule.matcher.case_sensitive,
|
||||
};
|
||||
}
|
||||
if (rule.matcher?.type === 'regex') {
|
||||
return {
|
||||
...createDefaultStage('regex_capture'),
|
||||
pattern: rule.matcher.pattern,
|
||||
capture_group: rule.matcher.capture_group,
|
||||
case_sensitive: rule.matcher.case_sensitive,
|
||||
};
|
||||
}
|
||||
if (rule.matcher?.type === 'position') {
|
||||
return {
|
||||
...createDefaultStage('select_line'),
|
||||
line_index: rule.matcher.line_index ?? rule.order ?? 1,
|
||||
};
|
||||
}
|
||||
const stages = rule.stages || [];
|
||||
return stages.find((stage) => (
|
||||
stage.type === 'select_line'
|
||||
|| stage.type === 'select_line_range'
|
||||
|| stage.type === 'extract_prefix'
|
||||
|| stage.type === 'regex_capture'
|
||||
|| stage.type === 'substring'
|
||||
)) || { ...createDefaultStage('select_line'), line_index: rule.order };
|
||||
)) || { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
|
||||
}
|
||||
|
||||
function extractionMode(rule: XfaSplitRule): ExtractionMode {
|
||||
const stages = rule.stages || [];
|
||||
// 连续行/截取仍靠 stages 驱动 UI;正式 matcher 用 position 近似。
|
||||
if (stages.some((stage) => stage.type === 'select_line_range')) return 'select_line_range';
|
||||
if (stages.some((stage) => stage.type === 'substring')) return 'substring';
|
||||
if (rule.matcher?.type === 'prefix') return 'extract_prefix';
|
||||
if (rule.matcher?.type === 'regex') return 'regex_capture';
|
||||
if (rule.matcher?.type === 'position') return 'select_line';
|
||||
return extractionStage(rule).type as ExtractionMode;
|
||||
}
|
||||
|
||||
/** 返回主提取之后顺序执行的高级处理步骤。 */
|
||||
function advancedStages(rule: XfaSplitRule): XfaSplitStage[] {
|
||||
const stages = rule.stages || [];
|
||||
const primary = extractionStage(rule);
|
||||
const primaryIndex = rule.stages.findIndex((stage) => stage.stage_id === primary.stage_id);
|
||||
const primaryIndex = stages.findIndex((stage) => stage.stage_id === primary.stage_id);
|
||||
if (primaryIndex < 0) return [];
|
||||
return rule.stages.slice(primaryIndex + 1);
|
||||
return stages.slice(primaryIndex + 1);
|
||||
}
|
||||
|
||||
/** 更换提取方式,同时保留公共拆分步骤和额外高级处理。 */
|
||||
/** 更换提取方式,同时同步正式 matcher 与兼容 stages。 */
|
||||
function changeExtractionMode(rule: XfaSplitRule, mode: ExtractionMode): void {
|
||||
const split = rule.stages.find((stage) => stage.type === 'split_lines') || createDefaultStage('split_lines');
|
||||
const stages = rule.stages || [];
|
||||
const split = stages.find((stage) => stage.type === 'split_lines') || createDefaultStage('split_lines');
|
||||
const advanced = advancedStages(rule);
|
||||
const extraction = createDefaultStage(mode);
|
||||
if (mode === 'select_line') extraction.line_index = rule.order;
|
||||
if (mode === 'select_line') extraction.line_index = rule.order ?? 1;
|
||||
if (mode === 'select_line_range') {
|
||||
extraction.line_start = rule.order;
|
||||
extraction.line_end = rule.order + 1;
|
||||
extraction.line_start = rule.order ?? 1;
|
||||
extraction.line_end = (rule.order ?? 1) + 1;
|
||||
}
|
||||
updateRule(rule.rule_id, { stages: [split, extraction, ...advanced] });
|
||||
updateRule(rule.rule_id, {
|
||||
stages: [split, extraction, ...advanced],
|
||||
matcher: matcherFromExtraction(mode, extraction, rule.order ?? 1),
|
||||
});
|
||||
}
|
||||
|
||||
/** 在主提取之后追加高级处理步骤。 */
|
||||
@@ -394,10 +463,17 @@ function addAdvancedStage(ruleId: string, type: XfaSplitStageType): void {
|
||||
addStage(ruleId, type);
|
||||
}
|
||||
|
||||
/** 更新当前规则的业务提取步骤参数。 */
|
||||
/** 更新当前规则的业务提取步骤参数,并同步 matcher。 */
|
||||
function updateExtraction(rule: XfaSplitRule, patch: XfaSplitStagePatch): void {
|
||||
const current = extractionStage(rule);
|
||||
updateStage(rule.rule_id, current.stage_id, patch);
|
||||
const nextStage = { ...current, ...patch };
|
||||
const mode = extractionMode(rule);
|
||||
updateRule(rule.rule_id, {
|
||||
stages: (rule.stages || []).map((stage) => (
|
||||
stage.stage_id === current.stage_id ? nextStage : stage
|
||||
)),
|
||||
matcher: matcherFromExtraction(mode, nextStage, rule.order ?? 1),
|
||||
});
|
||||
}
|
||||
|
||||
/** 返回当前规则在最近一次预览中的识别结果。 */
|
||||
@@ -444,6 +520,7 @@ function updateRule(ruleId: string, patch: XfaSplitRulePatch): void {
|
||||
...patch,
|
||||
segment: patch.segment ? { ...rule.segment, ...patch.segment } : rule.segment,
|
||||
stages: patch.stages ?? rule.stages,
|
||||
matcher: patch.matcher ?? rule.matcher,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
@@ -490,7 +567,7 @@ function deleteStage(ruleId: string, stageId: string): void {
|
||||
function moveStage(ruleId: string, stageId: string, direction: -1 | 1): void {
|
||||
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
|
||||
if (!rule) return;
|
||||
const stages = [...rule.stages];
|
||||
const stages = [...(rule.stages || [])];
|
||||
const index = stages.findIndex((item) => item.stage_id === stageId);
|
||||
const target = index + direction;
|
||||
if (index < 0 || target < 0 || target >= stages.length) return;
|
||||
@@ -509,7 +586,7 @@ function updateStage(ruleId: string, stageId: string, patch: XfaSplitStagePatch)
|
||||
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
|
||||
if (!rule) return;
|
||||
updateRule(ruleId, {
|
||||
stages: rule.stages.map((stage) => (
|
||||
stages: (rule.stages || []).map((stage) => (
|
||||
stage.stage_id === stageId ? { ...stage, ...patch } : stage
|
||||
)),
|
||||
});
|
||||
@@ -619,7 +696,6 @@ function stageTypeLabel(type: XfaSplitStageType): string {
|
||||
|
||||
watch(() => props.selectedPathId, () => {
|
||||
invalidatePreview();
|
||||
revealFullValues.value = false;
|
||||
});
|
||||
|
||||
defineExpose({ addRule, runPreview, confirmRules });
|
||||
@@ -701,11 +777,6 @@ watch(activeRuleSet, (current, previous) => {
|
||||
· v{{ activeRuleSet.rule_version }}
|
||||
</p>
|
||||
|
||||
<label v-if="canRevealSensitive" class="xfa-split__reveal">
|
||||
<input v-model="revealFullValues" type="checkbox" :disabled="canPreview === false" />
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.revealPreviewValues') }}
|
||||
</label>
|
||||
|
||||
<div v-if="preview" class="xfa-split__preview">
|
||||
<h4>{{ t('admin.shippingOrderProfiles.xfaSplit.previewTitle') }}</h4>
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaSplit.previewStatus', { status: preview.status }) }}</p>
|
||||
@@ -824,7 +895,7 @@ watch(activeRuleSet, (current, previous) => {
|
||||
type="number"
|
||||
min="1"
|
||||
:disabled="isReadonly"
|
||||
:value="extractionStage(rule).line_index ?? rule.order"
|
||||
:value="extractionStage(rule).line_index ?? (rule.order ?? 1)"
|
||||
@input="updateExtraction(rule, { line_index: Number(($event.target as HTMLInputElement).value) || 1 })"
|
||||
/>
|
||||
</label>
|
||||
@@ -836,7 +907,7 @@ watch(activeRuleSet, (current, previous) => {
|
||||
type="number"
|
||||
min="1"
|
||||
:disabled="isReadonly"
|
||||
:value="extractionStage(rule).line_start ?? rule.order"
|
||||
:value="extractionStage(rule).line_start ?? (rule.order ?? 1)"
|
||||
@input="updateExtraction(rule, { line_start: Number(($event.target as HTMLInputElement).value) || 1 })"
|
||||
/>
|
||||
</label>
|
||||
@@ -846,7 +917,7 @@ watch(activeRuleSet, (current, previous) => {
|
||||
type="number"
|
||||
min="1"
|
||||
:disabled="isReadonly"
|
||||
:value="extractionStage(rule).line_end ?? rule.order + 1"
|
||||
:value="extractionStage(rule).line_end ?? (rule.order ?? 1) + 1"
|
||||
@input="updateExtraction(rule, { line_end: Number(($event.target as HTMLInputElement).value) || 1 })"
|
||||
/>
|
||||
</label>
|
||||
@@ -943,7 +1014,7 @@ watch(activeRuleSet, (current, previous) => {
|
||||
<button
|
||||
type="button"
|
||||
class="danger"
|
||||
:disabled="isReadonly || rule.stages.length <= 1"
|
||||
:disabled="isReadonly || (rule.stages || []).length <= 1"
|
||||
@click="deleteStage(rule.rule_id, stage.stage_id)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.deleteStage') }}
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ describe('XfaStructuredPreview', () => {
|
||||
mappedFieldPreviews: {
|
||||
header: [{
|
||||
mappingId: 'm1', fieldCode: 'customer_po_no', pathId: 'hdr-ebeln',
|
||||
pathLabel: 'EBELN', maskedValue: '4510***227',
|
||||
pathLabel: 'EBELN', value: '4510000227',
|
||||
}],
|
||||
line: [],
|
||||
},
|
||||
|
||||
+5
-5
@@ -17,7 +17,7 @@ export interface XfaMappedFieldPreviewRow {
|
||||
fieldCode: string;
|
||||
pathId: string;
|
||||
pathLabel: string;
|
||||
maskedValue: string | null;
|
||||
value: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -39,7 +39,7 @@ const headerRows = computed(() => props.mappedFieldPreviews?.header?.length
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
maskedValue: null as string | null,
|
||||
value: null as string | null,
|
||||
})));
|
||||
|
||||
const lineRows = computed(() => props.mappedFieldPreviews?.line?.length
|
||||
@@ -49,7 +49,7 @@ const lineRows = computed(() => props.mappedFieldPreviews?.line?.length
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
maskedValue: null as string | null,
|
||||
value: null as string | null,
|
||||
})));
|
||||
const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
|
||||
|
||||
@@ -73,7 +73,7 @@ const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
|
||||
<li v-for="item in mappingRows" :key="item.mappingId">
|
||||
<strong>{{ item.fieldCode }}</strong>
|
||||
← {{ item.pathLabel }}
|
||||
<span v-if="item.maskedValue" class="masked">({{ item.maskedValue }})</span>
|
||||
<span v-if="item.value" class="value">({{ item.value }})</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.noMappings') }}</p>
|
||||
@@ -93,7 +93,7 @@ const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
|
||||
.maps__heading--line { margin-top: 12px; }
|
||||
.maps__list { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
|
||||
.maps li { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: .75rem; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.masked { color: var(--status-success-fg); }
|
||||
.value { color: var(--status-success-fg); }
|
||||
.empty { margin: 4px 0 0; color: var(--text-muted); font-size: .78rem; }
|
||||
h3 { margin: 0 0 8px; font-size: .9rem; }
|
||||
p { margin: 0; color: var(--text-secondary); }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/types/shipping-order-document-profile.types.ts
|
||||
* 用途:订单文档坐标模板、XFA 数据路径模板、受控样本预览和字段区域 DTO。
|
||||
* 用途:订单文档坐标模板、XFA 统一绑定(value/visual/split)、受控样本预览和字段区域 DTO。
|
||||
* 依赖:无。
|
||||
* 逻辑:管理页面只提交样本选择、白名单解析器与受控 path_id;不持有或提交 HTML/
|
||||
* 完整 XML、原始 PDF bytes 或对象存储地址。template_mode 为鉴别联合入口。
|
||||
@@ -108,6 +108,53 @@ export interface XfaCrossChecks {
|
||||
total_amount_policy: XfaTotalAmountPolicy;
|
||||
}
|
||||
|
||||
/** 归一化页面框(相对页宽高 0–1)。 */
|
||||
export interface XfaNormalizedBBox {
|
||||
x0: number;
|
||||
y0: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
}
|
||||
|
||||
export type XfaValueBindingType = 'xfa_dataset' | 'pdf_coordinate' | 'ocr_coordinate';
|
||||
export type XfaVisualBindingSource = 'acroform_widget' | 'user_drawn' | 'system_suggested';
|
||||
export type XfaVisualBindingStatus = 'suggested' | 'confirmed' | 'rejected' | 'needs_review';
|
||||
export type XfaBindingScope = 'header' | 'line';
|
||||
|
||||
/** 正式值绑定:XFA 仅 datasets 路径;普通 PDF 允许坐标/OCR。 */
|
||||
export interface XfaValueBinding {
|
||||
type: XfaValueBindingType;
|
||||
path_id?: string | null;
|
||||
data_path?: string | null;
|
||||
region_id?: string | null;
|
||||
}
|
||||
|
||||
/** 视觉绑定:页码 + 归一化框 + 确认状态;发布前正式字段须 confirmed。 */
|
||||
export interface XfaVisualBinding {
|
||||
page_no: number;
|
||||
normalized_bbox: XfaNormalizedBBox;
|
||||
source: XfaVisualBindingSource;
|
||||
status: XfaVisualBindingStatus;
|
||||
confidence?: number;
|
||||
}
|
||||
|
||||
/** 字段对拆分段的引用。 */
|
||||
export interface XfaSplitRuleRef {
|
||||
rule_set_id: string;
|
||||
segment_id: string;
|
||||
}
|
||||
|
||||
/** 统一字段绑定:value_binding + visual_binding + 可选 split_rule_ref。 */
|
||||
export interface XfaUnifiedFieldBinding {
|
||||
binding_id: string;
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
scope: XfaBindingScope;
|
||||
value_binding: XfaValueBinding;
|
||||
visual_binding: XfaVisualBinding;
|
||||
split_rule_ref?: XfaSplitRuleRef | null;
|
||||
}
|
||||
|
||||
/** xfa_dataset 模式 definition:禁止混入 table_regions / order_field_layouts。 */
|
||||
export interface OrderXfaDatasetProfileDefinition {
|
||||
template_mode: 'xfa_dataset';
|
||||
@@ -116,9 +163,13 @@ export interface OrderXfaDatasetProfileDefinition {
|
||||
line_mapping: XfaLineMapping;
|
||||
cross_checks: XfaCrossChecks;
|
||||
split_rules?: XfaSplitRuleSet[];
|
||||
/** 统一绑定列表(阶段 1+);与 header_mappings/line_mapping 并存至迁移完成。 */
|
||||
bindings?: XfaUnifiedFieldBinding[];
|
||||
}
|
||||
|
||||
export type XfaSplitHandling = 'mapped' | 'evidence_only';
|
||||
export type XfaSplitMatcherType = 'position' | 'prefix' | 'regex';
|
||||
/** @deprecated 历史 stages[] 管道;正式契约为 matcher 模型(阶段 1)。 */
|
||||
export type XfaSplitStageType =
|
||||
| 'split_lines'
|
||||
| 'select_line'
|
||||
@@ -141,6 +192,18 @@ export interface XfaSplitSegment {
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
/** 单行匹配器:优先级固定 prefix > regex > position > unmatched。 */
|
||||
export interface XfaSplitMatcher {
|
||||
type: XfaSplitMatcherType;
|
||||
line_index?: number | null;
|
||||
value?: string | null;
|
||||
separators?: string[];
|
||||
case_sensitive?: boolean;
|
||||
pattern?: string | null;
|
||||
capture_group?: number | null;
|
||||
}
|
||||
|
||||
/** @deprecated 仅兼容未迁移草稿的 stages[] UI。 */
|
||||
export interface XfaSplitStage {
|
||||
stage_id: string;
|
||||
type: XfaSplitStageType;
|
||||
@@ -164,8 +227,12 @@ export interface XfaSplitStage {
|
||||
|
||||
export interface XfaSplitRule {
|
||||
rule_id: string;
|
||||
order: number;
|
||||
/** 正式 matcher;与 stages 二选一,优先 matcher。 */
|
||||
matcher?: XfaSplitMatcher;
|
||||
segment: XfaSplitSegment;
|
||||
/** UI / 历史排序字段;matcher 模型可忽略。 */
|
||||
order: number;
|
||||
/** 历史 stages[];新规则可为空数组。 */
|
||||
stages: XfaSplitStage[];
|
||||
}
|
||||
|
||||
@@ -176,13 +243,17 @@ export interface XfaSplitNormalization {
|
||||
}
|
||||
|
||||
export interface XfaSplitRuleSet {
|
||||
/** 规则集 ID;兼容旧字段名 rule_id。 */
|
||||
rule_set_id?: string;
|
||||
rule_id: string;
|
||||
rule_version: number;
|
||||
source_path_id: string;
|
||||
source_field_code: string;
|
||||
source_scope?: 'header' | 'line';
|
||||
source_field_code?: string | null;
|
||||
/** 服务端从当前 XFA 分析重写的受控源路径,供正式提取使用。 */
|
||||
source_data_path?: string | null;
|
||||
strategy: 'pipeline';
|
||||
/** @deprecated 历史 pipeline 策略标记。 */
|
||||
strategy?: 'pipeline' | 'matcher';
|
||||
normalization?: XfaSplitNormalization;
|
||||
rules: XfaSplitRule[];
|
||||
unmatched_line_policy?: 'evidence_only' | 'needs_review';
|
||||
@@ -238,6 +309,82 @@ export interface XfaSplitRulesValidateResponse {
|
||||
issues: Array<{ code: string; message: string }>;
|
||||
}
|
||||
|
||||
/** 视觉绑定候选(suggest 返回;歧义不自动确认)。 */
|
||||
export interface XfaVisualPathCandidate {
|
||||
path_id: string;
|
||||
dataset_value_masked?: string | null;
|
||||
score?: number;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface XfaVisualBindingCandidate {
|
||||
candidate_id?: string;
|
||||
binding_id?: string;
|
||||
widget_id?: string;
|
||||
page_no?: number;
|
||||
normalized_bbox?: XfaNormalizedBBox;
|
||||
acroform_field_name_tail?: string | null;
|
||||
path_id?: string | null;
|
||||
field_code?: string | null;
|
||||
display_name?: string | null;
|
||||
confidence?: number;
|
||||
status?: XfaVisualBindingStatus | 'suggested';
|
||||
visual_binding?: XfaVisualBinding;
|
||||
path_candidates?: Array<XfaVisualPathCandidate & {
|
||||
data_path_hash?: string;
|
||||
match_hint?: string;
|
||||
confidence?: number;
|
||||
}>;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface XfaVisualBindingsSuggestResponse {
|
||||
profile_id?: number;
|
||||
document_id: number;
|
||||
page_no?: number;
|
||||
normalized_bbox?: XfaNormalizedBBox;
|
||||
candidates: XfaVisualBindingCandidate[];
|
||||
diagnostics?: Array<{ code: string; message: string }> | Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 XfaVisualBindingsSuggestResponse */
|
||||
export type XfaVisualBindingSuggestResponse = XfaVisualBindingsSuggestResponse;
|
||||
|
||||
export interface XfaVisualBindingMutationResponse {
|
||||
binding_id: string;
|
||||
visual_binding?: XfaVisualBinding;
|
||||
status?: XfaVisualBindingStatus | string;
|
||||
definition?: OrderXfaDatasetProfileDefinition;
|
||||
lock_version?: number;
|
||||
profile_id?: number;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 XfaVisualBindingMutationResponse */
|
||||
export type XfaVisualBindingActionResponse = XfaVisualBindingMutationResponse;
|
||||
|
||||
export interface XfaSplitRulesSuggestResponse {
|
||||
profile_id?: number;
|
||||
document_id?: number;
|
||||
path_id?: string | null;
|
||||
suggestion_status?: string;
|
||||
suggestion_checksum?: string;
|
||||
suggested_rule_set?: XfaSplitRuleSet | null;
|
||||
rule_set?: XfaSplitRuleSet | null;
|
||||
diagnostics?: Array<{ code: string; message: string }>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface XfaUnifiedMappingSuggestResponse {
|
||||
profile_id: number;
|
||||
document_id: number;
|
||||
suggestion_status?: string;
|
||||
suggestion_id?: string;
|
||||
suggestion_checksum?: string;
|
||||
visual_suggestion?: XfaVisualBindingsSuggestResponse | null;
|
||||
split_rule_suggestion?: XfaSplitRulesSuggestResponse | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type OrderProfileDefinition = OrderCoordinateProfileDefinition | OrderXfaDatasetProfileDefinition;
|
||||
|
||||
/**
|
||||
@@ -519,6 +666,11 @@ export interface OrderProfileVersionFamilySummary {
|
||||
default_version: number;
|
||||
version_count: number;
|
||||
updated_at: string;
|
||||
template_mode?: OrderProfileTemplateMode;
|
||||
unified_binding_status?: 'needs_migration' | 'pending_visual' | 'ready';
|
||||
unified_binding_count?: number;
|
||||
unified_pending_visual_count?: number;
|
||||
unified_needs_migration?: boolean;
|
||||
}
|
||||
|
||||
export interface OrderProfileVersionSummary {
|
||||
@@ -708,7 +860,18 @@ export interface OrderProfileTestSuite {
|
||||
page_no: number;
|
||||
}>;
|
||||
approved_at?: string | null;
|
||||
latest_run?: { status: 'passed' | 'failed'; sample_count: number; passed_sample_count: number; failure_codes: string[] } | null;
|
||||
latest_run?: {
|
||||
status: 'passed' | 'failed';
|
||||
sample_count: number;
|
||||
passed_sample_count: number;
|
||||
failure_codes: string[];
|
||||
metrics?: {
|
||||
visual_coverage_rate?: number;
|
||||
mirror_consistency_rate?: number;
|
||||
evidence_retention_rate?: number;
|
||||
key_field_accuracy_rate?: number;
|
||||
} | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileBlindTestInput {
|
||||
@@ -746,7 +909,7 @@ export interface OrderProfileBlindTestCandidate {
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
export interface OrderProfileCanvasRegion {
|
||||
id: string;
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value';
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value' | 'xfa_visual';
|
||||
label: string;
|
||||
region: OrderProfileRelativeRegion;
|
||||
fieldCode?: string | null;
|
||||
@@ -768,6 +931,8 @@ export interface OrderProfileCanvasRegion {
|
||||
stopAnchorText?: string | null;
|
||||
/** 标记所属文档页;画布切页时仅渲染当前页的区域。 */
|
||||
pageNo: number;
|
||||
/** XFA 视觉绑定确认状态;仅 kind=xfa_visual 时使用。 */
|
||||
visualBindingStatus?: XfaVisualBindingStatus;
|
||||
}
|
||||
|
||||
export interface OrderProfileSampleDocument {
|
||||
|
||||
@@ -195,23 +195,52 @@ export const createWorkspaceOrderExtractionSubmission = (
|
||||
* 核心逻辑:内嵌 conversation_processing 可选;缺省时前端由 work_items 合成分组;
|
||||
* 旧 conversation processing GET 已移除(无历史兼容)。
|
||||
*/
|
||||
type WorkspaceShippingProcessingResponse = {
|
||||
conversation_id: string;
|
||||
work_items: ReturnType<typeof normalizeShippingProcessingWorkItems>;
|
||||
conversation_processing: ConversationProcessingProjection | null;
|
||||
};
|
||||
|
||||
/** 同一会话跨组件实例共享在途请求,避免历史路由恢复重挂载造成重复慢查询。 */
|
||||
const shippingProcessingRequests = new Map<string, Promise<WorkspaceShippingProcessingResponse>>();
|
||||
const SHIPPING_PROCESSING_REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
export const getWorkspaceShippingProcessing = async (
|
||||
conversationId: string,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
const raw = await requestJson<{
|
||||
conversation_id?: string;
|
||||
work_items?: unknown[];
|
||||
conversation_processing?: ConversationProcessingProjection | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(conversationId)}`,
|
||||
{ signal },
|
||||
const normalized = String(conversationId || '').trim();
|
||||
const existing = shippingProcessingRequests.get(normalized);
|
||||
if (existing) return existing;
|
||||
|
||||
// 不把单个组件的 AbortSignal 传给共享网络请求:卸载旧实例不能取消新实例仍需的首屏数据。
|
||||
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
SHIPPING_PROCESSING_REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
return {
|
||||
conversation_id: String(raw?.conversation_id || conversationId),
|
||||
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
|
||||
conversation_processing: raw?.conversation_processing ?? null,
|
||||
};
|
||||
const request = requestJson<{
|
||||
conversation_id?: string;
|
||||
work_items?: unknown[];
|
||||
conversation_processing?: ConversationProcessingProjection | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(normalized)}`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((raw): WorkspaceShippingProcessingResponse => ({
|
||||
conversation_id: String(raw?.conversation_id || normalized),
|
||||
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
|
||||
conversation_processing: raw?.conversation_processing ?? null,
|
||||
}))
|
||||
.finally(() => {
|
||||
clearTimeout(timeout);
|
||||
if (shippingProcessingRequests.get(normalized) === request) {
|
||||
shippingProcessingRequests.delete(normalized);
|
||||
}
|
||||
});
|
||||
shippingProcessingRequests.set(normalized, request);
|
||||
return request;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -84,15 +84,15 @@ type MaintenanceRecordPanelCommand = {
|
||||
|
||||
const page = useChatPageContext();
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const shippingProcessing = useShippingNoticeWorkflow({
|
||||
conversationId: () => page.conversationId,
|
||||
// 历史会话首屏直接使用路由 ID,与聊天消息并行拉取统一进度。
|
||||
conversationId: () => page.conversationId || String(route.query.conversation_id || ''),
|
||||
refreshTrigger: () => page.workflowRefreshTrigger,
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
|
||||
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
|
||||
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts
|
||||
* 用途:验收 OT 导航数量阈值与模式切换。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewDocumentNavigation, {
|
||||
type ReviewDocumentNavItem,
|
||||
} from './ReviewDocumentNavigation.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
unnamedDocument: '未命名 PDF',
|
||||
documentNavigation: '导航',
|
||||
caseStatuses: { draft: '草稿', unknown: '未知' },
|
||||
otNav: {
|
||||
listTitle: '订单列表 · {count}',
|
||||
searchPlaceholder: '搜索',
|
||||
filterAll: '全部',
|
||||
filterNeedsAction: '待人工',
|
||||
filterProcessing: '处理中',
|
||||
filterDone: '完成',
|
||||
filterFailed: '失败',
|
||||
narrowTrigger: '订单 {current}/{total}',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 生成 n 个导航项。
|
||||
*/
|
||||
function items(count: number): ReviewDocumentNavItem[] {
|
||||
return Array.from({ length: count }, (_, i) => ({
|
||||
case_no: `C-${i + 1}`,
|
||||
file_name: `f${i + 1}.pdf`,
|
||||
status: 'draft',
|
||||
issue_count: i === 0 ? 1 : 0,
|
||||
}));
|
||||
}
|
||||
|
||||
type NavForceMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
|
||||
|
||||
/**
|
||||
* 挂载导航。
|
||||
*/
|
||||
function mountNav(count: number, forceMode?: NavForceMode) {
|
||||
return mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: items(count),
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: forceMode ?? null,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewDocumentNavigation', () => {
|
||||
it('hides navigation for a single OT', () => {
|
||||
const wrapper = mountNav(1, 'hidden');
|
||||
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses top tabs for 2–4 OTs', () => {
|
||||
const wrapper = mountNav(3, 'tabs');
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-tabs"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses sidebar list for 5–20 OTs', () => {
|
||||
const wrapper = mountNav(8, 'sidebar');
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(true);
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
|
||||
});
|
||||
|
||||
it('shows search for 20+ OTs', () => {
|
||||
const wrapper = mountNav(25, 'sidebar_search');
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-search"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-filter"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('emits select when a tab is clicked', async () => {
|
||||
const wrapper = mountNav(2, 'tabs');
|
||||
await wrapper.get('[data-testid="review-doc-nav-C-2"]').trigger('click');
|
||||
expect(wrapper.emitted('select')?.[0]).toEqual(['C-2']);
|
||||
});
|
||||
});
|
||||
+325
-19
@@ -1,72 +1,378 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewDocumentNavigation.vue
|
||||
用途:复核工作台顶部横向 PDF 文件导航(紧凑标签样式)。
|
||||
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 顶栏标签 / 左侧列表 / 窄屏抽屉)。
|
||||
依赖:vue-i18n、lucide-vue-next。
|
||||
逻辑:ShippingOrderReviewView 传入 Run 内 Case 摘要;emit select 切换当前 PDF Case。
|
||||
逻辑:1 份隐藏;2–4 顶栏;≥5 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { TriangleAlert } from 'lucide-vue-next';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Circle,
|
||||
Search,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
/** 导航项:一 PDF / 一 OT。 */
|
||||
export type ReviewDocumentNavItem = {
|
||||
case_no: string;
|
||||
file_name?: string | null;
|
||||
status: string;
|
||||
issue_count?: number;
|
||||
po_number?: string | null;
|
||||
customer_name?: string | null;
|
||||
stage_label?: string | null;
|
||||
};
|
||||
|
||||
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
|
||||
|
||||
const props = defineProps<{
|
||||
items: ReviewDocumentNavItem[];
|
||||
activeCaseNo?: string | null;
|
||||
/** 导航区域无障碍标签(避免与原生 aria-label 属性在 vue-tsc 中冲突) */
|
||||
navAriaLabel: string;
|
||||
/** 外部强制模式(测试用);默认按数量 + 窄屏自动推导 */
|
||||
forceMode?: ReviewDocumentNavMode | null;
|
||||
/** 侧栏是否默认收起为编号轨 */
|
||||
initiallyCollapsed?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [caseNo: string];
|
||||
'mode-change': [mode: ReviewDocumentNavMode];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const isNarrow = ref(false);
|
||||
const collapsed = ref(Boolean(props.initiallyCollapsed));
|
||||
const drawerOpen = ref(false);
|
||||
const searchQuery = ref('');
|
||||
const statusFilter = ref<'all' | 'needs_action' | 'processing' | 'done' | 'failed'>('all');
|
||||
|
||||
let mediaQuery: MediaQueryList | null = null;
|
||||
|
||||
/**
|
||||
* 将 Case 状态码映射为本地化文案,供导航标签展示。
|
||||
* @param status - Case 状态码
|
||||
* @returns 本地化文案;未知状态回落 unknown
|
||||
* 同步窄屏断点(lg 以下走抽屉入口)。
|
||||
*/
|
||||
function syncNarrow(event?: MediaQueryListEvent) {
|
||||
isNarrow.value = event ? event.matches : Boolean(mediaQuery?.matches);
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return;
|
||||
mediaQuery = window.matchMedia('(max-width: 1023px)');
|
||||
syncNarrow();
|
||||
mediaQuery.addEventListener('change', syncNarrow);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
mediaQuery?.removeEventListener('change', syncNarrow);
|
||||
});
|
||||
|
||||
/**
|
||||
* 推导导航呈现模式。
|
||||
*/
|
||||
const mode = computed<ReviewDocumentNavMode>(() => {
|
||||
if (props.forceMode) return props.forceMode;
|
||||
const count = props.items.length;
|
||||
if (count <= 1) return 'hidden';
|
||||
if (isNarrow.value) return 'narrow';
|
||||
if (count <= 4) return 'tabs';
|
||||
if (count <= 20) return 'sidebar';
|
||||
return 'sidebar_search';
|
||||
});
|
||||
|
||||
watch(mode, (value) => emit('mode-change', value), { immediate: true });
|
||||
|
||||
const activeIndex = computed(() => {
|
||||
const idx = props.items.findIndex((item) => item.case_no === props.activeCaseNo);
|
||||
return idx >= 0 ? idx + 1 : 1;
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 Case 状态码映射为本地化文案。
|
||||
*/
|
||||
function caseStatusLabel(status: string): string {
|
||||
const key = `chat.shippingOrderReview.caseStatuses.${status}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 导航状态图标语义。
|
||||
*/
|
||||
function navIconKind(item: ReviewDocumentNavItem): 'active' | 'alert' | 'processing' | 'done' | 'failed' | 'idle' {
|
||||
if (props.activeCaseNo === item.case_no) return 'active';
|
||||
const status = String(item.status || '').toLowerCase();
|
||||
if (item.issue_count && item.issue_count > 0) return 'alert';
|
||||
if (status === 'failed' || status === 'error') return 'failed';
|
||||
if (status === 'confirmed' || status === 'completed' || status === 'ready' || status === 'closed') return 'done';
|
||||
if (status === 'processing' || status === 'reparse_pending' || status === 'queued') return 'processing';
|
||||
if (status === 'non_order' || status === 'cancelled' || status === 'superseded') return 'idle';
|
||||
if (status === 'draft' || status === 'pending_review' || status === 'waiting_review') return 'alert';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否匹配状态分段过滤。
|
||||
*/
|
||||
function matchesStatusFilter(item: ReviewDocumentNavItem): boolean {
|
||||
if (statusFilter.value === 'all') return true;
|
||||
const kind = navIconKind(item);
|
||||
if (statusFilter.value === 'needs_action') return kind === 'alert';
|
||||
if (statusFilter.value === 'processing') return kind === 'processing' || kind === 'active';
|
||||
if (statusFilter.value === 'done') return kind === 'done';
|
||||
if (statusFilter.value === 'failed') return kind === 'failed';
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索 + 过滤后的列表。
|
||||
*/
|
||||
const filteredItems = computed(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase();
|
||||
return props.items.filter((item) => {
|
||||
if (!matchesStatusFilter(item)) return false;
|
||||
if (!q) return true;
|
||||
const hay = [
|
||||
item.file_name,
|
||||
item.case_no,
|
||||
item.po_number,
|
||||
item.customer_name,
|
||||
item.stage_label,
|
||||
].map((v) => String(v || '').toLowerCase()).join(' ');
|
||||
return hay.includes(q);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 选择 OT;窄屏抽屉内选择后关闭。
|
||||
*/
|
||||
function onSelect(caseNo: string) {
|
||||
emit('select', caseNo);
|
||||
drawerOpen.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav
|
||||
class="rounded-xl border border-slate-200 bg-white p-2 shadow-sm dark:border-slate-800 dark:bg-slate-900"
|
||||
v-if="mode !== 'hidden'"
|
||||
:aria-label="navAriaLabel"
|
||||
data-testid="review-document-navigation"
|
||||
:data-nav-mode="mode"
|
||||
:class="mode === 'tabs'
|
||||
? 'rounded-xl border border-slate-200 bg-white p-2 shadow-sm dark:border-slate-800 dark:bg-slate-900'
|
||||
: mode === 'narrow'
|
||||
? ''
|
||||
: 'sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900 lg:w-64'"
|
||||
>
|
||||
<div class="flex gap-1.5 overflow-x-auto">
|
||||
<!-- 2–4:顶部标签 -->
|
||||
<div
|
||||
v-if="mode === 'tabs'"
|
||||
class="flex gap-1.5 overflow-x-auto"
|
||||
data-testid="review-doc-nav-tabs"
|
||||
>
|
||||
<button
|
||||
v-for="item in items"
|
||||
:key="item.case_no"
|
||||
type="button"
|
||||
class="inline-flex max-w-[220px] shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-left text-xs transition-colors"
|
||||
class="inline-flex min-w-[9rem] max-w-[240px] shrink-0 flex-col gap-0.5 rounded-lg border px-2.5 py-1.5 text-left text-xs transition-colors"
|
||||
:class="activeCaseNo === item.case_no
|
||||
? 'border-sky-500 bg-sky-50 text-sky-950 dark:border-sky-700 dark:bg-sky-950/40 dark:text-sky-100'
|
||||
? 'border-sky-500 bg-sky-50 text-sky-950 ring-1 ring-sky-400 dark:border-sky-700 dark:bg-sky-950/40 dark:text-sky-100'
|
||||
: 'border-slate-200 text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800'"
|
||||
:data-testid="`review-doc-nav-${item.case_no}`"
|
||||
@click="emit('select', item.case_no)"
|
||||
@click="onSelect(item.case_no)"
|
||||
>
|
||||
<TriangleAlert
|
||||
v-if="item.issue_count"
|
||||
class="h-3.5 w-3.5 shrink-0 text-amber-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="truncate font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
<span class="shrink-0 text-[10px] text-slate-500 dark:text-slate-400">
|
||||
{{ caseStatusLabel(item.status) }}
|
||||
<span class="flex items-center gap-1 truncate font-medium">
|
||||
<TriangleAlert
|
||||
v-if="navIconKind(item) === 'alert'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-amber-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Check
|
||||
v-else-if="navIconKind(item) === 'done'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-emerald-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<X
|
||||
v-else-if="navIconKind(item) === 'failed'"
|
||||
class="h-3.5 w-3.5 shrink-0 text-rose-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Circle
|
||||
v-else
|
||||
class="h-3 w-3 shrink-0 text-slate-400"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="truncate">{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
</span>
|
||||
<span class="truncate text-[10px] text-slate-500 dark:text-slate-400">
|
||||
{{ item.customer_name || caseStatusLabel(item.status) }}
|
||||
<template v-if="item.stage_label"> · {{ item.stage_label }}</template>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- ≥5:左侧列表 -->
|
||||
<template v-else-if="mode === 'sidebar' || mode === 'sidebar_search'">
|
||||
<div class="flex items-center justify-between gap-2 border-b border-slate-100 px-2 py-2 dark:border-slate-800">
|
||||
<span class="text-xs font-semibold text-primary">
|
||||
{{ t('chat.shippingOrderReview.otNav.listTitle', { count: items.length }) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-muted hover:bg-slate-100 dark:hover:bg-slate-800"
|
||||
data-testid="review-doc-nav-collapse"
|
||||
@click="collapsed = !collapsed"
|
||||
>
|
||||
<ChevronLeft
|
||||
v-if="!collapsed"
|
||||
class="h-4 w-4"
|
||||
/>
|
||||
<ChevronRight
|
||||
v-else
|
||||
class="h-4 w-4"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!collapsed && mode === 'sidebar_search'"
|
||||
class="space-y-2 border-b border-slate-100 px-2 py-2 dark:border-slate-800"
|
||||
>
|
||||
<label class="relative block">
|
||||
<Search class="pointer-events-none absolute left-2 top-1.5 h-3.5 w-3.5 text-muted" />
|
||||
<input
|
||||
v-model="searchQuery"
|
||||
type="search"
|
||||
class="w-full rounded-md border border-slate-200 bg-white py-1 pl-7 pr-2 text-[11px] dark:border-slate-700 dark:bg-slate-950"
|
||||
:placeholder="t('chat.shippingOrderReview.otNav.searchPlaceholder')"
|
||||
data-testid="review-doc-nav-search"
|
||||
>
|
||||
</label>
|
||||
<select
|
||||
v-model="statusFilter"
|
||||
class="w-full rounded-md border border-slate-200 bg-white px-2 py-1 text-[11px] dark:border-slate-700 dark:bg-slate-950"
|
||||
data-testid="review-doc-nav-filter"
|
||||
>
|
||||
<option value="all">{{ t('chat.shippingOrderReview.otNav.filterAll') }}</option>
|
||||
<option value="needs_action">{{ t('chat.shippingOrderReview.otNav.filterNeedsAction') }}</option>
|
||||
<option value="processing">{{ t('chat.shippingOrderReview.otNav.filterProcessing') }}</option>
|
||||
<option value="done">{{ t('chat.shippingOrderReview.otNav.filterDone') }}</option>
|
||||
<option value="failed">{{ t('chat.shippingOrderReview.otNav.filterFailed') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="min-h-0 flex-1 overflow-y-auto p-1.5"
|
||||
data-testid="review-doc-nav-list"
|
||||
>
|
||||
<button
|
||||
v-for="(item, index) in (collapsed ? items : filteredItems)"
|
||||
:key="item.case_no"
|
||||
type="button"
|
||||
class="mb-1 flex w-full items-start gap-2 rounded-lg border px-2 py-1.5 text-left text-xs transition-colors"
|
||||
:class="activeCaseNo === item.case_no
|
||||
? 'border-sky-500 bg-sky-50 dark:border-sky-700 dark:bg-sky-950/40'
|
||||
: 'border-transparent hover:bg-slate-50 dark:hover:bg-slate-800'"
|
||||
:title="collapsed
|
||||
? `${item.file_name || item.case_no} · ${caseStatusLabel(item.status)}`
|
||||
: undefined"
|
||||
:data-testid="`review-doc-nav-${item.case_no}`"
|
||||
@click="onSelect(item.case_no)"
|
||||
>
|
||||
<span
|
||||
v-if="collapsed"
|
||||
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-slate-100 text-[10px] font-semibold dark:bg-slate-800"
|
||||
>
|
||||
{{ index + 1 }}
|
||||
</span>
|
||||
<template v-else>
|
||||
<TriangleAlert
|
||||
v-if="navIconKind(item) === 'alert'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500"
|
||||
/>
|
||||
<Check
|
||||
v-else-if="navIconKind(item) === 'done'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"
|
||||
/>
|
||||
<X
|
||||
v-else-if="navIconKind(item) === 'failed'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-rose-500"
|
||||
/>
|
||||
<Circle
|
||||
v-else
|
||||
class="mt-0.5 h-3 w-3 shrink-0 text-slate-400"
|
||||
/>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate font-medium text-primary">
|
||||
{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
|
||||
</span>
|
||||
<span class="block truncate text-[10px] text-muted">
|
||||
{{ item.customer_name || caseStatusLabel(item.status) }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 窄屏:入口 + 抽屉 -->
|
||||
<template v-else-if="mode === 'narrow'">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-medium shadow-sm dark:border-slate-800 dark:bg-slate-900"
|
||||
data-testid="review-doc-nav-narrow-trigger"
|
||||
@click="drawerOpen = true"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.otNav.narrowTrigger', { current: activeIndex, total: items.length }) }}
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="drawerOpen"
|
||||
class="fixed inset-0 z-50 flex justify-end"
|
||||
data-testid="review-doc-nav-narrow-drawer"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-0 bg-slate-900/40"
|
||||
@click="drawerOpen = false"
|
||||
/>
|
||||
<aside class="relative z-10 flex h-full w-full max-w-sm flex-col border-l border-default bg-surface p-3 shadow-xl">
|
||||
<div class="mb-3 flex items-center justify-between">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.otNav.listTitle', { count: items.length }) }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 hover:bg-surface-muted"
|
||||
@click="drawerOpen = false"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 space-y-1 overflow-y-auto">
|
||||
<button
|
||||
v-for="item in items"
|
||||
:key="item.case_no"
|
||||
type="button"
|
||||
class="flex w-full flex-col rounded-lg border px-3 py-2 text-left text-xs"
|
||||
:class="activeCaseNo === item.case_no
|
||||
? 'border-sky-500 bg-sky-50'
|
||||
: 'border-slate-200'"
|
||||
:data-testid="`review-doc-nav-${item.case_no}`"
|
||||
@click="onSelect(item.case_no)"
|
||||
>
|
||||
<span class="font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
<span class="text-[10px] text-muted">{{ caseStatusLabel(item.status) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
</nav>
|
||||
</template>
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewUnsavedSwitchDialog.spec.ts
|
||||
* 用途:验收切换 OT 未保存硬拦截三按钮。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewUnsavedSwitchDialog from './ReviewUnsavedSwitchDialog.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
unsavedSwitch: {
|
||||
title: '有未保存的修改',
|
||||
message: '当前订单有 {count} 项修改尚未保存。',
|
||||
cancel: '取消',
|
||||
discard: '放弃修改',
|
||||
saveAndSwitch: '保存后切换',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('ReviewUnsavedSwitchDialog', () => {
|
||||
it('emits cancel / discard / save-and-switch', async () => {
|
||||
const wrapper = mount(ReviewUnsavedSwitchDialog, {
|
||||
props: { open: true, unsavedCount: 2 },
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: { Teleport: { template: '<div><slot /></div>' } },
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-unsaved-switch-dialog"]').exists()).toBe(true);
|
||||
await wrapper.get('[data-testid="review-unsaved-cancel"]').trigger('click');
|
||||
expect(wrapper.emitted('cancel')).toBeTruthy();
|
||||
await wrapper.get('[data-testid="review-unsaved-discard"]').trigger('click');
|
||||
expect(wrapper.emitted('discard')).toBeTruthy();
|
||||
await wrapper.get('[data-testid="review-unsaved-save-switch"]').trigger('click');
|
||||
expect(wrapper.emitted('save-and-switch')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewUnsavedSwitchDialog.vue
|
||||
用途:切换 OT/PDF 时未保存硬拦截确认框。
|
||||
依赖:vue-i18n。
|
||||
逻辑:由 ShippingOrderReviewView 在 select 前打开;三选一:取消 / 放弃修改 / 保存后切换。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
defineProps<{
|
||||
open: boolean;
|
||||
unsavedCount: number;
|
||||
saving?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
cancel: [];
|
||||
discard: [];
|
||||
'save-and-switch': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-[60] flex items-center justify-center p-4"
|
||||
data-testid="review-unsaved-switch-dialog"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-0 bg-slate-900/40"
|
||||
:aria-label="t('chat.shippingOrderReview.unsavedSwitch.cancel')"
|
||||
@click="emit('cancel')"
|
||||
/>
|
||||
<div
|
||||
class="relative z-10 w-full max-w-md rounded-xl border border-default bg-surface p-4 shadow-xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
<h2 class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingOrderReview.unsavedSwitch.title') }}
|
||||
</h2>
|
||||
<p class="mt-2 text-xs text-secondary">
|
||||
{{ t('chat.shippingOrderReview.unsavedSwitch.message', { count: unsavedCount }) }}
|
||||
</p>
|
||||
<div class="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-medium"
|
||||
data-testid="review-unsaved-cancel"
|
||||
:disabled="saving"
|
||||
@click="emit('cancel')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.unsavedSwitch.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-rose-200 px-3 py-1.5 text-xs font-medium text-rose-700 dark:border-rose-900 dark:text-rose-300"
|
||||
data-testid="review-unsaved-discard"
|
||||
:disabled="saving"
|
||||
@click="emit('discard')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.unsavedSwitch.discard') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-sky-600 px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50"
|
||||
data-testid="review-unsaved-save-switch"
|
||||
:disabled="saving"
|
||||
@click="emit('save-and-switch')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.unsavedSwitch.saveAndSwitch') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -1,14 +1,17 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkbenchFooter.vue
|
||||
用途:订单复核工作台底部固定操作栏。
|
||||
依赖:vue-i18n、lucide-vue-next。
|
||||
逻辑:ShippingOrderReviewView 传入 available_actions 与门禁状态;sticky bottom 保证在主滚动区内常驻可见。
|
||||
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 流程恢复动作)。
|
||||
依赖:vue-i18n、lucide-vue-next、ActionPresentation。
|
||||
逻辑:ShippingOrderReviewView 传入 available_actions 与流程动作投影;sticky bottom;
|
||||
系统自动推进中隐藏无效主写按钮;流程写操作经 flow-action emit。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RefreshCw, Save } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
const props = defineProps<{
|
||||
const props = withDefaults(defineProps<{
|
||||
availableActions: string[];
|
||||
canConfirmBuild: boolean;
|
||||
saving: boolean;
|
||||
@@ -16,7 +19,18 @@ const props = defineProps<{
|
||||
hasDraft: boolean;
|
||||
/** can_build && can_auto_create 时隐藏确认按钮并展示自动推进提示 */
|
||||
hideConfirmBecauseAutoGate?: boolean;
|
||||
}>();
|
||||
/** 未保存本地修改计数(硬拦截与底栏提示同源) */
|
||||
unsavedCount?: number;
|
||||
/** 统一流程动作(原进度条 ActionBar);surface=review */
|
||||
flowPresentation?: ActionPresentation | null;
|
||||
/** 系统自动推进中:隐藏主写按钮 */
|
||||
automating?: boolean;
|
||||
}>(), {
|
||||
unsavedCount: 0,
|
||||
flowPresentation: null,
|
||||
automating: false,
|
||||
hideConfirmBecauseAutoGate: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'mark-non-order': [];
|
||||
@@ -25,9 +39,10 @@ const emit = defineEmits<{
|
||||
'upload-replacement': [event: Event];
|
||||
validate: [];
|
||||
confirm: [];
|
||||
'flow-action': [item: ActionPresentationItem];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 判断某 action 是否在当前 Case 可用。
|
||||
@@ -35,84 +50,140 @@ const { t } = useI18n();
|
||||
function hasAction(action: string): boolean {
|
||||
return props.availableActions.includes(action);
|
||||
}
|
||||
|
||||
const showFooter = computed(() => props.hasDraft && !props.isReadOnly);
|
||||
|
||||
const flowItems = computed((): ActionPresentationItem[] => {
|
||||
const presentation = props.flowPresentation;
|
||||
if (!presentation) return [];
|
||||
const items: ActionPresentationItem[] = [];
|
||||
if (presentation.primary) items.push(presentation.primary);
|
||||
if (presentation.secondary) items.push(presentation.secondary);
|
||||
items.push(...presentation.overflow);
|
||||
// 刷新留给顶部只读区;底栏不重复。
|
||||
return items.filter((item) => item.intent !== 'refresh');
|
||||
});
|
||||
|
||||
/**
|
||||
* 流程动作文案。
|
||||
*/
|
||||
function flowLabel(item: ActionPresentationItem): string {
|
||||
if (te(item.labelKey)) return t(item.labelKey);
|
||||
const gateKey = `workspace.shippingNotice.processGate.actions.${item.actionCode}`;
|
||||
if (te(gateKey)) return t(gateKey);
|
||||
return item.actionCode;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<footer
|
||||
v-if="hasDraft && !isReadOnly"
|
||||
v-if="showFooter"
|
||||
class="sticky bottom-0 z-20 flex shrink-0 flex-col gap-3 border-t border-slate-200 bg-white/95 p-3 shadow-[0_-4px_12px_rgba(15,23,42,0.06)] backdrop-blur sm:flex-row sm:items-center sm:justify-between dark:border-slate-800 dark:bg-slate-900/95"
|
||||
data-testid="review-footer-actions"
|
||||
:data-automating="automating ? '1' : '0'"
|
||||
>
|
||||
<div class="order-1 flex flex-wrap items-center gap-2 sm:order-1">
|
||||
<button
|
||||
v-if="hasAction('mark_non_order')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
|
||||
@click="emit('mark-non-order')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.markNonOrder') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
|
||||
@click="emit('mark-quality-issue')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.markQualityIssue') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('reparse')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
@click="emit('reparse')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
>
|
||||
<input
|
||||
class="sr-only"
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
<template v-if="!automating">
|
||||
<button
|
||||
v-if="hasAction('mark_non_order')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
@change="emit('upload-replacement', $event)"
|
||||
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
|
||||
@click="emit('mark-non-order')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.uploadReplacement') }}
|
||||
</label>
|
||||
{{ t('chat.shippingOrderReview.markNonOrder') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
|
||||
@click="emit('mark-quality-issue')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.markQualityIssue') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('reparse')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
@click="emit('reparse')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
>
|
||||
<input
|
||||
class="sr-only"
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
:disabled="saving"
|
||||
@change="emit('upload-replacement', $event)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.uploadReplacement') }}
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<button
|
||||
v-for="item in flowItems"
|
||||
:key="`${item.intent}-${item.actionCode}`"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-slate-300 px-3 py-2 text-sm text-slate-700 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
:data-testid="`review-footer-flow-${item.intent}`"
|
||||
:data-intent="item.intent"
|
||||
@click="emit('flow-action', item)"
|
||||
>
|
||||
{{ flowLabel(item) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="order-2 flex flex-wrap items-center justify-end gap-2 sm:order-2">
|
||||
<p
|
||||
v-if="hideConfirmBecauseAutoGate"
|
||||
v-if="unsavedCount > 0"
|
||||
class="text-xs text-amber-700 dark:text-amber-300"
|
||||
data-testid="review-footer-unsaved"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.unsavedSwitch.unsavedCount', { count: unsavedCount }) }}
|
||||
</p>
|
||||
<p
|
||||
v-if="automating"
|
||||
class="text-xs text-muted"
|
||||
data-testid="review-footer-automating-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.automatingFooterHint') }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="hideConfirmBecauseAutoGate"
|
||||
class="text-xs text-muted"
|
||||
data-testid="review-auto-gate-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.autoGateProgressHint') }}
|
||||
</p>
|
||||
<button
|
||||
v-if="hasAction('validate')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
@click="emit('validate')"
|
||||
>
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
|
||||
type="button"
|
||||
:disabled="saving || !canConfirmBuild"
|
||||
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
data-testid="review-confirm-create"
|
||||
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
|
||||
@click="emit('confirm')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.confirmCreate') }}
|
||||
</button>
|
||||
<template v-if="!automating">
|
||||
<button
|
||||
v-if="hasAction('validate')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
@click="emit('validate')"
|
||||
>
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
|
||||
type="button"
|
||||
:disabled="saving || !canConfirmBuild"
|
||||
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
data-testid="review-confirm-create"
|
||||
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
|
||||
@click="emit('confirm')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.confirmCreate') }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</footer>
|
||||
</template>
|
||||
+43
-15
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts
|
||||
* 用途:复核统一进度面板——UnifiedProgressTrack 挂载;人工入口仅 Gate 动作。
|
||||
* 用途:订单处理台进度面板——紧凑五域条;人工入口仅 Gate 动作。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n stub、RouterLink stub。
|
||||
* 逻辑:有 processingProjection 才渲染轨道节点;manual upload 入口需 nextActionCode;RPA 不展示人工 CTA。
|
||||
* 逻辑:有 processingProjection 才渲染 ReviewProgressStrip;无页内 15 阶展开;manual upload 入口需 nextActionCode。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
@@ -22,7 +22,7 @@ const messages = {
|
||||
subtitle: 'Advances through freight upload',
|
||||
polling: 'Refreshing…',
|
||||
progressUnavailable: 'Progress unavailable — refresh the page.',
|
||||
openTaskWorkbench: 'Open task workbench to register',
|
||||
openTaskWorkbench: 'Open Task Center to register',
|
||||
nextStepsManualUpload:
|
||||
'Next: download Excel → upload on freight platform → submit evidence and receipt',
|
||||
nextStepsGeneric: 'Manual action required — follow the system prompt.',
|
||||
@@ -30,6 +30,22 @@ const messages = {
|
||||
},
|
||||
shippingProcessing: {
|
||||
panelTitle: 'Shipping processing',
|
||||
expandHistory: 'Show full track',
|
||||
collapseHistory: 'Hide full track',
|
||||
progress: {
|
||||
completedOfTotal: '{done} of {total} done',
|
||||
remainingHint: '{count} remaining',
|
||||
positionOfTotal: '{current} / {total}',
|
||||
domainReceiveParse: 'Receive',
|
||||
domainCandidateIdentity: 'Candidate',
|
||||
domainOrderConfirm: 'Confirm',
|
||||
domainInventoryHandle: 'Inventory',
|
||||
domainFulfillmentShip: 'Ship',
|
||||
currentNeedLabel: 'Need: ',
|
||||
systemProcessingNeed: 'System processing',
|
||||
viewProcessDetails: 'View process details',
|
||||
},
|
||||
gateReasons: { generic: 'Needs action' },
|
||||
status: {
|
||||
automating: 'Automating',
|
||||
blocked: 'Blocked',
|
||||
@@ -39,6 +55,18 @@ const messages = {
|
||||
freight_uploading: 'Uploading to freight',
|
||||
excel_generating: 'Generating Excel',
|
||||
},
|
||||
action: {
|
||||
refresh: 'Refresh',
|
||||
},
|
||||
},
|
||||
},
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actions: {
|
||||
wait_manual_upload: 'Wait for manual upload',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -76,11 +104,12 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
it('shows unavailable state without projection', () => {
|
||||
const wrapper = mountPanel({ polling: false, processingProjection: null });
|
||||
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="unified-progress-track"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-progress-strip"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="unified-progress-track"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders unified track nodes from projection stage', () => {
|
||||
it('renders compact domain strip without inline 15-node expand', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
@@ -90,13 +119,14 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(false);
|
||||
const current = wrapper.findAll('[data-testid="unified-progress-node"]')
|
||||
.find((node) => node.attributes('data-stage') === 'excel_generating');
|
||||
expect(current?.attributes('data-current')).toBe('true');
|
||||
expect(current?.attributes('data-state')).toBe('running');
|
||||
expect(wrapper.find('[data-testid="review-progress-strip"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('[data-testid="review-progress-domains"] [data-domain]').length).toBe(5);
|
||||
expect(wrapper.find('[data-testid="review-progress-expand-full"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="unified-action-bar"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-progress-open-details"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('lights freight_uploading and hides manual CTA while automating', () => {
|
||||
it('hides manual CTA while automating freight upload', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
@@ -105,14 +135,12 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
sourceType: 'eml',
|
||||
},
|
||||
});
|
||||
const freight = wrapper.findAll('[data-testid="unified-progress-node"]')
|
||||
.find((node) => node.attributes('data-stage') === 'freight_uploading');
|
||||
expect(freight?.attributes('data-current')).toBe('true');
|
||||
expect(wrapper.find('[data-testid="review-progress-strip"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows task workbench link when gate next_action is manual upload', () => {
|
||||
it('shows Task Center link when gate next_action is manual upload', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
@@ -129,7 +157,7 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
});
|
||||
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
|
||||
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
|
||||
expect(link.text()).toContain('Open task workbench to register');
|
||||
expect(link.text()).toContain('Open Task Center to register');
|
||||
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
|
||||
expect(link.attributes('href')).toContain('SN-1');
|
||||
});
|
||||
|
||||
+17
-7
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue
|
||||
用途:复核工作台统一进度轨道(完整 15 阶密度窗口)+ Gate 下一步提示。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、UnifiedProgressTrack、shippingProcessingFulfillment。
|
||||
逻辑:节点高亮仅读统一投影;任务台入口仅当 currentGate.nextActionCode 指人工上传。
|
||||
用途:订单处理工作台只读进度区(ReviewProgressStrip)+ Gate / 人工上传下一步提示。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、ReviewProgressStrip。
|
||||
逻辑:节点高亮只读统一投影;打开流程详情 / 刷新 emit 给宿主;写操作不在本面板。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import UnifiedProgressTrack from '@/features/shipping-progress/components/UnifiedProgressTrack.vue';
|
||||
import ReviewProgressStrip from '@/features/shipping-progress/components/ReviewProgressStrip.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
item: ShippingReviewProgressContext | null;
|
||||
@@ -29,6 +29,11 @@ const props = defineProps<{
|
||||
processingProjection?: ShippingProcessingProjection | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-process-details': [];
|
||||
refresh: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const hasProjection = computed(() => Boolean(props.processingProjection));
|
||||
@@ -115,10 +120,15 @@ const genericNextStepMessage = computed(() => {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-3" data-testid="review-progress-nodes">
|
||||
<UnifiedProgressTrack
|
||||
<div
|
||||
v-if="processingProjection"
|
||||
class="mt-3"
|
||||
data-testid="review-progress-nodes"
|
||||
>
|
||||
<ReviewProgressStrip
|
||||
:projection="processingProjection"
|
||||
density="review"
|
||||
@open-process-details="emit('open-process-details')"
|
||||
@refresh="emit('refresh')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+87
-1
@@ -8,7 +8,10 @@ import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import type { ConversationProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import type {
|
||||
ConversationProcessingProjection,
|
||||
ShippingProcessingProjection,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import ShippingConversationProcessingCard from './ShippingConversationProcessingCard.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
@@ -64,6 +67,41 @@ function buildProjection(): ConversationProcessingProjection {
|
||||
};
|
||||
}
|
||||
|
||||
/** 构造任务卡使用的权威统一进度。 */
|
||||
function buildWorkItem(
|
||||
taskNo: string,
|
||||
patch: Partial<ShippingProcessingProjection> = {},
|
||||
): ShippingProcessingProjection {
|
||||
return {
|
||||
workItemType: 'order_task',
|
||||
workItemNo: taskNo,
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: taskNo,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-1',
|
||||
intakeNo: 'INT-1',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['view_details'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: `${taskNo}.pdf`,
|
||||
documentId: taskNo === 'OT-NEED' ? 1 : 2,
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('ShippingConversationProcessingCard', () => {
|
||||
it('renders needs_action / processing / completed groups, hides history on the right panel', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
@@ -315,4 +353,52 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
item: { workItemNo: 'SNI-1' },
|
||||
});
|
||||
});
|
||||
|
||||
it('renders each PDF task with its own compact projection, including completed tasks', async () => {
|
||||
const projection = buildProjection();
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection,
|
||||
workItems: [
|
||||
buildWorkItem('OT-NEED', {
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
}),
|
||||
buildWorkItem('OT-PROC', {
|
||||
stage: 'inventory_matching',
|
||||
}),
|
||||
buildWorkItem('OT-DONE', {
|
||||
status: 'completed',
|
||||
stage: 'completed',
|
||||
}),
|
||||
],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 未聚焦时:needs_action/processing 显示紧凑进度;已完成默认收起(UI-05)。
|
||||
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"] [data-testid="sidebar-progress-inline"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待复核');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').text()).toContain('已完成');
|
||||
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('maps internal review_case_draft status to a user-facing review label', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.needs_action = [{
|
||||
...projection.needs_action[0],
|
||||
status_label: 'review_case_draft',
|
||||
}];
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.text()).toContain('待复核');
|
||||
expect(wrapper.text()).not.toContain('review_case_draft');
|
||||
});
|
||||
});
|
||||
+67
-5
@@ -2,10 +2,11 @@
|
||||
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
|
||||
* 用途:右侧「本次处理中」顶层任务卡——按 needs_action / processing / completed 展示。
|
||||
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
|
||||
* shippingProcessingLabels。
|
||||
* shippingProcessingLabels、SidebarProgressInline。
|
||||
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems,禁止 Workflow fallback;
|
||||
* 单 PDF 主标题用文件名,多 PDF 用「订单识别任务」;右侧不渲染 history;
|
||||
* 任务级操作只消费后端 available_actions;另渲染尚未建 OT 的 order_intake 材料卡。
|
||||
* 仅聚焦卡展开完整 SidebarProgressInline,未聚焦显示紧凑单行,已完成默认收起(UI-05);
|
||||
* 单 PDF 不展示「展开文件详情」。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue';
|
||||
@@ -31,6 +32,8 @@ import {
|
||||
shippingProcessingSourceTypeKey,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
|
||||
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
const props = defineProps<{
|
||||
projection: ConversationProcessingProjection | null;
|
||||
@@ -51,6 +54,8 @@ const emit = defineEmits<{
|
||||
taskAction: [payload: { task: ConversationProcessingUserTask; action: string }];
|
||||
/** Intake 级统一投影动作(如 retry_parse) */
|
||||
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
|
||||
/** OT 卡内统一进度动作。 */
|
||||
projectionAction: [payload: { projection: ShippingProcessingProjection; item: ActionPresentationItem }];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -82,6 +87,17 @@ const focusedTaskNo = computed(() => resolveFocusedTask(uiState, {
|
||||
recentTaskNo: activeProjection.value?.recent_task_no,
|
||||
}));
|
||||
|
||||
/** 按权威 OT 编号取得卡片自己的统一进度投影。 */
|
||||
function projectionForTask(task: ConversationProcessingUserTask): ShippingProcessingProjection | null {
|
||||
const taskNo = String(task.user_task_no || '').trim();
|
||||
if (!taskNo) return null;
|
||||
const items = Array.isArray(props.workItems) ? props.workItems : [];
|
||||
return items.find((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
&& String(item.workItemNo || '').trim() === taskNo
|
||||
)) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切会话时重置本地焦点/展开,避免跨会话残留。
|
||||
*/
|
||||
@@ -129,6 +145,28 @@ function isMultiDocumentTask(task: ConversationProcessingUserTask): boolean {
|
||||
return Array.isArray(task.document_names) && task.document_names.length > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否展示「展开文件详情」:单 PDF/单对象时隐藏,避免空抽屉。
|
||||
*/
|
||||
function canExpandFileDetails(task: ConversationProcessingUserTask): boolean {
|
||||
if (isMultiDocumentTask(task)) return true;
|
||||
const objects = Array.isArray(task.objects) ? task.objects : [];
|
||||
return objects.length > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* UI-05:仅聚焦且非已完成卡展开完整进度;未聚焦显示紧凑单行;已完成默认不展进度。
|
||||
*/
|
||||
function progressModeForTask(task: ConversationProcessingUserTask): 'full' | 'compact' | 'hidden' {
|
||||
if (!projectionForTask(task)) return 'hidden';
|
||||
const focused = focusedTaskNo.value === task.user_task_no;
|
||||
const completed = String(task.group || '').trim() === 'completed'
|
||||
|| String(task.status_label || '').trim().toLowerCase() === 'completed';
|
||||
if (completed && !focused) return 'hidden';
|
||||
if (focused) return 'full';
|
||||
return 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务主标题:单 PDF 用文件名;多 PDF 用 i18n「订单识别任务」;禁止 OT/Run 编号。
|
||||
*/
|
||||
@@ -500,8 +538,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length"
|
||||
v-if="visibleTaskActions(task).length && !projectionForTask(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
@@ -517,6 +562,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
@click="onToggleDetails(task)"
|
||||
@@ -582,8 +628,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length"
|
||||
v-if="visibleTaskActions(task).length && !projectionForTask(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
@@ -599,6 +652,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
@click="onToggleDetails(task)"
|
||||
@@ -652,8 +706,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
{{ documentNamesPreview(task) }}
|
||||
</div>
|
||||
</button>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length"
|
||||
v-if="visibleTaskActions(task).length && !projectionForTask(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
@@ -669,6 +730,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
@click="onToggleDetails(task)"
|
||||
|
||||
+148
-1
@@ -6,10 +6,13 @@
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ref } from 'vue';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -52,6 +55,7 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
it('renders batch summary, current stage, health tip and action buttons', () => {
|
||||
// 冷启动 transform 较慢时放宽超时,避免首测误伤。
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-1' },
|
||||
global: { plugins: [i18n] },
|
||||
@@ -62,7 +66,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('刷新状态');
|
||||
expect(wrapper.text()).toContain('取消本次识别');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-document-result"]').length).toBe(0);
|
||||
});
|
||||
}, 30_000);
|
||||
|
||||
it('renders duplicate-linked notice when only open_existing results remain', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
@@ -185,6 +189,149 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('影响对象:');
|
||||
expect(wrapper.text()).toContain('ST-88');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(3);
|
||||
// 无统一投影时仍允许 handlingItems 主按钮(过渡兜底)。
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('hides handling primary actions when unified processing projection is present (UI-01)', () => {
|
||||
const projection = {
|
||||
workItemType: 'order_task' as const,
|
||||
workItemNo: 'OT-UI01',
|
||||
sourceType: 'direct_pdf' as const,
|
||||
rootOrderTaskNo: 'OT-UI01',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: null,
|
||||
submissionNo: 'SUB-1',
|
||||
intakeNo: 'INT-1',
|
||||
status: 'waiting_review' as const,
|
||||
stage: 'waiting_review' as const,
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
stageNodes: [],
|
||||
currentGate: null,
|
||||
availableActions: ['open_order_review'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'PO.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
};
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'review_required',
|
||||
userTaskNo: 'OT-UI01',
|
||||
availableActions: ['review_candidate', 'view_details'],
|
||||
primaryNotice: 'candidate_confirmation',
|
||||
handlingItems: [
|
||||
{
|
||||
category: 'candidate_confirmation',
|
||||
count: 1,
|
||||
reasonCodes: [],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'review_candidate',
|
||||
},
|
||||
{
|
||||
category: 'parse_failed',
|
||||
count: 1,
|
||||
reasonCodes: ['layout_failed'],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'retry_failed_documents',
|
||||
},
|
||||
],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
}),
|
||||
runNo: 'SNER-UI01',
|
||||
processingProjection: projection,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
ChatProgressSummary: true,
|
||||
ProcessGateRecoveryCard: true,
|
||||
'router-link': true,
|
||||
},
|
||||
},
|
||||
});
|
||||
// 主操作只来自投影 Presenter;已被 Gate/进度表达的 handling 项不重复列出。
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBe(0);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(1);
|
||||
});
|
||||
|
||||
it('renders one unified progress summary for each PDF under the same root task', () => {
|
||||
const buildWorkItem = (
|
||||
taskNo: string,
|
||||
filename: string,
|
||||
documentId: number,
|
||||
): ShippingProcessingProjection => ({
|
||||
workItemType: 'order_task',
|
||||
workItemNo: taskNo,
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-1',
|
||||
intakeNo: 'INT-1',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['view_details'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename,
|
||||
documentId,
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
});
|
||||
const workItems = [
|
||||
buildWorkItem('OT-ROOT', 'PO-001.pdf', 1),
|
||||
buildWorkItem('OT-CHILD', 'PO-002.pdf', 2),
|
||||
];
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({ userTaskNo: 'OT-ROOT' }),
|
||||
runNo: 'SNER-MULTI-PDF',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
provide: {
|
||||
[SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref(workItems),
|
||||
loading: ref(false),
|
||||
error: ref(null),
|
||||
refresh: async () => undefined,
|
||||
focusConversationTask: async () => undefined,
|
||||
markConversationTaskViewed: async () => undefined,
|
||||
stop: () => undefined,
|
||||
},
|
||||
},
|
||||
stubs: {
|
||||
ChatProgressSummary: {
|
||||
props: ['projection'],
|
||||
template: '<div data-testid="chat-progress-summary">{{ projection.workItemNo }}</div>',
|
||||
},
|
||||
ProcessGateRecoveryCard: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.findAll('[data-testid="chat-progress-summary"]')).toHaveLength(2);
|
||||
expect(wrapper.text()).toContain('PO-001.pdf');
|
||||
expect(wrapper.text()).toContain('PO-002.pdf');
|
||||
});
|
||||
|
||||
it('emits cancel after confirmation', async () => {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
|
||||
* 用途:聊天主区批次进度卡——摘要计数、Run 级诊断事项、当前文件阶段、健康提醒与动作。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、
|
||||
* orderExtractionProgressDisplay、vue-router、vue-i18n、ProcessGateRecoveryCard。
|
||||
* 逻辑:回退 handling_items / primary_notice / Run summary;
|
||||
* Run 失败优先展示 errorExplainability.message;详情抽屉证据入口携带 focus+document_id;
|
||||
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗;不再读取 Workflow 空壳 counts。
|
||||
* orderExtractionProgressDisplay、vue-router、vue-i18n、ChatProgressSummary;
|
||||
* ProcessGateRecoveryCard 仅兼容保留(runLevelProcessGate 当前恒为空)。
|
||||
* 逻辑:有统一投影时按当前 Run 根 OT 展示全部 PDF/OT 紧凑进度,主操作仅来自投影;
|
||||
* handlingItems 保留诊断信息,不再渲染与投影平级的 primaryAction 主按钮;
|
||||
* Run 失败优先展示 errorExplainability.message;详情抽屉证据入口携带 focus+document_id。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, ref } from 'vue';
|
||||
@@ -23,6 +24,12 @@ import type {
|
||||
ShippingProcessGateUserSummary,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
import ChatProgressSummary from '@/features/shipping-progress/components/ChatProgressSummary.vue';
|
||||
import {
|
||||
SHIPPING_WORKFLOW_KEY,
|
||||
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
|
||||
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
|
||||
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
import {
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents,
|
||||
@@ -47,6 +54,8 @@ const props = defineProps<{
|
||||
/** 新版 Run 已替代旧版时,历史卡仅允许查看详情。 */
|
||||
readonly?: boolean;
|
||||
readonlyReason?: string | null;
|
||||
/** 可选统一投影;缺省时从 SHIPPING_WORKFLOW_KEY 解析。 */
|
||||
processingProjection?: ShippingProcessingProjection | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -59,6 +68,54 @@ const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const chatPage = inject(CHAT_PAGE_KEY, null);
|
||||
const shippingWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
|
||||
|
||||
/**
|
||||
* 解析当前 Run/任务对应的全部统一 ShippingProcessing 投影。
|
||||
* 核心逻辑:显式 prop 优先;根 OT 同时匹配自身与 rootOrderTaskNo 相同的兄弟 OT;
|
||||
* Candidate 前回退本会话 order_intake,禁止用 find() 丢失同 Run 的其他 PDF。
|
||||
*/
|
||||
const resolvedProcessingProjections = computed((): ShippingProcessingProjection[] => {
|
||||
if (props.processingProjection) return [props.processingProjection];
|
||||
const items = shippingWorkflow?.processingWorkItems?.value || [];
|
||||
if (!items.length) return [];
|
||||
const taskNo = String(props.state.userTaskNo || '').trim();
|
||||
if (taskNo) {
|
||||
const matched = items.filter((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
&& (
|
||||
String(item.workItemNo || '').trim() === taskNo
|
||||
|| String(item.rootOrderTaskNo || '').trim() === taskNo
|
||||
)
|
||||
));
|
||||
if (matched.length) return matched;
|
||||
}
|
||||
return items.filter((item) => item.workItemType === 'order_intake');
|
||||
});
|
||||
|
||||
const hasProcessingProjection = computed(() => resolvedProcessingProjections.value.length > 0);
|
||||
|
||||
/** 进度行标题优先使用 PDF 文件名,其次使用 PO,最后使用工作项号。 */
|
||||
function processingProjectionTitle(item: ShippingProcessingProjection): string {
|
||||
return String(
|
||||
item.sourceSummary?.filename
|
||||
|| item.sourceSummary?.poNumber
|
||||
|| item.workItemNo,
|
||||
).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一进度摘要动作:刷新 / 进入复核等由宿主路由承接。
|
||||
*/
|
||||
function onChatProgressAction(item: ActionPresentationItem) {
|
||||
if (item.intent === 'refresh') {
|
||||
emit('refresh');
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_order_review') {
|
||||
void openOrderReview();
|
||||
}
|
||||
}
|
||||
const confirmCancelOpen = ref(false);
|
||||
const cancelReason = ref('');
|
||||
|
||||
@@ -92,7 +149,21 @@ const displaySummary = computed(() => props.state.summary);
|
||||
const workflowStageLabel = computed(() => '');
|
||||
const workflowLastActivityLabel = computed(() => '');
|
||||
|
||||
const handlingItems = computed(() => props.state.handlingItems || []);
|
||||
const handlingItems = computed(() => {
|
||||
const items = props.state.handlingItems || [];
|
||||
// [UI-04] 有 OT 统一投影时,隐藏已被 Gate/进度表达的复核类事项,仅保留未归属异常。
|
||||
if (!hasProcessingProjection.value) return items;
|
||||
const covered = new Set([
|
||||
'manual_review',
|
||||
'field_conflict',
|
||||
'customer_confirmation',
|
||||
'candidate_confirmation',
|
||||
'duplicate_check',
|
||||
'inventory_source',
|
||||
'review_required',
|
||||
]);
|
||||
return items.filter((item) => !covered.has(String(item.category || '').trim()));
|
||||
});
|
||||
|
||||
/**
|
||||
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
|
||||
@@ -528,7 +599,7 @@ function openCancelConfirm() {
|
||||
</div>
|
||||
|
||||
<ProcessGateRecoveryCard
|
||||
v-if="runLevelProcessGate?.current_blocking_gate"
|
||||
v-if="runLevelProcessGate?.current_blocking_gate && !hasProcessingProjection"
|
||||
class="mt-2"
|
||||
:summary="runLevelProcessGate"
|
||||
:can-handle="!readonly"
|
||||
@@ -538,6 +609,25 @@ function openCancelConfirm() {
|
||||
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="hasProcessingProjection"
|
||||
class="mt-2 space-y-2"
|
||||
data-testid="chat-progress-summary-list"
|
||||
>
|
||||
<div
|
||||
v-for="projection in resolvedProcessingProjections"
|
||||
:key="projection.workItemNo"
|
||||
>
|
||||
<div class="truncate text-[11px] font-semibold opacity-90">
|
||||
{{ processingProjectionTitle(projection) }}
|
||||
</div>
|
||||
<ChatProgressSummary
|
||||
:projection="projection"
|
||||
@action="onChatProgressAction"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="handlingItems.length"
|
||||
class="mt-2 space-y-1.5"
|
||||
@@ -558,9 +648,10 @@ function openCancelConfirm() {
|
||||
<span class="ml-1 opacity-80">{{ t('chat.shippingOrderExtractionHandling.count', { count: item.count }) }}</span>
|
||||
</div>
|
||||
<button
|
||||
v-if="item.primaryAction && !readonly && (item.primaryAction !== 'review_candidate' || !handlingItems.some((other) => other.primaryAction === 'enter_manual_review'))"
|
||||
v-if="item.primaryAction && !readonly && !hasProcessingProjection && (item.primaryAction !== 'review_candidate' || !handlingItems.some((other) => other.primaryAction === 'enter_manual_review'))"
|
||||
type="button"
|
||||
class="shrink-0 rounded-md border border-current/20 px-2 py-0.5 text-[11px] font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
data-testid="shipping-order-extraction-handling-primary-action"
|
||||
@click="handleHandlingAction(item)"
|
||||
>
|
||||
{{ (item.primaryAction === 'review_candidate' || item.primaryAction === 'enter_manual_review')
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 用途:聊天页右侧「本次处理中」面板——OT 任务卡 + 按需展开的文件明细。
|
||||
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
|
||||
* conversationProcessingProjection、DetailDrawer、ReasonDialog、ProcessGateRecoveryCard。
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;展开任务后由
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;每张 OT 卡内展示自己的紧凑进度与动作;
|
||||
* mapUserTaskObjectsToFileRows 合成文件行;取消/重识别走 Run API;
|
||||
* 路由 focus_task_no / 服务端 focused_task_no 驱动选中卡与当前阶段摘要;
|
||||
* 详情抽屉仅用列表投影,不再请求 WorkflowItem 详情 API。
|
||||
@@ -43,6 +43,7 @@ import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer
|
||||
import ShippingWorkflowReasonDialog, {
|
||||
type ShippingWorkflowReasonAction,
|
||||
} from './ShippingWorkflowReasonDialog.vue';
|
||||
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
const props = defineProps<{
|
||||
conversationId?: string | null;
|
||||
@@ -261,12 +262,15 @@ function itemActivityLabel(item: ShippingWorkflowItem | null): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开当前 PDF 对应的人工复核工作台(fileItems 行)。
|
||||
* 打开当前 PDF 对应的订单处理工作台(fileItems 行)。
|
||||
* 核心逻辑:复用 Run/Case/文档上下文,避免用户重新寻找待处理文件。
|
||||
*/
|
||||
async function openReview(item: ShippingWorkflowItem) {
|
||||
const runNo = String(item.current_run_no || '').trim();
|
||||
if (!runNo) return;
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingOrderReview.caseRequired'));
|
||||
return;
|
||||
}
|
||||
await pushOrderReviewQuery({
|
||||
runNo,
|
||||
documentId: item.current_document_id,
|
||||
@@ -276,11 +280,15 @@ async function openReview(item: ShippingWorkflowItem) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 OT 任务投影打开复核(无 fileItems 时的生产路径)。
|
||||
* 从 OT 任务投影打开订单处理工作台(无 fileItems 时的生产路径)。
|
||||
* 核心逻辑:必须有 run_no;缺失时 toast 提示,禁止静默 return。
|
||||
*/
|
||||
async function openReviewFromTask(task: ConversationProcessingUserTask) {
|
||||
const runNo = String(task.run_no || '').trim();
|
||||
if (!runNo) return;
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingOrderReview.caseRequired'));
|
||||
return;
|
||||
}
|
||||
const doc = (task.objects || []).find((row) => row.kind === 'document');
|
||||
const caseObj = (task.objects || []).find((row) => String(row.case_no || '').trim());
|
||||
await pushOrderReviewQuery({
|
||||
@@ -745,6 +753,46 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个 OT 卡的统一动作点击:复用 Timeline 已有任务处理器。
|
||||
* @param payload.projection - 当前卡片自己的权威投影
|
||||
* @param payload.item - 动作展示项
|
||||
*/
|
||||
function onTaskProjectionAction(payload: {
|
||||
projection: ShippingProcessingProjection;
|
||||
item: ActionPresentationItem;
|
||||
}) {
|
||||
const { projection, item } = payload;
|
||||
const taskNo = String(projection.workItemNo || '').trim();
|
||||
const code = String(item.actionCode || '').trim();
|
||||
if (code === 'retry_parse' || item.intent === 'retry') {
|
||||
void onProcessingIntakeAction({ item: projection, action: code || 'retry_parse' });
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'refresh') {
|
||||
void onRefresh();
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_order_review') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
...(displayProcessing.value?.completed || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
void onProcessingTaskAction({ task, action: 'open_review' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_manual_upload' && taskNo) {
|
||||
void router.push({
|
||||
name: 'workspace-shipping-my-tasks',
|
||||
query: { task_no: taskNo },
|
||||
});
|
||||
}
|
||||
// 其余 intent 由任务卡/ Gate 卡片承载,此处安全 no-op。
|
||||
}
|
||||
|
||||
watch(
|
||||
() => error.value,
|
||||
() => {
|
||||
@@ -812,7 +860,10 @@ watch(
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-0.5 text-xs text-secondary" data-testid="shipping-workflow-panel-summary">
|
||||
<template v-if="displayProcessing">
|
||||
<template v-if="loading && !displayProcessing">
|
||||
{{ t('chat.shippingProcessing.loading') }}
|
||||
</template>
|
||||
<template v-else-if="displayProcessing">
|
||||
{{ t('chat.shippingProcessing.summaryLine', {
|
||||
total: displayProcessing.summary.total_files
|
||||
|| displayProcessing.summary.total_tasks,
|
||||
@@ -867,6 +918,7 @@ watch(
|
||||
@collapse-files="onCollapseTaskFiles"
|
||||
@task-action="(payload) => void onProcessingTaskAction(payload)"
|
||||
@intake-action="(payload) => void onProcessingIntakeAction(payload)"
|
||||
@projection-action="onTaskProjectionAction"
|
||||
/>
|
||||
|
||||
<section
|
||||
|
||||
@@ -13,23 +13,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
|
||||
import {
|
||||
|
||||
isBuildConfirmBlocked,
|
||||
|
||||
isDraftVersionMismatchError,
|
||||
|
||||
isReviewCaseHistorical,
|
||||
|
||||
isReviewReadOnly,
|
||||
|
||||
isReviewWorkItemClosed,
|
||||
|
||||
lineNeedsManualInventorySelection,
|
||||
|
||||
lineHasPendingRoutingSuggestion,
|
||||
|
||||
lineNeedsInventoryRoutingRecovery,
|
||||
|
||||
mapReviewContextLifecycleStatus,
|
||||
REVIEW_BUILD_ELIGIBILITY_BLOCKED,
|
||||
|
||||
REVIEW_DRAFT_VERSION_MISMATCH,
|
||||
@@ -231,6 +223,14 @@ describe('useShippingOrderReview historical readonly', () => {
|
||||
)).toBe(true);
|
||||
});
|
||||
|
||||
it('maps confirmed case to non-closed lifecycle for post-confirm automation', () => {
|
||||
// 关键断言:confirmed 不得映射 closed,否则统一进度轨道会被误判为终态。
|
||||
expect(mapReviewContextLifecycleStatus('confirmed', null)).toBe('building_order');
|
||||
expect(mapReviewContextLifecycleStatus('confirmed', 'inventory_matching')).toBe('inventory_matching');
|
||||
expect(mapReviewContextLifecycleStatus('closed', null)).toBe('closed');
|
||||
expect(mapReviewContextLifecycleStatus('quality_issue', null)).toBe('closed');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
/**
|
||||
* features/chat/shipping-review/useShippingOrderReview.ts
|
||||
* ?????????? Run??? PDF Case ?????????ShippingReviewProgressContext??
|
||||
* ???shipping API review / extraction-run?useShippingProcessingWorkItem?Vue ????BusinessError?
|
||||
* ????????? runNo ????????????????? Workflow ????
|
||||
* Case.order_task_no / Candidate ??? OT ?????????? Run ? OT ? Notice ???
|
||||
* ?? REVIEW_DRAFT_VERSION_MISMATCH ???????????????
|
||||
* build_eligibility ???????????????????????reroute / adopt / keep??
|
||||
* ????? ShippingProcessing ???????? OT ??? extraction-run ???
|
||||
* ???? extraction-run ??????????? Review Run/Case?
|
||||
* ???????? Workflow ?????????????????????
|
||||
* ?????????/?/?/evidence_id?????? evidence ??????????????
|
||||
* PDF Blob ?? ensurePreviewLoaded ??????load/selectCase ??????
|
||||
* ????????? composable??Run/Case/PDF ??????????
|
||||
* ???shipping API review/extraction-run?useShippingProcessingWorkItem?Vue ref/computed?BusinessError?
|
||||
* ???? runNo ?? Review Run/Case??? ShippingReviewProgressContext?
|
||||
* ?? OT ?? Case.order_task_no / Candidate ????? ShippingProcessing ???
|
||||
* 409 REVIEW_DRAFT_VERSION_MISMATCH ???????build_eligibility ???? reroute/adopt/keep?
|
||||
* ???? extraction-run?draft_ready ? reload?PDF Blob ? ensurePreviewLoaded ????
|
||||
*/
|
||||
import { computed, getCurrentInstance, onBeforeUnmount, ref } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
@@ -69,13 +64,13 @@ export type ReviewStatusMessage =
|
||||
| 'draft_version_conflict'
|
||||
| null;
|
||||
|
||||
/** ???????????????? ConflictError.code ???? */
|
||||
/** ????????? ConflictError.code???????? */
|
||||
export const REVIEW_DRAFT_VERSION_MISMATCH = 'SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH';
|
||||
|
||||
/** ???????? confirm ?????? */
|
||||
/** ?????????? confirm ????? */
|
||||
export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED';
|
||||
|
||||
/** ???????????????????????? */
|
||||
/** ????????????????????????? */
|
||||
const INVENTORY_BLOCK_REASONS = new Set([
|
||||
'require_manual_review',
|
||||
'no_inventory_source_candidates',
|
||||
@@ -84,7 +79,7 @@ const INVENTORY_BLOCK_REASONS = new Set([
|
||||
'inventory_source_unresolved',
|
||||
]);
|
||||
|
||||
/** ???????????????????????????? Case??????? */
|
||||
/** ????????????/??????????? Case ??? */
|
||||
export type DraftVersionConflict = {
|
||||
localVersion: number;
|
||||
serverVersion: number | null;
|
||||
@@ -93,7 +88,7 @@ export type DraftVersionConflict = {
|
||||
};
|
||||
|
||||
/**
|
||||
* ??????????????????
|
||||
* ??????????????409 REVIEW_DRAFT_VERSION_MISMATCH??
|
||||
* @param error - ???????
|
||||
*/
|
||||
export function isDraftVersionMismatchError(error: unknown): boolean {
|
||||
@@ -143,7 +138,7 @@ type WorkItemRef = {
|
||||
} | null | undefined;
|
||||
|
||||
/**
|
||||
* ???? Case ?????/????????????
|
||||
* ???? Case ????????superseded ?? WorkItem ?? Case ?????
|
||||
*/
|
||||
export function isReviewCaseHistorical(activeCase: ReviewCaseRef, workItem: WorkItemRef): boolean {
|
||||
const caseNo = String(activeCase?.case_no || '');
|
||||
@@ -154,8 +149,8 @@ export function isReviewCaseHistorical(activeCase: ReviewCaseRef, workItem: Work
|
||||
}
|
||||
|
||||
/**
|
||||
* ???????????????/??????
|
||||
* ?????manual_upload_pending / upload_rpa_* ???????????????
|
||||
* ?? WorkItem ??????? closed/cancelled??
|
||||
* ?????confirmed / building_order ???? lifecycle ???????
|
||||
*/
|
||||
export function isReviewWorkItemClosed(workItem: WorkItemRef): boolean {
|
||||
const status = String(workItem?.lifecycle_status || '').trim();
|
||||
@@ -163,7 +158,7 @@ export function isReviewWorkItemClosed(workItem: WorkItemRef): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* ???????????????????????
|
||||
* ?????????? Case ? WorkItem ????
|
||||
*/
|
||||
export function isReviewReadOnly(activeCase: ReviewCaseRef, workItem: WorkItemRef): boolean {
|
||||
return isReviewCaseHistorical(activeCase, workItem) || isReviewWorkItemClosed(workItem);
|
||||
@@ -214,14 +209,16 @@ export function lineNeedsInventoryRoutingRecovery(
|
||||
}
|
||||
|
||||
/**
|
||||
* ? Case / Extraction Run ??????? WorkflowItem ? lifecycle_status?
|
||||
* ?????draft/ready ? pending_review?non_order ? cancelled???? Run ??????? lifecycle?
|
||||
* ? Case / Extraction Run ????? WorkflowItem lifecycle_status?
|
||||
* ?????draft/ready ? pending_review?non_order ? cancelled?
|
||||
* confirmed ???? closed?????? building_order ???
|
||||
* ??? closed / quality_issue ? closed?Extraction Run ????? Case ????
|
||||
*
|
||||
* @param caseStatus - Review Case ??
|
||||
* @param runStatus - Extraction Run ??????
|
||||
* @returns ?? WorkflowItem ?????????
|
||||
* @returns ??????? lifecycle ???
|
||||
*/
|
||||
function mapReviewContextLifecycleStatus(
|
||||
export function mapReviewContextLifecycleStatus(
|
||||
caseStatus?: string | null,
|
||||
runStatus?: string | null,
|
||||
): ShippingWorkflowItemLifecycleStatus {
|
||||
@@ -230,7 +227,13 @@ function mapReviewContextLifecycleStatus(
|
||||
|
||||
if (cs === 'non_order') return 'cancelled';
|
||||
if (cs === 'quality_issue') return 'closed';
|
||||
if (['confirmed', 'closed'].includes(cs)) return 'closed';
|
||||
if (cs === 'closed') return 'closed';
|
||||
// [UI-05] confirmed ? closed????????????????????
|
||||
if (cs === 'confirmed') {
|
||||
if (['building_order', 'inventory_matching', 'generating_excel'].includes(rs)) return rs;
|
||||
if (['manual_upload_pending', 'upload_rpa_pending', 'upload_rpa_running'].includes(rs)) return rs;
|
||||
return 'building_order';
|
||||
}
|
||||
if (cs === 'reparse_pending') return 'extracting';
|
||||
if (['failed', 'cancelled'].includes(rs)) return rs;
|
||||
if (rs === 'reparse_failed') return 'reparse_failed';
|
||||
|
||||
@@ -481,6 +481,8 @@ describe('conversationProcessingProjection', () => {
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: 'OT-WAIT',
|
||||
shippingNoticeNo: null,
|
||||
runNo: 'RUN-WAIT',
|
||||
caseNo: 'CASE-WAIT',
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-2',
|
||||
@@ -545,6 +547,53 @@ describe('conversationProcessingProjection', () => {
|
||||
expect(projection!.processing.map((t) => t.user_task_no)).toEqual(['OT-RUN']);
|
||||
expect(projection!.needs_action[0]?.file_count).toBe(2);
|
||||
expect(projection!.needs_action[0]?.display_kind).toBe('multi_document_task');
|
||||
// [P0] 合成任务必须透传 run_no,禁止写死 null。
|
||||
expect(projection!.needs_action[0]?.run_no).toBe('RUN-WAIT');
|
||||
});
|
||||
|
||||
it('deduplicates conversation total_files by authoritative PDF id', () => {
|
||||
const base = {
|
||||
sourceType: 'direct_pdf' as const,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'waiting_review' as const,
|
||||
stage: 'waiting_review' as const,
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['open_order_review'],
|
||||
childOrderTasks: [],
|
||||
};
|
||||
const workItems: ShippingProcessingProjection[] = [
|
||||
{
|
||||
...base,
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-A',
|
||||
rootOrderTaskNo: 'OT-A',
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'a.pdf', documentId: 17,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-A',
|
||||
},
|
||||
},
|
||||
{
|
||||
...base,
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-B',
|
||||
rootOrderTaskNo: 'OT-A',
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'a.pdf', documentId: 17,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-B',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const projection = projectConversationProcessingFromWorkItems(workItems);
|
||||
// 异常重复绑定同一主 PDF 时,顶部必须仍显示 1 个文件。
|
||||
expect(projection?.summary.total_files).toBe(1);
|
||||
});
|
||||
|
||||
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
|
||||
|
||||
@@ -529,10 +529,9 @@ export function groupConversationProcessingTasks(
|
||||
const completed = tasks.filter((t) => t.group === 'completed');
|
||||
const history = tasks.filter((t) => t.group === 'history');
|
||||
const active = [...needs_action, ...processing, ...completed];
|
||||
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
|
||||
const summary: ConversationProcessingSummary = {
|
||||
total_tasks: needs_action.length + processing.length + completed.length,
|
||||
total_files: totalFiles,
|
||||
total_files: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
|
||||
processing: processing.length,
|
||||
needs_action: needs_action.length,
|
||||
completed: completed.length,
|
||||
@@ -661,7 +660,8 @@ export function projectConversationProcessingFromWorkItems(
|
||||
group,
|
||||
status_label: String(item.status || '') || null,
|
||||
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
|
||||
run_no: null,
|
||||
// [P0] 消费后端投影 run_no,禁止写死 null 导致「进入订单处理」静默失败。
|
||||
run_no: String(item.runNo || '').trim() || null,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: Array.isArray(item.availableActions) ? [...item.availableActions] : [],
|
||||
@@ -675,7 +675,15 @@ export function projectConversationProcessingFromWorkItems(
|
||||
|
||||
const active = [...needs_action, ...processing, ...completed];
|
||||
if (!active.length && !history.length) return null;
|
||||
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
|
||||
// 后端未返回 embedded 汇总时,仍按 OT 主 PDF ID 去重,禁止兄弟 OT 重复累计。
|
||||
const documentIds = new Set(
|
||||
orderTasks
|
||||
.map((item) => Number(item.sourceSummary?.documentId || 0))
|
||||
.filter((id) => id > 0),
|
||||
);
|
||||
const totalFiles = documentIds.size > 0
|
||||
? documentIds.size
|
||||
: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
|
||||
return {
|
||||
summary: {
|
||||
total_tasks: active.length,
|
||||
|
||||
@@ -35,6 +35,7 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
source_summary: {
|
||||
email_subject: null,
|
||||
filename: 'a.pdf',
|
||||
document_id: 17,
|
||||
document_count: 1,
|
||||
parsed_document_count: 1,
|
||||
candidate_count: 1,
|
||||
@@ -53,10 +54,27 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized!.currentGate?.gateCode).toBe('field_conflict_resolution');
|
||||
expect(normalized!.currentGate?.attemptNo).toBe(1);
|
||||
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
|
||||
expect(normalized!.sourceSummary.documentId).toBe(17);
|
||||
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
|
||||
expect(normalized!.availableActions).toEqual(['open_review']);
|
||||
});
|
||||
|
||||
it('normalizes stage_nodes from backend', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-2',
|
||||
work_item_type: 'order_task',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
stage_nodes: [
|
||||
{ stage: 'upload_received', absolute_index: 0, status: 'passed' },
|
||||
{ stage: 'document_parsing', absolute_index: 2, status: 'running' },
|
||||
],
|
||||
});
|
||||
expect(normalized?.stageNodes).toHaveLength(2);
|
||||
expect(normalized?.stageNodes?.[1]?.status).toBe('running');
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('returns null when work_item_no missing', () => {
|
||||
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -11,6 +11,8 @@ import type {
|
||||
ShippingOrderTaskSummary,
|
||||
ShippingProcessingProjection,
|
||||
ShippingProcessingStage,
|
||||
ShippingProcessingStageNode,
|
||||
ShippingProcessingStageNodeStatus,
|
||||
ShippingProcessingStatus,
|
||||
ShippingProcessingWorkItemType,
|
||||
} from '../types/shipping.api.types';
|
||||
@@ -76,6 +78,26 @@ function normalizeGate(raw: unknown): ProcessGateSummary | null {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范单个 stage_node(兼容 snake / camel)。
|
||||
*/
|
||||
function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const stage = readString(item, 'stage', 'stage') as ShippingProcessingStage;
|
||||
if (!stage) return null;
|
||||
const absoluteIndexRaw = item.absolute_index ?? item.absoluteIndex;
|
||||
const absoluteIndex = Number.isFinite(Number(absoluteIndexRaw))
|
||||
? Number(absoluteIndexRaw)
|
||||
: 0;
|
||||
const status = readString(item, 'status', 'status') as ShippingProcessingStageNodeStatus;
|
||||
return {
|
||||
stage,
|
||||
absoluteIndex,
|
||||
status: status || 'pending',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
|
||||
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
|
||||
@@ -100,6 +122,10 @@ export function normalizeShippingProcessingProjection(
|
||||
const availableActions = Array.isArray(actionsRaw)
|
||||
? actionsRaw.map((action) => String(action || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
const stageNodesRaw = item.stage_nodes ?? item.stageNodes;
|
||||
const stageNodes = Array.isArray(stageNodesRaw)
|
||||
? stageNodesRaw.map(normalizeStageNode).filter((row): row is ShippingProcessingStageNode => Boolean(row))
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
|
||||
@@ -107,6 +133,8 @@ export function normalizeShippingProcessingProjection(
|
||||
sourceType: (readNullableString(item, 'source_type', 'sourceType') || 'eml') as OrderIntakeSourceType,
|
||||
rootOrderTaskNo: readNullableString(item, 'root_order_task_no', 'rootOrderTaskNo'),
|
||||
shippingNoticeNo: readNullableString(item, 'shipping_notice_no', 'shippingNoticeNo'),
|
||||
runNo: readNullableString(item, 'run_no', 'runNo'),
|
||||
caseNo: readNullableString(item, 'case_no', 'caseNo'),
|
||||
conversationId: readNullableString(item, 'conversation_id', 'conversationId'),
|
||||
submissionNo: readString(item, 'submission_no', 'submissionNo'),
|
||||
intakeNo: readString(item, 'intake_no', 'intakeNo'),
|
||||
@@ -114,11 +142,13 @@ export function normalizeShippingProcessingProjection(
|
||||
stage: (readString(item, 'stage', 'stage') || 'upload_received') as ShippingProcessingStage,
|
||||
progressVersion: Number(item.progress_version ?? item.progressVersion ?? 0) || 0,
|
||||
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
|
||||
stageNodes: stageNodes?.length ? stageNodes : undefined,
|
||||
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
|
||||
availableActions,
|
||||
sourceSummary: {
|
||||
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
|
||||
filename: readNullableString(summaryRaw, 'filename', 'filename'),
|
||||
documentId: Number(summaryRaw.document_id ?? summaryRaw.documentId ?? 0) || null,
|
||||
documentCount: Number(summaryRaw.document_count ?? summaryRaw.documentCount ?? 0) || 0,
|
||||
parsedDocumentCount: Number(summaryRaw.parsed_document_count ?? summaryRaw.parsedDocumentCount ?? 0) || 0,
|
||||
candidateCount: Number(summaryRaw.candidate_count ?? summaryRaw.candidateCount ?? 0) || 0,
|
||||
|
||||
@@ -17,6 +17,7 @@ const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
|
||||
cancelling: 'processing',
|
||||
blocked: 'blocked',
|
||||
automating: 'automating',
|
||||
review_case_draft: 'waiting_review',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -139,6 +139,22 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('coalesces concurrent refreshes for the same conversation', async () => {
|
||||
const pending = deferred<ReturnType<typeof buildUnifiedProcessing>>();
|
||||
api.getShippingProcessing.mockImplementation(() => pending.promise);
|
||||
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
const manualRefresh = ctl.refresh();
|
||||
await nextTick();
|
||||
|
||||
// 首轮恢复、页面刷新和可见性触发命中同一会话时只能产生一个网络请求。
|
||||
expect(api.getShippingProcessing).toHaveBeenCalledTimes(1);
|
||||
pending.resolve(buildUnifiedProcessing());
|
||||
await manualRefresh;
|
||||
expect(ctl.processing.value?.summary.needs_action).toBe(1);
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('records recoverable error without throwing', async () => {
|
||||
const conversationId = ref('conv-1');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
|
||||
@@ -116,6 +116,7 @@ export function useShippingNoticeWorkflow(
|
||||
let pollGeneration = 0;
|
||||
let requestController: AbortController | null = null;
|
||||
let requestGeneration = 0;
|
||||
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
|
||||
let failureCount = 0;
|
||||
let pollingStopped = false;
|
||||
|
||||
@@ -151,17 +152,10 @@ export function useShippingNoticeWorkflow(
|
||||
/**
|
||||
* 仅拉取统一 shipping-processing 投影。
|
||||
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
|
||||
* 新请求会中止旧请求,且只有最新一代请求可回写 loading / error / 会话数据。
|
||||
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据。
|
||||
* @returns Promise<void>;可恢复网络失败写入 error,不向页面抛出。
|
||||
*/
|
||||
async function refresh(): Promise<void> {
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (!conversationId) {
|
||||
processing.value = null;
|
||||
processingWorkItems.value = [];
|
||||
error.value = null;
|
||||
return;
|
||||
}
|
||||
async function executeRefresh(conversationId: string): Promise<void> {
|
||||
const generation = ++requestGeneration;
|
||||
loading.value = true;
|
||||
const controller = createRequestController();
|
||||
@@ -196,6 +190,27 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取统一进度;同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
|
||||
*/
|
||||
function refresh(): Promise<void> {
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (!conversationId) {
|
||||
processing.value = null;
|
||||
processingWorkItems.value = [];
|
||||
error.value = null;
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (inFlightRefresh?.conversationId === conversationId) {
|
||||
return inFlightRefresh.promise;
|
||||
}
|
||||
const promise = executeRefresh(conversationId).finally(() => {
|
||||
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
|
||||
});
|
||||
inFlightRefresh = { conversationId, promise };
|
||||
return promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
|
||||
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingOrderExtractionRuns.spec.ts
|
||||
* 用途:验证订单抽取 Run 的状态映射、消息幂等持久化与轮询生命周期。
|
||||
* 用途:验证订单抽取 Run 的状态映射、单状态卡消息持久化与轮询生命周期。
|
||||
* 依赖:Vitest、Vue refs、shipping.api mock、useShippingOrderExtractionRuns。
|
||||
* 逻辑:覆盖状态契约、新会话启动、无变化轮询、恢复失败及切会话迟到响应。
|
||||
* 逻辑:覆盖新建/追加提交不生成重复反馈气泡、状态契约、无变化轮询及恢复隔离。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -98,7 +98,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('persists stable user and assistant formIds and does not write unchanged polling state again', async () => {
|
||||
it('persists one user message and one Run state card without duplicate submission feedback', async () => {
|
||||
const queued = run({
|
||||
run_no: 'SNER-START',
|
||||
conversation_id: 'conv-created',
|
||||
@@ -126,14 +126,41 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(harness.options.onConversationResolved).toHaveBeenCalledWith('conv-created');
|
||||
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
|
||||
'shipping-order-extraction-user:SNER-START',
|
||||
'shipping-submission-decision:op-1',
|
||||
'shipping-order-extraction-run:SNER-START',
|
||||
]);
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(3);
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-START', expect.any(AbortSignal));
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(3);
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('keeps an appended submission in the user message and the existing Run state card only', async () => {
|
||||
const queued = run({
|
||||
run_no: 'SNER-APPENDED',
|
||||
conversation_id: 'conv-existing',
|
||||
user_task_no: 'OT-EXISTING',
|
||||
});
|
||||
api.createSubmission.mockResolvedValue({
|
||||
decision: 'appended',
|
||||
user_task_no: 'OT-EXISTING',
|
||||
run_no: 'SNER-APPENDED',
|
||||
created_new: false,
|
||||
operation_id: 'op-appended',
|
||||
});
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-existing';
|
||||
|
||||
await harness.runs.startRun('追加附件', ['SNI-1'], []);
|
||||
|
||||
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
|
||||
'shipping-order-extraction-user:SNER-APPENDED',
|
||||
'shipping-order-extraction-run:SNER-APPENDED',
|
||||
]);
|
||||
expect(harness.messages.value[0]?.payload?.submission_decision).toBe('appended');
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
@@ -177,6 +204,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect.objectContaining({ content: '' }),
|
||||
undefined,
|
||||
);
|
||||
expect(harness.messages.value).toHaveLength(2);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingOrderExtractionRuns.ts
|
||||
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
|
||||
* 依赖:shipping.api 统一提交/Run 接口、shippingSubmissionFeedback、chat.types、Vue refs。
|
||||
* 依赖:shipping.api 统一提交/Run 接口、shippingSubmissionFeedback 标识生成器、chat.types、Vue refs。
|
||||
* 逻辑:发送处理器调用 startRun → createWorkspaceOrderExtractionSubmission(后端裁决 append/create);
|
||||
* 写入用户消息 + 非阻塞决策系统消息后轮询 Run;终态后仍保留 run_no 供状态卡展示。
|
||||
* 写入用户消息 + 唯一 Run 状态卡后轮询;终态后仍保留 run_no 供状态卡展示。
|
||||
* 右侧「本次处理」由 processing / Workflow 投影驱动,本模块在终态/重识别后触发刷新回调。
|
||||
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
|
||||
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
|
||||
@@ -23,7 +23,6 @@ import type { ChatMessage, ChatMessageAttachment, ShippingOrderExtractionReviewA
|
||||
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
|
||||
import type { ShippingNoticeCandidate } from '../types/shipping.types';
|
||||
import {
|
||||
buildShippingSubmissionFeedback,
|
||||
createComposerContextId,
|
||||
createShippingSubmissionId,
|
||||
} from './shippingSubmissionFeedback';
|
||||
@@ -430,7 +429,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
};
|
||||
|
||||
/**
|
||||
* 启动订单抽取统一提交:后端裁决 append/create,并把用户操作与状态卡持久化到本地会话。
|
||||
* 启动订单抽取统一提交:后端裁决 append/create,并只持久化用户操作与唯一 Run 状态卡。
|
||||
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
|
||||
* @param intakeNos - 本次冻结的 Intake 编号。
|
||||
* @param attachments - 用户消息中的安全附件快照。
|
||||
@@ -463,11 +462,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
composerBoundConversationId = run.conversation_id;
|
||||
}
|
||||
|
||||
const feedback = buildShippingSubmissionFeedback(submission, attachments.length);
|
||||
const decisionKey = feedback.decision === 'appended'
|
||||
? 'chat.shippingSubmission.appended'
|
||||
: 'chat.shippingSubmission.created';
|
||||
|
||||
const userMessage: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
@@ -479,29 +473,12 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
formId: `shipping-order-extraction-user:${run.run_no}`,
|
||||
order_extraction_run_no: run.run_no,
|
||||
user_task_no: submission.user_task_no,
|
||||
submission_decision: feedback.decision,
|
||||
submission_decision: submission.decision,
|
||||
},
|
||||
};
|
||||
options.messages.value.push(userMessage);
|
||||
await options.saveLocalMessageToBackend(userMessage, query || undefined);
|
||||
|
||||
// 非阻塞系统反馈:可回看,不弹窗。
|
||||
const systemMessage: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: options.t(decisionKey, { count: feedback.fileCount }),
|
||||
local_id: options.newLocalMessageId('shipping-submission-decision'),
|
||||
local_only: true,
|
||||
payload: {
|
||||
formId: `shipping-submission-decision:${submission.operation_id || submissionId}`,
|
||||
submission_decision: feedback.decision,
|
||||
user_task_no: submission.user_task_no,
|
||||
run_no: submission.run_no,
|
||||
},
|
||||
};
|
||||
options.messages.value.push(systemMessage);
|
||||
await options.saveLocalMessageToBackend(systemMessage);
|
||||
|
||||
// 新建任务自动聚焦;追加则保持/回写当前 OT。
|
||||
options.setFocusedUserTaskNo?.(submission.user_task_no || null);
|
||||
|
||||
|
||||
@@ -68,6 +68,13 @@ export type ShippingProcessingStageNodeStatus =
|
||||
| 'blocked'
|
||||
| 'failed';
|
||||
|
||||
/** 后端 stage_nodes 单节点(BE-02 权威态;优先于前端 index 启发式)。 */
|
||||
export interface ShippingProcessingStageNode {
|
||||
stage: ShippingProcessingStage;
|
||||
absoluteIndex: number;
|
||||
status: ShippingProcessingStageNodeStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一动作意图(四页面只能消费 ActionPresentation)。
|
||||
* 权威:progress_audit_contract.SHIPPING_PROCESSING_ACTION_INTENTS
|
||||
@@ -139,6 +146,10 @@ export interface ShippingProcessingProjection {
|
||||
sourceType: OrderIntakeSourceType;
|
||||
rootOrderTaskNo: string | null;
|
||||
shippingNoticeNo: string | null;
|
||||
/** 关联 Extraction Run 编号;进入订单处理工作台深链必填。 */
|
||||
runNo?: string | null;
|
||||
/** 开放 Review Case 编号(若有)。 */
|
||||
caseNo?: string | null;
|
||||
conversationId: string | null;
|
||||
submissionNo: string;
|
||||
intakeNo: string;
|
||||
@@ -146,11 +157,15 @@ export interface ShippingProcessingProjection {
|
||||
stage: ShippingProcessingStage;
|
||||
progressVersion: number;
|
||||
lastActivityAt: string;
|
||||
/** 后端 15 阶节点态;存在时 UI 优先消费,禁止页面自行推导。 */
|
||||
stageNodes?: ShippingProcessingStageNode[];
|
||||
currentGate: ProcessGateSummary | null;
|
||||
availableActions: string[];
|
||||
sourceSummary: {
|
||||
emailSubject: string | null;
|
||||
filename: string | null;
|
||||
/** 当前 OT 主 PDF;会话汇总按此字段去重。 */
|
||||
documentId?: number | null;
|
||||
documentCount: number;
|
||||
parsedDocumentCount: number;
|
||||
candidateCount: number;
|
||||
@@ -472,6 +487,7 @@ export interface ShippingTaskSummary {
|
||||
customer_resolution_method?: string | null;
|
||||
customer_name_snapshot?: string | null;
|
||||
customer_short_code_snapshot?: string | null;
|
||||
po_number?: string | null;
|
||||
current_step?: string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
@@ -536,6 +552,8 @@ export interface ShippingTaskSummary {
|
||||
can_handle?: boolean;
|
||||
/** 统一 ShippingProcessing status(列表轮询优先读此字段)。 */
|
||||
shipping_processing_status?: string | null;
|
||||
/** 统一 ShippingProcessing stage(任务中心紧凑进度)。 */
|
||||
shipping_processing_stage?: string | null;
|
||||
/** 统一进度版本(与 shipping_processing_status 配套)。 */
|
||||
progress_version?: number | null;
|
||||
/** 关联的真实 OT 编号(Candidate 形成后);工作台拉取统一投影用。 */
|
||||
|
||||
@@ -61,6 +61,7 @@ const reviewRun = ref({
|
||||
],
|
||||
});
|
||||
const workItem = ref<Record<string, any> | null>(null);
|
||||
const reviewProgressContext = ref<Record<string, any> | null>(null);
|
||||
|
||||
const activeCase = ref({
|
||||
case_no: 'CASE-1',
|
||||
@@ -121,7 +122,13 @@ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
|
||||
useShippingOrderReview: () => ({
|
||||
reviewRun,
|
||||
activeCase,
|
||||
reviewProgressContext,
|
||||
workItem,
|
||||
authoritativeOrderTaskNo: computed(() => {
|
||||
const no = String(reviewProgressContext.value?.user_task_no || '').trim();
|
||||
if (!no || reviewProgressContext.value?.user_task_authoritative === false) return null;
|
||||
return no;
|
||||
}),
|
||||
versions: ref([]),
|
||||
statusMessage: ref(null),
|
||||
draftConflict: ref(null),
|
||||
@@ -180,6 +187,10 @@ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
|
||||
requestSuggestion: vi.fn(),
|
||||
decideSuggestion: vi.fn(),
|
||||
editable: computed(() => true),
|
||||
formalEditable: computed(() => false),
|
||||
canEditFormalFields: computed(() => false),
|
||||
isFieldEditable: () => true,
|
||||
isWorkItemClosed: computed(() => false),
|
||||
showWorkflowProgress: computed(() => false),
|
||||
workflowProgressPolling: computed(() => false),
|
||||
shippingProcessingProjection: ref(null),
|
||||
@@ -488,10 +499,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
vi.clearAllMocks();
|
||||
resetActiveCaseFixture();
|
||||
workItem.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
});
|
||||
|
||||
it('shows restored version as current and latest version only as failed attempt', async () => {
|
||||
workItem.value = {
|
||||
reviewProgressContext.value = {
|
||||
item_no: 'WFI-1',
|
||||
current_version_no: 4,
|
||||
lifecycle_status: 'reparse_failed',
|
||||
@@ -516,7 +528,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
});
|
||||
|
||||
it('does not show reparse-failure version notice for normal review', async () => {
|
||||
workItem.value = {
|
||||
reviewProgressContext.value = {
|
||||
item_no: 'WFI-1', current_version_no: 3, lifecycle_status: 'pending_review',
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
@@ -634,6 +646,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resetActiveCaseFixture();
|
||||
reviewProgressContext.value = null;
|
||||
vi.mocked(auditWorkspaceShippingOrderReviewVersionHistory).mockResolvedValue({
|
||||
audited: true,
|
||||
case_no: 'CASE-1',
|
||||
|
||||
@@ -1,29 +1,21 @@
|
||||
<!--
|
||||
features/chat/views/ShippingOrderReviewView.vue
|
||||
用途:建单前订单人工复核工作台(主编辑区 + 摘要侧栏 + workbenchMode 状态机)。
|
||||
用途:建单前/正式任务「订单处理工作台」(主编辑区 + 摘要侧栏 + workbenchMode 状态机)。
|
||||
依赖:路由参数、useShippingOrderReview、ReviewWorkbenchHeader/Footer、ReviewDocumentNavigation、
|
||||
ReviewWorkflowProgressPanel、ReviewProcessDetailDrawer、ReviewUnsavedSwitchDialog、
|
||||
ReviewWorkbenchModeToggle、ReviewDocumentEvidenceDrawer、ReviewVersionHistoryDrawer、
|
||||
ReviewLlmSuggestionDrawer、ReviewActionConfirmDialog、ReviewLineNoOverrideDialog、
|
||||
ReviewCustomerResolutionPanel / ReviewFieldConflictPanel / ReviewDuplicatePanel /
|
||||
ReviewAutomationStatusPanel、
|
||||
ReviewBuildEligibilitySummary、ReviewInventoryIssueList、ReviewInventoryCandidatesPanel、
|
||||
ProcessGateRecoveryCard;确认后进度回到对话侧,不重复挂载完整进度面板。
|
||||
逻辑:顶部横向 PDF 导航 + 模式切换;主编辑区始终保持订单字段/明细宽度;
|
||||
证据默认右下角浮动面板(不进网格);用户主动「固定为侧栏」才双栏;
|
||||
非宽屏将当前业务阻断(Gate/未确认客户/建单资格)置于长表格之前;
|
||||
客户已确认后缩为摘要并放入「更多状态」;
|
||||
定位图标按 highlight_quality 绿/橙/红着色;无可靠坐标用 CircleAlert(仅诊断);
|
||||
双击字段可定位 PDF;证据联动字段高亮;Alt+[ / Alt+] 切换异常字段;
|
||||
明细单元格纵向排布输入与来源/定位,窄屏靠横向滚动;
|
||||
库存模式仅异常行处理;完整检查/AI/版本历史按需抽屉并写访问审计(失败告警且不打开);
|
||||
页面仅保留单一主纵向滚动,底栏 sticky;build_eligibility 驱动建单门禁;
|
||||
确认响应读 confirm_outcome/auto_progress;刷新时由 post_confirm_auto_progress 恢复重试条;
|
||||
重识别/确认进度模式自动切换 workbenchMode;不含对话上下文渲染。
|
||||
ReviewAutomationStatusPanel、ReviewBuildEligibilitySummary、ReviewInventory*、
|
||||
ProcessGateRecoveryCard;formal_task 挂载 TaskTodoPanel(仅表单,主写按钮在 Footer)。
|
||||
逻辑:只读五域进度 + 流程详情抽屉;OT 导航按数量响应式;写操作仅底栏;
|
||||
切换 OT 未保存硬拦截;证据浮窗/侧栏不与流程详情抢位;
|
||||
页面单一主纵向滚动,底栏 sticky;build_eligibility 驱动建单门禁。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ArrowLeft, Check, CircleX, Crosshair, Plus, RefreshCw, Undo2, Copy, Trash2 } from 'lucide-vue-next';
|
||||
import { Check, CircleX, Crosshair, 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';
|
||||
@@ -38,6 +30,7 @@ import {
|
||||
autoProgressWorkspaceShippingTask,
|
||||
attemptWorkspaceShippingOrderReviewFieldLocate,
|
||||
getWorkspaceShippingOrderReviewEvidenceItem,
|
||||
getWorkspaceShippingTask,
|
||||
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
|
||||
} from '../api/shipping.api';
|
||||
import ReviewActionConfirmDialog, {
|
||||
@@ -55,27 +48,36 @@ import ReviewFulfillmentSummaryCard from '../components/shipping-review/ReviewFu
|
||||
import ReviewCloseFulfillmentDialog from '../components/shipping-review/ReviewCloseFulfillmentDialog.vue';
|
||||
import ReviewAuditTrailDrawer from '../components/shipping-review/ReviewAuditTrailDrawer.vue';
|
||||
import ReviewAutomationStatusPanel from '../components/shipping-review/ReviewAutomationStatusPanel.vue';
|
||||
import ReviewDocumentNavigation from '../components/shipping-review/ReviewDocumentNavigation.vue';
|
||||
import ReviewDocumentNavigation, {
|
||||
type ReviewDocumentNavMode,
|
||||
} from '../components/shipping-review/ReviewDocumentNavigation.vue';
|
||||
import ReviewWorkflowProgressPanel from '../components/shipping-review/ReviewWorkflowProgressPanel.vue';
|
||||
import ReviewInventoryCandidatesPanel from '../components/shipping-review/ReviewInventoryCandidatesPanel.vue';
|
||||
import ReviewInventoryIssueList from '../components/shipping-review/ReviewInventoryIssueList.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 ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
import TaskTodoPanel from '@/features/workspace/shipping-task-center/TaskTodoPanel.vue';
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
|
||||
import ReviewLineNoOverrideDialog, {
|
||||
type LineNoOverridePayload,
|
||||
} from '../components/shipping-review/ReviewLineNoOverrideDialog.vue';
|
||||
import ReviewLlmSuggestionDrawer from '../components/shipping-review/ReviewLlmSuggestionDrawer.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 { parseOrderReviewConfirmResponse } from '../shipping-review/parseOrderReviewConfirmResponse';
|
||||
import { REVIEW_BUILD_ELIGIBILITY_BLOCKED, useShippingOrderReview } from '../shipping-review/useShippingOrderReview';
|
||||
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
import type {
|
||||
ReviewWorkbenchMode,
|
||||
ReviewWorkbenchPanelState,
|
||||
ShippingOrderReviewDraftFieldMeta,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewValueSource,
|
||||
ShippingTaskDetail,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
/** 证据模式才加载,避免标准复核首屏拉入 pdfjs 预览组件。 */
|
||||
@@ -93,6 +95,7 @@ const {
|
||||
reviewProgressContext,
|
||||
shippingProcessingProjection,
|
||||
authoritativeOrderTaskNo,
|
||||
refreshShippingProcessing,
|
||||
workflowProgressPolling,
|
||||
versions,
|
||||
statusMessage,
|
||||
@@ -170,10 +173,12 @@ const shippingProcessingSummaryLabel = computed(() => {
|
||||
return [status, stage].filter(Boolean).join(' · ');
|
||||
});
|
||||
|
||||
/** 复核页始终可见的统一进度条:有投影或权威 OT 号即展示。 */
|
||||
/** 复核页始终可见的统一进度条:有投影、权威 OT 或确认成功即展示。 */
|
||||
const showUnifiedProcessingStrip = computed(() => (
|
||||
Boolean(shippingProcessingProjection.value)
|
||||
|| Boolean(shippingProcessingSummaryLabel.value)
|
||||
|| Boolean(authoritativeOrderTaskNo.value)
|
||||
|| Boolean(confirmSuccess.value)
|
||||
));
|
||||
|
||||
const runNo = computed(() => String(route.query.run_no || route.params.runNo || ''));
|
||||
@@ -201,6 +206,10 @@ const panelState = ref<ReviewWorkbenchPanelState>({
|
||||
scrollRestoreKey: null,
|
||||
});
|
||||
const auditTrailOpen = ref(false);
|
||||
const processDetailOpen = ref(false);
|
||||
const unsavedSwitchOpen = ref(false);
|
||||
const pendingSwitchCaseNo = ref<string | null>(null);
|
||||
const otNavMode = ref<ReviewDocumentNavMode>('hidden');
|
||||
const closeFulfillmentOpen = ref(false);
|
||||
const closeFulfillmentLineKeys = ref<string[]>([]);
|
||||
|
||||
@@ -872,6 +881,50 @@ const canEnterInventory = computed(() => (
|
||||
|| Number(activeCase.value?.line_fulfillment?.open_count || 0) > 0
|
||||
));
|
||||
const availableActions = computed(() => activeCase.value?.available_actions || []);
|
||||
|
||||
/** 底栏流程写操作:与原进度条 ActionBar 同源,surface=review。 */
|
||||
const flowProjectionRef = computed(() => shippingProcessingProjection.value);
|
||||
const flowPresentation = useProcessingActionPresentation(flowProjectionRef, { surface: 'review' });
|
||||
|
||||
/** 系统自动推进中:底栏隐藏无效主写按钮。 */
|
||||
const isProcessingAutomating = computed(() => {
|
||||
const status = String(shippingProcessingProjection.value?.status || '').trim().toLowerCase();
|
||||
return ['processing', 'automating', 'queued'].includes(status)
|
||||
&& !shippingProcessingProjection.value?.currentGate?.nextActionCode;
|
||||
});
|
||||
|
||||
/** OT 导航侧栏模式(≥5)时主区并排。 */
|
||||
const otNavUsesSidebar = computed(() => (
|
||||
otNavMode.value === 'sidebar' || otNavMode.value === 'sidebar_search'
|
||||
));
|
||||
|
||||
/**
|
||||
* 导航项:一 PDF 一 Case;当前 Case 附带 PO/客户/阶段(摘要列表无跨 Case 草稿字段)。
|
||||
*/
|
||||
const documentNavItems = computed(() => {
|
||||
const items = reviewRun.value?.items || [];
|
||||
const header = activeCase.value?.draft?.header_values as Record<string, unknown> | undefined;
|
||||
const activeNo = activeCase.value?.case_no;
|
||||
const stage = shippingProcessingProjection.value?.stage;
|
||||
const stageKey = stage ? shippingProcessingStageKey(stage) : '';
|
||||
const stageLabel = stageKey && te(stageKey) ? t(stageKey) : null;
|
||||
return items.map((item) => {
|
||||
const isActive = item.case_no === activeNo;
|
||||
return {
|
||||
...item,
|
||||
po_number: isActive ? (String(header?.po_number || '').trim() || null) : null,
|
||||
customer_name: isActive ? (String(header?.customer_name || '').trim() || null) : null,
|
||||
stage_label: isActive ? stageLabel : 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;
|
||||
});
|
||||
|
||||
const isReparsePrimary = computed(() => workbenchMode.value === 'reparse' && reparseProgressActive.value);
|
||||
/** 重识别任务存在时常驻展示轨道;轮询结束后保留最终状态,避免用户失去进度上下文。 */
|
||||
const hasReparseProgressContext = computed(() => Boolean(
|
||||
@@ -903,6 +956,52 @@ const hasCreatedShippingTask = computed(() => Boolean(
|
||||
|| String(reviewProgressContext.value?.current_task_no || '').trim(),
|
||||
));
|
||||
|
||||
/** 正式 Notice 编号(SN),供履约写 API / TaskTodoPanel。 */
|
||||
const confirmedNoticeTaskNo = computed(() => String(
|
||||
activeCase.value?.confirmed_task_no
|
||||
|| reviewProgressContext.value?.current_task_no
|
||||
|| '',
|
||||
).trim());
|
||||
|
||||
/** 确认后履约待办详情;任务中心不再挂工作台,由本工作台承接。 */
|
||||
const formalTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||||
const formalTaskDetailLoading = ref(false);
|
||||
const formalTodoPanelRef = ref<{
|
||||
invokeActionByCode: (actionId: string) => Promise<void>;
|
||||
openCustomerDialog: () => Promise<void>;
|
||||
} | null>(null);
|
||||
|
||||
/**
|
||||
* 拉取确认后的 Notice 履约详情,供 TaskTodoPanel 使用。
|
||||
*/
|
||||
async function loadFormalTaskDetail() {
|
||||
const taskNo = confirmedNoticeTaskNo.value;
|
||||
if (!taskNo) {
|
||||
formalTaskDetail.value = null;
|
||||
return;
|
||||
}
|
||||
formalTaskDetailLoading.value = true;
|
||||
try {
|
||||
formalTaskDetail.value = await getWorkspaceShippingTask(taskNo);
|
||||
} catch {
|
||||
formalTaskDetail.value = null;
|
||||
} finally {
|
||||
formalTaskDetailLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
[confirmedNoticeTaskNo, workbenchMode, hasCreatedShippingTask],
|
||||
([taskNo, mode, created]) => {
|
||||
if (taskNo && created && (mode === 'formal_task' || mode === 'confirm_progress')) {
|
||||
void loadFormalTaskDetail();
|
||||
return;
|
||||
}
|
||||
if (!taskNo) formalTaskDetail.value = null;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** Schema 字段显示名同时按 field_code / field_id 建索引,避免阻断只显示内部标识。 */
|
||||
const reviewFieldLabels = computed(() => Object.fromEntries(
|
||||
(activeCase.value?.schema.fields || []).flatMap((field) => [
|
||||
@@ -1196,7 +1295,7 @@ const autoProgressStatusLabel = (status: string) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认后主路径:返回对话并以 order_task_no 聚焦 OT 卡;Notice 编号仅用于文案辅助。
|
||||
* 确认后主路径留在复核页:统一动作栏驱动重试/刷新/任务台;返回对话仅作次要链接。
|
||||
*/
|
||||
const openTaskProgress = (orderTaskNo: string, noticeNo?: string) => {
|
||||
const focusNo = String(orderTaskNo || '').trim();
|
||||
@@ -1250,6 +1349,60 @@ const retryAutoProgressAfterConfirm = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 统一动作栏点击:优先复用已有写路径;履约业务动作委托 TaskTodoPanel。
|
||||
*/
|
||||
const onUnifiedProcessingAction = (item: ActionPresentationItem) => {
|
||||
const intent = item.intent;
|
||||
if (intent === 'retry') {
|
||||
void retryAutoProgressAfterConfirm();
|
||||
return;
|
||||
}
|
||||
if (intent === 'refresh') {
|
||||
void refreshShippingProcessing();
|
||||
void loadFormalTaskDetail();
|
||||
return;
|
||||
}
|
||||
if (intent === 'download_excel' && confirmedNoticeTaskNo.value) {
|
||||
void (async () => {
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(confirmedNoticeTaskNo.value);
|
||||
await loadFormalTaskDetail();
|
||||
} catch (error: unknown) {
|
||||
msg.warning(error instanceof Error ? error.message : t('errors.generic'));
|
||||
}
|
||||
})();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
intent === 'open_manual_upload'
|
||||
|| intent === 'open_inventory_source_review'
|
||||
|| intent === 'open_inventory_match_review'
|
||||
|| intent === 'open_shortage_review'
|
||||
|| intent === 'upload_inventory_file'
|
||||
|| intent === 'regenerate_excel'
|
||||
) {
|
||||
// [UI-01] 履约动作统一由 ActionBar 触发,表单/弹窗仍由 TaskTodoPanel 承接。
|
||||
if (!formalTaskDetail.value && confirmedNoticeTaskNo.value) {
|
||||
void loadFormalTaskDetail().then(() => {
|
||||
void formalTodoPanelRef.value?.invokeActionByCode(item.actionCode);
|
||||
});
|
||||
} else {
|
||||
void formalTodoPanelRef.value?.invokeActionByCode(item.actionCode);
|
||||
}
|
||||
void nextTick(() => {
|
||||
document
|
||||
.querySelector('[data-testid="review-formal-task-todo-panel"]')
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (intent === 'open_order_review' || intent === 'edit_formal_task') {
|
||||
// 已在订单处理工作台,无需跳转。
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const reportSave = async (action: () => Promise<unknown> | null) => {
|
||||
try { await action(); }
|
||||
catch (error) {
|
||||
@@ -1481,12 +1634,55 @@ const selectReplacement = (event: Event) => {
|
||||
(event.target as HTMLInputElement).value = '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 实际切换 Case(无未保存拦截)。
|
||||
*/
|
||||
const select = async (caseNo: string) => {
|
||||
focusedEvidenceRef.value = null;
|
||||
await selectCase(caseNo);
|
||||
await router.replace({ query: { ...route.query, case: 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 reportSave(() => validate());
|
||||
unsavedSwitchOpen.value = false;
|
||||
pendingSwitchCaseNo.value = null;
|
||||
if (target) await select(target);
|
||||
};
|
||||
|
||||
/**
|
||||
* 版本历史面板选择:历史版本只读打开,当前版本正常编辑。
|
||||
*/
|
||||
@@ -1768,7 +1964,7 @@ watch(
|
||||
<button
|
||||
v-if="confirmSuccess.progressFailed"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded border border-amber-500 px-2.5 py-1.5 text-xs font-medium hover:bg-amber-100 disabled:opacity-50 dark:hover:bg-amber-900"
|
||||
class="inline-flex items-center gap-1 rounded border border-amber-500 bg-amber-100/80 px-2.5 py-1.5 text-xs font-medium hover:bg-amber-100 disabled:opacity-50 dark:bg-amber-900/40 dark:hover:bg-amber-900"
|
||||
:disabled="progressRetrying"
|
||||
data-testid="retry-auto-progress-after-confirm"
|
||||
@click="retryAutoProgressAfterConfirm"
|
||||
@@ -1776,21 +1972,19 @@ watch(
|
||||
<RefreshCw class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.autoProgress.retry') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="confirmSuccess.orderTaskNo"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded border px-2.5 py-1.5 text-xs font-medium"
|
||||
:class="confirmSuccess.progressFailed
|
||||
? 'border-amber-500 hover:bg-amber-100 dark:hover:bg-amber-900'
|
||||
: 'border-emerald-400 hover:bg-emerald-100 dark:hover:bg-emerald-900'"
|
||||
data-testid="open-confirmed-task-progress"
|
||||
class="text-xs font-medium text-emerald-800 underline hover:text-emerald-950 dark:text-emerald-200 dark:hover:text-emerald-50"
|
||||
data-testid="open-confirmed-task-progress-link"
|
||||
@click="openTaskProgress(confirmSuccess.orderTaskNo, confirmSuccess.taskNo)"
|
||||
>
|
||||
<ArrowLeft class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.autoProgress.returnToChat') }}
|
||||
{{ t('chat.shippingOrderReview.autoProgress.returnToChat') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 确认后进度主路径回到对话「本次处理中」;复核页仅保留结果摘要与返回入口。 -->
|
||||
<!-- 确认后统一进度主路径留在本页;返回对话仅作次要聚焦链接。 -->
|
||||
|
||||
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
|
||||
<div
|
||||
@@ -1819,12 +2013,14 @@ watch(
|
||||
>
|
||||
<ReviewWorkflowProgressPanel
|
||||
v-if="showUnifiedProcessingStrip"
|
||||
:item="null"
|
||||
:item="reviewProgressContext"
|
||||
:task-no="authoritativeOrderTaskNo"
|
||||
:polling="workflowProgressPolling"
|
||||
:processing-projection="shippingProcessingProjection"
|
||||
class="mb-1"
|
||||
data-testid="review-shipping-processing-strip"
|
||||
@open-process-details="processDetailOpen = true"
|
||||
@refresh="() => { void refreshShippingProcessing(); }"
|
||||
/>
|
||||
<p
|
||||
v-if="workbenchMode === 'formal_task'"
|
||||
@@ -1838,14 +2034,23 @@ watch(
|
||||
class="ml-1.5 text-muted"
|
||||
>{{ authoritativeOrderTaskNo }}</span>
|
||||
</p>
|
||||
<template v-if="showWorkbenchGrid">
|
||||
<ReviewDocumentNavigation
|
||||
:items="reviewRun?.items || []"
|
||||
:active-case-no="activeCase?.case_no"
|
||||
:nav-aria-label="t('chat.shippingOrderReview.documentNavigation')"
|
||||
@select="select"
|
||||
<section
|
||||
v-if="hasCreatedShippingTask && (workbenchMode === 'formal_task' || workbenchMode === 'confirm_progress')"
|
||||
class="rounded-xl border border-default bg-surface p-3"
|
||||
data-testid="review-formal-task-todo-panel"
|
||||
>
|
||||
<div v-if="formalTaskDetailLoading" class="py-4 text-center text-xs text-muted">
|
||||
{{ t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<TaskTodoPanel
|
||||
v-else-if="formalTaskDetail"
|
||||
ref="formalTodoPanelRef"
|
||||
:detail="formalTaskDetail"
|
||||
:can-handle="!isReadOnly"
|
||||
:hide-primary-actions="true"
|
||||
@refreshed="() => { void loadFormalTaskDetail(); void refreshShippingProcessing(); }"
|
||||
/>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="hasReparseProgressContext"
|
||||
@@ -1983,6 +2188,22 @@ watch(
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showWorkbenchGrid"
|
||||
:class="otNavUsesSidebar ? 'lg:flex lg:items-start lg:gap-4' : 'contents'"
|
||||
data-testid="review-workbench-ot-shell"
|
||||
>
|
||||
<ReviewDocumentNavigation
|
||||
:items="documentNavItems"
|
||||
:active-case-no="activeCase?.case_no"
|
||||
:nav-aria-label="t('chat.shippingOrderReview.documentNavigation')"
|
||||
@mode-change="(mode) => { otNavMode = mode; }"
|
||||
@select="(caseNo) => { void requestSelectCase(caseNo); }"
|
||||
/>
|
||||
<div
|
||||
class="min-w-0 flex-1 space-y-4"
|
||||
:class="otNavUsesSidebar ? '' : 'contents'"
|
||||
>
|
||||
<template v-if="showWorkbenchGrid">
|
||||
<ReviewWorkbenchModeToggle
|
||||
v-if="workbenchMode !== 'standard' && workbenchMode !== 'reparse'"
|
||||
@@ -2483,6 +2704,8 @@ watch(
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -2571,12 +2794,35 @@ watch(
|
||||
:saving="saving"
|
||||
:is-read-only="isReadOnly"
|
||||
:has-draft="Boolean(activeCase?.draft)"
|
||||
:unsaved-count="unsavedEditCount"
|
||||
:flow-presentation="flowPresentation"
|
||||
:automating="isProcessingAutomating"
|
||||
@mark-non-order="openActionDialog('non_order')"
|
||||
@mark-quality-issue="openActionDialog('quality_issue')"
|
||||
@reparse="openActionDialog('reparse')"
|
||||
@upload-replacement="selectReplacement"
|
||||
@validate="reportSave(() => validate())"
|
||||
@confirm="openActionDialog('confirm')"
|
||||
@flow-action="onUnifiedProcessingAction"
|
||||
/>
|
||||
|
||||
<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; }"
|
||||
/>
|
||||
|
||||
<ReviewUnsavedSwitchDialog
|
||||
:open="unsavedSwitchOpen"
|
||||
:unsaved-count="unsavedEditCount"
|
||||
:saving="saving"
|
||||
@cancel="() => { unsavedSwitchOpen = false; pendingSwitchCaseNo = null; }"
|
||||
@discard="() => { void discardAndSwitchCase(); }"
|
||||
@save-and-switch="() => { void saveAndSwitchCase(); }"
|
||||
/>
|
||||
|
||||
<ReviewActionConfirmDialog
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/shipping-progress/actionPresentation.spec.ts
|
||||
* 用途:验收统一动作优先级与自动态空主按钮。
|
||||
* 用途:验收统一动作优先级、自动态空主按钮与 surface 过滤。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
@@ -74,4 +74,19 @@ describe('resolveProcessingActionPresentation', () => {
|
||||
expect(result.primary?.intent).toBe('retry');
|
||||
expect(result.primary?.actionCode).toBe('retry_parse');
|
||||
});
|
||||
|
||||
it('filters open_order_review on review surface', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['open_order_review', 'refresh'],
|
||||
}), { surface: 'review' });
|
||||
expect(result.primary?.intent).toBe('refresh');
|
||||
expect(result.overflow.some((i) => i.intent === 'open_order_review')).toBe(false);
|
||||
});
|
||||
|
||||
it('maps open_order_review label to processing entry on chat surface', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['open_order_review'],
|
||||
}), { surface: 'chat' });
|
||||
expect(result.primary?.labelKey).toBe('chat.shippingProcessing.action.open_order_processing');
|
||||
});
|
||||
});
|
||||
@@ -3,33 +3,41 @@
|
||||
* 用途:从统一投影解析四页面共用的 ActionPresentation(主/次/溢出)。
|
||||
* 依赖:ShippingProcessingProjection、SHIPPING_PROCESSING_ACTION_INTENTS、types。
|
||||
* 逻辑:优先级 Gate.nextActionCode → availableActions → 终态查看 → none;
|
||||
* 自动处理中(processing/automating)主按钮为空,避免误导性 CTA。
|
||||
* 自动处理中(processing/automating)主按钮为空;review 面隐藏 open_order_review。
|
||||
*/
|
||||
|
||||
import type {
|
||||
ShippingProcessingActionIntent,
|
||||
ShippingProcessingProjection,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import type { ActionPresentation, ActionPresentationItem } from './types';
|
||||
import type { ActionPresentation, ActionPresentationItem, ActionPresentationSurface } from './types';
|
||||
|
||||
/** 可映射为统一意图的原始动作码(gate / available_actions)。 */
|
||||
const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
|
||||
open_order_review: 'open_order_review',
|
||||
open_review: 'open_order_review',
|
||||
open_order_processing: 'open_order_review',
|
||||
edit_formal_task: 'edit_formal_task',
|
||||
open_inventory_source_review: 'open_inventory_source_review',
|
||||
confirm_inventory_source: 'open_inventory_source_review',
|
||||
retry_resolve_inventory_source: 'open_inventory_source_review',
|
||||
open_inventory_match_review: 'open_inventory_match_review',
|
||||
rematch: 'open_inventory_match_review',
|
||||
match_inventory: 'open_inventory_match_review',
|
||||
open_shortage_review: 'open_shortage_review',
|
||||
upload_inventory_file: 'upload_inventory_file',
|
||||
retry: 'retry',
|
||||
retry_parse: 'retry',
|
||||
retry_failed_documents: 'retry',
|
||||
refresh: 'refresh',
|
||||
regenerate_excel: 'regenerate_excel',
|
||||
generate_excel: 'regenerate_excel',
|
||||
download_excel: 'download_excel',
|
||||
open_manual_upload: 'open_manual_upload',
|
||||
wait_manual_upload: 'open_manual_upload',
|
||||
mark_manual_uploaded: 'open_manual_upload',
|
||||
regenerate_manual_upload_todo: 'open_manual_upload',
|
||||
open_fulfillment: 'view_result',
|
||||
view_result: 'view_result',
|
||||
view_details: 'view_result',
|
||||
view_record: 'view_record',
|
||||
@@ -49,11 +57,22 @@ export function mapActionCodeToIntent(code: string | null | undefined): Shipping
|
||||
/**
|
||||
* 构建单个动作项。
|
||||
*/
|
||||
function toItem(code: string, intent: ShippingProcessingActionIntent): ActionPresentationItem {
|
||||
function toItem(
|
||||
code: string,
|
||||
intent: ShippingProcessingActionIntent,
|
||||
surface?: ActionPresentationSurface,
|
||||
): ActionPresentationItem {
|
||||
let labelKey = `chat.shippingProcessing.action.${intent}`;
|
||||
if (
|
||||
intent === 'open_order_review'
|
||||
&& (surface === 'chat' || surface === 'right')
|
||||
) {
|
||||
labelKey = 'chat.shippingProcessing.action.open_order_processing';
|
||||
}
|
||||
return {
|
||||
intent,
|
||||
actionCode: code,
|
||||
labelKey: `chat.shippingProcessing.action.${intent}`,
|
||||
labelKey,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,14 +83,17 @@ function toItem(code: string, intent: ShippingProcessingActionIntent): ActionPre
|
||||
* 1. processing/automating/queued → 主按钮为空(自动推进中);
|
||||
* 2. currentGate.nextActionCode 优先;
|
||||
* 3. availableActions 依次填主/次/溢出;
|
||||
* 4. completed/failed/cancelled → view_result / view_record 兜底。
|
||||
* 4. completed/failed/cancelled → view_result / view_record 兜底;
|
||||
* 5. surface=review 时过滤 open_order_review(已在复核页)。
|
||||
*/
|
||||
export function resolveProcessingActionPresentation(
|
||||
projection: ShippingProcessingProjection | null | undefined,
|
||||
options?: { surface?: ActionPresentationSurface },
|
||||
): ActionPresentation {
|
||||
const empty: ActionPresentation = { primary: null, secondary: null, overflow: [] };
|
||||
if (!projection) return empty;
|
||||
|
||||
const surface = options?.surface;
|
||||
const status = String(projection.status || '').trim().toLowerCase();
|
||||
if (AUTOMATING_STATUSES.has(status) && !projection.currentGate?.nextActionCode) {
|
||||
return empty;
|
||||
@@ -87,8 +109,9 @@ export function resolveProcessingActionPresentation(
|
||||
if (seen.has(key)) return;
|
||||
const intent = mapActionCodeToIntent(code);
|
||||
if (!intent || intent === 'none') return;
|
||||
if (surface === 'review' && intent === 'open_order_review') return;
|
||||
seen.add(key);
|
||||
items.push(toItem(code, intent));
|
||||
items.push(toItem(code, intent, surface));
|
||||
};
|
||||
|
||||
pushCode(projection.currentGate?.nextActionCode);
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
<!--
|
||||
features/shipping-progress/components/ChatProgressSummary.vue
|
||||
用途:对话气泡区文本型进度摘要——已完成/当前/阻断 + 主/次动作;默认无卡片网格。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、UnifiedActionBar、UnifiedProgressTrack。
|
||||
逻辑:由 ShippingOrderExtractionCard 挂载;展开后显示完整 UnifiedProgressTrack。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import { resolveShippingProcessingStatusLabel, shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { buildProgressRangeHint, buildProgressWindow } from '../progressWindow';
|
||||
import { useProcessingActionPresentation } from '../composables/useProcessingActionPresentation';
|
||||
import type { ActionPresentationItem } from '../types';
|
||||
import UnifiedActionBar from './UnifiedActionBar.vue';
|
||||
import UnifiedProgressTrack from './UnifiedProgressTrack.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
projection: ShippingProcessingProjection;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
action: [item: ActionPresentationItem];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const expanded = ref(false);
|
||||
|
||||
const projectionRef = computed(() => props.projection);
|
||||
const actionPresentation = useProcessingActionPresentation(projectionRef, { surface: 'chat' });
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'chat'));
|
||||
const currentNodes = computed(() => buildProgressWindow(props.projection, 'chat'));
|
||||
|
||||
/**
|
||||
* 当前阶段中性名称。
|
||||
*/
|
||||
const currentStageLabel = computed(() => {
|
||||
const key = rangeHint.value?.currentLabelKey || shippingProcessingStageKey(props.projection.stage);
|
||||
return te(key) ? t(key) : props.projection.stage;
|
||||
});
|
||||
|
||||
/**
|
||||
* 状态 + 已完成摘要行。
|
||||
*/
|
||||
const summaryLine = computed(() => {
|
||||
const hint = rangeHint.value;
|
||||
if (!hint) return '';
|
||||
const completed = t('chat.shippingProcessing.progress.completedOfTotal', {
|
||||
done: hint.done,
|
||||
total: hint.total,
|
||||
});
|
||||
const current = t('chat.shippingProcessing.progress.currentStage', {
|
||||
stage: currentStageLabel.value,
|
||||
});
|
||||
return `${completed} · ${current}`;
|
||||
});
|
||||
|
||||
/**
|
||||
* Gate 阻断原因文案。
|
||||
*/
|
||||
const blockerLabel = computed(() => {
|
||||
const code = String(props.projection.currentGate?.blockingReasonCode || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `workspace.shippingNotice.workflowReasons.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
});
|
||||
|
||||
/**
|
||||
* 当前投影状态标签。
|
||||
*/
|
||||
const statusLabel = computed(() =>
|
||||
resolveShippingProcessingStatusLabel(props.projection.status, te, t),
|
||||
);
|
||||
|
||||
/**
|
||||
* 切换完整轨道展开。
|
||||
*/
|
||||
function toggleExpanded() {
|
||||
expanded.value = !expanded.value;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="mt-2 rounded-lg border border-current/15 bg-black/5 px-2.5 py-2 text-xs dark:bg-white/5"
|
||||
data-testid="chat-progress-summary"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span
|
||||
v-if="statusLabel"
|
||||
class="font-semibold"
|
||||
data-testid="chat-progress-status"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
<span
|
||||
v-if="summaryLine"
|
||||
class="opacity-90"
|
||||
data-testid="chat-progress-summary-line"
|
||||
>
|
||||
{{ summaryLine }}
|
||||
</span>
|
||||
</div>
|
||||
<p
|
||||
v-if="blockerLabel"
|
||||
class="mt-1 font-medium text-amber-800 dark:text-amber-200"
|
||||
data-testid="chat-progress-blocker"
|
||||
>
|
||||
{{ blockerLabel }}
|
||||
</p>
|
||||
<div class="mt-2">
|
||||
<UnifiedActionBar
|
||||
:presentation="actionPresentation"
|
||||
@action="(item) => emit('action', item)"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
v-if="currentNodes.length"
|
||||
type="button"
|
||||
class="mt-2 text-[11px] font-medium underline-offset-2 hover:underline"
|
||||
data-testid="chat-progress-expand"
|
||||
@click="toggleExpanded"
|
||||
>
|
||||
{{ expanded
|
||||
? t('chat.shippingProcessing.collapseHistory')
|
||||
: t('chat.shippingProcessing.expandHistory') }}
|
||||
</button>
|
||||
<div
|
||||
v-if="expanded"
|
||||
class="mt-2"
|
||||
data-testid="chat-progress-full-track"
|
||||
>
|
||||
<UnifiedProgressTrack
|
||||
:projection="projection"
|
||||
density="chat"
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,217 @@
|
||||
<!--
|
||||
features/shipping-progress/components/ReviewProcessDetailDrawer.vue
|
||||
用途:订单处理工作台「流程详情」只读抽屉——完整 15 阶按五域分组。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、shippingProcessingLabels。
|
||||
逻辑:由 ShippingOrderReviewView 挂载;缺时间/主体显示「—」;禁止抽屉内写操作按钮。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import {
|
||||
REVIEW_PROGRESS_DOMAIN_RANGES,
|
||||
buildFullProgressNodes,
|
||||
buildProgressRangeHint,
|
||||
stageAbsoluteIndex,
|
||||
} from '../progressWindow';
|
||||
import type { ProgressWindowNode } from '../types';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
projection: ShippingProcessingProjection | null;
|
||||
/** 标题副文案:PO */
|
||||
poNumber?: string | null;
|
||||
/** 标题副文案:OT */
|
||||
orderTaskNo?: string | null;
|
||||
/** 有审计入口时展示只读链接 */
|
||||
auditAvailable?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
'open-audit': [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const nodes = computed(() => buildFullProgressNodes(props.projection));
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
if (!props.projection) return '';
|
||||
return resolveShippingProcessingStatusLabel(props.projection.status, te, t);
|
||||
});
|
||||
|
||||
const positionLabel = computed(() => {
|
||||
if (!props.projection) return '';
|
||||
const index = stageAbsoluteIndex(props.projection.stage) + 1;
|
||||
return t('chat.shippingProcessing.progress.positionOfTotal', { current: index, total: 15 });
|
||||
});
|
||||
|
||||
/**
|
||||
* 按五域分组的完整节点。
|
||||
*/
|
||||
const domainGroups = computed(() => (
|
||||
REVIEW_PROGRESS_DOMAIN_RANGES.map((domain) => ({
|
||||
key: domain.key,
|
||||
labelKey: domain.labelKey,
|
||||
nodes: nodes.value.filter((node) => (
|
||||
node.absoluteIndex >= domain.start && node.absoluteIndex <= domain.end
|
||||
)),
|
||||
}))
|
||||
));
|
||||
|
||||
/**
|
||||
* 阶段名。
|
||||
*/
|
||||
function nodeLabel(node: ProgressWindowNode): string {
|
||||
const key = shippingProcessingStageKey(node.stage);
|
||||
return te(key) ? t(key) : node.stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点态文案。
|
||||
*/
|
||||
function nodeStatusLabel(status: ProgressWindowNode['status']): string {
|
||||
const key = `chat.shippingProcessing.stageNode.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 圆点样式。
|
||||
*/
|
||||
function dotClass(status: ProgressWindowNode['status']): string {
|
||||
if (status === 'passed') return 'bg-emerald-500';
|
||||
if (status === 'running') return 'bg-brand-500';
|
||||
if (status === 'blocked') return 'bg-amber-500';
|
||||
if (status === 'failed') return 'bg-rose-500';
|
||||
if (status === 'skipped') return 'bg-slate-200 opacity-50';
|
||||
return 'bg-slate-300';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex justify-end"
|
||||
data-testid="review-process-detail-drawer"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-0 bg-slate-900/40"
|
||||
:aria-label="t('chat.shippingProcessing.progress.closeProcessDetails')"
|
||||
data-testid="review-process-detail-backdrop"
|
||||
@click="emit('close')"
|
||||
/>
|
||||
<aside
|
||||
class="relative z-10 flex h-full w-full max-w-md flex-col border-l border-default bg-surface shadow-xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('chat.shippingProcessing.progress.processDetailsTitle')"
|
||||
>
|
||||
<header class="flex items-start justify-between gap-3 border-b border-default px-4 py-3">
|
||||
<div class="min-w-0">
|
||||
<h2 class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingProcessing.progress.processDetailsTitle') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 truncate text-[11px] text-secondary">
|
||||
<span v-if="poNumber">PO {{ poNumber }}</span>
|
||||
<span v-if="poNumber && orderTaskNo"> · </span>
|
||||
<span v-if="orderTaskNo">{{ orderTaskNo }}</span>
|
||||
</p>
|
||||
<p
|
||||
v-if="statusLabel || positionLabel"
|
||||
class="mt-1 text-[11px] text-muted"
|
||||
data-testid="review-process-detail-summary"
|
||||
>
|
||||
<span v-if="statusLabel">{{ statusLabel }}</span>
|
||||
<span v-if="statusLabel && positionLabel"> · </span>
|
||||
<span v-if="positionLabel">{{ positionLabel }}</span>
|
||||
<span v-if="rangeHint">
|
||||
· {{ t('chat.shippingProcessing.progress.completedOfTotal', {
|
||||
done: rangeHint.done,
|
||||
total: rangeHint.total,
|
||||
}) }}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg p-1.5 text-muted hover:bg-surface-muted hover:text-primary"
|
||||
data-testid="review-process-detail-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-y-auto px-4 py-3">
|
||||
<section
|
||||
v-for="group in domainGroups"
|
||||
:key="group.key"
|
||||
class="mb-4"
|
||||
:data-domain-group="group.key"
|
||||
>
|
||||
<h3 class="mb-2 text-[11px] font-semibold uppercase tracking-wide text-muted">
|
||||
{{ t(group.labelKey) }}
|
||||
</h3>
|
||||
<ol class="space-y-2">
|
||||
<li
|
||||
v-for="node in group.nodes"
|
||||
:key="node.stage"
|
||||
class="rounded-lg border border-default bg-surface-soft/50 px-2.5 py-2"
|
||||
:data-stage="node.stage"
|
||||
:data-state="node.status"
|
||||
:data-current="node.isCurrent ? 'true' : 'false'"
|
||||
data-testid="review-process-detail-node"
|
||||
>
|
||||
<div class="flex items-center gap-2 text-xs">
|
||||
<span
|
||||
class="inline-block h-2 w-2 shrink-0 rounded-full"
|
||||
:class="dotClass(node.status)"
|
||||
/>
|
||||
<span :class="node.isCurrent ? 'font-semibold text-primary' : 'text-secondary'">
|
||||
{{ nodeLabel(node) }}
|
||||
</span>
|
||||
<span class="ml-auto shrink-0 text-[10px] text-muted">
|
||||
{{ nodeStatusLabel(node.status) }}
|
||||
</span>
|
||||
</div>
|
||||
<dl class="mt-1.5 grid grid-cols-2 gap-x-2 gap-y-0.5 text-[10px] text-muted">
|
||||
<div>
|
||||
<dt class="inline">{{ t('chat.shippingProcessing.progress.nodeTime') }}</dt>
|
||||
<dd class="ml-1 inline">{{ t('chat.shippingProcessing.progress.placeholderDash') }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="inline">{{ t('chat.shippingProcessing.progress.nodeActor') }}</dt>
|
||||
<dd class="ml-1 inline">{{ t('chat.shippingProcessing.progress.placeholderDash') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer
|
||||
v-if="auditAvailable"
|
||||
class="border-t border-default px-4 py-3"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] font-medium text-brand-700 underline-offset-2 hover:underline dark:text-brand-300"
|
||||
data-testid="review-process-detail-open-audit"
|
||||
@click="emit('open-audit')"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.progress.viewFullAudit') }}
|
||||
</button>
|
||||
</footer>
|
||||
</aside>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,145 @@
|
||||
<!--
|
||||
features/shipping-progress/components/ReviewProgressStrip.vue
|
||||
用途:订单处理工作台只读紧凑进度——五域摘要 + 当前节点 n/15 + 当前需要 + 打开流程详情。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、gateReasonLabel。
|
||||
逻辑:由 ReviewWorkflowProgressPanel 挂载;正文不展开 15 阶、不挂 ActionBar;写操作只在底部 Footer。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import {
|
||||
buildProgressRangeHint,
|
||||
buildReviewProgressDomainSummary,
|
||||
stageAbsoluteIndex,
|
||||
} from '../progressWindow';
|
||||
import { resolveGateReasonLabel } from '../gateReasonLabel';
|
||||
import type { ProgressDomainState } from '../types';
|
||||
|
||||
const props = defineProps<{
|
||||
projection: ShippingProcessingProjection;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-process-details': [];
|
||||
refresh: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
|
||||
|
||||
const domains = computed(() => buildReviewProgressDomainSummary(props.projection));
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
|
||||
|
||||
const isAutomating = computed(() => (
|
||||
AUTOMATING_STATUSES.has(String(props.projection.status || '').trim().toLowerCase())
|
||||
&& !props.projection.currentGate?.nextActionCode
|
||||
));
|
||||
|
||||
/**
|
||||
* ● 当前阶段 · 第 n/15。
|
||||
*/
|
||||
const currentLine = computed(() => {
|
||||
const stageKey = rangeHint.value?.currentLabelKey || shippingProcessingStageKey(props.projection.stage);
|
||||
const stageLabel = te(stageKey) ? t(stageKey) : props.projection.stage;
|
||||
const index = stageAbsoluteIndex(props.projection.stage) + 1;
|
||||
return `● ${stageLabel} · ${t('chat.shippingProcessing.progress.positionOfTotal', { current: index, total: 15 })}`;
|
||||
});
|
||||
|
||||
/**
|
||||
* 当前需要:Gate 原因;自动推进中用系统文案。
|
||||
*/
|
||||
const currentNeed = computed(() => {
|
||||
if (isAutomating.value) {
|
||||
return t('chat.shippingProcessing.progress.systemProcessingNeed');
|
||||
}
|
||||
return resolveGateReasonLabel(
|
||||
props.projection.currentGate?.blockingReasonCode,
|
||||
{ t, te },
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* 五域圆点样式。
|
||||
*/
|
||||
function domainDotClass(state: ProgressDomainState): string {
|
||||
if (state === 'passed') return 'bg-emerald-500';
|
||||
if (state === 'current') return 'bg-brand-500';
|
||||
if (state === 'blocked') return 'bg-amber-500';
|
||||
if (state === 'failed') return 'bg-rose-500';
|
||||
return 'bg-slate-300';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="space-y-2"
|
||||
data-testid="review-progress-strip"
|
||||
>
|
||||
<div
|
||||
v-if="domains.length"
|
||||
class="flex flex-wrap items-center gap-1.5"
|
||||
data-testid="review-progress-domains"
|
||||
>
|
||||
<div
|
||||
v-for="domain in domains"
|
||||
:key="domain.key"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-default bg-surface px-2 py-0.5 text-[11px]"
|
||||
:data-domain="domain.key"
|
||||
:data-state="domain.state"
|
||||
>
|
||||
<span
|
||||
class="inline-block h-1.5 w-1.5 rounded-full"
|
||||
:class="domainDotClass(domain.state)"
|
||||
/>
|
||||
<span :class="domain.state === 'current' || domain.state === 'blocked' ? 'font-semibold text-primary' : 'text-secondary'">
|
||||
{{ t(domain.labelKey) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-secondary"
|
||||
data-testid="review-progress-range"
|
||||
>
|
||||
<span data-testid="review-progress-current-line">{{ currentLine }}</span>
|
||||
<span v-if="rangeHint">
|
||||
{{ t('chat.shippingProcessing.progress.completedOfTotal', {
|
||||
done: rangeHint.done,
|
||||
total: rangeHint.total,
|
||||
}) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="currentNeed"
|
||||
class="text-[11px] text-amber-800 dark:text-amber-200"
|
||||
data-testid="review-progress-current-need"
|
||||
>
|
||||
<span class="font-medium text-secondary">{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}</span>
|
||||
{{ currentNeed }}
|
||||
</p>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-brand-700 hover:bg-surface-muted dark:text-brand-300"
|
||||
data-testid="review-progress-open-details"
|
||||
@click="emit('open-process-details')"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.progress.viewProcessDetails') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="isAutomating"
|
||||
type="button"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted"
|
||||
data-testid="review-progress-refresh"
|
||||
@click="emit('refresh')"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.action.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,83 @@
|
||||
<!--
|
||||
features/shipping-progress/components/SidebarProgressInline.vue
|
||||
用途:对话右侧紧凑进度行——● 当前阶段 · 第 x/total + Gate 原因 + 内联动作。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、UnifiedActionBar、gateReasonLabel。
|
||||
逻辑:由 ShippingConversationProcessingCard 仅在聚焦卡内嵌完整版;
|
||||
compact=true 时只显示单行阶段摘要,不渲染动作栏。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { buildProgressRangeHint, stageAbsoluteIndex } from '../progressWindow';
|
||||
import { useProcessingActionPresentation } from '../composables/useProcessingActionPresentation';
|
||||
import type { ActionPresentationItem } from '../types';
|
||||
import { resolveGateReasonLabel } from '../gateReasonLabel';
|
||||
import UnifiedActionBar from './UnifiedActionBar.vue';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
projection: ShippingProcessingProjection;
|
||||
/** 非聚焦卡:仅单行摘要,不展开节点与动作。 */
|
||||
compact?: boolean;
|
||||
}>(), {
|
||||
compact: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
action: [item: ActionPresentationItem];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const projectionRef = computed(() => props.projection);
|
||||
const actionPresentation = useProcessingActionPresentation(projectionRef, { surface: 'right' });
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'right'));
|
||||
|
||||
/**
|
||||
* 紧凑单行:● 阶段名 · 第 x/total。
|
||||
*/
|
||||
const inlineLine = computed(() => {
|
||||
const hint = rangeHint.value;
|
||||
const stageKey = hint?.currentLabelKey || shippingProcessingStageKey(props.projection.stage);
|
||||
const stageLabel = te(stageKey) ? t(stageKey) : props.projection.stage;
|
||||
const index = stageAbsoluteIndex(props.projection.stage) + 1;
|
||||
return `● ${stageLabel} · ${t('chat.shippingProcessing.progress.positionOfTotal', { current: index, total: 15 })}`;
|
||||
});
|
||||
|
||||
/**
|
||||
* Gate 阻断原因(禁止展示内部码)。
|
||||
*/
|
||||
const gateReason = computed(() => resolveGateReasonLabel(
|
||||
props.projection.currentGate?.blockingReasonCode,
|
||||
{ t, te },
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="space-y-1.5"
|
||||
data-testid="sidebar-progress-inline"
|
||||
:data-compact="compact ? '1' : '0'"
|
||||
>
|
||||
<div
|
||||
class="text-[11px] font-medium text-secondary"
|
||||
data-testid="sidebar-progress-line"
|
||||
>
|
||||
{{ inlineLine }}
|
||||
</div>
|
||||
<template v-if="!compact">
|
||||
<p
|
||||
v-if="gateReason"
|
||||
class="text-[11px] text-amber-800 dark:text-amber-200"
|
||||
data-testid="sidebar-progress-gate-reason"
|
||||
>
|
||||
{{ gateReason }}
|
||||
</p>
|
||||
<UnifiedActionBar
|
||||
:presentation="actionPresentation"
|
||||
@action="(item) => emit('action', item)"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,129 @@
|
||||
<!--
|
||||
features/shipping-progress/components/WorkbenchProgressGrouped.vue
|
||||
用途:任务台分组进度——解析 1–10 / 库存 11–12 / 履约 13–15 三域 + 当前阶段;可选动作栏。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、UnifiedProgressTrack、UnifiedActionBar。
|
||||
逻辑:由 ShippingTaskWorkbench 挂载;任务台履约动作归 TaskTodoPanel,默认关闭本组件动作栏(UI-05)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { buildProgressRangeHint, stageAbsoluteIndex } from '../progressWindow';
|
||||
import { useProcessingActionPresentation } from '../composables/useProcessingActionPresentation';
|
||||
import type { ActionPresentationItem } from '../types';
|
||||
import UnifiedActionBar from './UnifiedActionBar.vue';
|
||||
import UnifiedProgressTrack from './UnifiedProgressTrack.vue';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
projection: ShippingProcessingProjection;
|
||||
/** 是否渲染投影动作栏;任务台内嵌时应为 false,避免与 TaskTodoPanel 双入口。 */
|
||||
showActions?: boolean;
|
||||
}>(), {
|
||||
showActions: true,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
action: [item: ActionPresentationItem];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const showDetailTrack = ref(false);
|
||||
|
||||
const projectionRef = computed(() => props.projection);
|
||||
const actionPresentation = useProcessingActionPresentation(projectionRef, { surface: 'workbench' });
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
|
||||
|
||||
/** 三域阶段下标区间(0-based,含端点)。 */
|
||||
const DOMAIN_RANGES = [
|
||||
{ key: 'intake', labelKey: 'chat.shippingProcessing.progress.domainIntake', start: 0, end: 9 },
|
||||
{ key: 'inventory', labelKey: 'chat.shippingProcessing.progress.domainInventory', start: 10, end: 11 },
|
||||
{ key: 'fulfillment', labelKey: 'chat.shippingProcessing.progress.domainFulfillment', start: 12, end: 14 },
|
||||
] as const;
|
||||
|
||||
const currentIndex = computed(() => stageAbsoluteIndex(props.projection.stage));
|
||||
|
||||
/**
|
||||
* 判断某域是否为当前/已过/未到。
|
||||
*/
|
||||
function domainState(start: number, end: number): 'passed' | 'current' | 'pending' {
|
||||
const idx = currentIndex.value;
|
||||
if (idx > end) return 'passed';
|
||||
if (idx >= start && idx <= end) return 'current';
|
||||
return 'pending';
|
||||
}
|
||||
|
||||
/**
|
||||
* 域标签样式。
|
||||
*/
|
||||
function domainClass(state: 'passed' | 'current' | 'pending'): string {
|
||||
if (state === 'passed') return 'border-emerald-200 bg-emerald-50 text-emerald-800';
|
||||
if (state === 'current') return 'border-brand-300 bg-brand-50 text-brand-800';
|
||||
return 'border-default bg-surface text-muted';
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前阶段中性名称。
|
||||
*/
|
||||
const currentStageLabel = computed(() => {
|
||||
const key = rangeHint.value?.currentLabelKey || shippingProcessingStageKey(props.projection.stage);
|
||||
return te(key) ? t(key) : props.projection.stage;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="space-y-3"
|
||||
data-testid="workbench-progress-grouped"
|
||||
>
|
||||
<div
|
||||
v-if="rangeHint"
|
||||
class="text-xs text-secondary"
|
||||
data-testid="workbench-progress-range"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.progress.completedOfTotal', {
|
||||
done: rangeHint.done,
|
||||
total: rangeHint.total,
|
||||
}) }}
|
||||
·
|
||||
{{ t('chat.shippingProcessing.progress.currentStage', { stage: currentStageLabel }) }}
|
||||
</div>
|
||||
|
||||
<div class="grid gap-2 sm:grid-cols-3">
|
||||
<div
|
||||
v-for="domain in DOMAIN_RANGES"
|
||||
:key="domain.key"
|
||||
class="rounded-xl border px-3 py-2 text-xs font-semibold"
|
||||
:class="domainClass(domainState(domain.start, domain.end))"
|
||||
:data-domain="domain.key"
|
||||
:data-state="domainState(domain.start, domain.end)"
|
||||
>
|
||||
{{ te(domain.labelKey) ? t(domain.labelKey) : domain.key }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UnifiedActionBar
|
||||
v-if="showActions"
|
||||
:presentation="actionPresentation"
|
||||
data-testid="workbench-progress-action-bar"
|
||||
@action="(item) => emit('action', item)"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs font-medium text-brand-700 underline-offset-2 hover:underline dark:text-brand-300"
|
||||
data-testid="workbench-progress-toggle-detail"
|
||||
@click="showDetailTrack = !showDetailTrack"
|
||||
>
|
||||
{{ showDetailTrack
|
||||
? t('chat.shippingProcessing.collapseHistory')
|
||||
: t('chat.shippingProcessing.expandHistory') }}
|
||||
</button>
|
||||
|
||||
<UnifiedProgressTrack
|
||||
v-if="showDetailTrack"
|
||||
:projection="projection"
|
||||
density="workbench"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* features/shipping-progress/components/presenters.spec.ts
|
||||
* 用途:四页面进度 Presenter 冒烟挂载。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import ChatProgressSummary from './ChatProgressSummary.vue';
|
||||
import SidebarProgressInline from './SidebarProgressInline.vue';
|
||||
import ReviewProgressStrip from './ReviewProgressStrip.vue';
|
||||
import ReviewProcessDetailDrawer from './ReviewProcessDetailDrawer.vue';
|
||||
import WorkbenchProgressGrouped from './WorkbenchProgressGrouped.vue';
|
||||
|
||||
function sampleProjection(): ShippingProcessingProjection {
|
||||
return {
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-1',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: 'OT-1',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'c1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'blocked',
|
||||
stage: 'waiting_review',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: {
|
||||
gateCode: 'order_review',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'open_order_review',
|
||||
blockingReasonCode: 'review_required',
|
||||
attemptNo: 1,
|
||||
},
|
||||
availableActions: ['open_order_review', 'refresh'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'a.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
};
|
||||
}
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingProcessing: {
|
||||
stage: { waiting_review: '订单复核' },
|
||||
status: { blocked: '已阻断' },
|
||||
progress: {
|
||||
completedOfTotal: '已完成 {done} / {total}',
|
||||
currentStage: '当前:{stage}',
|
||||
remainingHint: '后续还有 {count} 个阶段',
|
||||
positionOfTotal: '第 {current} / {total}',
|
||||
domainIntake: '解析与复核',
|
||||
domainInventory: '库存',
|
||||
domainFulfillment: '履约与上传',
|
||||
domainReceiveParse: '接收与解析',
|
||||
domainCandidateIdentity: '候选识别',
|
||||
domainOrderConfirm: '订单确认',
|
||||
domainInventoryHandle: '库存处理',
|
||||
domainFulfillmentShip: '发货履约',
|
||||
currentNeedLabel: '当前需要:',
|
||||
systemProcessingNeed: '系统处理中',
|
||||
viewProcessDetails: '查看流程详情',
|
||||
closeProcessDetails: '关闭',
|
||||
processDetailsTitle: '流程详情',
|
||||
nodeTime: '时间',
|
||||
nodeActor: '主体',
|
||||
placeholderDash: '—',
|
||||
viewFullAudit: '审计',
|
||||
},
|
||||
stageNode: {
|
||||
skipped: '已跳过',
|
||||
pending: '未开始',
|
||||
running: '进行中',
|
||||
passed: '已通过',
|
||||
blocked: '已阻断',
|
||||
failed: '失败',
|
||||
},
|
||||
gateReasons: {
|
||||
generic: '需要人工',
|
||||
review_required: '需要复核',
|
||||
},
|
||||
action: {
|
||||
open_order_review: '进入复核',
|
||||
open_order_processing: '进入订单处理',
|
||||
refresh: '刷新进度',
|
||||
more: '更多',
|
||||
},
|
||||
expandHistory: '展开',
|
||||
collapseHistory: '收起',
|
||||
panelTitle: '当前货代处理',
|
||||
},
|
||||
},
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
workflowReasons: { review_required: '需要复核' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('shipping progress presenters', () => {
|
||||
const projection = sampleProjection();
|
||||
|
||||
it('mounts ChatProgressSummary', () => {
|
||||
const wrapper = mount(ChatProgressSummary, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="chat-progress-summary"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('mounts SidebarProgressInline', () => {
|
||||
const wrapper = mount(SidebarProgressInline, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('mounts ReviewProgressStrip as compact five-domain readonly strip', () => {
|
||||
const wrapper = mount(ReviewProgressStrip, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-progress-strip"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('[data-testid="review-progress-domains"] [data-domain]').length).toBe(5);
|
||||
// 正文不得再挂 ActionBar / 页内完整 15 阶展开
|
||||
expect(wrapper.find('[data-testid="unified-action-bar"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-progress-expand-full"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-progress-nodes-strip"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-progress-open-details"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('mounts ReviewProcessDetailDrawer with readonly 15 nodes', () => {
|
||||
const wrapper = mount(ReviewProcessDetailDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
projection,
|
||||
poNumber: 'PO-1',
|
||||
orderTaskNo: 'OT-1',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: { Teleport: { template: '<div><slot /></div>' } },
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-process-detail-drawer"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('[data-testid="review-process-detail-node"]').length).toBe(15);
|
||||
expect(wrapper.text()).toContain('—');
|
||||
expect(wrapper.text()).not.toContain('重新处理');
|
||||
});
|
||||
|
||||
it('mounts WorkbenchProgressGrouped with domain groups', () => {
|
||||
const wrapper = mount(WorkbenchProgressGrouped, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="workbench-progress-grouped"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('[data-domain]').length).toBe(3);
|
||||
});
|
||||
});
|
||||
+15
-4
@@ -2,20 +2,31 @@
|
||||
* features/shipping-progress/composables/useProcessingActionPresentation.ts
|
||||
* 用途:包装 resolveProcessingActionPresentation,供 Vue 组件消费。
|
||||
* 依赖:vue computed、actionPresentation、ShippingProcessingProjection。
|
||||
* 逻辑:投影变化时重算;页面禁止自行按 status/stage 拼按钮。
|
||||
* 逻辑:投影变化时重算;页面禁止自行按 status/stage 拼按钮;可选 surface 过滤同页动作。
|
||||
*/
|
||||
|
||||
import { computed, type ComputedRef, type Ref } from 'vue';
|
||||
import { computed, unref, type ComputedRef, type MaybeRef, type Ref } from 'vue';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import { resolveProcessingActionPresentation } from '../actionPresentation';
|
||||
import type { ActionPresentation } from '../types';
|
||||
import type { ActionPresentation, ActionPresentationSurface } from '../types';
|
||||
|
||||
export interface UseProcessingActionPresentationOptions {
|
||||
surface?: ActionPresentationSurface;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从投影 ref 得到响应式 ActionPresentation。
|
||||
*
|
||||
* @param projection - 统一投影 ref
|
||||
* @param options - 可选 surface(chat/right/review/workbench)
|
||||
*/
|
||||
export function useProcessingActionPresentation(
|
||||
projection: Ref<ShippingProcessingProjection | null | undefined>
|
||||
| ComputedRef<ShippingProcessingProjection | null | undefined>,
|
||||
options?: MaybeRef<UseProcessingActionPresentationOptions | undefined>,
|
||||
): ComputedRef<ActionPresentation> {
|
||||
return computed(() => resolveProcessingActionPresentation(projection.value));
|
||||
return computed(() => resolveProcessingActionPresentation(
|
||||
projection.value,
|
||||
unref(options),
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* features/shipping-progress/gateReasonLabel.ts
|
||||
* 用途:将 Gate blockingReasonCode 解析为用户可读文案,禁止界面直接暴露内部码。
|
||||
* 依赖:vue-i18n TranslateResult 兼容的 t/te 函数。
|
||||
* 逻辑:优先 chat.shippingProcessing.gateReasons.* → workspace.shippingNotice.workflowReasons.*
|
||||
* → 通用兜底;永不回退为原始 code。
|
||||
*/
|
||||
|
||||
export type GateReasonI18n = {
|
||||
t: (key: string, values?: Record<string, unknown>) => string;
|
||||
te: (key: string) => boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析 Gate 阻断原因文案。
|
||||
*
|
||||
* 核心逻辑:多命名空间查找;未命中时返回「需要人工处理」类兜底,禁止展示内部码。
|
||||
*
|
||||
* @param code - blockingReasonCode
|
||||
* @param i18n - t / te
|
||||
* @returns 用户可读文案;无 code 时空串
|
||||
*/
|
||||
export function resolveGateReasonLabel(
|
||||
code: string | null | undefined,
|
||||
i18n: GateReasonI18n,
|
||||
): string {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return '';
|
||||
const keys = [
|
||||
`chat.shippingProcessing.gateReasons.${normalized}`,
|
||||
`workspace.shippingNotice.workflowReasons.${normalized}`,
|
||||
];
|
||||
for (const key of keys) {
|
||||
if (i18n.te(key)) return i18n.t(key);
|
||||
}
|
||||
return i18n.te('chat.shippingProcessing.gateReasons.generic')
|
||||
? i18n.t('chat.shippingProcessing.gateReasons.generic')
|
||||
: i18n.t('chat.shippingProcessing.status.blocked');
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
/**
|
||||
* features/shipping-progress/progressWindow.spec.ts
|
||||
* 用途:验收密度窗口切分与节点态推导。
|
||||
* 用途:验收密度窗口切分、stageNodes 优先与范围摘要。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
buildProgressRangeHint,
|
||||
buildProgressWindow,
|
||||
buildReviewProgressDomainSummary,
|
||||
computeProgressWindowRange,
|
||||
resolveStageNodeStatus,
|
||||
stageAbsoluteIndex,
|
||||
@@ -80,4 +82,40 @@ describe('progressWindow', () => {
|
||||
expect(start).toBeLessThanOrEqual(7);
|
||||
expect(end).toBeGreaterThan(7);
|
||||
});
|
||||
|
||||
it('prefers backend stageNodes status over index heuristic', () => {
|
||||
const nodes = buildProgressWindow(baseProjection({
|
||||
stage: 'inventory_source_resolving',
|
||||
status: 'processing',
|
||||
stageNodes: [
|
||||
{ stage: 'upload_received', absoluteIndex: 0, status: 'passed' },
|
||||
{ stage: 'inventory_source_resolving', absoluteIndex: 7, status: 'failed' },
|
||||
],
|
||||
}), 'workbench');
|
||||
expect(nodes[7]?.status).toBe('failed');
|
||||
});
|
||||
|
||||
it('buildProgressRangeHint returns done/total and current label key', () => {
|
||||
const hint = buildProgressRangeHint(baseProjection({
|
||||
stage: 'waiting_review',
|
||||
status: 'waiting_review',
|
||||
}), 'review');
|
||||
expect(hint).not.toBeNull();
|
||||
expect(hint!.currentLabelKey).toBe('chat.shippingProcessing.stage.waiting_review');
|
||||
expect(hint!.total).toBeGreaterThan(0);
|
||||
expect(hint!.done).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('buildReviewProgressDomainSummary maps waiting_review into order_confirm blocked', () => {
|
||||
const domains = buildReviewProgressDomainSummary(baseProjection({
|
||||
stage: 'waiting_review',
|
||||
status: 'blocked',
|
||||
}));
|
||||
expect(domains).toHaveLength(5);
|
||||
expect(domains[0]?.state).toBe('passed');
|
||||
expect(domains[1]?.state).toBe('passed');
|
||||
expect(domains[2]?.key).toBe('order_confirm');
|
||||
expect(domains[2]?.state).toBe('blocked');
|
||||
expect(domains[3]?.state).toBe('pending');
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/shipping-progress/progressWindow.ts
|
||||
* 用途:按密度从 15 阶中切出可见进度窗口,并推导节点执行态。
|
||||
* 依赖:SHIPPING_PROCESSING_STAGES / EML_ONLY / types ProgressDensity。
|
||||
* 逻辑:锚点为当前 stage;紧凑模式折叠窗口外节点与边缘 skipped;workbench 展示全 15 阶。
|
||||
* 用途:按密度从 15 阶中切出可见进度窗口,推导节点执行态,并提供订单台五域摘要。
|
||||
* 依赖:SHIPPING_PROCESSING_STAGES / EML_ONLY / types ProgressDensity·ProgressDomain*、shippingProcessingLabels。
|
||||
* 逻辑:锚点为当前 stage;stageNodes 优先;workbench=全 15 阶;五域供 ReviewProgressStrip 紧凑条。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -14,12 +14,25 @@ import {
|
||||
type ShippingProcessingStageNodeStatus,
|
||||
type ShippingProcessingStatus,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import {
|
||||
PROGRESS_DENSITY_WINDOW_SIZE,
|
||||
type ProgressDensity,
|
||||
type ProgressDomainState,
|
||||
type ProgressDomainSummaryItem,
|
||||
type ProgressRangeHint,
|
||||
type ProgressWindowNode,
|
||||
} from './types';
|
||||
|
||||
/** 订单处理工作台五域(0-based 含端点,对齐 15 阶)。 */
|
||||
export const REVIEW_PROGRESS_DOMAIN_RANGES = [
|
||||
{ key: 'receive_parse', labelKey: 'chat.shippingProcessing.progress.domainReceiveParse', start: 0, end: 2 },
|
||||
{ key: 'candidate_identity', labelKey: 'chat.shippingProcessing.progress.domainCandidateIdentity', start: 3, end: 7 },
|
||||
{ key: 'order_confirm', labelKey: 'chat.shippingProcessing.progress.domainOrderConfirm', start: 8, end: 9 },
|
||||
{ key: 'inventory', labelKey: 'chat.shippingProcessing.progress.domainInventoryHandle', start: 10, end: 11 },
|
||||
{ key: 'fulfillment', labelKey: 'chat.shippingProcessing.progress.domainFulfillmentShip', start: 12, end: 14 },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 返回 stage 在 15 阶中的下标;未知码回退 0。
|
||||
*/
|
||||
@@ -29,10 +42,26 @@ export function stageAbsoluteIndex(stage: string | null | undefined): number {
|
||||
return idx >= 0 ? idx : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从投影 stageNodes 查找指定阶的后端权威态。
|
||||
*/
|
||||
function resolveBackendNodeStatus(
|
||||
projection: ShippingProcessingProjection,
|
||||
stage: ShippingProcessingStage,
|
||||
absoluteIndex: number,
|
||||
): ShippingProcessingStageNodeStatus | null {
|
||||
const nodes = projection.stageNodes;
|
||||
if (!nodes?.length) return null;
|
||||
const matched = nodes.find((node) => (
|
||||
node.stage === stage || node.absoluteIndex === absoluteIndex
|
||||
));
|
||||
return matched?.status ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导单个节点执行态。
|
||||
*
|
||||
* 核心逻辑:direct_pdf 的 EML 专属阶 → skipped;当前阶按投影 status 映射;
|
||||
* 核心逻辑:stageNodes 优先;direct_pdf 的 EML 专属阶 → skipped;当前阶按投影 status 映射;
|
||||
* 已过阶 → passed;未到 → pending;失败/阻断仅落在当前阶。
|
||||
*/
|
||||
export function resolveStageNodeStatus(options: {
|
||||
@@ -41,7 +70,9 @@ export function resolveStageNodeStatus(options: {
|
||||
projectionStatus: ShippingProcessingStatus | string | null | undefined;
|
||||
sourceType?: OrderIntakeSourceType | string | null;
|
||||
stage: ShippingProcessingStage;
|
||||
backendStatus?: ShippingProcessingStageNodeStatus | null;
|
||||
}): ShippingProcessingStageNodeStatus {
|
||||
if (options.backendStatus) return options.backendStatus;
|
||||
const source = String(options.sourceType || '').trim().toLowerCase();
|
||||
if (source === 'direct_pdf' && EML_ONLY_PROCESSING_STAGES.has(options.stage)) {
|
||||
return 'skipped';
|
||||
@@ -77,6 +108,25 @@ export function computeProgressWindowRange(
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析单阶节点态(供窗口与范围摘要共用)。
|
||||
*/
|
||||
function resolveProjectionStageStatus(
|
||||
projection: ShippingProcessingProjection,
|
||||
stage: ShippingProcessingStage,
|
||||
absoluteIndex: number,
|
||||
currentIndex: number,
|
||||
): ShippingProcessingStageNodeStatus {
|
||||
return resolveStageNodeStatus({
|
||||
absoluteIndex,
|
||||
currentIndex,
|
||||
projectionStatus: projection.status,
|
||||
sourceType: projection.sourceType,
|
||||
stage,
|
||||
backendStatus: resolveBackendNodeStatus(projection, stage, absoluteIndex),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一投影构建密度窗口节点列表。
|
||||
*
|
||||
@@ -90,7 +140,6 @@ export function buildProgressWindow(
|
||||
if (!projection) return [];
|
||||
const currentIndex = stageAbsoluteIndex(projection.stage);
|
||||
const { start, end } = computeProgressWindowRange(currentIndex, density);
|
||||
const sourceType = projection.sourceType || null;
|
||||
const nodes: ProgressWindowNode[] = [];
|
||||
for (let i = start; i < end; i += 1) {
|
||||
const stage = SHIPPING_PROCESSING_STAGES[i]!;
|
||||
@@ -98,13 +147,7 @@ export function buildProgressWindow(
|
||||
stage,
|
||||
absoluteIndex: i,
|
||||
isCurrent: i === currentIndex,
|
||||
status: resolveStageNodeStatus({
|
||||
absoluteIndex: i,
|
||||
currentIndex,
|
||||
projectionStatus: projection.status,
|
||||
sourceType,
|
||||
stage,
|
||||
}),
|
||||
status: resolveProjectionStageStatus(projection, stage, i, currentIndex),
|
||||
});
|
||||
}
|
||||
// 紧凑模式:去掉窗口两端连续 skipped,避免空白占位。
|
||||
@@ -114,3 +157,77 @@ export function buildProgressWindow(
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建进度范围摘要(已完成 n/total、当前阶段键、窗口外剩余阶数)。
|
||||
*
|
||||
* @param projection - 统一投影
|
||||
* @param density - 页面密度(决定 hiddenAfter 计算窗口)
|
||||
* @returns 摘要 DTO;无投影时 null
|
||||
*/
|
||||
export function buildProgressRangeHint(
|
||||
projection: ShippingProcessingProjection | null | undefined,
|
||||
density: ProgressDensity,
|
||||
): ProgressRangeHint | null {
|
||||
if (!projection) return null;
|
||||
const currentIndex = stageAbsoluteIndex(projection.stage);
|
||||
let done = 0;
|
||||
let total = 0;
|
||||
for (let i = 0; i < SHIPPING_PROCESSING_STAGES.length; i += 1) {
|
||||
const stage = SHIPPING_PROCESSING_STAGES[i]!;
|
||||
const status = resolveProjectionStageStatus(projection, stage, i, currentIndex);
|
||||
if (status === 'skipped') continue;
|
||||
total += 1;
|
||||
if (status === 'passed') done += 1;
|
||||
}
|
||||
const { end } = computeProgressWindowRange(currentIndex, density);
|
||||
const hiddenAfter = Math.max(0, SHIPPING_PROCESSING_STAGES.length - end);
|
||||
return {
|
||||
done,
|
||||
total,
|
||||
currentLabelKey: shippingProcessingStageKey(projection.stage),
|
||||
hiddenAfter,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建订单处理工作台五域摘要(默认紧凑条用,非完整 15 阶)。
|
||||
*
|
||||
* 核心逻辑:当前索引落在域内 → current/blocked/failed;整域已过 → passed;否则 pending。
|
||||
*/
|
||||
export function buildReviewProgressDomainSummary(
|
||||
projection: ShippingProcessingProjection | null | undefined,
|
||||
): ProgressDomainSummaryItem[] {
|
||||
if (!projection) return [];
|
||||
const currentIndex = stageAbsoluteIndex(projection.stage);
|
||||
const statusNorm = String(projection.status || '').trim().toLowerCase();
|
||||
return REVIEW_PROGRESS_DOMAIN_RANGES.map((domain) => {
|
||||
let state: ProgressDomainState = 'pending';
|
||||
if (currentIndex > domain.end) {
|
||||
state = 'passed';
|
||||
} else if (currentIndex >= domain.start && currentIndex <= domain.end) {
|
||||
if (statusNorm === 'failed' || statusNorm === 'cancelled') state = 'failed';
|
||||
else if (statusNorm === 'blocked' || statusNorm === 'waiting_review' || statusNorm === 'needs_action') {
|
||||
state = 'blocked';
|
||||
} else {
|
||||
state = 'current';
|
||||
}
|
||||
}
|
||||
return {
|
||||
key: domain.key,
|
||||
labelKey: domain.labelKey,
|
||||
start: domain.start,
|
||||
end: domain.end,
|
||||
state,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整 15 阶窗口(流程详情抽屉专用)。
|
||||
*/
|
||||
export function buildFullProgressNodes(
|
||||
projection: ShippingProcessingProjection | null | undefined,
|
||||
): ProgressWindowNode[] {
|
||||
return buildProgressWindow(projection, 'workbench');
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/shipping-progress/types.ts
|
||||
* 用途:统一进度轨道与动作栏的前端 DTO(密度、窗口节点、ActionPresentation)。
|
||||
* 用途:统一进度轨道与动作栏的前端 DTO(密度、窗口节点、五域摘要、ActionPresentation)。
|
||||
* 依赖:shipping.api.types 的 Stage / StageNodeStatus / ActionIntent。
|
||||
* 逻辑:供 progressWindow / actionPresentation / Unified* 组件共用;禁止页面私自发明状态码。
|
||||
* 逻辑:供 progressWindow / actionPresentation / Unified* / ReviewProgressStrip 共用;禁止页面私自发明状态码。
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -47,3 +47,26 @@ export interface ActionPresentation {
|
||||
secondary: ActionPresentationItem | null;
|
||||
overflow: ActionPresentationItem[];
|
||||
}
|
||||
|
||||
/** 动作栏页面上下文(UI-07:同页隐藏冗余 intent)。 */
|
||||
export type ActionPresentationSurface = 'chat' | 'right' | 'review' | 'workbench';
|
||||
|
||||
/** 进度范围摘要(UI-03:已完成 n/total + 剩余提示)。 */
|
||||
export interface ProgressRangeHint {
|
||||
done: number;
|
||||
total: number;
|
||||
currentLabelKey: string;
|
||||
hiddenAfter: number;
|
||||
}
|
||||
|
||||
/** 订单处理工作台五域摘要状态。 */
|
||||
export type ProgressDomainState = 'passed' | 'current' | 'pending' | 'blocked' | 'failed';
|
||||
|
||||
/** 订单处理工作台五域摘要项。 */
|
||||
export interface ProgressDomainSummaryItem {
|
||||
key: string;
|
||||
labelKey: string;
|
||||
start: number;
|
||||
end: number;
|
||||
state: ProgressDomainState;
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskCenterPage.vue
|
||||
* 用途:发货「我的待办」壳——Pending|Processing|Done + 识别 Run 续办表 + 右侧任务工作台或复核深链。
|
||||
* 依赖:shipping-tasks.api(my-todos)、shipping.api 详情、ShippingTaskWorkbench、ShippingRunProgressTable、useShippingTodoBadge。
|
||||
* 逻辑:review_case 项用 review_run_no 打开人工复核;task 项打开任务处理工作台;
|
||||
* 轮询仅依据 shipping_processing_status / process_status / Intake parse_status,
|
||||
* 不回退 WorkflowItem lifecycle;created/queued/parsing Intake 持续刷新。
|
||||
* 用途:发货「任务中心」壳——Pending|Processing|Done + 识别 Run 续办表;仅列表入口。
|
||||
* 依赖:shipping-tasks.api(my-todos)、shipping.api 详情(直链摘要)、ShippingRunProgressTable、useShippingTodoBadge、
|
||||
* shippingProcessingLabels。
|
||||
* 逻辑:选中项展示入口卡 + 统一进度紧凑摘要(UI-03);唯一主按钮深链「订单处理工作台」或对话;
|
||||
* 不内嵌 ShippingTaskWorkbench;轮询依据 shipping_processing_status /
|
||||
* process_status / Intake parse_status。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ExternalLink, RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
getWorkspaceShippingTask,
|
||||
listShippingChatAgents,
|
||||
@@ -27,13 +29,19 @@ import {
|
||||
IN_PROGRESS_PROCESSING_STATUSES,
|
||||
TERMINAL_PROCESSING_STATUSES,
|
||||
} from '@/features/chat/shipping/shippingProcessingFulfillment';
|
||||
import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { stageAbsoluteIndex } from '@/features/shipping-progress/progressWindow';
|
||||
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
|
||||
import {
|
||||
IN_PROGRESS_PROCESS,
|
||||
isShippingTodoListItemInProgress,
|
||||
} from './shippingTaskCenterPolling';
|
||||
import ShippingTaskWorkbench from './ShippingTaskWorkbench.vue';
|
||||
import ShippingRunProgressTable from './ShippingRunProgressTable.vue';
|
||||
|
||||
const { t, te } = useI18n();
|
||||
/** 进行中 Workflow/Task 前台轮询间隔。 */
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
/** 页面隐藏时后台轮询间隔。 */
|
||||
@@ -70,7 +78,7 @@ const { refreshShippingTodoBadge } = useShippingTodoBadge();
|
||||
/** todos=建单后待办;runs=建单前识别续办 */
|
||||
const surface = ref<'todos' | 'runs'>('todos');
|
||||
const bucket = ref<'pending' | 'processing' | 'done'>('pending');
|
||||
const filterTodoCategory = ref<'all' | 'review' | 'exception' | 'manual_upload'>('all');
|
||||
const filterTodoCategory = ref<'all' | 'review' | 'exception' | 'manual_upload' | 'intake_parse'>('all');
|
||||
const filterCustomer = ref('');
|
||||
const filterTaskNo = ref('');
|
||||
const appliedFilters = ref({
|
||||
@@ -82,6 +90,7 @@ const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const tasks = ref<ShippingTaskSummary[]>([]);
|
||||
const selectedRef = ref<string | null>(null);
|
||||
/** 仅直链摘要,供入口卡展示;禁止内嵌履约工作台。 */
|
||||
const detail = ref<ShippingTaskDetail | null>(null);
|
||||
const currentPage = ref(1);
|
||||
const pageSize = 20;
|
||||
@@ -97,11 +106,9 @@ let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollInFlight = false;
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(totalTasks.value / pageSize)));
|
||||
const canHandle = computed(() => detail.value?.can_handle !== false);
|
||||
const preferredTaskNo = computed(() =>
|
||||
String(route.params.taskNo || route.query.task_no || '').trim().toUpperCase(),
|
||||
);
|
||||
const preferredReviewRun = computed(() => String(route.query.run_no || '').trim());
|
||||
const isDirectTaskRoute = computed(() => Boolean(String(route.params.taskNo || '').trim()));
|
||||
|
||||
const selectedItem = computed(() =>
|
||||
@@ -111,6 +118,53 @@ const isReviewSelection = computed(() => selectedItem.value?.item_kind === 'revi
|
||||
|| Boolean(selectedItem.value?.review_run_no && !selectedItem.value?.task_no));
|
||||
const isIntakeSelection = computed(() => selectedItem.value?.item_kind === 'order_intake'
|
||||
|| Boolean(selectedItem.value?.intake_no && !selectedItem.value?.task_no && !selectedItem.value?.review_run_no));
|
||||
/** 建单后 Notice/OT 任务选中(列表项或直链详情)。 */
|
||||
const isTaskSelection = computed(() => {
|
||||
if (isDirectTaskRoute.value && detail.value) return true;
|
||||
if (!selectedItem.value) return false;
|
||||
return !isReviewSelection.value && !isIntakeSelection.value && Boolean(selectedItem.value.task_no);
|
||||
});
|
||||
|
||||
/**
|
||||
* 入口卡展示对象:优先列表选中项,直链时回退详情摘要。
|
||||
*/
|
||||
const entryItem = computed((): ShippingTaskSummary | ShippingTaskDetail | null => {
|
||||
if (selectedItem.value) return selectedItem.value;
|
||||
if (detail.value) return detail.value;
|
||||
return null;
|
||||
});
|
||||
|
||||
/**
|
||||
* 任务中心选中项的统一进度紧凑摘要(UI-03):阶段 · n/15 + 阻断文案。
|
||||
*/
|
||||
const entryProgressSummary = computed(() => {
|
||||
const item = entryItem.value;
|
||||
if (!item) return null;
|
||||
const stage = String(
|
||||
('shipping_processing_stage' in item ? item.shipping_processing_stage : null)
|
||||
|| '',
|
||||
).trim();
|
||||
const status = String(item.shipping_processing_status || '').trim();
|
||||
if (!stage && !status) return null;
|
||||
const stageKey = shippingProcessingStageKey(stage || '');
|
||||
const stageLabel = stage && te(stageKey) ? t(stageKey) : (stage || resolveShippingProcessingStatusLabel(status, te, t));
|
||||
const index = stage ? stageAbsoluteIndex(stage) + 1 : 0;
|
||||
const gateCode = String(
|
||||
item.ui_state?.process_gate?.current_blocking_gate?.blocking_reason_code
|
||||
|| item.ui_state?.process_gate?.blocking_reason_code
|
||||
|| '',
|
||||
).trim();
|
||||
const blocker = resolveGateReasonLabel(gateCode, { t, te });
|
||||
return {
|
||||
stageLabel,
|
||||
index,
|
||||
total: 15,
|
||||
statusLabel: resolveShippingProcessingStatusLabel(status, te, t),
|
||||
blocker,
|
||||
poNumber: String(item.po_number || '').trim() || null,
|
||||
customerName: String(item.customer_name || '').trim() || null,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 待办列表项稳定主键:复核用 case_no,Intake 用 intake_no,任务用 task_no。
|
||||
@@ -139,12 +193,12 @@ function todoDisplayNo(item: ShippingTaskSummary): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否应继续自动轮询:processing 桶、进行中详情,或 runs 面;列表项按统一投影 / process_status。
|
||||
* 是否应继续自动轮询:processing 桶、进行中直链详情,或 runs 面;列表项按统一投影 / process_status。
|
||||
*/
|
||||
const shouldAutoRefresh = computed(() => {
|
||||
if (surface.value === 'runs') return true;
|
||||
if (bucket.value === 'processing') return true;
|
||||
if (isDetailInProgress(detail.value)) return true;
|
||||
if (isDirectTaskRoute.value && isDetailInProgress(detail.value)) return true;
|
||||
return tasks.value.some((item) => isListItemInProgress(item));
|
||||
});
|
||||
|
||||
@@ -169,7 +223,7 @@ function stopAutoRefresh() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 调度下一次自动刷新(仅进行中 Workflow/Task)。
|
||||
* 调度下一次自动刷新(仅进行中项)。
|
||||
*/
|
||||
function scheduleAutoRefresh() {
|
||||
stopAutoRefresh();
|
||||
@@ -192,7 +246,7 @@ function scheduleAutoRefresh() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析货代 Chat Agent,供复核/会话深链。
|
||||
* 解析货代 Chat Agent,供订单处理/会话深链。
|
||||
*/
|
||||
async function resolveChatAgent() {
|
||||
try {
|
||||
@@ -231,7 +285,7 @@ function applyFilters() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空筛选条件并重新拉取列表。
|
||||
* 清空筛选并重载。
|
||||
*/
|
||||
function resetFilters() {
|
||||
filterTodoCategory.value = 'all';
|
||||
@@ -242,35 +296,29 @@ function resetFilters() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前 bucket 分页拉取「我的待办」;优先选中路由 task_no / run_no。
|
||||
* 拉取当前桶待办列表。
|
||||
* @param resetPage - 切换桶时重置到第一页
|
||||
*/
|
||||
async function loadTodos(resetPage = false) {
|
||||
if (resetPage) currentPage.value = 1;
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await listWorkspaceShippingMyTodos({
|
||||
const category = appliedFilters.value.todo_category || undefined;
|
||||
const result = await listWorkspaceShippingMyTodos({
|
||||
bucket: bucket.value,
|
||||
page: currentPage.value,
|
||||
page_size: pageSize,
|
||||
...(appliedFilters.value.todo_category ? { todo_category: appliedFilters.value.todo_category } : {}),
|
||||
...(appliedFilters.value.customer ? { customer: appliedFilters.value.customer } : {}),
|
||||
...(appliedFilters.value.task_no ? { task_no: appliedFilters.value.task_no } : {}),
|
||||
todo_category: category as 'review' | 'exception' | 'manual_upload' | 'intake_parse' | undefined,
|
||||
customer: appliedFilters.value.customer || undefined,
|
||||
task_no: appliedFilters.value.task_no || undefined,
|
||||
});
|
||||
tasks.value = res.items || [];
|
||||
totalTasks.value = Number(res.total || 0);
|
||||
const byTask = preferredTaskNo.value
|
||||
? tasks.value.find((item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value)
|
||||
: null;
|
||||
const byRun = preferredReviewRun.value
|
||||
? tasks.value.find((item) => String(item.review_run_no || '') === preferredReviewRun.value)
|
||||
: null;
|
||||
const preferred = byTask || byRun;
|
||||
if (preferred) {
|
||||
selectedRef.value = todoItemKey(preferred);
|
||||
} else if (selectedRef.value && !tasks.value.some((item) => todoItemKey(item) === selectedRef.value)) {
|
||||
selectedRef.value = tasks.value[0] ? todoItemKey(tasks.value[0]) : null;
|
||||
} else if (!selectedRef.value && tasks.value[0]) {
|
||||
selectedRef.value = todoItemKey(tasks.value[0]);
|
||||
tasks.value = result.items || [];
|
||||
totalTasks.value = Number(result.total || 0);
|
||||
if (preferredTaskNo.value && !selectedRef.value) {
|
||||
const hit = tasks.value.find(
|
||||
(item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value,
|
||||
);
|
||||
if (hit) selectedRef.value = todoItemKey(hit);
|
||||
}
|
||||
} catch {
|
||||
tasks.value = [];
|
||||
@@ -281,7 +329,7 @@ async function loadTodos(resetPage = false) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取任务详情;复核项不拉 Task API。
|
||||
* 直链场景拉取任务摘要(仅入口卡,不挂工作台)。
|
||||
*/
|
||||
async function loadDetail(taskNo: string) {
|
||||
detailLoading.value = true;
|
||||
@@ -295,30 +343,20 @@ async function loadDetail(taskNo: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表与详情联动刷新。
|
||||
* @param options.silent - 轮询时不强制切换 loading 闪烁(详情仍更新)
|
||||
* 列表与(可选)直链摘要联动刷新。
|
||||
*/
|
||||
async function refreshAll(options?: { silent?: boolean }) {
|
||||
const silent = Boolean(options?.silent);
|
||||
if (!silent) {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
} else {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
}
|
||||
async function refreshAll(_options?: { silent?: boolean }) {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
if (isDirectTaskRoute.value && preferredTaskNo.value) {
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
return;
|
||||
}
|
||||
const item = selectedItem.value;
|
||||
if (item?.task_no && item.item_kind !== 'review_case') {
|
||||
await loadDetail(item.task_no);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开人工复核工作台(Chat 主区替换为 order-review 模式)。
|
||||
* 打开订单处理工作台(Chat 主区 order-review;单 OT 全生命周期)。
|
||||
* 任务中心仅作列表入口,禁止在本页履约写操作。
|
||||
*/
|
||||
function openReview(item: ShippingTaskSummary) {
|
||||
function openOrderProcessing(item: ShippingTaskSummary | ShippingTaskDetail) {
|
||||
const runNo = String(item.review_run_no || '').trim();
|
||||
if (!runNo) return;
|
||||
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
|
||||
@@ -334,6 +372,16 @@ function openReview(item: ShippingTaskSummary) {
|
||||
void router.push({ path: `/chat/${agentId}`, query });
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前入口是否可深链订单处理工作台。
|
||||
*/
|
||||
function canOpenOrderProcessing(item: ShippingTaskSummary | ShippingTaskDetail | null): boolean {
|
||||
if (!item) return false;
|
||||
const runNo = String(item.review_run_no || '').trim();
|
||||
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
|
||||
return Boolean(runNo && agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开对话「本次处理中」卡,聚焦未建 OT 的 Intake 材料。
|
||||
*/
|
||||
@@ -351,37 +399,40 @@ function openIntakeConversation(item: ShippingTaskSummary) {
|
||||
/**
|
||||
* 可选深链:打开 Chat 会话查看上下文(非履约写入口)。
|
||||
*/
|
||||
function openInChat() {
|
||||
if (!chatAgentId.value || !detail.value) return;
|
||||
const query: Record<string, string> = { task_id: detail.value.task_no };
|
||||
const batchNo = String(detail.value.batch_no || '').trim();
|
||||
function openInChat(item?: ShippingTaskSummary | ShippingTaskDetail | null) {
|
||||
const row = item || entryItem.value;
|
||||
if (!chatAgentId.value || !row) return;
|
||||
const query: Record<string, string> = {};
|
||||
const taskNo = String(row.task_no || '').trim();
|
||||
const orderTaskNo = String(row.order_task_no || '').trim();
|
||||
if (taskNo) query.task_id = taskNo;
|
||||
if (orderTaskNo) query.focus_task_no = orderTaskNo;
|
||||
const batchNo = String(('batch_no' in row ? row.batch_no : '') || '').trim();
|
||||
if (batchNo) query.batch_no = batchNo;
|
||||
const cid = String(detail.value.conversation_id || '').trim();
|
||||
const cid = String(row.conversation_id || '').trim();
|
||||
if (/^[0-9a-f]{32}$/i.test(cid)) query.conversation_id = cid;
|
||||
void router.push({ path: `/chat/${chatAgentId.value}`, query });
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中列表项:复核显示入口卡;任务加载工作台详情。
|
||||
* 选中列表项:仅更新选中态与 query;不拉详情工作台。
|
||||
*/
|
||||
async function selectTodo(item: ShippingTaskSummary) {
|
||||
selectedRef.value = todoItemKey(item);
|
||||
detail.value = null;
|
||||
const nextQuery: Record<string, string> = { ...route.query as Record<string, string> };
|
||||
if (item.item_kind === 'review_case' || item.review_run_no) {
|
||||
if (item.item_kind === 'review_case' || (item.review_run_no && !item.task_no)) {
|
||||
delete nextQuery.task_no;
|
||||
delete nextQuery.intake_no;
|
||||
if (item.review_run_no) nextQuery.run_no = String(item.review_run_no);
|
||||
detail.value = null;
|
||||
} else if (item.item_kind === 'order_intake' || item.intake_no) {
|
||||
delete nextQuery.task_no;
|
||||
delete nextQuery.run_no;
|
||||
if (item.intake_no) nextQuery.intake_no = String(item.intake_no);
|
||||
detail.value = null;
|
||||
} else if (item.task_no) {
|
||||
delete nextQuery.run_no;
|
||||
delete nextQuery.intake_no;
|
||||
nextQuery.task_no = item.task_no;
|
||||
await loadDetail(item.task_no);
|
||||
}
|
||||
void router.replace({
|
||||
name: route.name || 'workspace-shipping-my-tasks',
|
||||
@@ -403,27 +454,20 @@ watch(bucket, () => {
|
||||
|
||||
watch(selectedItem, (item) => {
|
||||
if (!item) {
|
||||
detail.value = null;
|
||||
if (!isDirectTaskRoute.value) detail.value = null;
|
||||
return;
|
||||
}
|
||||
if (
|
||||
item.item_kind === 'review_case'
|
||||
|| item.item_kind === 'order_intake'
|
||||
|| (item.review_run_no && !item.task_no)
|
||||
|| (item.intake_no && !item.task_no)
|
||||
) {
|
||||
detail.value = null;
|
||||
return;
|
||||
}
|
||||
if (item.task_no && detail.value?.task_no !== item.task_no) {
|
||||
void loadDetail(item.task_no);
|
||||
}
|
||||
// 列表选中不拉详情;履约写一律走订单处理工作台。
|
||||
detail.value = null;
|
||||
});
|
||||
|
||||
watch(shouldAutoRefresh, () => {
|
||||
scheduleAutoRefresh();
|
||||
});
|
||||
|
||||
/**
|
||||
* 页面可见性变化时重排轮询间隔。
|
||||
*/
|
||||
function onVisibilityChange() {
|
||||
scheduleAutoRefresh();
|
||||
}
|
||||
@@ -436,7 +480,9 @@ onMounted(async () => {
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
} else {
|
||||
const hit = tasks.value.find((item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value);
|
||||
if (!hit) {
|
||||
if (hit) {
|
||||
selectedRef.value = todoItemKey(hit);
|
||||
} else {
|
||||
selectedRef.value = preferredTaskNo.value;
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
}
|
||||
@@ -488,237 +534,311 @@ onBeforeUnmount(() => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="isDirectTaskRoute" class="rounded-2xl border border-default bg-surface p-4">
|
||||
<div
|
||||
v-if="isDirectTaskRoute"
|
||||
class="rounded-2xl border border-default bg-surface p-4"
|
||||
data-testid="my-todos-direct-task-entry"
|
||||
>
|
||||
<div v-if="detailLoading" class="py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!detail" class="py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.selectCase') }}
|
||||
</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ detail.task_no }}</div>
|
||||
<div v-else class="space-y-4">
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ detail.task_no }}</div>
|
||||
<p class="text-sm text-secondary">
|
||||
{{ detail.ui_state?.summary?.message || detail.ui_state?.summary?.current_todo || $t('workspace.shippingNotice.myTodos.openProcessingHint') }}
|
||||
</p>
|
||||
<p class="text-xs text-muted">
|
||||
{{ $t('workspace.shippingNotice.myTodos.openProcessingHint') }}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!canOpenOrderProcessing(detail)"
|
||||
data-testid="my-todos-open-order-processing"
|
||||
@click="openOrderProcessing(detail)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="chatAgentId"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary hover:bg-surface-soft"
|
||||
@click="openInChat"
|
||||
@click="openInChat(detail)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.openChat') }}
|
||||
</button>
|
||||
</div>
|
||||
<ShippingTaskWorkbench :detail="detail" :can-handle="canHandle" @refreshed="() => refreshAll()" />
|
||||
<p
|
||||
v-if="!canOpenOrderProcessing(detail)"
|
||||
class="text-xs text-amber-700 dark:text-amber-300"
|
||||
data-testid="my-todos-open-processing-unavailable"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.openProcessingUnavailable') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingRunProgressTable v-else-if="surface === 'runs'" />
|
||||
|
||||
<template v-else>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="key in (['pending', 'processing', 'done'] as const)"
|
||||
:key="key"
|
||||
type="button"
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium"
|
||||
:class="bucket === key ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
|
||||
@click="bucket = key"
|
||||
>
|
||||
{{ $t(`workspace.shippingNotice.myTodos.buckets.${key}`) }}
|
||||
<span class="ml-1 opacity-80">({{ bucketCounts[key] }})</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3">
|
||||
<label v-if="bucket === 'pending'" class="space-y-1">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.todoCategory') }}</span>
|
||||
<select v-model="filterTodoCategory" class="input-field text-sm min-w-[9rem]">
|
||||
<option value="all">{{ $t('workspace.shippingNotice.myTodos.filters.all') }}</option>
|
||||
<option value="review">{{ $t('workspace.shippingNotice.myTodos.filters.review') }}</option>
|
||||
<option value="exception">{{ $t('workspace.shippingNotice.myTodos.filters.exception') }}</option>
|
||||
<option value="manual_upload">{{ $t('workspace.shippingNotice.myTodos.filters.manualUpload') }}</option>
|
||||
<option value="intake_parse">{{ $t('workspace.shippingNotice.myTodos.filters.intakeParse') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1 flex-1 min-w-[10rem]">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.customer') }}</span>
|
||||
<input
|
||||
v-model="filterCustomer"
|
||||
type="text"
|
||||
class="input-field text-sm w-full"
|
||||
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
|
||||
@keyup.enter="applyFilters"
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1 flex-1 min-w-[10rem]">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.taskNo') }}</span>
|
||||
<input
|
||||
v-model="filterTaskNo"
|
||||
type="text"
|
||||
class="input-field text-sm w-full font-mono uppercase"
|
||||
:placeholder="$t('workspace.shippingNotice.myTodos.filters.taskNoPlaceholder')"
|
||||
@keyup.enter="applyFilters"
|
||||
/>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="key in (['pending', 'processing', 'done'] as const)"
|
||||
:key="key"
|
||||
type="button"
|
||||
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="applyFilters"
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium"
|
||||
:class="bucket === key ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
|
||||
@click="bucket = key"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="resetFilters"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.reset') }}
|
||||
{{ $t(`workspace.shippingNotice.myTodos.buckets.${key}`) }}
|
||||
<span class="ml-1 opacity-80">({{ bucketCounts[key] }})</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-5 lg:grid-cols-[minmax(18rem,0.85fr)_minmax(0,2.15fr)]">
|
||||
<div class="space-y-2">
|
||||
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!tasks.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.myTodos.empty') }}
|
||||
</div>
|
||||
<button
|
||||
v-for="item in tasks"
|
||||
:key="todoItemKey(item)"
|
||||
type="button"
|
||||
class="w-full rounded-2xl border px-4 py-3 text-left transition-colors"
|
||||
:class="selectedRef === todoItemKey(item) ? 'border-brand-400 bg-brand-50/60' : 'border-default hover:bg-surface-soft/70'"
|
||||
@click="selectTodo(item)"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-mono text-sm font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
|
||||
<span
|
||||
v-if="item.todo_category === 'review' || item.item_kind === 'review_case'"
|
||||
class="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] text-amber-700"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="item.todo_category === 'intake_parse' || item.item_kind === 'order_intake'"
|
||||
class="rounded-full bg-violet-50 px-2 py-0.5 text-[10px] text-violet-700"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="item.can_handle === false"
|
||||
class="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] text-slate-600"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.todo.adminViewOnlyShort') }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 truncate text-sm text-secondary">
|
||||
{{ item.ui_state?.summary?.current_todo || item.ui_state?.summary?.title || item.process_status }}
|
||||
</div>
|
||||
<div class="mt-1 truncate text-xs text-muted">
|
||||
{{ item.customer_name || item.source_file_name || item.review_run_no || '—' }}
|
||||
</div>
|
||||
</button>
|
||||
<div v-if="totalPages > 1" class="flex items-center justify-between gap-2 pt-2 text-xs text-muted">
|
||||
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3">
|
||||
<label v-if="bucket === 'pending'" class="space-y-1">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.todoCategory') }}</span>
|
||||
<select v-model="filterTodoCategory" class="input-field text-sm min-w-[9rem]">
|
||||
<option value="all">{{ $t('workspace.shippingNotice.myTodos.filters.all') }}</option>
|
||||
<option value="review">{{ $t('workspace.shippingNotice.myTodos.filters.review') }}</option>
|
||||
<option value="exception">{{ $t('workspace.shippingNotice.myTodos.filters.exception') }}</option>
|
||||
<option value="manual_upload">{{ $t('workspace.shippingNotice.myTodos.filters.manualUpload') }}</option>
|
||||
<option value="intake_parse">{{ $t('workspace.shippingNotice.myTodos.filters.intakeParse') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1 flex-1 min-w-[10rem]">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.customer') }}</span>
|
||||
<input
|
||||
v-model="filterCustomer"
|
||||
type="text"
|
||||
class="input-field text-sm w-full"
|
||||
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
|
||||
@keyup.enter="applyFilters"
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1 flex-1 min-w-[10rem]">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.taskNo') }}</span>
|
||||
<input
|
||||
v-model="filterTaskNo"
|
||||
type="text"
|
||||
class="input-field text-sm w-full font-mono uppercase"
|
||||
:placeholder="$t('workspace.shippingNotice.myTodos.filters.taskNoPlaceholder')"
|
||||
@keyup.enter="applyFilters"
|
||||
/>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="currentPage <= 1 || loading"
|
||||
@click="currentPage -= 1; loadTodos()"
|
||||
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="applyFilters"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.pagination.previous') }}
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
|
||||
</button>
|
||||
<span>{{ currentPage }}/{{ totalPages }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="currentPage >= totalPages || loading"
|
||||
@click="currentPage += 1; loadTodos()"
|
||||
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="resetFilters"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.pagination.next') }}
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.reset') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div
|
||||
v-if="isReviewSelection && selectedItem"
|
||||
class="space-y-4 rounded-2xl border border-default bg-surface p-6"
|
||||
>
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ todoDisplayNo(selectedItem) }}</div>
|
||||
<p class="text-sm text-secondary">
|
||||
{{ selectedItem.ui_state?.summary?.message || selectedItem.ui_state?.summary?.current_todo }}
|
||||
</p>
|
||||
<p v-if="selectedItem.source_file_name" class="text-xs text-muted">
|
||||
{{ selectedItem.source_file_name }}
|
||||
<span v-if="selectedItem.review_run_no"> · {{ selectedItem.review_run_no }}</span>
|
||||
</p>
|
||||
<div class="grid gap-5 lg:grid-cols-[minmax(18rem,0.85fr)_minmax(0,2.15fr)]">
|
||||
<div class="space-y-2">
|
||||
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!tasks.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.myTodos.empty') }}
|
||||
</div>
|
||||
<button
|
||||
v-for="item in tasks"
|
||||
:key="todoItemKey(item)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!selectedItem.review_run_no || !(selectedItem.owner_agent_id || chatAgentId)"
|
||||
@click="openReview(selectedItem)"
|
||||
class="w-full rounded-2xl border px-4 py-3 text-left transition-colors"
|
||||
:class="selectedRef === todoItemKey(item) ? 'border-brand-400 bg-brand-50/60' : 'border-default hover:bg-surface-soft/70'"
|
||||
@click="selectTodo(item)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-mono text-sm font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
|
||||
<span
|
||||
v-if="item.todo_category === 'review' || item.item_kind === 'review_case'"
|
||||
class="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] text-amber-700"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="item.todo_category === 'intake_parse' || item.item_kind === 'order_intake'"
|
||||
class="rounded-full bg-violet-50 px-2 py-0.5 text-[10px] text-violet-700"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="item.can_handle === false"
|
||||
class="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] text-slate-600"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.todo.adminViewOnlyShort') }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 truncate text-sm text-secondary">
|
||||
{{ item.ui_state?.summary?.current_todo || item.ui_state?.summary?.title || item.process_status }}
|
||||
</div>
|
||||
<div class="mt-1 truncate text-xs text-muted">
|
||||
{{ item.customer_name || item.source_file_name || item.review_run_no || '—' }}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="isIntakeSelection && selectedItem"
|
||||
class="space-y-4 rounded-2xl border border-default bg-surface p-6"
|
||||
data-testid="my-todos-intake-selection"
|
||||
>
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ todoDisplayNo(selectedItem) }}</div>
|
||||
<p class="text-sm text-secondary">
|
||||
{{ selectedItem.ui_state?.summary?.message || selectedItem.ui_state?.summary?.current_todo }}
|
||||
</p>
|
||||
<p v-if="selectedItem.source_file_name" class="text-xs text-muted">
|
||||
{{ selectedItem.source_file_name }}
|
||||
<span v-if="selectedItem.intake_parse_status"> · {{ selectedItem.intake_parse_status }}</span>
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!(selectedItem.owner_agent_id || chatAgentId)"
|
||||
data-testid="my-todos-open-intake-conversation"
|
||||
@click="openIntakeConversation(selectedItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openConversation') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="detailLoading" class="rounded-2xl border border-dashed border-default py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!detail" class="rounded-2xl border border-dashed border-default py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.selectCase') }}
|
||||
</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ detail.task_no }}</div>
|
||||
<div v-if="totalPages > 1" class="flex items-center justify-between gap-2 pt-2 text-xs text-muted">
|
||||
<button
|
||||
v-if="chatAgentId"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary hover:bg-surface-soft"
|
||||
@click="openInChat"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="currentPage <= 1 || loading"
|
||||
@click="currentPage -= 1; loadTodos()"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.openChat') }}
|
||||
{{ $t('workspace.shippingNotice.pagination.previous') }}
|
||||
</button>
|
||||
<span>{{ currentPage }}/{{ totalPages }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="currentPage >= totalPages || loading"
|
||||
@click="currentPage += 1; loadTodos()"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.pagination.next') }}
|
||||
</button>
|
||||
</div>
|
||||
<ShippingTaskWorkbench
|
||||
:detail="detail"
|
||||
:can-handle="canHandle"
|
||||
@refreshed="() => refreshAll()"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div
|
||||
v-if="isReviewSelection && selectedItem"
|
||||
class="space-y-4 rounded-2xl border border-default bg-surface p-6"
|
||||
data-testid="my-todos-review-selection"
|
||||
>
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ todoDisplayNo(selectedItem) }}</div>
|
||||
<p class="text-sm text-secondary">
|
||||
{{ selectedItem.ui_state?.summary?.message || selectedItem.ui_state?.summary?.current_todo }}
|
||||
</p>
|
||||
<p v-if="selectedItem.source_file_name" class="text-xs text-muted">
|
||||
{{ selectedItem.source_file_name }}
|
||||
<span v-if="selectedItem.review_run_no"> · {{ selectedItem.review_run_no }}</span>
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!canOpenOrderProcessing(selectedItem)"
|
||||
data-testid="my-todos-open-order-processing"
|
||||
@click="openOrderProcessing(selectedItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="isIntakeSelection && selectedItem"
|
||||
class="space-y-4 rounded-2xl border border-default bg-surface p-6"
|
||||
data-testid="my-todos-intake-selection"
|
||||
>
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ todoDisplayNo(selectedItem) }}</div>
|
||||
<p class="text-sm text-secondary">
|
||||
{{ selectedItem.ui_state?.summary?.message || selectedItem.ui_state?.summary?.current_todo }}
|
||||
</p>
|
||||
<p v-if="selectedItem.source_file_name" class="text-xs text-muted">
|
||||
{{ selectedItem.source_file_name }}
|
||||
<span v-if="selectedItem.intake_parse_status"> · {{ selectedItem.intake_parse_status }}</span>
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!(selectedItem.owner_agent_id || chatAgentId)"
|
||||
data-testid="my-todos-open-intake-conversation"
|
||||
@click="openIntakeConversation(selectedItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openConversation') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="isTaskSelection && entryItem"
|
||||
class="space-y-4 rounded-2xl border border-default bg-surface p-6"
|
||||
data-testid="my-todos-task-selection"
|
||||
>
|
||||
<div class="font-mono text-lg font-bold text-primary">
|
||||
{{ 'task_no' in entryItem ? entryItem.task_no : todoDisplayNo(entryItem as ShippingTaskSummary) }}
|
||||
<span
|
||||
v-if="entryProgressSummary?.poNumber"
|
||||
class="ml-2 font-sans text-sm font-medium text-secondary"
|
||||
>· PO {{ entryProgressSummary.poNumber }}</span>
|
||||
</div>
|
||||
<p
|
||||
v-if="entryProgressSummary"
|
||||
class="text-sm font-medium text-primary"
|
||||
data-testid="my-todos-progress-summary"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.progressSummary', {
|
||||
stage: entryProgressSummary.stageLabel,
|
||||
current: entryProgressSummary.index || '—',
|
||||
total: entryProgressSummary.total,
|
||||
}) }}
|
||||
</p>
|
||||
<p
|
||||
v-if="entryProgressSummary?.blocker"
|
||||
class="text-xs text-amber-700 dark:text-amber-300"
|
||||
data-testid="my-todos-progress-blocker"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.progressBlocker', { reason: entryProgressSummary.blocker }) }}
|
||||
</p>
|
||||
<p class="text-sm text-secondary">
|
||||
{{ entryItem.ui_state?.summary?.message || entryItem.ui_state?.summary?.current_todo || $t('workspace.shippingNotice.myTodos.openProcessingHint') }}
|
||||
</p>
|
||||
<p class="text-xs text-muted">
|
||||
{{ $t('workspace.shippingNotice.myTodos.openProcessingHint') }}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!canOpenOrderProcessing(entryItem)"
|
||||
data-testid="my-todos-open-order-processing"
|
||||
@click="openOrderProcessing(entryItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="chatAgentId"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary hover:bg-surface-soft"
|
||||
@click="openInChat(entryItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.openChat') }}
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-if="!canOpenOrderProcessing(entryItem)"
|
||||
class="text-xs text-amber-700 dark:text-amber-300"
|
||||
data-testid="my-todos-open-processing-unavailable"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.openProcessingUnavailable') }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-else-if="detailLoading" class="rounded-2xl border border-dashed border-default py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else class="rounded-2xl border border-dashed border-default py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.selectCase') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,9 +2,10 @@
|
||||
* features/workspace/shipping-task-center/ShippingTaskWorkbench.vue
|
||||
* 用途:发货任务处理主区——当前待办栏、统一 15 阶进度、最后活动/终止原因、STP 事实、订单概览、时间线。
|
||||
* 依赖:TaskTodoPanel、StpProgressFactsPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、
|
||||
* useShippingProcessingWorkItem、UnifiedProgressTrack、listWorkspaceShippingTaskAuditTimeline。
|
||||
* useShippingProcessingWorkItem、WorkbenchProgressGrouped、listWorkspaceShippingTaskAuditTimeline。
|
||||
* 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;OT 身份取 detail.order_task_no(禁止 WorkflowItem);
|
||||
* 进度仅来自 ShippingProcessingProjection;时间线仅消费统一 ShippingAuditEvent。
|
||||
* 进度仅来自 ShippingProcessingProjection(showActions=false,动作归 TaskTodoPanel,UI-05);
|
||||
* 时间线仅消费统一 ShippingAuditEvent。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
@@ -18,7 +19,9 @@ import {
|
||||
import { useShippingProcessingWorkItem } from '@/features/chat/shipping/useShippingProcessingWorkItem';
|
||||
import type { ShippingTaskAuditTimelineItem, ShippingTaskDetail } from '@/features/chat/types/shipping.api.types';
|
||||
import { listWorkspaceShippingTaskAuditTimeline } from '@/features/chat/api/shipping.api';
|
||||
import UnifiedProgressTrack from '@/features/shipping-progress/components/UnifiedProgressTrack.vue';
|
||||
import WorkbenchProgressGrouped from '@/features/shipping-progress/components/WorkbenchProgressGrouped.vue';
|
||||
import { resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import TaskTodoPanel from './TaskTodoPanel.vue';
|
||||
import StpProgressFactsPanel from './StpProgressFactsPanel.vue';
|
||||
@@ -67,6 +70,20 @@ const { projection: shippingProcessingProjection } = useShippingProcessingWorkIt
|
||||
},
|
||||
);
|
||||
|
||||
/** 动作栏已提供 download_excel 时隐藏下方重复按钮。 */
|
||||
const actionBarOffersDownloadExcel = computed(() => {
|
||||
const presentation = resolveProcessingActionPresentation(
|
||||
shippingProcessingProjection.value,
|
||||
{ surface: 'workbench' },
|
||||
);
|
||||
const all = [
|
||||
presentation.primary,
|
||||
presentation.secondary,
|
||||
...presentation.overflow,
|
||||
].filter(Boolean);
|
||||
return all.some((item) => item?.intent === 'download_excel');
|
||||
});
|
||||
|
||||
/** 最后活动:统一投影优先,否则 Notice.updated_at。 */
|
||||
const lastActivityAt = computed(() =>
|
||||
shippingProcessingProjection.value?.lastActivityAt
|
||||
@@ -110,6 +127,24 @@ const taskMatchStatusLabel = computed(() => {
|
||||
return te(key) ? t(key) : t('workspace.shippingNotice.matchStatus.unknown');
|
||||
});
|
||||
|
||||
/**
|
||||
* 任务台统一动作栏:刷新投影;其余 intent 由 TaskTodoPanel 承载。
|
||||
*/
|
||||
function onTaskUnifiedAction(item: ActionPresentationItem) {
|
||||
if (item.intent === 'refresh') {
|
||||
emit('refreshed');
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'download_excel') {
|
||||
void downloadExcel();
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_manual_upload') {
|
||||
// 已在任务台,无需跳转。
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取任务统一审计时间线(ShippingAuditEvent 单源)。
|
||||
*/
|
||||
@@ -181,10 +216,11 @@ async function downloadExcel() {
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.todo.progressUnavailable') }}
|
||||
</p>
|
||||
<UnifiedProgressTrack
|
||||
<WorkbenchProgressGrouped
|
||||
v-if="shippingProcessingProjection"
|
||||
:projection="shippingProcessingProjection"
|
||||
density="workbench"
|
||||
:show-actions="false"
|
||||
@action="onTaskUnifiedAction"
|
||||
/>
|
||||
<dl class="mt-3 grid gap-2 text-xs sm:grid-cols-2">
|
||||
<div>
|
||||
@@ -196,7 +232,7 @@ async function downloadExcel() {
|
||||
<dd class="text-secondary">{{ terminateReason || '—' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div v-if="hasExcelArtifact" class="mt-3">
|
||||
<div v-if="hasExcelArtifact && !actionBarOffersDownloadExcel" class="mt-3">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/TaskTodoPanel.vue
|
||||
* 用途:渲染统一 Gate 恢复卡片与 STP 履约待办动作(ui_state.action_buttons)。
|
||||
* 用途:渲染统一 Gate 恢复卡片与 STP 履约待办说明(表单/弹窗入口)。
|
||||
* 依赖:ProcessGateRecoveryCard、shipping.api、shipping-tasks.api、ManualUploadEvidenceDialog。
|
||||
* 逻辑:优先展示 ui_state.process_gate 阻断信息与 next_action_code;禁止按 workflow_item.lifecycle
|
||||
* 或 process_status 推断人工上传;存在 current_blocking_gate 时不渲染旧 action_buttons。
|
||||
* 逻辑:优先展示 ui_state.process_gate 阻断信息;hidePrimaryActions=true 时不渲染平级主按钮
|
||||
* (由订单处理工作台统一 ActionBar 输出,UI-01 / BE-05);对话框与登记表单仍由此面板承接。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -35,10 +35,14 @@ import ProcessGateRecoveryCard from '@/features/shipping-process-gates/component
|
||||
import type { ShippingProcessGateUserSummary } from '@/features/chat/types/shipping.api.types';
|
||||
import { gateSummaryIndicatesManualUpload } from '@/features/chat/shipping/shippingProcessingFulfillment';
|
||||
|
||||
const props = defineProps<{
|
||||
const props = withDefaults(defineProps<{
|
||||
detail: ShippingTaskDetail;
|
||||
canHandle: boolean;
|
||||
}>();
|
||||
/** 为 true 时隐藏主按钮区与 Gate 卡内主操作(统一进度 ActionBar 已输出)。 */
|
||||
hidePrimaryActions?: boolean;
|
||||
}>(), {
|
||||
hidePrimaryActions: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
@@ -155,11 +159,28 @@ const allowedIds = computed(() => {
|
||||
});
|
||||
const hasBlockingGate = computed(() => Boolean(processGateSummary.value?.current_blocking_gate));
|
||||
|
||||
const UNIFIED_OWNED_ACTION_IDS = new Set([
|
||||
'retry',
|
||||
'refresh',
|
||||
'download_excel',
|
||||
'export',
|
||||
'open_manual_upload',
|
||||
'mark_manual_uploaded',
|
||||
'regenerate_excel',
|
||||
'view_result',
|
||||
'open_order_review',
|
||||
'open_order_processing',
|
||||
]);
|
||||
|
||||
const visibleActions = computed(() => {
|
||||
// [STEP] Gate 阻断时后端已清零 action_buttons;前端再兜底隐藏,避免双真相。
|
||||
if (hasBlockingGate.value) return [];
|
||||
return actionButtons.value.filter((action) => {
|
||||
const id = String(action.id || '');
|
||||
// [UI-01 / BE-05] 统一 ActionBar 已表达的动作不再重复渲染;未映射的履约动作仍由本面板承接。
|
||||
if (props.hidePrimaryActions && UNIFIED_OWNED_ACTION_IDS.has(id)) {
|
||||
return false;
|
||||
}
|
||||
if (!allowedIds.value.has(id) || !isActionAllowedForCheckpoint(id, checkpointKind.value)) {
|
||||
return false;
|
||||
}
|
||||
@@ -169,6 +190,8 @@ const visibleActions = computed(() => {
|
||||
return true;
|
||||
});
|
||||
});
|
||||
/** Gate 卡在统一进度存在时仍可执行业务恢复(客户确认等),但避免与 ActionBar 重复的 next_action。 */
|
||||
const gateCanHandle = computed(() => props.canHandle);
|
||||
/**
|
||||
* 动作成功后刷新详情并更新导航徽标。
|
||||
*/
|
||||
@@ -371,12 +394,34 @@ async function runAction(action: ShippingChatAction) {
|
||||
busyId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 供订单处理工作台统一 ActionBar 委托履约动作(库存源/匹配/上传登记等)。
|
||||
*
|
||||
* @param actionId - ui_state / Gate 动作码
|
||||
*/
|
||||
async function invokeActionByCode(actionId: string) {
|
||||
const id = String(actionId || '').trim();
|
||||
if (!id) return;
|
||||
const fromButtons = actionButtons.value.find((item) => String(item.id || '') === id);
|
||||
await runAction(fromButtons || {
|
||||
id,
|
||||
label: id,
|
||||
message: '',
|
||||
variant: 'primary',
|
||||
});
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
invokeActionByCode,
|
||||
openCustomerDialog,
|
||||
});
|
||||
</script>
|
||||
<template>
|
||||
<div class="space-y-3">
|
||||
<ProcessGateRecoveryCard
|
||||
:summary="processGateSummary"
|
||||
:can-handle="canHandle"
|
||||
:can-handle="gateCanHandle"
|
||||
:navigation-context="{
|
||||
agentId: detail.owner_agent_id != null ? String(detail.owner_agent_id) : undefined,
|
||||
conversationId: detail.conversation_id || undefined,
|
||||
|
||||
Reference in new issue
Block a user