diff --git a/backend/app/services/shipping_notice/order_document_profile_service.py b/backend/app/services/shipping_notice/order_document_profile_service.py index 6b444c0f..d5bbc3d8 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -965,9 +965,13 @@ def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | Non def render_preview_page(*, token: str, page_no: int, actor_id: int | None) -> bytes: - """ PNG PDF?HTML""" + """按页返回受控 PNG;令牌在 TTL 内可重复使用,以支持标注画布翻页回访。 + + 核心逻辑:校验 Redis 中的短时 grant(不 getdel);token 仍绑定 profile/document/actor/page。 + 标注编辑需要在多页间来回切换,一次性消费会导致每次翻页都「画布不可用」。 + """ store = _preview_grant_store() - raw_grant = store.getdel(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token)}') + raw_grant = store.get(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token)}') try: grant = json.loads(raw_grant) if raw_grant else None except (TypeError, json.JSONDecodeError): diff --git a/backend/app/services/shipping_notice/order_document_profile_validation_service.py b/backend/app/services/shipping_notice/order_document_profile_validation_service.py index b584ee46..1ca8cf97 100644 --- a/backend/app/services/shipping_notice/order_document_profile_validation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_validation_service.py @@ -1136,6 +1136,20 @@ def _published_representative_samples(profile_id: int) -> list[ShippingOrderDocu ).all() +def published_rival_snapshots_for_overlap(profile: ShippingOrderDocumentProfile) -> list[dict[str, Any]]: + """ + 跨模板唯一性候选:同 Schema 已发布快照,但排除本模板族。 + + 发布时同 profile_code 的旧 published 会被 retire,新草稿不必与自家旧版比唯一性; + 否则 clone 出的 v2 几乎必然与 v1 冲突。 + """ + code = str(profile.profile_code or '') + return [ + item for item in profile_service.published_snapshots_for_schema(profile.schema_version_id) + if str(item.get('profile_code') or '') != code + ] + + def _build_coordinate_overlap_evidence( *, profile: ShippingOrderDocumentProfile, @@ -1152,11 +1166,7 @@ def _build_coordinate_overlap_evidence( definition = dict(profile.definition_json or {}) thresholds = _match_thresholds(definition) schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {} - published = [ - item for item in profile_service.published_snapshots_for_schema(profile.schema_version_id) - if str(item.get('profile_code') or '') != profile.profile_code - or int(item.get('version') or 0) != int(profile.version) - ] + published = published_rival_snapshots_for_overlap(profile) candidates = [draft_snapshot, *published] sample_role_pollution = _detect_sample_role_pollution(profile) diff --git a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py index a25bf053..f818d8de 100644 --- a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py +++ b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py @@ -1252,7 +1252,6 @@ def build_identity_snapshot(*, profile: Any, revision: Any, samples: list[Any]) def build_overlap_evidence(*, profile: Any, signature_run: Any, training_samples: list[Any], blind_samples: list[Any]) -> tuple[str, dict[str, Any], dict[str, Any]]: """复用共同视觉 overlap,并仅追加 datasets 值源身份冲突证据。""" from app.services.shipping_notice import order_document_profile_validation_service as validation_service - from app.services.shipping_notice import order_document_profile_service as profile_service # [STEP 1] 共同 matcher 负责样本、阈值、正反向命中和污染判定;datasets 不得重建该流程。 status, summary, snapshot = validation_service._build_coordinate_overlap_evidence( @@ -1266,12 +1265,11 @@ def build_overlap_evidence(*, profile: Any, signature_run: Any, training_samples snapshot = dict(snapshot or {}) # [STEP 2] datasets 仅在共同视觉结论后追加正式值源身份的 fail-closed 冲突。 + # 同 profile_code 旧版会在发布时 retire,不与自家模板比身份冲突。 source = (profile.definition_json or {}).get('source_contract') if isinstance((profile.definition_json or {}).get('source_contract'), dict) else {} template, fingerprint = str(source.get('template_packet_checksum') or '').strip(), str(source.get('dataset_structure_fingerprint') or '').strip() conflicts: list[dict[str, Any]] = [] - for item in profile_service.published_snapshots_for_schema(profile.schema_version_id): - if str(item.get('profile_code') or '') == profile.profile_code and int(item.get('version') or 0) == int(profile.version): - continue + for item in validation_service.published_rival_snapshots_for_overlap(profile): other = item.get('definition') if isinstance(item.get('definition'), dict) else {} other_source = other.get('source_contract') if isinstance(other.get('source_contract'), dict) else {} if template and fingerprint and str(other_source.get('template_packet_checksum') or '') == template and str(other_source.get('dataset_structure_fingerprint') or '') == fingerprint: diff --git a/backend/app/services/shipping_notice/preview_grant_store.py b/backend/app/services/shipping_notice/preview_grant_store.py index ec166831..1bb04da2 100644 --- a/backend/app/services/shipping_notice/preview_grant_store.py +++ b/backend/app/services/shipping_notice/preview_grant_store.py @@ -3,7 +3,8 @@ backend/app/services/shipping_notice/preview_grant_store.py 用途:为订单文档模板页预览令牌提供受控存储后端选择。 依赖:Flask current_app、统一 Redis client。 -逻辑:生产默认强依赖 Redis;开发单进程可按配置回退到进程内一次性令牌存储。 +逻辑:生产默认强依赖 Redis;开发单进程可按配置回退到进程内短时令牌存储。 + PNG 页预览令牌在 TTL 内可重复 get(支持翻页);原 PDF 预览仍可用 getdel 单次消费。 """ from __future__ import annotations @@ -19,7 +20,7 @@ from app.services.redis_client import get_redis_client class _MemoryGrantStore: - """为单进程开发环境提供最小 setex/getdel 语义,保持一次性令牌行为。""" + """为单进程开发环境提供 setex/get/getdel,PNG 页令牌可在 TTL 内重复读取。""" def __init__(self) -> None: self._lock = threading.Lock() @@ -30,6 +31,19 @@ class _MemoryGrantStore: with self._lock: self._items[key] = (expires_at, value) + def get(self, key: str) -> str | None: + """读取未过期令牌且不删除,供标注画布翻页回访同一 PNG grant。""" + now = time.time() + with self._lock: + row = self._items.get(key) + if row is None: + return None + expires_at, value = row + if expires_at <= now: + self._items.pop(key, None) + return None + return value + def getdel(self, key: str) -> str | None: now = time.time() with self._lock: @@ -57,7 +71,7 @@ def preview_grant_store() -> Any: 返回模板预览授权存储。 AI/调用方触发时机:仅供订单文档模板预览接口内部使用。Redis 不可用时, - 只有启用了开发兜底配置,才允许退回进程内一次性 token 存储。 + 只有启用了开发兜底配置,才允许退回进程内短时 token 存储。 """ client = get_redis_client() if client is not None: diff --git a/backend/tests/test_order_document_profile_overlap_summary.py b/backend/tests/test_order_document_profile_overlap_summary.py index 0e94d082..788a0ba2 100644 --- a/backend/tests/test_order_document_profile_overlap_summary.py +++ b/backend/tests/test_order_document_profile_overlap_summary.py @@ -7,8 +7,13 @@ tests/test_order_document_profile_overlap_summary.py """ from __future__ import annotations -from app.services.shipping_notice.order_document_profile_validation_service import build_cross_template_overlap_summary -from app.services.shipping_notice.order_document_profile_validation_service import _evaluate_self_sample_match +from types import SimpleNamespace + +from app.services.shipping_notice.order_document_profile_validation_service import ( + build_cross_template_overlap_summary, + published_rival_snapshots_for_overlap, + _evaluate_self_sample_match, +) from app.services.shipping_notice.document_layout.order_profile_matcher import ( ProfileMatchCandidate, ProfileMatchResult, @@ -75,3 +80,24 @@ def test_overlap_ignores_ineligible_candidate_when_unique_match_has_no_eligible_ assert outcome['self_unique'] is True assert outcome['margin'] == 1.0 assert outcome['margin_ok'] is True + + +def test_published_rival_snapshots_exclude_same_profile_code(monkeypatch): + """同模板族旧 published 版不得进入跨模板冲突候选池。""" + from app.services.shipping_notice import order_document_profile_service as profile_service + + monkeypatch.setattr( + profile_service, + 'published_snapshots_for_schema', + lambda _schema_id: [ + {'profile_code': 'ODP-SELF', 'version': 1}, + {'profile_code': 'ODP-SELF', 'version': 2}, + {'profile_code': 'ODP-OTHER', 'version': 1}, + ], + ) + profile = SimpleNamespace(profile_code='ODP-SELF', schema_version_id=1, version=3) + + rivals = published_rival_snapshots_for_overlap(profile) + + assert [item['profile_code'] for item in rivals] == ['ODP-OTHER'] + assert all(item['profile_code'] != 'ODP-SELF' for item in rivals) diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index de43f473..0cec410e 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -2100,8 +2100,8 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap assert updated['lock_version'] == draft['lock_version'] + 1 -def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(app, monkeypatch): - """页面预览只允许绑定样本,令牌限管理员/单页/单次且响应禁止缓存和暴露存储地址。""" +def test_profile_page_preview_is_bound_ttl_reusable_and_never_exposes_storage_url(app, monkeypatch): + """页面预览只允许绑定样本;PNG 令牌在 TTL 内可翻页回访,响应禁止缓存和暴露存储地址。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): schema = _schema_version() @@ -2144,11 +2144,14 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url( preview_store: dict[str, str] = {} class PreviewStore: - """模拟 Redis 的 TTL 写入和原子 GETDEL,验证预览令牌无法重放。""" + """模拟 Redis 的 TTL 写入与 GET;PNG 页令牌在过期前可重复读取以支持翻页。""" def setex(self, key, _ttl, value): preview_store[key] = value + def get(self, key): + return preview_store.get(key) + def getdel(self, key): return preview_store.pop(key, None) @@ -2175,11 +2178,13 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url( assert image.mimetype == 'image/png' assert image.headers['Cache-Control'] == 'private, no-store, max-age=0' assert b'private-bucket' not in image.data and b'internal/preview.pdf' not in image.data + # 关键断言:TTL 内再次用同一 token 拉同页必须成功,否则标注画布翻页会「画布不可用」。 replay = client.get( f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/preview-pages/1", query_string={'preview_token': grant['preview_token']}, headers=headers, ) - assert replay.status_code == 404 + assert replay.status_code == 200 + assert replay.mimetype == 'image/png' candidates = client.get( f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/preview-pages/1/text-candidates", query_string={'document_id': document_id}, headers=headers, @@ -2259,14 +2264,16 @@ def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, def test_profile_page_preview_uses_memory_fallback_in_development(app, monkeypatch): - """开发环境允许单进程内存兜底,仍需保持一次性令牌语义。""" + """开发环境允许单进程内存兜底;PNG 令牌在 TTL 内可重复 get。""" with app.app_context(): app.config['ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK'] = True monkeypatch.setattr(preview_grant_store_service, 'get_redis_client', lambda: None) store = service._preview_grant_store() store.setex('preview-token', 30, '{"page_no":1}') + assert store.get('preview-token') == '{"page_no":1}' + assert store.get('preview-token') == '{"page_no":1}' assert store.getdel('preview-token') == '{"page_no":1}' - assert store.getdel('preview-token') is None + assert store.get('preview-token') is None def test_preview_page_region_text_reads_only_the_admin_selected_glyphs(app, monkeypatch): diff --git a/backend/tests/test_shipping_xfa_formal_extraction_route.py b/backend/tests/test_shipping_xfa_formal_extraction_route.py index f4a6ded0..7770f9c2 100644 --- a/backend/tests/test_shipping_xfa_formal_extraction_route.py +++ b/backend/tests/test_shipping_xfa_formal_extraction_route.py @@ -85,7 +85,6 @@ def test_datasets_blind_cross_check_reports_shared_ocr_mismatch(): def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_conflict(monkeypatch): """关键断言:跨模板 overlap 先走共同 matcher,datasets 只能追加末端身份冲突。""" - from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice import order_document_profile_validation_service as validation_service from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset @@ -100,9 +99,9 @@ def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_co ), ) monkeypatch.setattr( - profile_service, - 'published_snapshots_for_schema', - lambda _schema_id: [{ + validation_service, + 'published_rival_snapshots_for_overlap', + lambda _profile: [{ 'profile_code': 'XFA-OTHER', 'version': 3, 'checksum': 'other', 'definition': {'source_contract': { 'template_packet_checksum': 'template', @@ -135,6 +134,41 @@ def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_co assert snapshot['conflict_profiles'][1]['reason_codes'] == ['value_source_exact_identity_conflict'] +def test_datasets_overlap_skips_same_profile_code_identity_rival(monkeypatch): + """datasets 身份冲突也不得拿同模板族旧版跟自己比。""" + from app.services.shipping_notice import order_document_profile_validation_service as validation_service + from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset + + monkeypatch.setattr( + validation_service, + '_build_coordinate_overlap_evidence', + lambda **_kwargs: ('passed', {'false_hit_other_count': 0}, {'conflict_profiles': []}), + ) + monkeypatch.setattr( + validation_service, + 'published_rival_snapshots_for_overlap', + lambda _profile: [], + ) + profile = SimpleNamespace( + profile_code='XFA-CURRENT', version=2, schema_version_id=9, + definition_json={'source_contract': { + 'template_packet_checksum': 'template', + 'dataset_structure_fingerprint': 'structure', + }}, + ) + + status, summary, snapshot = xfa_dataset.build_overlap_evidence( + profile=profile, + signature_run=SimpleNamespace(id=1), + training_samples=[], + blind_samples=[], + ) + + assert status == 'passed' + assert summary['value_source_identity_conflict_count'] == 0 + assert snapshot['conflict_profiles'] == [] + + def test_datasets_overlap_parse_result_uses_formal_datasets_extraction(monkeypatch): """XFA overlap 解析门禁必须消费 datasets 抽取结果,不能误用坐标字段覆盖。""" from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue index a49a8d5d..f6ff1e9c 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue @@ -4,11 +4,13 @@ 依赖:受控预览 API、Schema API、DocumentCanvas、useOrderProfileValueAdapter、 XfaDatasetTree、XfaCollectionSelector、XfaSplitRulePanel、shippingOrderField.utils。 逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas); - XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区。 + XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区; + 未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败。 -->