feat(shipping-notice): 添加货代履约策略管理功能,支持策略创建、发布及版本控制,增强订单冻结和预约管理逻辑

This commit is contained in:
hugo committed 2026-07-23 12:06:34 +08:00
1 parent abd8fc1e16
commit d62f5107b2
82 files changed
+4914 -514

No files matched your search

@@ -1,8 +1,8 @@
<!--
features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue
用途:通过 MinerU 样本表格可视化创建和发布订单文档 Profile。
用途:通过 MinerU/PDF 坐标样本工作台创建、复核和发布订单文档 Profile。
依赖:Profile/Schema API、BusinessError、useMessage、Vue I18n。
逻辑:管理员选择真实样本、表格、表头行和列目标;浏览器不展示 HTML,也不编辑 JSON/结构指纹。
逻辑:管理员选择样本并按物理行编辑列边界和字段;后端提供全量/当前行建议及最终候选,浏览器不展示 HTML 或结构指纹。
-->
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
@@ -14,12 +14,16 @@ import {
createOrderProfileSample,
createOrderProfileFromSample,
deleteOrderDocumentProfile,
deleteOrderProfileSample,
getOrderProfileSampleTables,
getOrderProfileSampleStatus,
generateOrderProfileOcrCoordinateEvidence,
listOrderDocumentProfiles,
listOrderProfileSamples,
publishOrderDocumentProfile,
retireOrderDocumentProfile,
previewOrderProfileCoordinateReconstruction,
suggestOrderProfileCoordinateReconstruction,
updateOrderProfileFromSample,
} from '@/features/admin/api/shipping-order-document-profile.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
@@ -28,11 +32,16 @@ import type {
OrderProfileSampleDocument,
OrderProfileSamplePreview,
OrderProfileSampleTable,
CoordinateReconstructionPreview,
CoordinateReconstructionSettings,
CoordinateSubrowLayout,
ShippingOrderDocumentProfile,
} from '@/features/admin/types/shipping-order-document-profile.types';
import {
buildOrderProfileColumnRules,
findDuplicateOrderProfileTargets,
mergeOrderProfileHeaderLabels,
shouldShowStandardOrderProfilePreview,
} from './orderProfileForm.utils';
import type {
ShippingOrderFieldConfig,
@@ -49,7 +58,27 @@ const editingProfileId = ref<number | null>(null);
const editingLockVersion = ref<number | null>(null);
const profiles = ref<ShippingOrderDocumentProfile[]>([]);
const samples = ref<OrderProfileSampleDocument[]>([]);
const sampleSearch = ref('');
const preview = ref<OrderProfileSamplePreview | null>(null);
const reconstructionPreview = ref<CoordinateReconstructionPreview | null>(null);
const reconstructing = ref(false);
const reconstructionPreviewFailed = ref(false);
const suggesting = ref(false);
const suggestingSubrowIndex = ref<number | null>(null);
const ocrGenerating = ref(false);
const reconstructionMethod = ref<CoordinateReconstructionSettings['method']>('native_pdf_coordinates.v1');
const reconstructionConfirmed = ref(false);
const reconstructionFieldSignature = ref('');
const columnBoundaryInput = ref('0, 0.10, 0.25, 0.33, 0.52, 0.65, 0.77, 0.88, 0.94, 1');
const multiSubrowEnabled = ref(false);
type SubrowEditor = {
role: CoordinateSubrowLayout['role']; row_offset: number; boundaries: string;
fields: Array<string | null>; samples: string[][];
};
const subrowEditors = ref<SubrowEditor[]>([
{ role: 'main', row_offset: 0, boundaries: '0, 1', fields: [null], samples: [] },
]);
const selectedSubrowIndex = ref(0);
const publishedSchemas = ref<ShippingOrderSchemaVersion[]>([]);
const form = reactive({
profile_code: '', display_name: '', schema_version_id: 0,
@@ -62,6 +91,32 @@ const columnRules = ref<Array<{ extractor_key: 'direct' | 'temp_internal_parts';
const selectedTable = computed<OrderProfileSampleTable | null>(() => (
preview.value?.tables.find((item) => item.table_id === form.table_id) || null
));
const showStandardPreview = computed(() => shouldShowStandardOrderProfilePreview(
Boolean(selectedTable.value?.profile_creation_allowed),
multiSubrowEnabled.value,
Boolean(selectedTable.value?.coordinate_reconstruction_available),
));
const displayedTable = computed<OrderProfileSampleTable | CoordinateReconstructionPreview | null>(() => (
reconstructionPreview.value || selectedTable.value
));
const mergedHeaderLabels = computed(() => mergeOrderProfileHeaderLabels(
displayedTable.value?.rows || [],
form.header_row_index,
displayedTable.value?.column_count || 0,
));
const displayedRowRole = (rowIndex: number) => (
reconstructionPreview.value?.row_roles[rowIndex] || (rowIndex <= form.header_row_index ? 'header' : 'data')
);
const displayedSourceRows = (rowIndex: number) => reconstructionPreview.value?.source_row_indices[rowIndex] || [];
const visibleSamples = computed(() => {
const keyword = sampleSearch.value.trim().toLowerCase();
return samples.value.filter((sample) => !keyword || String(sample.filename || '').toLowerCase().includes(keyword));
});
const selectedSample = computed(() => samples.value.find((sample) => sample.document_id === form.document_id) || null);
const selectedSubrow = computed(() => subrowEditors.value[selectedSubrowIndex.value] || subrowEditors.value[0]);
const currentProfileIds = computed(() => new Set(
profiles.value.filter((profile) => profile.status === 'published').map((profile) => profile.id),
));
const selectedSchema = computed(() => publishedSchemas.value.find((item) => item.id === form.schema_version_id) || null);
const lineFields = computed<ShippingOrderFieldConfig[]>(() => (
selectedSchema.value?.definition?.fields.filter((item) => item.enabled !== false && item.scope === 'line') || []
@@ -77,14 +132,25 @@ const duplicateTargets = computed(() => {
if (form.row_structure !== 'preserved') return [];
return findDuplicateOrderProfileTargets(normalizedRules());
});
const reconstructionMatchesFields = computed(() => (
!reconstructionPreview.value || reconstructionFieldSignature.value === coordinateFieldSignature()
));
const livePreviewStatusKey = computed(() => {
if (reconstructing.value) return 'livePreviewUpdating';
if (!subrowEditors.value[0]?.fields.includes('line_no')) return 'livePreviewWaitingLineNo';
if (reconstructionPreviewFailed.value) return 'livePreviewFailed';
if (reconstructionPreview.value && reconstructionMatchesFields.value) return 'livePreviewReady';
return 'livePreviewEmpty';
});
const canSave = computed(() => Boolean(
form.profile_code.trim() && form.display_name.trim() && form.schema_version_id
&& form.document_id && form.table_id && selectedTable.value
&& selectedTable.value.profile_creation_allowed
&& form.document_id && form.table_id && displayedTable.value
&& (selectedTable.value?.profile_creation_allowed || reconstructionConfirmed.value)
&& form.data_start_row_index > form.header_row_index
&& form.header_row_index >= 0
&& form.data_start_row_index < (selectedTable.value?.row_count || 0)
&& form.data_start_row_index < (displayedTable.value?.row_count || 0)
&& duplicateTargets.value.length === 0
&& reconstructionMatchesFields.value
&& (form.row_structure === 'unsupported_row_structure' || hasConfiguredColumn.value),
));
@@ -115,6 +181,8 @@ const load = async () => {
/** 选择样本文档后读取由后端展开的网格。 */
const loadPreview = async () => {
preview.value = null;
reconstructionPreview.value = null;
reconstructionConfirmed.value = false;
form.table_id = '';
if (!form.document_id) return;
try {
@@ -145,6 +213,8 @@ const uploadSample = async (event: Event) => {
await new Promise((resolve) => window.setTimeout(resolve, 1000));
}
await load();
const uploadedSample = samples.value.find((sample) => sample.intake_no === intake.intake_no);
if (uploadedSample) form.document_id = uploadedSample.document_id;
message.success(t('admin.shippingOrderProfiles.sampleUploaded'));
} catch (error) {
showError(error);
@@ -156,10 +226,274 @@ const uploadSample = async (event: Event) => {
/** 表格变化时按真实列数初始化受控列映射。 */
const resetColumns = () => {
const count = selectedTable.value?.column_count || 0;
const count = displayedTable.value?.column_count || 0;
columnRules.value = Array.from({ length: count }, () => ({ extractor_key: 'direct', target: '' }));
form.header_row_index = 0;
form.data_start_row_index = Math.min(1, Math.max((selectedTable.value?.row_count || 1) - 1, 0));
form.data_start_row_index = Math.min(1, Math.max((displayedTable.value?.row_count || 1) - 1, 0));
};
/** 清理上一张表的坐标重建编辑状态,避免切换样本后隐藏或污染当前配置区。 */
const resetCoordinateReconstructionState = () => {
if (reconstructionPreviewTimer) window.clearTimeout(reconstructionPreviewTimer);
reconstructionPreviewTimer = null;
reconstructionPreviewRequestId += 1;
multiSubrowEnabled.value = false;
subrowEditors.value = [
{ role: 'main', row_offset: 0, boundaries: '0, 1', fields: [null], samples: [] },
];
selectedSubrowIndex.value = 0;
reconstructionPreview.value = null;
reconstructionPreviewFailed.value = false;
reconstructionConfirmed.value = false;
reconstructionFieldSignature.value = '';
};
/** 按重建列数保留已有字段映射,并只补齐或裁掉实际变化的列。 */
const resizeColumns = (count: number) => {
columnRules.value = Array.from({ length: count }, (_, index) => (
columnRules.value[index] || { extractor_key: 'direct', target: '' }
));
};
/** 解析 0..1 严格递增边界;单内容块物理行允许只使用 0,1。 */
const parseBoundaryInput = (raw: string): number[] | null => {
const values = raw.split(',').map((item) => Number(item.trim()));
if (values.length < 2 || values.some((value) => !Number.isFinite(value)) || values[0] !== 0 || values[values.length - 1] !== 1
|| values.some((value, index) => index > 0 && value <= values[index - 1]!)) return null;
return values;
};
/** 边界数量变化时保留已有子行字段映射,并补齐新的列。 */
const syncSubrowFields = (editor: SubrowEditor) => {
const count = Math.max((parseBoundaryInput(editor.boundaries)?.length || 1) - 1, 0);
editor.fields = Array.from({ length: count }, (_, index) => editor.fields[index] || null);
};
/** 返回边界尺的有效刻度;输入异常时保留最小可编辑区间。 */
const subrowBoundaries = (editor: SubrowEditor) => parseBoundaryInput(editor.boundaries) || [0, 1];
/** 拖动内部刻度时限制其不能越过相邻边界,并同步字段列数。 */
const updateSubrowBoundary = (editor: SubrowEditor, boundaryIndex: number, rawValue: string) => {
const values = [...subrowBoundaries(editor)];
const previous = values[boundaryIndex - 1] ?? 0;
const next = values[boundaryIndex + 1] ?? 1;
values[boundaryIndex] = Math.min(next - 0.01, Math.max(previous + 0.01, Number(rawValue)));
editor.boundaries = values.map((value) => Number(value.toFixed(2))).join(', ');
syncSubrowFields(editor);
};
/** 只有区间宽度足够容纳两个最小 1% 列时才允许继续拆分。 */
const canSplitSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
const boundaries = subrowBoundaries(editor);
return boundaries[columnIndex + 1]! - boundaries[columnIndex]! >= 0.02;
};
/** 在当前逻辑明细末尾增加任意一条物理子行配置。 */
const addSubrow = () => {
subrowEditors.value.push({
role: 'continuation', row_offset: subrowEditors.value.length,
boundaries: '0, 1', fields: [null], samples: [],
});
selectedSubrowIndex.value = subrowEditors.value.length - 1;
};
/** 删除指定续行并重排 row_offset;首行是新明细锚点,禁止删除。 */
const removeSubrow = (index: number) => {
if (index <= 0) return;
subrowEditors.value.splice(index, 1);
subrowEditors.value.forEach((item, rowIndex) => {
item.row_offset = rowIndex;
item.role = rowIndex === 0 ? 'main' : 'continuation';
});
selectedSubrowIndex.value = Math.min(selectedSubrowIndex.value, subrowEditors.value.length - 1);
};
/** 在指定列区间中点插入新边界;原列配置保留,新列插入其后等待映射。 */
const addSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
const boundaries = [...subrowBoundaries(editor)];
const midpoint = Number(((boundaries[columnIndex]! + boundaries[columnIndex + 1]!) / 2).toFixed(2));
boundaries.splice(columnIndex + 1, 0, midpoint);
editor.boundaries = boundaries.join(', ');
editor.fields.splice(columnIndex + 1, 0, null);
editor.samples.splice(columnIndex + 1, 0, []);
};
/** 删除当前物理行的一列并合并相邻边界;每行至少保留一列。 */
const removeSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
if (editor.fields.length <= 1) return;
const boundaries = [...subrowBoundaries(editor)];
boundaries.splice(columnIndex === 0 ? 1 : columnIndex, 1);
editor.boundaries = boundaries.join(', ');
editor.fields.splice(columnIndex, 1);
editor.samples.splice(columnIndex, 1);
};
/** 将多子行编辑器转换为严格契约;主行必须映射 line_no 才能识别新明细。 */
const multiSubrowLayouts = (): CoordinateSubrowLayout[] | null => {
const result: CoordinateSubrowLayout[] = [];
for (const editor of subrowEditors.value) {
const boundaries = parseBoundaryInput(editor.boundaries);
if (!boundaries) return null;
const columnCount = boundaries.length - 1;
result.push({
role: editor.role, row_offset: editor.row_offset,
column_boundaries: boundaries,
column_field_codes: Array.from({ length: columnCount }, (_, index) => editor.fields[index] || null),
});
}
const main = result.find((item) => item.role === 'main');
return main?.column_field_codes.includes('line_no') ? result : null;
};
/** 将管理员确认的相对列边界转为受控坐标重建参数。 */
const coordinateReconstructionSettings = (includeFieldRules = false): CoordinateReconstructionSettings | null => {
if (multiSubrowEnabled.value) {
const layouts = multiSubrowLayouts();
return layouts ? { method: reconstructionMethod.value, column_boundaries: [], subrow_layouts: layouts } : null;
}
const values = parseBoundaryInput(columnBoundaryInput.value);
if (!values) return null;
const fieldCodes = includeFieldRules ? columnRules.value.map((item) => (
item.extractor_key === 'direct' ? (item.target || null) : 'customer_part_number'
)) : [];
const lineStartColumn = fieldCodes.findIndex((code) => code === 'line_no');
return {
method: reconstructionMethod.value,
column_boundaries: values,
column_field_codes: fieldCodes.some(Boolean) ? fieldCodes : [],
line_start_column_index: lineStartColumn >= 0 ? lineStartColumn : 0,
};
};
/** 生成影响内容适配和新行判断的列映射签名,用于阻止未复核配置直接保存。 */
const coordinateFieldSignature = () => JSON.stringify({
columnRules: columnRules.value.map((item) => ({ extractor_key: item.extractor_key, target: item.target })),
multiSubrowEnabled: multiSubrowEnabled.value,
subrows: subrowEditors.value,
});
/** 用后端冻结坐标生成行版式和边界建议;仅确定性行号自动绑定,其余字段由管理员确认。 */
const suggestLayouts = async () => {
if (!form.document_id || !form.table_id) return;
suggesting.value = true;
reconstructionPreview.value = null;
reconstructionConfirmed.value = false;
try {
const suggestion = await suggestOrderProfileCoordinateReconstruction(form.document_id, form.table_id);
multiSubrowEnabled.value = true;
subrowEditors.value = suggestion.subrow_layouts.map((item) => ({
role: item.role,
row_offset: item.row_offset,
boundaries: item.column_boundaries.join(', '),
fields: [...item.suggested_field_codes],
samples: item.column_samples,
}));
selectedSubrowIndex.value = 0;
message.success(t('admin.shippingOrderProfiles.layoutSuggestionReady'));
} catch (error) {
showError(error);
} finally {
suggesting.value = false;
}
};
/** 仅重新识别当前物理行,按列位置保留已确认字段,不覆盖其他行版式。 */
const suggestCurrentSubrow = async () => {
const editor = selectedSubrow.value;
if (!editor || !form.document_id || !form.table_id) return;
suggestingSubrowIndex.value = editor.row_offset;
try {
const suggestion = await suggestOrderProfileCoordinateReconstruction(
form.document_id, form.table_id, editor.row_offset,
);
const current = suggestion.subrow_layouts[0];
if (!current) return;
const previousFields = [...editor.fields];
editor.boundaries = current.column_boundaries.join(', ');
editor.samples = current.column_samples;
editor.fields = current.suggested_field_codes.map((code, index) => code || previousFields[index] || null);
message.success(t('admin.shippingOrderProfiles.currentRowSuggestionReady'));
} catch (error) {
showError(error);
} finally {
suggestingSubrowIndex.value = null;
}
};
/** 对扫描 PDF 生成 OCR 字符坐标,随后重新加载表格并继续人工审核。 */
const generateOcrEvidence = async () => {
if (!form.document_id || !form.table_id) return;
const tableId = form.table_id;
ocrGenerating.value = true;
try {
await generateOrderProfileOcrCoordinateEvidence(form.document_id, form.table_id);
reconstructionMethod.value = 'ocr_pdf_coordinates.v1';
await loadPreview();
form.table_id = preview.value?.tables.some((table) => table.table_id === tableId)
? tableId : (preview.value?.tables[0]?.table_id || '');
message.success(t('admin.shippingOrderProfiles.ocrEvidenceReady'));
} catch (error) {
showError(error);
} finally {
ocrGenerating.value = false;
}
};
let reconstructionPreviewTimer: ReturnType<typeof window.setTimeout> | null = null;
let reconstructionPreviewRequestId = 0;
/** 请求只读重建候选;自动刷新静默校验,手动刷新继续给出明确错误。 */
const runReconstructionPreview = async (silent = false) => {
if (multiSubrowEnabled.value && !subrowEditors.value[0]?.fields.includes('line_no')) {
if (!silent) message.error(t('admin.shippingOrderProfiles.lineNoRequired'));
return;
}
const settings = coordinateReconstructionSettings(true);
if (!settings || !form.document_id || !form.table_id) {
if (!silent) message.error(t('admin.shippingOrderProfiles.reconstructionBoundariesInvalid'));
return;
}
const requestId = ++reconstructionPreviewRequestId;
reconstructing.value = true;
reconstructionPreviewFailed.value = false;
reconstructionConfirmed.value = false;
try {
const result = await previewOrderProfileCoordinateReconstruction(form.document_id, form.table_id, settings);
if (requestId !== reconstructionPreviewRequestId) return;
reconstructionPreview.value = result;
resizeColumns(reconstructionPreview.value.column_count);
if (multiSubrowEnabled.value) {
const fieldCodes = multiSubrowLayouts()?.flatMap((item) => item.column_field_codes.filter((code): code is string => Boolean(code))) || [];
const uniqueCodes = [...new Set(fieldCodes)];
columnRules.value = uniqueCodes.map((target) => ({ extractor_key: 'direct', target }));
}
reconstructionFieldSignature.value = coordinateFieldSignature();
form.header_row_index = 0;
form.data_start_row_index = Math.min(1, Math.max(reconstructionPreview.value.row_count - 1, 0));
} catch (error) {
if (requestId !== reconstructionPreviewRequestId) return;
reconstructionPreviewFailed.value = true;
if (!silent) showError(error);
} finally {
if (requestId === reconstructionPreviewRequestId) reconstructing.value = false;
}
};
/** 手动重建用于显式复核,并保留完整错误反馈。 */
const reconstructTable = () => runReconstructionPreview(false);
/** 映射编辑停止后自动刷新右侧候选,避免每次选择都产生请求。 */
const scheduleReconstructionPreview = () => {
if (reconstructionPreviewTimer) window.clearTimeout(reconstructionPreviewTimer);
reconstructionPreviewFailed.value = false;
reconstructionConfirmed.value = false;
if (!multiSubrowEnabled.value || !selectedTable.value?.coordinate_reconstruction_available) return;
if (!form.document_id || !form.table_id || !subrowEditors.value[0]?.fields.includes('line_no')) return;
if (!coordinateReconstructionSettings(true)) return;
reconstructionPreviewTimer = window.setTimeout(() => {
reconstructionPreviewTimer = null;
void runReconstructionPreview(true);
}, 500);
};
/** 转换结构化表单为后端白名单列规则,不提交结构指纹或 HTML。 */
@@ -185,6 +519,7 @@ const saveDraft = async () => {
profile_code: form.profile_code.trim().toUpperCase(),
display_name: form.display_name.trim(),
column_rules: form.row_structure === 'preserved' ? normalizedRules() : [],
coordinate_reconstruction: reconstructionConfirmed.value ? coordinateReconstructionSettings(true) : null,
};
if (editingProfileId.value && editingLockVersion.value !== null) {
await updateOrderProfileFromSample(editingProfileId.value, {
@@ -266,6 +601,26 @@ const removeProfile = async (profile: ShippingOrderDocumentProfile) => {
}
};
/** 删除前端专用样本;后端再次校验解析状态、所有权与盲测引用。 */
const removeSample = async () => {
const sample = selectedSample.value;
if (!sample?.can_delete || !window.confirm(t('admin.shippingOrderProfiles.deleteSampleConfirm'))) return;
try {
await deleteOrderProfileSample(sample.intake_no);
await load();
form.document_id = samples.value[0]?.document_id || 0;
if (!form.document_id) preview.value = null;
message.success(t('admin.shippingOrderProfiles.sampleDeleted'));
} catch (error) {
showError(error);
}
};
/** 统一显示上传时间,避免同名样本在下拉框中不可区分。 */
const formatSampleTime = (value?: string | null) => (
value ? new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'short' }).format(new Date(value)) : '-'
);
/** 退役当前发布版本;历史运行继续使用冻结快照。 */
const retireProfile = async (profile: ShippingOrderDocumentProfile) => {
if (!window.confirm(t('admin.shippingOrderProfiles.retireConfirm'))) return;
@@ -279,7 +634,29 @@ const retireProfile = async (profile: ShippingOrderDocumentProfile) => {
};
watch(() => form.document_id, loadPreview);
watch(() => form.table_id, resetColumns);
watch(() => form.table_id, () => {
resetCoordinateReconstructionState();
resetColumns();
});
watch(() => form.header_row_index, (headerRowIndex) => {
if (form.data_start_row_index <= headerRowIndex) form.data_start_row_index = headerRowIndex + 1;
});
watch(columnRules, () => {
if (reconstructionConfirmed.value && reconstructionFieldSignature.value !== coordinateFieldSignature()) {
reconstructionConfirmed.value = false;
}
}, { deep: true });
watch(multiSubrowEnabled, (enabled) => {
if (enabled) subrowEditors.value.forEach(syncSubrowFields);
reconstructionPreview.value = null;
reconstructionPreviewFailed.value = false;
reconstructionConfirmed.value = false;
scheduleReconstructionPreview();
});
watch(subrowEditors, () => {
if (reconstructionPreview.value) reconstructionConfirmed.value = false;
scheduleReconstructionPreview();
}, { deep: true });
onMounted(load);
</script>
@@ -291,83 +668,242 @@ onMounted(load);
<p class="mt-1 text-sm text-slate-500">{{ t('admin.shippingOrderProfiles.subtitle') }}</p>
</header>
<div class="grid gap-6 xl:grid-cols-[420px_minmax(0,1fr)]">
<form class="space-y-4 rounded-xl border border-slate-200 bg-white p-5 shadow-sm" @submit.prevent="saveDraft">
<div class="flex items-center justify-between gap-3">
<div class="space-y-6">
<form class="space-y-5 rounded-xl border border-slate-200 bg-white p-5 shadow-sm" @submit.prevent="saveDraft">
<div class="flex items-center justify-between gap-3 border-b border-slate-100 pb-4">
<h2 class="font-semibold">{{ t(editingProfileId ? 'admin.shippingOrderProfiles.editTitle' : 'admin.shippingOrderProfiles.createTitle') }}</h2>
<button v-if="editingProfileId" type="button" class="text-sm text-slate-500" @click="cancelEdit">{{ t('common.cancel') }}</button>
<div class="flex items-center gap-2">
<button v-if="editingProfileId" type="button" class="h-9 rounded-lg px-3 text-sm text-slate-600 hover:bg-slate-100" @click="cancelEdit">{{ t('common.cancel') }}</button>
<button type="submit" :disabled="!canSave || saving" class="h-9 rounded-lg bg-blue-600 px-4 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50">
{{ saving ? t('admin.shippingOrderProfiles.saving') : t(editingProfileId ? 'admin.shippingOrderProfiles.updateDraft' : 'admin.shippingOrderProfiles.createDraft') }}
</button>
</div>
</div>
<label class="block text-sm">
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.sample') }}</span>
<select v-model.number="form.document_id" class="w-full rounded-lg border border-slate-300 px-3 py-2">
<option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option>
<option v-for="sample in samples" :key="sample.document_id" :value="sample.document_id">
{{ sample.filename || `Document ${sample.document_id}` }} ({{ sample.table_count }})
</option>
</select>
</label>
<div class="rounded-lg border border-dashed border-slate-300 p-3">
<p class="text-sm text-slate-600">{{ t('admin.shippingOrderProfiles.uploadSampleHint') }}</p>
<input ref="sampleInput" class="sr-only" type="file" accept=".pdf,.eml,application/pdf,message/rfc822" @change="uploadSample" />
<button type="button" :disabled="sampleUploading" class="mt-2 rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700 disabled:opacity-50" @click="sampleInput?.click()">
{{ sampleUploading ? t('common.loading') : t('admin.shippingOrderProfiles.uploadSample') }}
</button>
<div class="space-y-4">
<div class="max-w-[980px]">
<label class="block text-xs font-medium text-slate-600">{{ t('admin.shippingOrderProfiles.sample') }}</label>
<div class="mt-1.5 flex flex-wrap items-center gap-2">
<input v-model="sampleSearch" class="h-9 w-52 rounded-lg border border-slate-300 px-3 text-sm" :placeholder="t('admin.shippingOrderProfiles.searchSample')" />
<select v-model.number="form.document_id" class="h-9 min-w-0 flex-1 rounded-lg border border-slate-300 bg-white px-3 text-sm">
<option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option>
<option v-for="sample in visibleSamples" :key="sample.document_id" :value="sample.document_id">
{{ sample.filename || `Document ${sample.document_id}` }} · {{ formatSampleTime(sample.created_at) }} · {{ sample.parse_status }} · {{ sample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}
</option>
</select>
<input ref="sampleInput" class="sr-only" type="file" accept=".pdf,.eml,application/pdf,message/rfc822" @change="uploadSample" />
<button type="button" :disabled="sampleUploading" class="h-9 shrink-0 rounded-lg border border-blue-200 px-3 text-sm font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="sampleInput?.click()">
{{ sampleUploading ? t('common.loading') : t('admin.shippingOrderProfiles.uploadSample') }}
</button>
<button type="button" :disabled="!selectedSample?.can_delete" class="h-9 shrink-0 rounded-lg border border-red-200 px-3 text-sm font-medium text-red-600 hover:bg-red-50 disabled:cursor-not-allowed disabled:border-slate-200 disabled:text-slate-400" @click="removeSample">
{{ t('admin.shippingOrderProfiles.deleteSample') }}
</button>
</div>
<p v-if="selectedSample" class="mt-1.5 text-xs text-slate-500">
{{ t('admin.shippingOrderProfiles.sampleDetails', { time: formatSampleTime(selectedSample.created_at), status: selectedSample.parse_status }) }}
· {{ selectedSample.is_template_sample ? t('admin.shippingOrderProfiles.templateSampleOnly') : t('admin.shippingOrderProfiles.businessSampleProtected') }}
</p>
</div>
<div class="flex flex-wrap items-end gap-x-3 gap-y-3">
<label class="w-44 text-xs font-medium text-slate-600">
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.table') }}</span>
<select v-model="form.table_id" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm" :disabled="!preview">
<option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option>
<option v-for="table in preview?.tables || []" :key="table.table_id" :value="table.table_id">P{{ table.page_no }} · {{ table.row_count }}×{{ table.column_count }}</option>
</select>
</label>
<label class="w-52 text-xs font-medium text-slate-600">
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.schema') }}</span>
<select v-model.number="form.schema_version_id" :disabled="Boolean(editingProfileId)" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm disabled:bg-slate-100">
<option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }} · {{ schema.status }}</option>
</select>
</label>
<label class="w-44 text-xs font-medium text-slate-600">
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.code') }}</span>
<input v-model="form.profile_code" :disabled="Boolean(editingProfileId)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm disabled:bg-slate-100" />
</label>
<label class="w-72 text-xs font-medium text-slate-600">
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.name') }}</span>
<input v-model="form.display_name" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" />
</label>
<label class="mb-2 flex items-center gap-2 whitespace-nowrap text-sm text-slate-700"><input v-model="form.drop_zero_qty" type="checkbox" />{{ t('admin.shippingOrderProfiles.dropZeroQty') }}</label>
</div>
<details class="max-w-[980px] rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
<summary class="cursor-pointer text-sm font-medium text-slate-700">{{ t('admin.shippingOrderProfiles.advancedSettings') }}</summary>
<div class="mt-3 flex flex-wrap items-end gap-3 border-t border-slate-200 pt-3">
<label class="w-72 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.rowStructure') }}</span><select v-model="form.row_structure" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm"><option value="preserved">{{ t('admin.shippingOrderProfiles.rowPreserved') }}</option><option value="unsupported_row_structure">{{ t('admin.shippingOrderProfiles.rowUnsupported') }}</option></select></label>
<label class="w-36 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.headerRow') }}</span><input v-model.number="form.header_row_index" type="number" min="0" :max="Math.max((displayedTable?.row_count || 1) - 2, 0)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
<label class="w-32 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.dataRow') }}</span><input v-model.number="form.data_start_row_index" type="number" :min="form.header_row_index + 1" :max="Math.max((displayedTable?.row_count || 1) - 1, 0)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
<label v-if="editingProfileId" class="w-80 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.changeNote') }}</span><input v-model="form.change_note" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
</div>
</details>
</div>
<label class="block text-sm">
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.table') }}</span>
<select v-model="form.table_id" class="w-full rounded-lg border border-slate-300 px-3 py-2" :disabled="!preview">
<option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option>
<option v-for="table in preview?.tables || []" :key="table.table_id" :value="table.table_id">
P{{ table.page_no }} · {{ table.row_count }}×{{ table.column_count }}
</option>
</select>
</label>
<div class="grid grid-cols-2 gap-3">
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.code') }}</span><input v-model="form.profile_code" :disabled="Boolean(editingProfileId)" class="w-full rounded-lg border border-slate-300 px-3 py-2 disabled:bg-slate-100" /></label>
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.name') }}</span><input v-model="form.display_name" class="w-full rounded-lg border border-slate-300 px-3 py-2" /></label>
<div v-if="selectedTable && !selectedTable.profile_creation_allowed" class="overflow-hidden rounded-xl border border-slate-200 bg-slate-50">
<div class="flex items-start gap-3 border-b border-slate-200 bg-white px-4 py-3">
<span class="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-amber-100 text-sm font-bold text-amber-700">!</span>
<div>
<p class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.reconstructionRequired') }}</p>
<p v-if="selectedTable.coordinate_reconstruction_available" class="mt-1 text-xs leading-5 text-slate-500">{{ t('admin.shippingOrderProfiles.autoSuggestLayoutHint') }}</p>
</div>
</div>
<template v-if="selectedTable.coordinate_reconstruction_available">
<label class="flex items-center gap-2 border-b border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700">
<input v-model="multiSubrowEnabled" type="checkbox" />
{{ t('admin.shippingOrderProfiles.multiSubrowEnabled') }}
</label>
<label v-if="!multiSubrowEnabled" class="block p-4 text-xs"><span class="mb-1 block">{{ t('admin.shippingOrderProfiles.columnBoundaries') }}</span><input v-model="columnBoundaryInput" class="w-full rounded-lg border border-slate-300 bg-white px-3 py-2" /></label>
<div v-else class="p-3">
<div class="grid min-w-0 gap-3 lg:grid-cols-[180px_minmax(0,1fr)]">
<aside class="overflow-hidden rounded-lg border border-slate-200 bg-white">
<div class="border-b border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600">{{ t('admin.shippingOrderProfiles.physicalRows') }}</div>
<div class="p-1.5">
<button v-for="(editor, editorIndex) in subrowEditors" :key="editor.row_offset" type="button" class="mb-1 flex h-9 w-full items-center justify-between rounded-md px-2.5 text-left text-sm last:mb-0" :class="selectedSubrowIndex === editorIndex ? 'bg-blue-50 font-medium text-blue-700' : 'text-slate-700 hover:bg-slate-50'" @click="selectedSubrowIndex = editorIndex">
<span>{{ t(editorIndex === 0 ? 'admin.shippingOrderProfiles.firstSubrow' : 'admin.shippingOrderProfiles.followingSubrow', { index: editorIndex + 1 }) }}</span>
<span class="text-xs opacity-60">{{ editor.fields.length }}</span>
</button>
</div>
<div class="flex border-t border-slate-200 p-1.5">
<button type="button" class="h-8 flex-1 rounded-md text-xs font-medium text-blue-700 hover:bg-blue-50" @click="addSubrow">+ {{ t('admin.shippingOrderProfiles.addSubrow') }}</button>
</div>
</aside>
<section v-if="selectedSubrow" class="min-w-0 overflow-hidden rounded-lg border border-slate-200 bg-white">
<div class="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200 px-3 py-2">
<div><span class="text-sm font-semibold text-slate-900">{{ t(selectedSubrowIndex === 0 ? 'admin.shippingOrderProfiles.firstSubrow' : 'admin.shippingOrderProfiles.followingSubrow', { index: selectedSubrowIndex + 1 }) }}</span><span class="ml-2 text-xs text-slate-400">{{ selectedSubrow.fields.length }} {{ t('admin.shippingOrderProfiles.columnsUnit') }}</span></div>
<div class="flex items-center gap-1.5">
<button type="button" :disabled="suggestingSubrowIndex !== null" class="h-8 rounded-md border border-blue-200 px-2.5 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="suggestCurrentSubrow">{{ suggestingSubrowIndex === selectedSubrow.row_offset ? t('common.loading') : t('admin.shippingOrderProfiles.suggestCurrentRow') }}</button>
<button v-if="selectedSubrowIndex > 0" type="button" class="h-8 rounded-md px-2.5 text-xs font-medium text-red-600 hover:bg-red-50" @click="removeSubrow(selectedSubrowIndex)">{{ t('common.delete') }}</button>
</div>
</div>
<div class="p-3">
<div class="mb-2 flex items-center justify-between text-[11px] font-medium text-slate-500">
<span>{{ t('admin.shippingOrderProfiles.visualBoundaries') }}</span>
<span>{{ t('admin.shippingOrderProfiles.dragBoundaryHint') }}</span>
</div>
<div class="relative h-12 rounded-md border border-slate-300 bg-slate-50 px-1 pt-1">
<div class="flex h-7 overflow-hidden rounded border border-white bg-white shadow-sm">
<div v-for="(_, index) in selectedSubrow.fields" :key="index" class="flex min-w-0 items-center justify-center border-r border-blue-100 bg-blue-50/60 px-1 text-[10px] font-medium text-blue-700 last:border-r-0" :style="{ width: `${(subrowBoundaries(selectedSubrow)[index + 1]! - subrowBoundaries(selectedSubrow)[index]!) * 100}%` }">
<span class="truncate">{{ index + 1 }} · {{ Math.round((subrowBoundaries(selectedSubrow)[index + 1]! - subrowBoundaries(selectedSubrow)[index]!) * 100) }}%</span>
</div>
</div>
<template v-for="(boundary, boundaryIndex) in subrowBoundaries(selectedSubrow).slice(1, -1)" :key="boundaryIndex">
<span class="pointer-events-none absolute bottom-1 top-1 w-px bg-blue-500" :style="{ left: `${boundary * 100}%` }" />
<input :value="boundary" type="range" min="0.01" max="0.99" step="0.01" class="boundary-slider absolute inset-x-0 top-5 h-5 w-full" :aria-label="t('admin.shippingOrderProfiles.boundaryHandle', { index: boundaryIndex + 1 })" @input="updateSubrowBoundary(selectedSubrow, boundaryIndex + 1, ($event.target as HTMLInputElement).value)" />
</template>
</div>
<div class="mt-3 flex gap-2 overflow-x-auto pb-2">
<article v-for="(_, index) in selectedSubrow.fields" :key="index" class="w-52 shrink-0 rounded-lg border border-slate-200 bg-slate-50 p-2.5">
<div class="flex items-center justify-between gap-2">
<span class="text-xs font-semibold text-slate-700">{{ t('admin.shippingOrderProfiles.subrowColumn', { index: index + 1 }) }}</span>
<div class="flex items-center gap-1">
<button type="button" :disabled="!canSplitSubrowColumn(selectedSubrow, index)" class="rounded px-1.5 py-0.5 text-[11px] font-medium text-blue-700 hover:bg-blue-50 disabled:cursor-not-allowed disabled:text-slate-300 disabled:hover:bg-transparent" @click="addSubrowColumn(selectedSubrow, index)">+ {{ t('admin.shippingOrderProfiles.insertColumnAfter') }}</button>
<button v-if="selectedSubrow.fields.length > 1" type="button" class="rounded px-1.5 py-0.5 text-[11px] text-red-600 hover:bg-red-50" @click="removeSubrowColumn(selectedSubrow, index)">{{ t('common.delete') }}</button>
</div>
</div>
<div class="mt-2 truncate rounded-md bg-white px-2 py-1.5 text-xs text-slate-500" :title="selectedSubrow.samples[index]?.join(' / ') || '-'">{{ selectedSubrow.samples[index]?.join(' / ') || '-' }}</div>
<select v-model="selectedSubrow.fields[index]" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
<option :value="null">{{ t('admin.shippingOrderProfiles.ignoreColumn') }}</option>
<option v-for="field in lineFields" :key="field.field_id" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option>
</select>
<div class="mt-2 font-mono text-[10px] text-slate-400">{{ Math.round(subrowBoundaries(selectedSubrow)[index]! * 100) }}%–{{ Math.round(subrowBoundaries(selectedSubrow)[index + 1]! * 100) }}%</div>
</article>
</div>
<details class="mt-2 text-[11px] text-slate-500">
<summary class="cursor-pointer select-none font-medium">{{ t('admin.shippingOrderProfiles.preciseBoundaryValues') }}</summary>
<input v-model="selectedSubrow.boundaries" class="mt-1.5 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 font-mono text-[11px]" @change="syncSubrowFields(selectedSubrow)" />
</details>
</div>
</section>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-slate-200 bg-white p-2">
<button type="button" :disabled="suggesting" class="h-8 rounded-md border border-blue-200 px-2.5 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="suggestLayouts">{{ suggesting ? t('common.loading') : t('admin.shippingOrderProfiles.autoSuggestAllRows') }}</button>
<button type="button" :disabled="reconstructing" class="h-8 rounded-md bg-blue-600 px-3 text-xs font-medium text-white hover:bg-blue-700 disabled:opacity-50" @click="reconstructTable">{{ t('admin.shippingOrderProfiles.reconstructTable') }}</button>
</div>
<aside class="mt-3 min-w-0 overflow-hidden rounded-lg border border-slate-200 bg-white">
<div class="flex items-center justify-between gap-3 border-b border-slate-200 px-3 py-2">
<div>
<h3 class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.livePreview') }}</h3>
<p class="mt-0.5 text-[11px]" :class="reconstructionPreviewFailed ? 'text-red-600' : reconstructing ? 'text-blue-600' : 'text-slate-500'">{{ t(`admin.shippingOrderProfiles.${livePreviewStatusKey}`) }}</p>
</div>
<label v-if="reconstructionPreview" class="flex shrink-0 items-center gap-1.5 text-xs font-medium text-slate-700"><input v-model="reconstructionConfirmed" type="checkbox" />{{ t('admin.shippingOrderProfiles.confirmPreview') }}</label>
</div>
<div class="max-h-[52vh] min-h-56 overflow-auto">
<table v-if="reconstructionPreview" class="min-w-full border-collapse text-xs">
<tbody>
<tr v-for="(row, rowIndex) in reconstructionPreview.rows" :key="rowIndex" :class="displayedRowRole(rowIndex) === 'deleted' ? 'bg-red-50 text-slate-500' : rowIndex === form.header_row_index ? 'bg-blue-50 font-semibold' : ''">
<td class="sticky left-0 min-w-20 border border-slate-200 bg-slate-50 px-2 py-1.5 text-[11px] text-slate-500">
<div>{{ t(`admin.shippingOrderProfiles.rowRole.${displayedRowRole(rowIndex)}`) }}</div>
<div v-if="displayedSourceRows(rowIndex).length" class="mt-0.5">{{ displayedSourceRows(rowIndex).map((value) => value + 1).join(', ') }}</div>
</td>
<td v-for="(cell, columnIndex) in row" :key="columnIndex" class="max-w-52 whitespace-nowrap border border-slate-200 px-2 py-1.5" :title="cell">{{ cell }}</td>
</tr>
</tbody>
</table>
<div v-else class="flex min-h-56 items-center justify-center px-6 text-center text-xs leading-5 text-slate-500">{{ t(`admin.shippingOrderProfiles.${livePreviewStatusKey}`) }}</div>
</div>
</aside>
</div>
<div class="flex flex-wrap items-center justify-between gap-2 border-t border-slate-200 bg-white px-4 py-2.5">
<p class="text-[11px] text-slate-500">{{ t('admin.shippingOrderProfiles.multiSubrowHint') }}</p>
<p v-if="reconstructionPreview && !reconstructionMatchesFields" class="text-[11px] font-medium text-amber-700">{{ t('admin.shippingOrderProfiles.rebuildAfterFieldMapping') }}</p>
</div>
</template>
<template v-else>
<div class="flex flex-wrap items-center justify-between gap-3 p-4">
<p class="text-xs text-amber-900">{{ t('admin.shippingOrderProfiles.reconstructionUnavailable') }}</p>
<button type="button" :disabled="ocrGenerating" class="rounded-lg border border-amber-500 bg-white px-3 py-2 text-sm text-amber-900 disabled:opacity-50" @click="generateOcrEvidence">{{ ocrGenerating ? t('common.loading') : t('admin.shippingOrderProfiles.generateOcrEvidence') }}</button>
</div>
</template>
</div>
<label class="block text-sm">
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.schema') }}</span>
<select v-model.number="form.schema_version_id" :disabled="Boolean(editingProfileId)" class="w-full rounded-lg border border-slate-300 px-3 py-2 disabled:bg-slate-100">
<option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }} · {{ schema.status }}</option>
</select>
</label>
<label class="block text-sm">
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.rowStructure') }}</span>
<select v-model="form.row_structure" class="w-full rounded-lg border border-slate-300 px-3 py-2">
<option value="preserved">{{ t('admin.shippingOrderProfiles.rowPreserved') }}</option>
<option value="unsupported_row_structure">{{ t('admin.shippingOrderProfiles.rowUnsupported') }}</option>
</select>
</label>
<div class="grid grid-cols-2 gap-3">
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.headerRow') }}</span><input v-model.number="form.header_row_index" type="number" min="0" class="w-full rounded-lg border border-slate-300 px-3 py-2" /></label>
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.dataRow') }}</span><input v-model.number="form.data_start_row_index" type="number" min="1" class="w-full rounded-lg border border-slate-300 px-3 py-2" /></label>
</div>
<label class="flex items-center gap-2 text-sm"><input v-model="form.drop_zero_qty" type="checkbox" />{{ t('admin.shippingOrderProfiles.dropZeroQty') }}</label>
<label class="block text-sm">
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.changeNote') }}</span>
<textarea v-model="form.change_note" rows="2" class="w-full rounded-lg border border-slate-300 px-3 py-2" />
</label>
<p v-if="duplicateTargets.length" class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
{{ t('admin.shippingOrderProfiles.duplicateTargets', { fields: duplicateTargets.join(', ') }) }}
</p>
<p v-if="selectedTable && !selectedTable.profile_creation_allowed" class="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">
<p v-if="selectedTable && !selectedTable.profile_creation_allowed && !reconstructionConfirmed" class="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">
{{ t('admin.shippingOrderProfiles.structureBlocked') }}
</p>
<button type="submit" :disabled="!canSave || saving" class="w-full rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white disabled:opacity-50">
{{ saving ? t('admin.shippingOrderProfiles.saving') : t(editingProfileId ? 'admin.shippingOrderProfiles.updateDraft' : 'admin.shippingOrderProfiles.createDraft') }}
</button>
</form>
<div class="min-w-0 space-y-4">
<div class="overflow-auto rounded-xl border border-slate-200 bg-white shadow-sm">
<table v-if="selectedTable" class="min-w-full border-collapse text-sm">
<div v-if="showStandardPreview" class="min-w-0 space-y-4">
<section v-if="displayedTable && form.header_row_index > 0 && form.row_structure === 'preserved'" class="overflow-hidden rounded-xl border border-blue-200 bg-white shadow-sm">
<div class="border-b border-blue-100 bg-blue-50 px-4 py-3">
<h3 class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.multiRowHeaderMapping') }}</h3>
<p class="mt-1 text-xs text-slate-600">{{ t('admin.shippingOrderProfiles.multiRowHeaderHint', { end: form.header_row_index }) }}</p>
</div>
<div class="flex gap-2 overflow-x-auto p-3">
<article v-for="(label, columnIndex) in mergedHeaderLabels" :key="columnIndex" class="w-52 shrink-0 rounded-lg border border-slate-200 bg-slate-50 p-2.5">
<div class="text-[11px] font-semibold text-slate-500">{{ t('admin.shippingOrderProfiles.mergedHeaderColumn', { index: columnIndex + 1 }) }}</div>
<div class="mt-1 min-h-10 break-words text-xs font-medium leading-5 text-slate-800">{{ label || '-' }}</div>
<select v-model="columnRule(columnIndex).target" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
<option value="">{{ t('admin.shippingOrderProfiles.ignoreColumn') }}</option>
<option v-for="field in lineFields" :key="field.field_id" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option>
</select>
<select v-model="columnRule(columnIndex).extractor_key" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
<option value="direct">{{ t('admin.shippingOrderProfiles.direct') }}</option>
<option value="temp_internal_parts" :disabled="!compositeExtractorAvailable">{{ t('admin.shippingOrderProfiles.compositePart') }}</option>
</select>
</article>
</div>
</section>
<div class="max-h-[70vh] overflow-auto rounded-xl border border-slate-200 bg-white shadow-sm">
<div v-if="reconstructionPreview" class="border-b border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">{{ t('admin.shippingOrderProfiles.reconstructionPreview') }}</div>
<table v-if="displayedTable" class="min-w-full border-collapse text-sm">
<tbody>
<tr v-for="(row, rowIndex) in selectedTable.rows" :key="rowIndex" :class="rowIndex === form.header_row_index ? 'bg-blue-50 font-semibold' : ''">
<td class="sticky left-0 border border-slate-200 bg-slate-50 px-2 py-2 text-xs text-slate-500">{{ rowIndex }}</td>
<tr v-for="(row, rowIndex) in displayedTable.rows" :key="rowIndex" :class="rowIndex <= form.header_row_index ? 'bg-blue-50 font-semibold' : displayedRowRole(rowIndex) === 'deleted' ? 'bg-red-50 text-slate-500' : ''">
<td class="sticky left-0 min-w-24 border border-slate-200 bg-slate-50 px-2 py-2 text-xs text-slate-500">
<div>{{ rowIndex }}</div>
<div v-if="reconstructionPreview" class="mt-1 font-medium" :class="displayedRowRole(rowIndex) === 'deleted' ? 'text-red-600' : 'text-emerald-700'">
{{ t(`admin.shippingOrderProfiles.rowRole.${displayedRowRole(rowIndex)}`) }}
</div>
<div v-if="displayedSourceRows(rowIndex).length" class="mt-1 text-[11px]">
{{ t('admin.shippingOrderProfiles.sourceRows', { rows: displayedSourceRows(rowIndex).map((value) => value + 1).join(', ') }) }}
</div>
</td>
<td v-for="(cell, columnIndex) in row" :key="columnIndex" class="max-w-[260px] border border-slate-200 px-3 py-2 align-top">
<div class="break-words">{{ cell }}</div>
<div v-if="rowIndex === form.header_row_index && form.row_structure === 'preserved'" class="mt-2 space-y-1">
<div v-if="rowIndex === form.header_row_index && form.header_row_index === 0 && form.row_structure === 'preserved' && !multiSubrowEnabled" class="mt-2 space-y-1">
<div v-if="columnRule(columnIndex).extractor_key === 'temp_internal_parts'" class="rounded bg-slate-100 px-2 py-1 text-xs text-slate-600">
customer_part_number + part_number
</div>
@@ -380,6 +916,9 @@ onMounted(load);
<option value="temp_internal_parts" :disabled="!compositeExtractorAvailable">{{ t('admin.shippingOrderProfiles.compositePart') }}</option>
</select>
</div>
<div v-else-if="rowIndex === form.header_row_index && multiSubrowEnabled" class="mt-2 rounded bg-slate-100 px-2 py-1 text-xs text-slate-600">
{{ cell }}
</div>
</td>
</tr>
</tbody>
@@ -394,7 +933,7 @@ onMounted(load);
<div v-if="loading" class="p-6 text-sm text-slate-500">{{ t('common.loading') }}</div>
<div v-else class="divide-y divide-slate-100">
<div v-for="profile in profiles" :key="profile.id" class="flex flex-wrap items-center justify-between gap-3 px-5 py-4">
<div><div class="font-medium">{{ profile.display_name }} · v{{ profile.version }}</div><div class="text-xs text-slate-500">{{ profile.profile_code }} · Schema v{{ profile.schema_version }} · {{ profile.status }}<span v-if="profile.change_note"> · {{ profile.change_note }}</span></div></div>
<div><div class="font-medium">{{ profile.display_name }} · v{{ profile.version }} <span v-if="currentProfileIds.has(profile.id)" class="rounded bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-800">{{ t('admin.shippingOrderProfiles.currentVersion') }}</span></div><div class="text-xs text-slate-500">{{ profile.profile_code }} · Schema v{{ profile.schema_version }} · {{ profile.status }}<span v-if="profile.published_at"> · {{ t('admin.shippingOrderProfiles.publishedAt', { time: formatSampleTime(profile.published_at) }) }}</span><span v-if="profile.change_note"> · {{ profile.change_note }}</span></div></div>
<div class="flex gap-2">
<button v-if="profile.status === 'draft'" class="rounded border border-slate-300 px-3 py-1.5 text-sm text-slate-700" @click="editDraft(profile)">{{ t('common.edit') }}</button>
<button v-if="profile.status === 'draft'" class="rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700" @click="publishProfile(profile)">{{ t('admin.shippingOrderProfiles.publish') }}</button>
@@ -408,3 +947,45 @@ onMounted(load);
</div>
</section>
</template>
<style scoped>
.boundary-slider {
appearance: none;
background: transparent;
pointer-events: none;
}
.boundary-slider::-webkit-slider-runnable-track {
height: 1px;
background: transparent;
}
.boundary-slider::-webkit-slider-thumb {
width: 12px;
height: 20px;
margin-top: -10px;
appearance: none;
border: 2px solid white;
border-radius: 4px;
background: #2563eb;
box-shadow: 0 0 0 1px #2563eb;
cursor: ew-resize;
pointer-events: auto;
}
.boundary-slider::-moz-range-track {
height: 1px;
background: transparent;
}
.boundary-slider::-moz-range-thumb {
width: 10px;
height: 18px;
border: 2px solid white;
border-radius: 4px;
background: #2563eb;
box-shadow: 0 0 0 1px #2563eb;
cursor: ew-resize;
pointer-events: auto;
}
</style>
@@ -1,6 +1,6 @@
/**
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts
* 用途:验证可视化订单模板表单只生成受控规则并阻止目标字段重复映射。
* 用途:验证可视化订单模板表单生成受控规则,并确保切换样本时配置入口不会消失。
* 依赖:Vitest、orderProfileForm.utils。
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端。
*/
@@ -9,6 +9,8 @@ import { describe, expect, it } from 'vitest';
import {
buildOrderProfileColumnRules,
findDuplicateOrderProfileTargets,
mergeOrderProfileHeaderLabels,
shouldShowStandardOrderProfilePreview,
} from './orderProfileForm.utils';
describe('order profile form rules', () => {
@@ -45,4 +47,25 @@ describe('order profile form rules', () => {
{ extractor_key: 'temp_internal_parts', target: '' },
], false)).toEqual([]);
});
it('keeps directly configurable tables visible despite stale multi-row state', () => {
// 断言上一张表残留的多物理行开关不能隐藏当前可直接配置的表格。
expect(shouldShowStandardOrderProfilePreview(true, true, true)).toBe(true);
expect(shouldShowStandardOrderProfilePreview(false, true, true)).toBe(false);
});
it('merges every physical header row into stable logical column labels', () => {
const labels = mergeOrderProfileHeaderLabels([
['Item', 'Material', 'Vendor Part Number'],
['Item', 'Description', ''],
['IncoTerm', '', 'Manufacturer Part'],
], 2, 3);
// 断言同列跨行文字按顺序合并,并去掉展开 rowspan 产生的重复标签。
expect(labels).toEqual([
'Item / IncoTerm',
'Material / Description',
'Vendor Part Number / Manufacturer Part',
]);
});
});
@@ -1,6 +1,6 @@
/**
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
* 用途:构造可视化订单模板的白名单列规则,并在提交前发现目标字段冲突。
* 用途:构造可视化订单模板的白名单列规则,并控制样本表格配置区的安全显示。
* 依赖:订单 Profile DTO。
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次。
*/
@@ -12,6 +12,39 @@ export interface OrderProfileColumnSelection {
target: string;
}
/**
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
* @param multiSubrowEnabled - 当前是否启用多物理行坐标重建
* @param coordinateReconstructionAvailable - 当前表格是否具备坐标重建证据
* @returns 为 true 时显示普通表格及字段配置入口
*/
export const shouldShowStandardOrderProfilePreview = (
profileCreationAllowed: boolean,
multiSubrowEnabled: boolean,
coordinateReconstructionAvailable: boolean,
): boolean => (
profileCreationAllowed || !multiSubrowEnabled || !coordinateReconstructionAvailable
);
/**
* 将表头区域内同一逻辑列的多行文字合并为虚拟列头,重复的 rowspan/colspan 文本只保留一次。
* @param rows - 后端展开后的样本表格行
* @param headerRowIndex - 最后一行表头的零基索引
* @param columnCount - 表格逻辑列数
* @returns 与逻辑列一一对应的合并表头文字
*/
export const mergeOrderProfileHeaderLabels = (
rows: string[][], headerRowIndex: number, columnCount: number,
): string[] => Array.from({ length: columnCount }, (_, columnIndex) => {
const labels: string[] = [];
rows.slice(0, Math.max(headerRowIndex + 1, 0)).forEach((row) => {
const label = String(row[columnIndex] || '').replace(/\s+/g, ' ').trim();
if (label && !labels.some((item) => item.toLowerCase() === label.toLowerCase())) labels.push(label);
});
return labels.join(' / ');
});
/** 将逐列选择转换为后端白名单规则;不可用的复合解析器不会进入请求。 */
export const buildOrderProfileColumnRules = (
selections: OrderProfileColumnSelection[], compositeExtractorAvailable: boolean,