feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验
- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全 - 引入审计事件的哈希链校验机制,支持数据完整性验证 - 增强订单抽取与审计功能,支持敏感快照的访问控制 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
95cdfe66b0
commit
d0fe084999
225 files changed
+25923
-6653
No files matched your search
+34
-20
@@ -48,7 +48,7 @@ const hasTrainingSample = ref(false);
|
||||
const availableSamplesLoaded = ref(false);
|
||||
const availableSamplesLoading = ref(false);
|
||||
const uploadingSample = ref(false);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed' } | null>(null);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
let uploadPollingTimer: number | null = null;
|
||||
let availableSamplesController: AbortController | null = null;
|
||||
let availableSamplesTimeout: number | null = null;
|
||||
@@ -86,12 +86,16 @@ const failureDetails = computed(() => (suite.value?.latest_run?.failure_codes ||
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.unknown', { sample: sampleName }) };
|
||||
}));
|
||||
/** 读取订单字段复核状态;候选加载完成时会初始化,默认值仅用于渲染过程中的安全兜底。 */
|
||||
function orderFieldReview(fieldCode: string): { correct: boolean; value: string } {
|
||||
return orderFieldReviews.value[fieldCode] || { correct: true, value: '' };
|
||||
function orderFieldReview(fieldKey: string): { correct: boolean; value: string } {
|
||||
return orderFieldReviews.value[fieldKey] || { correct: true, value: '' };
|
||||
}
|
||||
/** 更新单个订单字段的人工复核状态,保持其他字段复核结果不被输入事件覆盖。 */
|
||||
function updateOrderFieldReview(fieldCode: string, patch: Partial<{ correct: boolean; value: string }>): void {
|
||||
orderFieldReviews.value[fieldCode] = { ...orderFieldReview(fieldCode), ...patch };
|
||||
function updateOrderFieldReview(fieldKey: string, patch: Partial<{ correct: boolean; value: string }>): void {
|
||||
orderFieldReviews.value[fieldKey] = { ...orderFieldReview(fieldKey), ...patch };
|
||||
}
|
||||
/** 复核与服务端使用同一个 scope:field_code 键,避免同名 Header/Line 字段覆盖。 */
|
||||
function orderFieldKey(field: { scope: 'header'; field_code: string }): string {
|
||||
return `${field.scope}:${field.field_code}`;
|
||||
}
|
||||
|
||||
/** 将统一业务错误转换为安全的界面提示,不暴露盲测真值或内部布局数据。 */
|
||||
@@ -99,6 +103,15 @@ function report(error: unknown): void {
|
||||
const code = error instanceof BusinessError ? error.code : '';
|
||||
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
|
||||
}
|
||||
/** 将模板布局失败码转成盲测页可执行的提示,不向管理员回显内部快照数据。 */
|
||||
function sampleFailureMessage(errorCode?: string | null): string {
|
||||
const key = errorCode === 'mineru_cell_coordinates_missing'
|
||||
? 'sampleLayoutCoordinatesMissing'
|
||||
: errorCode === 'shipping_document_layout_snapshot_size_exceeded'
|
||||
? 'sampleLayoutSnapshotTooLarge'
|
||||
: 'sampleParseFailed';
|
||||
return t(`admin.shippingOrderProfiles.wizard.${key}`);
|
||||
}
|
||||
|
||||
/** 创建或读取当前草稿 checksum 对应的盲测集;候选样本按需加载,避免进入页面时扫描全部历史样本。 */
|
||||
async function loadSuite(): Promise<void> {
|
||||
@@ -174,7 +187,9 @@ async function pollUploadedSample(intakeNo: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingUpload.value = { intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed' };
|
||||
pendingUpload.value = {
|
||||
intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
return;
|
||||
}
|
||||
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 1500);
|
||||
@@ -215,7 +230,7 @@ async function previewSample(): Promise<void> {
|
||||
candidate.value = await previewOrderProfileBlindTestCandidate(suite.value.id, selectedSample.value);
|
||||
rowReviews.value = candidate.value.rows.map(() => ({ correct: true, correction: '' }));
|
||||
orderFieldReviews.value = Object.fromEntries(candidate.value.order_fields.map((field) => [
|
||||
field.field_code,
|
||||
orderFieldKey(field),
|
||||
{ correct: true, value: field.value == null ? '' : String(field.value) },
|
||||
]));
|
||||
} catch (error) {
|
||||
@@ -256,8 +271,8 @@ async function confirmReview(): Promise<void> {
|
||||
document_id: candidate.value.document_id,
|
||||
table_id: candidate.value.table_id,
|
||||
row_reviews: reviews,
|
||||
order_field_reviews: Object.fromEntries(Object.entries(orderFieldReviews.value).map(([fieldCode, review]) => [
|
||||
fieldCode,
|
||||
order_field_reviews: Object.fromEntries(Object.entries(orderFieldReviews.value).map(([fieldKey, review]) => [
|
||||
fieldKey,
|
||||
review.correct ? { correct: true } : { correct: false, value: review.value },
|
||||
])),
|
||||
});
|
||||
@@ -356,11 +371,10 @@ onBeforeUnmount(() => {
|
||||
</section>
|
||||
|
||||
<section v-if="suite.status === 'draft'" class="card">
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2>
|
||||
<p v-if="!availableSamplesLoaded">{{ t('admin.shippingOrderProfiles.blindTest.loadIndependentSamplesHint') }}</p>
|
||||
<p v-else-if="!availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
|
||||
<div class="sample-picker"><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.wizard.uploadNewSample') }}</span></label><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 || working" @click="previewSample">{{ t('admin.shippingOrderProfiles.blindTest.addCurrentSample') }}</button></template></div>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : t('admin.shippingOrderProfiles.wizard.sampleParseFailed') }}</p>
|
||||
<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 || working" @click="previewSample">{{ t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button></template></div>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : sampleFailureMessage(pendingUpload.errorCode) }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="candidate" class="card candidate-card">
|
||||
@@ -373,10 +387,10 @@ onBeforeUnmount(() => {
|
||||
<textarea v-if="!rowReviews[index].correct" v-model="rowReviews[index].correction" class="input-field" :placeholder="t('admin.shippingOrderProfiles.blindTest.expectedRowsPlaceholder')" />
|
||||
</template>
|
||||
</article>
|
||||
<article v-for="field in candidate.order_fields" :key="field.field_code" class="review-item">
|
||||
<article v-for="field in candidate.order_fields" :key="field.field_id" class="review-item">
|
||||
<h3>{{ field.field_code }}</h3><code>{{ field.value ?? t('admin.shippingOrderProfiles.emptyCandidateValue') }}</code>
|
||||
<label><input :checked="orderFieldReview(field.field_code).correct" type="checkbox" @change="updateOrderFieldReview(field.field_code, { correct: ($event.target as HTMLInputElement).checked })">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
|
||||
<input v-if="!orderFieldReview(field.field_code).correct" class="input-field" :value="orderFieldReview(field.field_code).value" :placeholder="t('admin.shippingOrderProfiles.blindTest.correctedValue')" @input="updateOrderFieldReview(field.field_code, { value: ($event.target as HTMLInputElement).value })">
|
||||
<label><input :checked="orderFieldReview(orderFieldKey(field)).correct" type="checkbox" @change="updateOrderFieldReview(orderFieldKey(field), { correct: ($event.target as HTMLInputElement).checked })">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
|
||||
<input v-if="!orderFieldReview(orderFieldKey(field)).correct" class="input-field" :value="orderFieldReview(orderFieldKey(field)).value" :placeholder="t('admin.shippingOrderProfiles.blindTest.correctedValue')" @input="updateOrderFieldReview(orderFieldKey(field), { value: ($event.target as HTMLInputElement).value })">
|
||||
</article>
|
||||
<button type="button" class="btn-primary" :disabled="working || !candidate.rows.length" @click="confirmReview">{{ t('admin.shippingOrderProfiles.blindTest.confirmReview') }}</button>
|
||||
</section>
|
||||
@@ -390,16 +404,16 @@ onBeforeUnmount(() => {
|
||||
|
||||
<style scoped>
|
||||
.blind-test-page { padding: 24px; color: var(--text-secondary); }
|
||||
header, .suite-summary, .execution, .actions, .sample-picker, li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
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; }
|
||||
.status { color: var(--status-warning-fg); font-weight: 700; } .status.approved { color: var(--status-success-fg); } .status.superseded { color: var(--status-error-fg); }
|
||||
.sample-picker .select-field { min-width: 260px; } .candidate-card .input-field { padding: 8px; border-radius: 6px; } textarea.input-field { min-height: 72px; font-family: ui-monospace, monospace; }
|
||||
.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); }
|
||||
.candidate-card { grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); } .candidate-card > h2, .candidate-card > p, .candidate-card > button { grid-column: 1 / -1; }
|
||||
.review-item { display: grid; gap: 8px; border: 1px solid var(--border-default); border-radius: 8px; padding: 12px; } code { overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text-primary); font-size: 12px; } label { display: flex; gap: 6px; align-items: center; }
|
||||
ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; } li { border-top: 1px solid var(--border-default); padding-top: 8px; }
|
||||
.failure-details { border-color: var(--status-error-border); background: var(--status-error-bg); }.failure-details h2 { color: var(--status-error-fg); }.failure-details li { display: grid; gap: 4px; color: var(--status-error-fg); }.failure-details code { color: var(--status-error-fg); }
|
||||
.training-required { color: var(--status-warning-fg) !important; font-weight: 600; }
|
||||
@media (max-width: 700px) { header, .suite-summary, .execution, .sample-picker { align-items: stretch; flex-direction: column; } .sample-picker .select-field { min-width: 0; width: 100%; } }
|
||||
@media (max-width: 700px) { header, .suite-summary, .execution, .sample-heading, .sample-picker { align-items: stretch; flex-direction: column; } .sample-picker .select-field { min-width: 0; width: 100%; } }
|
||||
</style>
|
||||
+22
-4
@@ -5,7 +5,7 @@
|
||||
逻辑:首步仅收集业务名称和 Schema;最后一步由服务端生成系统编码并原子创建草稿、样本绑定、Revision 与 Lease。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowLeft, ArrowRight, Check, FileText, Layers3, Sparkles } from 'lucide-vue-next';
|
||||
@@ -33,6 +33,7 @@ const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
|
||||
const canNext = computed(() => step.value === 1
|
||||
? Boolean(identity.displayName.trim() && identity.schemaId)
|
||||
@@ -59,10 +60,22 @@ async function loadContext(): Promise<void> {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed'));
|
||||
}
|
||||
}
|
||||
/** 刷新上传后的样本库;样本解析未完成时只会留在样本库,不能产出半成品模板。 */
|
||||
async function refreshSamples(): Promise<void> {
|
||||
/** 刷新上传后的样本库;轮询失败静默处理,避免短暂网络异常持续弹出提示。 */
|
||||
async function refreshSamples(showError = true): Promise<void> {
|
||||
try { samples.value = await listOrderProfileSamples(); }
|
||||
catch { message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
|
||||
catch { if (showError) message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
|
||||
}
|
||||
/** 仅在第二步保持已解析文档列表为最新,离开步骤后立即停止。 */
|
||||
function stopSampleRefresh(): void {
|
||||
if (sampleRefreshTimer !== null) clearTimeout(sampleRefreshTimer);
|
||||
sampleRefreshTimer = null;
|
||||
}
|
||||
function scheduleSampleRefresh(): void {
|
||||
stopSampleRefresh();
|
||||
if (step.value !== 2) return;
|
||||
void refreshSamples(false).finally(() => {
|
||||
if (step.value === 2) sampleRefreshTimer = setTimeout(scheduleSampleRefresh, 2000);
|
||||
});
|
||||
}
|
||||
/** 加载选定样本的可用表格;单表场景由下一步直接作为订单明细表。 */
|
||||
async function loadTables(id: number): Promise<void> {
|
||||
@@ -75,6 +88,10 @@ watch(documentId, async (id) => {
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
});
|
||||
watch(step, (currentStep) => {
|
||||
if (currentStep === 2) scheduleSampleRefresh();
|
||||
else stopSampleRefresh();
|
||||
});
|
||||
/** 前进仅校验当前步骤;单表直接创建,多表才要求管理员确认订单明细表。 */
|
||||
async function next(): Promise<void> {
|
||||
if (!canNext.value) {
|
||||
@@ -117,6 +134,7 @@ async function finish(enterEditor: boolean): Promise<void> {
|
||||
} finally { saving.value = false; }
|
||||
}
|
||||
onMounted(loadContext);
|
||||
onBeforeUnmount(stopSampleRefresh);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
+221
-82
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue
|
||||
用途:订单坐标 Profile v2 的独立草稿标注编辑页。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel。
|
||||
逻辑:仅编辑由向导创建的草稿;撤销/重做、自动保存和建议决定均受当前标签租约保护。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、shippingOrderField.utils。
|
||||
逻辑:仅编辑由向导创建的草稿;起行锚点默认 customer_po_line_no(内部项次 line_no 亦可绑定);
|
||||
撤销/重做、自动保存和建议决定均受当前标签租约保护。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
@@ -59,7 +60,10 @@ import {
|
||||
suggestFieldCodeFromHeaders,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
isOrderProfileAnchorRelativeCandidate,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
toOrderProfileAnchorRelativeRegion,
|
||||
} from "./orderProfileForm.utils";
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -94,6 +98,7 @@ const sampleTables = ref<
|
||||
const preview = ref<CoordinateReconstructionPreview | null>(null);
|
||||
const orderFieldValuePreviews = ref<OrderFieldValuePreview[]>([]);
|
||||
const orderFieldValueState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle');
|
||||
const orderFieldValueError = ref('');
|
||||
const previewError = ref("");
|
||||
const headerSuggestions = ref<
|
||||
Array<{
|
||||
@@ -141,6 +146,7 @@ let previewTimer: number | null = null;
|
||||
let orderFieldValueTimer: number | null = null;
|
||||
let pendingGestureId: string | null = null;
|
||||
let pendingFormEdit: OrderProfileCanvasRegion[] | null = null;
|
||||
let restoringProfile = false;
|
||||
|
||||
const form = reactive({
|
||||
profileCode: "",
|
||||
@@ -169,9 +175,22 @@ const lineFields = computed<ShippingOrderFieldConfig[]>(
|
||||
(item) =>
|
||||
item.enabled !== false &&
|
||||
item.scope === "line" &&
|
||||
item.field_code != null &&
|
||||
item.allowed_sources?.includes("pdf_coordinate"),
|
||||
) || [],
|
||||
);
|
||||
/** 根据当前主行映射自动选择起行字段,优先客户 PO 行号,避免暴露内部配置。 */
|
||||
const resolveLineStartFieldCode = (mainLineFieldCodes: Set<string>): string => {
|
||||
const availableFieldCodes = new Set(
|
||||
lineFields.value.map((field) => field.field_code).filter(Boolean),
|
||||
);
|
||||
const validMainLineCodes = [...mainLineFieldCodes].filter((fieldCode) =>
|
||||
availableFieldCodes.has(fieldCode),
|
||||
);
|
||||
return validMainLineCodes.includes("customer_po_line_no")
|
||||
? "customer_po_line_no"
|
||||
: validMainLineCodes[0] || "customer_po_line_no";
|
||||
};
|
||||
/** 订单单头区域只能绑定 Schema 中声明为 header 的坐标字段。 */
|
||||
const headerFields = computed<ShippingOrderFieldConfig[]>(
|
||||
() =>
|
||||
@@ -193,7 +212,7 @@ const selectedRegion = computed(
|
||||
/** 当前样本值只能来自本次按画布坐标回读的结果,禁止回退到旧的自动建议缓存。 */
|
||||
const selectedRegionSampleValue = computed(() => {
|
||||
const region = selectedRegion.value;
|
||||
if (!region || !['order_field', 'header_field'].includes(region.kind)) return null;
|
||||
if (!region || region.kind !== 'order_field') return null;
|
||||
if (region.suggestedValue) return region.suggestedValue;
|
||||
if (!region.fieldCode) return null;
|
||||
return orderFieldValuePreviews.value.find((item) => item.field_code === region.fieldCode)?.value || null;
|
||||
@@ -201,7 +220,7 @@ const selectedRegionSampleValue = computed(() => {
|
||||
/** 右侧选区值与画布标签共享同一个读取状态,禁止以旧建议值回退。 */
|
||||
const selectedRegionSampleDisplay = computed(() => {
|
||||
if (orderFieldValueState.value === 'loading') return t('admin.shippingOrderProfiles.workbench.orderFieldValueReading');
|
||||
if (orderFieldValueState.value === 'failed') return t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
if (orderFieldValueState.value === 'failed') return orderFieldValueError.value || t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
return selectedRegionSampleValue.value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
});
|
||||
const orderFieldValues = computed<Record<string, string | null>>(() => Object.fromEntries(
|
||||
@@ -311,6 +330,23 @@ const issues = computed(() => {
|
||||
if (duplicateOrderFieldCodes.length) {
|
||||
result.push(`订单字段 ${[...new Set(duplicateOrderFieldCodes)].join(", ")} 已在其他区域绑定;请编辑原区域或先解除原绑定。`);
|
||||
}
|
||||
const pageNos = [...new Set(regions.value.filter((item) => item.kind === "line").map((item) => item.pageNo))];
|
||||
for (const regionPageNo of pageNos) {
|
||||
const pageLines = regions.value
|
||||
.filter((item) => item.pageNo === regionPageNo && item.kind === "line")
|
||||
.sort((left, right) => left.region.y0 - right.region.y0);
|
||||
const mainLine = pageLines[0];
|
||||
if (!mainLine) continue;
|
||||
const mainLineFieldCodes = regions.value
|
||||
.filter((item) => item.kind === "field" && item.parentId === mainLine.id && item.fieldCode)
|
||||
.map((item) => item.fieldCode!);
|
||||
if (!mainLineFieldCodes.length) continue;
|
||||
const startFieldCode = resolveLineStartFieldCode(new Set(mainLineFieldCodes));
|
||||
if (!mainLineFieldCodes.includes(startFieldCode)) {
|
||||
result.push(t("admin.shippingOrderProfiles.workbench.issues.lineStartAnchorRequired"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
/** 将 API 业务错误转换为工作台消息,避免内部错误详情出现在页面。 */
|
||||
@@ -341,6 +377,18 @@ const checkpoint = () => {
|
||||
markLocalChange();
|
||||
scheduleAutosave();
|
||||
};
|
||||
/**
|
||||
* 为订单字段及其标签锚点分配同一命名空间内的唯一序号。
|
||||
* 直接框选值和“标签 + 值”两种标注方式会共同写入 order_field_layouts,不能各自从 1 编号。
|
||||
*/
|
||||
const nextOrderFieldSequence = (targetPageNo: number): number => {
|
||||
const occupiedIds = new Set(
|
||||
regions.value.flatMap((region) => [region.id, region.orderFieldId].filter(Boolean)),
|
||||
);
|
||||
let sequence = 1;
|
||||
while (occupiedIds.has(`order_field_${targetPageNo}_${sequence}`)) sequence += 1;
|
||||
return sequence;
|
||||
};
|
||||
/** 记录输入控件编辑前的状态;只有值实际变化时才写入撤销历史。 */
|
||||
const beginFormEdit = () => {
|
||||
pendingFormEdit = snapshot();
|
||||
@@ -356,6 +404,17 @@ const finishFormEdit = () => {
|
||||
scheduleOrderFieldSuggestionValues();
|
||||
scheduleAutosave();
|
||||
};
|
||||
/**
|
||||
* 同步订单字段的可见标签与其 Schema 绑定,避免字段已改为送货地址而画布仍显示账款地址。
|
||||
* 表头/明细列保留原始文档文字,只有订单字段使用 Schema 业务名称作为稳定展示标签。
|
||||
*/
|
||||
const finishFieldBindingEdit = () => {
|
||||
const target = selectedRegion.value;
|
||||
if (target?.kind === 'order_field' && target.fieldCode) {
|
||||
target.label = schemaFieldLabel(target.fieldCode);
|
||||
}
|
||||
finishFormEdit();
|
||||
};
|
||||
/** 撤销上一项区域、字段或删除操作。 */
|
||||
const undo = () => {
|
||||
const prior = history.value.pop();
|
||||
@@ -439,7 +498,9 @@ const addRegion = (
|
||||
y1: 0.35 + count * 0.06,
|
||||
});
|
||||
// layout_id is persisted, so generate a contract-safe and non-reused identifier rather than using a timestamp.
|
||||
let sequence = count;
|
||||
let sequence = effectiveKind === 'order_field'
|
||||
? nextOrderFieldSequence(pageNo.value)
|
||||
: count;
|
||||
while (
|
||||
regions.value.some(
|
||||
(entry) => entry.id === `${effectiveKind}_${pageNo.value}_${sequence}`,
|
||||
@@ -554,7 +615,7 @@ const createDrawnRegion = async (region: OrderProfileRelativeRegion) => {
|
||||
}
|
||||
history.value.push(snapshot());
|
||||
future.value = [];
|
||||
const sequence = pageRegions.value.filter((item) => item.kind === 'order_anchor').length + 1;
|
||||
const sequence = nextOrderFieldSequence(pageNo.value);
|
||||
const orderFieldId = `order_field_${pageNo.value}_${sequence}`;
|
||||
const anchor: OrderProfileCanvasRegion = {
|
||||
id: `${orderFieldId}_anchor`, kind, label, region, orderFieldId, pageNo: pageNo.value,
|
||||
@@ -576,7 +637,10 @@ const createDrawnRegion = async (region: OrderProfileRelativeRegion) => {
|
||||
const anchor = pendingOrderFieldAnchor.value;
|
||||
const valueRegion: OrderProfileCanvasRegion = {
|
||||
id: anchor.orderFieldId!, kind, label: value, region, parentId: anchor.id,
|
||||
orderFieldId: anchor.orderFieldId, valueMode: 'single_line', suggestedValue: value, pageNo: pageNo.value,
|
||||
// The Schema selector uses null for its explicit "unbound" option. Do not
|
||||
// leave this undefined, otherwise a newly drawn value box can retain the
|
||||
// previous selected address field in the browser control.
|
||||
fieldCode: null, orderFieldId: anchor.orderFieldId, valueMode: 'single_line', suggestedValue: value, pageNo: pageNo.value,
|
||||
};
|
||||
regions.value.push(valueRegion);
|
||||
pendingOrderFieldAnchor.value = null;
|
||||
@@ -685,47 +749,39 @@ const updateRegion = (id: string, region: OrderProfileRelativeRegion) => {
|
||||
};
|
||||
/** 将区域编辑器转换为严格 v2 定义;浏览器只发送白名单 field_code/解析器和相对区域。 */
|
||||
const definition = () => {
|
||||
// 自动建议和历史草稿可能带有浮点边界误差;保存前统一裁剪,保证绝对值框合法。
|
||||
regions.value = regions.value.map((item) => ({
|
||||
// Build a normalized payload without mutating canvas state. Preview requests must
|
||||
// not turn an unsaved relative value box into a different local annotation.
|
||||
const normalizedRegions = regions.value.map((item) => ({
|
||||
...item,
|
||||
region: normalizedCanvasRegion(item.region) || item.region,
|
||||
}));
|
||||
const tableRegions = [...new Set(
|
||||
regions.value
|
||||
normalizedRegions
|
||||
.filter((item) => item.kind === "line" || item.kind === "header_field")
|
||||
.map((item) => item.pageNo),
|
||||
)]
|
||||
.sort((left, right) => left - right)
|
||||
.map((regionPageNo) => {
|
||||
const pageItems = regions.value.filter(
|
||||
const pageItems = normalizedRegions.filter(
|
||||
(item) => item.pageNo === regionPageNo,
|
||||
);
|
||||
const lineRegions = pageItems.filter((item) => item.kind === "line");
|
||||
const boundLineFieldRegionIds = new Set<string>();
|
||||
const boundLineFieldCodes = new Set<string>();
|
||||
const groupedLineFields = groupUniqueOrderProfileLineFields(
|
||||
pageItems,
|
||||
lineRegions.map((item) => item.id),
|
||||
);
|
||||
const boundLineFieldRegionIds = groupedLineFields.boundRegionIds;
|
||||
/** 将已分组的画布字段转换为 v2 字段区域;重复读取不会改变后续保存内容。 */
|
||||
const fieldRegionsFor = (layoutId: string): OrderProfileFieldRegion[] =>
|
||||
pageItems
|
||||
.filter(
|
||||
(item) =>
|
||||
item.kind === "field" &&
|
||||
item.parentId === layoutId &&
|
||||
item.fieldCode &&
|
||||
!boundLineFieldCodes.has(item.fieldCode),
|
||||
)
|
||||
.map((item) => {
|
||||
// The v2 contract assigns each Schema line field one coordinate source.
|
||||
// Continuation-row frames remain visible, but cannot duplicate that binding.
|
||||
boundLineFieldCodes.add(item.fieldCode!);
|
||||
boundLineFieldRegionIds.add(item.id);
|
||||
return {
|
||||
(groupedLineFields.fieldsByLayout.get(layoutId) || []).map((item) => ({
|
||||
field_id: "",
|
||||
field_code: item.fieldCode!,
|
||||
scope: "line" as const,
|
||||
region: item.region,
|
||||
extractor_key: "direct",
|
||||
allowed_sources: ["pdf_coordinate"],
|
||||
minimum_evidence_level: "coordinate",
|
||||
};
|
||||
});
|
||||
}));
|
||||
const headerLayouts = pageItems
|
||||
.filter((item) => item.kind === "header_field" && item.parentId)
|
||||
.reduce<string[]>((layoutIds, item) => {
|
||||
@@ -750,6 +806,7 @@ const definition = () => {
|
||||
.map((field) => ({
|
||||
field_id: "",
|
||||
field_code: field.fieldCode!,
|
||||
scope: "line" as const,
|
||||
region: field.region,
|
||||
extractor_key: "direct" as const,
|
||||
allowed_sources: ["pdf_coordinate" as const],
|
||||
@@ -769,11 +826,18 @@ const definition = () => {
|
||||
y1: Math.max(...layoutRegions.map((item) => item.region.y1)),
|
||||
}
|
||||
: { x0: 0.1, y0: 0.25, x1: 0.9, y1: 0.85 };
|
||||
const firstLineRegion = lineRegions[0];
|
||||
const mainLineFieldCodes = new Set(
|
||||
firstLineRegion
|
||||
? fieldRegionsFor(firstLineRegion.id).map((item) => item.field_code)
|
||||
: [],
|
||||
);
|
||||
return {
|
||||
region_id: `main_lines_page_${regionPageNo}`,
|
||||
page_scope: "exact_page" as const,
|
||||
page_no: regionPageNo,
|
||||
region: tableRegion,
|
||||
line_start_field_code: resolveLineStartFieldCode(mainLineFieldCodes),
|
||||
header_layouts: headerLayouts,
|
||||
line_layouts: lineRegions.map((line, index) => {
|
||||
const fieldRegions = fieldRegionsFor(line.id);
|
||||
@@ -821,19 +885,25 @@ const definition = () => {
|
||||
minimum_margin: documentMatch.minimumMargin,
|
||||
},
|
||||
table_regions: tableRegions,
|
||||
order_field_layouts: regions.value
|
||||
order_field_layouts: normalizedRegions
|
||||
.filter((item) => item.kind === "order_field" && item.fieldCode)
|
||||
.map((item) => {
|
||||
const anchor = regions.value.find(
|
||||
const anchor = normalizedRegions.find(
|
||||
(candidate) =>
|
||||
candidate.kind === "order_anchor" &&
|
||||
(candidate.id === item.parentId || candidate.orderFieldId === item.orderFieldId),
|
||||
);
|
||||
const anchorId = toOrderProfileAnchorId(anchor);
|
||||
const isAnchorRelative = Boolean(anchor && anchorId && ["right_of_anchor", "below_anchor"].includes(item.valueMode || "")
|
||||
&& isOrderProfileAnchorRelativeCandidate(item.region, anchor.region));
|
||||
const relativeValueRegion = isAnchorRelative && anchor
|
||||
? toOrderProfileAnchorRelativeRegion(item.region, anchor.region)
|
||||
: null;
|
||||
return {
|
||||
layout_id: item.orderFieldId || item.id,
|
||||
field_id: "",
|
||||
field_code: item.fieldCode!,
|
||||
scope: "header" as const,
|
||||
page_scope: "exact_page" as const,
|
||||
page_no: item.pageNo,
|
||||
// Historical unbound labels can lack a usable canvas ID. In that case,
|
||||
@@ -845,12 +915,13 @@ const definition = () => {
|
||||
aliases: [],
|
||||
match_mode: "exact" as const,
|
||||
region: anchor.region,
|
||||
position_locked: !isAnchorRelative,
|
||||
minimum_evidence_level: "coordinate" as const,
|
||||
}
|
||||
: null,
|
||||
// 画布框是读取边界;锚点只用于定位字段,不能再参与值框二次投影。
|
||||
value_region: null,
|
||||
absolute_value_region: anchor && anchorId ? item.region : null,
|
||||
value_region: relativeValueRegion,
|
||||
absolute_value_region: anchor && anchorId && !relativeValueRegion ? item.region : null,
|
||||
fallback_value_region: anchor && anchorId ? null : item.region,
|
||||
value_mode: item.valueMode || "single_line",
|
||||
stop_anchors:
|
||||
@@ -868,7 +939,7 @@ const definition = () => {
|
||||
minimum_evidence_level: item.evidenceSource === "ocr_coordinate" ? "ocr_coordinate" as const : "coordinate" as const,
|
||||
};
|
||||
}),
|
||||
draft_unbound_order_field_layouts: regions.value
|
||||
draft_unbound_order_field_layouts: normalizedRegions
|
||||
.filter(
|
||||
(item) =>
|
||||
item.kind === "order_field" &&
|
||||
@@ -876,11 +947,16 @@ const definition = () => {
|
||||
)
|
||||
.map((item) => {
|
||||
const layoutId = item.orderFieldId || item.id.replace(/^unbound-/, "");
|
||||
const anchor = regions.value.find(
|
||||
const anchor = normalizedRegions.find(
|
||||
(candidate) =>
|
||||
candidate.kind === "order_anchor" &&
|
||||
(candidate.id === item.parentId || candidate.orderFieldId === layoutId),
|
||||
);
|
||||
const isAnchorRelative = Boolean(anchor && ["right_of_anchor", "below_anchor"].includes(item.valueMode || "")
|
||||
&& isOrderProfileAnchorRelativeCandidate(item.region, anchor.region));
|
||||
const relativeValueRegion = isAnchorRelative && anchor
|
||||
? toOrderProfileAnchorRelativeRegion(item.region, anchor.region)
|
||||
: null;
|
||||
return {
|
||||
layout_id: layoutId,
|
||||
label: item.label,
|
||||
@@ -893,11 +969,12 @@ const definition = () => {
|
||||
aliases: [],
|
||||
match_mode: "exact" as const,
|
||||
region: anchor.region,
|
||||
position_locked: !isAnchorRelative,
|
||||
minimum_evidence_level: "coordinate" as const,
|
||||
}
|
||||
: null,
|
||||
value_region: null,
|
||||
absolute_value_region: anchor ? item.region : null,
|
||||
value_region: relativeValueRegion,
|
||||
absolute_value_region: anchor && !relativeValueRegion ? item.region : null,
|
||||
fallback_value_region: anchor ? null : item.region,
|
||||
value_mode: item.valueMode || "single_line",
|
||||
stop_anchors:
|
||||
@@ -972,7 +1049,13 @@ const save = async (automatic = false) => {
|
||||
} else {
|
||||
fail(error);
|
||||
}
|
||||
if (automatic && autosaveFailures < 3 && navigator.onLine) {
|
||||
// A definition validation error cannot recover without an administrator edit.
|
||||
// Retrying it only produces repeated toast notifications for the same canvas state.
|
||||
const retryable = !(error instanceof BusinessError && [
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
].includes(error.code));
|
||||
if (automatic && retryable && autosaveFailures < 3 && navigator.onLine) {
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
retryTimer = window.setTimeout(() => void save(true), 1500 * autosaveFailures);
|
||||
}
|
||||
@@ -1048,6 +1131,7 @@ const suggestRegions = async () => {
|
||||
parentId: headerId,
|
||||
label: field.field_code || field.text || t("admin.shippingOrderProfiles.workbench.unboundColumn", { count: fieldIndex + 1 }),
|
||||
region: field.region,
|
||||
// 表头绑定表达列语义;运行期仅从明细行字段框读取实际业务值。
|
||||
fieldCode: field.field_code || null,
|
||||
pageNo: pageNo.value,
|
||||
});
|
||||
@@ -1157,7 +1241,10 @@ const suggestRegions = async () => {
|
||||
suggestingRegions.value = false;
|
||||
}
|
||||
};
|
||||
/** 接受、调整接受或拒绝当前待确认建议;重建议不会覆盖当前人工区域。 */
|
||||
/**
|
||||
* 接受、调整接受或拒绝当前待确认建议;重建议替换同页旧的自动表格区域,保留人工区域。
|
||||
* 自动区域 ID 使用稳定的 header_/line_ 前缀,借此避免重复自动标记叠加为无效 Profile。
|
||||
*/
|
||||
const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted' | 'rejected') => {
|
||||
if (!pendingSuggestion.value || !active.value || !editLeaseToken.value) return;
|
||||
const item = pendingSuggestion.value;
|
||||
@@ -1175,8 +1262,39 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
|
||||
});
|
||||
if (decision !== 'rejected') {
|
||||
checkpoint();
|
||||
const suggestionPages = new Set(item.regions.map((region) => region.pageNo));
|
||||
const isReplaceableAutoTableRegion = (region: OrderProfileCanvasRegion) =>
|
||||
suggestionPages.has(region.pageNo) &&
|
||||
(region.id.startsWith(`header_${region.pageNo}_`) ||
|
||||
region.id.startsWith(`line_${region.pageNo}_`));
|
||||
// A new suggestion is a complete table layout for its page. Replace its
|
||||
// previous generated header/line frames before appending it, otherwise a
|
||||
// changed suggestion ID leaves geometrically overlapping regions behind.
|
||||
regions.value = regions.value.filter(
|
||||
(region) => !isReplaceableAutoTableRegion(region),
|
||||
);
|
||||
const existingIds = new Set(regions.value.map((region) => region.id));
|
||||
const acceptedRegions = item.regions.filter((region) => !existingIds.has(region.id)).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode }));
|
||||
const suggestedLines = acceptedRegions.filter((region) => region.kind === 'line');
|
||||
if (suggestedLines.length) {
|
||||
const fieldParentIds = new Set(
|
||||
regions.value
|
||||
.filter((region) => region.kind === 'field' && region.parentId)
|
||||
.map((region) => region.parentId!),
|
||||
);
|
||||
// The wizard starts with one full-table empty line purely to make a legal
|
||||
// draft. Once coordinate suggestion provides real rows, keeping it makes
|
||||
// the v2 non-overlap contract unsavable.
|
||||
regions.value = regions.value.filter((region) => !(
|
||||
region.kind === 'line' &&
|
||||
!fieldParentIds.has(region.id) &&
|
||||
suggestedLines.some((suggested) =>
|
||||
region.pageNo === suggested.pageNo &&
|
||||
region.region.x0 <= suggested.region.x0 && region.region.y0 <= suggested.region.y0 &&
|
||||
region.region.x1 >= suggested.region.x1 && region.region.y1 >= suggested.region.y1
|
||||
)
|
||||
));
|
||||
}
|
||||
regions.value.push(...acceptedRegions);
|
||||
selectedId.value = item.regions.find((region) => region.fieldCode)?.id || item.regions[0]?.id || null;
|
||||
}
|
||||
@@ -1193,6 +1311,7 @@ let orderFieldValueRequest = 0;
|
||||
const clearOrderFieldValuePreview = (state: 'idle' | 'loading' | 'failed') => {
|
||||
orderFieldValuePreviews.value = [];
|
||||
orderFieldValueState.value = state;
|
||||
orderFieldValueError.value = '';
|
||||
};
|
||||
/** 根据当前画布定义读取订单字段;过期请求不得覆盖更新后的值框结果。 */
|
||||
const refreshOrderFieldSuggestionValues = async () => {
|
||||
@@ -1212,8 +1331,13 @@ const refreshOrderFieldSuggestionValues = async () => {
|
||||
if (request !== orderFieldValueRequest) return;
|
||||
orderFieldValuePreviews.value = result.fields;
|
||||
orderFieldValueState.value = 'ready';
|
||||
} catch {
|
||||
if (request === orderFieldValueRequest) clearOrderFieldValuePreview('failed');
|
||||
} catch (error) {
|
||||
if (request === orderFieldValueRequest) {
|
||||
clearOrderFieldValuePreview('failed');
|
||||
orderFieldValueError.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
}
|
||||
}
|
||||
};
|
||||
/** 订单字段框或读取方式变化后延迟回读整页字符证据,避免地址字段停留在旧的空候选。 */
|
||||
@@ -1587,6 +1711,9 @@ const renewLeaseOnVisibility = (): void => {
|
||||
};
|
||||
/** 打开路由指定草稿并恢复冻结的标注上下文。 */
|
||||
const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
// 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;
|
||||
active.value = profile;
|
||||
form.profileCode = profile.profile_code;
|
||||
form.displayName = profile.display_name;
|
||||
@@ -1616,9 +1743,13 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
boundSamples.value.find((item) => item.sample_role === "annotation")?.document_id || 0;
|
||||
await loadSampleTables();
|
||||
await loadPages();
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
restoringProfile = false;
|
||||
// Page preview grants are independent from coordinate extraction. A grant
|
||||
// failure must not leave the right-hand recognition panel at "waiting".
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
}
|
||||
};
|
||||
/** 跳转到独立验证页;页面仍需当前标签持有租约,不能绕过草稿单写者保护。 */
|
||||
@@ -1712,11 +1843,14 @@ watch(
|
||||
pageGrant.value = null;
|
||||
pageGrants.value = [];
|
||||
canvasUnavailable.value = false;
|
||||
if (restoringProfile) return;
|
||||
void loadSampleTables();
|
||||
if (active.value) void loadPages();
|
||||
},
|
||||
);
|
||||
watch(() => form.tableId, schedulePreview);
|
||||
watch(() => form.tableId, () => {
|
||||
if (!restoringProfile) schedulePreview();
|
||||
});
|
||||
const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (!dirty.value) return;
|
||||
event.preventDefault();
|
||||
@@ -1841,38 +1975,35 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<output class="save-status" :class="`save-status--${saveState}`">{{ t(`admin.shippingOrderProfiles.workbench.saveStatus.${saveState}`) }}</output>
|
||||
<template v-if="saveState === 'readonly'">
|
||||
<button type="button" class="btn-secondary" @click="downloadLocalDraft">{{ t('admin.shippingOrderProfiles.workbench.exportLocalDraft') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease()">{{ t('admin.shippingOrderProfiles.workbench.recoverLease') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease(true)">{{ t('admin.shippingOrderProfiles.workbench.takeOverLease') }}</button>
|
||||
</template>
|
||||
<div v-if="saveState === 'readonly'" class="header-actions__lease">
|
||||
<button 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>
|
||||
<button
|
||||
v-if="active"
|
||||
v-else-if="active"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
:disabled="!form.documentId || !form.tableId || currentSampleIsTraining || saveState === 'readonly'"
|
||||
:disabled="!form.documentId || !form.tableId || saveState === 'readonly'"
|
||||
@click="() => void addCurrentTrainingSample()"
|
||||
>{{ currentSampleIsTraining ? t('admin.shippingOrderProfiles.blindTest.trainingAdded') : t('admin.shippingOrderProfiles.blindTest.addTrainingSample') }}</button>
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
:disabled="issues.length > 0 || saving || saveState === 'readonly'"
|
||||
class="btn-primary"
|
||||
@click="() => void save()"
|
||||
>
|
||||
{{
|
||||
saving
|
||||
? t("admin.shippingOrderProfiles.saving")
|
||||
: t("admin.shippingOrderProfiles.updateDraft")
|
||||
}}
|
||||
</button>
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
@click="validateProfile(active)"
|
||||
>{{ t('admin.orderProfileValidation.validateTemplate') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">{{ t('admin.shippingOrderProfiles.workbench.returnToLibrary') }}</button>
|
||||
>{{ t('admin.shippingOrderProfiles.workbench.headerAddTrainingSample') }}</button>
|
||||
<div class="header-actions__flow">
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
:disabled="issues.length > 0 || saving || saveState === 'readonly'"
|
||||
class="btn-primary"
|
||||
@click="() => void save()"
|
||||
>{{ saving ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.workbench.headerSaveDraft") }}</button>
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
@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">
|
||||
@@ -1935,7 +2066,7 @@ onBeforeUnmount(() => {
|
||||
<header>
|
||||
<span>{{ t("admin.shippingOrderProfiles.workbench.currentConfiguration") }}</span>
|
||||
</header>
|
||||
<section class="document-match-editor">
|
||||
<section v-if="!documentMatch.requiredAnchors.length || documentAnchorNotice" class="document-match-editor">
|
||||
<div class="document-match-editor__heading">
|
||||
<div>
|
||||
<strong>{{ t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTool') }}</strong>
|
||||
@@ -1944,10 +2075,6 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
<p v-if="!documentMatch.requiredAnchors.length" class="document-match-editor__warning">{{ t('admin.shippingOrderProfiles.workbench.documentMatchAnchorEmpty') }}</p>
|
||||
<p v-if="documentAnchorNotice" class="document-match-editor__warning">{{ documentAnchorNotice }}</p>
|
||||
<article v-for="(anchor, index) in documentMatch.requiredAnchors" :key="`required-${index}`" class="document-match-editor__row">
|
||||
<b>{{ t('common.required') }}</b>
|
||||
<span>{{ anchor.label }}</span><span>{{ anchor.value }}</span>
|
||||
</article>
|
||||
</section>
|
||||
<section v-if="selectedRegion" class="editor">
|
||||
<div class="selected-region-meta">
|
||||
@@ -1995,7 +2122,7 @@ onBeforeUnmount(() => {
|
||||
class="select-field"
|
||||
:disabled="compactEditor || saveState === 'readonly'"
|
||||
@focus="beginFormEdit"
|
||||
@change="finishFormEdit"
|
||||
@change="finishFieldBindingEdit"
|
||||
>
|
||||
<option :value="null">
|
||||
{{ t("admin.shippingOrderProfiles.workbench.selectField") }}
|
||||
@@ -2174,6 +2301,14 @@ onBeforeUnmount(() => {
|
||||
.schema-warning { color: #b91c1c; }
|
||||
.schema-hint { color: #047857; }
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.header-actions__lease,
|
||||
.header-actions__flow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
@@ -2377,9 +2512,6 @@ onBeforeUnmount(() => {
|
||||
.document-match-editor__heading strong { font-size: 0.84rem; }
|
||||
.document-match-editor__heading p { margin: 0.3rem 0 0; font-size: 0.72rem; color: #64748b; }
|
||||
.document-match-editor__warning { margin: 0.6rem 0; color: #b45309; font-size: 0.75rem; }
|
||||
.document-match-editor__row { display: grid; grid-template-columns: auto minmax(0, 1fr) minmax(0, 1.4fr); gap: 0.35rem; align-items: center; margin-top: 0.45rem; }
|
||||
.document-match-editor__row b { font-size: 0.7rem; color: #0f766e; }
|
||||
.document-match-editor__row span { overflow: hidden; color: #475569; font-size: .72rem; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.selected-region-meta { display: grid; gap: .2rem; margin-bottom: .8rem; border-bottom: 1px solid #dbe4ef; padding-bottom: .75rem; }
|
||||
.selected-region-meta span { color: #64748b; font-size: .7rem; font-weight: 700; }
|
||||
.selected-region-meta strong { color: #0f172a; font-size: .82rem; }
|
||||
@@ -2509,8 +2641,10 @@ onBeforeUnmount(() => {
|
||||
background: rgb(15 23 42 / .48);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.save-status { border-radius: 999px; background: #e2e8f0; padding: .4rem .6rem; color: #334155; font-size: .72rem; }
|
||||
.save-status,
|
||||
.training-sample-status { border-radius: 999px; background: #e2e8f0; padding: .4rem .6rem; color: #334155; font-size: .72rem; }
|
||||
.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-workbench .bench-header { max-width: none; padding: .7rem 1rem; color: #e2e8f0; }
|
||||
.editor-workbench .bench-header p { color: #94a3b8; }
|
||||
@@ -2659,8 +2793,13 @@ onBeforeUnmount(() => {
|
||||
}
|
||||
.header-actions {
|
||||
width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.header-actions > button {
|
||||
.header-actions__lease,
|
||||
.header-actions__flow {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.header-actions button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
+25
-1
@@ -34,6 +34,13 @@ const filteredFamilies = computed(() => {
|
||||
return families.value.filter((item) => `${item.profile_code} ${item.display_name}`.toLowerCase().includes(keyword));
|
||||
});
|
||||
|
||||
/** 仅以服务端返回的不可变 Schema 身份决定复制或迁移,列表页不猜测兼容性。 */
|
||||
function schemaMigrationRequired(item: OrderProfileVersionFamilySummary): boolean {
|
||||
return item.published_schema_version_id != null
|
||||
&& item.current_schema_version_id != null
|
||||
&& item.published_schema_version_id !== item.current_schema_version_id;
|
||||
}
|
||||
|
||||
/** 加载模板族摘要;列表只显示聚合结果,不能将每个版本扁平为独立模板。 */
|
||||
async function loadFamilies(): Promise<void> {
|
||||
loading.value = true;
|
||||
@@ -88,6 +95,16 @@ function viewVersion(item: OrderProfileVersionFamilySummary): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: item.profile_code, version: item.default_version } });
|
||||
}
|
||||
|
||||
/** 打开已发布版本的 Schema 迁移决策;字段兼容性只能由详情接口安全计算。 */
|
||||
function openSchemaMigration(item: OrderProfileVersionFamilySummary): void {
|
||||
if (!item.published_version) return;
|
||||
router.push({
|
||||
name: 'AdminShippingOrderDocumentProfileVersionDetail',
|
||||
params: { profileCode: item.profile_code, version: item.published_version },
|
||||
query: { migrate: '1' },
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(loadFamilies);
|
||||
</script>
|
||||
|
||||
@@ -128,11 +145,17 @@ onMounted(loadFamilies);
|
||||
<span class="status-badge" :class="{ draft: item.draft_profile_id, published: !item.draft_profile_id && item.published_profile_id }">
|
||||
{{ item.draft_profile_id ? t('admin.shippingOrderProfiles.library.draft') : item.published_profile_id ? t('admin.shippingOrderProfiles.library.published', { version: item.published_version }) : t('admin.shippingOrderProfiles.library.retired') }}
|
||||
</span>
|
||||
<small v-if="item.published_profile_id && item.current_schema_version" class="schema-status" :class="{ warning: schemaMigrationRequired(item) }">
|
||||
{{ schemaMigrationRequired(item)
|
||||
? t('admin.shippingOrderProfiles.schemaMigration.versionMismatch', { bound: item.published_schema_version, current: item.current_schema_version })
|
||||
: t('admin.shippingOrderProfiles.schemaMigration.versionMatched', { version: item.current_schema_version }) }}
|
||||
</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" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</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>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -171,6 +194,7 @@ onMounted(loadFamilies);
|
||||
.status-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; }
|
||||
.status-badge.draft { border-color: #bae6fd; background: #f0f9ff; color: #0369a1; }
|
||||
.status-badge.published { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
|
||||
.schema-status { display: block; margin-top: 5px; color: #64748b; font-size: 11px; white-space: nowrap; }.schema-status.warning { color: #b45309; }
|
||||
.actions-heading { min-width: 190px; }
|
||||
.profile-library__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
|
||||
|
||||
|
||||
+139
-2
@@ -5,12 +5,17 @@
|
||||
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;后续仅剩盲测隔离与发布治理收口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import { useMessage } from "@/shared/composables/useMessage";
|
||||
import { cloneOrderDocumentProfile } from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import {
|
||||
cloneOrderDocumentProfile,
|
||||
migrateOrderDocumentProfileSchema,
|
||||
} from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
|
||||
import type { ShippingOrderSchemaVersion } from "@/features/admin/types/shipping-order-schema.types";
|
||||
import OrderProfileReadOnlyCanvas from "./components/OrderProfileReadOnlyCanvas.vue";
|
||||
import OrderProfileAuditTimeline from "./components/OrderProfileAuditTimeline.vue";
|
||||
import OrderProfileVersionDiff from "./components/OrderProfileVersionDiff.vue";
|
||||
@@ -26,6 +31,10 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const cloning = ref(false);
|
||||
const migrating = ref(false);
|
||||
const migrationOpen = ref(false);
|
||||
const publishedSchema = ref<ShippingOrderSchemaVersion | null>(null);
|
||||
const migrationResolutions = ref<Record<string, { action: "unbind" } | { replacement_field_id: string }>>({});
|
||||
const {
|
||||
activeTab,
|
||||
detail,
|
||||
@@ -36,6 +45,92 @@ const {
|
||||
versions,
|
||||
} = useOrderProfileVersionDetail();
|
||||
|
||||
const canMigrateSchema = computed(() =>
|
||||
detail.value?.status === "published"
|
||||
&& publishedSchema.value !== null
|
||||
&& detail.value.schema_version_id !== publishedSchema.value.id,
|
||||
);
|
||||
|
||||
const breakingChanges = computed(() => detail.value?.schema_compatibility?.breaking_changes || []);
|
||||
|
||||
const loadPublishedSchema = async () => {
|
||||
try {
|
||||
const state = await getShippingOrderSchemaState();
|
||||
publishedSchema.value = state.versions.find((item) => item.status === "published") || null;
|
||||
} catch {
|
||||
publishedSchema.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const openSchemaMigration = () => {
|
||||
migrationResolutions.value = Object.fromEntries(
|
||||
breakingChanges.value.map((change) => [change.field_id, { action: "unbind" }]),
|
||||
);
|
||||
migrationOpen.value = true;
|
||||
};
|
||||
|
||||
const setMigrationResolution = (fieldId: string, replacementId: string) => {
|
||||
migrationResolutions.value[fieldId] = replacementId
|
||||
? { replacement_field_id: replacementId }
|
||||
: { action: "unbind" };
|
||||
};
|
||||
|
||||
const migrationReplacementId = (fieldId: string): string => {
|
||||
const resolution = migrationResolutions.value[fieldId];
|
||||
return resolution && "replacement_field_id" in resolution ? resolution.replacement_field_id : "";
|
||||
};
|
||||
|
||||
const migrationErrorMessage = (error: unknown): string => {
|
||||
if (!(error instanceof BusinessError)) return t("admin.shippingOrderProfiles.loadFailed");
|
||||
const reason = String(error.details.reason || "");
|
||||
if (reason === "duplicate_field_code") {
|
||||
return t("admin.shippingOrderProfiles.schemaMigration.duplicateSchemaField", {
|
||||
field: error.details.field_code || "-",
|
||||
existingScope: error.details.existing_scope || "-",
|
||||
duplicateScope: error.details.duplicate_scope || "-",
|
||||
});
|
||||
}
|
||||
if (reason === "line_start_field_unbound") {
|
||||
return t("admin.shippingOrderProfiles.schemaMigration.lineStartRequired", {
|
||||
field: error.details.line_start_field_code || "-",
|
||||
});
|
||||
}
|
||||
const fieldPath = String(error.details.field_path || "");
|
||||
return fieldPath
|
||||
? `${error.message} (${t("admin.shippingOrderProfiles.schemaMigration.invalidPath", { path: fieldPath })})`
|
||||
: error.message;
|
||||
};
|
||||
|
||||
const migrateSchema = async () => {
|
||||
if (!detail.value || !publishedSchema.value || migrating.value) return;
|
||||
migrating.value = true;
|
||||
try {
|
||||
const draft = await migrateOrderDocumentProfileSchema(
|
||||
detail.value.id,
|
||||
publishedSchema.value.id,
|
||||
migrationResolutions.value,
|
||||
);
|
||||
message.success(t("admin.shippingOrderProfiles.schemaMigration.created"));
|
||||
migrationOpen.value = false;
|
||||
void router.push({
|
||||
name: "AdminShippingOrderDocumentProfiles",
|
||||
query: { profileCode: draft.profile_code, profileId: String(draft.id) },
|
||||
});
|
||||
} catch (error) {
|
||||
message.error(migrationErrorMessage(error));
|
||||
} finally {
|
||||
migrating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => { void loadPublishedSchema(); });
|
||||
|
||||
watch([detail, publishedSchema, () => route.query.migrate], () => {
|
||||
if (route.query.migrate !== "1" || !canMigrateSchema.value || migrationOpen.value) return;
|
||||
openSchemaMigration();
|
||||
void router.replace({ query: { ...route.query, migrate: undefined } });
|
||||
});
|
||||
|
||||
const pageTitle = computed(() => {
|
||||
if (!detail.value) {
|
||||
return `${profileCode.value} · v${route.params.version || ""}`;
|
||||
@@ -153,6 +248,14 @@ const createNewVersion = async () => {
|
||||
: t("admin.shippingOrderProfiles.newVersion")
|
||||
}}
|
||||
</button>
|
||||
<button
|
||||
v-if="canMigrateSchema"
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
@click="openSchemaMigration"
|
||||
>
|
||||
{{ t("admin.shippingOrderProfiles.schemaMigration.action", { version: publishedSchema?.version }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -209,6 +312,36 @@ const createNewVersion = async () => {
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="migrationOpen" class="migration-backdrop" role="presentation" @click.self="migrationOpen = false">
|
||||
<section class="migration-dialog" role="dialog" aria-modal="true" :aria-label="t('admin.shippingOrderProfiles.schemaMigration.title')">
|
||||
<h2>{{ t("admin.shippingOrderProfiles.schemaMigration.title") }}</h2>
|
||||
<p>{{ t("admin.shippingOrderProfiles.schemaMigration.description", { from: detail?.schema_version, to: publishedSchema?.version }) }}</p>
|
||||
<p class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.revalidation") }}</p>
|
||||
<div v-if="breakingChanges.length" class="migration-changes">
|
||||
<article v-for="change in breakingChanges" :key="change.field_id">
|
||||
<strong>{{ change.before || change.field_id }}</strong>
|
||||
<span>{{ t("admin.shippingOrderProfiles.schemaMigration.reason", { reason: change.reason }) }}</span>
|
||||
<label>
|
||||
{{ t("admin.shippingOrderProfiles.schemaMigration.resolution") }}
|
||||
<select
|
||||
:value="migrationReplacementId(change.field_id)"
|
||||
@change="setMigrationResolution(change.field_id, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="">{{ t("admin.shippingOrderProfiles.schemaMigration.unbind") }}</option>
|
||||
<option v-for="candidate in change.replacement_candidates || []" :key="candidate.field_id" :value="candidate.field_id">
|
||||
{{ candidate.display_name || candidate.field_code || candidate.field_id }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.noBreakingChanges") }}</p>
|
||||
<footer>
|
||||
<button type="button" class="btn-secondary" :disabled="migrating" @click="migrationOpen = false">{{ t("admin.shippingOrderProfiles.schemaMigration.cancel") }}</button>
|
||||
<button type="button" class="btn-primary" :disabled="migrating" @click="migrateSchema">{{ migrating ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.schemaMigration.confirm") }}</button>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -349,6 +482,10 @@ const createNewVersion = async () => {
|
||||
color: var(--status-error-fg);
|
||||
}
|
||||
|
||||
.migration-backdrop { position: fixed; z-index: 30; inset: 0; display: grid; place-items: center; padding: 1rem; background: rgb(15 23 42 / 45%); }
|
||||
.migration-dialog { display: grid; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); }
|
||||
.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }.migration-dialog footer { display: flex; justify-content: flex-end; gap: .5rem; }
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.header-main,
|
||||
.version-switcher {
|
||||
|
||||
+14
-3
@@ -19,12 +19,21 @@ const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: []; }
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const uploading = ref(false);
|
||||
const pendingIntake = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed' } | null>(null);
|
||||
const pendingIntake = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
let pollingTimer: number | null = null;
|
||||
const selectedSample = computed(() => props.samples.find((item) => item.document_id === props.modelValue) || null);
|
||||
|
||||
/** 停止当前轮询;离开步骤或开始新上传时都不保留后台计时器。 */
|
||||
function stopPolling(): void { if (pollingTimer) window.clearTimeout(pollingTimer); pollingTimer = null; }
|
||||
/** 将模板布局失败码转成管理员可执行的提示,不把内部快照内容暴露到页面。 */
|
||||
function sampleFailureMessage(errorCode?: string | null): string {
|
||||
const key = errorCode === 'mineru_cell_coordinates_missing'
|
||||
? 'sampleLayoutCoordinatesMissing'
|
||||
: errorCode === 'shipping_document_layout_snapshot_size_exceeded'
|
||||
? 'sampleLayoutSnapshotTooLarge'
|
||||
: 'sampleParseFailed';
|
||||
return t(`admin.shippingOrderProfiles.wizard.${key}`);
|
||||
}
|
||||
/** 刷新样本列表后按 Intake 精确定位新文档,防止同名历史文件被误选。 */
|
||||
function selectUploadedSample(intakeNo: string): boolean {
|
||||
const sample = props.samples.find((item) => item.intake_no === intakeNo);
|
||||
@@ -46,7 +55,9 @@ async function pollIntake(intakeNo: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingIntake.value = { intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed' };
|
||||
pendingIntake.value = {
|
||||
intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
return;
|
||||
}
|
||||
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1500);
|
||||
@@ -85,7 +96,7 @@ onBeforeUnmount(stopPolling);
|
||||
|
||||
<div v-if="pendingIntake" class="parse-status" :class="{ failed: pendingIntake.state === 'failed' }">
|
||||
<Clock3 v-if="pendingIntake.state === 'parsing'" :size="19" /><span v-else>!</span>
|
||||
<div><strong>{{ pendingIntake.filename }}</strong><p>{{ pendingIntake.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : t('admin.shippingOrderProfiles.wizard.sampleParseFailed') }}</p></div>
|
||||
<div><strong>{{ pendingIntake.filename }}</strong><p>{{ pendingIntake.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : sampleFailureMessage(pendingIntake.errorCode) }}</p></div>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedSample" class="selected-sample"><CheckCircle2 :size="20" /><div><strong>{{ t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong><span>{{ selectedSample.filename || selectedSample.intake_no }} · {{ selectedSample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</span></div></div>
|
||||
|
||||
+49
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts
|
||||
* 用途:验证可视化订单模板表单生成受控规则,并确保切换样本时配置入口不会消失。
|
||||
* 用途:验证可视化订单模板表单生成受控规则、明细字段分组,并确保切换样本时配置入口不会消失。
|
||||
* 依赖:Vitest、orderProfileForm.utils。
|
||||
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端。
|
||||
*/
|
||||
@@ -15,10 +15,37 @@ import {
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
isOrderProfileAnchorRelativeCandidate,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
toOrderProfileAnchorRelativeRegion,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
it.each(['line_no', 'customer_po_line_no'])(
|
||||
'keeps %s available after resolving the main-line fields',
|
||||
(startFieldCode) => {
|
||||
const regions = [
|
||||
{ id: 'main', kind: 'line' as const, label: 'Main', pageNo: 1, region: { x0: .1, y0: .3, x1: .9, y1: .4 } },
|
||||
{ id: 'start', kind: 'field' as const, label: 'Start', fieldCode: startFieldCode, parentId: 'main', pageNo: 1, region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
|
||||
{ id: 'part', kind: 'field' as const, label: 'Part', fieldCode: 'part_number', parentId: 'main', pageNo: 1, region: { x0: .2, y0: .3, x1: .5, y1: .4 } },
|
||||
];
|
||||
|
||||
const grouped = groupUniqueOrderProfileLineFields(regions, ['main']);
|
||||
|
||||
// 关键断言:起行字段选择和 line_layout 序列化复用同一结果时,字段不会被第一次读取消费。
|
||||
expect(grouped.fieldsByLayout.get('main')?.map((item) => item.fieldCode)).toEqual([
|
||||
startFieldCode,
|
||||
'part_number',
|
||||
]);
|
||||
expect(grouped.fieldsByLayout.get('main')?.map((item) => item.fieldCode)).toEqual([
|
||||
startFieldCode,
|
||||
'part_number',
|
||||
]);
|
||||
expect(grouped.boundRegionIds).toEqual(new Set(['start', 'part']));
|
||||
},
|
||||
);
|
||||
|
||||
it('builds only registered direct and composite rules', () => {
|
||||
const rules = buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'direct', target: 'qty' },
|
||||
@@ -198,4 +225,25 @@ describe('order profile form rules', () => {
|
||||
// 完全落在页面外或零面积的框没有可解释的读取边界,必须由管理员重画。
|
||||
expect(normalizeOrderProfileRelativeRegion({ x0: 1.1, y0: .2, x1: 1.2, y1: .3 })).toBeNull();
|
||||
});
|
||||
|
||||
it('serializes a right-of-anchor value box as a movable anchor-relative region', () => {
|
||||
expect(toOrderProfileAnchorRelativeRegion(
|
||||
{ x0: .42, y0: .80, x1: .50, y1: .82 },
|
||||
{ x0: .30, y0: .80, x1: .41, y1: .82 },
|
||||
)).toEqual({ x0: expect.closeTo(1.090909), y0: 0, x1: expect.closeTo(1.818181), y1: 1 });
|
||||
});
|
||||
|
||||
it('keeps a remote legacy value box absolute instead of creating invalid relative offsets', () => {
|
||||
expect(isOrderProfileAnchorRelativeCandidate(
|
||||
{ x0: .33, y0: .58, x1: .72, y1: .60 },
|
||||
{ x0: .02, y0: .10, x1: .15, y1: .12 },
|
||||
)).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps a same-row auto suggestion absolute when its tiny label makes the relative span exceed the contract', () => {
|
||||
expect(isOrderProfileAnchorRelativeCandidate(
|
||||
{ x0: .30, y0: .40, x1: .95, y1: .42 },
|
||||
{ x0: .20, y0: .40, x1: .21, y1: .42 },
|
||||
)).toBe(false);
|
||||
});
|
||||
});
|
||||
+70
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
|
||||
* 用途:构造可视化订单模板的白名单列规则,并控制样本表格配置区的安全显示。
|
||||
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
|
||||
* 依赖:订单 Profile DTO。
|
||||
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次。
|
||||
*/
|
||||
@@ -19,6 +19,38 @@ export interface OrderProfileColumnSelection {
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface OrderProfileLineFieldGroups {
|
||||
fieldsByLayout: Map<string, OrderProfileCanvasRegion[]>;
|
||||
boundRegionIds: Set<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按物理行顺序收集唯一的明细字段绑定,供起行字段选择和最终定义复用同一份结果。
|
||||
* 核心逻辑:每个 Schema 字段只归属首个物理行;返回结果可重复读取,不会因预览起行字段而消费绑定。
|
||||
* @param regions - 当前页面全部画布区域。
|
||||
* @param layoutIds - 按主行到续行排列的物理行 ID。
|
||||
* @returns 每个物理行的字段区域,以及已进入正式绑定的区域 ID。
|
||||
*/
|
||||
export const groupUniqueOrderProfileLineFields = (
|
||||
regions: OrderProfileCanvasRegion[],
|
||||
layoutIds: string[],
|
||||
): OrderProfileLineFieldGroups => {
|
||||
const claimedFieldCodes = new Set<string>();
|
||||
const boundRegionIds = new Set<string>();
|
||||
const fieldsByLayout = new Map<string, OrderProfileCanvasRegion[]>();
|
||||
layoutIds.forEach((layoutId) => {
|
||||
const fields = regions.filter((item) => {
|
||||
if (item.kind !== 'field' || item.parentId !== layoutId || !item.fieldCode) return false;
|
||||
if (claimedFieldCodes.has(item.fieldCode)) return false;
|
||||
claimedFieldCodes.add(item.fieldCode);
|
||||
boundRegionIds.add(item.id);
|
||||
return true;
|
||||
});
|
||||
fieldsByLayout.set(layoutId, fields);
|
||||
});
|
||||
return { fieldsByLayout, boundRegionIds };
|
||||
};
|
||||
|
||||
/**
|
||||
* 将画布或历史草稿的区域限制为页面归一化坐标。
|
||||
* @param region - 可能来自拖拽、自动建议或历史模板的页面区域。
|
||||
@@ -36,6 +68,43 @@ export const normalizeOrderProfileRelativeRegion = (
|
||||
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
|
||||
};
|
||||
|
||||
/** 将页面值框换算为锚点尺寸的相对偏移,供标签右侧字段随标签移动读取。 */
|
||||
export const toOrderProfileAnchorRelativeRegion = (
|
||||
valueRegion: OrderProfileRelativeRegion,
|
||||
anchorRegion: OrderProfileRelativeRegion,
|
||||
): OrderProfileRelativeRegion | null => {
|
||||
const width = anchorRegion.x1 - anchorRegion.x0;
|
||||
const height = anchorRegion.y1 - anchorRegion.y0;
|
||||
if (width <= 0 || height <= 0) return null;
|
||||
const relative = {
|
||||
x0: (valueRegion.x0 - anchorRegion.x0) / width,
|
||||
y0: (valueRegion.y0 - anchorRegion.y0) / height,
|
||||
x1: (valueRegion.x1 - anchorRegion.x0) / width,
|
||||
y1: (valueRegion.y1 - anchorRegion.y0) / height,
|
||||
};
|
||||
return Number.isFinite(relative.x0) && Number.isFinite(relative.y0)
|
||||
&& Number.isFinite(relative.x1) && Number.isFinite(relative.y1)
|
||||
&& relative.x0 < relative.x1 && relative.y0 < relative.y1 ? relative : null;
|
||||
};
|
||||
|
||||
/** 判断标签和值框是否是同一视觉行,只有这种画布关系可安全改为随标签移动。 */
|
||||
export const isOrderProfileAnchorRelativeCandidate = (
|
||||
valueRegion: OrderProfileRelativeRegion,
|
||||
anchorRegion: OrderProfileRelativeRegion,
|
||||
): boolean => {
|
||||
const anchorHeight = anchorRegion.y1 - anchorRegion.y0;
|
||||
const valueHeight = valueRegion.y1 - valueRegion.y0;
|
||||
if (anchorHeight <= 0 || valueHeight <= 0) return false;
|
||||
const tolerance = Math.max(anchorHeight, valueHeight) * 2;
|
||||
if (!(valueRegion.y0 <= anchorRegion.y1 + tolerance
|
||||
&& anchorRegion.y0 <= valueRegion.y1 + tolerance)) return false;
|
||||
const relative = toOrderProfileAnchorRelativeRegion(valueRegion, anchorRegion);
|
||||
// Backend intentionally bounds offsets to prevent a tiny auto-detected label
|
||||
// from producing an unbounded template rule. Fall back to the page box here.
|
||||
return relative !== null && [relative.x0, relative.y0, relative.x1, relative.y1]
|
||||
.every((value) => value >= -12 && value <= 12);
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
|
||||
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
|
||||
|
||||
Reference in new issue
Block a user