Merge branch 'dev-new' into runny827

This commit is contained in:
runny committed 2026-09-10 22:01:56 +08:00
commit f1beb6fefb
112 files changed
+6300 -586

No files matched your search

@@ -589,7 +589,15 @@ export const readOrderProfilePreviewPageRegionText = (
signal?: AbortSignal,
purpose?: 'reservation_id_region',
renderedImageBase64?: string | null,
) => requestJson<{ document_id: number; page_no: number; text: string; source: string | null; status: 'needs_review'; reservation_candidates?: Array<{ value: string; line_no: number | null; scope: 'header' | 'line'; raw_text: string; status: string }> }>(
) => requestJson<{
document_id: number;
page_no: number;
text: string;
source: string | null;
status: 'needs_review';
reservation_candidates?: Array<{ value: string; line_no: number | null; scope: 'header' | 'line'; raw_text: string; status: string }>;
reservation_region_reason?: string | null;
}>(
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/region-text`, {
method: 'POST', body: JSON.stringify({ document_id: documentId, region, ...(purpose ? { purpose } : {}), ...(renderedImageBase64 ? { rendered_image_base64: renderedImageBase64 } : {}) }), signal, ...jsonAuth(),
},
@@ -294,7 +294,7 @@ export function useScheduleAdminRuns(
const a = document.createElement('a');
a.href = url;
const disposition = res.headers.get('content-disposition');
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'inventory-rpa-raw.zip';
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || '库存RPA-库存.zip';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
@@ -171,8 +171,16 @@
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</template>
<footer v-if="source.enabled" class="readiness-footer">
<button type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
<footer v-if="source.enabled || source.activation?.ready" class="readiness-footer">
<button v-if="source.enabled" type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
<button
v-else
type="button"
class="btn-primary btn-sm"
:disabled="sourceDirty"
:title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined"
@click="requestSourceActivation"
>{{ t('admin.shippingInventory.activateSource') }}</button>
</footer>
</section>
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
@@ -460,6 +468,7 @@ import {
deleteShippingInventoryParsingProfile,
deleteShippingInventoryRule,
deleteShippingInventorySource,
activateShippingInventorySource,
deactivateShippingInventorySource,
deleteShippingRpaProfile,
getShippingInventoryConfig,
@@ -527,7 +536,7 @@ const orderSchemaPublished = ref(false);
const saving = ref(false);
const confirmation = reactive({
visible: false,
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'deactivateSource' | 'replaceInventorySample' | '',
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'activateSource' | 'deactivateSource' | 'replaceInventorySample' | '',
title: '',
message: '',
confirmText: '',
@@ -1248,7 +1257,7 @@ function openConfirmation(action: Exclude<typeof confirmation.action, ''>, messa
confirmation.visible = true;
}
/** 执行用户在统一确认弹窗中确认的删除或归档动作。 */
/** 执行用户在统一确认弹窗中确认的删除、启停或归档动作。 */
async function confirmPendingAction(): Promise<void> {
if (!selectedId.value || !confirmation.action) return;
const action = confirmation.action;
@@ -1258,6 +1267,11 @@ async function confirmPendingAction(): Promise<void> {
if (action === 'retireTemplate') await retireShippingExcelTemplate(selectedId.value);
if (action === 'retireParsing') await retireShippingInventoryParsingProfile(selectedId.value);
if (action === 'retireInventoryField') await retireShippingInventoryField(selectedId.value);
if (action === 'activateSource') {
await activateShippingInventorySource(selectedId.value);
await refreshSelectedSource();
return;
}
if (action === 'deactivateSource') await deactivateShippingInventorySource(selectedId.value);
if (action === 'replaceInventorySample') { sampleReplacementConfirmed.value = true; await saveCurrent(); return; }
if (action === 'delete' && activeTab.value === 'profiles') await deleteShippingRpaProfile(selectedId.value);
@@ -1274,6 +1288,20 @@ async function confirmPendingAction(): Promise<void> {
function clearConfirmation(): void { confirmation.visible = false; confirmation.action = ''; }
/**
* 停用后条件仍满足时,经确认弹窗调用已有 activate API 再次启用。
* 核心逻辑:未保存编辑一律阻断;服务端仍复用正式门禁,前端不放宽启用条件。
*/
function requestSourceActivation(): void {
if (!selectedId.value || sourceDirty.value || !source.activation?.ready) return;
confirmation.visible = true;
confirmation.action = 'activateSource';
confirmation.title = t('admin.shippingInventory.activateSource');
confirmation.message = t('admin.shippingInventory.activateSourceConfirm');
confirmation.confirmText = t('admin.shippingInventory.activateSource');
confirmation.tone = 'primary';
}
/** 停用动作使用平台确认弹窗,防止误将正在运行的库存站点下线。 */
function requestSourceDeactivation(): void {
confirmation.visible = true;
@@ -442,6 +442,14 @@ onBeforeUnmount(() => {
<section v-if="candidate" class="card candidate-card">
<h2>{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</h2>
<p v-if="!candidate.confirmable" class="training-required">{{ t('admin.shippingOrderProfiles.blindTest.diagnosticOnly') }}</p>
<p
v-if="candidate.reservation_region_status === 'needs_review'"
class="training-required"
>
{{ t('admin.shippingOrderProfiles.blindTest.reservationRegionNeedsReview', {
reasons: (candidate.reservation_region_review_reasons || []).join(', ') || candidate.reservation_region_status,
}) }}
</p>
<p v-if="!candidate.rows.length">{{ t('admin.shippingOrderProfiles.blindTest.candidateRowsEmpty') }}</p>
<article v-for="(row, index) in candidate.rows" :key="index" class="review-item">
<template v-if="rowReviews[index]">
@@ -5,7 +5,8 @@
XfaDatasetTree、XfaCollectionSelector、XfaSplitRulePanel、shippingOrderField.utils。
逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas);
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区;
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败。
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败;
选中已有标注时退出绘制模式,避免 drawing 态吞掉缩放导致标签高度无法调整。
-->
<script setup lang="ts">
import {
@@ -467,6 +468,7 @@ const reservationIdCandidates = ref<Array<{
raw_text: string;
status: string;
}>>([]);
const reservationIdRegionReason = ref<string | null>(null);
const reservationIdCandidateState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle');
/**
* 共同画布的字段选项只决定视觉定位;coordinate 末端值源仍必须由 Schema 显式授权
@@ -556,7 +558,11 @@ const ensureTableRegionSetting = (targetPageNo: number) => {
/** coordinate 末端取值 adapter 投影的画布动作。 */
const coordinateCanvasActions = computed<OrderProfileCanvasActions>(() => ({
create: (region) => createDrawnRegion(region),
select: (id) => { selectedId.value = id; },
select: (id) => {
// 选中已有框时退出绘制,否则 .drawing 会吞掉缩放手柄事件,表现为高度无法调整。
creationKind.value = null;
selectedId.value = id;
},
dragStart: (id) => beginRegionGesture(id),
dragEnd: () => endRegionGesture(),
change: (id, region) => updateRegion(id, region),
@@ -1038,18 +1044,22 @@ const updateReservationIdRegion = (region: OrderProfileRelativeRegion): void =>
};
const clearReservationIdRegion = (): void => {
reservationIdRegion.value = null;
reservationIdCandidates.value = [];
reservationIdRegionReason.value = null;
reservationIdCandidateState.value = 'idle';
reservationIdRegionDirty.value = true;
markLocalChange();
scheduleAutosave();
};
/**
* 读取当前圈选区域的 Reservation 候选。
* 核心逻辑:编辑器预览调用与正式解析相同的后端固定解析器,前端不自行推断行归属。
* 读取当前专区启用后的 Reservation 候选(与正式解析相同的 Vendor Comments 锚点)。
* 核心逻辑:编辑器预览调用后端锚点扫描;矩形仅作启用标记,前端不自行推断行归属。
*/
const refreshReservationIdCandidates = async (): Promise<void> => {
const configured = reservationIdRegion.value;
if (!active.value || !form.documentId || !configured) {
reservationIdCandidates.value = [];
reservationIdRegionReason.value = null;
reservationIdCandidateState.value = 'idle';
return;
}
@@ -1064,9 +1074,11 @@ const refreshReservationIdCandidates = async (): Promise<void> => {
'reservation_id_region',
);
reservationIdCandidates.value = result.reservation_candidates || [];
reservationIdRegionReason.value = result.reservation_region_reason || null;
reservationIdCandidateState.value = 'ready';
} catch {
reservationIdCandidates.value = [];
reservationIdRegionReason.value = null;
reservationIdCandidateState.value = 'failed';
}
};
@@ -1103,6 +1115,19 @@ const nextOrderFieldSequence = (targetPageNo: number): number => {
const beginFormEdit = () => {
pendingFormEdit = snapshot();
};
/**
* 将选中物理行标记为主明细或 LN 补料号补充表(如 COO)。
* 核心逻辑:写入 tableRegionRole 后走同一 finishFormEdit,保存时按角色拆成两个 table_regions。
*/
const onSelectedLineTableRegionRoleChange = (event: Event): void => {
const target = selectedRegion.value;
if (!target || target.kind !== 'line') return;
const value = (event.target as HTMLSelectElement).value;
target.tableRegionRole = value === 'line_field_supplement'
? 'line_field_supplement'
: 'business_lines';
finishFormEdit();
};
/**
* 记录字段改绑前的共同视觉身份。
*
@@ -1537,12 +1562,51 @@ const definition = () => {
.map((item) => item.pageNo),
)]
.sort((left, right) => left - right)
.map((regionPageNo) => {
.flatMap((regionPageNo) => {
const regionSettings = ensureTableRegionSetting(regionPageNo);
const pageItems = normalizedRegions.filter(
(item) => item.pageNo === regionPageNo,
);
const lineRegions = pageItems.filter((item) => item.kind === "line");
const roles: Array<'business_lines' | 'line_field_supplement'> = [
'business_lines',
'line_field_supplement',
];
return roles.flatMap((regionRole) => {
const lineRegions = pageItems.filter(
(item) =>
item.kind === "line"
&& (item.tableRegionRole || 'business_lines') === regionRole,
);
const supplementLineRegions = pageItems.filter(
(item) =>
item.kind === "line"
&& (item.tableRegionRole || 'business_lines') === 'line_field_supplement',
);
/** 表头中心点是否落在补充表明细行并集内(含少量纵向余量)。 */
const headerOverlapsSupplement = (header: typeof pageItems[number]): boolean => {
if (!supplementLineRegions.length) return false;
const cy = (header.region.y0 + header.region.y1) / 2;
const cx = (header.region.x0 + header.region.x1) / 2;
return supplementLineRegions.some((line) => {
const pad = Math.max(0.01, (line.region.y1 - line.region.y0) * 0.5);
return (
cx >= line.region.x0
&& cx <= line.region.x1
&& cy >= line.region.y0 - pad
&& cy <= line.region.y1 + pad
);
});
};
// 表头只挂在业务明细区;补充表(COO)不携带 header_layouts。
// 落在补充行附近的表头不得并入 business,否则会污染版面签名 header_tokens。
const pageHeaderItems = regionRole === 'business_lines'
? pageItems.filter(
(item) => item.kind === "header_field" && !headerOverlapsSupplement(item),
)
: [];
if (!lineRegions.length && !pageHeaderItems.length) {
return [];
}
const groupedLineFields = groupUniqueOrderProfileLineFields(
pageItems,
lineRegions.map((item) => item.id),
@@ -1567,14 +1631,14 @@ const definition = () => {
lineFields.value.map((field) => field.field_code),
);
};
const headerLayouts = pageItems
.filter((item) => item.kind === "header_field" && item.parentId)
const headerLayouts = pageHeaderItems
.filter((item) => item.parentId)
.reduce<string[]>((layoutIds, item) => {
if (!layoutIds.includes(item.parentId!)) layoutIds.push(item.parentId!);
return layoutIds;
}, [])
.map((layoutId) => {
const fields = pageItems.filter(
const fields = pageHeaderItems.filter(
(item) =>
item.kind === "header_field" && item.parentId === layoutId,
);
@@ -1596,7 +1660,7 @@ const definition = () => {
});
const layoutRegions = [
...lineRegions,
...pageItems.filter((item) => item.kind === "header_field"),
...pageHeaderItems,
];
const tableRegion = layoutRegions.length
? {
@@ -1612,12 +1676,15 @@ const definition = () => {
? fieldRegionsFor(firstLineRegion.id).map((item) => item.field_code)
: [],
);
return {
region_id: `main_lines_page_${regionPageNo}`,
return [{
region_id: regionRole === 'line_field_supplement'
? `line_supplement_page_${regionPageNo}`
: `main_lines_page_${regionPageNo}`,
// 仅为旧 schema 提供兼容形状;运行时会自动选择适用页范围。
page_scope: 'exact_page' as const,
page_no: regionPageNo,
region: tableRegion,
region_role: regionRole,
line_start_field_code: resolveLineStartFieldCode(mainLineFieldCodes),
// 仅为旧 schema 提供兼容形状;运行时固定/自适应策略并行评估。
row_reconstruction_mode: 'fixed_subrows' as const,
@@ -1649,6 +1716,7 @@ const definition = () => {
(item) =>
(item.kind === "field" || item.kind === "header_field") &&
item.parentId &&
lineRegions.some((line) => line.id === item.parentId) &&
(!item.fieldCode ||
(item.kind === "header_field" && !coordinateFieldScope(item.fieldCode)) ||
(item.kind === "field" && !boundLineFieldRegionIds.has(item.id))),
@@ -1659,7 +1727,8 @@ const definition = () => {
label: item.label,
region: item.region,
})),
};
}];
});
});
const visualDefinition: OrderCoordinateProfileDefinition = {
// 主表身份由创建向导冻结;编辑器保存时随定义原样携带,不能退化为只存 sample.table_id。
@@ -2715,6 +2784,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
label: item.layout_id,
region: item.region,
pageNo: regionPageNo,
tableRegionRole: table.region_role || 'business_lines',
})),
...table.line_layouts.flatMap((line) =>
line.field_regions.map((item, index) => ({
@@ -3360,11 +3430,14 @@ onBeforeUnmount(() => {
>
清除区域
</button>
<small v-if="reservationIdRegion">已标记第 {{ reservationIdRegion.page_no }} 页区域;解析结果由预览/复核统一返回。</small>
<small v-if="reservationIdRegion">已标记第 {{ reservationIdRegion.page_no }} 页区域;正式取值按 Vendor Comments→Terms 锚点,与验证/盲测/正式解析一致。</small>
<p v-if="reservationIdCandidateState === 'loading'" class="reservation-region-config__status">正在识别 Reservation ID…</p>
<p v-else-if="reservationIdCandidateState === 'failed'" class="reservation-region-config__status">区域预览失败;保存后可在盲测/复核中再次确认。</p>
<template v-else-if="reservationIdCandidateState === 'ready'">
<p v-if="!reservationIdCandidates.length" class="reservation-region-config__status">未识别到 Reservation ID,请检查圈选范围。</p>
<p v-if="reservationIdRegionReason" class="reservation-region-config__status reservation-region-config__review">
专区锚点异常:{{ reservationIdRegionReason }}
</p>
<p v-else-if="!reservationIdCandidates.length" class="reservation-region-config__status">未识别到 Reservation ID,请检查 Vendor Comments / Terms 锚点。</p>
<ul v-else class="reservation-region-config__candidates">
<li v-for="candidate in reservationIdCandidates" :key="`${candidate.value}:${candidate.line_no}:${candidate.raw_text}`">
<code>{{ candidate.value }}</code>
@@ -3428,6 +3501,20 @@ onBeforeUnmount(() => {
{{ line.label }}
</option>
</select></label
><label v-if="selectedRegion.kind === 'line'"
>{{ t('admin.shippingOrderProfiles.workbench.tableRegionRole')
}}<select
:value="selectedRegion.tableRegionRole || 'business_lines'"
class="select-field"
:disabled="compactEditor || saveState === 'readonly'"
@focus="beginFormEdit"
@change="onSelectedLineTableRegionRoleChange"
>
<option value="business_lines">{{ t('admin.shippingOrderProfiles.workbench.tableRegionRoles.business_lines') }}</option>
<option value="line_field_supplement">{{ t('admin.shippingOrderProfiles.workbench.tableRegionRoles.line_field_supplement') }}</option>
</select>
<small>{{ t('admin.shippingOrderProfiles.workbench.tableRegionRoleHint') }}</small>
</label
><label v-if="['header_field', 'field', 'order_field'].includes(selectedRegion.kind)"
>{{ t("admin.shippingOrderProfiles.workbench.schemaField")
}}<select
@@ -261,20 +261,23 @@ onMounted(loadFamilies);
</small>
</td>
<td class="profile-library__actions">
<button v-if="item.draft_profile_id" class="btn-ghost btn-sm" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button>
<button v-if="item.draft_profile_id" class="btn-danger btn-sm" type="button" @click="requestDeleteDraft(item)">{{ t('admin.delete') }}</button>
<button v-else-if="item.published_profile_id && !schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
<button v-if="!item.draft_profile_id && item.published_profile_id && schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="openSchemaMigration(item)">{{ t('admin.shippingOrderProfiles.schemaMigration.listAction') }}</button>
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
<button
v-if="item.unified_binding_status === 'needs_migration' || item.unified_needs_migration"
class="btn-ghost btn-sm"
type="button"
data-testid="order-profile-unified-migration-open"
@click="openUnifiedMigration(item)"
>
{{ t('admin.shippingOrderProfiles.unifiedMigration.open') }}
</button>
<!-- flex 必须放在 td 内层,避免破坏 table-cell 盒模型导致行分隔线错位 -->
<div class="profile-library__actions-inner">
<button v-if="item.draft_profile_id" class="btn-ghost btn-sm" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button>
<button v-if="item.draft_profile_id" class="btn-danger btn-sm" type="button" @click="requestDeleteDraft(item)">{{ t('admin.delete') }}</button>
<button v-else-if="item.published_profile_id && !schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
<button v-if="!item.draft_profile_id && item.published_profile_id && schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="openSchemaMigration(item)">{{ t('admin.shippingOrderProfiles.schemaMigration.listAction') }}</button>
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
<button
v-if="item.unified_binding_status === 'needs_migration' || item.unified_needs_migration"
class="btn-ghost btn-sm"
type="button"
data-testid="order-profile-unified-migration-open"
@click="openUnifiedMigration(item)"
>
{{ t('admin.shippingOrderProfiles.unifiedMigration.open') }}
</button>
</div>
</td>
</tr>
</tbody>
@@ -326,7 +329,8 @@ onMounted(loadFamilies);
.status-badge.published { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
.schema-status { display: block; margin-top: 5px; color: #64748b; font-size: 11px; white-space: nowrap; }.schema-status.warning { color: #b45309; }
.actions-heading { min-width: 190px; }
.profile-library__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
.profile-library__actions { vertical-align: middle; }
.profile-library__actions-inner { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
@media (max-width: 700px) {
.page-header { flex-direction: column; }
@@ -55,10 +55,19 @@ const validationEvidence = computed<OrderProfileValidationEvidence | null>(() =>
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
? value.cross_checks as Record<string, unknown>
: {},
reservation_region_status: typeof value.reservation_region_status === 'string'
? value.reservation_region_status
: undefined,
reservation_region_review_reasons: Array.isArray(value.reservation_region_review_reasons)
? value.reservation_region_review_reasons.map((item) => String(item))
: undefined,
};
});
const evidenceHeaderFields = computed(() => validationEvidence.value?.header_fields || []);
const evidenceLines = computed(() => validationEvidence.value?.lines || []);
const reservationRegionReviewReasons = computed(
() => validationEvidence.value?.reservation_region_review_reasons || [],
);
const ADAPTER_CROSS_CHECK_KEYS = [
'mirror_status',
'acroform_status',
@@ -330,6 +339,16 @@ onMounted(async () => {
</dl>
<p v-else>{{ t('admin.orderProfileValidation.noHeaderResults') }}</p>
<section
v-if="validationEvidence?.reservation_region_status === 'needs_review' || reservationRegionReviewReasons.length"
class="reservation-region-review"
>
<h3>{{ t('admin.orderProfileValidation.reservationRegionTitle') }}</h3>
<p>{{ t('admin.orderProfileValidation.reservationRegionNeedsReview', {
reasons: reservationRegionReviewReasons.join(', ') || validationEvidence?.reservation_region_status || '-',
}) }}</p>
</section>
<h3>{{ t('admin.orderProfileValidation.lineResults') }}</h3>
<div v-if="evidenceLines.length" class="line-results">
<article v-for="line in evidenceLines" :key="String(line.row_index)" class="xfa-line-card">
@@ -371,6 +390,9 @@ button:disabled { cursor: not-allowed; opacity: .55; }
.results { margin-top: 20px; padding: 16px; }.results-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }.results h2, .results h3 { margin: 0; color: #1e293b; }.results h2 { font-size: 15px; }.results h3 { margin-top: 20px; font-size: 14px; }.results-heading p { margin: 5px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; }.header-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin: 12px 0 0; }.header-results div { border: 1px solid #e5ebf1; border-radius: 6px; background: #fbfdff; padding: 10px; }.header-results dt { color: #475569; font-size: 13px; font-weight: 600; }.header-results dd { margin: 4px 0 0; overflow-wrap: anywhere; }.header-results .field-code, .line-results th small { color: #94a3b8; font-size: 11px; font-weight: 400; }.line-results { margin-top: 12px; overflow-x: auto; border: 1px solid #e5ebf1; border-radius: 6px; }.line-results table { width: 100%; min-width: 560px; border-collapse: collapse; }.line-results th, .line-results td { padding: 10px 12px; border-bottom: 1px solid #e5ebf1; text-align: left; vertical-align: top; overflow-wrap: anywhere; }.line-results tbody tr:last-child td { border-bottom: 0; }.line-results th { background: #f8fafc; color: #64748b; font-size: 12px; font-weight: 600; }.line-results th span, .line-results th small { display: block; }.deleted-row { color: #94a3b8; text-decoration: line-through; }.result-error { color: #b91c1c; }
.header-results .field-needs_review, .header-results .field-unavailable, .header-results .field-failed, .header-results .field-missing { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
.header-results .field-passed { border-color: #bbf7d0; background: #f0fdf4; }
.reservation-region-review { margin-top: 16px; padding: 12px; border: 1px solid #fed7aa; border-radius: 8px; background: #fff7ed; }
.reservation-region-review h3 { margin: 0; color: #9a3412; font-size: 14px; }
.reservation-region-review p { margin: 6px 0 0; color: #b45309; font-size: 13px; }
.xfa-line-card { margin-top: 12px; padding: 12px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fbfdff; }.xfa-line-card h4 { margin: 0 0 8px; font-size: 13px; color: #475569; }
@media (max-width: 767px) { .validation-page { padding: 16px; } header, .validation-state, .current-draft-validation > header, .checks article, .blind-test-gate, .results-heading { display: grid; }.validation-state button, .current-draft-validation > header button, .blind-test-gate button, .results-heading button { width: 100%; } }
</style>
@@ -142,6 +142,112 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
expect(region.attributes('aria-label')).toContain('待绑定');
});
it('ignores wheel zoom while a vertical resize drag is active', async () => {
const shortAnchor = {
id: 'order_field_1_1_anchor',
kind: 'order_anchor' as const,
label: 'Number',
pageNo: 1,
region: { x0: .78, y0: .12, x1: .84, y1: .158 },
};
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 8,
grant: { page_no: 1, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/8/preview-pages',
regions: [shortAnchor],
selectedRegionId: shortAnchor.id,
pageNo: 1,
pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { pagePreviewAlt: 'page', resizeHandle: '{direction}' } } },
},
},
})],
},
});
await flushPromises();
const stage = wrapper.find('.canvas-stage').element as HTMLElement;
Object.defineProperty(stage, 'getBoundingClientRect', {
value: () => ({ left: 0, top: 0, width: 1000, height: 1000, right: 1000, bottom: 1000, x: 0, y: 0, toJSON: () => ({}) }),
});
const southEdge = wrapper.find('.resize-edge-s');
southEdge.element.dispatchEvent(new PointerEvent('pointerdown', {
bubbles: true, cancelable: true, clientX: 810, clientY: 158, pointerId: 1,
}));
// 拖高过程中触控板滚轮不得改缩放,否则纵向手势表现为“高度拉不动”。
const beforeZoom = wrapper.find('.zoom-control output').text();
await wrapper.find('.canvas-viewport').trigger('wheel', { deltaY: -120 });
expect(wrapper.find('.zoom-control output').text()).toBe(beforeZoom);
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 810, clientY: 240 }));
window.dispatchEvent(new PointerEvent('pointerup', { clientX: 810, clientY: 240 }));
await flushPromises();
const change = wrapper.emitted('change')?.at(-1);
expect((change?.[1] as { y1: number }).y1).toBeGreaterThan(shortAnchor.region.y1);
expect(wrapper.find('.region').attributes('style')).toContain('bottom:');
});
it('allows shrinking label height below the legacy 0.01 floor', async () => {
const tallAnchor = {
id: 'order_field_1_2_anchor',
kind: 'order_anchor' as const,
label: 'Number',
pageNo: 1,
region: { x0: .70, y0: .035, x1: .85, y1: .055 },
};
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 8,
grant: { page_no: 1, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/8/preview-pages',
regions: [tallAnchor],
selectedRegionId: tallAnchor.id,
pageNo: 1,
pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { pagePreviewAlt: 'page', resizeHandle: '{direction}' } } },
},
},
})],
},
});
await flushPromises();
const stage = wrapper.find('.canvas-stage').element as HTMLElement;
Object.defineProperty(stage, 'getBoundingClientRect', {
value: () => ({ left: 0, top: 0, width: 1000, height: 1000, right: 1000, bottom: 1000, x: 0, y: 0, toJSON: () => ({}) }),
});
// 从下边向上拖,目标高度约 0.006(低于旧下限 0.01,高于新下限 0.002)。
wrapper.find('.resize-edge-s').element.dispatchEvent(new PointerEvent('pointerdown', {
bubbles: true, cancelable: true, clientX: 775, clientY: 55, pointerId: 1,
}));
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 775, clientY: 41 }));
window.dispatchEvent(new PointerEvent('pointerup', { clientX: 775, clientY: 41 }));
await flushPromises();
const next = wrapper.emitted('change')?.at(-1)?.[1] as { y0: number; y1: number };
// 关键断言:单行标签可缩到 <0.01;旧硬编码 .01 会把 y1 卡在 y0+0.01。
expect(next.y1 - next.y0).toBeLessThan(0.01);
expect(next.y1 - next.y0).toBeGreaterThanOrEqual(0.002);
});
it('captures the selected XFA appearance from the unscaled PDF.js canvas', async () => {
const drawImage = vi.fn();
const toDataURL = vi.fn(() => 'data:image/png;base64,canvas-crop');
@@ -5,6 +5,9 @@
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
绘制模式下仍允许操作当前选中框;整边 resize 热区便于矮标签拉高;
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
-->
<script setup lang="ts">
@@ -245,20 +248,39 @@ const onRetryClick = () => {
emit('retry');
};
/**
* 画布框最小边长(相对页坐标)。
* 旧值 0.01(页高 1%)对单行标签过粗,例如 Number 框会被卡在高度差 ≥0.01;
* 0.002 仍保证正面积,又能贴紧字形。
*/
const MIN_REGION_SPAN = 0.002;
/**
* 判断缩放手柄是否包含指定轴向。
* 核心逻辑:用显式枚举替代 `includes('n')`,避免手柄命名变更时误匹配。
*/
const resizeAffects = (handle: ResizeHandle, axis: 'n' | 'e' | 's' | 'w'): boolean => {
if (axis === 'n') return handle === 'n' || handle === 'ne' || handle === 'nw';
if (axis === 's') return handle === 's' || handle === 'se' || handle === 'sw';
if (axis === 'e') return handle === 'e' || handle === 'ne' || handle === 'se';
return handle === 'w' || handle === 'nw' || handle === 'sw';
};
/** 将指针移动映射为相对坐标;readonly 模式只保留选中,不允许几何变化。 */
const move = (event: PointerEvent) => {
if (!activeDrag || !canvas.value || readonlyMode.value) return;
const bounds = canvas.value.getBoundingClientRect();
if (bounds.width < 1 || bounds.height < 1) return;
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,
x0: resizeAffects(handle, 'w') ? Math.max(0, Math.min(prior.x1 - MIN_REGION_SPAN, prior.x0 + dx)) : prior.x0,
y0: resizeAffects(handle, 'n') ? Math.max(0, Math.min(prior.y1 - MIN_REGION_SPAN, prior.y0 + dy)) : prior.y0,
x1: resizeAffects(handle, 'e') ? Math.max(prior.x0 + MIN_REGION_SPAN, Math.min(1, prior.x1 + dx)) : prior.x1,
y1: resizeAffects(handle, 's') ? Math.max(prior.y0 + MIN_REGION_SPAN, Math.min(1, prior.y1 + dy)) : prior.y1,
};
emit('change', activeDrag.id, next);
return;
@@ -279,6 +301,7 @@ const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode:
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', endMove, { once: true });
window.addEventListener('pointercancel', endMove, { once: true });
};
/** 结束一次区域移动并停止全局事件监听。 */
@@ -286,6 +309,7 @@ const endMove = () => {
activeDrag = null;
emit('end');
window.removeEventListener('pointermove', move);
window.removeEventListener('pointercancel', endMove);
};
/** 未处于绘制模式时以左键拖动画布视口,避免依赖横纵滚动条定位放大页面。 */
const beginPan = (event: PointerEvent) => {
@@ -321,7 +345,7 @@ const updateCreation = (event: PointerEvent) => {
};
const endCreation = () => {
const region = creationRegion.value;
if (region && region.x1 - region.x0 >= .01 && region.y1 - region.y0 >= .01) emit('create', region);
if (region && region.x1 - region.x0 >= MIN_REGION_SPAN && region.y1 - region.y0 >= MIN_REGION_SPAN) emit('create', region);
creationStart = null;
creationRegion.value = null;
window.removeEventListener('pointermove', updateCreation);
@@ -357,8 +381,11 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
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 handleWheel = (event: WheelEvent) => {
if (activeDrag || activePan || creationStart) return;
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)));
@@ -511,7 +538,12 @@ onBeforeUnmount(() => {
},
region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '',
]"
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
:style="{
left: `${region.region.x0 * 100}%`,
top: `${region.region.y0 * 100}%`,
right: `${(1 - region.region.x1) * 100}%`,
bottom: `${(1 - region.region.y1) * 100}%`,
}"
:aria-label="displayRegionLabel(region)"
@pointerdown.stop="beginDrag($event, region, 'move')"
@keydown.enter="emit('select', region.id)"
@@ -521,9 +553,39 @@ onBeforeUnmount(() => {
<template v-if="region.kind === 'line' && !readonlyMode && !region.isPreview">
<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-if="!readonlyMode && !region.isPreview" 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)" />
<!-- 整边缩放热区:矮标签框拖上下边时不再落入整体 move。角点手柄叠在热区之上。 -->
<template v-if="!readonlyMode && !region.isPreview && selected.has(region.id)">
<span
v-for="edge in ['n', 'e', 's', 'w'] as ResizeHandle[]"
:key="`edge-${edge}`"
class="resize-edge"
:class="`resize-edge-${edge}`"
:aria-hidden="true"
@pointerdown.stop="beginDrag($event, region, edge)"
/>
</template>
<span
v-if="!readonlyMode && !region.isPreview"
v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]"
:key="handle"
role="button"
tabindex="-1"
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
v-if="creationRegion"
class="creation-region"
:style="{
left: `${creationRegion.x0 * 100}%`,
top: `${creationRegion.y0 * 100}%`,
right: `${(1 - creationRegion.x1) * 100}%`,
bottom: `${(1 - creationRegion.y1) * 100}%`,
}"
/>
</div>
</div>
</div>
@@ -578,6 +640,9 @@ onBeforeUnmount(() => {
.canvas-stage img { display: block; width: 100%; user-select: none; }
.canvas-stage canvas.pdf-page { display: block; background: white; pointer-events: none; user-select: none; }
.canvas-stage.drawing { cursor: crosshair; }
.canvas-stage.drawing .region { pointer-events: none; }
/* 绘制模式下仍可缩放/移动当前选中框,避免点了标签工具后高度完全拉不动。 */
.canvas-stage.drawing .region.selected { pointer-events: auto; }
.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 2.65rem; padding: .3rem; 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 button { display: grid; min-height: 2rem; place-items: center; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem; color: #e2e8f0; }
@@ -589,16 +654,24 @@ onBeforeUnmount(() => {
.suggestion-preview-badge { color: #fbbf24; font-size: .68rem; }
.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; }
.region-label { position: absolute; z-index: 2; 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-edge { position: absolute; z-index: 4; touch-action: none; }
.resize-edge-n, .resize-edge-s { left: 8px; right: 8px; height: 14px; cursor: ns-resize; }
.resize-edge-e, .resize-edge-w { top: 8px; bottom: 8px; width: 14px; cursor: ew-resize; }
.resize-edge-n { top: -7px; }
.resize-edge-s { bottom: -7px; }
.resize-edge-e { right: -7px; }
.resize-edge-w { left: -7px; }
.resize-handle { position: absolute; z-index: 5; box-sizing: border-box; width: 12px; height: 12px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; cursor: pointer; }
.handle-n, .handle-s { left: 50%; margin-left: -6px; cursor: ns-resize; }
.handle-e, .handle-w { top: 50%; margin-top: -6px; 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; }
.handle-n, .handle-nw, .handle-ne { top: -7px; }
.handle-s, .handle-sw, .handle-se { bottom: -7px; }
.handle-e, .handle-ne, .handle-se { right: -7px; }
.handle-w, .handle-nw, .handle-sw { left: -7px; }
.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-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }
@@ -652,7 +725,6 @@ onBeforeUnmount(() => {
.region.selected:not(.region-line) { z-index: 4; }
.region-preview { z-index: 5; border-style: dashed; border-width: 2px; border-color: #fbbf24; background: rgb(245 158 11 / .18); color: #fef3c7; cursor: default; pointer-events: auto; }
.region-preview .region-label { background: #a16207; }
.canvas-stage.drawing .region { pointer-events: none; }
@media (max-width: 900px) {
.canvas-shell { height: auto; min-height: 36rem; }
.canvas-toolbar { grid-template-columns: 1fr auto; }
@@ -763,7 +763,13 @@ export const selectCurrentDatasetsValidationEvidence = (
lines: value.lines,
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
? value.cross_checks : {},
} as OrderProfileValidationEvidence;
...(typeof value.reservation_region_status === 'string'
? { reservation_region_status: value.reservation_region_status }
: {}),
...(Array.isArray(value.reservation_region_review_reasons)
? { reservation_region_review_reasons: value.reservation_region_review_reasons.map((item) => String(item)) }
: {}),
};
};
/**
@@ -11,6 +11,8 @@ export type OrderProfileExtractorKey = 'direct' | 'temp_internal_parts' | 'quant
export type OrderProfileEvidenceLevel = 'coordinate' | 'ocr_coordinate';
export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate';
export type OrderProfileRowReconstructionMode = 'fixed_subrows' | 'adaptive_record_columns';
/** 主明细命中源 vs 同文档按 LN 补料号的补充表(如 COO)。 */
export type OrderProfileTableRegionRole = 'business_lines' | 'line_field_supplement';
export type OrderProfileChangeSource = 'wizard_created' | 'manual_save' | 'autosave' | 'restore' | 'sample_changed';
export type OrderProfileLeaseState = 'active' | 'expired' | 'released' | 'taken_over';
export type OrderProfileValidationRunType = 'instant_check' | 'current_sample' | 'blind_test' | 'scenario_coverage' | 'schema_compatibility' | 'layout_signature' | 'cross_template_overlap' | 'xfa_structure_signature';
@@ -72,7 +74,26 @@ export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: str
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; }
export interface OrderProfileLineLayout { layout_id: string; row_offset: number; role: 'main' | 'continuation'; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; new_line_anchor?: OrderProfileAnchorRule | null; continuation_conditions: OrderProfileAnchorRule[]; required_fields: string[]; allowed_empty_fields: string[]; }
export interface OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; /** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */ line_start_field_code?: string; /** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */ row_reconstruction_mode?: OrderProfileRowReconstructionMode; /** 管理员确认的视觉行结构来源;审计用途,不是字段正式值源。 */ visual_evidence_source?: 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' | null; header_layouts: OrderProfileHeaderLayout[]; line_layouts: OrderProfileLineLayout[]; continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] }; termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>; exclusion_regions: OrderProfileRelativeRegion[]; draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>; }
export interface OrderProfileTableRegion {
region_id: string;
page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page';
page_no?: number | null;
region: OrderProfileRelativeRegion;
/** 主明细命中源(默认)或同文档 LN 补料号补充表。 */
region_role?: OrderProfileTableRegionRole;
/** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */
line_start_field_code?: string;
/** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */
row_reconstruction_mode?: OrderProfileRowReconstructionMode;
/** 管理员确认的视觉行结构来源;审计用途,不是字段正式值源。 */
visual_evidence_source?: 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' | null;
header_layouts: OrderProfileHeaderLayout[];
line_layouts: OrderProfileLineLayout[];
continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] };
termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>;
exclusion_regions: OrderProfileRelativeRegion[];
draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>;
}
export interface OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; }
/**
@@ -577,6 +598,9 @@ export interface OrderProfileValidationEvidence {
header_fields: OrderProfileValidationEvidenceField[];
lines: OrderProfileValidationEvidenceLine[];
cross_checks: Record<string, unknown>;
/** Vendor Comments 专区与正式解析共用;仅 needs_review 时出现。 */
reservation_region_status?: string;
reservation_region_review_reasons?: string[];
}
/** 绑定精确草稿 checksum 的不可变验证运行摘要。 */
@@ -936,6 +960,8 @@ export interface OrderProfileBlindTestCandidate {
layout_version_id: number | null; layout_payload_checksum: string | null;
layout_parser_key: string | null; layout_parser_version: string | null;
order_fields: Array<{ field_id: string; field_code: string; scope: 'header'; value: unknown; status: 'confirmed' | 'needs_review' | 'unavailable'; page_no: number | null; issues: string[] }>;
reservation_region_status?: string;
reservation_region_review_reasons?: string[];
}
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
@@ -963,6 +989,8 @@ export interface OrderProfileCanvasRegion {
stopAnchorText?: string | null;
/** 标记所属文档页;画布切页时仅渲染当前页的区域。 */
pageNo: number;
/** 物理行所属表区角色;补充表(如 COO)保存为 line_field_supplement。 */
tableRegionRole?: OrderProfileTableRegionRole;
/** datasets adapter 可附加的视觉证据确认状态,不影响共同画布区域种类。 */
visualBindingStatus?: XfaVisualBindingStatus;
/** 工作台待确认候选的临时视觉标记;不会进入 Profile 保存 payload。 */
@@ -18,7 +18,9 @@ const i18n = createI18n({
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
routeType: '路由类型', executionMode: '执行模式',
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断', extractionBlockedReason: '阻断原因:{reasons}',
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断',
extractionBlockedNoMatch: '模板未唯一命中,字段提取被阻断',
extractionBlockedReason: '阻断原因:{reasons}',
coordinateModel: {
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
translateY: '纵向平移', reasonCodes: '原因码',
@@ -122,6 +124,30 @@ describe('ReviewProfileMatchPanel', () => {
// 关键断言:唯一模板命中不等于字段已提取,必须明确暴露下游阻断原因。
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
.toContain('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS');
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
.toContain('模板已命中');
});
it('未选定模板时阻断文案不得再写模板已命中', () => {
const wrapper = mount(ReviewProfileMatchPanel, {
props: {
profileMatch: {
available: true,
visibility: 'admin',
status: 'evidence_insufficient',
needs_review: true,
selected_profile: null,
candidates: [],
fallback_reason_codes: ['coordinate_evidence_unavailable'],
},
},
global: { plugins: [i18n] },
});
const blocked = wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text();
expect(blocked).toContain('模板未唯一命中');
expect(blocked).not.toContain('模板已命中');
expect(blocked).toContain('coordinate_evidence_unavailable');
});
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
@@ -43,10 +43,20 @@ const selectedCoordinateTransform = computed(() => {
const coordinateTransformReasonCodes = computed(() => (
selectedCoordinateTransform.value?.reason_codes || []
));
/** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。 */
/** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。
* 未选定模板时不得再写「模板已命中」,避免与上方「未选定模板」矛盾。 */
const extractionBlockReasons = computed(() => (
(props.profileMatch?.fallback_reason_codes || []).filter((code) => String(code).trim())
));
const hasSelectedProfile = computed(() => Boolean(
String(props.profileMatch?.selected_profile?.profile_code || '').trim()
|| String(props.profileMatch?.selected_profile?.display_name || '').trim(),
));
const extractionBlockedTitle = computed(() => (
hasSelectedProfile.value
? t('chat.shippingOrderReview.profileMatch.extractionBlocked')
: t('chat.shippingOrderReview.profileMatch.extractionBlockedNoMatch')
));
watch(
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
@@ -117,7 +127,7 @@ const selectedLabel = computed(() => {
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-profile-match-extraction-blocked"
>
<p class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.extractionBlocked') }}</p>
<p class="font-medium">{{ extractionBlockedTitle }}</p>
<p class="mt-1 text-amber-800 dark:text-amber-200">
{{ t('chat.shippingOrderReview.profileMatch.extractionBlockedReason', { reasons: extractionBlockReasons.join(', ') }) }}
</p>
@@ -1068,29 +1068,54 @@ describe('useShippingOrderReview build eligibility writes', () => {
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
},
});
api.getCase.mockResolvedValue(readyCase);
const confirmedCase = {
...readyCase,
status: 'confirmed',
confirmed_task_no: 'OT-1',
order_task_no: 'OT-1',
has_formal_ot: true,
};
api.getCase.mockResolvedValue(confirmedCase);
api.getRun.mockResolvedValue({
run_no: 'RUN-1', summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }],
});
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: 'CASE-1', document_id: 1, source_run_no: 'RUN-1', status: 'confirmed',
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
}],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue({ preview_url: '' });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'blocked', user_status: 'waiting_human',
workItemNo: 'OT-1',
status: 'waiting_human',
userStatus: 'waiting_human',
stage: 'inventory_matching',
currentGate: { gateCode: 'inventory_matching', status: 'blocked_manual' },
uiState: {
status: 'waiting_human',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current' }],
},
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' }, auto_progress_started: true,
case: confirmedCase, auto_progress_started: true,
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
const queueCallsBeforeConfirm = api.getQueue.mock.calls.length;
await review.confirm();
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
// 中断(waiting_human,即“等待人工处理”)视为线性终态:结果不会自行变化,必须停止轮询。
// 中断(waiting_human)停轮询前须刷新 Case/Queue,否则自动跳阶段拿不到 lifecycle。
expect(api.getQueue.mock.calls.length).toBeGreaterThan(queueCallsBeforeConfirm);
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
@@ -621,9 +621,12 @@ export function useShippingOrderReview(options: {
};
/**
* 轮询正式 OT / Extraction Run 的处理投影,驱动工作流进度与阶段条。
*
* OT ShippingProcessing Extraction Run
* WorkflowItem OT Run
* 核心逻辑:有权威 OT 时刷 shipping processing;投影进入 waiting_human/failed 等
* 终态前先 await refreshActiveAutomationLifecycle,保证五阶段条能跟随跳转后再停轮询。
*
* @param itemNo - 可选工作流/OT 编号覆盖
*/
const startWorkflowProgressPolling = (itemNo?: string | null) => {
stopWorkflowProgressPolling();
@@ -658,12 +661,8 @@ export function useShippingOrderReview(options: {
lastUnifiedStatus = unifiedStatus;
options.onWorkflowRefresh?.();
}
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
stopWorkflowProgressPolling();
return;
}
// 顶部五阶段取 Case/Queue 的 lifecycle_entries。仅当 OT 投影的阶段/门禁发生变化
// 时刷新一次,避免每 2.5 秒重复读取队列;不等待该读取,保证终态轮询及时停止。
// 时刷新一次,避免每 2.5 秒重复读取队列。
const lifecycleFingerprint = [
unifiedStatus,
String(shippingProcessingProjection.value?.stage || ''),
@@ -672,7 +671,13 @@ export function useShippingOrderReview(options: {
].join('|');
if (lifecycleFingerprint !== lastLifecycleFingerprint) {
lastLifecycleFingerprint = lifecycleFingerprint;
void refreshActiveAutomationLifecycle();
// [STEP] waiting_human/failed 也会停轮询,但停前必须落地一次阶段投影,
// 否则提交订单后秒级阻断时五阶段条卡在订单复核、自动跳转永不触发。
await refreshActiveAutomationLifecycle();
}
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
stopWorkflowProgressPolling();
return;
}
return;
}
@@ -1999,6 +1999,47 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}
});
it('follows the backend stage advance when the route has no lifecycle_stage deep link', async () => {
// 无 lifecycle_stage = 尚未钉工作面,应跟随系统 current,不能因空深链永久停在订单复核。
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'order_review',
lifecycle_entries: [
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const wrapper = await mountView({});
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBeUndefined();
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
await nextTick();
await flushPromises();
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBe('fulfillment_prep');
expect(messageMocks.success).toHaveBeenCalledWith('已自动推进到通知准备');
} finally {
reviewQueue.value = originalQueue;
}
});
it('keeps a manually revisited earlier lifecycle stage when the backend advances', async () => {
const originalQueue = reviewQueue.value;
try {
@@ -4451,8 +4451,10 @@ watch(
) return;
// 只响应后端 current 阶段的真实推进:用户点击已完成阶段只会改路由,
// 绝不能触发自动跳转而被带回当前阶段。
// 无 lifecycle_stage 深链 = 尚未钉工作面,视为仍跟随系统(与「仍停在旧 current」同权)。
const requested = String(route.query.lifecycle_stage || '').trim();
if (requested !== previousStage) return;
const followingSystem = !requested || requested === previousStage;
if (!followingSystem) return;
if (lifecycleStagePinnedByUserForCase.value === String(activeCase.value?.case_no || '').trim()) return;
const previousIndex = LIFECYCLE_STAGE_CODES.indexOf(previousStage);
const currentIndex = LIFECYCLE_STAGE_CODES.indexOf(currentStage);
@@ -1,7 +1,7 @@
/**
* 合同付款预警 API 类型与请求封装。
* 依赖:统一 requestJson;后端 /api/contract-payment。
* 逻辑:台账/合同详情查询、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
* 逻辑:台账/合同详情查询、汇总卡统计、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
*/
import { requestBlob, requestJson } from '@/shared/api/client';
@@ -21,11 +21,27 @@ export interface ContractPaymentContract {
status: string; parse_status: string; plan_status: string; parse_issues?: string[]; nodes: PaymentNode[]; alerts?: PaymentAlert[]; attachments?: ContractAttachment[];
}
export interface ContractListResponse { total: number; page: number; page_size: number; pages: number; items: ContractPaymentContract[]; }
export type LedgerFocus = 'due' | 'overdue' | 'needs_completion' | 'due_this_month';
export interface LedgerSummary {
due: number;
overdue: number;
needs_completion: number;
due_this_month: number;
}
export interface AlertBatch { id: number; batch_no: string; week_key: string; status: string; summary?: { total?: number; stages?: Record<string, number> }; excel_file_name?: string | null; excel_file_size?: number | null; sent_at?: string | null; }
export interface AlertSummary { pending_count: number; next_send_at?: string | null; timezone?: string | null; }
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; page?: number; pageSize?: number }) => {
const query = new URLSearchParams(); if (params?.keyword) query.set('keyword', params.keyword); if (params?.parse_status) query.set('parse_status', params.parse_status); if (params?.reviewOnly) query.set('review_only', '1'); if (params?.page) query.set('page', String(params.page)); if (params?.pageSize) query.set('page_size', String(params.pageSize));
/**
* 分页查询合同付款台账或待确认合同。
* 核心逻辑:keyword 同时匹配合同号、流程号、采购单号和供应商;reviewOnly 走待确认列表。
* @param params.keyword - 模糊检索词,可为空。
* @param params.parse_status - 解析状态精确筛选。
* @param params.reviewOnly - 为 true 时只查 needs_review。
* @param params.focus - 汇总卡口径:即将到期 / 逾期未付 / 待补充 / 本月应付。
* @returns 分页后的合同列表。
*/
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; focus?: LedgerFocus; page?: number; pageSize?: number }) => {
const query = new URLSearchParams(); if (params?.keyword) query.set('keyword', params.keyword); if (params?.parse_status) query.set('parse_status', params.parse_status); if (params?.reviewOnly) query.set('review_only', '1'); if (params?.focus) query.set('focus', params.focus); if (params?.page) query.set('page', String(params.page)); if (params?.pageSize) query.set('page_size', String(params.pageSize));
const suffix = query.toString() ? `?${query.toString()}` : ''; return requestJson<ContractListResponse>(`/api/contract-payment/contracts${suffix}`);
};
/** 获取单份合同的概览、原文附件、付款计划与预警审计详情。 */
@@ -42,6 +58,12 @@ export const enqueueContractPaymentAlertScan = () => requestJson<{ job_id: strin
export const enqueueContractPaymentWeeklyAlert = () => requestJson<{ job_id: string }>('/api/contract-payment/alerts/weekly-run', { method: 'POST' });
/** 查询本周待发送笔数和下一次周五汇总发送时间。 */
export const getContractPaymentAlertSummary = () => requestJson<AlertSummary>('/api/contract-payment/alerts/summary');
/**
* 查询合同台账四张汇总卡的合同份数。
* 核心逻辑:始终统计全部已解析台账,不跟当前 keyword;与点卡片过滤共用 focus 口径。
* @returns due / overdue / needs_completion / due_this_month。
*/
export const getContractPaymentLedgerSummary = () => requestJson<LedgerSummary>('/api/contract-payment/contracts/summary');
export const listContractPaymentAlertBatches = () => requestJson<{ items: AlertBatch[] }>('/api/contract-payment/alert-batches');
/** 下载已归档的合同付款预警周汇总 Excel 明细。 */
export const downloadContractPaymentAlertBatchExcel = (batchId: number) => requestBlob(`/api/contract-payment/alert-batches/${batchId}/excel`);
@@ -1,6 +1,6 @@
<!--
合同付款预警工作台:展示合同台账、付款阶段字段、本周待发送摘要,并提供预警任务入口。
依赖:contract-payment.api、PaginationBar、统一消息提示;周汇总批次由独立页面展示。
合同付款预警工作台:展示汇总卡、合同台账、付款阶段字段、本周待发送摘要;同步/扫描/发送仅管理员可见。
依赖:contract-payment.api、PaginationBar、useAuthStore、统一消息提示;周汇总批次由独立页面展示。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
@@ -11,6 +11,7 @@ import { BusinessError } from '@/shared/api/client';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import {
enqueueContractPaymentAlertScan,
@@ -18,21 +19,34 @@ import {
enqueueContractPaymentSync,
enqueueContractPaymentWeeklyAlert,
getContractPaymentAlertSummary,
getContractPaymentLedgerSummary,
listContractPaymentContracts,
type AlertSummary,
type ContractPaymentContract,
type LedgerFocus,
type LedgerSummary,
} from '../api/contract-payment.api';
import { displayCurrency } from '../utils/currency';
import { aggregateContractNodeStatus, type ContractNodeStatusCode } from '../utils/paymentStatus';
const { t } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const isAdmin = computed(() => auth.isAdmin);
const msg = useMessage(); const keyword = ref(''); const loading = ref(false); const actionLoading = ref(false);
const showForceSyncConfirm = ref(false);
const showReparseExistingConfirm = ref(false);
const contracts = ref<ContractPaymentContract[]>([]);
const alertSummary = ref<AlertSummary | null>(null);
const ledgerSummary = ref<LedgerSummary>({ due: 0, overdue: 0, needs_completion: 0, due_this_month: 0 });
const ledgerFocus = ref<LedgerFocus | ''>('');
const page = ref(1); const pageSize = ref(20); const total = ref(0); const pages = ref(1);
const ledgerFocusCards = computed(() => ([
{ key: 'due' as const, label: t('admin.contractPayment.ledgerFocus.due'), hint: t('admin.contractPayment.ledgerFocus.dueHint'), value: ledgerSummary.value.due, tone: 'due' },
{ key: 'overdue' as const, label: t('admin.contractPayment.ledgerFocus.overdue'), hint: '', value: ledgerSummary.value.overdue, tone: 'overdue' },
{ key: 'needs_completion' as const, label: t('admin.contractPayment.ledgerFocus.needsCompletion'), hint: '', value: ledgerSummary.value.needs_completion, tone: 'needs' },
{ key: 'due_this_month' as const, label: t('admin.contractPayment.ledgerFocus.dueThisMonth'), hint: t('admin.contractPayment.ledgerFocus.dueThisMonthHint'), value: ledgerSummary.value.due_this_month, tone: 'month' },
]));
const stage = (item: ContractPaymentContract, name: string) => item.nodes.find((node) => node.node_type === name);
/**
* 以整数格式展示付款比例,不改变接口返回的精确比例值。
@@ -123,19 +137,37 @@ async function refreshSummary(): Promise<void> {
if (!alertSummary.value) alertSummary.value = { pending_count: 0, next_send_at: null, timezone: 'Asia/Shanghai' };
}
}
/**
* 刷新四张汇总卡的合同份数。
* 核心逻辑:始终统计全部已解析台账,失败时保留上次数字,不阻断列表。
*/
async function refreshLedgerSummary(): Promise<void> {
try {
ledgerSummary.value = await getContractPaymentLedgerSummary();
} catch {
/* 汇总失败不影响台账列表 */
}
}
/**
* 加载当前页合同台账。
* 核心逻辑:合同列表使用服务端分页;搜索和每页条数变化均从第一页开始,并并行刷新待发送摘要。
* @param resetPage - 为 true 时重置为第一页,用于关键词查询。
* @returns 完成后更新当前列表、分页元数据和待发送摘要。
* 核心逻辑:合同列表使用服务端分页;关键词同时匹配合同号、流程号、采购单号和供应商;
* 汇总卡 focus 与关键词叠加;搜索、点卡片和每页条数变化均从第一页开始,并并行刷新待发送摘要与汇总卡。
* @param resetPage - 为 true 时重置为第一页,用于关键词查询或切换汇总卡。
* @returns 完成后更新当前列表、分页元数据、待发送摘要和汇总卡。
*/
async function load(resetPage = false): Promise<void> {
if (resetPage) page.value = 1;
loading.value = true;
try {
const [result] = await Promise.all([
listContractPaymentContracts({ keyword: keyword.value.trim(), page: page.value, pageSize: pageSize.value }),
listContractPaymentContracts({
keyword: keyword.value.trim(),
focus: ledgerFocus.value || undefined,
page: page.value,
pageSize: pageSize.value,
}),
refreshSummary(),
refreshLedgerSummary(),
]);
contracts.value = result.items || [];
total.value = result.total || 0;
@@ -147,13 +179,23 @@ async function load(resetPage = false): Promise<void> {
loading.value = false;
}
}
/**
* 点击汇总卡过滤台账;再次点击同一张卡则取消过滤。
* 核心逻辑:focus 写入列表查询;汇总数字本身仍看全部台账。
* @param key - 汇总卡口径。
*/
function toggleLedgerFocus(key: LedgerFocus): void {
ledgerFocus.value = ledgerFocus.value === key ? '' : key;
void load(true);
}
/**
* 提交合同付款预警后台任务。
* 核心逻辑:按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
* 核心逻辑:仅管理员可提交;按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
* @param action - sync 同步 OA、force-sync 强制覆盖、reparse-existing 刷新存量解析、scan 扫描预警、weekly 周汇总。
* @returns 任务提交完成后显示成功或失败提示。
*/
async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): Promise<void> {
if (!isAdmin.value) return;
actionLoading.value = true;
try {
if (action === 'sync' || action === 'force-sync') {
@@ -181,6 +223,7 @@ async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' |
* @param action - 待提交的预警任务类型。
*/
function run(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): void {
if (!isAdmin.value) return;
if (action === 'force-sync') {
showForceSyncConfirm.value = true;
return;
@@ -212,8 +255,33 @@ onMounted(() => void load());
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div class="flex gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
<div class="surface-panel rounded-2xl p-4 mt-5"><div class="flex flex-wrap gap-3 items-center"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 w-4 h-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPayment.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button><span v-if="weeklyPendingText" class="text-xs text-muted">{{ weeklyPendingText }}</span></div></div>
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div v-if="isAdmin" class="flex flex-wrap gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
<div class="contract-stat-grid">
<button
v-for="card in ledgerFocusCards"
:key="card.key"
type="button"
class="contract-stat-card"
:class="[card.tone, { active: ledgerFocus === card.key }]"
@click="toggleLedgerFocus(card.key)"
>
<span class="contract-stat-label">{{ card.label }}<small v-if="card.hint">({{ card.hint }})</small></span>
<strong class="contract-stat-value">{{ card.value }}</strong>
</button>
</div>
<div class="contract-filter-bar">
<div class="contract-filter-search">
<Search class="contract-filter-icon" />
<input
v-model="keyword"
class="contract-filter-input"
:placeholder="t('admin.contractPayment.searchPlaceholder')"
@keyup.enter="load(true)"
/>
</div>
<button type="button" class="contract-filter-submit" @click="load(true)">{{ t('admin.contractPayment.search') }}</button>
<span v-if="weeklyPendingText" class="contract-filter-meta">{{ weeklyPendingText }}</span>
</div>
<div class="surface-panel contract-ledger-panel mt-4 overflow-x-auto">
<table class="contract-ledger-table text-sm">
<thead><tr>
@@ -233,8 +301,9 @@ onMounted(() => void load());
</tbody>
</table>
</div>
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim()" @update:page="() => load()" @update:page-size="() => load()" />
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim() || !!ledgerFocus" @update:page="() => load()" @update:page-size="() => load()" />
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showForceSyncConfirm"
:title="t('admin.contractPayment.forceSync')"
:message="t('admin.contractPayment.forceSyncConfirm')"
@@ -242,6 +311,7 @@ onMounted(() => void load());
@confirm="confirmForceSync"
/>
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showReparseExistingConfirm"
:title="t('admin.contractPayment.reparseExisting')"
:message="t('admin.contractPayment.reparseExistingConfirm')"
@@ -251,6 +321,83 @@ onMounted(() => void load());
</section>
</template>
<style scoped>
.contract-stat-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 16px;
}
.contract-stat-card {
display: flex;
flex-direction: column;
align-items: flex-start;
min-height: 88px;
padding: 14px 16px 12px;
border: 1px solid #d7e1ef;
border-radius: 14px;
background: #fff;
box-shadow: 0 6px 20px rgba(33, 65, 111, .05);
text-align: left;
cursor: pointer;
}
.contract-stat-card.active { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .16); }
.contract-stat-label { color: #8aa0bd; font-size: 12px; font-weight: 600; line-height: 1.35; }
.contract-stat-label small { margin-left: 2px; font-size: 12px; font-weight: 600; }
.contract-stat-value { margin-top: 8px; font-size: 28px; font-weight: 800; line-height: 1; }
.contract-stat-card.due .contract-stat-value { color: #d97706; }
.contract-stat-card.overdue .contract-stat-value { color: #dc2626; }
.contract-stat-card.needs .contract-stat-value { color: #0f172a; }
.contract-stat-card.month .contract-stat-value { color: #16a34a; }
@media (max-width: 900px) { .contract-stat-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.contract-filter-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 16px;
padding: 10px 14px;
border: 1px solid #d7e1ef;
border-radius: 12px;
background: #fff;
}
.contract-filter-search { position: relative; width: min(100%, 320px); }
.contract-filter-icon {
position: absolute;
left: 10px;
top: 50%;
width: 14px;
height: 14px;
color: #8aa0bd;
transform: translateY(-50%);
pointer-events: none;
}
.contract-filter-input {
box-sizing: border-box;
width: 100%;
height: 36px;
padding: 0 12px 0 30px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #f7faff;
color: #183c72;
font-size: 14px;
line-height: 36px;
outline: none;
}
.contract-filter-input::placeholder { color: #8aa0bd; font-size: 14px; }
.contract-filter-input:focus { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .12); }
.contract-filter-submit {
height: 36px;
padding: 0 14px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #fff;
color: #426493;
font-size: 14px;
font-weight: 600;
}
.contract-filter-submit:hover { background: #f7faff; color: #183c72; }
.contract-filter-meta { color: #8aa0bd; font-size: 13px; line-height: 1.4; }
.contract-ledger-panel { border: 1px solid #d7e1ef; border-radius: 14px; background: #fff; box-shadow: 0 6px 20px rgba(33, 65, 111, .05); }
.contract-ledger-table { width: 100%; min-width: 1260px; border-collapse: collapse; color: #183c72; }
.contract-ledger-table th { height: 59px; padding: 11px 12px; background: #f7faff; border-bottom: 1px solid #d7e1ef; color: #426493; font-size: 13px; font-weight: 700; line-height: 1.35; text-align: left; vertical-align: top; white-space: nowrap; }
@@ -28,7 +28,7 @@ const pages = ref(1);
/**
* 读取需要人工确认的合同列表。
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同。
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同;关键词同样匹配供应商。
* @param resetPage - 为 true 时重置到第一页,供关键词查询使用。
* @returns 请求完成后更新分页数据;失败时保留已有列表并提示原因。
*/
@@ -66,7 +66,18 @@ onMounted(() => void load());
<template>
<section class="section-gap animate-fade-in-up">
<div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPaymentReview.title') }}</h2><p class="mt-1 text-sm text-muted">{{ t('admin.contractPaymentReview.subtitle') }}</p></div>
<div class="surface-panel mt-5 rounded-2xl p-4"><div class="flex flex-wrap items-center gap-3"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 h-4 w-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPaymentReview.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button></div></div>
<div class="contract-filter-bar">
<div class="contract-filter-search">
<Search class="contract-filter-icon" />
<input
v-model="keyword"
class="contract-filter-input"
:placeholder="t('admin.contractPaymentReview.searchPlaceholder')"
@keyup.enter="load(true)"
/>
</div>
<button type="button" class="contract-filter-submit" @click="load(true)">{{ t('admin.contractPayment.search') }}</button>
</div>
<div class="surface-panel mt-4 overflow-x-auto rounded-2xl">
<table class="review-table text-sm"><thead><tr><th>{{ t('admin.contractPaymentReview.contractWorkflow') }}</th><th>{{ t('admin.contractPayment.purchaseOrder') }}</th><th>{{ t('admin.contractPayment.supplier') }}</th><th>{{ t('admin.contractPayment.amount') }}</th><th>{{ t('admin.contractPaymentReview.reason') }}</th></tr></thead>
<tbody><tr v-for="item in contracts" :key="item.id" class="cursor-pointer hover:bg-surface-soft" @click="openContractDetail(item.id)"><td><strong>{{ item.contract_no || t('admin.contractPayment.contractNoPending') }}</strong><span>{{ item.workflow_no || '—' }}</span></td><td>{{ item.purchase_order_no || '—' }}</td><td>{{ item.supplier_name || '—' }}</td><td>{{ item.total_amount || '—' }}</td><td><ul><li v-for="issue in item.parse_issues || [t('admin.contractPaymentReview.fallbackIssue')]" :key="issue">{{ issue }}</li></ul></td></tr><tr v-if="!loading && !contracts.length"><td colspan="5" class="py-9 text-center text-muted">{{ t('admin.contractPaymentReview.empty') }}</td></tr></tbody>
@@ -77,5 +88,53 @@ onMounted(() => void load());
</template>
<style scoped>
.contract-filter-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 16px;
padding: 10px 14px;
border: 1px solid #d7e1ef;
border-radius: 12px;
background: #fff;
}
.contract-filter-search { position: relative; width: min(100%, 320px); }
.contract-filter-icon {
position: absolute;
left: 10px;
top: 50%;
width: 14px;
height: 14px;
color: #8aa0bd;
transform: translateY(-50%);
pointer-events: none;
}
.contract-filter-input {
box-sizing: border-box;
width: 100%;
height: 36px;
padding: 0 12px 0 30px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #f7faff;
color: #183c72;
font-size: 14px;
line-height: 36px;
outline: none;
}
.contract-filter-input::placeholder { color: #8aa0bd; font-size: 14px; }
.contract-filter-input:focus { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .12); }
.contract-filter-submit {
height: 36px;
padding: 0 14px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #fff;
color: #426493;
font-size: 14px;
font-weight: 600;
}
.contract-filter-submit:hover { background: #f7faff; color: #183c72; }
.review-table { width: 100%; min-width: 980px; border-collapse: collapse; color: #183c72; }.review-table th { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; background: #f7faff; color: #426493; text-align: left; }.review-table td { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; vertical-align: top; }.review-table tbody tr:last-child td { border-bottom: 0; }.review-table strong, .review-table span { display: block; }.review-table strong { color: #102d59; }.review-table span, .review-table li { color: #9a3412; }.review-table ul { margin: 0; padding-left: 18px; }.review-table li + li { margin-top: 3px; }
</style>
@@ -1,16 +1,17 @@
<!--
features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue
用途:独立展示合同付款预警的周汇总批次及其企业微信发送审计摘要,并下载 Excel 明细。
依赖:contract-payment.api、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载,手动发送仅提交异步任务。
依赖:contract-payment.api、useAuthStore、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;手动发送仅管理员可见并提交异步任务。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { CalendarClock, Download, RefreshCw, Send } from 'lucide-vue-next';
import { computed, onMounted, ref } from 'vue';
import { CalendarClock, Download, Send } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import {
downloadContractPaymentAlertBatchExcel,
enqueueContractPaymentWeeklyAlert,
@@ -19,6 +20,8 @@ import {
} from '../api/contract-payment.api';
const { t, te } = useI18n();
const auth = useAuthStore();
const isAdmin = computed(() => auth.isAdmin);
const msg = useMessage();
const batches = ref<AlertBatch[]>([]);
const loading = ref(false);
@@ -44,10 +47,11 @@ async function load(): Promise<void> {
/**
* 手动提交本周汇总发送任务。
* 核心逻辑:调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
* 核心逻辑:仅管理员可调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
* @returns 提交结果通过统一消息提示反馈,成功后刷新批次列表。
*/
async function runWeeklyAlert(): Promise<void> {
if (!isAdmin.value) return;
actionLoading.value = true;
try {
await enqueueContractPaymentWeeklyAlert();
@@ -128,10 +132,7 @@ onMounted(() => void load());
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.weeklyBatchesTitle') }}</h2>
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPayment.weeklyBatchesSubtitle') }}</p>
</div>
<div class="flex gap-2">
<button class="btn-secondary-ds" :disabled="loading" @click="() => load()">
<RefreshCw class="h-4 w-4" />{{ t('admin.contractPayment.refresh') }}
</button>
<div v-if="isAdmin" class="flex gap-2">
<button class="btn-primary" :disabled="actionLoading" @click="runWeeklyAlert">
<Send class="h-4 w-4" />{{ t('admin.contractPayment.weeklySend') }}
</button>
+11 -6
View File
@@ -1,12 +1,14 @@
/**
* features/kb/api/kb.api.ts
* 用途:知识库 HTTP API 封装。
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)。
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)、shared/utils/download。
* 逻辑:KbWorkspace / composables 调用;失败时优先保留 BusinessError.message,否则回退本地化 fallback。
* 源文件下载走 ?download=1,文件名由 Content-Disposition filename* 或调用方 source_file_name 决定。
*/
import i18n from '@/i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
import { parseContentDispositionFilename } from '@/shared/utils/download';
const kbT = (key: string) => String(i18n.global.t(key));
const kbErrorMessage = (e: unknown, fallbackKey: string) =>
@@ -300,11 +302,17 @@ export const getKbDocumentVersions = async (
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
};
/**
* 拉取知识库版本原始文件,供作业面触发本地下载。
* 核心逻辑:带 download=1 走附件响应;文件名优先 RFC 5987 filename*,失败由调用方回退 source_file_name。
* @param versionId - 文档版本 ID
* @returns 成功时含 blob 与解析出的文件名;失败时 ok=false
*/
export const getKbDocumentVersionSourceFile = async (
versionId: number
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
try {
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file?download=1`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
@@ -318,13 +326,10 @@ export const getKbDocumentVersionSourceFile = async (
}
return { ok: false, error: message };
}
const disposition = res.headers.get('content-disposition') || '';
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
return {
ok: true,
blob: await res.blob(),
filename: filename || undefined,
filename: parseContentDispositionFilename(res.headers.get('content-disposition')),
contentType: res.headers.get('content-type') || undefined,
};
} catch {
@@ -1,7 +1,10 @@
/**
* features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
* 记录/来源/Markdown/失败弹窗与原始文件预览。
* 用途:记录/来源/Markdown/失败弹窗与原始文件下载。
* 依赖:kb.api、kb-workspace state/computed/data、shared/utils/download。
* 逻辑:KbWorkspaceOverlays 调用;源文件点击只触发一次 a[download],保存名与上传时一致。
*/
import { triggerBlobDownload } from '@/shared/utils/download';
import type { KbDocumentItem, KbDocumentMarkdown, KbDocumentVersionItem } from '../../api/kb.api';
import {
getKbDocumentMarkdown,
@@ -74,6 +77,11 @@ export function useKbWorkspaceModals(
showSourceInfoModal.value = false;
};
/**
* 下载当前版本的原始文件,保存名与上传时的源文件名一致。
* 核心逻辑:拉 blob 后只触发一次 a[download];不用 window.open blob URL,避免再下一份 UUID 名文件。
* @param version - 源文件信息弹窗中的版本项
*/
const openOriginalSourceFile = async (version: KbDocumentVersionItem) => {
openingSourceVersionId.value = version.id;
const result = await getKbDocumentVersionSourceFile(version.id);
@@ -84,15 +92,8 @@ export function useKbWorkspaceModals(
return;
}
const objectUrl = window.URL.createObjectURL(result.blob);
const opened = window.open(objectUrl, '_blank', 'noopener,noreferrer');
if (!opened) {
const link = window.document.createElement('a');
link.href = objectUrl;
link.download = result.filename || version.source_file_name || `source-${version.id}`;
link.click();
}
window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 60_000);
const filename = version.source_file_name || result.filename || `source-${version.id}`;
triggerBlobDownload(result.blob, filename);
};
const openFailureModal = (type: 'upload' | 'clean' | 'sync') => {