feat(shipping-notice): 添加订单文档 Profile 的样本和审计管理功能,支持样本绑定、审计记录和模板预览,增强文档模板的管理和验证能力

This commit is contained in:
hugo committed 2026-07-27 09:11:25 +08:00
1 parent d62f5107b2
commit 93777fd6df
63 files changed
+9707 -1491

No files matched your search

@@ -77,7 +77,7 @@
<PaginationBar v-model:page="exportPage" v-model:page-size="auditPageSize" :total="exports.length" />
</div>
<div v-else class="object-list-panel">
<div v-else-if="activeTab !== 'orderSchema'" class="object-list-panel">
<div class="object-list">
<div v-if="!currentItems.length" class="empty-state">{{ t('admin.shippingInventory.emptyConfig') }}</div>
<button
@@ -1,991 +1,13 @@
<!--
features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue
用途:通过 MinerU/PDF 坐标样本工作台创建、复核和发布订单文档 Profile。
依赖:Profile/Schema API、BusinessError、useMessage、Vue I18n。
逻辑:管理员选择样本并按物理行编辑列边界和字段;后端提供全量/当前行建议及最终候选,浏览器不展示 HTML 或结构指纹。
用途:订单坐标 Profile 管理路由入口。
依赖:OrderProfileWorkbench。
逻辑:页面编排保持极薄;受控页面预览、区域标注、版本抽屉和草稿保护全部由工作台组件协作完成。
-->
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
cloneOrderDocumentProfile,
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';
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
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,
ShippingOrderSchemaVersion,
} from '@/features/admin/types/shipping-order-schema.types';
const { t } = useI18n();
const message = useMessage();
const loading = ref(false);
const saving = ref(false);
const sampleUploading = ref(false);
const sampleInput = ref<HTMLInputElement | null>(null);
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,
document_id: 0, table_id: '', header_row_index: 0, data_start_row_index: 1,
row_structure: 'preserved' as 'preserved' | 'unsupported_row_structure',
drop_zero_qty: true, change_note: '',
});
const columnRules = ref<Array<{ extractor_key: 'direct' | 'temp_internal_parts'; target: string }>>([]);
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') || []
));
const compositeExtractorAvailable = computed(() => {
const codes = new Set(lineFields.value.map((item) => item.field_code));
return codes.has('customer_part_number') && codes.has('part_number');
});
const hasConfiguredColumn = computed(() => columnRules.value.some((item) => (
item.extractor_key === 'temp_internal_parts' ? compositeExtractorAvailable.value : Boolean(item.target)
)));
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 && 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 < (displayedTable.value?.row_count || 0)
&& duplicateTargets.value.length === 0
&& reconstructionMatchesFields.value
&& (form.row_structure === 'unsupported_row_structure' || hasConfiguredColumn.value),
));
/** 将 API 错误映射到统一消息;页面不展示后端内部详情。 */
const showError = (error: unknown) => {
if (error instanceof BusinessError) message.error(t(`errors.codes.${error.code}`, error.message));
else message.error(t('admin.shippingOrderProfiles.loadFailed'));
};
/** 加载 Profile、样本和不可变 Schema 版本。 */
const load = async () => {
loading.value = true;
try {
const [profileRows, sampleRows, schemaState] = await Promise.all([
listOrderDocumentProfiles(), listOrderProfileSamples(), getShippingOrderSchemaState(),
]);
profiles.value = profileRows;
samples.value = sampleRows;
publishedSchemas.value = schemaState.versions.filter((item) => item.status !== 'draft' && item.definition);
if (!form.schema_version_id) form.schema_version_id = schemaState.versions.find((item) => item.status === 'published')?.id || 0;
} catch (error) {
showError(error);
} finally {
loading.value = false;
}
};
/** 选择样本文档后读取由后端展开的网格。 */
const loadPreview = async () => {
preview.value = null;
reconstructionPreview.value = null;
reconstructionConfirmed.value = false;
form.table_id = '';
if (!form.document_id) return;
try {
preview.value = await getOrderProfileSampleTables(form.document_id);
form.table_id = preview.value.tables[0]?.table_id || '';
} catch (error) {
showError(error);
}
};
/** 上传管理员专用 PDF/EML 样本并轮询预解析;此入口不创建发货任务或调用 Dify。 */
const uploadSample = async (event: Event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
const extension = file.name.split('.').pop()?.toLowerCase();
if (extension !== 'pdf' && extension !== 'eml') {
message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid'));
return;
}
sampleUploading.value = true;
try {
const asset = await uploadFileAsset(file);
const intake = await createOrderProfileSample(asset.asset_no);
for (let attempt = 0; attempt < 30; attempt += 1) {
const state = await getOrderProfileSampleStatus(intake.intake_no);
if (state.parse_status === 'parsed') break;
if (state.parse_status === 'parse_failed') throw new Error(state.error_code || 'sample parse failed');
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);
} finally {
sampleUploading.value = false;
if (sampleInput.value) sampleInput.value.value = '';
}
};
/** 表格变化时按真实列数初始化受控列映射。 */
const resetColumns = () => {
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((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。 */
const normalizedRules = () => buildOrderProfileColumnRules(
columnRules.value, compositeExtractorAvailable.value,
);
/** 模板渲染前确保指定列存在规则对象。 */
const columnRule = (columnIndex: number) => {
if (!columnRules.value[columnIndex]) {
columnRules.value[columnIndex] = { extractor_key: 'direct', target: '' };
}
return columnRules.value[columnIndex]!;
};
/** 创建或更新草稿;指纹由后端按当前样本 HTML 计算。 */
const saveDraft = async () => {
if (!canSave.value) return;
saving.value = true;
try {
const payload = {
...form,
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, {
...payload, expected_lock_version: editingLockVersion.value,
});
} else {
await createOrderProfileFromSample(payload);
}
message.success(t(editingProfileId.value
? 'admin.shippingOrderProfiles.updated'
: 'admin.shippingOrderProfiles.created'));
editingProfileId.value = null;
editingLockVersion.value = null;
await load();
} catch (error) {
showError(error);
} finally {
saving.value = false;
}
};
/** 进入草稿配置模式;结构仍必须从管理员随后选择的新样本生成。 */
const editDraft = (profile: ShippingOrderDocumentProfile) => {
editingProfileId.value = profile.id;
editingLockVersion.value = profile.lock_version;
form.profile_code = profile.profile_code;
form.display_name = profile.display_name;
form.schema_version_id = profile.schema_version_id;
form.row_structure = profile.definition.row_structure;
form.drop_zero_qty = profile.definition.drop_zero_qty;
form.change_note = profile.change_note || '';
form.document_id = 0;
preview.value = null;
form.table_id = '';
};
/** 取消草稿编辑并恢复新建模式。 */
const cancelEdit = () => {
editingProfileId.value = null;
editingLockVersion.value = null;
form.profile_code = '';
form.display_name = '';
form.change_note = '';
form.document_id = 0;
};
/** 从不可变版本复制下一草稿,并立即进入样本重配模式。 */
const createNextVersion = async (profile: ShippingOrderDocumentProfile) => {
try {
const draft = await cloneOrderDocumentProfile(profile.id);
editDraft(draft);
message.success(t('admin.shippingOrderProfiles.cloned'));
await load();
} catch (error) {
showError(error);
}
};
/** 发布草稿并刷新版本列表。 */
const publishProfile = async (profile: ShippingOrderDocumentProfile) => {
try {
await publishOrderDocumentProfile(profile.id, profile.lock_version);
message.success(t('admin.shippingOrderProfiles.published'));
await load();
} catch (error) {
showError(error);
}
};
/** 删除错误草稿;发布版本由服务端保护。 */
const removeProfile = async (profile: ShippingOrderDocumentProfile) => {
if (!window.confirm(t('admin.shippingOrderProfiles.deleteConfirm'))) return;
try {
await deleteOrderDocumentProfile(profile.id);
message.success(t('admin.shippingOrderProfiles.deleted'));
await load();
} catch (error) {
showError(error);
}
};
/** 删除前端专用样本;后端再次校验解析状态、所有权与盲测引用。 */
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;
try {
await retireOrderDocumentProfile(profile.id);
message.success(t('admin.shippingOrderProfiles.retired'));
await load();
} catch (error) {
showError(error);
}
};
watch(() => form.document_id, loadPreview);
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);
import OrderProfileWorkbench from './OrderProfileWorkbench.vue';
</script>
<template>
<section class="min-h-full bg-slate-50 p-6 text-slate-900">
<div class="mx-auto max-w-[1500px] space-y-6">
<header>
<h1 class="text-2xl font-semibold">{{ t('admin.shippingOrderProfiles.title') }}</h1>
<p class="mt-1 text-sm text-slate-500">{{ t('admin.shippingOrderProfiles.subtitle') }}</p>
</header>
<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>
<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>
<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>
<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>
<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 && !reconstructionConfirmed" class="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">
{{ t('admin.shippingOrderProfiles.structureBlocked') }}
</p>
</form>
<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 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.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>
<select v-else v-model="columnRule(columnIndex).target" class="w-full rounded border border-slate-300 px-2 py-1 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="w-full rounded border border-slate-300 px-2 py-1 text-xs">
<option value="direct">{{ t('admin.shippingOrderProfiles.direct') }}</option>
<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>
</table>
<div v-else class="p-10 text-center text-sm text-slate-500">{{ t('admin.shippingOrderProfiles.previewEmpty') }}</div>
</div>
</div>
</div>
<div class="rounded-xl border border-slate-200 bg-white shadow-sm">
<div class="border-b border-slate-200 px-5 py-4 font-semibold">{{ t('admin.shippingOrderProfiles.versions') }}</div>
<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 }} <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>
<button v-if="profile.status === 'draft'" class="rounded border border-red-300 px-3 py-1.5 text-sm text-red-700" @click="removeProfile(profile)">{{ t('common.delete') }}</button>
<button v-if="profile.status === 'published' || profile.status === 'retired'" class="rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700" @click="createNextVersion(profile)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
<button v-if="profile.status === 'published'" class="rounded border border-amber-300 px-3 py-1.5 text-sm text-amber-700" @click="retireProfile(profile)">{{ t('admin.shippingOrderProfiles.retire') }}</button>
</div>
</div>
</div>
</div>
</div>
</section>
<OrderProfileWorkbench />
</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>
@@ -0,0 +1,226 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
用途:展示受控 PDF 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
逻辑:父工作台签发单页令牌并提供分页/保存动作;本组件下载短时 PNG,以三段式工具栏和窄工具轨承载标注交互。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ArrowLeft, ArrowRight, BoxSelect, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Save, ScanLine, Sparkles, TableProperties, Trash2 } from 'lucide-vue-next';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
const props = defineProps<{
profileId: number | null;
grant?: OrderProfilePreviewPageGrant | null;
regions: OrderProfileCanvasRegion[];
selectedRegionId?: string | null;
creationKind?: OrderProfileCanvasRegion['kind'] | null;
autoSuggestDisabled?: boolean;
suggesting?: boolean;
suggestionProgress?: string;
undoDisabled?: boolean;
redoDisabled?: boolean;
duplicateDisabled?: boolean;
deleteDisabled?: boolean;
pageNo: number;
pageCount: number;
saveDisabled?: boolean;
saving?: boolean;
}>();
const { t } = useI18n();
const emit = defineEmits<{
select: [regionId: string];
start: [regionId: string];
end: [];
change: [regionId: string, region: OrderProfileCanvasRegion['region']];
create: [region: OrderProfileCanvasRegion['region']];
draw: [kind: OrderProfileCanvasRegion['kind']];
suggest: [];
undo: [];
redo: [];
duplicate: [];
delete: [];
save: [];
page: [pageNo: number];
}>();
const imageUrl = ref('');
const loading = ref(false);
const canvas = ref<HTMLElement | null>(null);
const viewport = ref<HTMLElement | null>(null);
const zoom = ref(1);
const toolsOpen = ref(true);
const zoomPercent = computed(() => Math.round(zoom.value * 100));
const pageInput = ref(props.pageNo);
type ResizeHandle = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';
type DragMode = 'move' | ResizeHandle;
let activeDrag: { id: string; mode: DragMode; startX: number; startY: number; region: OrderProfileCanvasRegion['region'] } | null = null;
let activePan: { startX: number; startY: number; scrollLeft: number; scrollTop: number } | null = null;
let creationStart: { x: number; y: number } | null = null;
const creationRegion = ref<OrderProfileCanvasRegion['region'] | null>(null);
/** 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。 */
const loadPage = async () => {
if (!props.profileId || !props.grant) return;
loading.value = true;
URL.revokeObjectURL(imageUrl.value);
imageUrl.value = '';
try {
const response = await fetch(
`/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages/${props.grant.page_no}?preview_token=${encodeURIComponent(props.grant.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
imageUrl.value = URL.createObjectURL(await response.blob());
} finally {
loading.value = false;
}
};
/** 将指针移动映射为相对坐标;八向手柄独立调整边或角,放大后仍以相对坐标精确落位。 */
const move = (event: PointerEvent) => {
if (!activeDrag || !canvas.value) return;
const bounds = canvas.value.getBoundingClientRect();
const dx = (event.clientX - activeDrag.startX) / bounds.width;
const dy = (event.clientY - activeDrag.startY) / bounds.height;
if (activeDrag.mode !== 'move') {
const handle = activeDrag.mode;
const prior = activeDrag.region;
const next = {
x0: handle.includes('w') ? Math.max(0, Math.min(prior.x1 - .01, prior.x0 + dx)) : prior.x0,
y0: handle.includes('n') ? Math.max(0, Math.min(prior.y1 - .01, prior.y0 + dy)) : prior.y0,
x1: handle.includes('e') ? Math.max(prior.x0 + .01, Math.min(1, prior.x1 + dx)) : prior.x1,
y1: handle.includes('s') ? Math.max(prior.y0 + .01, Math.min(1, prior.y1 + dy)) : prior.y1,
};
emit('change', activeDrag.id, next);
return;
}
const width = activeDrag.region.x1 - activeDrag.region.x0;
const height = activeDrag.region.y1 - activeDrag.region.y0;
const x0 = Math.max(0, Math.min(1 - width, activeDrag.region.x0 + dx));
const y0 = Math.max(0, Math.min(1 - height, activeDrag.region.y0 + dy));
emit('change', activeDrag.id, { x0, y0, x1: x0 + width, y1: y0 + height });
};
/** 为单次鼠标手势建立一个撤销边界,避免每个像素移动污染历史。 */
const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => {
event.preventDefault();
emit('select', region.id);
emit('start', region.id);
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', endMove, { once: true });
};
/** 结束一次区域移动并停止全局事件监听。 */
const endMove = () => {
activeDrag = null;
emit('end');
window.removeEventListener('pointermove', move);
};
/** 未处于绘制模式时以左键拖动画布视口,避免依赖横纵滚动条定位放大页面。 */
const beginPan = (event: PointerEvent) => {
if (props.creationKind || !viewport.value || event.button !== 0) return;
event.preventDefault();
activePan = { startX: event.clientX, startY: event.clientY, scrollLeft: viewport.value.scrollLeft, scrollTop: viewport.value.scrollTop };
window.addEventListener('pointermove', pan);
window.addEventListener('pointerup', endPan, { once: true });
};
const pan = (event: PointerEvent) => {
if (!activePan || !viewport.value) return;
viewport.value.scrollLeft = activePan.scrollLeft - (event.clientX - activePan.startX);
viewport.value.scrollTop = activePan.scrollTop - (event.clientY - activePan.startY);
};
const endPan = () => { activePan = null; window.removeEventListener('pointermove', pan); };
/** 在启用绘制模式时,把指针位置转换为受约束的相对区域并交由父级创建。 */
const beginCreation = (event: PointerEvent) => {
if (!props.creationKind || !canvas.value) { beginPan(event); return; }
const bounds = canvas.value.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
creationStart = { x, y };
creationRegion.value = { x0: x, y0: y, x1: x, y1: y };
window.addEventListener('pointermove', updateCreation);
window.addEventListener('pointerup', endCreation, { once: true });
};
const updateCreation = (event: PointerEvent) => {
if (!creationStart || !canvas.value) return;
const bounds = canvas.value.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
creationRegion.value = { x0: Math.min(creationStart.x, x), y0: Math.min(creationStart.y, y), x1: Math.max(creationStart.x, x), y1: Math.max(creationStart.y, y) };
};
const endCreation = () => {
const region = creationRegion.value;
if (region && region.x1 - region.x0 >= .01 && region.y1 - region.y0 >= .01) emit('create', region);
creationStart = null;
creationRegion.value = null;
window.removeEventListener('pointermove', updateCreation);
};
const selected = computed(() => new Set([props.selectedRegionId]));
/** 以固定步进调整页面倍率;区域采用相对坐标,缩放后仍与图像精确对齐。 */
const adjustZoom = (delta: number) => { zoom.value = Math.max(.5, Math.min(4, Math.round((zoom.value + delta) * 100) / 100)); };
/** 恢复适合工作台宽度的默认倍率,便于快速定位整页。 */
const resetZoom = () => { zoom.value = 1; };
/** 在画布上滚动时缩放页面,避免管理员来回点击工具栏中断标注。 */
const handleWheel = (event: WheelEvent) => { adjustZoom(event.deltaY < 0 ? .1 : -.1); };
/** 校验页码输入并请求父工作台切页;超出范围时吸附到最近有效页。 */
const goToPage = () => {
const nextPage = Math.max(1, Math.min(props.pageCount || 1, Math.round(Number(pageInput.value) || props.pageNo)));
pageInput.value = nextPage;
if (nextPage !== props.pageNo) emit('page', nextPage);
};
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom });
watch(() => props.grant?.preview_token, () => { void loadPage(); }, { immediate: true });
watch(() => props.pageNo, (value) => { pageInput.value = value; });
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
</script>
<template>
<section class="canvas-shell" aria-label="Document annotation canvas">
<header v-if="imageUrl" class="canvas-toolbar">
<div class="toolbar-actions"><button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button><button type="button" :disabled="redoDisabled" :title="t('admin.shippingOrderProfiles.workbench.redo')" @click="emit('redo')"><Redo2 /></button><span class="toolbar-divider" aria-hidden="true" /><button type="button" :disabled="duplicateDisabled" :title="t('admin.shippingOrderProfiles.workbench.duplicateRegionShortcut')" @click="emit('duplicate')"><Copy /></button><button type="button" class="delete-action" :disabled="deleteDisabled" :title="t('admin.shippingOrderProfiles.workbench.deleteRegionShortcut')" @click="emit('delete')"><Trash2 /></button><span class="toolbar-divider" aria-hidden="true" /><button type="button" class="save-action" :disabled="saveDisabled || saving" :title="t('admin.save')" @click="emit('save')"><Save /><span>{{ saving ? t('admin.shippingOrderProfiles.saving') : t('admin.save') }}</span></button></div>
<div class="page-control"><button type="button" :disabled="pageNo <= 1" :title="t('admin.shippingOrderExtractionRuns.previous')" @click="emit('page', pageNo - 1)"><ArrowLeft /></button><label><input v-model.number="pageInput" type="number" min="1" :max="pageCount" :aria-label="t('admin.shippingOrderProfiles.workbench.pageNavigation')" @change="goToPage" @keydown.enter.prevent="goToPage" /><span>/ {{ pageCount }}</span></label><button type="button" :disabled="pageNo >= pageCount" :title="t('admin.shippingOrderExtractionRuns.next')" @click="emit('page', pageNo + 1)"><ArrowRight /></button></div>
<div class="zoom-control"><button type="button" :disabled="zoom <= .5" :title="t('admin.shippingOrderProfiles.workbench.zoomOut')" @click="adjustZoom(-.25)"><Minus /></button><output>{{ zoomPercent }}%</output><button type="button" :disabled="zoom >= 4" :title="t('admin.shippingOrderProfiles.workbench.zoomIn')" @click="adjustZoom(.25)"><Plus /></button><button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button></div>
</header>
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</div>
<div v-else class="canvas-work-area"><aside class="annotation-tools" :class="{ collapsed: !toolsOpen }"><button type="button" class="tools-toggle" :aria-expanded="toolsOpen" :aria-label="toolsOpen ? t('admin.shippingOrderProfiles.workbench.hideAnnotationTools') : t('admin.shippingOrderProfiles.workbench.showAnnotationTools')" @click="toolsOpen = !toolsOpen"><BoxSelect /><span v-if="toolsOpen">{{ t('admin.shippingOrderProfiles.workbench.annotationTools') }}</span></button><template v-if="toolsOpen"><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawHeader')" :class="{ active: creationKind === 'header_field' }" @click="emit('draw', 'header_field')"><TableProperties /><span>{{ t('admin.shippingOrderProfiles.workbench.header') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawLine')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><ScanLine /><span>{{ t('admin.shippingOrderProfiles.workbench.line') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawField')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.field') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawExclusion')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /><span>{{ t('admin.shippingOrderProfiles.workbench.exclusion') }}</span></button><button type="button" class="suggest" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><Sparkles /><span>{{ suggesting ? t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') : t('admin.shippingOrderProfiles.workbench.autoSuggest') }}</span></button><p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p></template></aside><div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind }" @wheel.prevent="handleWheel"><div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
<img :src="imageUrl" alt="Controlled document page preview" draggable="false" />
<div
v-for="region in regions"
:key="region.id"
role="button"
tabindex="0"
class="region"
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }]"
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
@pointerdown.stop="beginDrag($event, region, 'move')"
@keydown.enter="emit('select', region.id)"
@keydown.space.prevent="emit('select', region.id)"
><span class="region-label" @pointerdown.stop="beginDrag($event, region, 'move')">{{ region.label }}</span><template v-if="region.kind === 'line'"><span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" /></template><button v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" /></div>
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
</div></div></div>
</section>
</template>
<style scoped>
.canvas-shell { min-height: 36rem; background: #101827; padding: 0 1rem 1rem; overflow: hidden; }.canvas-toolbar { position: sticky; top: 0; z-index: 4; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: .75rem; margin: 0 -1rem 1rem; padding: .55rem 1rem; border-bottom: 1px solid #26354b; background: rgb(15 23 42 / .98); color: #cbd5e1; font-size: .75rem; }.canvas-toolbar>div { display: flex; align-items: center; gap: .35rem; }.canvas-toolbar button { display: inline-flex; min-width: 2rem; height: 2rem; align-items: center; justify-content: center; gap: .35rem; border: 1px solid #475569; border-radius: .35rem; background: #1e293b; padding: .3rem .5rem; color: #e2e8f0; font-size: .72rem; }.canvas-toolbar button:hover { border-color: #60a5fa; background: #26364f; }.canvas-toolbar button:disabled { cursor: not-allowed; opacity: .4; }.canvas-toolbar svg,.annotation-tools svg { width: .95rem; height: .95rem; }.toolbar-actions { justify-self: start; }.toolbar-divider { width: 1px; height: 1.25rem; margin: 0 .15rem; background: #475569; }.toolbar-actions .delete-action:not(:disabled) { color: #fecaca; }.toolbar-actions .delete-action:not(:disabled):hover { border-color: #f87171; background: #7f1d1d; color: #fff; }.toolbar-actions .save-action { border-color: #0284c7; background: #0284c7; padding-inline: .65rem; }.page-control { justify-self: center; }.page-control label { display: flex; height: 2rem; align-items: center; gap: .3rem; border: 1px solid #475569; border-radius: .35rem; background: #0f172a; padding: 0 .45rem; color: #94a3b8; }.page-control input { width: 3rem; border: 0; background: transparent; color: #f8fafc; font: 700 .76rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; text-align: right; outline: 0; }.zoom-control { justify-self: end; }.canvas-toolbar output { min-width: 3.4rem; color: #f8fafc; text-align: center; }.zoom-control .fit-action { padding-inline: .65rem; }
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; }
.canvas-work-area { display: flex; max-height: 43rem; gap: .6rem; }.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }.canvas-viewport.panning { cursor: grab; }.canvas-viewport.panning:active { cursor: grabbing; }.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }.canvas-stage img { display: block; width: 100%; user-select: none; }.canvas-stage.drawing { cursor: crosshair; }.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 7rem; padding: .35rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }.annotation-tools.collapsed { flex-basis: 2.45rem; padding: .3rem; }.annotation-tools button { display: flex; min-height: 2rem; align-items: center; gap: .4rem; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem .45rem; color: #e2e8f0; font-size: .7rem; text-align: left; white-space: nowrap; }.annotation-tools button:hover,.annotation-tools button.active { border-color: #38bdf8; background: #0c4a6e; color: #f0f9ff; }.annotation-tools .tools-toggle { justify-content: center; }.annotation-tools.collapsed .tools-toggle { padding-inline: 0; }.annotation-tools .suggest { border-color: #0ea5e9; background: #0284c7; font-weight: 700; }.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }.suggestion-progress.failed { color: #fca5a5; }
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
.region-label { position: absolute; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
.resize-handle { position: absolute; z-index: 3; width: 10px; height: 10px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; }.handle-n,.handle-s { left: 50%; margin-left: -5px; cursor: ns-resize; }.handle-e,.handle-w { top: 50%; margin-top: -5px; cursor: ew-resize; }.handle-nw,.handle-se { cursor: nwse-resize; }.handle-ne,.handle-sw { cursor: nesw-resize; }.handle-n,.handle-nw,.handle-ne { top: -6px; }.handle-s,.handle-sw,.handle-se { bottom: -6px; }.handle-e,.handle-ne,.handle-se { right: -6px; }.handle-w,.handle-nw,.handle-sw { left: -6px; }
.region-header_field { z-index: 2; border: 1.5px solid #f59e0b; background: rgb(245 158 11 / .08); }.region-header_field .region-label,.region-header_field .resize-handle { background: #b45309; }
.region-line { z-index: 0; border-color: #a78bfa; background: rgb(167 139 250 / .1); pointer-events: none; }.region-line .region-label,.region-line .line-hit-edge,.region-line.selected .resize-handle { pointer-events: auto; }.region-line .region-label,.region-line .resize-handle { background: #6d28d9; }
.line-hit-edge { position: absolute; z-index: 2; display: block; }.line-hit-n,.line-hit-s { right: -6px; left: -6px; height: 12px; cursor: move; }.line-hit-e,.line-hit-w { top: 6px; bottom: 6px; width: 12px; cursor: move; }.line-hit-n { top: -6px; }.line-hit-e { right: -6px; }.line-hit-s { bottom: -6px; }.line-hit-w { left: -6px; }
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }.region-exclusion .region-label,.region-exclusion .resize-handle { background: #b91c1c; }
.region:not(.selected) .resize-handle { display: none; }.region.selected { outline: 3px solid white; outline-offset: 2px; }.region.selected:not(.region-line) { z-index: 4; }
.canvas-stage.drawing .region { pointer-events: none; }
@media (max-width: 900px) { .canvas-toolbar { grid-template-columns: 1fr auto; }.page-control { grid-column: 1 / -1; grid-row: 2; }.zoom-control { justify-self: end; }.canvas-stage { min-width: 32rem; }.canvas-viewport { max-height: 32rem; } } @media (max-width: 640px) { .canvas-shell { min-height: 24rem; padding-inline: .5rem; }.canvas-toolbar { margin-inline: -.5rem; padding-inline: .5rem; }.toolbar-actions .save-action span,.fit-action { display: none; }.annotation-tools { flex-basis: 2.45rem; }.annotation-tools button span,.suggestion-progress { display: none; } }
.tools-toggle span { display: none; }
</style>
@@ -0,0 +1,35 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileIssuePanel.vue
用途:统一呈现工作台保存前的配置问题与局部预览状态。
依赖:无。
逻辑:父页面计算问题码;本组件只呈现可操作的短提示,不保存样本正文或坐标。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const props = defineProps<{ issues: string[]; previewState: 'idle' | 'updating' | 'ready' | 'failed'; previewError?: string }>();
const { t } = useI18n();
const previewStatusLabel = (state: 'idle' | 'updating' | 'ready' | 'failed') => ({
idle: t('admin.shippingOrderProfiles.workbench.previewIdle'),
updating: t('admin.shippingOrderProfiles.workbench.previewUpdating'),
ready: t('admin.shippingOrderProfiles.workbench.previewReady'),
failed: t('admin.shippingOrderProfiles.workbench.previewFailed'),
}[state]);
</script>
<template>
<aside class="issue-panel">
<div class="issue-title"><span>{{ t('admin.shippingOrderProfiles.workbench.review') }}</span><span :class="`state-${previewState}`">{{ previewStatusLabel(previewState) }}</span></div>
<p v-if="previewState === 'failed' && props.previewError" class="preview-error">{{ props.previewError }}</p>
<p v-if="!issues.length" class="issue-empty">{{ t('admin.shippingOrderProfiles.workbench.noIssues') }}</p>
<ul v-else><li v-for="issue in issues" :key="issue">{{ issue }}</li></ul>
</aside>
</template>
<style scoped>
.issue-panel { border-top: 1px solid #dbe4ef; background: #f8fafc; padding: .75rem 1rem; }
.issue-title { display: flex; align-items: center; justify-content: space-between; color: #334155; font: 700 .72rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .08em; text-transform: uppercase; }
.issue-title span:last-child { border-radius: 999px; padding: .25rem .5rem; font-size: .65rem; letter-spacing: normal; text-transform: none; }
.state-idle { background: #e2e8f0; }.state-updating { background: #dbeafe; color: #1d4ed8; }.state-ready { background: #dcfce7; color: #166534; }.state-failed { background: #fee2e2; color: #b91c1c; }
ul { margin: .6rem 0 0; padding-left: 1rem; color: #b45309; font-size: .75rem; line-height: 1.4; }.issue-empty { margin: .5rem 0 0; color: #64748b; font-size: .75rem; }
.preview-error { margin: .55rem 0 0; color: #b91c1c; font-size: .75rem; line-height: 1.4; }
</style>
@@ -0,0 +1,36 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileVersionDrawer.vue
用途:将模板历史收进可开合抽屉,避免版本列表占据标注工作面。
依赖:ShippingOrderDocumentProfile DTO。
逻辑:父页面负责版本动作和盲测流程;抽屉只发出用户意图。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
defineProps<{ open: boolean; profiles: ShippingOrderDocumentProfile[] }>();
const { t } = useI18n();
defineEmits<{ close: []; edit: [profile: ShippingOrderDocumentProfile]; publish: [profile: ShippingOrderDocumentProfile]; clone: [profile: ShippingOrderDocumentProfile]; migrate: [profile: ShippingOrderDocumentProfile]; retire: [profile: ShippingOrderDocumentProfile]; remove: [profile: ShippingOrderDocumentProfile]; test: [profile: ShippingOrderDocumentProfile] }>();
</script>
<template>
<aside v-if="open" class="drawer" :aria-label="t('admin.shippingOrderProfiles.versions')">
<header><strong>{{ t('admin.shippingOrderProfiles.versions') }}</strong><button type="button" @click="$emit('close')">{{ t('common.close') }}</button></header>
<article v-for="profile in profiles" :key="profile.id">
<div><b>{{ profile.display_name }} · v{{ profile.version }}</b><small>{{ profile.profile_code }} · {{ profile.status }}</small><small v-if="profile.migration_status === 'needs_revalidation'" class="migration-status">{{ t('admin.shippingOrderProfiles.migrationNeedsReview') }}</small></div>
<div class="actions">
<button v-if="profile.status === 'draft'" type="button" @click="$emit('edit', profile)">{{ t('common.edit') }}</button>
<button v-if="profile.status === 'draft'" type="button" @click="$emit('test', profile)">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</button>
<button v-if="profile.status === 'draft'" type="button" @click="$emit('publish', profile)">{{ t('admin.shippingOrderProfiles.publish') }}</button>
<button v-if="profile.status === 'draft'" type="button" @click="$emit('remove', profile)">{{ t('common.delete') }}</button>
<button v-if="profile.status !== 'draft'" type="button" @click="$emit('clone', profile)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
<button v-if="profile.status === 'published' && profile.schema_compatibility?.status === 'breaking'" type="button" @click="$emit('migrate', profile)">{{ t('admin.shippingOrderProfiles.migrateSchema') }}</button>
<button v-if="profile.status === 'published'" type="button" @click="$emit('retire', profile)">{{ t('admin.shippingOrderProfiles.retire') }}</button>
</div>
</article>
</aside>
</template>
<style scoped>
.drawer { position: fixed; inset: 0 0 0 auto; z-index: 30; width: min(28rem, 92vw); overflow: auto; border-left: 1px solid #cbd5e1; background: white; box-shadow: -16px 0 36px rgb(15 23 42 / .16); }.drawer header { position: sticky; top: 0; display: flex; justify-content: space-between; border-bottom: 1px solid #e2e8f0; background: #fff; padding: 1rem; }.drawer article { display: grid; gap: .75rem; border-bottom: 1px solid #e2e8f0; padding: 1rem; }.drawer b,.drawer small { display: block; }.drawer small { margin-top: .25rem; color: #64748b; }.actions { display: flex; flex-wrap: wrap; gap: .4rem; }.actions button,.drawer header button { border: 1px solid #cbd5e1; border-radius: .4rem; background: white; padding: .35rem .55rem; font-size: .75rem; }.actions button:hover { background: #f1f5f9; }
.drawer small.migration-status { color: #b45309; }
</style>
@@ -10,6 +10,8 @@ import {
buildOrderProfileColumnRules,
findDuplicateOrderProfileTargets,
mergeOrderProfileHeaderLabels,
restoreOrderProfileRegionPageNo,
suggestFieldCodeFromHeaders,
shouldShowStandardOrderProfilePreview,
} from './orderProfileForm.utils';
@@ -68,4 +70,45 @@ describe('order profile form rules', () => {
'Vendor Part Number / Manufacturer Part',
]);
});
it('restores legacy all-page regions to the first page instead of leaking them onto page two', () => {
const base = {
region_id: 'legacy', region: { x0: 0, y0: 0, x1: 1, y1: 1 }, header_layouts: [], line_layouts: [],
continuation_rule: { allow_cross_page: false, required_anchor_ids: [] }, termination_rules: [], exclusion_regions: [],
};
// 断言旧 all_pages 缺失原始页码时采用首篇迁移策略,精确页与续页语义保持不变。
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'all_pages' })).toBe(1);
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'continuation_pages' })).toBe(2);
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'exact_page', page_no: 7 })).toBe(7);
});
it('suggests a cross-page field only when one confirmed header clearly covers the column', () => {
const field = {
id: 'field', kind: 'field' as const, label: 'Field', pageNo: 1,
region: { x0: .6, y0: .4, x1: .8, y1: .45 },
};
const headers = [{
id: 'header-field', kind: 'header_field' as const, label: 'Delivery Date', pageNo: 2,
fieldCode: 'requested_receipt_date', region: { x0: .58, y0: .2, x1: .82, y1: .25 },
}];
// 断言不同页面但同一横向列可形成待确认建议,函数本身不写回字段。
expect(suggestFieldCodeFromHeaders(field, headers)).toBe('requested_receipt_date');
expect(field.fieldCode).toBeUndefined();
});
it('rejects ambiguous cross-page header semantics', () => {
const field = {
id: 'field', kind: 'field' as const, label: 'Field', pageNo: 1,
region: { x0: .6, y0: .4, x1: .8, y1: .45 },
};
const headers = [
{ id: 'a', kind: 'header_field' as const, label: 'A', pageNo: 1, fieldCode: 'part_number', region: { x0: .6, y0: .2, x1: .8, y1: .25 } },
{ id: 'b', kind: 'header_field' as const, label: 'B', pageNo: 2, fieldCode: 'customer_part_number', region: { x0: .6, y0: .2, x1: .8, y1: .25 } },
];
// 断言两个不同字段以相同覆盖率竞争时保持未映射,禁止静默选择。
expect(suggestFieldCodeFromHeaders(field, headers)).toBeNull();
});
});
@@ -6,6 +6,7 @@
*/
import type { OrderProfileColumnRule } from '@/features/admin/types/shipping-order-document-profile.types';
import type { OrderProfileCanvasRegion, OrderProfileTableRegion } from '@/features/admin/types/shipping-order-document-profile.types';
export interface OrderProfileColumnSelection {
extractor_key: 'direct' | 'temp_internal_parts';
@@ -73,3 +74,44 @@ export const findDuplicateOrderProfileTargets = (rules: OrderProfileColumnRule[]
const targets = rules.flatMap((item) => item.target_field_codes);
return [...new Set(targets.filter((target, index) => targets.indexOf(target) !== index))];
};
/**
* 将历史页作用域恢复为单页画布页码;旧 all_pages 缺少原始页号时按首篇样例页迁移。
* @param tableRegion - 已保存的 v2 表格区域
* @returns 当前画布应显示的 1 基页码
*/
export const restoreOrderProfileRegionPageNo = (tableRegion: OrderProfileTableRegion): number => {
if (tableRegion.page_scope === 'exact_page') return tableRegion.page_no || 1;
return tableRegion.page_scope === 'continuation_pages' ? 2 : 1;
};
/**
* 根据已确认表头的横向覆盖关系建议明细字段;冲突或覆盖不足时拒绝猜测。
* @param fieldRegion - 当前待绑定的明细字段区域
* @param headerRegions - 所有页面上已确认 Schema 字段的表头区域
* @returns 唯一且覆盖至少一半字段宽度的 field_code,否则返回 null
*/
export const suggestFieldCodeFromHeaders = (
fieldRegion: OrderProfileCanvasRegion,
headerRegions: OrderProfileCanvasRegion[],
): string | null => {
const width = fieldRegion.region.x1 - fieldRegion.region.x0;
if (fieldRegion.kind !== 'field' || width <= 0) return null;
const candidates = headerRegions
.filter((item) => item.kind === 'header_field' && item.fieldCode)
.map((item) => ({
fieldCode: item.fieldCode!,
overlap: Math.max(
0,
Math.min(fieldRegion.region.x1, item.region.x1) - Math.max(fieldRegion.region.x0, item.region.x0),
) / width,
}))
.filter((item) => item.overlap >= .5)
.sort((left, right) => right.overlap - left.overlap);
if (!candidates.length) return null;
const best = candidates[0]!;
const competing = candidates.find((item, index) => (
index > 0 && item.fieldCode !== best.fieldCode && Math.abs(item.overlap - best.overlap) < .1
));
return competing ? null : best.fieldCode;
};
@@ -21,6 +21,7 @@ import {
getShippingOrderSchemaVersion,
getShippingOrderSchemaVersionDiff,
getShippingOrderSchemaVersionUsage,
getShippingOrderSchemaProfileImpact,
getShippingOrderExtractionAudit,
getShippingOrderSchemaState,
getShippingFulfillmentPolicyState,
@@ -50,6 +51,7 @@ import type {
ShippingOrderSchemaVersion,
ShippingOrderSchemaVersionDiff,
ShippingOrderSchemaVersionUsage,
ShippingOrderSchemaProfileImpact,
ShippingOrderExtractionAudit,
ShippingFulfillmentPolicyState,
} from '@/features/admin/types/shipping-order-schema.types';
@@ -65,6 +67,8 @@ defineProps<{ embedded?: boolean }>();
const state = ref<ShippingOrderSchemaState | null>(null);
const loading = ref(false);
const saving = ref(false);
const profileImpact = ref<ShippingOrderSchemaProfileImpact | null>(null);
const profileImpactOpen = ref(false);
const fieldForm = reactive({
field_code: '', field_category: 'order_line' as FieldCategory,
value_type: 'string' as ShippingOrderField['value_type'], context_provider_option_id: null as number | null,
@@ -134,6 +138,16 @@ const selectedExposurePolicies = computed(() => (
));
const publishedPolicy = computed(() => fulfillmentPolicyState.value?.policies.find((item) => item.status === 'published') || null);
const draftPolicy = computed(() => fulfillmentPolicyState.value?.policies.find((item) => item.status === 'draft') || null);
const fulfillmentCapabilityLabel = (capabilityCode: string): string => {
const labels: Record<string, string> = {
'fulfillment.reservation_identity': 'reservationIdentity',
'fulfillment.part_number': 'partNumber',
'fulfillment.quantity': 'quantity',
'routing.inventory_source_hint': 'inventorySourceHint',
};
const labelKey = labels[capabilityCode];
return labelKey ? t(`admin.shippingOrderSchema.fulfillmentCapability.${labelKey}`) : capabilityCode;
};
const policyFieldsFor = (capability: { scope: string; value_type: string }) => (state.value?.fields || []).filter((field) => (
field.status === 'active'
&& published.value?.definition?.fields.some((config) => config.field_id === field.id && config.enabled !== false)
@@ -699,6 +713,12 @@ const publishDraft = async (): Promise<void> => {
if (!draft.value) return;
saving.value = true;
try {
const impact = await getShippingOrderSchemaProfileImpact(draft.value.id);
if (impact.summary.breaking_count || impact.summary.review_required_count || impact.summary.draft_impact_count) {
profileImpact.value = impact;
profileImpactOpen.value = true;
return;
}
await publishShippingOrderSchemaDraft(draft.value.id, draft.value.lock_version);
message.success(t('admin.shippingOrderSchema.published'));
await load();
@@ -708,6 +728,21 @@ const publishDraft = async (): Promise<void> => {
saving.value = false;
}
};
const confirmPublishWithImpact = async (): Promise<void> => {
if (!draft.value) return;
saving.value = true;
try {
await publishShippingOrderSchemaDraft(draft.value.id, draft.value.lock_version, true);
profileImpactOpen.value = false;
profileImpact.value = null;
message.success(t('admin.shippingOrderSchema.published'));
await load();
} catch (error) {
await handleWriteError(error);
} finally {
saving.value = false;
}
};
/** 删除配置错误的草稿,释放下一版本创建门禁。 */
const deleteDraft = async (): Promise<void> => {
@@ -865,7 +900,7 @@ onMounted(async () => {
<p v-if="!published" class="fulfillment-warning">{{ t('admin.shippingOrderSchema.fulfillmentSchemaRequired') }}</p>
<div v-else class="fulfillment-bindings">
<label v-for="capability in fulfillmentPolicyState?.capabilities || []" :key="capability.capability_code">
<span><strong>{{ t(`admin.shippingOrderSchema.fulfillmentCapability.${capability.capability_code}`) }}</strong><small>{{ capability.required ? t('admin.shippingOrderSchema.fulfillmentRequired') : t('admin.shippingOrderSchema.fulfillmentOptional') }}</small></span>
<span><strong>{{ fulfillmentCapabilityLabel(capability.capability_code) }}</strong><small>{{ capability.required ? t('admin.shippingOrderSchema.fulfillmentRequired') : t('admin.shippingOrderSchema.fulfillmentOptional') }}</small></span>
<select v-model="fulfillmentBindings[capability.capability_code]" :disabled="saving || Boolean(draftPolicy)">
<option value="">{{ t('admin.shippingOrderSchema.fulfillmentSelectField') }}</option>
<option v-for="field in policyFieldsFor(capability)" :key="field.id" :value="field.id">{{ displayNameForField(field, 0) }} ({{ field.field_code }})</option>
@@ -973,7 +1008,7 @@ onMounted(async () => {
</template>
</div>
<template v-if="!selectedIsContext"><div class="rule-switches"><label><input v-model="selectedRuleConfig.required" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.required') }}</strong></span></label><label><input v-model="selectedRuleConfig.auto_create_key_field" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.autoCreateKeyField') }}</strong></span></label><label><input v-model="selectedRuleConfig.evidence_policy.required" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.evidenceRequired') }}</strong></span></label><label><input v-model="selectedRuleConfig.evidence_policy.allow_single_source" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.allowSingleSource') }}</strong></span></label></div>
<details class="advanced-rules"><summary>{{ t('admin.shippingOrderSchema.advancedRules') }}</summary><div class="advanced-content"><div class="rule-grid"><label><span>{{ t('admin.shippingOrderSchema.normalizer') }}</span><select v-model="selectedRuleConfig.normalizer_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_normalizers')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.comparator') }}</span><select v-model="selectedRuleConfig.comparator_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_comparators')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.relationRole') }}</span><select v-model="selectedRuleConfig.relation_role" :disabled="isReadOnly || !selectedDraftField?.enabled"><option :value="null">{{ t('admin.shippingOrderSchema.notSet') }}</option><option v-for="item in state.catalog.relation_roles" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.conflictPolicy') }}</span><select v-model="selectedRuleConfig.evidence_policy.conflict_policy" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in state.catalog.conflict_policies" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label></div><fieldset><legend>{{ t('admin.shippingOrderSchema.validators') }}</legend><div class="check-row"><label v-for="item in compatibleRules(selectedRuleConfig, 'type_validators')" :key="item"><input :checked="selectedRuleConfig.validator_keys.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.validator_keys = toggleValue(selectedRuleConfig.validator_keys, item))">{{ ruleLabel(item) }}</label></div></fieldset><fieldset><legend>{{ t('admin.shippingOrderSchema.sourcePrecedence') }}</legend><div class="check-row"><label v-for="item in state.catalog.source_types" :key="item"><input :checked="selectedRuleConfig.evidence_policy.source_precedence.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.evidence_policy.source_precedence = toggleValue(selectedRuleConfig.evidence_policy.source_precedence, item))">{{ sourceLabel(item) }}</label></div></fieldset></div></details></template>
<details class="advanced-rules"><summary>{{ t('admin.shippingOrderSchema.advancedRules') }}</summary><div class="advanced-content"><div class="rule-grid"><label><span>{{ t('admin.shippingOrderSchema.normalizer') }}</span><select v-model="selectedRuleConfig.normalizer_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_normalizers')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.comparator') }}</span><select v-model="selectedRuleConfig.comparator_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_comparators')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.relationRole') }}</span><select v-model="selectedRuleConfig.relation_role" :disabled="isReadOnly || !selectedDraftField?.enabled"><option :value="null">{{ t('admin.shippingOrderSchema.notSet') }}</option><option v-for="item in state.catalog.relation_roles" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.conflictPolicy') }}</span><select v-model="selectedRuleConfig.evidence_policy.conflict_policy" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in state.catalog.conflict_policies" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label></div><fieldset v-if="selectedField?.scope === 'line'"><legend>{{ t('admin.shippingOrderSchema.coordinateSources') }}</legend><div class="check-row compact-check-row"><label v-for="item in ['pdf_coordinate', 'ocr_coordinate'] as const" :key="item"><input :checked="selectedRuleConfig.allowed_sources?.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.allowed_sources = toggleValue(selectedRuleConfig.allowed_sources || [], item) as Array<'pdf_coordinate' | 'ocr_coordinate'>)">{{ t(`admin.shippingOrderSchema.coordinateSourceOption.${item}`) }}</label></div><small>{{ t('admin.shippingOrderSchema.coordinateSourcesHint') }}</small></fieldset><fieldset><legend>{{ t('admin.shippingOrderSchema.validators') }}</legend><div class="check-row"><label v-for="item in compatibleRules(selectedRuleConfig, 'type_validators')" :key="item"><input :checked="selectedRuleConfig.validator_keys.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.validator_keys = toggleValue(selectedRuleConfig.validator_keys, item))">{{ ruleLabel(item) }}</label></div></fieldset><fieldset><legend>{{ t('admin.shippingOrderSchema.sourcePrecedence') }}</legend><div class="check-row"><label v-for="item in state.catalog.source_types" :key="item"><input :checked="selectedRuleConfig.evidence_policy.source_precedence.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.evidence_policy.source_precedence = toggleValue(selectedRuleConfig.evidence_policy.source_precedence, item))">{{ sourceLabel(item) }}</label></div></fieldset></div></details></template>
</div>
<footer v-if="!isReadOnly" class="rule-footer"><label><span>{{ t('admin.shippingOrderSchema.changeNote') }}</span><input v-model="changeNote" :placeholder="t('admin.shippingOrderSchema.changeNotePlaceholder')"></label><button :disabled="saving" class="text-danger" @click="deleteDraft">{{ t('admin.shippingOrderSchema.deleteDraft') }}</button></footer>
</template>
@@ -1021,6 +1056,19 @@ onMounted(async () => {
@load-more="selectedVersionUsage && openVersionUsage(selectedVersionUsage.version.id, false)"
/>
<SchemaExtractionAuditDrawer v-model="extractionAuditOpen" :audit="selectedExtractionAudit" :loading="extractionAuditLoading" />
<div v-if="profileImpactOpen && profileImpact" class="impact-overlay" @click.self="profileImpactOpen = false">
<section class="impact-dialog">
<header><h2>{{ t('admin.shippingOrderSchema.profileImpactTitle') }}</h2><button type="button" class="text-button" @click="profileImpactOpen = false">{{ t('common.close') }}</button></header>
<p>{{ t('admin.shippingOrderSchema.profileImpactSummary', profileImpact.summary) }}</p>
<div class="impact-list">
<article v-for="item in profileImpact.items.filter((entry) => entry.status !== 'compatible')" :key="item.profile_id">
<strong>{{ item.profile_code }} · v{{ item.profile_version }}</strong><small>{{ item.profile_status }} · {{ item.status }}</small>
<ul><li v-for="change in [...item.breaking_changes, ...item.review_changes]" :key="`${change.field_id}-${change.reason}`">{{ change.field_id }} · {{ change.reason }}</li></ul>
</article>
</div>
<footer><button type="button" class="secondary-button" @click="profileImpactOpen = false">{{ t('common.cancel') }}</button><button type="button" class="primary-button" :disabled="saving" @click="confirmPublishWithImpact">{{ t('admin.shippingOrderSchema.confirmImpactPublish') }}</button></footer>
</section>
</div>
</section>
</template>
@@ -1031,6 +1079,9 @@ onMounted(async () => {
.secondary-button { border: 1px solid #d7e0ea; background: #fff; color: #475569; }
.text-button { background: transparent; color: #64748b; }
.primary-button:disabled, .secondary-button:disabled { cursor: not-allowed; opacity: .55; }
.impact-overlay { position: fixed; z-index: 60; inset: 0; display: grid; place-items: center; background: rgb(15 23 42 / .42); padding: 24px; }
.impact-dialog { display: grid; width: min(720px, 96vw); max-height: 82vh; gap: 14px; overflow: hidden; border-radius: 12px; background: #fff; padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24); }
.impact-dialog header,.impact-dialog footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; }.impact-dialog h2,.impact-dialog p { margin: 0; }.impact-list { display: grid; gap: 8px; overflow: auto; }.impact-list article { border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px 12px; }.impact-list small { display: block; color: #b45309; }.impact-list ul { margin: 8px 0 0; padding-left: 18px; color: #64748b; font-size: 12px; }
.schema-setup { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(240px, .6fr); gap: 24px; border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 24px; }
.schema-setup-copy { max-width: 600px; }
.schema-setup-kicker { margin: 0 0 6px; color: #0284c7; font-size: 12px; font-weight: 600; }
@@ -1051,21 +1102,22 @@ onMounted(async () => {
.auto-creation-switch span { display: grid; gap: 3px; }
.auto-creation-switch strong { color: #334155; font-size: 13px; }
.auto-creation-switch small { color: #64748b; font-size: 11px; }
.fulfillment-policy-card { display: grid; gap: 14px; margin: 0 0 16px; border: 1px solid #dbe6ef; border-radius: 10px; background: #fff; padding: 16px; }
.fulfillment-policy-card { display: grid; gap: 10px; margin: 0 0 16px; border: 1px solid #dbe6ef; border-radius: 10px; background: #fff; padding: 12px 14px; }
.fulfillment-policy-card > header, .fulfillment-policy-card > footer { display: flex; align-items: center; justify-content: space-between; gap: 14px; }
.fulfillment-policy-card h2, .fulfillment-policy-card p { margin: 0; }
.fulfillment-policy-card header p { color: #0284c7; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
.fulfillment-policy-card h2 { margin-top: 3px; color: #1e293b; font-size: 14px; }
.fulfillment-policy-card header small, .fulfillment-policy-card footer p { color: #64748b; font-size: 12px; }
.fulfillment-policy-card h2 { margin-top: 2px; color: #1e293b; font-size: 14px; }
.fulfillment-policy-card header small, .fulfillment-policy-card footer p { color: #64748b; font-size: 11px; }
.fulfillment-warning { border-radius: 7px; background: #fff7ed; padding: 9px 11px; color: #9a3412; font-size: 12px; }
.fulfillment-bindings { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.fulfillment-bindings { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
.fulfillment-bindings label, .fulfillment-policy-card footer label { display: grid; gap: 5px; color: #64748b; font-size: 12px; }
.fulfillment-bindings label { grid-template-columns: minmax(0, 1fr) minmax(180px, .8fr); align-items: center; border: 1px solid #edf1f5; border-radius: 7px; padding: 10px; }
.fulfillment-bindings label { grid-template-columns: minmax(0, 1fr); align-items: start; border: 1px solid #edf1f5; border-radius: 7px; padding: 8px 9px; }
.fulfillment-bindings span { display: grid; gap: 2px; }
.fulfillment-bindings strong { color: #334155; font-weight: 600; }
.fulfillment-bindings small { color: #94a3b8; font-size: 10px; }
.fulfillment-bindings select, .fulfillment-policy-card footer input { min-width: 0; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff; padding: 8px 9px; color: #334155; font: inherit; font-size: 12px; }
.fulfillment-bindings select, .fulfillment-policy-card footer input { min-width: 0; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff; padding: 7px 8px; color: #334155; font: inherit; font-size: 12px; }
.fulfillment-policy-card footer label { flex: 1; }
@media (max-width: 1180px) { .fulfillment-bindings { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 900px) { .fulfillment-bindings { grid-template-columns: 1fr; } }
.field-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; border-right: 1px solid #e5ebf1; background: #fbfcfe; }
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
@@ -1139,8 +1191,8 @@ onMounted(async () => {
.context-field-note { display: grid; gap: 5px; border: 1px solid #bae6fd; border-radius: 8px; background: #f0f9ff; padding: 12px; color: #475569; font-size: 12px; line-height: 1.5; }
.context-field-note strong { color: #0369a1; font-weight: 650; }
.rule-body textarea { min-height: 78px; resize: vertical; }
.rule-switches { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
.rule-switches label { display: flex; min-height: 48px; align-items: center; gap: 9px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fff; padding: 10px 12px; color: #475569; cursor: pointer; }
.rule-switches { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
.rule-switches label { display: flex; min-height: 42px; align-items: center; gap: 8px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fff; padding: 8px 10px; color: #475569; cursor: pointer; }
.rule-switches label:hover { border-color: #bae6fd; background: #f8fcff; }
.rule-switches strong { font-size: 12px; font-weight: 600; }
.rule-switches input { width: 16px; height: 16px; flex: 0 0 16px; margin: 0; accent-color: #0ea5e9; }
@@ -1152,10 +1204,13 @@ onMounted(async () => {
.advanced-content { border-top: 1px solid #edf1f5; padding: 16px; }
.advanced-content fieldset { display: grid; gap: 9px; border: 0; margin: 0; padding: 0; }
.advanced-content legend { color: #64748b; font-size: 12px; }
.advanced-content small { color: #94a3b8; font-size: 11px; line-height: 1.4; }
.compact-check-row { gap: 8px; }
.compact-check-row label { border: 1px solid #e5ebf1; border-radius: 6px; background: #f8fafc; padding: 5px 8px; font-size: 12px; }
.rule-footer { display: flex; flex: 0 0 auto; align-items: flex-end; justify-content: space-between; gap: 16px; border-top: 1px solid #e5ebf1; background: #fbfcfe; padding: 12px 24px; }
.rule-footer label { flex: 1; }
.text-danger { border: 0; background: transparent; color: #ef4444; font: inherit; font-size: 12px; cursor: pointer; }
.rule-empty { display: grid; min-height: 360px; place-items: center; color: #94a3b8; font-size: 13px; }
@media (max-width: 900px) { .schema-workbench { height: auto; overflow: visible; grid-template-columns: 1fr; } .field-panel { max-height: 360px; border-right: 0; border-bottom: 1px solid #e2e8f0; } .rule-panel { overflow: visible; } .rule-body { max-height: none; overflow: visible; } .schema-setup { grid-template-columns: 1fr; } .schema-setup-form { border-top: 1px solid #e2e8f0; border-left: 0; padding: 18px 0 0; } .rule-switches { grid-template-columns: 1fr; } }
@media (max-width: 900px) { .schema-workbench { height: auto; overflow: visible; grid-template-columns: 1fr; } .field-panel { max-height: 360px; border-right: 0; border-bottom: 1px solid #e2e8f0; } .rule-panel { overflow: visible; } .rule-body { max-height: none; overflow: visible; } .schema-setup { grid-template-columns: 1fr; } .schema-setup-form { border-top: 1px solid #e2e8f0; border-left: 0; padding: 18px 0 0; } .rule-switches { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 640px) { .schema-toolbar, .rule-heading, .rule-footer { align-items: flex-start; flex-direction: column; } .rule-heading-actions { width: 100%; justify-content: space-between; } .schema-workbench { min-height: auto; } .form-grid, .rule-grid, .rule-basics { grid-template-columns: 1fr; } .rule-basics .span-two { grid-column: auto; } .schema-setup, .rule-body { padding: 18px; } }
</style>