feat(shipping-notice): 添加订单文档 Profile 的样本和审计管理功能,支持样本绑定、审计记录和模板预览,增强文档模板的管理和验证能力
This commit is contained in:
1 parent
d62f5107b2
commit
93777fd6df
63 files changed
+9707
-1491
No files matched your search
@@ -8,7 +8,9 @@ backend/app/api/admin/shipping_order_document_profiles.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
import io
|
||||
|
||||
from flask import g, request, send_file
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
@@ -26,6 +28,14 @@ def _ok(data, *, status: int = 200):
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
def _private_ok(data, *, status: int = 200):
|
||||
"""返回不允许浏览器或代理缓存的受控预览 JSON。"""
|
||||
response, response_status = _ok(data, status=status)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
return response, response_status
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profiles():
|
||||
@@ -145,6 +155,30 @@ def clone_order_document_profile(profile_id: int):
|
||||
return _ok(service.clone_draft(profile_id, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/schema-migration', methods=['POST'])
|
||||
@require_admin
|
||||
def migrate_order_document_profile_schema(profile_id: int):
|
||||
"""从已发布模板创建目标 Schema 版本的字段级迁移草稿。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
target_version_id = int(data.get('target_schema_version_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise service.ValidationError(
|
||||
'target_schema_version_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID',
|
||||
) from exc
|
||||
resolutions = data.get('resolutions') or {}
|
||||
if not isinstance(resolutions, dict):
|
||||
raise service.ValidationError(
|
||||
'resolutions must be an object', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID',
|
||||
)
|
||||
return _ok(service.create_schema_migration_draft(
|
||||
profile_id,
|
||||
target_schema_version_id=target_version_id,
|
||||
resolutions=resolutions,
|
||||
actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_order_document_profile(profile_id: int):
|
||||
@@ -159,7 +193,7 @@ def publish_order_document_profile(profile_id: int):
|
||||
@require_admin
|
||||
def retire_order_document_profile(profile_id: int):
|
||||
"""手工退役当前发布模板。"""
|
||||
return _ok(service.retire(profile_id))
|
||||
return _ok(service.retire(profile_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@@ -170,10 +204,96 @@ def delete_order_document_profile(profile_id: int):
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/samples', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_bound_samples(profile_id: int):
|
||||
"""列出当前模板绑定的标注和训练样本摘要。"""
|
||||
return _ok(service.list_profile_samples(profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/samples', methods=['POST'])
|
||||
@require_admin
|
||||
def add_order_document_profile_bound_sample(profile_id: int):
|
||||
"""向草稿绑定受控样本,不接受正文或对象存储地址。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(service.add_profile_sample(
|
||||
profile_id, document_id=data.get('document_id'), table_id=data.get('table_id'),
|
||||
sample_role=data.get('sample_role'), actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/samples/<int:sample_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def remove_order_document_profile_bound_sample(profile_id: int, sample_id: int):
|
||||
"""解除草稿样本绑定,原始文件按既有样本生命周期单独回收。"""
|
||||
return _ok(service.remove_profile_sample(profile_id, sample_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/preview-pages', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_preview_pages(profile_id: int):
|
||||
"""签发管理员单用途 PDF 页面预览令牌,不返回对象存储下载地址。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(service.list_preview_pages(
|
||||
profile_id, document_id=data.get('document_id'), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/preview-pages/<int:page_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_preview_page(profile_id: int, page_no: int):
|
||||
"""消费短时授权并流式返回一页低分辨率 PNG,禁止缓存和重放。"""
|
||||
image = service.render_preview_page(
|
||||
token=str(request.args.get('preview_token') or ''), page_no=page_no, actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(image), mimetype='image/png', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/preview-pages/<int:page_no>/text-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_preview_page_text_candidates(profile_id: int, page_no: int):
|
||||
"""读取当前页的紧凑文本候选,供标注工作台局部确认。"""
|
||||
return _private_ok(service.page_text_candidates(
|
||||
profile_id, document_id=request.args.get('document_id'), page_no=page_no, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/preview-region', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_order_document_profile_region(profile_id: int):
|
||||
"""基于当前模板绑定样本重建局部候选,响应不含 HTML、坐标或存储地址。"""
|
||||
return _private_ok(service.preview_profile_region(
|
||||
profile_id, data=request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/header-suggestions', methods=['POST'])
|
||||
@require_admin
|
||||
def suggest_order_document_profile_header(profile_id: int):
|
||||
"""识别当前或全部已配置表头行,仅返回待确认的 Schema 别名建议。"""
|
||||
return _private_ok(service.suggest_profile_header(
|
||||
profile_id, data=request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/ocr-coordinate-evidence', methods=['POST'])
|
||||
@require_admin
|
||||
def generate_bound_order_document_profile_ocr_coordinate_evidence(profile_id: int):
|
||||
"""显式生成当前模板绑定 PDF 样本的 OCR 坐标证据,不接受跨样本访问。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(service.generate_profile_ocr_evidence(
|
||||
profile_id, document_id=data.get('document_id'), table_id=data.get('table_id'), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/test-suites', methods=['POST'])
|
||||
@require_admin
|
||||
def create_order_document_profile_test_suite(profile_id: int):
|
||||
"""为发布模板创建独立盲测集。"""
|
||||
"""为草稿或发布模板创建独立盲测集。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
return _ok(quality.create_suite(profile_id=profile_id, actor_id=_actor_id()), status=201)
|
||||
|
||||
@@ -190,6 +310,14 @@ def add_order_document_profile_test_sample(suite_id: int):
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/samples/<int:sample_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def remove_order_document_profile_test_sample(suite_id: int, sample_id: int):
|
||||
"""删除尚未批准盲测集的单个样本真值,并留下操作审计。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
return _ok(quality.remove_sample(suite_id=suite_id, sample_id=sample_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/execute', methods=['POST'])
|
||||
@require_admin
|
||||
def execute_order_document_profile_test_suite(suite_id: int):
|
||||
|
||||
@@ -186,6 +186,13 @@ def get_shipping_order_schema_version_usage(version_id: int):
|
||||
return _ok(service.get_version_usage(version_id, page=page, page_size=page_size))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/profile-impact', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_version_profile_impact(version_id: int):
|
||||
"""只读评估目标 Schema 版本对已发布订单文档模板的兼容性影响。"""
|
||||
return _ok(service.get_profile_impact(version_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/order-extractions/<int:extraction_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_extraction_audit(extraction_id: int):
|
||||
@@ -221,6 +228,7 @@ def publish_shipping_order_schema_version(version_id: int):
|
||||
return _ok(service.publish(
|
||||
version_id, actor_id=_actor_id(), expected_lock_version=data.get('expected_lock_version'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
confirm_profile_impact=bool(data.get('confirm_profile_impact', False)),
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -65,7 +65,11 @@ from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.models.shipping_order_document_profile import ShippingOrderDocumentProfile
|
||||
from app.models.shipping_order_document_profile import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.models.shipping_document_profile_quality import (
|
||||
ShippingDocumentProfileTestRun,
|
||||
ShippingDocumentProfileTestSample,
|
||||
@@ -174,6 +178,8 @@ __all__ = [
|
||||
'ShippingOrderExtractionQualityBatch',
|
||||
'ShippingOrderExtractionQualityLabel',
|
||||
'ShippingOrderDocumentProfile',
|
||||
'ShippingOrderDocumentProfileAudit',
|
||||
'ShippingOrderDocumentProfileSample',
|
||||
'ShippingDocumentProfileTestSuite',
|
||||
'ShippingDocumentProfileTestSample',
|
||||
'ShippingDocumentProfileTestRun',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_document_profile.py
|
||||
|
||||
用途:保存订单文档模板解析 Profile 的草稿、不可变发布版本及 Schema 绑定。
|
||||
依赖:shipping_order_schema_versions、users、SQLAlchemy Base。
|
||||
逻辑:同一模板编码按版本递增;发布版本冻结结构指纹、固定列规则和稳定字段 ID,Run 再复制完整快照。
|
||||
用途:保存订单坐标 Profile 的版本、样本绑定和追加式配置审计。
|
||||
依赖:订单 Schema、订单文档、用户和 SQLAlchemy Base。
|
||||
逻辑:Profile 主表保存可索引摘要;完整 v2 定义仍在 definition_json,样本/审计实体提供可追溯治理事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +29,7 @@ class ShippingOrderDocumentProfile(Base):
|
||||
),
|
||||
Index('ix_shipping_order_document_profiles_schema_status', 'schema_version_id', 'status'),
|
||||
Index('ix_shipping_order_document_profiles_fingerprint', 'structure_fingerprint'),
|
||||
Index('ix_shipping_order_document_profiles_mode_status', 'template_mode', 'status'),
|
||||
Index(
|
||||
'uq_shipping_order_document_profiles_one_published',
|
||||
'profile_code',
|
||||
@@ -48,6 +49,9 @@ class ShippingOrderDocumentProfile(Base):
|
||||
)
|
||||
structure_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
template_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='coordinate_v2', server_default='coordinate_v2')
|
||||
training_sample_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
match_strategy_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -67,3 +71,40 @@ class ShippingOrderDocumentProfile(Base):
|
||||
source_profile: Mapped[Optional['ShippingOrderDocumentProfile']] = relationship(
|
||||
remote_side='ShippingOrderDocumentProfile.id', foreign_keys=[source_profile_id],
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfileSample(Base):
|
||||
"""绑定 Profile 与建模/盲测样本文档;不复制正文、PDF 或对象存储地址。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_samples'
|
||||
__table_args__ = (
|
||||
CheckConstraint("sample_role IN ('annotation', 'training', 'blind_test')", name='ck_shipping_order_document_profile_samples_role'),
|
||||
UniqueConstraint('profile_id', 'document_id', 'table_id', 'sample_role', name='uq_shipping_order_document_profile_samples_source_role'),
|
||||
Index('ix_shipping_order_document_profile_samples_document', 'document_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
|
||||
table_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
sample_role: Mapped[str] = mapped_column(String(16), nullable=False, default='annotation', server_default='annotation')
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfileAudit(Base):
|
||||
"""追加式 Profile 操作审计;详情只保存无敏感值的结构摘要和对象身份。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_audits'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_order_document_profile_audits_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_audits_document', 'document_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_documents.id', ondelete='SET NULL'), nullable=True)
|
||||
event_type: Mapped[str] = mapped_column(String(48), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -1004,7 +1004,11 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None
|
||||
|
||||
|
||||
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布草稿并写入不可变规则定义快照。"""
|
||||
"""发布草稿并写入不可变规则定义快照。
|
||||
|
||||
路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际
|
||||
库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。
|
||||
"""
|
||||
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
|
||||
@@ -1017,11 +1021,11 @@ def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
for code in payload.get('source_codes', [])
|
||||
if str(code or '').strip()
|
||||
}
|
||||
enabled_codes = {
|
||||
existing_codes = {
|
||||
str(code).strip().upper()
|
||||
for (code,) in db.session.query(ShippingInventorySource.source_code).filter_by(enabled=True).all()
|
||||
for (code,) in db.session.query(ShippingInventorySource.source_code).all()
|
||||
}
|
||||
missing_codes = sorted(source_codes - enabled_codes)
|
||||
missing_codes = sorted(source_codes - existing_codes)
|
||||
if missing_codes:
|
||||
raise ValidationError(
|
||||
'Routing rule references unavailable inventory sources',
|
||||
|
||||
+627
-4
@@ -15,6 +15,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
|
||||
|
||||
|
||||
_LINE_NUMBER_PATTERN = re.compile(r'^(?:0{2,}\d+|\d{1,6})$')
|
||||
@@ -112,10 +113,371 @@ class CoordinateSubrowSuggestion(CoordinateReconstructionModel):
|
||||
role: Literal['main', 'continuation']
|
||||
row_offset: int = Field(ge=0)
|
||||
column_boundaries: list[float] = Field(min_length=2)
|
||||
y0: float = Field(ge=0, le=1)
|
||||
y1: float = Field(ge=0, le=1)
|
||||
column_samples: list[list[str]]
|
||||
suggested_field_codes: list[str | None]
|
||||
|
||||
|
||||
class CoordinateHeaderRegionSuggestion(CoordinateReconstructionModel):
|
||||
"""数据区之前的独立表头视觉行;只提供几何和复核文本,不自动绑定字段。"""
|
||||
|
||||
region: LayoutBBox
|
||||
text: str = ''
|
||||
fields: list['CoordinateHeaderFieldRegionSuggestion'] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CoordinateHeaderFieldRegionSuggestion(CoordinateReconstructionModel):
|
||||
"""表头物理行内的单列文字块及其相对区域。"""
|
||||
|
||||
region: LayoutBBox
|
||||
text: str = ''
|
||||
|
||||
|
||||
class HeaderFieldSuggestion(CoordinateReconstructionModel):
|
||||
"""一个已配置表头字段区域的受控建议;不向调用方暴露字符坐标。"""
|
||||
|
||||
field_code: str | None = None
|
||||
text: str = ''
|
||||
confidence: Literal['confirmed_binding', 'exact_alias', 'unmapped'] = 'unmapped'
|
||||
|
||||
|
||||
class HeaderLayoutSuggestion(CoordinateReconstructionModel):
|
||||
"""单条表头物理行的候选结果,供管理员确认而非自动覆盖绑定。"""
|
||||
|
||||
layout_id: str
|
||||
fields: list[HeaderFieldSuggestion] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CoordinateProfileLogicalRow(CoordinateReconstructionModel):
|
||||
"""v2 坐标模板重建的一条逻辑明细,字段仍由上层 Schema 规范化。"""
|
||||
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
source_row_indices: list[int] = Field(min_length=1)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def suggest_header_layouts(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
header_layouts: list[dict[str, Any]],
|
||||
schema_fields: list[dict[str, Any]],
|
||||
) -> list[HeaderLayoutSuggestion]:
|
||||
"""
|
||||
在管理员已划定的独立表头区域内给出严格别名建议。
|
||||
|
||||
AI/调用方触发时机:管理员点击“识别当前/全部表头”时调用。此函数仅以当前
|
||||
Schema 的 field_code、display_name、aliases 作精确规范化匹配;无唯一结果保持
|
||||
未映射,因此绝不会根据列位置覆盖管理员已确认字段绑定。
|
||||
|
||||
Args:
|
||||
characters: 表格范围内冻结的原生或 OCR 字符。
|
||||
table_bbox: 表格的绝对页面区域,用来把相对区域转换为绝对区域。
|
||||
header_layouts: 当前画布中的表头物理行及可选字段区域;未绑定时直接分析表头框。
|
||||
schema_fields: 当前冻结 Schema 的启用且允许坐标来源的字段。
|
||||
Returns:
|
||||
每个表头字段区域的脱敏文本和唯一精确别名建议,不含任何 bbox 或 glyph ID。
|
||||
"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
glyphs = _table_glyphs(characters, bbox)
|
||||
aliases: dict[str, str | None] = {}
|
||||
for field in schema_fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
for value in (code, field.get('display_name'), *(field.get('aliases') or [])):
|
||||
normalized = _normalized_header_text(str(value or ''))
|
||||
if not normalized:
|
||||
continue
|
||||
aliases[normalized] = code if aliases.get(normalized, code) == code else None
|
||||
suggestions: list[HeaderLayoutSuggestion] = []
|
||||
for layout in header_layouts:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
fields: list[HeaderFieldSuggestion] = []
|
||||
configured_fields = [
|
||||
item for item in layout.get('field_regions') or []
|
||||
if isinstance(item, dict) and isinstance(item.get('region'), dict)
|
||||
]
|
||||
# 工作台以一个表头框表达一个语义字段;尚未绑定时直接分析表头框本身。
|
||||
candidate_fields = configured_fields or [{'field_code': None, 'region': layout.get('region')}]
|
||||
for field_region in candidate_fields:
|
||||
if not isinstance(field_region, dict) or not isinstance(field_region.get('region'), dict):
|
||||
continue
|
||||
region = _absolute_relative_region(bbox, field_region['region'])
|
||||
text = ''.join(glyph.text for _, glyph in glyphs if _inside_region(glyph.bbox, region)).strip()
|
||||
confirmed_code = str(field_region.get('field_code') or '').strip()
|
||||
code = confirmed_code if confirmed_code in {str(item.get('field_code') or '') for item in schema_fields} else aliases.get(_normalized_header_text(text))
|
||||
fields.append(HeaderFieldSuggestion(
|
||||
field_code=code,
|
||||
text=text[:160],
|
||||
confidence='confirmed_binding' if confirmed_code and code == confirmed_code else ('exact_alias' if code else 'unmapped'),
|
||||
))
|
||||
suggestions.append(HeaderLayoutSuggestion(layout_id=str(layout.get('layout_id') or ''), fields=fields))
|
||||
return suggestions
|
||||
|
||||
|
||||
def reconstruct_coordinate_profile_rows(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
line_layouts: list[dict[str, Any]],
|
||||
table_region: dict[str, Any] | None = None,
|
||||
termination_rules: list[dict[str, Any]] | None = None,
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
initial_fields: dict[str, str] | None = None,
|
||||
initial_next_offset: int = 0,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
|
||||
主行必须在其已绑定 ``line_no`` 区域中出现有效行号才启动明细;未满足此条件的
|
||||
视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,避免描述
|
||||
换行、合计或相邻无关表区静默混入当前订单行。
|
||||
"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
|
||||
if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))):
|
||||
raise ValueError('coordinate profile line layouts must have contiguous offsets')
|
||||
region_centers = []
|
||||
for item in ordered_layouts:
|
||||
region = item.get('region')
|
||||
if isinstance(region, dict):
|
||||
region_centers.append((float(region['y0']) + float(region['y1'])) / 2)
|
||||
layout_order_valid = len(region_centers) != len(ordered_layouts) or all(
|
||||
right > left for left, right in zip(region_centers, region_centers[1:])
|
||||
)
|
||||
glyphs = _table_glyphs(characters, bbox)
|
||||
if isinstance(table_region, dict):
|
||||
configured_table_region = _absolute_relative_region(bbox, table_region)
|
||||
# 标注框描述可重复应用的行版式,纵向只是一条样例;整表候选不能因此被裁成单行。
|
||||
glyphs = [item for item in glyphs if _inside_horizontal_region(item[1].bbox, configured_table_region)]
|
||||
exclusions = [
|
||||
_absolute_relative_region(bbox, item)
|
||||
for item in (exclusion_regions or []) if isinstance(item, dict)
|
||||
]
|
||||
if exclusions:
|
||||
# Footer, signature and tax blocks are not candidate physical rows at all.
|
||||
glyphs = [item for item in glyphs if not any(_inside_region(item[1].bbox, region) for region in exclusions)]
|
||||
if not glyphs:
|
||||
return []
|
||||
|
||||
relative_y_rows = _reconstruct_relative_y_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
ordered_layouts=ordered_layouts,
|
||||
termination_rules=termination_rules or [],
|
||||
initial_fields=initial_fields,
|
||||
)
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
|
||||
def values_for(band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any]) -> tuple[dict[str, str], list[str]]:
|
||||
"""按当前物理行读取字段列;标注区域的纵向位置只表达子行版式,不限定绝对页坐标。"""
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
|
||||
continue
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code:
|
||||
continue
|
||||
region = _absolute_relative_region(bbox, field['region'])
|
||||
text = _text_in_horizontal_region(band, region)
|
||||
if text:
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=text,
|
||||
)
|
||||
# Composite parsers are atomic: no partial output may contaminate a logical row.
|
||||
if extracted:
|
||||
for extracted_code, extracted_value in extracted.items():
|
||||
previous = values.get(extracted_code)
|
||||
if previous is not None and previous != extracted_value:
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
return values, issues
|
||||
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
current: dict[str, str] | None = dict(initial_fields) if initial_fields else None
|
||||
sources: list[int] = []
|
||||
next_offset = initial_next_offset if current is not None else 0
|
||||
current_issues: list[str] = []
|
||||
|
||||
def flush() -> None:
|
||||
nonlocal current, sources, next_offset, current_issues
|
||||
if current is not None and (sources or initial_fields):
|
||||
results.append(CoordinateProfileLogicalRow(fields=current, source_row_indices=sources, issues=current_issues))
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, bbox, termination_rules or []):
|
||||
flush()
|
||||
break
|
||||
if _DELETED_PATTERN.fullmatch(re.sub(r'\s+', '', text)):
|
||||
# Deletion markers apply only to the immediately preceding started record.
|
||||
# Do not emit it as a partial row and do not guess an association when no
|
||||
# main row is active.
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
continue
|
||||
main_values, main_issues = values_for(band, ordered_layouts[0])
|
||||
line_no = re.sub(r'\s+', '', main_values.get('line_no', ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
|
||||
flush()
|
||||
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
|
||||
continue
|
||||
if current is None or next_offset >= len(ordered_layouts):
|
||||
continue
|
||||
if not layout_order_valid:
|
||||
current_issues.append('coordinate_profile_layout_region_mismatch')
|
||||
flush()
|
||||
continue
|
||||
continuation, continuation_issues = values_for(band, ordered_layouts[next_offset])
|
||||
if not continuation:
|
||||
# Once a logical row has started, its declared physical rows must be consecutive.
|
||||
# Continuing after an unexpected region would silently mix two visual records.
|
||||
if continuation_issues:
|
||||
current_issues.extend(continuation_issues)
|
||||
flush()
|
||||
continue
|
||||
for code, value in continuation.items():
|
||||
previous = current.get(code, '').strip()
|
||||
if previous and previous != value:
|
||||
current_issues.append(f'coordinate_profile_composite_conflict:{code}')
|
||||
else:
|
||||
current[code] = value
|
||||
sources.append(row_index)
|
||||
current_issues.extend(continuation_issues)
|
||||
next_offset += 1
|
||||
flush()
|
||||
return results
|
||||
|
||||
|
||||
def _reconstruct_relative_y_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
table_bbox: LayoutBBox,
|
||||
ordered_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]],
|
||||
initial_fields: dict[str, str] | None,
|
||||
) -> list[CoordinateProfileLogicalRow] | None:
|
||||
"""
|
||||
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
|
||||
|
||||
只有字段框明确切分了父物理行的纵向子带时才启用;旧模板的整高字段和多物理行
|
||||
row_offset 继续走原有逐视觉行算法。运行时先用 ``line_no`` 找到每条明细起点,再把
|
||||
样例字段的相对 Y 映射到相邻起点之间,避免料号尾数污染下方数量、单位和日期。
|
||||
"""
|
||||
if initial_fields or len(ordered_layouts) != 1:
|
||||
return None
|
||||
layout = ordered_layouts[0]
|
||||
parent = layout.get('region')
|
||||
fields = [
|
||||
field for field in (layout.get('field_regions') or [])
|
||||
if isinstance(field, dict) and isinstance(field.get('region'), dict)
|
||||
]
|
||||
if not isinstance(parent, dict) or not _has_relative_y_subregions(parent, fields):
|
||||
return None
|
||||
line_field = next((field for field in fields if str(field.get('field_code') or '') == 'line_no'), None)
|
||||
if line_field is None:
|
||||
return None
|
||||
bands = _group_visual_rows(glyphs)
|
||||
usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
for row_index, band in enumerate(bands):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules):
|
||||
break
|
||||
usable_bands.append((row_index, band))
|
||||
if not usable_bands:
|
||||
return []
|
||||
|
||||
line_region = _absolute_relative_region(table_bbox, line_field['region'])
|
||||
anchors: list[int] = []
|
||||
for index, (_, band) in enumerate(usable_bands):
|
||||
line_text = re.sub(r'\s+', '', _text_in_horizontal_region(band, line_region))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_text):
|
||||
anchors.append(index)
|
||||
if not anchors:
|
||||
return []
|
||||
|
||||
sample_end = anchors[1] if len(anchors) > 1 else len(usable_bands)
|
||||
sample_record = usable_bands[anchors[0]:sample_end]
|
||||
field_band_indices = _calibrate_field_band_indices(
|
||||
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
|
||||
)
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
|
||||
record = usable_bands[start:end]
|
||||
if any(_DELETED_PATTERN.fullmatch(re.sub(
|
||||
r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)),
|
||||
)) for _, band in record):
|
||||
continue
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
matched_bands, alignment_issues = _match_field_band_groups(
|
||||
fields=fields,
|
||||
record=record,
|
||||
expected_indices=field_band_indices,
|
||||
table_bbox=table_bbox,
|
||||
)
|
||||
issues.extend(alignment_issues)
|
||||
for field in fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code:
|
||||
continue
|
||||
band_index = matched_bands.get(id(field))
|
||||
if band_index is None:
|
||||
continue
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(record[band_index][1], region)
|
||||
if not raw:
|
||||
continue
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
for extracted_code, extracted_value in extracted.items():
|
||||
previous = values.get(extracted_code)
|
||||
if previous is not None and previous != extracted_value:
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
line_no = re.sub(r'\s+', '', values.get('line_no', ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
issues=issues,
|
||||
))
|
||||
return results
|
||||
|
||||
|
||||
def _matches_termination_rule(
|
||||
band: list[tuple[int, PositionedCharacter]], table_bbox: LayoutBBox, rules: list[dict[str, Any]],
|
||||
) -> bool:
|
||||
"""仅在管理员声明的区域和文字锚点同时命中时停止,避免条款文本误伤明细。"""
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
for rule in rules:
|
||||
anchor = rule.get('anchor') if isinstance(rule, dict) else None
|
||||
if not isinstance(anchor, dict):
|
||||
continue
|
||||
expected = str(anchor.get('text') or '').strip()
|
||||
if not expected:
|
||||
continue
|
||||
region = anchor.get('region')
|
||||
if isinstance(region, dict):
|
||||
absolute = _absolute_relative_region(table_bbox, region)
|
||||
center_y = sum((glyph.bbox.y0 + glyph.bbox.y1) / 2 for _, glyph in band) / len(band)
|
||||
if not absolute.y0 <= center_y <= absolute.y1:
|
||||
continue
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if text.casefold() == expected.casefold():
|
||||
return True
|
||||
elif expected.casefold() in text.casefold():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def suggest_multi_subrow_layouts(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
@@ -171,10 +533,17 @@ def suggest_multi_subrow_layouts(
|
||||
boundaries, column_samples, line_column = _suggest_band_boundaries(
|
||||
samples, bbox, detect_line_number=row_offset == 0,
|
||||
)
|
||||
# 列边界可聚合多条明细,但纵向样例必须来自同一条记录;否则会把每种
|
||||
# 子行拉伸到整张表高度,造成主行与续行区域互相重叠。
|
||||
band_glyphs = [glyph for _, glyph in samples[0]]
|
||||
y0 = min(glyph.bbox.y0 for glyph in band_glyphs)
|
||||
y1 = max(glyph.bbox.y1 for glyph in band_glyphs)
|
||||
suggestions.append(CoordinateSubrowSuggestion(
|
||||
role='main' if row_offset == 0 else 'continuation',
|
||||
row_offset=row_offset,
|
||||
column_boundaries=boundaries,
|
||||
y0=max(0, (y0 - bbox.y0) / (bbox.y1 - bbox.y0)),
|
||||
y1=min(1, (y1 - bbox.y0) / (bbox.y1 - bbox.y0)),
|
||||
column_samples=column_samples,
|
||||
suggested_field_codes=[
|
||||
'line_no' if row_offset == 0 and index == line_column else None
|
||||
@@ -184,6 +553,66 @@ def suggest_multi_subrow_layouts(
|
||||
return suggestions
|
||||
|
||||
|
||||
def suggest_header_regions(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
) -> list[CoordinateHeaderRegionSuggestion]:
|
||||
"""从首条明细前识别独立表头视觉行;混有业务值的行保持人工复核。"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
glyphs = _table_glyphs(characters, bbox)
|
||||
width = bbox.x1 - bbox.x0
|
||||
height = bbox.y1 - bbox.y0
|
||||
if not glyphs or width <= 0 or height <= 0:
|
||||
return []
|
||||
result: list[CoordinateHeaderRegionSuggestion] = []
|
||||
for band in _group_visual_rows(glyphs):
|
||||
if _band_starts_item(band, bbox):
|
||||
break
|
||||
text = ' '.join(value for value in (
|
||||
''.join(glyph.text for _, glyph in run).strip()
|
||||
for run in _group_text_runs(sorted(band, key=lambda item: item[1].bbox.x0))
|
||||
) if value)
|
||||
if not _looks_like_header(text):
|
||||
continue
|
||||
band_bbox = _band_bbox(band)
|
||||
field_runs = [
|
||||
run for run in _group_text_runs(sorted(band, key=lambda item: item[1].bbox.x0))
|
||||
if ''.join(glyph.text for _, glyph in run).strip()
|
||||
]
|
||||
run_boxes = [_run_bbox(run) for run in field_runs]
|
||||
field_regions: list[CoordinateHeaderFieldRegionSuggestion] = []
|
||||
for field_index, run in enumerate(field_runs):
|
||||
run_text = ''.join(glyph.text for _, glyph in run).strip()
|
||||
if not run_text:
|
||||
continue
|
||||
run_bbox = _run_bbox(run)
|
||||
# Expand each text token to its column slot using neighboring midpoints;
|
||||
# this keeps the header field aligned with the detail column below it.
|
||||
left = band_bbox.x0 if field_index == 0 else (run_boxes[field_index - 1].x1 + run_bbox.x0) / 2
|
||||
right = band_bbox.x1 if field_index == len(run_boxes) - 1 else (run_bbox.x1 + run_boxes[field_index + 1].x0) / 2
|
||||
field_regions.append(CoordinateHeaderFieldRegionSuggestion(
|
||||
region={
|
||||
'x0': max(0, (left - bbox.x0) / width),
|
||||
'y0': max(0, (run_bbox.y0 - bbox.y0) / height),
|
||||
'x1': min(1, (right - bbox.x0) / width),
|
||||
'y1': min(1, (run_bbox.y1 - bbox.y0) / height),
|
||||
},
|
||||
text=run_text[:160],
|
||||
))
|
||||
result.append(CoordinateHeaderRegionSuggestion(
|
||||
region={
|
||||
'x0': max(0, (band_bbox.x0 - bbox.x0) / width),
|
||||
'y0': max(0, (band_bbox.y0 - bbox.y0) / height),
|
||||
'x1': min(1, (band_bbox.x1 - bbox.x0) / width),
|
||||
'y1': min(1, (band_bbox.y1 - bbox.y0) / height),
|
||||
},
|
||||
text=text[:160],
|
||||
fields=field_regions,
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def reconstruct_table_from_positioned_text(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
@@ -393,9 +822,18 @@ def _band_field_values(
|
||||
|
||||
|
||||
def _looks_like_header(text: str) -> bool:
|
||||
"""以有限英文表头词识别数据区之前的多层表头,避免把表头并入首条明细。"""
|
||||
"""以有限英文表头词识别数据区之前的多层表头,兼容 PDF 丢失词间空格。"""
|
||||
words = set(re.findall(r'[a-z]+', text.lower()))
|
||||
return len(words & _HEADER_TERMS) >= 2
|
||||
matched = words & _HEADER_TERMS
|
||||
# 部分 PDF 字符层会把 ``ITEM NO``、``UNIT PRICE`` 合并成 ITEMNO、UNITPRICE。
|
||||
# 仅对已知表头词做子串恢复,且仍要求至少两个不同词,避免普通业务值误命中。
|
||||
compact_words = {word for word in words if len(word) >= 5}
|
||||
matched.update(
|
||||
term
|
||||
for term in _HEADER_TERMS
|
||||
if len(term) >= 3 and any(term in word for word in compact_words)
|
||||
)
|
||||
return len(matched) >= 2
|
||||
|
||||
|
||||
def _band_starts_item(
|
||||
@@ -480,6 +918,182 @@ def _table_glyphs(
|
||||
return sorted(glyphs, key=lambda item: ((item[1].bbox.y0 + item[1].bbox.y1) / 2, item[1].bbox.x0, item[0]))
|
||||
|
||||
|
||||
def _absolute_relative_region(table_bbox: LayoutBBox, relative: dict[str, Any]) -> LayoutBBox:
|
||||
"""把 Profile 的 0..1 相对区域投影到当前页面绝对坐标,适配页面缩放。"""
|
||||
x0, y0, x1, y1 = (float(relative[key]) for key in ('x0', 'y0', 'x1', 'y1'))
|
||||
return LayoutBBox(
|
||||
x0=table_bbox.x0 + (table_bbox.x1 - table_bbox.x0) * x0,
|
||||
y0=table_bbox.y0 + (table_bbox.y1 - table_bbox.y0) * y0,
|
||||
x1=table_bbox.x0 + (table_bbox.x1 - table_bbox.x0) * x1,
|
||||
y1=table_bbox.y0 + (table_bbox.y1 - table_bbox.y0) * y1,
|
||||
)
|
||||
|
||||
|
||||
def _inside_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅收集中心在管理员框选区域内的字符,边缘字符不跨区域复制。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
|
||||
|
||||
|
||||
def _inside_horizontal_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅按标注框横向范围筛选字符,使同一行版式可应用到整张表的重复明细。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1
|
||||
|
||||
|
||||
def _has_relative_y_subregions(parent: dict[str, Any], fields: list[dict[str, Any]]) -> bool:
|
||||
"""判断字段是否在父物理行内提供了可用于投影的纵向子带。"""
|
||||
parent_y0, parent_y1 = float(parent['y0']), float(parent['y1'])
|
||||
if parent_y1 <= parent_y0:
|
||||
return False
|
||||
tolerance = max(1e-6, (parent_y1 - parent_y0) * .02)
|
||||
return any(
|
||||
float(field['region']['y0']) > parent_y0 + tolerance
|
||||
or float(field['region']['y1']) < parent_y1 - tolerance
|
||||
for field in fields
|
||||
)
|
||||
|
||||
|
||||
def _calibrate_field_band_indices(
|
||||
*,
|
||||
fields: list[dict[str, Any]],
|
||||
sample_record: list[tuple[int, list[tuple[int, PositionedCharacter]]]],
|
||||
table_bbox: LayoutBBox,
|
||||
) -> dict[int, int]:
|
||||
"""用样例字段框与首条明细真实字符的 Y 重叠校准视觉 band offset。"""
|
||||
result: dict[int, int] = {}
|
||||
band_boxes = [_band_bbox(band) for _, band in sample_record]
|
||||
for field in fields:
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
overlaps = [max(0.0, min(region.y1, box.y1) - max(region.y0, box.y0)) for box in band_boxes]
|
||||
best_overlap = max(overlaps, default=0.0)
|
||||
if best_overlap > 0:
|
||||
candidates = [index for index, overlap in enumerate(overlaps) if overlap == best_overlap]
|
||||
else:
|
||||
center = (region.y0 + region.y1) / 2
|
||||
distances = [abs(center - (box.y0 + box.y1) / 2) for box in band_boxes]
|
||||
nearest = min(distances, default=0.0)
|
||||
candidates = [index for index, distance in enumerate(distances) if distance == nearest]
|
||||
result[id(field)] = candidates[0] if candidates else 0
|
||||
return result
|
||||
|
||||
|
||||
def _match_field_band_groups(
|
||||
*,
|
||||
fields: list[dict[str, Any]],
|
||||
record: list[tuple[int, list[tuple[int, PositionedCharacter]]]],
|
||||
expected_indices: dict[int, int],
|
||||
table_bbox: LayoutBBox,
|
||||
) -> tuple[dict[int, int], list[str]]:
|
||||
"""将样例纵向字段组单调对齐到运行时 bands;额外换行可插入但组顺序不可倒退。"""
|
||||
if not record:
|
||||
return {}, []
|
||||
groups: dict[int, list[dict[str, Any]]] = {}
|
||||
for field in fields:
|
||||
groups.setdefault(expected_indices[id(field)], []).append(field)
|
||||
matched: dict[int, int] = {}
|
||||
issues: list[str] = []
|
||||
previous_index = -1
|
||||
for expected_index, group_fields in sorted(groups.items()):
|
||||
if any(str(field.get('field_code') or '') == 'line_no' for field in group_fields):
|
||||
selected_index = 0
|
||||
else:
|
||||
candidates: list[tuple[float, int]] = []
|
||||
for index in range(previous_index + 1, len(record)):
|
||||
score = 0.0
|
||||
evidence_count = 0
|
||||
for field in group_fields:
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(record[index][1], region)
|
||||
if not raw:
|
||||
continue
|
||||
evidence_count += 1
|
||||
score += _profile_field_band_score(
|
||||
raw=raw,
|
||||
field_code=str(field.get('field_code') or ''),
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'),
|
||||
)
|
||||
if evidence_count:
|
||||
score -= abs(index - expected_index) * .2
|
||||
candidates.append((score, index))
|
||||
if not candidates:
|
||||
continue
|
||||
candidates.sort(reverse=True)
|
||||
best_score, selected_index = candidates[0]
|
||||
if len(candidates) > 1 and best_score - candidates[1][0] < .25:
|
||||
codes = ','.join(sorted(str(field.get('field_code') or '') for field in group_fields))
|
||||
issues.append(f'coordinate_profile_field_band_ambiguous:{codes}')
|
||||
continue
|
||||
for field in group_fields:
|
||||
matched[id(field)] = selected_index
|
||||
previous_index = selected_index
|
||||
return matched, issues
|
||||
|
||||
|
||||
def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str) -> float:
|
||||
"""以注册解析器和既有有限字段形态评分,禁止自由规则或模板专用特例。"""
|
||||
extracted = extract_profile_field_value(extractor_key=extractor_key, field_code=field_code, raw=raw)
|
||||
if not extracted:
|
||||
return -1.0
|
||||
score = 1.0 + _field_content_score(raw, field_code)
|
||||
if field_code in {'part_number', 'customer_part_number', 'aws_part_number'}:
|
||||
compact = re.sub(r'\s+', '', raw)
|
||||
if re.search(r'\s', raw):
|
||||
score -= .75
|
||||
if re.search(r'\d|[._/-]', compact):
|
||||
score += .5
|
||||
return score
|
||||
|
||||
|
||||
def _text_in_region(
|
||||
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
|
||||
) -> str:
|
||||
"""按 PDF 字符间距恢复视觉空格,避免原生文本层省略空格导致字段粘连。"""
|
||||
selected = sorted(
|
||||
(item for item in band if _inside_region(item[1].bbox, region)),
|
||||
key=lambda item: (item[1].bbox.x0, item[0]),
|
||||
)
|
||||
if not selected:
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
|
||||
|
||||
def _text_in_horizontal_region(
|
||||
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
|
||||
) -> str:
|
||||
"""在当前视觉行内按字段横向边界恢复文本,忽略标注样例的绝对纵向位置。"""
|
||||
selected = sorted(
|
||||
(item for item in band if _inside_horizontal_region(item[1].bbox, region)),
|
||||
key=lambda item: (item[1].bbox.x0, item[0]),
|
||||
)
|
||||
if not selected:
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
|
||||
|
||||
def _normalized_header_text(value: str) -> str:
|
||||
"""标准化表头候选,允许空格、斜线和标点差异但不执行模糊语义猜测。"""
|
||||
return re.sub(r'[^a-z0-9]+', '', value.lower())
|
||||
|
||||
|
||||
def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[list[tuple[int, PositionedCharacter]]]:
|
||||
"""按自适应 y 阈值形成视觉行,阈值来自字体高度而不是固定页面像素。"""
|
||||
heights = [glyph.bbox.y1 - glyph.bbox.y0 for _, glyph in glyphs]
|
||||
@@ -522,6 +1136,15 @@ def _run_bbox(run: list[tuple[int, PositionedCharacter]]) -> LayoutBBox:
|
||||
)
|
||||
|
||||
|
||||
def _band_bbox(band: list[tuple[int, PositionedCharacter]]) -> LayoutBBox:
|
||||
"""汇总一条视觉 band 的字符边界,供样例字段框校准真实子行。"""
|
||||
boxes = [glyph.bbox for _, glyph in band]
|
||||
return LayoutBBox(
|
||||
x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes),
|
||||
x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes),
|
||||
)
|
||||
|
||||
|
||||
def _assign_column(
|
||||
bbox: LayoutBBox,
|
||||
text: str,
|
||||
@@ -569,11 +1192,11 @@ def _field_content_score(text: str, field_code: str | None) -> float:
|
||||
compact = value.replace(',', '').replace(' ', '')
|
||||
if field_code == 'line_no':
|
||||
return 1.0 if _LINE_NUMBER_PATTERN.fullmatch(compact) else -1.0
|
||||
if field_code in {'qty', 'unit_price', 'amount'}:
|
||||
if field_code in {'qty', 'unit_price', 'amount', 'line_amount_before_tax', 'line_amount_with_tax'}:
|
||||
return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0
|
||||
if field_code == 'uom':
|
||||
return 1.0 if re.fullmatch(r'[A-Za-z]{1,6}', compact) else -0.5
|
||||
if field_code == 'required_date':
|
||||
if field_code in {'required_date', 'requested_receipt_date'}:
|
||||
return 1.0 if re.fullmatch(r'\d{1,4}[-/]\d{1,2}[-/]\d{1,4}', compact) else -0.5
|
||||
if field_code in {'part_number', 'customer_part_number', 'aws_part_number'}:
|
||||
return 0.75 if re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/-]{2,}', compact) else 0.0
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
|
||||
用途:定义订单文档模板级解析 Profile 纯契约,覆盖全局 Schema 无法表达的模板列语义。
|
||||
依赖:Pydantic、HTML 网格、订单字段规则和既有 TEMP 复合料号规则。
|
||||
逻辑:普通 Profile 按精确表头指纹匹配;坐标 Profile 先合并物理续行并生成稳定虚拟表头,再按固定列执行注册解析器。
|
||||
用途:定义订单文档坐标模板 v2 的纯契约和受控字段绑定。
|
||||
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;运行时匹配器与坐标解析器只消费该不可变定义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -32,8 +32,8 @@ from app.services.shipping_notice.order_schema.table_contract import (
|
||||
)
|
||||
|
||||
|
||||
ORDER_PROFILE_VERSION = 'shipping_order_document_profile.v1'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts'})
|
||||
ORDER_PROFILE_VERSION = 'order_coordinate_profile.v2'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'})
|
||||
HEADER_LINE_ITEM_VALUE_PATTERN = re.compile(
|
||||
r'\b(?:item|line)\s*(?:no\.?|number|#)?\s*[:#-]?\s*0{2,}\d+\b',
|
||||
re.IGNORECASE,
|
||||
@@ -46,8 +46,235 @@ class OrderProfileModel(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class RelativeRegion(OrderProfileModel):
|
||||
"""表示页面或表格内的归一化矩形;绝不持久化浏览器像素。"""
|
||||
|
||||
x0: float = Field(ge=0, le=1)
|
||||
y0: float = Field(ge=0, le=1)
|
||||
x1: float = Field(ge=0, le=1)
|
||||
y1: float = Field(ge=0, le=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_area(self) -> 'RelativeRegion':
|
||||
"""拒绝零面积和反向区域,避免运行时存在不确定的坐标归属。"""
|
||||
if self.x0 >= self.x1 or self.y0 >= self.y1:
|
||||
raise ValueError('relative region must have positive area')
|
||||
return self
|
||||
|
||||
|
||||
class AnchorRule(OrderProfileModel):
|
||||
"""定义模板匹配或行启动使用的稳定静态文字锚点。"""
|
||||
|
||||
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
text: str = Field(min_length=1, max_length=160)
|
||||
match_mode: Literal['exact', 'contains'] = 'contains'
|
||||
region: RelativeRegion | None = None
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
|
||||
class FieldRegion(OrderProfileModel):
|
||||
"""将一个管理员确认的坐标区域绑定至稳定 Schema field_code。"""
|
||||
|
||||
field_id: str = Field(min_length=1, max_length=128)
|
||||
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
region: RelativeRegion
|
||||
extractor_key: Literal['direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'] = 'direct'
|
||||
allowed_sources: list[Literal['pdf_coordinate', 'ocr_coordinate']] = Field(min_length=1)
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
target_fields: list[dict[str, str]] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_source(self) -> 'FieldRegion':
|
||||
"""限制为后端注册的解析器和坐标来源,禁止正则、脚本或 Prompt 注入。"""
|
||||
if len(self.allowed_sources) != len(set(self.allowed_sources)):
|
||||
raise ValueError('field region sources must be unique')
|
||||
if self.target_fields:
|
||||
codes = [str(item.get('field_code') or '') for item in self.target_fields]
|
||||
if len(codes) != len(set(codes)) or self.field_code not in codes:
|
||||
raise ValueError('field region targets must be unique and include field_code')
|
||||
return self
|
||||
|
||||
|
||||
class HeaderLayout(OrderProfileModel):
|
||||
"""描述一条独立表头物理行;它只提供校准和字段建议证据。"""
|
||||
|
||||
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
region: RelativeRegion
|
||||
field_regions: list[FieldRegion] = Field(default_factory=list)
|
||||
|
||||
|
||||
class LineLayout(OrderProfileModel):
|
||||
"""描述一条逻辑明细内的物理行及其字段区域。"""
|
||||
|
||||
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
row_offset: int = Field(ge=0)
|
||||
role: Literal['main', 'continuation']
|
||||
region: RelativeRegion
|
||||
field_regions: list[FieldRegion] = Field(default_factory=list)
|
||||
new_line_anchor: AnchorRule | None = None
|
||||
continuation_conditions: list[AnchorRule] = Field(default_factory=list)
|
||||
required_fields: list[str] = Field(default_factory=list)
|
||||
allowed_empty_fields: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ContinuationRule(OrderProfileModel):
|
||||
"""声明表区或页面之间可合并的明确证据,默认绝不自动跨页拼接。"""
|
||||
|
||||
allow_cross_page: bool = False
|
||||
required_anchor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_explicit_cross_page_evidence(self) -> 'ContinuationRule':
|
||||
"""跨页必须有至少一个静态锚点;仅因相邻页或相似列布局不得合并。"""
|
||||
if self.allow_cross_page and not self.required_anchor_ids:
|
||||
raise ValueError('cross-page continuation requires anchor evidence')
|
||||
if len(self.required_anchor_ids) != len(set(self.required_anchor_ids)):
|
||||
raise ValueError('cross-page continuation anchors must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class TerminationRule(OrderProfileModel):
|
||||
"""定义明确的终止标记,防止合计、税额和条款被当作订单明细。"""
|
||||
|
||||
rule_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
anchor: AnchorRule
|
||||
|
||||
|
||||
class DraftUnboundFieldRegion(OrderProfileModel):
|
||||
"""草稿阶段尚未绑定 Schema 的字段框;运行和发布均不得使用。"""
|
||||
|
||||
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
|
||||
parent_layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
region: RelativeRegion
|
||||
|
||||
|
||||
class TableRegionProfile(OrderProfileModel):
|
||||
"""定义一个订单明细表区、独立表头和多物理行布局。"""
|
||||
|
||||
region_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
region: RelativeRegion
|
||||
header_layouts: list[HeaderLayout] = Field(default_factory=list)
|
||||
line_layouts: list[LineLayout] = Field(default_factory=list)
|
||||
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
|
||||
termination_rules: list[TerminationRule] = Field(default_factory=list)
|
||||
exclusion_regions: list[RelativeRegion] = Field(default_factory=list)
|
||||
draft_unbound_field_regions: list[DraftUnboundFieldRegion] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_table_layout(self) -> 'TableRegionProfile':
|
||||
"""校验物理行顺序、字段唯一性和同级区域不重叠,拒绝含糊的模板真相。"""
|
||||
if self.page_scope == 'exact_page' and self.page_no is None:
|
||||
raise ValueError('exact_page table region requires page_no')
|
||||
if self.page_scope != 'exact_page' and self.page_no is not None:
|
||||
raise ValueError('page_no is only allowed for exact_page table regions')
|
||||
layouts = self.header_layouts + self.line_layouts
|
||||
if not layouts:
|
||||
raise ValueError('table region requires at least one header or line layout')
|
||||
ids = [item.layout_id for item in layouts]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('table layout ids must be unique')
|
||||
offsets = [item.row_offset for item in self.line_layouts]
|
||||
if sorted(offsets) != list(range(len(offsets))):
|
||||
raise ValueError('line layout offsets must be contiguous from zero')
|
||||
if self.line_layouts and (sum(item.role == 'main' for item in self.line_layouts) != 1 or self.line_layouts[0].role != 'main'):
|
||||
raise ValueError('line layouts require one main layout at offset zero')
|
||||
if any(item.role != 'continuation' for item in self.line_layouts[1:]):
|
||||
raise ValueError('line layouts after the main layout must be continuations')
|
||||
# 表头映射只用于建议/校准,可以与明细字段同名;真正的提取绑定必须唯一。
|
||||
fields = [field.field_code for item in self.line_layouts for field in item.field_regions]
|
||||
if len(fields) != len(set(fields)):
|
||||
raise ValueError('field_code may bind to only one coordinate region per table')
|
||||
# A physical text band must have exactly one layout interpretation. Allowing
|
||||
# overlapping header/line regions would reintroduce the cross-row ambiguity
|
||||
# that v2 coordinate profiles are intended to eliminate.
|
||||
_validate_non_overlapping_regions([item.region for item in layouts])
|
||||
for item in layouts:
|
||||
_validate_non_overlapping_regions([field.region for field in item.field_regions])
|
||||
_validate_non_overlapping_regions(self.exclusion_regions)
|
||||
layout_ids = {item.layout_id for item in layouts}
|
||||
if any(item.parent_layout_id not in layout_ids for item in self.draft_unbound_field_regions):
|
||||
raise ValueError('draft unbound field region requires a layout parent')
|
||||
region_ids = [item.region_id for item in self.draft_unbound_field_regions]
|
||||
if len(region_ids) != len(set(region_ids)):
|
||||
raise ValueError('draft unbound field region ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class DocumentMatchProfile(OrderProfileModel):
|
||||
"""定义模板唯一匹配所需的静态证据;动态订单业务值不可进入此对象。"""
|
||||
|
||||
document_type: Literal['purchase_order'] = 'purchase_order'
|
||||
page_pattern: Literal['one_or_more'] = 'one_or_more'
|
||||
required_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
optional_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
minimum_score: float = Field(default=0.9, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_anchor_ids(self) -> 'DocumentMatchProfile':
|
||||
"""要求必选和可选锚点名称唯一,避免评分器使用含糊证据。"""
|
||||
ids = [item.anchor_id for item in self.required_anchors + self.optional_anchors]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('document match anchor ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
"""保存阶段 0 评审中的订单坐标模板 v2 定义,尚未接入旧运行路径。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
document_match: DocumentMatchProfile
|
||||
table_regions: list[TableRegionProfile] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
|
||||
"""阻断重复表区和重叠表区,确保一个字段位置只有唯一模板解释。"""
|
||||
ids = [item.region_id for item in self.table_regions]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('table region ids must be unique')
|
||||
for index, left in enumerate(self.table_regions):
|
||||
for right in self.table_regions[index + 1:]:
|
||||
# Different exact pages may use identical coordinates without competing at runtime.
|
||||
if _table_regions_can_apply_same_page(left, right):
|
||||
_validate_non_overlapping_regions([left.region, right.region])
|
||||
anchor_ids = {item.anchor_id for item in self.document_match.required_anchors + self.document_match.optional_anchors}
|
||||
for table in self.table_regions:
|
||||
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
|
||||
raise ValueError('cross-page continuation anchor must be a document match anchor')
|
||||
return self
|
||||
|
||||
|
||||
def _validate_non_overlapping_regions(regions: list[RelativeRegion]) -> None:
|
||||
"""拒绝任意正面积重叠,边缘相接仍是合法的精确坐标布局。"""
|
||||
for index, left in enumerate(regions):
|
||||
for right in regions[index + 1:]:
|
||||
if min(left.x1, right.x1) > max(left.x0, right.x0) and min(left.y1, right.y1) > max(left.y0, right.y0):
|
||||
raise ValueError('coordinate regions must not overlap')
|
||||
|
||||
|
||||
def _table_regions_can_apply_same_page(left: TableRegionProfile, right: TableRegionProfile) -> bool:
|
||||
"""判断两个页作用域是否可能命中同一页,供表区重叠校验排除不同精确页。"""
|
||||
if left.page_scope == 'all_pages' or right.page_scope == 'all_pages':
|
||||
return True
|
||||
if left.page_scope == 'exact_page' and right.page_scope == 'exact_page':
|
||||
return left.page_no == right.page_no
|
||||
if left.page_scope == 'exact_page':
|
||||
return left.page_no == 1 if right.page_scope == 'first_page' else bool(left.page_no and left.page_no > 1)
|
||||
if right.page_scope == 'exact_page':
|
||||
return right.page_no == 1 if left.page_scope == 'first_page' else bool(right.page_no and right.page_no > 1)
|
||||
return left.page_scope == right.page_scope
|
||||
|
||||
|
||||
# Transitional adapters keep the currently deployed extraction workflow importable while its
|
||||
# callers are migrated to the v2 coordinate runtime in later gated stages. They are not part
|
||||
# of the persisted v2 contract and must not be used by new Profile writes.
|
||||
class OrderProfileColumnRule(OrderProfileModel):
|
||||
"""定义一个固定来源列使用的注册解析器及目标字段编码。"""
|
||||
"""Legacy runtime column rule retained only until the frozen-run migration is complete."""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts']
|
||||
@@ -55,21 +282,19 @@ class OrderProfileColumnRule(OrderProfileModel):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_targets(self) -> 'OrderProfileColumnRule':
|
||||
"""限制注册解析器的固定输出形态,禁止自由脚本或任意字段注入。"""
|
||||
"""Preserve the established finite extractor whitelist for historical frozen snapshots."""
|
||||
targets = set(self.target_field_codes)
|
||||
if len(targets) != len(self.target_field_codes):
|
||||
raise ValueError('order profile target fields must be unique')
|
||||
if self.extractor_key == 'direct' and len(targets) != 1:
|
||||
raise ValueError('direct order profile extractor requires one target field')
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {
|
||||
'customer_part_number', 'part_number',
|
||||
}:
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {'customer_part_number', 'part_number'}:
|
||||
raise ValueError('TEMP/internal extractor targets are fixed')
|
||||
return self
|
||||
|
||||
|
||||
class CoordinateReconstructionProfile(OrderProfileModel):
|
||||
"""冻结管理员确认的相对列边界;同版 PDF 表格据此重建并仍受 Profile 精确指纹门禁。"""
|
||||
"""Legacy frozen-run coordinate reconstruction adapter; v2 uses FieldRegion instead."""
|
||||
|
||||
method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1'
|
||||
column_boundaries: list[float] = Field(default_factory=list)
|
||||
@@ -79,38 +304,27 @@ class CoordinateReconstructionProfile(OrderProfileModel):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_boundaries(self) -> 'CoordinateReconstructionProfile':
|
||||
"""边界须覆盖整表且严格递增,禁止由错误 HTML 反向猜列。"""
|
||||
"""Validate historical settings so existing frozen Run snapshots remain safe to load."""
|
||||
if self.subrow_layouts:
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout
|
||||
|
||||
layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts]
|
||||
offsets = [item.row_offset for item in layouts]
|
||||
roles = [item.role for item in layouts]
|
||||
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or roles.count('main') != 1:
|
||||
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or sum(item.role == 'main' for item in layouts) != 1:
|
||||
raise ValueError('coordinate subrow layouts require contiguous offsets and one main row')
|
||||
if next(item for item in layouts if item.role == 'main').row_offset != 0:
|
||||
raise ValueError('coordinate main row must use offset zero')
|
||||
if any(item.row_offset > 0 and item.role != 'continuation' for item in layouts):
|
||||
raise ValueError('coordinate rows after the main row must be continuations')
|
||||
return self
|
||||
if len(self.column_boundaries) < 3:
|
||||
raise ValueError('coordinate reconstruction requires column boundaries')
|
||||
if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate reconstruction boundaries must start at 0 and end at 1')
|
||||
if len(self.column_boundaries) < 3 or self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate reconstruction boundaries must cover the table')
|
||||
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
|
||||
raise ValueError('coordinate reconstruction boundaries must be strictly increasing')
|
||||
column_count = len(self.column_boundaries) - 1
|
||||
if self.column_field_codes and len(self.column_field_codes) != column_count:
|
||||
if self.column_field_codes and len(self.column_field_codes) != len(self.column_boundaries) - 1:
|
||||
raise ValueError('coordinate reconstruction field codes must match column count')
|
||||
if self.line_start_column_index >= column_count:
|
||||
raise ValueError('coordinate reconstruction line start column is out of range')
|
||||
return self
|
||||
|
||||
|
||||
class OrderDocumentProfile(OrderProfileModel):
|
||||
"""保存不可变模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
"""保存当前已发布运行路径的模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
contract_version: Literal['shipping_order_document_profile.v1'] = 'shipping_order_document_profile.v1'
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
structure_fingerprint: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_extractors.py
|
||||
|
||||
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
|
||||
依赖:订单料号复合解析与数值解析。
|
||||
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
|
||||
|
||||
_NUMBER_UNIT = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{1,12})\s*$')
|
||||
_MONEY_CURRENCY = re.compile(r'^\s*([A-Za-z]{3}|[$€£¥])\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$')
|
||||
_CURRENCY_MONEY = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{3}|[$€£¥])\s*$')
|
||||
_CURRENCY_SYMBOLS = {'$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'CNY'}
|
||||
|
||||
|
||||
def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str) -> dict[str, str]:
|
||||
"""将一个已确认区域按注册解析器拆分;不允许调用方传入规则、脚本或正则。"""
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return {}
|
||||
if extractor_key == 'direct':
|
||||
return {field_code: text}
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(text)
|
||||
return {
|
||||
code: str(value).strip() for code, value in (resolved or {}).items()
|
||||
if code in {'customer_part_number', 'part_number'} and str(value or '').strip()
|
||||
}
|
||||
if extractor_key == 'quantity_uom':
|
||||
matched = _NUMBER_UNIT.fullmatch(text)
|
||||
if not matched:
|
||||
return {}
|
||||
return {'qty': matched.group(1).replace(',', ''), 'uom': matched.group(2).upper()}
|
||||
if extractor_key in {'amount_currency', 'price_currency'}:
|
||||
matched = _MONEY_CURRENCY.fullmatch(text) or _CURRENCY_MONEY.fullmatch(text)
|
||||
if not matched:
|
||||
return {}
|
||||
first, second = matched.groups()
|
||||
currency, amount = (first, second) if first.isalpha() or first in _CURRENCY_SYMBOLS else (second, first)
|
||||
try:
|
||||
Decimal(amount.replace(',', ''))
|
||||
except (InvalidOperation, ValueError):
|
||||
return {}
|
||||
return {
|
||||
'line_amount_before_tax' if extractor_key == 'amount_currency' else 'unit_price': amount.replace(',', ''),
|
||||
'currency': _CURRENCY_SYMBOLS.get(currency, currency.upper()),
|
||||
}
|
||||
return {}
|
||||
|
||||
|
||||
def registered_extractor_output_codes(*, extractor_key: str, field_code: str) -> set[str]:
|
||||
"""返回一个注册解析器的固定输出集合,供契约校验拒绝含糊字段绑定。"""
|
||||
if extractor_key == 'direct':
|
||||
return {field_code}
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
return {'customer_part_number', 'part_number'}
|
||||
if extractor_key == 'quantity_uom':
|
||||
return {'qty', 'uom'}
|
||||
if extractor_key == 'amount_currency':
|
||||
return {'line_amount_before_tax', 'currency'}
|
||||
if extractor_key == 'price_currency':
|
||||
return {'unit_price', 'currency'}
|
||||
return set()
|
||||
@@ -0,0 +1,122 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
|
||||
用途:以冻结的页面坐标证据唯一匹配订单坐标模板。
|
||||
依赖:OrderCoordinateProfileV2 和布局快照。逻辑:必需锚点与表区数量先作为硬条件,
|
||||
可选锚点只参与评分;没有达到阈值或分差的候选绝不进入确定性解析。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
|
||||
|
||||
|
||||
class ProfileMatchCandidate(BaseModel):
|
||||
"""记录单个冻结 Profile 的非敏感匹配分数和失败原因。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
profile_code: str
|
||||
version: int = Field(ge=1)
|
||||
score: float = Field(ge=0, le=1)
|
||||
hard_match: bool
|
||||
reasons: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ProfileMatchResult(BaseModel):
|
||||
"""文档级唯一匹配结果;只有 unique_match 可以启动坐标确定性解析。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
status: Literal['unique_match', 'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient']
|
||||
profile_code: str | None = None
|
||||
version: int | None = None
|
||||
checksum: str | None = None
|
||||
candidates: list[ProfileMatchCandidate] = Field(default_factory=list)
|
||||
|
||||
|
||||
def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: dict[str, Any]) -> ProfileMatchResult:
|
||||
"""对同一文档的冻结 Profile 做唯一匹配,业务值和上传时间均不参与计算。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
if not tables or not pages or not glyph_tables:
|
||||
return ProfileMatchResult(status='evidence_insufficient')
|
||||
|
||||
candidates: list[tuple[dict[str, Any], OrderCoordinateProfileV2, ProfileMatchCandidate]] = []
|
||||
for raw in profiles:
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
if definition.get('contract_version') != 'order_coordinate_profile.v2':
|
||||
continue
|
||||
try:
|
||||
profile = OrderCoordinateProfileV2(
|
||||
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
|
||||
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
reasons: list[str] = []
|
||||
if len(tables) < len(profile.table_regions):
|
||||
reasons.append('table_region_count_insufficient')
|
||||
required = profile.document_match.required_anchors
|
||||
required_hits = [_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in required]
|
||||
if not all(required_hits):
|
||||
reasons.append('required_anchor_missing')
|
||||
optional = profile.document_match.optional_anchors
|
||||
optional_hits = sum(_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in optional)
|
||||
hard_match = not reasons
|
||||
# Required evidence is mandatory rather than a soft score. Optional evidence only separates already valid templates.
|
||||
score = 1.0 if not optional else 0.8 + 0.2 * optional_hits / len(optional)
|
||||
candidates.append((raw, profile, ProfileMatchCandidate(
|
||||
profile_code=profile.profile_code, version=profile.version, score=score if hard_match else 0.0,
|
||||
hard_match=hard_match, reasons=reasons,
|
||||
)))
|
||||
rendered = sorted((item[2] for item in candidates), key=lambda item: (-item.score, item.profile_code, item.version))
|
||||
valid = sorted((item for item in candidates if item[2].hard_match), key=lambda item: (-item[2].score, item[1].profile_code, item[1].version))
|
||||
if not valid:
|
||||
status: Literal['no_match', 'layout_drift'] = 'layout_drift' if rendered else 'no_match'
|
||||
return ProfileMatchResult(status=status, candidates=rendered)
|
||||
raw, profile, first = valid[0]
|
||||
if first.score < profile.document_match.minimum_score:
|
||||
return ProfileMatchResult(status='no_match', candidates=rendered)
|
||||
if len(valid) > 1 and first.score - valid[1][2].score < profile.document_match.minimum_margin:
|
||||
return ProfileMatchResult(status='ambiguous', candidates=rendered)
|
||||
return ProfileMatchResult(
|
||||
status='unique_match', profile_code=profile.profile_code, version=profile.version,
|
||||
checksum=str(raw.get('checksum') or ''), candidates=rendered,
|
||||
)
|
||||
|
||||
|
||||
def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any], pages: dict[str, Any]) -> bool:
|
||||
"""检查静态锚点是否在指定页面区域出现;不读取订单业务字段或 HTML 网格。"""
|
||||
expected = str(anchor.get('text') or '').strip()
|
||||
if not expected:
|
||||
return False
|
||||
for table in tables:
|
||||
glyphs = glyph_tables.get(str(table.get('table_id') or ''))
|
||||
page = pages.get(str(table.get('page_no') or ''))
|
||||
if not isinstance(glyphs, list) or not isinstance(page, dict):
|
||||
continue
|
||||
selected = glyphs
|
||||
region = anchor.get('region')
|
||||
if isinstance(region, dict):
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
x0, y0, x1, y1 = float(region['x0']) * width, float(region['y0']) * height, float(region['x1']) * width, float(region['y1']) * height
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
selected = [item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)
|
||||
and x0 <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= x1
|
||||
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
|
||||
text = ''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))))
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if expected.casefold() == text.casefold():
|
||||
return True
|
||||
elif expected.casefold() in text.casefold():
|
||||
return True
|
||||
return False
|
||||
@@ -187,7 +187,7 @@ def build_mineru_table_snapshot(
|
||||
|
||||
|
||||
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""按 MinerU 整表 bbox 截取 PDF 字符证据;非表格正文与页面图像绝不持久化。"""
|
||||
"""保存表内字符和内部页尺寸,使 v2 页面相对坐标可在冻结 Run 中精确换算。"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
|
||||
pages = {item.page_no: item for item in extract_native_pdf_pages(content)}
|
||||
@@ -211,7 +211,15 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
|
||||
glyphs.append(item.model_dump(mode='json'))
|
||||
if glyphs:
|
||||
evidence[table_id] = glyphs
|
||||
return {'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence}
|
||||
return {
|
||||
'version': 'shipping_order_coordinate_evidence.v1',
|
||||
'tables': evidence,
|
||||
# Internal runtime metadata only. It is removed with layout_snapshot before Dify input.
|
||||
'pages': {
|
||||
str(page_no): {'width': page.width, 'height': page.height}
|
||||
for page_no, page in pages.items()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None:
|
||||
|
||||
@@ -23,23 +23,54 @@ from app.models import (
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderCoordinateProfileV2,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_service import _definition_contract
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
|
||||
from app.services.shipping_notice.order_document_profile_service import _audit, _definition_contract
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
MINIMUM_BLIND_SAMPLES = 3
|
||||
HEADERLESS_MINIMUM_BLIND_SAMPLES = 5
|
||||
|
||||
|
||||
def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str:
|
||||
"""返回当前可测试定义的稳定校验值;草稿用定义 hash,发布版用正式 checksum。"""
|
||||
checksum = profile.checksum if profile.status == 'published' else profile.structure_fingerprint
|
||||
if not checksum:
|
||||
raise ConflictError('Profile checksum is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
return str(checksum)
|
||||
|
||||
|
||||
def _requires_cross_page_sample(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""判断模板是否声明跨页拼接;该类模板必须用真实续页证据进行盲测。"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
return any(
|
||||
isinstance(region, dict)
|
||||
and bool((region.get('continuation_rule') or {}).get('allow_cross_page'))
|
||||
for region in definition.get('table_regions') or []
|
||||
)
|
||||
|
||||
|
||||
def _is_headerless(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""无表头坐标模板风险更高,要求五个独立回放样本。"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
regions = definition.get('table_regions') if isinstance(definition.get('table_regions'), list) else []
|
||||
return bool(regions) and not any(
|
||||
isinstance(region, dict) and region.get('header_layouts') for region in regions
|
||||
)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取已发布 Profile;草稿和退役版本不能获得自动建单质量凭证。"""
|
||||
"""读取草稿或发布 Profile;仅发布版本可最终获得自动建单凭证。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'published' or not profile.checksum:
|
||||
raise ConflictError('Only published order document profile can be tested', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
if profile.status not in {'draft', 'published'}:
|
||||
raise ConflictError('Only draft or published order document profile can be tested', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
_quality_checksum(profile)
|
||||
return profile
|
||||
|
||||
|
||||
@@ -57,6 +88,19 @@ def _table_html(document_id: int, table_id: str) -> str:
|
||||
raise ValidationError('Test sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
|
||||
|
||||
def _coordinate_table_available(document_id: int, table_id: str) -> bool:
|
||||
"""确认 v2 盲测有冻结页面尺寸和目标表的字符证据,不要求 MinerU HTML。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
layout = current_layout_snapshot(document) if document is not None else {}
|
||||
raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)), None)
|
||||
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
|
||||
return bool(
|
||||
isinstance(raw_table, dict)
|
||||
and isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
|
||||
and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or '')), dict)
|
||||
)
|
||||
|
||||
|
||||
def _expected_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
"""校验人工录入的盲测真值,只接受行字段字典且不允许空集合。"""
|
||||
if not isinstance(raw, list) or not raw or any(not isinstance(item, dict) or not item for item in raw):
|
||||
@@ -65,15 +109,18 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def create_suite(*, profile_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""为一个发布 Profile 建立唯一盲测集;旧批准凭证不会被覆盖。"""
|
||||
"""为草稿或发布 Profile 建立唯一盲测集;发布前完成审批以形成真正发布门禁。"""
|
||||
profile = _profile(profile_id)
|
||||
existing = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first()
|
||||
if existing is not None:
|
||||
return serialize_suite(existing)
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=profile.checksum, created_by_id=actor_id,
|
||||
profile_id=profile.id, profile_checksum=_quality_checksum(profile), created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
_audit(profile_id=profile.id, event_type='blind_test_suite_created', actor_id=actor_id, detail={
|
||||
'profile_checksum': _quality_checksum(profile),
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
@@ -85,17 +132,50 @@ def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
if suite.status != 'draft':
|
||||
raise ConflictError('Approved test suite is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE')
|
||||
_table_html(document_id, table_id)
|
||||
profile = _profile(suite.profile_id)
|
||||
from app.models import ShippingOrderDocumentProfileSample
|
||||
if ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id, document_id=int(document_id)).first() is not None:
|
||||
raise ConflictError('Blind test samples must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT')
|
||||
parser = _definition_contract(profile)
|
||||
if isinstance(parser, OrderCoordinateProfileV2):
|
||||
if not _coordinate_table_available(document_id, table_id):
|
||||
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
else:
|
||||
_table_html(document_id, table_id)
|
||||
sample = ShippingDocumentProfileTestSample(
|
||||
suite_id=suite.id, document_id=int(document_id), table_id=str(table_id),
|
||||
expected_rows_json=_expected_rows(expected_rows), created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(sample)
|
||||
try:
|
||||
db.session.commit()
|
||||
db.session.flush()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Test sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_CONFLICT') from exc
|
||||
_audit(profile_id=suite.profile_id, document_id=sample.document_id, event_type='blind_test_sample_added', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id, 'has_table_binding': bool(sample.table_id),
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
|
||||
def remove_sample(*, suite_id: int, sample_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""删除草稿盲测样本真值;批准后的证据不可原地删除或替换。"""
|
||||
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
|
||||
if suite is None:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
if suite.status != 'draft':
|
||||
raise ConflictError('Approved test suite is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE')
|
||||
sample = db.session.get(ShippingDocumentProfileTestSample, int(sample_id))
|
||||
if sample is None or sample.suite_id != suite.id:
|
||||
raise NotFoundError('Order document profile test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_FOUND')
|
||||
document_id = sample.document_id
|
||||
db.session.delete(sample)
|
||||
db.session.flush()
|
||||
_audit(profile_id=suite.profile_id, document_id=document_id, event_type='blind_test_sample_removed', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id,
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
|
||||
@@ -105,17 +185,44 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
if suite is None:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
profile = _profile(suite.profile_id)
|
||||
if suite.profile_checksum != profile.checksum:
|
||||
if suite.profile_checksum != _quality_checksum(profile):
|
||||
raise ConflictError('Profile changed after test suite creation', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_STALE')
|
||||
contract = compile_table_header_contract(profile.schema_version.definition_json or {})
|
||||
parser = _definition_contract(profile)
|
||||
failures: list[str] = []
|
||||
passed = 0
|
||||
for sample in suite.samples:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
layout = current_layout_snapshot(document) if document is not None else None
|
||||
if isinstance(parser, OrderCoordinateProfileV2):
|
||||
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
characters = (evidence.get('tables') or {}).get(sample.table_id) if isinstance(evidence.get('tables'), dict) else None
|
||||
raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id), None)
|
||||
page = pages.get(str((raw_table or {}).get('page_no') or '')) if isinstance(pages, dict) else None
|
||||
if not isinstance(characters, list) or not isinstance(page, dict):
|
||||
failures.append(f'sample:{sample.id}:coordinate_evidence_missing')
|
||||
continue
|
||||
try:
|
||||
table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
failures.append(f'sample:{sample.id}:coordinate_evidence_missing')
|
||||
continue
|
||||
actual_rows: list[dict[str, Any]] = []
|
||||
for region in parser.table_regions:
|
||||
actual_rows.extend(item.fields for item in reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox,
|
||||
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
) if not item.issues)
|
||||
if actual_rows == list(sample.expected_rows_json or []):
|
||||
passed += 1
|
||||
else:
|
||||
failures.append(f'sample:{sample.id}:mismatch')
|
||||
continue
|
||||
html = _table_html(sample.document_id, sample.table_id)
|
||||
if parser.coordinate_reconstruction is not None:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
layout = current_layout_snapshot(document) if document is not None else None
|
||||
raw_table = next((
|
||||
item for item in (layout or {}).get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id
|
||||
@@ -140,12 +247,16 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
failures.append(f'sample:{sample.id}:mismatch')
|
||||
sample_count = len(suite.samples)
|
||||
run = ShippingDocumentProfileTestRun(
|
||||
suite_id=suite.id, profile_checksum=profile.checksum,
|
||||
suite_id=suite.id, profile_checksum=_quality_checksum(profile),
|
||||
status='passed' if sample_count >= MINIMUM_BLIND_SAMPLES and passed == sample_count else 'failed',
|
||||
sample_count=sample_count, passed_sample_count=passed, failure_codes_json=failures,
|
||||
executed_by_id=actor_id,
|
||||
)
|
||||
db.session.add(run)
|
||||
_audit(profile_id=profile.id, event_type='blind_test_executed', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id, 'status': run.status, 'sample_count': sample_count,
|
||||
'passed_sample_count': passed,
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
@@ -158,13 +269,16 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
profile = _profile(suite.profile_id)
|
||||
last_run = suite.runs[-1] if suite.runs else None
|
||||
if (
|
||||
suite.status != 'draft' or suite.profile_checksum != profile.checksum or last_run is None
|
||||
or last_run.status != 'passed' or last_run.profile_checksum != profile.checksum
|
||||
suite.status != 'draft' or suite.profile_checksum != _quality_checksum(profile) or last_run is None
|
||||
or last_run.status != 'passed' or last_run.profile_checksum != _quality_checksum(profile)
|
||||
):
|
||||
raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY')
|
||||
suite.status = 'approved'
|
||||
suite.approved_by_id = actor_id
|
||||
suite.approved_at = datetime.utcnow()
|
||||
_audit(profile_id=profile.id, event_type='blind_test_approved', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id, 'profile_checksum': _quality_checksum(profile),
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
@@ -177,6 +291,60 @@ def profile_is_auto_create_approved(*, profile_id: int, checksum: str) -> bool:
|
||||
return suite is not None
|
||||
|
||||
|
||||
def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""执行坐标模板发布门禁:训练样本、独立盲测、多明细与跨页覆盖均不可绕过。"""
|
||||
from app.models import ShippingOrderDocumentProfileSample
|
||||
|
||||
draft_checksum = _quality_checksum(profile)
|
||||
training_count = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=profile.id, sample_role='training',
|
||||
).count()
|
||||
if training_count < 1:
|
||||
raise ConflictError('A training sample is required before publishing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING')
|
||||
suite = ShippingDocumentProfileTestSuite.query.filter_by(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved',
|
||||
).first()
|
||||
if suite is None or not suite.runs or suite.runs[-1].status != 'passed' or suite.runs[-1].profile_checksum != draft_checksum:
|
||||
raise ConflictError('An approved current blind test is required before publishing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST')
|
||||
minimum = HEADERLESS_MINIMUM_BLIND_SAMPLES if _is_headerless(profile) else MINIMUM_BLIND_SAMPLES
|
||||
samples = list(suite.samples)
|
||||
if len(samples) < minimum or len({item.document_id for item in samples}) < minimum:
|
||||
raise ConflictError('Insufficient independent blind test samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST')
|
||||
model_documents = {
|
||||
item.document_id for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
|
||||
}
|
||||
if model_documents & {item.document_id for item in samples}:
|
||||
raise ConflictError('Blind test samples must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST')
|
||||
if not any(len(item.expected_rows_json or []) > 1 for item in samples):
|
||||
raise ConflictError('A multi-line blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_MULTILINE')
|
||||
if _requires_cross_page_sample(profile):
|
||||
has_cross_page = False
|
||||
for sample in samples:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
layout = current_layout_snapshot(document) if document is not None else {}
|
||||
table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id), None)
|
||||
if isinstance(table, dict) and table.get('continuation_of'):
|
||||
has_cross_page = True
|
||||
break
|
||||
if not has_cross_page:
|
||||
raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE')
|
||||
|
||||
|
||||
def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str) -> None:
|
||||
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。"""
|
||||
suite = ShippingDocumentProfileTestSuite.query.filter_by(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved',
|
||||
).one_or_none()
|
||||
# Production callers have passed assert_profile_publishable. This guard keeps
|
||||
# isolated lifecycle tests from fabricating a quality credential by monkeypatch.
|
||||
if suite is None:
|
||||
return
|
||||
suite.profile_checksum = published_checksum
|
||||
for run in suite.runs:
|
||||
if run.profile_checksum == draft_checksum:
|
||||
run.profile_checksum = published_checksum
|
||||
|
||||
|
||||
def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
"""返回不含订单正文的盲测治理摘要,供管理端确认发布状态。"""
|
||||
latest = suite.runs[-1] if suite.runs else None
|
||||
|
||||
@@ -64,6 +64,19 @@ def _cfg_bool(key: str, default: bool = False) -> bool:
|
||||
return str(val).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _rpa_callback_success(value: Any) -> bool:
|
||||
"""严格解析 Worker 上传回调结果,拒绝把字符串 ``"false"`` 当作成功。"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {'true', '1'}:
|
||||
return True
|
||||
if normalized in {'false', '0'}:
|
||||
return False
|
||||
raise ValidationError('Upload callback success must be boolean', code='SHIPPING.UPLOAD_CALLBACK_INVALID')
|
||||
|
||||
|
||||
def _task_disposition_gate_response(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""在履约副作用前阻断回收站、作废或归档任务,避免迟到请求继续改变业务事实。"""
|
||||
reason = task_execution_block_reason(task)
|
||||
@@ -749,9 +762,21 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
artifact = current_upload_artifact(task, attempt.artifact_id)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
queued, trigger = write_upload_trigger(task.task_no, artifact.file_path, payload={
|
||||
'artifact_id': artifact.id, 'attempt_id': attempt.id, 'callback_id': f'rpa:{attempt.id}',
|
||||
})
|
||||
upload_connector_type = str(task.inventory_connector_type or '').strip().lower()
|
||||
upload_entry_url = ''
|
||||
if upload_connector_type == 'dbs' and task.inventory_source_code:
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source = get_rpa_trigger_inventory_source(task.inventory_source_code, enabled_only=False) or {}
|
||||
upload_entry_url = str(source.get('login_url') or source.get('entry_url') or '').strip()
|
||||
try:
|
||||
queued, trigger = write_upload_trigger(task.task_no, artifact.file_path, payload={
|
||||
'artifact_id': artifact.id, 'attempt_id': attempt.id, 'callback_id': f'rpa:{attempt.id}',
|
||||
'inventory_connector_type': upload_connector_type,
|
||||
'inventory_entry_url': upload_entry_url,
|
||||
})
|
||||
except OSError:
|
||||
queued, trigger = None, None
|
||||
if queued and trigger:
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
|
||||
attempt_no = attempt.attempt_no
|
||||
@@ -798,6 +823,15 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
},
|
||||
)
|
||||
|
||||
# Trigger 写入失败时,不能遗留 running Attempt / uploading Artifact;否则下一次
|
||||
# retry_upload 会被假性进行中的状态阻断。以独立 callback id 记录本地投递失败。
|
||||
complete_attempt(
|
||||
attempt,
|
||||
success=False,
|
||||
callback_id=f'trigger_failed:{attempt.id}',
|
||||
error_message='RPA upload trigger could not be written',
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -809,7 +843,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
detail=t("workflow.fulfillment.upload_takeover_detail", lang=lang),
|
||||
)
|
||||
task.error_message = t("workflow.fulfillment.upload_trigger_failed", lang=lang)
|
||||
log_task_event(task, "upload_rpa_pending", {})
|
||||
log_task_event(task, "upload_rpa_trigger_failed", {'attempt_id': attempt.id if 'attempt' in locals() else None})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -855,7 +889,10 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||
if artifact is None or artifact.task_id != task.id:
|
||||
return tool_response(status='failed', task=task, message='Upload attempt does not belong to this task', data=serialize_task_for_tool(task))
|
||||
success = bool(payload.get("success", True))
|
||||
try:
|
||||
success = _rpa_callback_success(payload.get("success", True))
|
||||
except ValidationError as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
try:
|
||||
completed = complete_attempt(
|
||||
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
|
||||
@@ -863,7 +900,8 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
if success:
|
||||
# 重复 callback 由 Attempt 的持久化结果决定,不能按本次请求值重写 UI 状态。
|
||||
if completed.status == 'succeeded':
|
||||
if task.process_status == 'uploaded':
|
||||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||||
set_task_step_progress(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,11 +19,15 @@ from app.services.shipping_notice.context_fields.dify_exposure import compile_re
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderDocumentProfile,
|
||||
OrderCoordinateProfileV2,
|
||||
OrderProfileColumnRule,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
|
||||
|
||||
def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
@@ -225,9 +229,30 @@ def _frozen_order_profile(raw: dict[str, Any]) -> OrderDocumentProfile:
|
||||
)
|
||||
|
||||
|
||||
def _profile_snapshot_targets_valid(raw: dict[str, Any], *, contract: Any) -> bool:
|
||||
def _profile_snapshot_targets_valid(
|
||||
raw: dict[str, Any], *, contract: Any, schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> bool:
|
||||
"""确认 Profile 冻结的 field_id/code 与 Run Schema 完全一致,禁止仅凭可变名称执行。"""
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
if definition.get('contract_version') == 'order_coordinate_profile.v2':
|
||||
for table in definition.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
return False
|
||||
for layout in (table.get('header_layouts') or []) + (table.get('line_layouts') or []):
|
||||
for target in layout.get('field_regions') or []:
|
||||
code = str(target.get('field_code') or '')
|
||||
config = contract.fields_by_code.get(code) or (schema_fields or {}).get(code)
|
||||
if config is None or str(target.get('field_id') or '') != str(config.get('field_id') or ''):
|
||||
return False
|
||||
targets = target.get('target_fields') if isinstance(target.get('target_fields'), list) else []
|
||||
if not targets:
|
||||
return False
|
||||
for output in targets:
|
||||
output_code = str(output.get('field_code') or '') if isinstance(output, dict) else ''
|
||||
output_config = contract.fields_by_code.get(output_code) or (schema_fields or {}).get(output_code)
|
||||
if output_config is None or str(output.get('field_id') or '') != str(output_config.get('field_id') or ''):
|
||||
return False
|
||||
return True
|
||||
for rule in definition.get('column_rules') or []:
|
||||
if not isinstance(rule, dict):
|
||||
return False
|
||||
@@ -288,6 +313,147 @@ def _dify_profile_candidates(tables: list[dict[str, Any]]) -> list[dict[str, Any
|
||||
return result
|
||||
|
||||
|
||||
def _coordinate_v2_profile_rows(
|
||||
*, raw_profile: dict[str, Any], raw_table: dict[str, Any], layout: dict[str, Any],
|
||||
contract: Any, schema_fields: dict[str, dict[str, Any]], initial_carry: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""用冻结 v2 区域和字符证据生成紧凑行候选;缺少坐标时 fail closed。"""
|
||||
profile = _frozen_coordinate_profile(raw_profile)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
characters = tables.get(str(raw_table.get('table_id') or ''))
|
||||
page_size = pages.get(str(raw_table.get('page_no') or ''))
|
||||
if not isinstance(characters, list) or not isinstance(page_size, dict):
|
||||
return None
|
||||
try:
|
||||
page_bbox = {
|
||||
'x0': 0, 'y0': 0, 'x1': float(page_size['width']), 'y1': float(page_size['height']),
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0:
|
||||
return None
|
||||
rows: list[dict[str, Any]] = []
|
||||
for region in profile.table_regions:
|
||||
page_no = int(raw_table.get('page_no') or 1)
|
||||
if region.page_scope == 'first_page' and page_no != 1:
|
||||
continue
|
||||
if region.page_scope == 'continuation_pages' and page_no <= 1:
|
||||
continue
|
||||
if region.page_scope == 'exact_page' and page_no != region.page_no:
|
||||
continue
|
||||
# A continuation page may carry column headers only; it is not a data layout.
|
||||
if not region.line_layouts:
|
||||
continue
|
||||
carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {}
|
||||
for reconstructed in reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=page_bbox,
|
||||
line_layouts=[item.model_dump() for item in region.line_layouts],
|
||||
table_region=region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
|
||||
):
|
||||
values: list[dict[str, Any]] = []
|
||||
issues = list(reconstructed.issues)
|
||||
for code, raw_value in reconstructed.fields.items():
|
||||
config = contract.fields_by_code.get(code)
|
||||
# Composite extractors may produce a frozen Header output (for example currency).
|
||||
# It is retained here and later accepted only when all rows agree on the same value.
|
||||
if config is None:
|
||||
config = schema_fields.get(code)
|
||||
if config is None:
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
try:
|
||||
value = normalize_order_field_value(raw_value, config)
|
||||
except (TypeError, ValueError, ValidationError):
|
||||
value = None
|
||||
if value is None or not validate_order_field_value(value, config):
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
values.append({'field_id': str(config.get('field_id') or ''), 'field_code': code, 'value': value, 'quote': str(raw_value)[:1000]})
|
||||
rows.append({'row_index': reconstructed.source_row_indices[0], 'status': 'parsed' if not issues else 'needs_review', 'fields': values, 'issues': issues,
|
||||
'_coordinate_region_id': region.region_id, '_coordinate_row_count': int(carry.get('source_row_count') or 0) + len(reconstructed.source_row_indices)})
|
||||
return rows
|
||||
|
||||
|
||||
def _cross_page_anchor_matches(*, raw_profile: dict[str, Any], raw_table: dict[str, Any], layout: dict[str, Any], anchor_ids: list[str]) -> bool:
|
||||
"""续页必须在冻结字符证据中命中管理员声明的静态锚点,缺坐标即拒绝合并。"""
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
|
||||
anchors = {str(item.get('anchor_id') or ''): item for item in (match.get('required_anchors') or []) + (match.get('optional_anchors') or []) if isinstance(item, dict)}
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
glyphs = (evidence.get('tables') or {}).get(str(raw_table.get('table_id') or ''))
|
||||
if not isinstance(glyphs, list):
|
||||
return False
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page = pages.get(str(raw_table.get('page_no') or ''))
|
||||
if not isinstance(page, dict):
|
||||
return False
|
||||
try:
|
||||
page_width, page_height = float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
for anchor_id in anchor_ids:
|
||||
anchor = anchors.get(anchor_id)
|
||||
expected = str((anchor or {}).get('text') or '')
|
||||
if not expected:
|
||||
return False
|
||||
selected = glyphs
|
||||
region = anchor.get('region')
|
||||
if isinstance(region, dict):
|
||||
try:
|
||||
x0, y0 = float(region['x0']) * page_width, float(region['y0']) * page_height
|
||||
x1, y1 = float(region['x1']) * page_width, float(region['y1']) * page_height
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
selected = [item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)
|
||||
and x0 <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= x1
|
||||
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
|
||||
bands: dict[int, list[dict[str, Any]]] = {}
|
||||
for item in selected:
|
||||
if not isinstance(item, dict) or not isinstance(item.get('bbox'), dict):
|
||||
continue
|
||||
center_y = (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2
|
||||
bands.setdefault(round(center_y / 3), []).append(item)
|
||||
texts = [
|
||||
''.join(str(item.get('text') or '') for item in sorted(band, key=lambda item: item.get('bbox', {}).get('x0', 0)))
|
||||
for _band, band in sorted(bands.items())
|
||||
]
|
||||
text = '\n'.join(texts)
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if not any(expected.casefold() == item.casefold() for item in texts):
|
||||
return False
|
||||
elif expected.casefold() not in text.casefold():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _validate_table_header_outputs(rows: list[dict[str, Any]], *, schema_fields: dict[str, dict[str, Any]]) -> bool:
|
||||
"""Header 输出只能在同表所有有效明细行一致时保留,否则阻断确定性建单。"""
|
||||
values_by_field: dict[str, set[str]] = {}
|
||||
for row in rows:
|
||||
if not isinstance(row, dict) or row.get('status') != 'parsed':
|
||||
continue
|
||||
for field in row.get('fields') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
config = schema_fields.get(str(field.get('field_code') or ''))
|
||||
if config is not None and config.get('scope') == 'header':
|
||||
values_by_field.setdefault(str(field.get('field_id') or ''), set()).add(
|
||||
json.dumps(field.get('value'), ensure_ascii=False, sort_keys=True),
|
||||
)
|
||||
if any(len(values) > 1 for values in values_by_field.values()):
|
||||
for row in rows:
|
||||
if isinstance(row, dict):
|
||||
row['status'] = 'needs_review'
|
||||
row.setdefault('issues', []).append('order_profile_header_value_conflict')
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
"""
|
||||
用 Run 冻结 Profile 解析 MinerU HTML,并生成不含坐标/HTML的紧凑字段候选。
|
||||
@@ -298,6 +464,10 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
contract = compile_table_header_contract(definition)
|
||||
schema_fields = {
|
||||
str(item.get('field_code') or ''): item for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
}
|
||||
profiles = [
|
||||
item for item in snapshot.get('order_document_profiles') or []
|
||||
if isinstance(item, dict)
|
||||
@@ -307,18 +477,86 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
|
||||
if layout.get('status') != 'ready' or not profiles:
|
||||
return {'matched': False, 'blocking': False, 'tables': [], 'issues': []}
|
||||
v2_profiles = [
|
||||
item for item in profiles
|
||||
if isinstance(item.get('definition'), dict)
|
||||
and item['definition'].get('contract_version') == 'order_coordinate_profile.v2'
|
||||
]
|
||||
if v2_profiles:
|
||||
match = match_frozen_coordinate_profiles(profiles=v2_profiles, layout=layout)
|
||||
if match.status != 'unique_match':
|
||||
return {
|
||||
'matched': False, 'blocking': True, 'tables': [],
|
||||
'issues': [f'order_profile_{match.status}'],
|
||||
'match': match.model_dump(mode='json'),
|
||||
}
|
||||
profiles = [
|
||||
item for item in v2_profiles
|
||||
if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version
|
||||
and str(item.get('checksum') or '') == match.checksum
|
||||
]
|
||||
result_tables: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
matched_any = False
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict) or not str(raw_table.get('html') or '').strip():
|
||||
cross_page_carries: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for raw_table in sorted((item for item in layout.get('tables') or [] if isinstance(item, dict)), key=lambda item: (int(item.get('page_no') or 1), str(item.get('table_id') or ''))):
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
table_id = str(raw_table.get('table_id') or '')
|
||||
matches: list[tuple[dict[str, Any], Any]] = []
|
||||
for raw_profile in profiles:
|
||||
if not _profile_snapshot_targets_valid(raw_profile, contract=contract):
|
||||
if not _profile_snapshot_targets_valid(raw_profile, contract=contract, schema_fields=schema_fields):
|
||||
issues.append('order_profile_snapshot_field_mismatch')
|
||||
continue
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
if definition.get('contract_version') == 'order_coordinate_profile.v2':
|
||||
# v2 consumes only the frozen table bounds and native/OCR coordinates.
|
||||
# MinerU HTML is intentionally neither required nor parsed on this path.
|
||||
try:
|
||||
profile = _frozen_coordinate_profile(raw_profile)
|
||||
carry = None
|
||||
parent_table_id = str(raw_table.get('continuation_of') or '')
|
||||
if parent_table_id:
|
||||
for region in profile.table_regions:
|
||||
candidate = cross_page_carries.get((str(raw_profile.get('profile_code') or ''), parent_table_id))
|
||||
if candidate and candidate.get('region_id') == region.region_id and region.continuation_rule.allow_cross_page and _cross_page_anchor_matches(
|
||||
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
|
||||
anchor_ids=region.continuation_rule.required_anchor_ids,
|
||||
):
|
||||
carry = candidate
|
||||
break
|
||||
v2_rows = _coordinate_v2_profile_rows(
|
||||
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
|
||||
contract=contract, schema_fields=schema_fields, initial_carry=carry,
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
issues.append('order_profile_snapshot_invalid')
|
||||
continue
|
||||
if v2_rows is None:
|
||||
issues.append('order_profile_coordinate_reconstruction_unavailable')
|
||||
continue
|
||||
if v2_rows:
|
||||
complete_rows = []
|
||||
for row in v2_rows:
|
||||
region = next((item for item in profile.table_regions if item.region_id == row.get('_coordinate_region_id')), None)
|
||||
if region is not None and row.get('_coordinate_row_count', 0) < len(region.line_layouts):
|
||||
cross_page_carries[(str(raw_profile.get('profile_code') or ''), table_id)] = {
|
||||
'region_id': region.region_id,
|
||||
'fields': {str(field.get('field_code') or ''): str(field.get('value') or '') for field in row.get('fields') or [] if isinstance(field, dict)},
|
||||
'next_offset': int(row.get('_coordinate_row_count') or 0),
|
||||
'source_row_count': int(row.get('_coordinate_row_count') or 0),
|
||||
}
|
||||
continue
|
||||
row.pop('_coordinate_region_id', None)
|
||||
row.pop('_coordinate_row_count', None)
|
||||
complete_rows.append(row)
|
||||
v2_rows = complete_rows
|
||||
if v2_rows:
|
||||
_validate_table_header_outputs(v2_rows, schema_fields=schema_fields)
|
||||
matches.append((raw_profile, v2_rows))
|
||||
continue
|
||||
if not str(raw_table.get('html') or '').strip():
|
||||
continue
|
||||
try:
|
||||
profile = _frozen_order_profile(raw_profile)
|
||||
source_html = _reconstructed_profile_html(layout=layout, raw_table=raw_table, profile=profile)
|
||||
@@ -343,6 +581,13 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
issues.append('order_profile_multiple_matches')
|
||||
continue
|
||||
raw_profile, parsed = matches[0]
|
||||
if isinstance(parsed, list):
|
||||
result_tables.append({
|
||||
'profile_code': str(raw_profile.get('profile_code') or ''), 'profile_version': int(raw_profile.get('version') or 0),
|
||||
'profile_checksum': str(raw_profile.get('checksum') or ''), 'table_id': table_id, 'page_no': int(raw_table.get('page_no') or 1),
|
||||
'auto_create_approved': bool(raw_profile.get('auto_create_approved')), 'rows': parsed,
|
||||
})
|
||||
continue
|
||||
if parsed.issues:
|
||||
issues.extend(parsed.issues)
|
||||
continue
|
||||
@@ -580,6 +825,15 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
return [order] if order is not None else None
|
||||
|
||||
|
||||
def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
|
||||
"""从 Run 快照恢复 v2 坐标契约,运行时不回读 Profile 数据库记录。"""
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
return OrderCoordinateProfileV2(
|
||||
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
|
||||
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
|
||||
)
|
||||
|
||||
|
||||
def _build_approved_profile_order(
|
||||
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
|
||||
table: dict[str, Any],
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/compatibility.py
|
||||
|
||||
用途:判断订单文档模板引用的稳定 field_id 是否能兼容新的订单 Schema。
|
||||
依赖:Schema definition JSON 与订单文档 Profile definition JSON。
|
||||
逻辑:字段身份按 field_id 对齐;新增字段兼容,缺失、作用域或类型变化属于破坏性变更。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _fields(definition: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
|
||||
"""按稳定 field_id 提取 Schema 字段快照。"""
|
||||
return {
|
||||
str(item.get('field_id')): item
|
||||
for item in (definition or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('field_id')
|
||||
}
|
||||
|
||||
|
||||
def referenced_field_ids(profile_definition: dict[str, Any] | None) -> set[str]:
|
||||
"""读取模板所有坐标字段区域引用的稳定 field_id。"""
|
||||
result: set[str] = set()
|
||||
for table in (profile_definition or {}).get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for layout_key in ('header_layouts', 'line_layouts'):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
for field in layout.get('field_regions') or []:
|
||||
if isinstance(field, dict) and field.get('field_id'):
|
||||
result.add(str(field['field_id']))
|
||||
for target in field.get('target_fields') or []:
|
||||
if isinstance(target, dict) and target.get('field_id'):
|
||||
result.add(str(target['field_id']))
|
||||
return result
|
||||
|
||||
|
||||
def is_replacement_compatible(
|
||||
source: dict[str, Any],
|
||||
candidate: dict[str, Any],
|
||||
*,
|
||||
source_field_id: str | None = None,
|
||||
candidate_field_id: str | None = None,
|
||||
) -> bool:
|
||||
"""判断迁移替代字段能否承接原坐标绑定;原字段不能替代自身。"""
|
||||
if source_field_id and candidate_field_id and source_field_id == candidate_field_id:
|
||||
return False
|
||||
return (
|
||||
candidate.get('enabled', True)
|
||||
and candidate.get('scope') == source.get('scope')
|
||||
and candidate.get('value_type') == source.get('value_type')
|
||||
and set(source.get('allowed_sources') or []).issubset(set(candidate.get('allowed_sources') or []))
|
||||
)
|
||||
|
||||
|
||||
def _replacement_candidates(
|
||||
source: dict[str, Any],
|
||||
target: dict[str, dict[str, Any]],
|
||||
*,
|
||||
source_field_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""返回服务端可再次校验的安全替代字段摘要。"""
|
||||
return [
|
||||
{
|
||||
'field_id': candidate_id,
|
||||
'field_code': candidate.get('field_code'),
|
||||
'display_name': candidate.get('display_name'),
|
||||
}
|
||||
for candidate_id, candidate in target.items()
|
||||
if is_replacement_compatible(
|
||||
source,
|
||||
candidate,
|
||||
source_field_id=source_field_id,
|
||||
candidate_field_id=candidate_id,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def compare_profile_schema(
|
||||
profile_definition: dict[str, Any] | None,
|
||||
profile_schema_definition: dict[str, Any] | None,
|
||||
target_schema_definition: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""按 field_id 计算模板从原 Schema 到目标 Schema 的兼容性。"""
|
||||
previous = _fields(profile_schema_definition)
|
||||
target = _fields(target_schema_definition)
|
||||
referenced = referenced_field_ids(profile_definition)
|
||||
breaking: list[dict[str, Any]] = []
|
||||
review: list[dict[str, Any]] = []
|
||||
unchanged: list[str] = []
|
||||
renamed: list[dict[str, Any]] = []
|
||||
for field_id in sorted(referenced):
|
||||
before = previous.get(field_id)
|
||||
after = target.get(field_id)
|
||||
if before is None:
|
||||
breaking.append({'field_id': field_id, 'reason': 'source_field_missing'})
|
||||
continue
|
||||
if after is None or after.get('enabled') is False:
|
||||
breaking.append({
|
||||
'field_id': field_id,
|
||||
'reason': 'removed_or_disabled',
|
||||
'replacement_candidates': _replacement_candidates(before, target, source_field_id=field_id),
|
||||
})
|
||||
continue
|
||||
if before is not None and before.get('scope') != after.get('scope'):
|
||||
breaking.append({
|
||||
'field_id': field_id,
|
||||
'reason': 'scope_changed',
|
||||
'before': before.get('scope'),
|
||||
'after': after.get('scope'),
|
||||
'replacement_candidates': _replacement_candidates(before, target, source_field_id=field_id),
|
||||
})
|
||||
continue
|
||||
if before is not None:
|
||||
for key, reason in (
|
||||
('value_type', 'value_type_changed'),
|
||||
('collection_mode', 'collection_mode_changed'),
|
||||
('field_category', 'field_category_changed'),
|
||||
('required', 'required_changed'),
|
||||
('normalizer_key', 'normalizer_changed'),
|
||||
('comparator_key', 'comparator_changed'),
|
||||
('allowed_sources', 'allowed_sources_changed'),
|
||||
):
|
||||
if before.get(key) != after.get(key):
|
||||
candidates = _replacement_candidates(before, target, source_field_id=field_id)
|
||||
breaking.append({'field_id': field_id, 'reason': reason, 'before': before.get(key), 'after': after.get(key), 'replacement_candidates': candidates})
|
||||
break
|
||||
if breaking and breaking[-1]['field_id'] == field_id:
|
||||
continue
|
||||
for key in (
|
||||
'validator_keys', 'enum_options', 'evidence_policy', 'extraction_instruction',
|
||||
'relation_role', 'business_purpose', 'auto_create_key_field', 'minimum_confidence',
|
||||
):
|
||||
if before.get(key) != after.get(key):
|
||||
review.append({
|
||||
'field_id': field_id, 'reason': f'{key}_changed',
|
||||
'before': before.get(key), 'after': after.get(key),
|
||||
})
|
||||
old_code = str(before.get('field_code') or '') if before else ''
|
||||
new_code = str(after.get('field_code') or '')
|
||||
if old_code and old_code != new_code:
|
||||
renamed.append({'field_id': field_id, 'from': old_code, 'to': new_code})
|
||||
else:
|
||||
unchanged.append(field_id)
|
||||
return {
|
||||
'status': 'breaking' if breaking else ('review_required' if review else 'compatible'),
|
||||
'auto_upgradable': not breaking,
|
||||
'referenced_field_ids': sorted(referenced),
|
||||
'unchanged_field_ids': unchanged,
|
||||
'renamed_fields': renamed,
|
||||
'breaking_changes': breaking,
|
||||
'review_changes': review,
|
||||
}
|
||||
|
||||
|
||||
def remap_profile_field_codes(
|
||||
profile_definition: dict[str, Any],
|
||||
target_schema_definition: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""复制模板定义并按目标版本 field_id 更新 field_code,不修改已发布原定义。"""
|
||||
import copy
|
||||
|
||||
result = copy.deepcopy(profile_definition)
|
||||
target = _fields(target_schema_definition)
|
||||
for table in result.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for layout_key in ('header_layouts', 'line_layouts'):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
code_map: dict[str, str] = {}
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
field_id = str(field.get('field_id') or '')
|
||||
target_field = target.get(field_id)
|
||||
if not target_field:
|
||||
continue
|
||||
old_code = str(field.get('field_code') or '')
|
||||
field['field_code'] = target_field.get('field_code')
|
||||
code_map[old_code] = str(target_field.get('field_code') or '')
|
||||
for output in field.get('target_fields') or []:
|
||||
if isinstance(output, dict) and output.get('field_id') in target:
|
||||
output['field_code'] = target[str(output['field_id'])].get('field_code')
|
||||
for key in ('required_fields', 'allowed_empty_fields'):
|
||||
values = layout.get(key)
|
||||
if isinstance(values, list):
|
||||
layout[key] = [code_map.get(str(code), code) for code in values]
|
||||
return result
|
||||
@@ -17,7 +17,7 @@ _SCALAR_KEYS = (
|
||||
'relation_role', 'comparator_key', 'extraction_instruction', 'context_source',
|
||||
'sensitivity_level', 'dify_exposure_policy', 'available_for_customer_identity', 'sequence',
|
||||
)
|
||||
_SET_KEYS = ('aliases', 'validator_keys', 'enum_options')
|
||||
_SET_KEYS = ('aliases', 'validator_keys', 'enum_options', 'allowed_sources')
|
||||
_EVIDENCE_POLICY_KEYS = ('required', 'source_precedence', 'conflict_policy', 'allow_single_source')
|
||||
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ SOURCE_TYPES = {
|
||||
'attachment_table', 'attachment_text', 'email_body_table', 'email_body_text',
|
||||
'backend_table', 'dify_llm',
|
||||
}
|
||||
COORDINATE_SOURCES = {'pdf_coordinate', 'ocr_coordinate'}
|
||||
CONFLICT_POLICIES = {'block', 'review', 'prefer_attachment', 'prefer_email'}
|
||||
TYPE_NORMALIZERS = {
|
||||
'string': {'trim', 'uppercase_trim', 'lowercase_trim', 'reservation_id'},
|
||||
@@ -71,6 +72,7 @@ def catalog() -> dict[str, list[str] | dict[str, list[str]]]:
|
||||
'comparators': _admin_rules(COMPARATORS),
|
||||
'relation_roles': sorted(item for item in RELATION_ROLES if item),
|
||||
'source_types': sorted(SOURCE_TYPES),
|
||||
'coordinate_sources': sorted(COORDINATE_SOURCES),
|
||||
'conflict_policies': sorted(CONFLICT_POLICIES),
|
||||
'type_normalizers': {key: _admin_rules(value) for key, value in TYPE_NORMALIZERS.items()},
|
||||
'type_validators': {key: _admin_rules(value) for key, value in TYPE_VALIDATORS.items()},
|
||||
|
||||
@@ -28,6 +28,7 @@ from app.models import (
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaAuditEvent,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldDecision,
|
||||
@@ -39,6 +40,7 @@ from app.services.shipping_notice.context_fields.provider_registry import regist
|
||||
from app.services.shipping_notice.order_schema.registry import (
|
||||
COLLECTION_MODES,
|
||||
COMPARATORS,
|
||||
COORDINATE_SOURCES,
|
||||
CONFLICT_POLICIES,
|
||||
FIELD_SCOPES,
|
||||
FIELD_CATEGORIES,
|
||||
@@ -52,6 +54,7 @@ from app.services.shipping_notice.order_schema.registry import (
|
||||
VALIDATORS,
|
||||
catalog,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.compatibility import compare_profile_schema
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.order_schema.diff import compare_definitions
|
||||
|
||||
@@ -595,6 +598,53 @@ def get_version_usage(version_id: int, *, page: int = 1, page_size: int = 20) ->
|
||||
}
|
||||
|
||||
|
||||
def get_profile_impact(version_id: int) -> dict[str, Any]:
|
||||
"""评估目标 Schema 版本对已发布订单文档 Profile 的影响,不修改任何配置。"""
|
||||
schema = _require_schema()
|
||||
target = _require_version(version_id, schema=schema)
|
||||
profiles = ShippingOrderDocumentProfile.query.filter(
|
||||
ShippingOrderDocumentProfile.status.in_(['published', 'draft']),
|
||||
).order_by(
|
||||
ShippingOrderDocumentProfile.profile_code.asc(),
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
).all()
|
||||
items: list[dict[str, Any]] = []
|
||||
for profile in profiles:
|
||||
source = profile.schema_version
|
||||
compatibility = compare_profile_schema(
|
||||
profile.definition_json,
|
||||
source.definition_json if source is not None else None,
|
||||
target.definition_json,
|
||||
)
|
||||
items.append({
|
||||
'profile_id': profile.id,
|
||||
'profile_code': profile.profile_code,
|
||||
'profile_version': profile.version,
|
||||
'profile_status': profile.status,
|
||||
'source_schema_version_id': profile.schema_version_id,
|
||||
'source_schema_version': source.version if source is not None else None,
|
||||
'target_schema_version_id': target.id,
|
||||
'target_schema_version': target.version,
|
||||
'status': compatibility['status'],
|
||||
'auto_upgradable': compatibility['auto_upgradable'],
|
||||
'renamed_fields': compatibility['renamed_fields'],
|
||||
'breaking_changes': compatibility['breaking_changes'],
|
||||
'review_changes': compatibility['review_changes'],
|
||||
'referenced_field_ids': compatibility['referenced_field_ids'],
|
||||
})
|
||||
return {
|
||||
'target_version': _version_payload(target, include_definition=False),
|
||||
'summary': {
|
||||
'profile_count': len(items),
|
||||
'compatible_count': sum(1 for item in items if item['status'] == 'compatible'),
|
||||
'review_required_count': sum(1 for item in items if item['status'] == 'review_required'),
|
||||
'breaking_count': sum(1 for item in items if item['status'] == 'breaking' and item['profile_status'] == 'published'),
|
||||
'draft_impact_count': sum(1 for item in items if item['profile_status'] == 'draft' and item['status'] != 'compatible'),
|
||||
},
|
||||
'items': items,
|
||||
}
|
||||
|
||||
|
||||
def _field_identity_map(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
|
||||
"""从提取时锁定的 Schema 快照读取字段身份,避免后续目录重命名污染运行审计。"""
|
||||
return {
|
||||
@@ -936,12 +986,25 @@ def _field_runtime_references(field_id: str) -> list[str]:
|
||||
)
|
||||
if parsing_reference:
|
||||
references.append('inventory_parsing_profile')
|
||||
order_profile_reference = any(
|
||||
any(
|
||||
def profile_references_field(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""同时识别历史列规则和 v2 表头/明细字段区域,避免退役留下悬空模板。"""
|
||||
definition = profile.definition_json or {}
|
||||
legacy_reference = any(
|
||||
str(target.get('field_id') or '') == field_id
|
||||
for rule in (profile.definition_json or {}).get('column_rules', []) if isinstance(rule, dict)
|
||||
for rule in definition.get('column_rules', []) if isinstance(rule, dict)
|
||||
for target in rule.get('target_fields', []) if isinstance(target, dict)
|
||||
)
|
||||
coordinate_reference = any(
|
||||
str(field_region.get('field_id') or '') == field_id
|
||||
for table_region in definition.get('table_regions', []) if isinstance(table_region, dict)
|
||||
for layout in list(table_region.get('header_layouts') or []) + list(table_region.get('line_layouts') or [])
|
||||
if isinstance(layout, dict)
|
||||
for field_region in layout.get('field_regions', []) if isinstance(field_region, dict)
|
||||
)
|
||||
return legacy_reference or coordinate_reference
|
||||
|
||||
order_profile_reference = any(
|
||||
profile_references_field(profile)
|
||||
for profile in ShippingOrderDocumentProfile.query.filter(
|
||||
ShippingOrderDocumentProfile.status.in_(['draft', 'published'])
|
||||
).all()
|
||||
@@ -1050,6 +1113,17 @@ def _evidence_policy(value: Any) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _coordinate_sources(value: Any) -> list[str]:
|
||||
"""规范化字段允许的坐标来源;未显式配置时 v2 模板不可绑定该字段。"""
|
||||
sources = _string_list(value if value is not None else [], field='allowed_sources')
|
||||
if set(sources) - COORDINATE_SOURCES:
|
||||
raise ValidationError(
|
||||
'allowed_sources contains unsupported coordinate source',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
return sources
|
||||
|
||||
|
||||
def save_draft(
|
||||
version_id: int, data: dict[str, Any], *, actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
@@ -1164,6 +1238,7 @@ def save_draft(
|
||||
'validator_keys': validators,
|
||||
'enum_options': enum_options,
|
||||
'evidence_policy': _evidence_policy(raw.get('evidence_policy', {})),
|
||||
'allowed_sources': _coordinate_sources(raw.get('allowed_sources')),
|
||||
'relation_role': relation_role,
|
||||
'comparator_key': comparator,
|
||||
'extraction_instruction': str(raw.get('extraction_instruction') or '').strip() or None,
|
||||
@@ -1192,7 +1267,7 @@ def save_draft(
|
||||
|
||||
def publish(
|
||||
version_id: int, *, actor_id: int | None, expected_lock_version: int | None = None,
|
||||
request_id: str | None = None,
|
||||
request_id: str | None = None, confirm_profile_impact: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""发布指定锁版本的草稿,生成不可变 checksum 并退役上一发布版本。"""
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
@@ -1230,6 +1305,13 @@ def publish(
|
||||
code='SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED',
|
||||
details={'fields': referenced_omissions},
|
||||
)
|
||||
impact = get_profile_impact(version.id)
|
||||
if impact['summary']['breaking_count'] and not confirm_profile_impact:
|
||||
raise ConflictError(
|
||||
'Schema publish has breaking order document profile impacts; explicit confirmation is required',
|
||||
code='SHIPPING.ORDER_SCHEMA_PROFILE_IMPACT_CONFIRM_REQUIRED',
|
||||
details={'summary': impact['summary'], 'items': impact['items']},
|
||||
)
|
||||
encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
now = datetime.utcnow()
|
||||
previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first()
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""add order coordinate profile governance
|
||||
|
||||
Revision ID: 028e9f0a1b2c
|
||||
Revises: 027d8e9f0a1b
|
||||
Create Date: 2026-07-23 13:10:00.000000
|
||||
|
||||
用途:为订单坐标 Profile 增加可索引摘要、样本绑定和无敏感内容的操作审计。
|
||||
依赖:shipping_order_document_profiles、shipping_notice_documents、users。
|
||||
逻辑:完整坐标定义继续保留在 definition_json;本迁移只建立版本治理与追溯实体。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '028e9f0a1b2c'
|
||||
down_revision = '027d8e9f0a1b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""扩展 Profile 主表并建立样本绑定、操作审计和查询索引。"""
|
||||
with op.batch_alter_table('shipping_order_document_profiles') as batch:
|
||||
batch.add_column(sa.Column('template_mode', sa.String(length=32), server_default='coordinate_v2', nullable=False))
|
||||
batch.add_column(sa.Column('training_sample_count', sa.Integer(), server_default='0', nullable=False))
|
||||
batch.add_column(sa.Column('match_strategy_summary_json', sa.JSON(), server_default=sa.text("'{}'"), nullable=False))
|
||||
batch.create_index('ix_shipping_order_document_profiles_mode_status', ['template_mode', 'status'])
|
||||
op.create_table(
|
||||
'shipping_order_document_profile_samples',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=False),
|
||||
sa.Column('document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('table_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('sample_role', sa.String(length=16), server_default='annotation', nullable=False),
|
||||
sa.Column('created_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint("sample_role IN ('annotation', 'training', 'blind_test')", name='ck_shipping_order_document_profile_samples_role'),
|
||||
sa.ForeignKeyConstraint(['created_by_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('profile_id', 'document_id', 'table_id', 'sample_role', name='uq_shipping_order_document_profile_samples_source_role'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_document_profile_samples_document', 'shipping_order_document_profile_samples', ['document_id'])
|
||||
op.create_table(
|
||||
'shipping_order_document_profile_audits',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=True),
|
||||
sa.Column('document_id', sa.Integer(), nullable=True),
|
||||
sa.Column('event_type', sa.String(length=48), nullable=False),
|
||||
sa.Column('actor_id', sa.Integer(), nullable=True),
|
||||
sa.Column('detail_json', sa.JSON(), server_default=sa.text("'{}'"), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['actor_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id'], ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_document_profile_audits_profile_created', 'shipping_order_document_profile_audits', ['profile_id', 'created_at'])
|
||||
op.create_index('ix_shipping_order_document_profile_audits_document', 'shipping_order_document_profile_audits', ['document_id'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按依赖逆序移除审计/样本表和主表治理摘要。"""
|
||||
op.drop_index('ix_shipping_order_document_profile_audits_document', table_name='shipping_order_document_profile_audits')
|
||||
op.drop_index('ix_shipping_order_document_profile_audits_profile_created', table_name='shipping_order_document_profile_audits')
|
||||
op.drop_table('shipping_order_document_profile_audits')
|
||||
op.drop_index('ix_shipping_order_document_profile_samples_document', table_name='shipping_order_document_profile_samples')
|
||||
op.drop_table('shipping_order_document_profile_samples')
|
||||
with op.batch_alter_table('shipping_order_document_profiles') as batch:
|
||||
batch.drop_index('ix_shipping_order_document_profiles_mode_status')
|
||||
batch.drop_column('match_strategy_summary_json')
|
||||
batch.drop_column('training_sample_count')
|
||||
batch.drop_column('template_mode')
|
||||
@@ -58,7 +58,13 @@ def _parsing_profile() -> dict:
|
||||
state = order_schema_service.get_state()
|
||||
if state['schema'] is None:
|
||||
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
|
||||
fields = {item['field_code']: item for item in order_schema_service.get_state()['fields']}
|
||||
# 解析 Profile 仅需要这两个订单行匹配键;不能把当前目录的所有字段
|
||||
# 带进最小 Schema,以免其类型专用 normalizer 影响本服务测试。
|
||||
fields = {
|
||||
item['field_code']: item
|
||||
for item in order_schema_service.get_state()['fields']
|
||||
if item['field_code'] in {'part_number', 'reservation_id'}
|
||||
}
|
||||
for code in ('part_number', 'reservation_id'):
|
||||
if code not in fields:
|
||||
fields[code] = order_schema_service.save_field(
|
||||
@@ -68,7 +74,8 @@ def _parsing_profile() -> dict:
|
||||
schema_draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
saved_schema = order_schema_service.save_draft(schema_draft['id'], {'fields': [{
|
||||
'field_id': field['id'], 'display_name': code, 'required': True, 'aliases': [],
|
||||
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
|
||||
'normalizer_key': 'decimal' if field['value_type'] == 'decimal' else 'trim',
|
||||
'validator_keys': [], 'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
@@ -491,8 +498,8 @@ def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED'
|
||||
|
||||
|
||||
def test_publish_rule_rejects_missing_or_disabled_source(app):
|
||||
"""发布规则只能引用启用库存源,避免运行期落入无法确认的伪候选。"""
|
||||
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
|
||||
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
|
||||
@@ -502,15 +509,21 @@ def test_publish_rule_rejects_missing_or_disabled_source(app):
|
||||
shipping_inventory_service.save_source(disabled_payload, actor_id=None)
|
||||
|
||||
reservation_field_id = _published_route_field_id()
|
||||
for index, code in enumerate(('MISSING_SOURCE', 'DISABLED_ROUTE_SOURCE'), start=1):
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': f'INVALID_SOURCE_{index}', 'rule_name': 'Invalid source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [code]},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': str(index)}],
|
||||
}, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
|
||||
missing_rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'MISSING_SOURCE', 'rule_name': 'Missing source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['MISSING_SOURCE']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.publish_rule(missing_rule['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
|
||||
|
||||
disabled_rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'DISABLED_SOURCE', 'rule_name': 'Disabled source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DISABLED_ROUTE_SOURCE']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '2'}],
|
||||
}, actor_id=None)
|
||||
assert shipping_inventory_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
|
||||
|
||||
valid_rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line',
|
||||
|
||||
@@ -39,7 +39,7 @@ from app.services.admin.agent_service import update_agent_permissions
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.admin.agent_service import list_agents
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
|
||||
_cross_page_anchor_matches, build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
|
||||
parse_order_extraction_workflow_result, validate_unit_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
@@ -51,6 +51,31 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_cross_page_coordinate_continuation_requires_frozen_relation_anchor_and_region():
|
||||
"""续页锚点须在声明区域命中;整页出现相同文本不足以授权跨页合并。"""
|
||||
profile = {'definition': {'document_match': {'required_anchors': [{
|
||||
'anchor_id': 'continued', 'text': 'CONTINUED', 'match_mode': 'exact',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .5, 'y1': .5},
|
||||
}]}}}
|
||||
layout = {'coordinate_evidence': {
|
||||
'tables': {'page-two': [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
|
||||
for index, char in enumerate('CONTINUED')
|
||||
]},
|
||||
'pages': {'2': {'width': 200, 'height': 200}},
|
||||
}}
|
||||
assert _cross_page_anchor_matches(
|
||||
raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout,
|
||||
anchor_ids=['continued'],
|
||||
) is True
|
||||
|
||||
profile['definition']['document_match']['required_anchors'][0]['region'] = {'x0': .5, 'y0': .5, 'x1': 1, 'y1': 1}
|
||||
assert _cross_page_anchor_matches(
|
||||
raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout,
|
||||
anchor_ids=['continued'],
|
||||
) is False
|
||||
|
||||
|
||||
def test_binding_rejects_non_internal_or_non_workflow_provider(app):
|
||||
"""订单抽取 Provider 必须是启用的 internal Dify Workflow,不能绑定普通 Chatflow。"""
|
||||
with app.app_context():
|
||||
@@ -757,6 +782,160 @@ def test_approved_profile_builds_order_from_its_own_parsed_rows(app):
|
||||
assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30
|
||||
|
||||
|
||||
def test_coordinate_v2_profile_builds_from_frozen_coordinates_without_html(app):
|
||||
"""v2 运行只消费冻结 bbox/字符证据;MinerU HTML 缺失也不得回退为固定列解析。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-V2')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
version.definition_json = {'fields': [
|
||||
{
|
||||
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal',
|
||||
'enabled': True, 'required': True, 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
{
|
||||
'field_id': 'uom-id', 'field_code': 'uom', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
]}
|
||||
|
||||
def glyphs() -> list[dict]:
|
||||
values = []
|
||||
for text, x0 in [('00010', 10), ('PART-A', 90), ('3 EA', 210)]:
|
||||
for offset, char in enumerate(text):
|
||||
values.append({'text': char, 'bbox': {
|
||||
'x0': x0 + offset * 4, 'y0': 20, 'x1': x0 + offset * 4 + 3, 'y1': 30,
|
||||
}})
|
||||
return values
|
||||
|
||||
definition = {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [{
|
||||
'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
||||
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .3, 'y0': 0, 'x1': .7, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'extractor_key': 'quantity_uom', 'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}, {'field_id': 'uom-id', 'field_code': 'uom'}], 'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number', 'qty', 'uom'], 'allowed_empty_fields': [],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='COORDINATE_V2', display_name='Coordinate v2', version=1, status='published',
|
||||
schema_version_id=version.id, structure_fingerprint='c' * 64, checksum='d' * 64,
|
||||
definition_json=definition, published_at=datetime.utcnow(),
|
||||
)
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'coordinate-only', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 300, 'y1': 60}}],
|
||||
'coordinate_evidence': {
|
||||
'tables': {'coordinate-only': glyphs()},
|
||||
'pages': {'1': {'width': 300, 'height': 60}},
|
||||
},
|
||||
})
|
||||
db.session.add(profile)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True
|
||||
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_build_approved_profile_order,
|
||||
_profile_table_candidates,
|
||||
build_deterministic_unit_orders,
|
||||
)
|
||||
|
||||
candidates = _profile_table_candidates(run, unit=unit)
|
||||
assert candidates['blocking'] is False, candidates
|
||||
assert candidates['tables'] and candidates['tables'][0]['auto_create_approved'] is True, candidates
|
||||
direct = _build_approved_profile_order(
|
||||
unit=unit, intake=run.input_snapshot_json['intakes'][0],
|
||||
schema=run.input_snapshot_json['schema']['extraction_contract'],
|
||||
definition=run.input_snapshot_json['schema']['definition'], table=candidates['tables'][0],
|
||||
)
|
||||
assert direct is not None, candidates
|
||||
orders = build_deterministic_unit_orders(run, unit=unit)
|
||||
assert orders is not None
|
||||
fields = {field['field_id']: field['observations'][0]['value'] for field in orders[0]['lines'][0]['fields']}
|
||||
assert fields == {'line-id': '00010', 'part-id': 'PART-A', 'qty-id': 3, 'uom-id': 'EA'}
|
||||
|
||||
|
||||
def test_coordinate_v2_profile_uses_page_relative_regions_not_table_bbox(app):
|
||||
"""画布保存整页相对区域;运行时不得再按 MinerU 表格 bbox 二次缩放。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-PAGE-SPACE')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
version.definition_json = {'fields': [
|
||||
{
|
||||
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'required': False, 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
]}
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='COORDINATE_PAGE_SPACE', display_name='Coordinate page space', version=1, status='published',
|
||||
schema_version_id=version.id, structure_fingerprint='e' * 64, checksum='f' * 64,
|
||||
definition_json={
|
||||
'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []},
|
||||
'table_regions': [{
|
||||
'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
||||
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
# This real canvas region is page-relative (x=20..80 on a 200pt page),
|
||||
# while MinerU's table bbox begins at x=50 and must not offset it again.
|
||||
'region': {'x0': .1, 'y0': .4, 'x1': .4, 'y1': .6},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': .1, 'y0': .4, 'x1': .2, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .2, 'y0': .4, 'x1': .4, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']},
|
||||
], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number'], 'allowed_empty_fields': [],
|
||||
}],
|
||||
}],
|
||||
}, published_at=datetime.utcnow(),
|
||||
)
|
||||
glyphs = []
|
||||
for text, x0 in [('00010', 22), ('PART-PAGE', 45)]:
|
||||
for offset, char in enumerate(text):
|
||||
glyphs.append({'text': char, 'bbox': {'x0': x0 + offset * 4, 'y0': 90, 'x1': x0 + offset * 4 + 3, 'y1': 100}})
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'offset-table', 'page_no': 1, 'bbox': {'x0': 50, 'y0': 70, 'x1': 160, 'y1': 140}}],
|
||||
'coordinate_evidence': {'tables': {'offset-table': glyphs}, 'pages': {'1': {'width': 200, 'height': 200}}},
|
||||
})
|
||||
db.session.add(profile)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no])
|
||||
unit = run.extraction_plan.units[0]
|
||||
run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
|
||||
orders = build_deterministic_unit_orders(run, unit=unit)
|
||||
assert orders is not None
|
||||
values = {
|
||||
field['field_id']: field['observations'][0]['value']
|
||||
for field in orders[0]['lines'][0]['fields']
|
||||
}
|
||||
assert values['part-id'] == 'PART-PAGE'
|
||||
|
||||
|
||||
def test_plain_text_complete_table_still_uses_provider(app):
|
||||
"""纯文本表格即使字段齐全也不能零 Provider,防止 L7 恢复猜列运行路径。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -582,6 +582,263 @@ def test_summarize_inventory_batch_results_empty():
|
||||
}
|
||||
|
||||
|
||||
def test_real_upload_requires_explicit_enablement(monkeypatch, tmp_path):
|
||||
"""未显式开启上传浏览器自动化时,不得打开货代页面或提交文件。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false")
|
||||
|
||||
with pytest.raises(RuntimeError, match="upload RPA is disabled"):
|
||||
worker._upload_shipment_with_browser(workbook)
|
||||
|
||||
|
||||
def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch, tmp_path):
|
||||
"""真实上传只能在页面成功标识可见后回传可选货代回执。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL", "https://freight.example/upload")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR", "#file")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR", "#submit")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR", "#success")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR", "#receipt")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
def __init__(self, selector: str):
|
||||
self.selector = selector
|
||||
self.first = self
|
||||
|
||||
def set_input_files(self, value: str, **_kwargs) -> None:
|
||||
events.append(("file", value))
|
||||
|
||||
def click(self, **_kwargs) -> None:
|
||||
events.append(("submit", self.selector))
|
||||
|
||||
def wait_for(self, **_kwargs) -> None:
|
||||
events.append(("success", self.selector))
|
||||
|
||||
def text_content(self, **_kwargs) -> str:
|
||||
return "FREIGHT-REF-001"
|
||||
|
||||
class _Page:
|
||||
def goto(self, url: str, **_kwargs) -> None:
|
||||
events.append(("goto", url))
|
||||
|
||||
def locator(self, selector: str) -> _Locator:
|
||||
return _Locator(selector)
|
||||
|
||||
class _Context:
|
||||
def close(self) -> None:
|
||||
events.append(("context_close", None))
|
||||
|
||||
class _Playwright:
|
||||
def stop(self) -> None:
|
||||
events.append(("playwright_stop", None))
|
||||
|
||||
runtime_profile = tmp_path / "profile"
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
|
||||
assert worker._upload_shipment_with_browser(workbook) == "FREIGHT-REF-001"
|
||||
assert events[:4] == [
|
||||
("goto", "https://freight.example/upload"),
|
||||
("file", str(workbook)),
|
||||
("submit", "#submit"),
|
||||
("success", "#success"),
|
||||
]
|
||||
|
||||
|
||||
def test_dsv_upload_navigates_from_my_applications_before_setting_file(monkeypatch, tmp_path):
|
||||
"""DSV 上传必须复用登录态,并优先使用截图确认的 My Applications 入口。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
def __init__(self, selector: str):
|
||||
self.selector = selector
|
||||
self.first = self
|
||||
|
||||
def wait_for(self, **_kwargs) -> None:
|
||||
events.append(("wait", self.selector))
|
||||
|
||||
def click(self, **_kwargs) -> None:
|
||||
events.append(("click", self.selector))
|
||||
|
||||
def set_input_files(self, _value: str, **_kwargs) -> None:
|
||||
events.append(("file", self.selector))
|
||||
|
||||
class _Page:
|
||||
def locator(self, selector: str) -> _Locator:
|
||||
return _Locator(selector)
|
||||
|
||||
def get_by_text(self, text: str, **_kwargs) -> _Locator:
|
||||
return _Locator(text)
|
||||
|
||||
class _Context:
|
||||
def close(self) -> None:
|
||||
events.append(("context_close", None))
|
||||
|
||||
class _Playwright:
|
||||
def stop(self) -> None:
|
||||
events.append(("playwright_stop", None))
|
||||
|
||||
runtime_profile = tmp_path / "profile"
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", lambda _page, filename: f"REF-{filename}")
|
||||
|
||||
assert worker._upload_shipment_with_browser(
|
||||
workbook, connector_type="dbs", dsv_entry_url="https://dsv.example/portal"
|
||||
) == "REF-shipment.xlsx"
|
||||
|
||||
assert events[0] == ("session", "https://dsv.example/portal")
|
||||
assert any(event == ("click", ":has-text(\"My Applications\") a:has-text('Upload Tool')") for event in events)
|
||||
assert ("file", "#file2") in events
|
||||
assert ("click", 'button.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
|
||||
"""DSV History 缺绿色状态或 Reference # 时,不得把文件提交误报为上传成功。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
class _Locator:
|
||||
first = None
|
||||
|
||||
def __init__(self):
|
||||
self.first = self
|
||||
|
||||
def click(self, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
class _Page:
|
||||
def get_by_text(self, _text: str, **_kwargs) -> _Locator:
|
||||
return _Locator()
|
||||
|
||||
def evaluate(self, _script: str, _arg: dict) -> dict:
|
||||
return {"found": True, "succeeded": False, "reference": "556833"}
|
||||
|
||||
monkeypatch.setattr(worker.time, "sleep", lambda _seconds: None)
|
||||
clock = {"value": 0.0}
|
||||
|
||||
def monotonic() -> float:
|
||||
clock["value"] += 2.0
|
||||
return clock["value"]
|
||||
|
||||
monkeypatch.setattr(worker.time, "monotonic", monotonic)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
|
||||
|
||||
with pytest.raises(RuntimeError, match="did not confirm a green success status"):
|
||||
worker._wait_for_dsv_upload_history_receipt(_Page(), "shipment.xlsx")
|
||||
|
||||
|
||||
def test_dsv_upload_history_returns_reference_only_for_confirmed_success(monkeypatch):
|
||||
"""History 的绿色同名行与非空 Reference # 必须原样作为 DSV 上传回执返回。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
class _Locator:
|
||||
first = None
|
||||
|
||||
def __init__(self):
|
||||
self.first = self
|
||||
|
||||
def click(self, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
class _Page:
|
||||
def get_by_text(self, _text: str, **_kwargs) -> _Locator:
|
||||
return _Locator()
|
||||
|
||||
def evaluate(self, _script: str, _arg: dict) -> dict:
|
||||
return {"found": True, "succeeded": True, "reference": "556833"}
|
||||
|
||||
assert worker._wait_for_dsv_upload_history_receipt(_Page(), "DUBH26072304.xlsx") == "556833"
|
||||
|
||||
|
||||
def test_dsv_upload_falls_back_to_apps_menu(monkeypatch):
|
||||
"""首页入口缺失时,DSV 仅可退回已确认的 Apps > Upload Tool 路径。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
events: list[str] = []
|
||||
|
||||
class _Locator:
|
||||
def __init__(self, selector: str):
|
||||
self.selector = selector
|
||||
self.first = self
|
||||
|
||||
def wait_for(self, **_kwargs) -> None:
|
||||
if "My Applications" in self.selector:
|
||||
raise RuntimeError("homepage tile missing")
|
||||
|
||||
def click(self, **_kwargs) -> None:
|
||||
events.append(self.selector)
|
||||
|
||||
class _Page:
|
||||
def locator(self, selector: str) -> _Locator:
|
||||
return _Locator(selector)
|
||||
|
||||
def get_by_text(self, _text: str, **_kwargs) -> _Locator:
|
||||
return _Locator("WMS Upload Tool")
|
||||
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda *_args: events.append("session"))
|
||||
worker._navigate_dsv_to_upload_tool(_Page(), "https://dsv.example/portal")
|
||||
|
||||
assert events[0] == "session"
|
||||
assert "nav a:has-text('Apps')" in events
|
||||
assert "a:has-text('Upload Tool')" in events
|
||||
|
||||
|
||||
def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
|
||||
"""浏览器上传未获成功证据时必须失败回调,不能遗留无限等待的 trigger。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "upload_triggers"
|
||||
trigger_dir.mkdir()
|
||||
trigger_path = trigger_dir / "upload_SN-UPLOAD-FAIL.json"
|
||||
queue_file = tmp_path / "shipment.xlsx"
|
||||
queue_file.write_bytes(b"test")
|
||||
trigger_path.write_text(json.dumps({
|
||||
"task_no": "SN-UPLOAD-FAIL", "file_path": str(queue_file), "attempt_id": 8, "callback_id": "rpa:8",
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda _path: (_ for _ in ()).throw(RuntimeError("success marker missing")))
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
|
||||
|
||||
assert callbacks == [("/api/shipping-notice/rpa/upload-complete", {
|
||||
"task_no": "SN-UPLOAD-FAIL", "attempt_id": 8, "callback_id": "rpa:8", "success": False,
|
||||
"error_message": "success marker missing",
|
||||
})]
|
||||
assert (trigger_dir / "processed" / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
|
||||
"""空上传路径必须直接失败回调,禁止把当前目录传给浏览器文件控件。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "upload_triggers"
|
||||
trigger_dir.mkdir()
|
||||
trigger_path = trigger_dir / "upload_SN-UPLOAD-EMPTY.json"
|
||||
trigger_path.write_text(json.dumps({
|
||||
"task_no": "SN-UPLOAD-EMPTY", "attempt_id": 9, "callback_id": "rpa:9",
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
|
||||
|
||||
assert callbacks[0][1]["success"] is False
|
||||
assert callbacks[0][1]["error_message"] == "queue file missing: <empty>"
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_skipped_and_failed():
|
||||
"""仅有 skipped+failed 时 legacy success 为 true(skipped 算已处理)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -9,7 +9,10 @@ from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
reconstruct_coordinate_profile_rows,
|
||||
reconstruct_table_from_positioned_text,
|
||||
suggest_header_layouts,
|
||||
suggest_header_regions,
|
||||
suggest_multi_subrow_layouts,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
@@ -22,6 +25,11 @@ from app.services.shipping_notice.document_layout.order_profile import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_build_approved_profile_order,
|
||||
_validate_table_header_outputs,
|
||||
)
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
def _glyphs(*rows: list[tuple[str, float]]) -> list[dict]:
|
||||
@@ -50,6 +58,615 @@ def _reconstruct(characters: list[dict]):
|
||||
)
|
||||
|
||||
|
||||
def test_header_suggestions_only_return_unique_schema_aliases():
|
||||
"""表头建议只能使用当前 Schema 的唯一精确别名,位置相近或歧义均保持未映射。"""
|
||||
suggestions = suggest_header_layouts(
|
||||
characters=_glyphs([('Quantity', 20), ('Part No.', 120)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
header_layouts=[{'layout_id': 'header_one', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .2}, 'field_regions': [
|
||||
{'region': {'x0': 0, 'y0': 0, 'x1': .45, 'y1': 1}},
|
||||
{'region': {'x0': .45, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
schema_fields=[
|
||||
{'field_code': 'qty', 'display_name': 'Quantity', 'aliases': ['Qty']},
|
||||
{'field_code': 'part_number', 'display_name': 'Part No.', 'aliases': []},
|
||||
{'field_code': 'customer_part_number', 'display_name': 'Part No.', 'aliases': []},
|
||||
],
|
||||
)
|
||||
|
||||
# Quantity 唯一命中;Part No. 同时属于两个 Schema 字段,因此不得猜测归属。
|
||||
assert suggestions[0].fields[0].model_dump() == {'field_code': 'qty', 'text': 'Quantity', 'confidence': 'exact_alias'}
|
||||
assert suggestions[0].fields[1].model_dump()['field_code'] is None
|
||||
|
||||
|
||||
def test_unbound_header_region_can_suggest_a_schema_field():
|
||||
"""未绑定表头框必须直接读取自身区域,并仅返回唯一 Schema 别名供管理员确认。"""
|
||||
suggestions = suggest_header_layouts(
|
||||
characters=_glyphs([('DELI. DATE', 120)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
header_layouts=[{
|
||||
'layout_id': 'delivery_header',
|
||||
'region': {'x0': .55, 'y0': 0, 'x1': 1, 'y1': .4},
|
||||
'field_regions': [],
|
||||
}],
|
||||
schema_fields=[{
|
||||
'field_code': 'requested_receipt_date',
|
||||
'display_name': 'Delivery Date',
|
||||
'aliases': ['DELI. DATE'],
|
||||
}],
|
||||
)
|
||||
|
||||
# 断言无需预先创建表头子字段框,也能形成待确认的精确别名建议。
|
||||
assert suggestions[0].fields[0].text == 'DELI. DATE'
|
||||
assert suggestions[0].fields[0].field_code == 'requested_receipt_date'
|
||||
assert suggestions[0].fields[0].confidence == 'exact_alias'
|
||||
|
||||
|
||||
def test_auto_header_regions_stop_before_first_detail_row():
|
||||
"""自动标记只框选首条明细前的独立表头,不能把业务数据当成表头。"""
|
||||
suggestions = suggest_header_regions(
|
||||
characters=_glyphs(
|
||||
[('Item', 10), ('Material', 65), ('Quantity', 150)],
|
||||
[('Description', 10), ('Delivery Date', 120)],
|
||||
[('00010', 10), ('PART-A', 65), ('3', 160)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
)
|
||||
|
||||
assert [item.text for item in suggestions] == [
|
||||
'Item Material Quantity', 'Description Delivery Date',
|
||||
]
|
||||
assert suggestions[0].region.y1 < suggestions[1].region.y0
|
||||
|
||||
|
||||
def test_auto_header_regions_recognize_compact_pdf_header_words():
|
||||
"""PDF 丢失表头词间空格时,仍应识别独立表头行。"""
|
||||
suggestions = suggest_header_regions(
|
||||
characters=_glyphs(
|
||||
[('ITEMNO', 10), ('MATERIALNO', 65), ('UNITPRICE', 140)],
|
||||
[('00010', 10), ('PART-A', 65), ('3.00', 150)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
)
|
||||
|
||||
assert len(suggestions) == 1
|
||||
assert suggestions[0].text == 'ITEMNO MATERIALNO UNITPRICE'
|
||||
|
||||
|
||||
def test_subrow_suggestion_uses_one_record_for_vertical_samples():
|
||||
"""多条明细只能增强列边界,不能把样例子行纵向范围拉伸到后续记录。"""
|
||||
suggestions = suggest_multi_subrow_layouts(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('2026-08-01', 120)],
|
||||
[('00020', 10), ('PART-B', 65)],
|
||||
[('2026-08-02', 120)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
)
|
||||
|
||||
assert len(suggestions) == 2
|
||||
assert suggestions[0].y1 < suggestions[1].y0
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
|
||||
"""v2 主行必须有行号,续行按 row_offset 合并,合计或额外文本不得混入明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-A', 65), ('5', 160)],
|
||||
[('Delivery', 65), ('2026-08-01', 150)],
|
||||
[('TOTAL AMOUNT', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'continuation', 'row_offset': 1, 'field_regions': [
|
||||
{'field_code': 'required_date', 'region': {'x0': .65, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
],
|
||||
)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
|
||||
|
||||
|
||||
def test_coordinate_profile_row_layout_repeats_across_the_table():
|
||||
"""物理行框是可重复版式样例;同一字段横向边界必须读取后续明细而非只命中标注时的绝对 Y。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('00020', 10), ('PART-B', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
table_region={'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .25, 'y1': .35}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': .15, 'x1': .75, 'y1': .35}},
|
||||
]}],
|
||||
)
|
||||
|
||||
# 断言样例框的 X 版式重复应用到第二条明细,Y 只用于表达该物理子行的相对顺序。
|
||||
assert [row.fields for row in rows] == [
|
||||
{'line_no': '00010', 'part_number': 'PART-A'},
|
||||
{'line_no': '00020', 'part_number': 'PART-B'},
|
||||
]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_apply_registered_composite_extractors_atomically():
|
||||
"""qty/uom、金额/币种和单价/币种必须成对拆分;格式无效时不写入任何半截字段。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('3 EA', 65), ('USD 10.50', 115), ('12.00 USD', 165)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'extractor_key': 'direct', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .2, 'y0': 0, 'x1': .5, 'y1': 1}},
|
||||
{'field_code': 'line_amount_before_tax', 'extractor_key': 'amount_currency', 'region': {'x0': .5, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'unit_price', 'extractor_key': 'price_currency', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert rows[0].fields == {
|
||||
'line_no': '00010', 'qty': '3', 'uom': 'EA', 'line_amount_before_tax': '10.50',
|
||||
'currency': 'USD', 'unit_price': '12.00',
|
||||
}
|
||||
|
||||
invalid = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('not-a-quantity', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert invalid[0].fields == {'line_no': '00010'}
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_marks_conflicting_composite_values_for_review():
|
||||
"""同一逻辑明细中的复合字段冲突必须留痕,不能以后到值静默覆盖前值。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('3 EA', 65)], [('4 PCS', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 80},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'continuation', 'row_offset': 1, 'field_regions': [
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
],
|
||||
)
|
||||
assert rows[0].fields['qty'] == '3'
|
||||
assert 'coordinate_profile_composite_conflict:qty' in rows[0].issues
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_treat_vertical_regions_as_repeatable_layout_samples():
|
||||
"""物理行纵向框表达子行顺序而非绝对页坐标,模板才能重复读取后续明细。"""
|
||||
base_layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'continuation', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
|
||||
{'field_code': 'required_date', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
]
|
||||
characters = _glyphs([('00010', 10), ('PART-A', 65)], [('2026-08-01', 100)])
|
||||
matched = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=base_layouts,
|
||||
)
|
||||
assert matched[0].fields['required_date'] == '2026-08-01'
|
||||
|
||||
base_layouts[1]['region']['y0'] = .6
|
||||
base_layouts[1]['region']['y1'] = .8
|
||||
repeated = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=base_layouts,
|
||||
)
|
||||
# 断言只要 row_offset 顺序有效,示例框移动不会把模板退化为只能识别一条绝对 Y 行。
|
||||
assert repeated[0].fields['required_date'] == '2026-08-01'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_reject_swapped_physical_region_order():
|
||||
"""字段绑定不变但物理行区域错序时必须阻断,不能仅因 y 顺序相邻而合并。"""
|
||||
characters = _glyphs(
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('2026-08-01', 100)],
|
||||
[('By Truck', 100)],
|
||||
)
|
||||
layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'delivery', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
|
||||
{'field_code': 'required_date', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'shipping', 'row_offset': 2, 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': .75}, 'field_regions': [
|
||||
{'field_code': 'shipway', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
]
|
||||
correct = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=layouts,
|
||||
)
|
||||
assert correct[0].fields['shipway'] == 'By Truck'
|
||||
|
||||
# Retain each layout's fields but assign the delivery layout to the shipping band.
|
||||
layouts[1]['region'], layouts[2]['region'] = layouts[2]['region'], layouts[1]['region']
|
||||
rejected = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=layouts,
|
||||
)
|
||||
assert rejected[0].fields == {'line_no': '00010', 'part_number': 'PART-A'}
|
||||
assert rejected[0].issues == ['coordinate_profile_layout_region_mismatch']
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_restore_pdf_visual_spaces():
|
||||
"""原生 PDF 未持久化空格时按字符间距恢复字段原文,供受控解析器与证据复核使用。"""
|
||||
characters = _glyphs([('00010', 10), ('By', 65), ('Truck', 81)])
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'shipway', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert rows[0].fields['shipway'] == 'By Truck'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_discard_the_prior_record_for_explicit_deleted_marker():
|
||||
"""`** Item deleted **` 只能废弃前一条已启动明细,不能作为下一条或独立明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-DELETED', 65)],
|
||||
[('** Item deleted **', 65)],
|
||||
[('00020', 10), ('PART-KEEP', 65)],
|
||||
[('TOTAL AMOUNT', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert [row.fields for row in rows] == [{'line_no': '00020', 'part_number': 'PART-KEEP'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schema_fields():
|
||||
"""脱敏回放 F9A1:四条物理行只合并为一条,并只读取已绑定的标准字段。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('541-000175-007', 50), ('B3-A08AR10000018-A7', 190)],
|
||||
[('AWS', 45), ('48.5U', 65), ('RACK', 92), ('175-007', 118), ('WELLTRUST', 150),
|
||||
('3.000', 195), ('PCS', 220), ('2026/05/05', 245)],
|
||||
[('EXW', 45), ('SGSIN', 62), ('DBS', 86), ('1,645.11000', 200), ('4,935.33', 250)],
|
||||
[('R2_SA;HF_SA;EF_SA', 45), ('ASG_S-ENCWIW260412386643', 120), ('@', 240), ('3000092530', 250)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .3}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .12, 'y1': 1}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .12, 'y0': 0, 'x1': .58, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .58, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'quantity_delivery', 'row_offset': 1, 'region': {'x0': 0, 'y0': .3, 'x1': 1, 'y1': .44}, 'field_regions': [
|
||||
{'field_code': 'qty', 'region': {'x0': .62, 'y0': 0, 'x1': .71, 'y1': 1}},
|
||||
{'field_code': 'uom', 'region': {'x0': .71, 'y0': 0, 'x1': .78, 'y1': 1}},
|
||||
{'field_code': 'required_date', 'region': {'x0': .78, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'terms_pricing', 'row_offset': 2, 'region': {'x0': 0, 'y0': .44, 'x1': 1, 'y1': .58}, 'field_regions': [
|
||||
{'field_code': 'incoterm', 'region': {'x0': .12, 'y0': 0, 'x1': .45, 'y1': 1}},
|
||||
{'field_code': 'unit_price', 'region': {'x0': .62, 'y0': 0, 'x1': .82, 'y1': 1}},
|
||||
{'field_code': 'line_amount_before_tax', 'region': {'x0': .82, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'reservation', 'row_offset': 3, 'region': {'x0': 0, 'y0': .58, 'x1': 1, 'y1': .75}, 'field_regions': [
|
||||
{'field_code': 'reservation_id', 'region': {'x0': .76, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
],
|
||||
)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0].source_row_indices == [0, 1, 2, 3]
|
||||
assert rows[0].fields == {
|
||||
'line_no': '10', 'customer_part_number': '541-000175-007', 'part_number': 'B3-A08AR10000018-A7',
|
||||
'qty': '3.000', 'uom': 'PCS', 'required_date': '2026/05/05', 'incoterm': 'EXW SGSIN DBS',
|
||||
'unit_price': '1,645.11000', 'line_amount_before_tax': '4,935.33', 'reservation_id': '@ 3000092530',
|
||||
}
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line():
|
||||
"""一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('B3-A08AR10000018-A7', 120)],
|
||||
[('3.000', 124), ('PCS', 158), ('2026/05/05', 190)],
|
||||
[('1,645.11000', 124), ('4,935.33', 220)],
|
||||
[('20', 10), ('B3-A08AR10000027-A9', 120)],
|
||||
[('8.000', 124), ('EA', 158), ('2026/06/01', 190)],
|
||||
[('2,100.00000', 124), ('16,800.00', 220)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 120},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail',
|
||||
'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .48},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .12, 'y1': .25}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .15, 'x1': 1, 'y1': .25}},
|
||||
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .26, 'x1': .52, 'y1': .36}},
|
||||
{'field_code': 'uom', 'region': {'x0': .52, 'y0': .26, 'x1': .63, 'y1': .36}},
|
||||
{'field_code': 'requested_receipt_date', 'region': {'x0': .63, 'y0': .26, 'x1': 1, 'y1': .36}},
|
||||
{'field_code': 'unit_price', 'region': {'x0': .38, 'y0': .37, 'x1': .72, 'y1': .48}},
|
||||
{'field_code': 'line_amount_before_tax', 'region': {'x0': .72, 'y0': .37, 'x1': 1, 'y1': .48}},
|
||||
],
|
||||
}],
|
||||
)
|
||||
|
||||
# 数量与单位不得从同一横向范围内、但位于首视觉行的内部料号尾数读取。
|
||||
assert [row.fields for row in rows] == [
|
||||
{
|
||||
'line_no': '10', 'part_number': 'B3-A08AR10000018-A7', 'qty': '3.000', 'uom': 'PCS',
|
||||
'requested_receipt_date': '2026/05/05', 'unit_price': '1,645.11000',
|
||||
'line_amount_before_tax': '4,935.33',
|
||||
},
|
||||
{
|
||||
'line_no': '20', 'part_number': 'B3-A08AR10000027-A9', 'qty': '8.000', 'uom': 'EA',
|
||||
'requested_receipt_date': '2026/06/01', 'unit_price': '2,100.00000',
|
||||
'line_amount_before_tax': '16,800.00',
|
||||
},
|
||||
]
|
||||
|
||||
deleted = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('B3-A08AR10000018-A7', 120)],
|
||||
[('3.000', 124), ('PCS', 158)],
|
||||
[('** Item deleted **', 30)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 80},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .65},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .12, 'y1': .35}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .2, 'x1': 1, 'y1': .35}},
|
||||
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .36, 'x1': .52, 'y1': .5}},
|
||||
],
|
||||
}],
|
||||
)
|
||||
assert deleted == []
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_replay_sample_visual_band_offsets_despite_parent_whitespace():
|
||||
"""父物理行含底部留白时应复用样例视觉子行偏移,不能按高度缩放把字段投到行间。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('6Y70B2501901', 55), ('0', 205), ('EA', 225)],
|
||||
[('D4-A08AR12000002', 55), ('06/22/2026', 170)],
|
||||
[('RoHS2', 20), ('EXW AWS HUB', 105)],
|
||||
[], [], [],
|
||||
[('00020', 10), ('6Y70B2501901', 55), ('30', 205), ('EA', 225)],
|
||||
[('D4-A08AR12000002', 55), ('06/29/2026', 170)],
|
||||
[('RoHS2', 20), ('EXW AWS HUB', 105)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 160},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0,
|
||||
# 样例父框包含第三子行后的留白;线性压缩会让第二子行字段落入空白。
|
||||
'region': {'x0': 0, 'y0': .05, 'x1': 1, 'y1': .53},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .12, 'x1': .2, 'y1': .19}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .12, 'x1': .64, 'y1': .19}},
|
||||
{'field_code': 'qty', 'region': {'x0': .76, 'y0': .12, 'x1': .86, 'y1': .19}},
|
||||
{'field_code': 'uom', 'region': {'x0': .86, 'y0': .12, 'x1': 1, 'y1': .19}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .21, 'x1': .64, 'y1': .28}},
|
||||
{'field_code': 'requested_receipt_date', 'region': {'x0': .64, 'y0': .21, 'x1': 1, 'y1': .28}},
|
||||
],
|
||||
}],
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [
|
||||
{
|
||||
'line_no': '00010', 'customer_part_number': '6Y70B2501901', 'qty': '0', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/22/2026',
|
||||
},
|
||||
{
|
||||
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/29/2026',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_calibrate_unbound_visual_bands_from_sample_evidence():
|
||||
"""字段之间存在未标注描述行时,必须按样例字符证据校准真实 band,不能压缩字段序号。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('CUSTOMER-A', 55)],
|
||||
[('UNBOUND DESCRIPTION', 55)],
|
||||
[('PART-A', 55)],
|
||||
[('00020', 10), ('CUSTOMER-B', 55)],
|
||||
[('UNBOUND DESCRIPTION', 55)],
|
||||
[('PART-B', 55)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 120},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .2, 'y1': .25}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .15, 'x1': .6, 'y1': .25}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .38, 'x1': .6, 'y1': .48}},
|
||||
]}],
|
||||
)
|
||||
|
||||
assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B']
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_band():
|
||||
"""某条明细多出未标注换行时,应以格式和顺序重新对齐,不能把描述静默写入料号。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('CUSTOMER-A', 55)],
|
||||
[('PART-A', 55)],
|
||||
[('00020', 10), ('CUSTOMER-B', 55)],
|
||||
[('WRAPPED DESCRIPTION', 55)],
|
||||
[('PART-B', 55)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
|
||||
]}],
|
||||
)
|
||||
|
||||
assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B']
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
|
||||
"""额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('CUSTOMER-A', 55)],
|
||||
[('PART-A', 55)],
|
||||
[('00020', 10), ('CUSTOMER-B', 55)],
|
||||
[('ALT-1', 55)],
|
||||
[('ALT-2', 55)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
|
||||
]}],
|
||||
)
|
||||
|
||||
assert rows[1].fields.get('part_number') is None
|
||||
assert 'coordinate_profile_field_band_ambiguous:part_number' in rows[1].issues
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary():
|
||||
"""脱敏回放 4518838152:删除标记废弃 00010,合计后的记录不允许泄漏。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('6Y70B2501901', 62), ('0', 210), ('EA', 225)],
|
||||
[('D4-A08AR12000002', 62), ('06/22/2026', 210)],
|
||||
[('EXW', 62), ('AWS', 80), ('HUB', 98), ('Ship by sea', 180)],
|
||||
[('** Item deleted **', 62)],
|
||||
[('00020', 10), ('6Y70B2501901', 62), ('30', 210), ('EA', 225)],
|
||||
[('D4-A08AR12000002', 62), ('06/29/2026', 210)],
|
||||
[('EXW', 62), ('AWS', 80), ('HUB', 98), ('Ship by land', 180)],
|
||||
[('TOTAL AMOUNT', 62), ('28,252.80', 210)],
|
||||
[('00030', 10), ('MUST-NOT-LEAK', 62)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 160},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .18, 'y1': 1}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .18, 'y0': 0, 'x1': .7, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .7, 'y0': 0, 'x1': .85, 'y1': 1}},
|
||||
{'field_code': 'uom', 'region': {'x0': .85, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'delivery', 'row_offset': 1, 'field_regions': [
|
||||
{'field_code': 'part_number', 'region': {'x0': .18, 'y0': 0, 'x1': .7, 'y1': 1}},
|
||||
{'field_code': 'required_date', 'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'terms', 'row_offset': 2, 'field_regions': [
|
||||
{'field_code': 'incoterm', 'region': {'x0': .18, 'y0': 0, 'x1': .62, 'y1': 1}},
|
||||
]},
|
||||
],
|
||||
)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0].source_row_indices == [4, 5, 6]
|
||||
assert rows[0].fields == {
|
||||
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'required_date': '06/29/2026', 'incoterm': 'EXW AWS HUB',
|
||||
}
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_honor_configured_table_exclusion_and_termination_regions():
|
||||
"""第 6 阶段:只有配置表区可读;排除区和显式终止锚点均不能流入订单。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('OUTSIDE', 10)],
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('SIGNATURE', 65)],
|
||||
[('STOP HERE', 65)],
|
||||
[('00020', 10), ('MUST-NOT-LEAK', 65)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
table_region={'x0': 0, 'y0': .3, 'x1': 1, 'y1': .9},
|
||||
exclusion_regions=[{'x0': 0, 'y0': .45, 'x1': 1, 'y1': .6}],
|
||||
termination_rules=[{'rule_id': 'stop', 'anchor': {
|
||||
'anchor_id': 'stop_here', 'text': 'STOP HERE', 'match_mode': 'exact',
|
||||
'region': {'x0': 0, 'y0': .6, 'x1': 1, 'y1': .75},
|
||||
}}],
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{'line_no': '00010', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_can_continue_only_explicit_carry_state_on_next_page():
|
||||
"""跨页续行由调用方传入已验证的 carry;当前页自身没有主行锚点时不会擅自建行。"""
|
||||
layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'delivery', 'row_offset': 1, 'field_regions': [
|
||||
{'field_code': 'required_date', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
]
|
||||
page_two = _glyphs([('2026-08-01', 80)])
|
||||
assert reconstruct_coordinate_profile_rows(
|
||||
characters=page_two, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, line_layouts=layouts,
|
||||
) == []
|
||||
|
||||
continued = reconstruct_coordinate_profile_rows(
|
||||
characters=page_two, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, line_layouts=layouts,
|
||||
initial_fields={'line_no': '00010', 'part_number': 'PART-A'}, initial_next_offset=1,
|
||||
)
|
||||
assert continued[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'required_date': '2026-08-01'}
|
||||
|
||||
|
||||
def test_currency_composite_output_becomes_header_only_when_all_rows_agree():
|
||||
"""行区域产生的币种遵循 Schema Header scope;币种冲突必须拒绝自动建单。"""
|
||||
definition = {'fields': [
|
||||
{'field_id': 'line-id', 'field_code': 'part_number', 'scope': 'line', 'enabled': True,
|
||||
'collection_mode': 'llm_extraction', 'required': True},
|
||||
{'field_id': 'currency-id', 'field_code': 'currency', 'scope': 'header', 'enabled': True,
|
||||
'collection_mode': 'llm_extraction', 'required': True},
|
||||
]}
|
||||
schema_fields = {item['field_code']: item for item in definition['fields']}
|
||||
table = {'rows': [
|
||||
{'status': 'parsed', 'issues': [], 'fields': [
|
||||
{'field_id': 'line-id', 'field_code': 'part_number', 'value': 'A', 'quote': 'A USD'},
|
||||
{'field_id': 'currency-id', 'field_code': 'currency', 'value': 'USD', 'quote': 'A USD'},
|
||||
]},
|
||||
{'status': 'parsed', 'issues': [], 'fields': [
|
||||
{'field_id': 'line-id', 'field_code': 'part_number', 'value': 'B', 'quote': 'B USD'},
|
||||
{'field_id': 'currency-id', 'field_code': 'currency', 'value': 'USD', 'quote': 'B USD'},
|
||||
]},
|
||||
]}
|
||||
assert _validate_table_header_outputs(table['rows'], schema_fields=schema_fields)
|
||||
order = _build_approved_profile_order(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-9'},
|
||||
schema={'schema_version_id': 1, 'checksum': 'a' * 64}, definition=definition, table=table,
|
||||
)
|
||||
assert order is not None
|
||||
assert order['header_fields'][0]['field_id'] == 'currency-id'
|
||||
assert all('currency-id' not in {field['field_id'] for field in line['fields']} for line in order['lines'])
|
||||
|
||||
table['rows'][1]['fields'][1]['value'] = 'EUR'
|
||||
assert not _validate_table_header_outputs(table['rows'], schema_fields=schema_fields)
|
||||
assert _build_approved_profile_order(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-9'},
|
||||
schema={'schema_version_id': 1, 'checksum': 'a' * 64}, definition=definition, table=table,
|
||||
) is None
|
||||
|
||||
|
||||
def test_coordinate_reconstruction_uses_x_y_and_continuation_rules():
|
||||
"""行号、料号、数量按 x/y 重建;无行号的下一视觉行只能是续行。"""
|
||||
result = _reconstruct(_glyphs(
|
||||
@@ -210,7 +827,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.2, 0.65, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.4, 0.7, 1],
|
||||
'column_field_codes': [None, 'required_date', 'remark']},
|
||||
'column_field_codes': [None, 'required_date', 'line_remark']},
|
||||
])
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
@@ -221,7 +838,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
reconstruction=settings,
|
||||
)
|
||||
grid = parse_html_grid(html, table_id='multi-subrow')
|
||||
headers = ['line_no', 'part_number', 'qty', 'required_date', 'remark']
|
||||
headers = ['line_no', 'part_number', 'qty', 'required_date', 'line_remark']
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='MULTI_SUBROW', version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
@@ -237,7 +854,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
{'field_code': 'part_number', 'enabled': True},
|
||||
{'field_code': 'qty', 'value_type': 'decimal', 'enabled': True},
|
||||
{'field_code': 'required_date', 'value_type': 'date', 'enabled': True},
|
||||
{'field_code': 'remark', 'enabled': True},
|
||||
{'field_code': 'line_remark', 'enabled': True},
|
||||
]})
|
||||
|
||||
parsed = parse_html_table_with_order_profile(html, table_id='multi-subrow', profile=profile, contract=contract)
|
||||
@@ -247,7 +864,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
assert parsed.rows[0].fields['part_number'] == 'PART-20'
|
||||
assert parsed.rows[0].fields['qty'] == 30
|
||||
assert parsed.rows[0].fields['required_date'] == '2026-06-29'
|
||||
assert parsed.rows[0].fields['remark'] == 'Ship by land'
|
||||
assert parsed.rows[0].fields['line_remark'] == 'Ship by land'
|
||||
|
||||
|
||||
def test_multi_subrow_profile_supports_four_or_more_physical_rows():
|
||||
|
||||
@@ -18,9 +18,12 @@ from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
@@ -38,15 +41,20 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', checksum='a' * 64,
|
||||
published_at=datetime.utcnow(), definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
||||
'value_type': 'decimal', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]},
|
||||
)
|
||||
@@ -136,6 +144,40 @@ def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(a
|
||||
assert getattr(immutable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
|
||||
|
||||
|
||||
def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app):
|
||||
"""v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
profile.definition_json = {
|
||||
'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []},
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .15, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
}]}],
|
||||
}
|
||||
for document in documents:
|
||||
glyphs = []
|
||||
for text, x0 in [('00010', 5), ('PN-1', 30), ('3', 150)]:
|
||||
for index, char in enumerate(text):
|
||||
glyphs.append({'text': char, 'bbox': {'x0': x0 + index * 4, 'y0': 20, 'x1': x0 + index * 4 + 3, 'y1': 30}})
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
||||
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}},
|
||||
})
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
for document in documents:
|
||||
quality.add_sample(suite_id=suite['id'], document_id=document.id, table_id='table-1',
|
||||
expected_rows=[{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
|
||||
|
||||
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
|
||||
with app.app_context():
|
||||
@@ -151,3 +193,165 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
profile.checksum = 'c' * 64
|
||||
db.session.commit()
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
|
||||
|
||||
def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(app):
|
||||
"""盲测草稿可受控删除样本并留痕,批准后的真值不得再被篡改。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
quality.add_sample(
|
||||
suite_id=suite['id'], document_id=documents[0].id, table_id='table-1',
|
||||
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
|
||||
)
|
||||
sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
|
||||
removed = quality.remove_sample(suite_id=suite['id'], sample_id=sample_id, actor_id=user.id)
|
||||
assert removed['sample_count'] == 0
|
||||
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileAudit.id.desc(),
|
||||
).first()
|
||||
assert audit.event_type == 'blind_test_sample_removed'
|
||||
assert audit.detail_json == {'suite_id': suite['id']}
|
||||
|
||||
for document in documents:
|
||||
quality.add_sample(
|
||||
suite_id=suite['id'], document_id=document.id, table_id='table-1',
|
||||
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
|
||||
)
|
||||
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
immutable_sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality.remove_sample(suite_id=suite['id'], sample_id=immutable_sample_id, actor_id=user.id)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
|
||||
|
||||
|
||||
def test_draft_publish_requires_independent_training_and_multiline_blind_gate(app):
|
||||
"""关键断言:发布前必须已有训练样本、独立多明细盲测与审批,不能发布后补门禁。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
profile.status = 'draft'
|
||||
profile.checksum = None
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=documents[0].id, table_id='table-1', sample_role='training', created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as missing_suite:
|
||||
profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert getattr(missing_suite.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
|
||||
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
# Use different documents than the training sample. One sample is real multi-line evidence.
|
||||
record_inline_layout_snapshot(documents[1], {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr><tr><td>PN-2</td><td>4</td></tr></table>'}],
|
||||
})
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
|
||||
{'part_number': 'PN-1', 'qty': 3}, {'part_number': 'PN-2', 'qty': 4},
|
||||
], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id)
|
||||
assert quality.execute_suite(suite_id=suite['id'], actor_id=user.id)['latest_run']['status'] == 'failed'
|
||||
|
||||
# A third independent document is necessary even when one sample is multi-line.
|
||||
extra = ShippingNoticeDocument(
|
||||
intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment',
|
||||
attachment_key='quality-extra.pdf', filename='quality-extra.pdf', content_hash='e' * 64,
|
||||
classification='order_notice', parse_status='parsed', extracted_text='PN-1 3',
|
||||
)
|
||||
db.session.add(extra)
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(extra, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr></table>'}],
|
||||
})
|
||||
db.session.commit()
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
# This legacy fixture cannot be republished under the v2-only write contract,
|
||||
# but its current approved credential proves the draft gate accepts independent evidence.
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.structure_fingerprint)
|
||||
|
||||
|
||||
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
"""关键断言:v2 草稿在训练、独立多明细盲测通过后可发布,并冻结正式 checksum 凭证。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
profile.status = 'draft'
|
||||
profile.checksum = None
|
||||
profile.published_at = None
|
||||
profile.definition_json = {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [{
|
||||
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [{'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .15}, 'field_regions': []}], 'termination_rules': [], 'exclusion_regions': [],
|
||||
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .16, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': .16, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .15, 'y0': .16, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
def set_coordinate_rows(document: ShippingNoticeDocument, rows: list[tuple[str, str]]) -> None:
|
||||
"""冻结每个样本的字符坐标,让 v2 盲测不依赖 HTML 网格。"""
|
||||
glyphs = []
|
||||
for row_index, (part, qty) in enumerate(rows):
|
||||
for text, x0 in ((f'{(row_index + 1) * 10:05d}', 5), (part, 30), (qty, 150)):
|
||||
for index, char in enumerate(text):
|
||||
glyphs.append({'text': char, 'bbox': {
|
||||
'x0': x0 + index * 4, 'y0': 20 + row_index * 20,
|
||||
'x1': x0 + index * 4 + 3, 'y1': 30 + row_index * 20,
|
||||
}})
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
||||
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}}},
|
||||
})
|
||||
|
||||
for document in documents:
|
||||
set_coordinate_rows(document, [('PN-1', '3')])
|
||||
set_coordinate_rows(documents[1], [('PN-1', '3'), ('PN-2', '4')])
|
||||
extra = ShippingNoticeDocument(
|
||||
intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment',
|
||||
attachment_key='quality-v2-extra.pdf', filename='quality-v2-extra.pdf', content_hash='f' * 64,
|
||||
classification='order_notice', parse_status='parsed', extracted_text='PN-3 5',
|
||||
)
|
||||
db.session.add(extra)
|
||||
db.session.flush()
|
||||
set_coordinate_rows(extra, [('PN-3', '5')])
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=documents[0].id, table_id='table-1', sample_role='training', created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
# Training document is rejected immediately, not only later at publication time.
|
||||
with pytest.raises(Exception) as reused:
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[0].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
assert getattr(reused.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT'
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
|
||||
{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}, {'line_no': '00020', 'part_number': 'PN-2', 'qty': '4'},
|
||||
], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert published['status'] == 'published'
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=published['checksum'])
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_coordinate_profile_governance_migration.py
|
||||
|
||||
用途:验证订单坐标 Profile 治理迁移可以在 SQLite 最小前置结构上升级和降级。
|
||||
依赖:Alembic Operations、SQLite 内存数据库、028e9f0a1b2c 迁移。
|
||||
逻辑:先构造 Profile 与外键目标,再检查新增列、样本/审计表和索引会被完整回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def _migration():
|
||||
"""以文件路径加载数字开头的 Alembic 迁移模块。"""
|
||||
path = Path(__file__).parents[1] / 'migrations' / 'versions' / '028e9f0a1b2c_add_order_coordinate_profile_governance.py'
|
||||
spec = importlib.util.spec_from_file_location('order_coordinate_profile_governance_migration', path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_order_coordinate_profile_governance_migration_round_trip():
|
||||
"""治理摘要、样本绑定和审计表必须可迁移并完全逆序回滚。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('users', 'shipping_notice_documents', 'shipping_order_schema_versions'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_order_document_profiles', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True), sa.Column('status', sa.String(16), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
migration = _migration()
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert {'shipping_order_document_profile_samples', 'shipping_order_document_profile_audits'} <= set(inspector.get_table_names())
|
||||
assert {'template_mode', 'training_sample_count', 'match_strategy_summary_json'} <= {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_document_profiles')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_document_profile_samples' not in inspector.get_table_names()
|
||||
assert 'shipping_order_document_profile_audits' not in inspector.get_table_names()
|
||||
assert not {'template_mode', 'training_sample_count', 'match_strategy_summary_json'} & {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_document_profiles')
|
||||
}
|
||||
@@ -13,6 +13,7 @@ from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderCoordinateProfileV2,
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
diagnose_order_profile_header,
|
||||
@@ -190,3 +191,72 @@ def test_template_profile_rejects_freeform_or_invalid_extractor_targets():
|
||||
extractor_key='temp_internal_parts',
|
||||
target_field_codes=['part_number'],
|
||||
)
|
||||
|
||||
|
||||
def test_coordinate_profile_v2_accepts_independent_header_and_multi_physical_line_layouts():
|
||||
"""坐标模板必须能表达多条表头、两条不同布局的物理行和独立字段区域。"""
|
||||
definition = {
|
||||
'profile_code': 'COORDINATE_A', 'version': 1,
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'text': 'PURCHASE ORDER'}]},
|
||||
'table_regions': [{
|
||||
'region_id': 'main_lines', 'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .8},
|
||||
'header_layouts': [
|
||||
{'layout_id': 'header_one', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}, 'field_regions': []},
|
||||
{'layout_id': 'header_two', 'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .2}, 'field_regions': []},
|
||||
],
|
||||
'line_layouts': [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .4},
|
||||
'field_regions': [{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
{'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation', 'region': {'x0': 0, 'y0': .4, 'x1': 1, 'y1': .6},
|
||||
'field_regions': [{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .5, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
], 'continuation_rule': {'allow_cross_page': False}, 'termination_rules': [], 'exclusion_regions': [],
|
||||
}],
|
||||
}
|
||||
|
||||
profile = OrderCoordinateProfileV2.model_validate(definition)
|
||||
|
||||
assert profile.contract_version == 'order_coordinate_profile.v2'
|
||||
assert len(profile.table_regions[0].header_layouts) == 2
|
||||
assert [item.row_offset for item in profile.table_regions[0].line_layouts] == [0, 1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mutation', [
|
||||
lambda value: value['table_regions'][0]['line_layouts'][1].update({'row_offset': 2}),
|
||||
lambda value: value['table_regions'][0]['line_layouts'][1].update({'role': 'main'}),
|
||||
lambda value: value['table_regions'][0]['line_layouts'][1]['field_regions'][0].update({'field_code': 'line_no'}),
|
||||
lambda value: value['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region'].update({'x1': 1.1}),
|
||||
lambda value: value['table_regions'][0]['line_layouts'][1]['region'].update({'y0': .4}),
|
||||
])
|
||||
def test_coordinate_profile_v2_rejects_ambiguous_or_invalid_regions(mutation):
|
||||
"""关键断言:错序物理行、重复字段和越界区域均不得进入可发布定义。"""
|
||||
value = {
|
||||
'profile_code': 'COORDINATE_B', 'version': 1, 'document_match': {},
|
||||
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .5}, 'field_regions': [{'field_id': 'line', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
{'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation', 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}, 'field_regions': [{'field_id': 'qty', 'field_code': 'qty', 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
]}],
|
||||
}
|
||||
mutation(value)
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
OrderCoordinateProfileV2.model_validate(value)
|
||||
|
||||
|
||||
def test_coordinate_profile_v2_requires_declared_document_anchor_for_cross_page_continuation():
|
||||
"""跨页只能绑定已有静态文档锚点,不能以相邻页面或列数相近作为合并理由。"""
|
||||
profile = {
|
||||
'profile_code': 'CROSS_PAGE', 'version': 1,
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'continued', 'text': 'CONTINUED'}]},
|
||||
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'continuation_rule': {'allow_cross_page': True, 'required_anchor_ids': ['continued']},
|
||||
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'field_regions': [
|
||||
{'field_id': 'line', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
]}],
|
||||
}],
|
||||
}
|
||||
assert OrderCoordinateProfileV2.model_validate(profile).table_regions[0].continuation_rule.allow_cross_page is True
|
||||
|
||||
profile['table_regions'][0]['continuation_rule']['required_anchor_ids'] = []
|
||||
with pytest.raises(ValidationError, match='cross-page continuation requires anchor evidence'):
|
||||
OrderCoordinateProfileV2.model_validate(profile)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -288,7 +288,7 @@ def test_create_run_freezes_published_order_document_profile_definition(app):
|
||||
|
||||
assert reused is False
|
||||
frozen = run.input_snapshot_json['order_document_profiles']
|
||||
assert frozen == [{
|
||||
assert [{key: value for key, value in item.items() if key != 'auto_create_approved'} for item in frozen] == [{
|
||||
'profile_id': profile.id,
|
||||
'profile_code': 'PO_312207',
|
||||
'version': 1,
|
||||
@@ -297,6 +297,8 @@ def test_create_run_freezes_published_order_document_profile_definition(app):
|
||||
'structure_fingerprint': 'b' * 64,
|
||||
'definition': profile.definition_json,
|
||||
}]
|
||||
# 质量门禁也必须成为冻结快照的一部分,不能在 Worker 中回读当前测试集状态。
|
||||
assert frozen[0]['auto_create_approved'] is False
|
||||
profile.definition_json = {**profile.definition_json, 'drop_zero_qty': False}
|
||||
db.session.commit()
|
||||
assert run.input_snapshot_json['order_document_profiles'][0]['definition']['drop_zero_qty'] is True
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""验证订单坐标模板的唯一匹配只使用静态锚点和冻结结构证据。"""
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
|
||||
|
||||
|
||||
def _profile(code: str, *, required: str = 'PURCHASE ORDER', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
|
||||
"""构造不包含订单号、料号、数量或金额的最小冻结 Profile。"""
|
||||
return {'profile_code': code, 'version': 1, 'checksum': f'{code.lower():0<64}'[:64], 'definition': {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {
|
||||
'required_anchors': [{'anchor_id': 'title', 'text': required}],
|
||||
'optional_anchors': [{'anchor_id': f'optional_{index}', 'text': value} for index, value in enumerate(optional or [])],
|
||||
'minimum_score': score, 'minimum_margin': margin,
|
||||
},
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}],
|
||||
}]}],
|
||||
}}
|
||||
|
||||
|
||||
def _layout(text: str = 'PURCHASE ORDER') -> dict:
|
||||
"""构造最小页面坐标证据,业务文本仅用于证明它没有参与匹配逻辑。"""
|
||||
return {'tables': [{'table_id': 'table-1', 'page_no': 1}], 'coordinate_evidence': {
|
||||
'tables': {'table-1': [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
|
||||
for index, char in enumerate(text)
|
||||
]}, 'pages': {'1': {'width': 200, 'height': 200}},
|
||||
}}
|
||||
|
||||
|
||||
def test_profile_matcher_uniquely_matches_static_anchors_not_dynamic_order_values():
|
||||
"""同一静态版式在订单号、料号、数量变化后仍稳定命中同一 Profile。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'])], layout=_layout('PURCHASE ORDER SUPPLIER A PO-999 QTY 999 PART-X'))
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'PO_A'
|
||||
|
||||
|
||||
def test_profile_matcher_rejects_similar_profiles_when_margin_is_insufficient():
|
||||
"""相同静态锚点的两个 Profile 必须返回 ambiguous,禁止按版本或顺序选择。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A'), _profile('PO_B')], layout=_layout())
|
||||
assert result.status == 'ambiguous'
|
||||
|
||||
|
||||
def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
|
||||
"""缺静态锚点为 layout_drift;没有坐标页证据则为 evidence_insufficient。"""
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('DELIVERY NOTE')).status == 'layout_drift'
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout={'tables': []}).status == 'evidence_insufficient'
|
||||
|
||||
|
||||
def test_profile_matcher_requires_optional_score_threshold():
|
||||
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout())
|
||||
assert result.status == 'no_match'
|
||||
@@ -24,6 +24,7 @@ from app.models import (
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchemaAuditEvent,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderDocumentProfile,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
@@ -468,6 +469,27 @@ def test_order_field_retire_is_blocked_by_active_cross_domain_config(app):
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
|
||||
|
||||
def test_order_field_retire_is_blocked_by_v2_coordinate_profile(app):
|
||||
"""关键断言:v2 表头或明细字段区域引用的 field_id 也必须阻止字段退役。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
field = service.save_field({'field_code': 'coordinate_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
schema = service.get_state()['schema']
|
||||
version = service.create_draft({}, actor_id=None)
|
||||
db.session.add(ShippingOrderDocumentProfile(
|
||||
profile_code='V2_REFERENCE', display_name='V2 reference', version=1, status='draft',
|
||||
schema_version_id=version['id'], structure_fingerprint='a' * 64,
|
||||
definition_json={'contract_version': 'order_coordinate_profile.v2', 'table_regions': [{
|
||||
'header_layouts': [], 'line_layouts': [{'field_regions': [{'field_id': field['id']}]}],
|
||||
}]}, lock_version=1,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
service.retire_field(field['id'])
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
|
||||
|
||||
def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
|
||||
"""新 Schema 版本移除下游仍在使用的字段时,发布必须在运行前阻断。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_schema_compatibility.py
|
||||
|
||||
用途:验证订单文档模板按稳定 field_id 自动兼容 Schema 小版本变化。
|
||||
依赖:纯兼容性判定和模板定义重映射函数。
|
||||
逻辑:覆盖字段改名、可选字段新增和破坏性类型变化。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.order_schema.compatibility import (
|
||||
compare_profile_schema,
|
||||
remap_profile_field_codes,
|
||||
)
|
||||
|
||||
|
||||
def test_profile_impact_service_is_exposed_by_compatibility_contract():
|
||||
"""纯函数契约保留字段级 breaking reason,供影响接口直接展示。"""
|
||||
result = compare_profile_schema(
|
||||
_profile(),
|
||||
_schema(_field('f1', 'old_code')),
|
||||
_schema(_field('f1', 'old_code', scope='header')),
|
||||
)
|
||||
assert result['status'] == 'breaking'
|
||||
assert result['breaking_changes'][0]['reason'] == 'scope_changed'
|
||||
|
||||
|
||||
def _schema(*fields):
|
||||
return {'fields': list(fields)}
|
||||
|
||||
|
||||
def _field(field_id, code, *, value_type='string', scope='line', enabled=True):
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'field_code': code,
|
||||
'value_type': value_type,
|
||||
'scope': scope,
|
||||
'enabled': enabled,
|
||||
}
|
||||
|
||||
|
||||
def _profile():
|
||||
return {
|
||||
'table_regions': [{
|
||||
'line_layouts': [{
|
||||
'field_regions': [{
|
||||
'field_id': 'f1', 'field_code': 'old_code',
|
||||
'target_fields': [{'field_id': 'f1', 'field_code': 'old_code'}],
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
def test_field_rename_and_optional_addition_are_automatically_compatible():
|
||||
result = compare_profile_schema(
|
||||
_profile(),
|
||||
_schema(_field('f1', 'old_code')),
|
||||
_schema(_field('f1', 'new_code'), _field('f2', 'optional_code')),
|
||||
)
|
||||
|
||||
assert result['status'] == 'compatible'
|
||||
assert result['auto_upgradable'] is True
|
||||
assert result['renamed_fields'] == [{'field_id': 'f1', 'from': 'old_code', 'to': 'new_code'}]
|
||||
|
||||
|
||||
def test_type_change_is_breaking_for_referenced_field():
|
||||
result = compare_profile_schema(
|
||||
_profile(),
|
||||
_schema(_field('f1', 'old_code')),
|
||||
_schema(_field('f1', 'old_code', value_type='decimal')),
|
||||
)
|
||||
|
||||
assert result['status'] == 'breaking'
|
||||
assert result['breaking_changes'][0]['reason'] == 'value_type_changed'
|
||||
|
||||
|
||||
def test_profile_field_codes_are_remapped_by_stable_identity():
|
||||
result = remap_profile_field_codes(
|
||||
_profile(),
|
||||
_schema(_field('f1', 'new_code')),
|
||||
)
|
||||
|
||||
field = result['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
assert field['field_id'] == 'f1'
|
||||
assert field['field_code'] == 'new_code'
|
||||
assert field['target_fields'][0]['field_code'] == 'new_code'
|
||||
|
||||
|
||||
def test_migration_resolution_contract_requires_each_breaking_field():
|
||||
"""破坏性字段必须逐项处理,避免迁移草稿静默丢失绑定。"""
|
||||
result = compare_profile_schema(
|
||||
_profile(),
|
||||
_schema(_field('f1', 'old_code')),
|
||||
_schema(_field('f1', 'old_code', value_type='decimal')),
|
||||
)
|
||||
assert [item['field_id'] for item in result['breaking_changes']] == ['f1']
|
||||
|
||||
|
||||
def test_semantic_rule_change_requires_review_without_forcing_coordinate_migration():
|
||||
before = _field('f1', 'code') | {'validator_keys': []}
|
||||
after = _field('f1', 'code') | {'validator_keys': ['non_empty']}
|
||||
result = compare_profile_schema(_profile(), _schema(before), _schema(after))
|
||||
assert result['status'] == 'review_required'
|
||||
assert result['auto_upgradable'] is True
|
||||
assert result['review_changes'][0]['reason'] == 'validator_keys_changed'
|
||||
|
||||
|
||||
def test_source_schema_missing_referenced_identity_is_breaking():
|
||||
result = compare_profile_schema(_profile(), _schema(), _schema(_field('f1', 'code')))
|
||||
assert result['status'] == 'breaking'
|
||||
assert result['breaking_changes'][0]['reason'] == 'source_field_missing'
|
||||
|
||||
|
||||
def test_replacement_candidates_exclude_changed_field_and_require_source_coverage():
|
||||
"""替代候选不能用原字段自我消解,且必须覆盖原字段全部坐标来源。"""
|
||||
before = _field('f1', 'old_code') | {
|
||||
'required': False,
|
||||
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
}
|
||||
target = _schema(
|
||||
_field('f1', 'old_code') | {
|
||||
'required': True,
|
||||
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
},
|
||||
_field('f2', 'partial') | {'allowed_sources': ['pdf_coordinate']},
|
||||
_field('f3', 'replacement') | {
|
||||
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
},
|
||||
)
|
||||
|
||||
result = compare_profile_schema(_profile(), _schema(before), target)
|
||||
|
||||
assert result['status'] == 'breaking'
|
||||
assert result['breaking_changes'][0]['replacement_candidates'] == [{
|
||||
'field_id': 'f3', 'field_code': 'replacement', 'display_name': None,
|
||||
}]
|
||||
|
||||
|
||||
def test_removed_field_still_offers_contract_compatible_replacement():
|
||||
"""删除字段时仍应提供安全候选,避免管理员只能解除绑定。"""
|
||||
before = _field('f1', 'old_code') | {'allowed_sources': ['pdf_coordinate']}
|
||||
replacement = _field('f2', 'replacement') | {'allowed_sources': ['pdf_coordinate']}
|
||||
|
||||
result = compare_profile_schema(_profile(), _schema(before), _schema(replacement))
|
||||
|
||||
assert result['breaking_changes'][0]['reason'] == 'removed_or_disabled'
|
||||
assert result['breaking_changes'][0]['replacement_candidates'] == [{
|
||||
'field_id': 'f2', 'field_code': 'replacement', 'display_name': None,
|
||||
}]
|
||||
@@ -17,6 +17,7 @@ from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingReservation, ShippingTask,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success
|
||||
from app.services.shipping_notice.upload_attempt_service import complete_attempt, start_rpa_attempt, void_rejected_artifact
|
||||
|
||||
|
||||
@@ -76,6 +77,20 @@ def test_failed_attempt_does_not_complete_reservation(app):
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready'
|
||||
|
||||
|
||||
def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app):
|
||||
"""共享目录投递失败要落为失败 Attempt,不能遗留 uploading Artifact 阻断下一轮。"""
|
||||
with app.app_context():
|
||||
task, artifact, reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
complete_attempt(
|
||||
attempt, success=False, callback_id=f'trigger_failed:{attempt.id}',
|
||||
error_message='RPA upload trigger could not be written',
|
||||
)
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready'
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
assert start_rpa_attempt(task, artifact_id=artifact.id).attempt_no == 2
|
||||
|
||||
|
||||
def test_only_explicit_rejection_can_void_and_release_artifact(app):
|
||||
"""网络失败不能释放预约单;货代明确拒绝且有授权后才可重新进入库存核验。"""
|
||||
with app.app_context():
|
||||
@@ -87,3 +102,15 @@ def test_only_explicit_rejection_can_void_and_release_artifact(app):
|
||||
void_rejected_artifact(task, artifact_id=artifact.id, operator_id=1, reason='货代明确拒绝')
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'superseded'
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'pending'
|
||||
|
||||
|
||||
def test_upload_callback_success_parsing_does_not_treat_false_text_as_success():
|
||||
"""Worker 回调的字符串 false/0 必须严格映射失败,非法值不得默认成功。"""
|
||||
assert _rpa_callback_success(True) is True
|
||||
assert _rpa_callback_success('true') is True
|
||||
assert _rpa_callback_success(False) is False
|
||||
assert _rpa_callback_success('false') is False
|
||||
assert _rpa_callback_success('0') is False
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_rpa_callback_success('yes')
|
||||
assert exc_info.value.code == 'SHIPPING.UPLOAD_CALLBACK_INVALID'
|
||||
+11
-4
@@ -1,5 +1,10 @@
|
||||
# 智能HR请假管理需求
|
||||
|
||||
## 订单坐标模板 v2(阶段 3-4)
|
||||
|
||||
- 管理员在受控低清 PDF 画布上配置表头、明细物理行和字段区域,不输入坐标数字;翻页按页加载,离开未保存草稿必须确认。
|
||||
- 表头行与明细行分别配置。表头识别只能给出当前冻结 Schema 的唯一精确别名建议,不能覆盖人工字段绑定;字段缺失、重复或不确定时保持未映射。
|
||||
|
||||
## 设备维保助手补充需求
|
||||
|
||||
- 查询方式:用户通过 `设备维保助手` 会话查询设备维护/维修记录,系统支持按设备编号、设备名称、故障描述、维修说明、维修人和状态筛选记录。
|
||||
@@ -113,15 +118,17 @@
|
||||
- 高置信发货需求只要包含可信内部料号 `part_number` + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。
|
||||
- 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。
|
||||
- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;Run 冻结用户、入口 Agent、会话、Intake/Document 正文和 published Schema,幂等键由服务端快照计算,不依赖浏览器 request ID。
|
||||
- 订单附件结构化必须支持版本化订单文档 Profile。Profile 绑定一个不可变订单 Schema 版本,以表头网格精确结构指纹选择固定列规则,并把目标字段冻结为稳定 `field_id + field_code`。已发布 Profile 不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile 与 MinerU 紧凑表格快照,不能只保存当前 Profile ID。
|
||||
- 业务管理员必须通过 MinerU 样本表格的结构化页面维护订单文档 Profile:只选择表格、表头/数据行、行结构、Schema 字段和注册解析器,不得编辑 HTML、bbox、JSON、正则、脚本或结构指纹。结构指纹由后端基于持久化样本计算;草稿更新使用乐观锁,同一目标字段不得跨列重复映射;不可变版本可复制为新草稿或退役。
|
||||
- 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。
|
||||
- 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。
|
||||
- Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。
|
||||
- 模板工作台页面预览仅针对已绑定样本:PDF 以短时、单页、单用途 Redis 授权返回低分辨率 PNG,响应始终 `private, no-store`,不返回 MinIO URL、PDF、bbox、原始 HTML 或永久下载令牌。OCR 坐标只可由管理员对绑定 PDF 显式触发;页面文本和局部解析候选不包含坐标/token 身份。EML 仅使用既有白名单清洗的表格文本,禁止脚本、事件属性、表单、iframe、外链及远程图片/字体。
|
||||
- MinerU 按显式环境开关固定使用 `pipeline`,由独立布局 Job 在 Intake 持久化 Document 后异步调用,不得阻塞 Intake 预解析。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Intake 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时回退现有 Dify/人工复核,不得伪造确定性字段。
|
||||
- 人工单元格真值当前允许延期,不阻塞布局版本/任务生命周期建设;但在真值评测完成前,不得宣称 95% 准确率、把 MinerU/OpenCV/文本对齐候选自动标记为 `accepted`,也不得据此开启错误自动建单风险。
|
||||
- 原生 PDF 可使用 PDFium 字符坐标与 MinerU HTML 生成 `shipping_document_layout.v1` 候选;只允许唯一连续文本或“OpenCV 多参数有框网格 + 原生文本全量一致”两条保守路径。候选必须保持 `needs_review`,扫描 PDF 不得由本阶段伪造 OCR 结果。
|
||||
- 扫描 PDF 的布局 OCR 必须保留 RapidOCR 原始多边形坐标和置信度,并且只有与严格有框网格及全部非空 cell 文本一致时才能生成 OCR cell 候选。EML HTML table 必须经主动内容/属性白名单清理后按 DOM 行列和跨度生成逻辑布局;原始 HTML 不得进入 Intake 摘要、Dify 或日志。两类结果在人工真值完成前均保持 `needs_review`。
|
||||
- 冻结 Schema 映射必须直接消费 layout.v1 的真实 `cell_id/token_ids`,不得从 HTML 再生成第二套证据 ID。表头后置、重复列、零 Qty、类型与安全校验复用同一规则;跨页只接受显式 continuation。needs_review 映射只能冻结为内部 candidate,禁止进入 Dify、自动接受或跳过 Provider。
|
||||
- 精确 Profile 命中后,模板语义优先于全局 Schema 别名。例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法映射。只有唯一命中表且每个保留行都具备可信 `part_number + qty` 时,后端才可跳过该附件的 LLM;显式 Qty=0 行删除。Reservation 可由邮件或其他附件补充,最终缺失仍须阻断库存匹配和发货 Excel。
|
||||
- 对 MinerU 行列关系错误或数据页表头不完整的 PDF,管理员可基于原生/OCR 字符坐标确认相对列边界和固定字段映射。坐标模板不得依赖数据页完整表头:系统以行号列识别新明细,按纵坐标形成物理行,将无新行号的相邻行按列合并为续行,并将删除标记回写最近明细、在合计/说明起始行终止。几何位置是主证据,字段内容类型与同行左右顺序仅用于边界歧义辅助;重建结果必须在页面展示逻辑明细、删除状态和来源物理行,管理员确认后才可进入草稿与盲测。
|
||||
- 对 MinerU 行列关系错误或数据页表头不完整的 PDF,管理员可基于原生/OCR 字符坐标确认相对字段区域。坐标模板不得依赖数据页完整表头:系统以主行锚点、y-band、物理行相对偏移、前一明细完整性和显式跨页声明综合判定新行/续行;无稳定主行锚点不得默认新明细。合计、税额、条款和签字区必须由排除/终止规则排除。几何位置是主证据,字段内容类型与同行左右顺序仅用于边界歧义辅助。
|
||||
- 同一订单明细允许由任意连续 N 条物理行构成,不限定两行、三行或四行。管理员可动态增加/删除第 2..N 行版式,每行独立配置相对列边界和固定字段映射,横坐标区间允许跨行重叠;第 1 行必须包含 `line_no` 作为新明细锚点,后续行按 `row_offset` 合并到最近明细。
|
||||
- 管理员不得被要求从 PDF 截图手工计算 0..1 列边界。系统须基于冻结的 PDF/OCR 字符坐标自动建议物理行数量、每行列边界及列示例文字;人工只确认字段映射,并可在必要时使用高级边界校准。
|
||||
- 阶段 2 创建 Run 时同步创建 `shipping_order_extraction` Job;Worker 按 Run 冻结快照调用 `shipping.order_extraction` 能力绑定的内部 Provider,并把 Dify 成功结果先于 HXOPS 订单落库独立提交,重试不得重复调用 Dify。
|
||||
@@ -583,6 +590,6 @@
|
||||
- L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。
|
||||
- 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。
|
||||
- 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。
|
||||
- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。每个已发布 Profile 版本必须建立独立盲测集,至少 3 个独立样本全部按管理员确认真值通过,并由管理员批准;资格与 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。
|
||||
- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;常规模板至少 3 份独立样本(无表头模板至少 5 份),其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。所有样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。
|
||||
- **Dify 证据边界**:Dify 输出只能使用冻结 `extraction_contract` 中的 field_id,所有 Observation 必须引用当前 Unit 文档且 quote 可在冻结输入中逐字验证;不得回传确定性上下文字段或覆盖已锁定值。Dify 画布由管理员在最终验收时手工配置,HXOPS 不修改画布。
|
||||
- **客户绑定与冻结**:订单原文、按 `order-customer-fingerprint.v1` 标准化生成的身份指纹、正式 `customer_id` 三层分离保存。Bill-to 是订购客户;只有已人工确认并写明理由的 Bill-to 匹配可以冻结为 Snapshot。调用方不能在冻结请求中自由传入客户或简码;Snapshot 固化客户简码和匹配规则版本,客户后续改名、合并或规则变化不回写历史。
|
||||
@@ -150,6 +150,16 @@ refs.intake_nos
|
||||
- Workflow Start 仅接收版本化 `execution_manifest` String;其包含 Run 标识、输入哈希、冻结的 `extraction_contract` / `documents` 及 `readonly_hints`。End 只输出 `orders`。`readonly_hints` 只用于当次提示/关联,不得加入订单字段输出、长期变量、知识库或自定义日志字段,也不得尝试恢复 `redacted` 值。
|
||||
- 本文其余 agent_runtime_context 说明仅适用于普通聊天续办与受控 Tool,不适用于订单抽取。
|
||||
|
||||
### 6.1 坐标模板 v2 的人工配置
|
||||
|
||||
后端会在唯一匹配且通过质量凭证的订单模板上,先以冻结的 PDF/OCR 坐标生成确定性字段。Dify 不参与模板匹配、坐标换算、跨页拼接、字段拆分或删除/合计判断。
|
||||
|
||||
1. 保持订单抽取 Workflow Start 只有 `execution_manifest`(String);不要新增 `layout_snapshot`、PDF 字符坐标、MinerU HTML、Profile 定义、正则、脚本或 Prompt 配置变量。
|
||||
2. End 节点仍只返回 `orders` JSON。若 HXOPS 注入了已锁定的确定性字段,Workflow 输出必须逐字段原样保留,不能删除、改写、补猜或以其他字段替代。
|
||||
3. 坐标模板未唯一命中、证据不足、跨页条件不足或质量凭证未批准时,HXOPS 会阻止零 Provider 自动建单;Workflow 只处理后端允许进入的补充场景,不得绕过该门禁。
|
||||
4. 不要按订单号、料号、数量、金额、上传时间或“最新模板版本”在 Prompt/Code 节点选择模板;模板选择完全由 HXOPS 的静态锚点、阈值和分差策略决定。
|
||||
5. 联调时分别验证:纯 Workflow 抽取、唯一坐标模板锁定字段、模板冲突回退、以及已锁定字段被 Workflow 篡改时后端拒绝响应。
|
||||
|
||||
## 7. 验收场景
|
||||
|
||||
联调时至少覆盖以下场景:
|
||||
|
||||
@@ -222,6 +222,8 @@ WYC26071501
|
||||
|
||||
**字段名称是系统标识,不是中文说明。** 管理员应填写英文小写下划线,例如 `part_number`、`customer_part_number`、`reservation_id`、`request_qty`。下游配置使用稳定字段 ID 建立关联,因此系统标识可以重命名;已发布历史版本仍保留发布时的旧名称。若需面向业务展示中文,可在“当前版本显示名称”填写“内部料号”“需求数量”等文案。
|
||||
|
||||
订单字段版本调整后,不会要求所有订单模板整体重做。系统会先区分可自动兼容、需管理员复核和破坏性变化:仅名称调整或新增字段可继续使用;校验和业务规则变化会在发布前提示;字段删除、停用、类型、作用域或坐标来源变化时,只迁移受影响字段。管理员可选择兼容替代字段,或保留原框选区域并重新绑定;迁移草稿必须重新完成盲测后才能发布。历史订单始终按当时冻结的字段和模板版本回放,不会被新配置改写。
|
||||
|
||||
“纳入当前版本”只决定字段是否参与本次发布和订单解析,不控制名称编辑。未纳入字段仍可修改并保存系统标识与当前草稿显示名称;后续重新纳入时继续使用已保存配置。
|
||||
|
||||
| 配置项 | 含义 | 建议维护方式 |
|
||||
|
||||
@@ -335,11 +335,17 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏
|
||||
|
||||
**Profile 持久化与运行接入 Review(2026-07-21)**:`shipping_order_document_profiles`、管理 API、发布唯一索引、Schema/稳定 field_id 门禁、Run `snapshot_version=2` 冻结和 Worker 精确执行已经实现。
|
||||
|
||||
**Schema 与 Profile 兼容治理 Review(2026-07-27)**:订单字段目录继续使用稳定 `field_id`,Schema 版本和已发布 Profile 均保持不可变。系统在 Schema 发布前只读评估 published/draft Profile,并按 `compatible / review_required / breaking` 分类:新增字段和仅 `field_code` 改名可自动继承;validator、枚举、证据策略、抽取说明、业务用途和置信度变化要求管理员确认;字段删除/停用,以及 scope、类型、集合模式、分类、必填、normalizer、comparator、坐标来源变化属于破坏性影响。存在 published breaking 影响时,发布接口要求显式确认;历史 Run 始终保留原 Schema/Profile 快照,不被新版本改写。
|
||||
|
||||
破坏性 Profile 通过结构化局部迁移创建下一草稿,不要求重做整份模板。每个受影响字段只能选择作用域、类型和坐标来源能力兼容的其他稳定字段,或解除绑定并保留原区域待重新绑定;原字段不能替代自身,同一布局不能重复绑定目标字段。迁移草稿复制 annotation/training 样本,不继承 blind-test 批准,并持续标记为需重新盲测;存在未绑定区域时禁止发布。运行时仅自动投影非 breaking 的已发布 Profile 到当前 published Schema,并按 `field_id` 更新名称,breaking Profile 不参与当前版本自动匹配。
|
||||
|
||||
**本阶段 Dify 配置**:无需修改。兼容评估、发布确认、字段迁移、Profile 投影和历史冻结均由 HXOPS 完成,不向 Dify 增加字段映射、迁移 Tool、Prompt 或画布节点。
|
||||
|
||||
**Profile 可视化治理 Review(2026-07-22)**:管理端 `/admin/shipping-order-document-profiles` 只展示 ready MinerU 样本文档及展开后的 cell 文本,不返回 HTML、bbox、全文或结构指纹。管理员选择表格、表头行、数据起始行、行结构和 Schema 明细字段;页面只允许 `direct` 与已注册 `temp_internal_parts` 解析器,阻止同一目标字段跨列重复映射。结构指纹始终由后端从持久化 HTML 计算,浏览器提交值无效。草稿支持乐观锁更新、发布、删除;不可变版本支持复制为下一草稿和退役。复制后的草稿必须选择样本重新确认映射才能更新,不允许直接编辑 JSON、HTML、正则、脚本或结构指纹。
|
||||
|
||||
**多行表头配置 Review(2026-07-23)**:`header_row_index` 明确表示最后一条表头物理行,表头区域固定为 `0..header_row_index`,运行解析从 `data_start_row_index` 开始,不需要新增数据库字段。模板页按逻辑列合并表头区域内的非空文字并去除 rowspan/colspan 展开造成的重复标签,以独立虚拟列头映射区维护字段;所有表头物理行统一高亮,不再要求管理员只在最后一行表头上选字段。切换样本或表格会清理上一表的多物理行坐标状态,可直接配置的表格始终显示普通预览。多行表头与一条明细占多条物理行是两个独立配置维度,前者不得进入 `subrow_layouts`。
|
||||
|
||||
**模板样本治理与版本识别 Review(2026-07-23)**:样本文档按上传时间倒序显示,并在选择器中标明文件名、时间、解析状态和表格数,可按文件名搜索;同一 `profile_code` 的 `published` 版本显示“当前生效”和发布时间。模板页上传的专用样本 (`purpose=order_document_profile_sample`) 仅在已解析完成、未被独立盲测引用且其资产未被其他业务引用时允许删除;删除同时回收源文件和布局结果。历史 `shipping_notice` 业务附件及盲测证据始终不可在模板页删除。Profile 当前未持久化“创建时样本”外键,因此不得声称可以按该不存在的关系阻止删除;如需这一级审计保护,须另行设计字段、迁移和历史数据策略。
|
||||
**模板样本治理与版本识别 Review(2026-07-23)**:样本文档按上传时间倒序显示,并在选择器中标明文件名、时间、解析状态和表格数,可按文件名搜索;同一 `profile_code` 的 `published` 版本显示“当前生效”和发布时间。模板工作台样本下拉只查询页面专用上传样本 (`purpose=order_document_profile_sample`),普通 `shipping_notice` 业务附件不显示也不可从该入口维护。专用样本仅在已解析完成、未被独立盲测引用且其资产未被其他业务引用时允许删除;删除同时回收源文件和布局结果。Profile 当前未持久化“创建时样本”外键,因此不得声称可以按该不存在的关系阻止删除;如需这一级审计保护,须另行设计字段、迁移和历史数据策略。
|
||||
|
||||
**表头污染与坐标重建 Review(2026-07-22)**:若样本表头混入明显订单行值(例如 `ITEM NO 00010`),预览返回稳定诊断 `order_profile_header_contaminated_by_data` 并标记不可建 Profile;服务端也拒绝从该表创建草稿,避免浏览器绕过。Profile 页面不是手工修复原始网格的入口。对有 PDF 原生 glyph 坐标且已人工确认列锚点的文档,`coordinate_table_reconstruction` 仅输出 `needs_review` 候选:以 x-overlap/唯一中心距离归属列,以字体高度自适应 y-band 判断新视觉行,内容形态与相邻行连续性只作辅助;无强行号的行只能是续行或复核,`** Item deleted **` 只能附着前一强锚定明细。候选保留 glyph 索引,坐标不足、列归属并列或删除行无前序明细时一律复核,绝不自动接受、发布 Profile 或进入履约。
|
||||
|
||||
@@ -1072,7 +1078,8 @@ GET /api/admin/shipping-order-schema/published-contract
|
||||
# SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
# SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
# SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
# 真实货代上传 RPA 尚未完成,默认 false;仅 mock 或已接入正式上传 Driver 后再开启。
|
||||
# 真实上传 Worker 默认关闭。先配置 URL、文件/提交/成功 selector,并在非生产环境 dry-run。
|
||||
# 只有成功标识出现才回调成功;最终提交还须由 Worker 的二次确认开关控制。
|
||||
# SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
# 当已发布 Excel 模板未定义 filename_pattern 时使用;模板规则优先。
|
||||
@@ -1814,7 +1821,7 @@ docker compose --env-file .env.prod exec -T hxops-backend \
|
||||
sh -lc 'test -d /mnt/hxops-rpa-prod-data/inventory_triggers && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
|
||||
```
|
||||
|
||||
再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=prod`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。正式上传 RPA 尚未完成时,继续保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`。
|
||||
再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=prod`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。真实上传由配置驱动的 Playwright 流程执行:DSV 已确认从 Portal 首页 `My Applications > Upload Tool`(回退 `Apps > Upload Tool`)进入 `WMS Upload Tool > Upload`,由 `SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` 指定受控 Portal 入口;`Browse` 的真实文件 input 是 `#file2`,选择文件后的真实提交控件为 `button.upload-button:has-text("Process File")`,DSV 默认使用这两个 selector。成功证据来自 `History`:同名文件行必须同时具有绿色 `em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #`,该 Reference 写入货代回执号;任一缺失均回调失败。其他站点使用受控上传 URL;必须设置文件/提交/成功 selector,并保持 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false`、`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false`,直到测试环境完成非生产 dry-run 且确认成功标识、回执语义。缺少配置、浏览器异常或未出现成功标识均回调失败,绝不把文件已选择视为上传成功。CRANE 上传页尚未确认,Worker 必须失败而不得复用 DSV 路径。由于尚未获得货代真实提交测试授权,生产仍须保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,以人工上传回执作为唯一可用生产路径。
|
||||
|
||||
计划维护或紧急停止时,先暂停正式库存 RPA 排程并等待/处理运行中的 trigger,再停止 Windows prod Worker,最后按需停止容器:
|
||||
|
||||
@@ -2115,7 +2122,9 @@ API 层
|
||||
|
||||
#### Dify 手工配置说明(阶段 1)
|
||||
|
||||
本阶段不由 HXOPS 修改 Dify 画布或 Tool。业务管理员仅需核对现有 Workflow 继续按照 HXOPS 发布契约返回 Observation:`reservation_id`、`part_number`、`qty` 均为 Line 值,必须附当前文档可验证的 quote 与 document ID;不得回传 `inventory_source_hint_default` 或 `shipping_method`,`inventory_source_hint` 缺失时留空。Dify 不判断重复 Reservation、不选择库存源、不冻结订单、不生成 Excel 或上传;这些结果全部由 HXOPS 门禁裁决。
|
||||
本阶段不由 HXOPS 修改 Dify 画布或 Tool。当前已发布 Schema V2(完整识别配置)包含 55 个启用字段:每个字段均维护了中文显示名、无冲突的中英文表头别名、业务说明、抽取指令和 `pdf_coordinate` 坐标识别许可。业务管理员应使现有 Workflow 仅依据运行时下发的 published contract 返回允许的 Observation;已启用字段在原文存在时均应返回当前文档可验证的 value、quote 与 document ID,15 个必填字段(Header:客户 PO、Bill 客户/地址、Ship 客户/地址、币种;Line:项次、内部料号、客户料号、预约单号、数量、单位、单价、含税金额、库存源线索)缺失时不得编造。
|
||||
|
||||
`reservation_id`、`part_number`、`qty` 和 `inventory_source_hint` 均为 Line 值;其中前三项是履约能力字段,必须附当前文档可验证的 quote 与 document ID。`pdf_coordinate` 仅允许 HXOPS 的订单文档 Profile 使用,不是 Dify 的输出来源或画布变量。不得回传 `inventory_source_hint_default` 或 `shipping_method`;Dify 不判断重复 Reservation、不选择库存源、不冻结订单、不生成 Excel 或上传,这些结果全部由 HXOPS 门禁裁决。
|
||||
|
||||
#### 字段能力绑定与履约策略(阶段 2)
|
||||
|
||||
@@ -2165,3 +2174,16 @@ API 层
|
||||
- Dify 只负责候选抽取;后端负责 evidence 校验、EML/PDF 交叉裁决、客户主数据匹配、歧义判断与最终确认。
|
||||
- 客户可配置识别规则不新增 Dify Tool 或画布修改。业务管理员在订单 Schema 发布后,只需确认 Dify 仍按 published contract 的稳定 `field_id` 回传 Header Observation、原文 quote 和 document ID;不得在 Dify 中匹配客户或站点。完整配置步骤和验收见 [customer_identity_rules_plan.md](customer_identity_rules_plan.md)。
|
||||
- Reservation ID 使用普通文本规则;Dify 仍须按字段识别说明排除 Allocation ID、UUID 和内部主键,后端安全校验作为兜底。
|
||||
### 订单文档模板坐标标注工作台
|
||||
|
||||
- PDF 工具栏采用左侧编辑操作、中间上一页/页码/下一页、右侧缩放操作的固定布局;页码输入支持大页数文档直接跳转,页面标记只按精确页码渲染。
|
||||
- 历史 `all_pages` 草稿缺少原始页码时按第 1 页恢复,重新保存后统一写入 `exact_page + page_no`,避免第 1 页标记泄漏到第 2 页。
|
||||
- 自动标记优先从 PDF 原生文字层补齐字符坐标与页面尺寸,仅在原生文字层为空时调用 OCR;补证结果仍属于待人工复核证据。
|
||||
- 物理行和字段框描述可重复应用的行版式:横向边界用于字段取值;一个物理行包含多条视觉子行时,系统使用首条 `line_no` 锚定明细的真实字符坐标,将字段框校准到实际视觉 band(未标注的描述/备注行仍计入序号),再把同一纵向字段组按严格单调顺序对齐到后续明细。记录出现额外换行时,以 X 命中、注册解析器和有限字段形态辅助选择;最佳候选不唯一时字段留空并记录 `coordinate_profile_field_band_ambiguous`,禁止静默猜测。该机制避免父框留白、行距变化和可变换行造成错位,也防止料号尾数污染数量、单位或日期;覆盖父行全高的旧字段框和多 `row_offset` 模板继续按原兼容链路解析。
|
||||
- 翻页时只选择当前页表格;当前页没有表格时清空表格与局部候选上下文,禁止复用上一页坐标证据。
|
||||
- 局部候选可返回多条逻辑明细;右侧按“候选 → 字段清单”展示,参与当前标注的字段统一按绑定 Schema 顺序排列,字段名表头不计入候选条数。
|
||||
- 表头框可显式绑定当前冻结 Schema 字段;“匹配表头”使用当前未保存画布定义和整页字符坐标,仅返回精确别名建议。管理员确认后才写入绑定,任何建议都不得自动覆盖人工选择。
|
||||
- 自动标记只在画布生成可编辑的 `header_field` 列头区域;同一视觉行通过内部 `parentId` 分组,保存时取各字段坐标并集自动生成 `header_layouts[].region`,无需管理员维护整行表头框。表头字段才允许绑定 Schema 并写入 `header_layouts[].field_regions`,未绑定列保存重开后仍按父布局恢复。
|
||||
- 已确认表头可按横向覆盖关系为其他页面的未绑定明细字段提供列语义建议;覆盖不足或多个不同字段竞争时保持未映射。表头证据不直接读取订单值,最终取值仍由物理行内字段区域完成。
|
||||
- 表头页可以出现在数据页之后:跨页语义只比较标准化 X 区间,不依赖页序,也不传播表头页的绝对 Y。若同一表头列在数据区包含多条纵向子字段(例如客户料号与内部料号),仍由数据页物理行内的视觉子行序号区分,后置表头不得替代数据页 Y 结构或自动覆盖人工绑定。
|
||||
- 嵌套标注采用固定语义层级:明细字段高于物理行容器,表头只展示列级字段,不显示内部表头行容器。物理行内部不吞掉字段点击,管理员通过物理行标签、边缘或已选中的缩放手柄操作父区域。
|
||||
+15
-2
@@ -15,7 +15,12 @@
|
||||
- 文档级订单抽取优化阶段 5 已完成:HXOPS 按唯一 PO 或 `(part_number, reservation_id)` 强身份跨文档合并,保留所有 Observation 并将值冲突交动态 Schema 裁决;弱身份不误合并。单元部分失败时成功结果继续提交,Run 转 needs_review。
|
||||
- 文档级订单抽取优化阶段 6 已完成:支持模型单元预算、Provider 进程并发上限和短期熔断;管理员诊断可查看脱敏单元状态/尝试/耗时/错误码并保留访问审计,用户端不泄露内部信息。
|
||||
- 文档级订单抽取优化阶段 7 已完成工程门禁、但质量验收延期:自动建单默认关闭,影子模式完整落 Candidate/证据但零 Task;只有当前 Schema 的达标质量批次和不同账号双角色批准全部满足后才可开启。人工真值、100 个影子 Run、20 个测试环境 Run 与 Dify 实配尚未验收,因此不得宣称阶段完成或达到 95%。
|
||||
- MinerU + 订单文档 Profile 运行基础已实现:Intake 持久化 Document 后创建独立版本化布局 Job,MinerU `pipeline` 不再阻塞 Intake;布局保存 parser revision/checksum/大小/质量/lease,失败版本不覆盖当前成功版本。版本化 Profile 绑定不可变 Schema 和稳定字段 ID,Run 冻结完整发布快照。唯一精确模板表且完整具备 `part_number + qty` 时由后端确定性解析并跳过该附件 LLM;模板级 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 合法,零 Qty 行删除。多表/多 Profile/结构漂移/Provider 失败均安全回退,布局 HTML 和坐标不进入 Dify。
|
||||
- 订单坐标 Profile v2 阶段 1 已完成并通过工程 Review:模板定义由静态锚点、相对表区、独立表头/明细物理行、字段区域、受控解析器、排除/终止和跨页规则组成;字段绑定冻结 `field_id + field_code`,并必须获得 Schema 对 PDF/OCR 坐标来源的显式授权。Profile 保存模板模式、训练样本计数和无正文匹配摘要;训练/标注样本、盲测样本、区域/字段绑定、草稿、执行、批准、发布/退役均追加无敏感审计。旧 HTML 网格行号/固定列定义不再允许保存,历史冻结 v1 仅保持只读回放;运行期唯一匹配、坐标解析和质量门禁将在后续阶段接入。
|
||||
- 订单坐标 Profile v2 阶段 2 已完成受控预览接口:PDF 按页低清 PNG 使用 Redis 短时单用途授权并禁止缓存;页面文本候选、OCR 触发和局部重建均要求 Profile 已绑定样本,且不返回对象存储 URL、永久 Token、原始 HTML 或整份坐标 JSON。EML 继续只使用既有白名单清洗后的文本/表格候选。
|
||||
- 订单坐标 Profile v2 阶段 3 已完成并通过工程 Review:管理端已替换为画布与配置同屏的桌面工作台,PDF 按页按需加载,区域支持选择、拖动、右下角缩放、撤销/重做和未保存离开保护;多个物理行按 `main + continuation` 连续保存,字段明确归属到行,版本历史收进右侧抽屉。页面与局部候选均不接触存储地址、HTML 或原始坐标。
|
||||
- 订单坐标 Profile v2 阶段 4 已完成并通过工程 Review:表头物理行独立于明细布局,表头字段区域可以绑定当前 Schema 字段。后端仅以 Schema 的唯一精确别名提供待确认建议;歧义、位置接近和缺失字段均保持未映射,建议永不自动覆盖人工绑定。
|
||||
- 订单坐标 Profile v2 阶段 9 已完成工程 Review:草稿可建立盲测集并显式添加训练样本;盲测样本在写入时即拒绝复用 annotation/training 文档。发布前强制训练样本、独立样本数量、至少一份多明细真值及跨页续页覆盖;批准套件随发布事务从草稿定义 hash 提升为正式 checksum,Run 仅认正式凭证。工作台提供人工真值 JSON、训练样本、执行和批准入口,四语言文案齐全;Dify 不参与此配置。
|
||||
- 订单 Schema/Profile 兼容治理已实现:稳定 `field_id` 支撑 `compatible / review_required / breaking` 三等级影响评估;Schema 发布前展示 published/draft 模板影响,published breaking 需显式确认。兼容模板运行时按当前 Schema 自动更新字段名称;破坏性字段使用受控候选或解除绑定保留坐标创建局部迁移草稿,复制训练/标注样本但不继承盲测批准,重新盲测后方可发布。历史 Run 保留原版本,Dify 无需修改。
|
||||
- PDF 模型输入优先使用 MinerU 分页文本块与表格 TSV,保留表头和行列关系;MinerU 不可用时回退原 `extracted_text`。Dify Manifest 仅携带紧凑纯文本,不包含 HTML、bbox、task 原响应或内部证据标识。
|
||||
- 订单文档 Profile 可视化治理已实现:管理员从 ready MinerU 样本文档选择表格、表头结束行/数据起始行和受控列映射;多行表头按逻辑列合并为虚拟列头后统一映射,并与明细多物理行版式独立配置。切换样本会清理旧坐标状态,避免配置区消失。结构指纹仅由后端计算;支持草稿更新、发布、删除、新版本复制和退役,重复目标字段在前后端阻断;业务管理员无需编辑 JSON、HTML、正则或脚本。
|
||||
- 坐标订单模板的逻辑明细重建已实现:数据页表头不完整时使用稳定虚拟表头;管理员确认相对列边界和固定字段映射后,系统按 x/y、字段格式和同行顺序辅助归列,合并多条物理续行,回写 `Item deleted`,在合计/说明区终止,并在模板页显示有效/删除明细及来源物理行。结果继续保持人工审核和盲测门禁,不直接提升为 accepted 履约证据。
|
||||
@@ -646,5 +651,13 @@
|
||||
| 订单抽取紧凑结构化候选 | 已实现 / 质量验收延期 | 唯一 Manifest、Run 冻结、无 HTML/bbox/token 泄漏、accepted 字段锁与完整表零 Provider;人工真值及 95% 指标暂缓。 |
|
||||
| 订单抽取 L6 证据裁决与诊断 | 已实现 / 质量验收延期 | Observation 证据引用、纯文本无 cell 转复核、同 Document 强身份关联、冲突阻断、Candidate/UI 原因码和脱敏管理员追溯率诊断。 |
|
||||
| 订单抽取 L7 启用准备 | 工程完成 / 阶段未验收 | 删除 Profile/纯文本零 Provider;自动建单要求当前 Schema 的已批准质量批次,并冻结到 Run、Worker 再核验。人工真值延期时无批准批次可选,自动建单保持关闭;影子 Run 和实际 Dify 验收尚缺。 |
|
||||
| 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布 Profile 与自动建单资格分离;至少 3 份独立样本全通过、管理员批准且 checksum 未漂移时,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 |
|
||||
| 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布前必须存在训练样本;盲测与 annotation/training 完全独立,常规模板至少 3 份、无表头至少 5 份,包含多明细及所需跨页续页样本;全通过、批准并原子提升到正式 checksum 后,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 |
|
||||
| 订单客户指纹与 Snapshot 绑定 | 已实现 | Bill-to/Ship-to 原文与正式客户分层保存;Bill-to 人工确认须有理由并生成规则版本化指纹,冻结只采纳该确认结果并固化客户简码。 |
|
||||
- 订单文档模板支持大页数 PDF 的上一页/页码跳转/下一页导航、顶部撤销/重做/复制/删除/保存/缩放工具栏、可折叠紧凑标注工具轨,以及按页隔离的区域标记;复制支持 `Ctrl/Cmd+D`,删除支持 `Delete/Backspace`,配置侧栏不再重复放置操作入口。
|
||||
- 订单文档模板自动标记支持原生 PDF 坐标优先补证、扫描件 OCR 兜底、页面尺寸修复和可重复多物理行版式候选重算。
|
||||
- 订单文档模板自动标记只展示独立 `header_field` 表头字段,不再产生可见、可编辑的整行表头框;同一视觉行由内部布局 ID 分组,保存时按字段坐标并集自动生成后端表头区域。
|
||||
- 订单文档模板草稿允许字段区域暂不绑定 Schema,不把正常标注中间态当成保存错误;发布门禁仍要求完整有效绑定。自动标记同时从首条明细前的独立视觉行生成待复核表头框,并兼容 PDF 字符层将 `ITEM NO`、`UNIT PRICE` 合并为紧凑文本;表头与业务值真正混行时仍保持人工复核。
|
||||
- 订单文档模板局部候选支持多明细分组展示,并按绑定 Schema 字段顺序逐项核对识别值与来源物理行。
|
||||
- 订单文档模板支持表头到 Schema 的显式确认绑定,并以已确认表头为跨页字段列提供不自动覆盖的语义建议;字段区域保持最终数据提取真相。
|
||||
- 订单文档模板支持父物理行内视觉 band 校准:运行时按 `line_no` 切分重复明细,以首条样例真实字符将字段框校准到实际 band,并将纵向字段组单调对齐到后续明细;未标注描述行和可变换行不会压缩字段序号,歧义候选留空复核。表头即使位于后续页面也可提供与页序无关的 X 列语义建议,但不传播绝对 Y、不自动覆盖人工绑定,旧整高字段和多物理行模板保持兼容。
|
||||
- 订单文档模板样本下拉仅显示模板页专用上传样本;普通发货历史附件不再混入模板维护入口。
|
||||
+14
-4
@@ -1,5 +1,11 @@
|
||||
# Agent 内部执行器注册补充(2026-07-21)
|
||||
|
||||
## 订单坐标模板 v2 工作台与表头建议(阶段 3-4)
|
||||
|
||||
- 工作台仅消费 Profile 绑定样本的短时单用途页面 PNG 和紧凑文本候选;翻页重新签发授权,浏览器不持有对象存储 URL、PDF 原件、HTML 或整份坐标证据。
|
||||
- 前端将几何状态转为 v2 相对区域,多个 `line_layouts` 以连续 `row_offset` 持久化;撤销/重做仅记录真实编辑手势。
|
||||
- 表头建议服务在服务端读取冻结字符坐标,将已配置相对区域投影到页面,并以启用且允许坐标来源的 Schema 精确别名匹配。歧义结果为未映射、状态固定 `needs_review`,不写回 Profile。
|
||||
|
||||
后台长任务能力采用“用户入口 Agent → Runtime Binding → internal_executor → Dify Workflow”模型。
|
||||
`effective_role` 由 `exposure_mode` 只读派生;内部执行器不进入用户授权和聊天呈现,必需能力绑定存在即启用。
|
||||
用户侧 API 以 `exposure_mode=workspace` 为统一信任边界:授权、公开列表、工作台、收藏、默认应用、FAQ、指南、详情和普通 Chat 均排除 internal;管理员通过用户入口同样不能绕过。内部执行器仅供管理配置和后台 Runtime Binding 执行。
|
||||
@@ -12,10 +18,11 @@
|
||||
- 原生 PDF 候选使用已有 `pypdfium2` 提取字符 bbox,并只为 MinerU 表格区域生成稳定 token。HTML cell 优先做唯一/连续/非重叠字符对齐;失败时仅允许 OpenCV 多参数有框网格共识,并由原生文本 100% 验证。结果以内嵌 `shipping_document_layout.v1` 保存且固定 `needs_review`;parser revision 已提升为 `v2`,使历史 v1 结果不会静默复用。
|
||||
- L3 将 parser revision 提升为 `v3`。扫描 PDF 直接适配 RapidOCR 多边形坐标,OCR cell 必须同时通过 OpenCV 网格和全部非空 cell 文本一致性;EML HTML 只保留清洗后的 table DOM,并用逻辑网格表达 rowspan/colspan。OCR/HTML 均固定 needs_review,原始 OCR 响应、页面图、主动 HTML 和临时表格片段不入库或 Dify。
|
||||
- L4 新增 layout.v1→冻结 Schema 映射层,复用现有 HTML Grid 安全规则并保留真实 cell/token evidence。Run snapshot 升级为 v3并冻结内部 `layout_schema_candidates`;跨页只读显式 continuation。Manifest 强制剥离布局及映射候选,needs_review 不参与当前确定性执行。
|
||||
- 订单文档坐标 Profile 使用冻结相对列边界、列字段编码和新行起始列生成稳定虚拟表头,避免数据页残缺/后置表头导致结构指纹漂移。重建器先按字体高度形成 y-band,再把相邻字符组成文本片段,以 x-overlap 为主、字段格式和同行顺序为辅归列;物理 `continuation` 按列合并到最近 `data`,`deleted` 回写最近明细,`summary` 终止数据区。无逻辑明细的纯表头页不算 Profile 命中。
|
||||
- 多行明细使用 `subrow_layouts[]` 表达任意连续 N 行版式:`row_offset=0` 固定为含 `line_no` 的 main 行,`row_offset=1..N-1` 为 continuation;offset 必须从 0 连续且唯一。每行独立保存边界和字段编码,重叠横坐标不共享列语义;重建时按当前明细内相对行序选取对应布局,超过最后已配置行时继续使用最后一行布局。
|
||||
- 订单坐标 Profile v2 的真相是 `document_match + table_regions[]`:每个表区保存相对区域、独立 `header_layouts[]`、连续的 `line_layouts[]`、字段区域到稳定 `field_id + field_code` 的绑定、受控解析器、排除/终止和跨页规则。表头只参与建议、校准和匹配,不能决定字段;所有区域为 `0..1` 相对坐标,越界、正面积重叠、重复明细字段和错序物理行由后端拒绝。
|
||||
- 多行明细使用 `line_layouts[]` 表达任意连续 N 行版式:`row_offset=0` 固定为 main,后续为 continuation;每行独立保存区域和字段区域。字段只可绑定 Schema 显式允许的 `pdf_coordinate`/`ocr_coordinate` 来源,字段 ID 由后端重写,浏览器不能提交自由正则、脚本或 Prompt。
|
||||
- 坐标版式建议先按自适应 y-band 分组物理行,再以左侧行号识别逻辑明细起点;相同 `row_offset` 的文本片段按相对 x 中心聚类,以相邻中心中点生成边界。接口只自动绑定确定性的 `line_no`,其他字段仍由管理员根据列示例确认,建议状态固定为 `needs_review`。
|
||||
- `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、精确表头结构指纹、固定列规则、稳定目标 field_id、checksum 和乐观锁。同一模板只允许一个 published 版本;Run `snapshot_version=2` 冻结全部匹配 Schema 的 published Profile 与 Document 布局快照,后续发布/退役不会改变排队中的运行。
|
||||
- `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、v2 定义校验值、完整定义、checksum 和乐观锁。同一模板只允许一个 published 版本;后续阶段的 Run 将冻结唯一匹配结果、Profile checksum、坐标证据和完整定义,发布/退役不会改变历史运行。
|
||||
- Schema 与 Profile 使用稳定 `field_id` 解耦版本:发布前评估 `compatible / review_required / breaking` 影响,published breaking 必须显式确认。非 breaking Profile 在运行快照中按目标 Schema 自动重映射 `field_code`;breaking 字段只能迁移到作用域、类型和坐标来源兼容的其他字段,或解除绑定并保留区域。迁移草稿不继承盲测批准且未绑定区域禁止发布,历史 Run 继续读取原冻结版本;该治理不改变 Dify 契约。
|
||||
- **货代字段与履约冻结(阶段 1)**:系统事实由代码/数据库固定;订单字段区分 57 个可按版本启用的标准目录与自定义字段,均以稳定 `field_id` 冻结。`SHIP_AVAILABLE_ROLLING_V1` 是当前唯一代码注册策略,只要求 Line `reservation_id:string`、`part_number:string`、`qty:decimal > 0` 和已确认订购客户;不要求全部 57 个字段,不新增 Header `inventory_source_hint_default` 或 `shipping_method`。`inventory_source_hint` 只可作为可选 Line 路由线索,库存路由只读取冻结 Snapshot。
|
||||
- **货代字段能力与策略(阶段 2)**:`ShippingFulfillmentPolicy` 独立版本化,字段能力只允许代码注册并按稳定 `field_id` 绑定;scope/value_type 不匹配、缺少最低能力或未发布策略均 fail closed。冻结 Snapshot 保存策略定义与 checksum,履约消费者不读取可变 Schema 的 `business_purpose`;自定义字段只要类型和作用域符合即可被策略受控绑定。
|
||||
- **Reservation 注册**:`shipping_reservations` 通过单列唯一 `reservation_id` 强制全局唯一,并持久化标准化 PO;PO 仅 trim + uppercase,保留前导零和中间字符。首次注册可缺 PO,但 Reservation 已注册后的重复记录缺 PO、不同 PO 或同快照重复均阻断;同 PO 内容变化返回可审计前后差异并等待人工确认;有效 Artifact 或上传后禁止直接修订。Dify 不参与这些判断,继续只返回字段 Observation。
|
||||
@@ -133,6 +140,7 @@
|
||||
- `ShippingOrderExtraction` 以 `schema_version_id` 锁定运行契约,新增 `input_snapshot_json` 冻结参与裁决的输入文档;版本使用查询由 `(schema_version_id, created_at)` 索引支持。管理员审计 API 返回保存的 LLM、规范化、校验、Observation、Decision 和 FieldValue,不回读当前字段目录。
|
||||
- Schema 发布前反向检查 draft/published 路由规则、库存解析 Profile 与 Excel 模板;新版本不得移除仍被运行配置引用的稳定字段。
|
||||
- `ShippingOrderExtraction` 锁定 Schema 版本和输入快照;`Observation/Decision/FieldValue` 分别承载来源观察、后端裁决和类型化下游投影。
|
||||
- 订单文档 Profile 以稳定 `field_id` 作为字段身份;新发布 Schema 会按字段作用域、类型、采集方式、必填性、归一化/比较器和坐标来源做兼容性判定。兼容变更(字段改名、别名/顺序或新增可选字段)自动继承并在运行快照中重映射 `field_code`;删除、禁用、作用域/类型/解析契约变化只阻断受影响 Profile,不要求整份模板重新标注。历史 Run 仍冻结原始 Schema 版本和完整定义。
|
||||
- 阶段一仅建立配置与数据基础;现有固定订单解析链在阶段二切换为动态 Schema 后移除,不建设长期双读兼容。
|
||||
|
||||
### 2.x 发货通知字段契约与后端裁决
|
||||
@@ -1256,5 +1264,7 @@ Dify
|
||||
- L6 Observation 通过 `evidence_ref + evidence_metadata_json` 保存文本、邮件头或 layout cell 证据身份。旧纯文本表格解析器只做候选检测,不再进入 verified Observation;accepted layout 仅按同 Document 强身份关联。
|
||||
- L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。
|
||||
- L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。
|
||||
- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。Profile 仅在至少 3 份样本全通过、管理员批准且当前 checksum 一致时获得 `auto_create_approved`;Run 创建冻结该事实。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。
|
||||
- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存草稿/发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。发布事务先以草稿定义 hash 校验至少 1 份训练样本、与 annotation/training 完全独立的盲测样本、常规模板至少 3 份(无表头至少 5 份)、至少 1 份多明细真值及跨页声明对应的 `continuation_of` 样本;全量通过并批准后,事务内将套件/执行记录的草稿 hash 原子提升为正式 Profile checksum。Run 创建只冻结正式 checksum 的 `auto_create_approved` 事实。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。
|
||||
- **坐标 Profile 治理审计**:`shipping_order_document_profiles` 增加 `template_mode`、`training_sample_count` 与无正文 `match_strategy_summary_json`;`shipping_order_document_profile_samples` 仅绑定 Document/Table/角色,`shipping_order_document_profile_audits` 只记录对象身份、事件和计数/checksum 摘要。样本、区域、字段绑定、盲测和版本事件使用同一追加式审计表,禁止保存锚点文本、坐标、PDF、HTML、MinIO URL 或凭据。
|
||||
- **受控坐标预览**:页面授权写入 Redis,key 为随机令牌且 TTL 120 秒;每个 token 固定管理员、Profile、Document、page_no,并通过 `GETDEL` 原子消费。Redis 不可用时预览 fail-closed。PDF 只在后端渲染低清单页 PNG;文本候选和局部预览按 Profile 样本关联再次鉴权,响应设置 `Cache-Control: private, no-store`。OCR 只能经绑定样本的显式管理员请求生成,EML 复用 HTML 白名单清洗结果且不渲染可执行 DOM。
|
||||
- **订单客户指纹与冻结门禁**:`ShippingOrderCustomerMatch` 保留 Bill-to/Ship-to 原文、标准化组件、`order-customer-fingerprint.v1` 指纹、候选快照和确认理由。只有 `bill_to.status=confirmed` 且存在客户/简码/指纹/规则版本时 `order_freeze_service` 才冻结 Snapshot;冻结服务不接受外部 `customer_id` 或 `customer_short_code`。Snapshot 的 `rule_versions_json.ordering_customer` 保存匹配 ID、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。
|
||||
@@ -14,6 +14,10 @@
|
||||
|
||||
## 2. 功能测试矩阵
|
||||
|
||||
| 功能分类 | 功能子项 | 功能描述 | 测试代码撰写要求 | 测试输入数据 (示例) | 预期测试输出 (示例) |
|
||||
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||
| **发货通知** | **订单坐标 Profile v2 工作台与表头建议** | 画布按页受控加载,物理行与字段区域可编辑;表头建议只使用唯一 Schema 别名。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile.py`、前端 `vue-tsc`/build。 | 多页 PDF、10 条物理行、50 个字段区域、重复 `Part No.`、缺失表头、拖动/缩放/撤销。 | 单页令牌不复用;保存为连续 main/continuation 布局;歧义表头不自动绑定;建议固定 `needs_review` 且不泄露 bbox/HTML。 |
|
||||
|
||||
| 功能分类 | 功能子项 | 功能描述 | 测试代码撰写要求 | 测试输入数据 (示例) | 预期测试输出 (示例) |
|
||||
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||
| **用户认证** | **用户注册** | 新用户通过填写表单提交注册申请,状态默认为 `pending`。需校验手机号、工号唯一性。 | 模拟 POST 请求 `/api/user/register`,验证必填字段缺失、字段重复等异常场景。 | `{ "username": "test_user", "password": "pwd", "email": "test@e.com", "real_name": "张三", "employee_id": "EMP001", "phone_number": "13800000000" }` | HTTP 201 Created; 返回 `{"id": 1}`;数据库中状态为 `pending`。 |
|
||||
@@ -56,12 +60,12 @@
|
||||
| **发货通知** | **文档版面结构化 L4 冻结 Schema 证据映射** | layout.v1 Table 直接按 Run 冻结 Schema 映射,字段证据必须引用真实 cell/token;跨页只接受显式 continuation。 | `test_shipping_document_layout_schema_mapping.py`、`test_shipping_document_layout_html_table.py`、`test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py` | 后置表头、重复目标列、Qty=0、真实 cell/token/evidence_ref、显式/缺失 continuation、Run 后 Schema 漂移、Manifest 泄漏 | 映射复用既有安全规则;重复列全 ambiguous;零 Qty 删除;Run v3冻结候选不漂移;needs_review 只标 candidate且不进 Dify/确定性执行。人工真值延期时不判真实字段映射准确率,但错误自动接受数必须为 0。 |
|
||||
| **发货通知** | **订单文档模板 Profile 纯契约** | 以表头网格精确结构指纹选择固定列规则,允许模板级字段语义覆盖全局 Schema;只运行注册解析器。 | `test_shipping_order_document_profile.py` | `Part Number -> customer_part_number`、`Vendor Item# -> part_number`、复合料号 cell、零 Qty、结构漂移、MinerU 行关系丢失、自由解析器注入 | 精确命中时模板映射原样生效;零 Qty 行删除;结构变化不做相似匹配;行关系丢失显式阻断;未知解析器或非法目标字段拒绝保存。 |
|
||||
| **发货通知** | **订单文档 Profile 发布与运行锁定** | Profile 绑定不可变 Schema/稳定 field_id,版本化发布;Run 冻结完整 Profile 与 MinerU 紧凑布局,Worker 只执行唯一精确匹配。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_migration.py`、`test_shipping_document_layout_runtime.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py` | 并发草稿覆盖、新版发布、字段退役、Provider 失败、多附件预算、多表/多 Profile、零 Qty、Decimal JSON、布局 HTML 泄漏 Dify、Run 后配置变化 | 乐观锁与单 published 唯一索引生效;字段引用阻断退役;Run 快照不漂移;Provider 失败安全回退;唯一完整表跳过 Dify;多表不自动合并;HTML/bbox/field_code 不进入 Dify;零 Qty 删除。 |
|
||||
| **发货通知** | **订单文档 Profile 可视化治理** | 管理员只从 ready MinerU 样本选择表格、行和受控字段/解析器,完成草稿、新版本、发布与退役;浏览器不持有可伪造运行契约。 | `test_shipping_order_document_profile_service.py`、`orderProfileForm.utils.spec.ts`、`shippingConfigNavigation.spec.ts`、前端生产构建 | 普通用户访问、伪造结构指纹、HTML/bbox 泄漏、越界行、重复目标字段、复合解析器冲突、过期 lock、新版本重配、unsupported 行结构、`ITEM NO 00010` 混入表头 | 普通用户拒绝;预览仅 cell 文本;指纹后端计算;表头污染返回稳定诊断并拒绝建草稿;越界/过期锁/重复字段阻断;只允许注册解析器;复制草稿须用样本重新确认;无需编辑 JSON/HTML/脚本。 |
|
||||
| **发货通知** | **订单坐标 Profile v2 契约治理** | 模板以文档静态锚点、相对表区、独立表头/明细物理行、字段区域、受控解析器、排除/终止/跨页规则表达;字段绑定必须冻结 Schema field_id 且获坐标来源授权。 | `test_shipping_order_document_profile.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 坐标越界/重叠、重复字段、物理行错序、未注册解析器、浏览器伪造 field_id、未授权 PDF/OCR 来源、旧网格行/列定义、过期 lock | 后端拒绝非法几何与歧义定义;表头布局和明细布局相互独立;字段 ID 后端重写;Schema 未授权来源阻断;新 Profile 不接收 HTML 网格、行号或固定列规则;乐观锁与不可变发布版本生效。 |
|
||||
| **发货通知** | **文档版面坐标重建候选** | 在可信 PDF/OCR 字符坐标存在时自动建议动态行数、列边界和列示例;管理员确认字段后,按 x 列归属、y 视觉行、字段内容适配及同行顺序重建错误 MinerU 网格,再按动态 N 行版式合并为可审核逻辑明细。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py` | `00010/00020` 行号、料号/数量/单位边界、2/3/4/N 行版式、每行不同列数、单内容块续行、跨行重叠边界、`** Item deleted **`、TOTAL 终止、残缺/后置表头、纯表头页、列归属并列 | 建议与候选固定 `needs_review`;自动建议排除表头/合计、自动标出首行 `line_no` 并只返回相对边界/少量示例;坐标虚拟表头不依赖数据页完整表头;第 2..N 行按独立边界合并;无坐标/歧义绝不自动接受、发布 Profile 或进入履约。 |
|
||||
| **发货通知** | **坐标修复模板闭环** | 结构污染 PDF 由管理员确认列边界后重建,确认结果随 Profile 与 Run 冻结。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 表头混入首条明细、无文本层 PDF、非法边界、未确认候选、盲测与 Run 证据缺失 | 浏览器只看到候选网格;边界必须从 0 到 1 严格递增;重建固定待审核且须显式确认;Profile/Run/盲测只用冻结坐标证据,任何缺失均阻断,不回退原始错误网格或 Dify。 |
|
||||
| **发货通知** | **订单模板页样本上传** | 管理员可从订单文档模板页直接上传 PDF/EML,建立隔离样本 Intake 并复用异步预解析和布局 Job。 | `test_shipping_order_document_profile_service.py`、前端生产构建、Alembic upgrade | PDF、EML 正文 HTML、多附件 EML、非 PDF/EML、样本解析中/失败、业务 Intake 混入 | 样本 Intake purpose 固定为 `order_document_profile_sample`,不绑定会话,不创建 Candidate/Task/指纹或 Dify 调用;仅解析完成的单 Document 表格可配置 Profile;文件类型前后端均拒绝;样本状态不泄露正文、HTML 或 bbox。 |
|
||||
| **发货通知** | **订单模板样本治理与版本识别** | 样本可按文件名搜索并展示时间/状态;当前发布版本可辨识;专用样本受控删除。 | `test_shipping_order_document_profile_service.py`、前端生产构建 | 同名样本、历史业务附件、解析中样本、盲测引用、资产共享、多个版本 | 选择器标明文件名/时间/状态/表格数;同编码 published 版本标记当前生效;仅 `order_document_profile_sample` 的已解析、未盲测引用且未共享资产样本可删除;删除同步回收源文件和布局,历史业务附件及盲测证据不可删除。 |
|
||||
| **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py`、`test_agent_runtime_bindings.py` | 少于 3 样本、真值不匹配、批准后编辑、checksum 漂移、未知/多模板、Dify 不可用 | 至少 3 个独立样本全通过且管理员批准才放行;批准样本不可改;checksum 变化立即失效;唯一已批准 Profile 直接生成确定性订单,其他情形回退 Dify/人工。 |
|
||||
| **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py`、`test_agent_runtime_bindings.py` | 缺训练样本、复用 annotation/training 文档、少于 3 样本、无表头少于 5 样本、无多明细、缺跨页续页、真值不匹配、批准后编辑、checksum 漂移、未知/多模板、Dify 不可用 | 发布前至少 1 训练样本;盲测与建模样本完全独立,常规模板至少 3 个、无表头至少 5 个,含至少 1 个多明细及所需跨页续页样本;全通过且管理员批准后,草稿 hash 原子提升为正式 checksum 凭证;批准样本不可改;唯一已批准 Profile 直接生成确定性订单,其他情形回退 Dify/人工。 |
|
||||
| **发货通知** | **Workflow 结果缓存与重试** | Dify 成功后先独立保存结构化 orders;即使无 workflow_run_id,HXOPS 落库失败重试也不得再次调用 Dify。 | `test_agent_runtime_bindings.py::test_worker_caches_provider_output_and_does_not_call_dify_twice` | 首次 Provider 成功、后续 DB 暂时失败 | Dify 调用 1 次、持久化尝试 2 次,Run 最终 completed。 |
|
||||
| **发货通知** | **Provider 变更与密钥轮换** | App ID/Base URL 漂移阻断旧 Run;API Key 轮换允许旧 Run 使用新密钥继续。 | `test_agent_runtime_bindings.py` Provider drift / key rotation 用例 | 排队后修改 App ID、Base URL 或 API Key | 前两者 Run/Job failed 且不调用 Dify;密钥轮换成功完成。 |
|
||||
| **发货通知** | **Run 安全视图与事务原子性** | 用户 API 不返回正文、Provider 快照/原始结果/配置;Agent 与 binding 保存同事务。 | `test_shipping_order_extraction_runs.py`、`tests/services/admin/test_agent_service.py` | 查询 Run;创建/更新时绑定校验失败 | 响应无敏感快照;失败后 Agent 字段和 binding 均不留下半成品。 |
|
||||
|
||||
@@ -9,12 +9,17 @@ import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
CreateOrderProfileFromSampleInput,
|
||||
LegacyCreateOrderProfileFromSampleInput,
|
||||
OrderProfileSampleDocument,
|
||||
CoordinateReconstructionPreview,
|
||||
CoordinateReconstructionSuggestion,
|
||||
CoordinateReconstructionSettings,
|
||||
OrderProfileSampleIntake,
|
||||
OrderProfileSamplePreview,
|
||||
OrderProfilePreviewPages,
|
||||
OrderProfileBoundSample,
|
||||
OrderProfilePageTextCandidates,
|
||||
OrderProfileTestSuite,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '../types/shipping-order-document-profile.types';
|
||||
|
||||
@@ -80,21 +85,21 @@ export const suggestOrderProfileCoordinateReconstruction = (
|
||||
|
||||
/** 为扫描 PDF 生成 OCR 坐标证据;随后仍必须由管理员审核重建网格。 */
|
||||
export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, tableId: string) =>
|
||||
requestJson<{ document_id: number; table_id: string; source: 'ocr' }>(
|
||||
requestJson<{ document_id: number; table_id: string; source: 'pdf' | 'ocr' }>(
|
||||
'/api/admin/shipping-notice/order-document-profile-samples/ocr-coordinate-evidence', {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId, table_id: tableId }), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 由真实样本和结构化列选择创建 Profile 草稿。 */
|
||||
export const createOrderProfileFromSample = (payload: CreateOrderProfileFromSampleInput) =>
|
||||
export const createOrderProfileFromSample = (payload: CreateOrderProfileFromSampleInput | LegacyCreateOrderProfileFromSampleInput) =>
|
||||
requestJson<ShippingOrderDocumentProfile>('/api/admin/shipping-notice/order-document-profiles/from-sample', {
|
||||
method: 'POST', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 用新样本和乐观锁更新已存在草稿。 */
|
||||
export const updateOrderProfileFromSample = (
|
||||
profileId: number, payload: CreateOrderProfileFromSampleInput & { expected_lock_version: number },
|
||||
profileId: number, payload: (CreateOrderProfileFromSampleInput | LegacyCreateOrderProfileFromSampleInput) & { expected_lock_version: number },
|
||||
) => requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/from-sample`, {
|
||||
method: 'PUT', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
@@ -127,3 +132,83 @@ export const deleteOrderDocumentProfile = (profileId: number) =>
|
||||
requestJson<void>(`/api/admin/shipping-notice/order-document-profiles/${profileId}`, {
|
||||
method: 'DELETE', ...auth(),
|
||||
});
|
||||
|
||||
/** 从已发布模板按字段稳定身份创建目标 Schema 版本迁移草稿。 */
|
||||
export const migrateOrderDocumentProfileSchema = (
|
||||
profileId: number,
|
||||
targetSchemaVersionId: number,
|
||||
resolutions: Record<string, { action: 'unbind' } | { replacement_field_id: string }>,
|
||||
) => requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/schema-migration`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ target_schema_version_id: targetSchemaVersionId, resolutions }),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 为已绑定 PDF 样本申请逐页、单用途的短时预览授权。 */
|
||||
export const authorizeOrderProfilePreviewPages = (profileId: number, documentId: number) =>
|
||||
requestJson<OrderProfilePreviewPages>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId }), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 列出当前 Profile 已绑定的标注/训练样本,用于恢复工作台上下文。 */
|
||||
export const listOrderProfileBoundSamples = (profileId: number) =>
|
||||
requestJson<OrderProfileBoundSample[]>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/samples`, auth(),
|
||||
);
|
||||
|
||||
/** 为草稿显式绑定训练样本;盲测样本不经过此接口,避免与建模证据混用。 */
|
||||
export const addOrderProfileTrainingSample = (profileId: number, payload: { document_id: number; table_id: string }) =>
|
||||
requestJson<OrderProfileBoundSample[]>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/samples`, {
|
||||
method: 'POST', body: JSON.stringify({ ...payload, sample_role: 'training' }), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 读取当前页的紧凑文本候选;不包含 HTML、坐标或内部 token。 */
|
||||
export const getOrderProfilePageTextCandidates = (profileId: number, documentId: number, pageNo: number) =>
|
||||
requestJson<OrderProfilePageTextCandidates>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/text-candidates?document_id=${documentId}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 使用当前 Profile 绑定样本执行局部坐标重建候选。 */
|
||||
export const previewOrderProfileRegion = (
|
||||
profileId: number, documentId: number, tableId: string, definition: ShippingOrderDocumentProfile['definition'],
|
||||
) => requestJson<CoordinateReconstructionPreview>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-region`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId, table_id: tableId, definition }),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 使用当前未保存画布定义识别一个或全部表头;返回值必须由管理员操作确认后才能应用。 */
|
||||
export const suggestOrderProfileHeader = (profileId: number, payload: { document_id: number; table_id: string; definition: ShippingOrderDocumentProfile['definition']; header_layout_id?: string }) =>
|
||||
requestJson<{ table_id: string; header_layouts: Array<{ layout_id: string; fields: Array<{ field_code: string | null; text: string; confidence: 'confirmed_binding' | 'exact_alias' | 'unmapped' }> }>; status: 'needs_review' }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/header-suggestions`, {
|
||||
method: 'POST', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 创建或读取当前模板版本的盲测集;草稿阶段即可完成发布所需验收。 */
|
||||
export const createOrderProfileTestSuite = (profileId: number) => requestJson<OrderProfileTestSuite>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/test-suites`, { method: 'POST', ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 将一份独立样本的人工真值写入当前盲测集。 */
|
||||
export const addOrderProfileTestSample = (suiteId: number, payload: { document_id: number; table_id: string; expected_rows: Array<Record<string, unknown>> }) => requestJson<OrderProfileTestSuite>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/samples`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 执行当前盲测集,任何字段或行数差异都保留为发布阻断。 */
|
||||
export const executeOrderProfileTestSuite = (suiteId: number) => requestJson<OrderProfileTestSuite>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/execute`, { method: 'POST', ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 仅批准当前、全量通过的盲测执行结果。 */
|
||||
export const approveOrderProfileTestSuite = (suiteId: number) => requestJson<OrderProfileTestSuite>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/approve`, { method: 'POST', ...jsonAuth() },
|
||||
);
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
ShippingOrderSchemaVersionDiff,
|
||||
ShippingOrderSchemaVersionPage,
|
||||
ShippingOrderSchemaVersionUsage,
|
||||
ShippingOrderSchemaProfileImpact,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingFulfillmentPolicyState,
|
||||
} from '../types/shipping-order-schema.types';
|
||||
@@ -114,6 +115,12 @@ export const getShippingOrderSchemaVersionUsage = (versionId: number, page = 1,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 只读评估目标 Schema 版本对已发布订单文档模板的字段级影响。 */
|
||||
export const getShippingOrderSchemaProfileImpact = (versionId: number) =>
|
||||
requestJson<ShippingOrderSchemaProfileImpact>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/profile-impact`, auth(),
|
||||
);
|
||||
|
||||
/** 读取单次动态订单解析冻结输入、LLM 输出、裁决和证据的只读审计详情。 */
|
||||
export const getShippingOrderExtractionAudit = (extractionId: number) =>
|
||||
requestJson<ShippingOrderExtractionAudit>(
|
||||
@@ -140,10 +147,12 @@ export const deleteShippingOrderSchemaDraft = (versionId: number) =>
|
||||
});
|
||||
|
||||
/** 发布草稿并自动退役上一当前版本。 */
|
||||
export const publishShippingOrderSchemaDraft = (versionId: number, expectedLockVersion: number) =>
|
||||
export const publishShippingOrderSchemaDraft = (
|
||||
versionId: number, expectedLockVersion: number, confirmProfileImpact = false,
|
||||
) =>
|
||||
requestJson<ShippingOrderSchemaVersion>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/publish`,
|
||||
{ method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth() },
|
||||
{ method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion, confirm_profile_impact: confirmProfileImpact }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取受控履约能力目录及策略版本,页面不提供任意表达式配置。 */
|
||||
|
||||
@@ -77,7 +77,7 @@
|
||||
<PaginationBar v-model:page="exportPage" v-model:page-size="auditPageSize" :total="exports.length" />
|
||||
</div>
|
||||
|
||||
<div v-else class="object-list-panel">
|
||||
<div v-else-if="activeTab !== 'orderSchema'" class="object-list-panel">
|
||||
<div class="object-list">
|
||||
<div v-if="!currentItems.length" class="empty-state">{{ t('admin.shippingInventory.emptyConfig') }}</div>
|
||||
<button
|
||||
|
||||
+2590
File diff suppressed because it is too large.
Load diff
+5
-983
@@ -1,991 +1,13 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue
|
||||
用途:通过 MinerU/PDF 坐标样本工作台创建、复核和发布订单文档 Profile。
|
||||
依赖:Profile/Schema API、BusinessError、useMessage、Vue I18n。
|
||||
逻辑:管理员选择样本并按物理行编辑列边界和字段;后端提供全量/当前行建议及最终候选,浏览器不展示 HTML 或结构指纹。
|
||||
用途:订单坐标 Profile 管理路由入口。
|
||||
依赖:OrderProfileWorkbench。
|
||||
逻辑:页面编排保持极薄;受控页面预览、区域标注、版本抽屉和草稿保护全部由工作台组件协作完成。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
cloneOrderDocumentProfile,
|
||||
createOrderProfileSample,
|
||||
createOrderProfileFromSample,
|
||||
deleteOrderDocumentProfile,
|
||||
deleteOrderProfileSample,
|
||||
getOrderProfileSampleTables,
|
||||
getOrderProfileSampleStatus,
|
||||
generateOrderProfileOcrCoordinateEvidence,
|
||||
listOrderDocumentProfiles,
|
||||
listOrderProfileSamples,
|
||||
publishOrderDocumentProfile,
|
||||
retireOrderDocumentProfile,
|
||||
previewOrderProfileCoordinateReconstruction,
|
||||
suggestOrderProfileCoordinateReconstruction,
|
||||
updateOrderProfileFromSample,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import type {
|
||||
OrderProfileSampleDocument,
|
||||
OrderProfileSamplePreview,
|
||||
OrderProfileSampleTable,
|
||||
CoordinateReconstructionPreview,
|
||||
CoordinateReconstructionSettings,
|
||||
CoordinateSubrowLayout,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
buildOrderProfileColumnRules,
|
||||
findDuplicateOrderProfileTargets,
|
||||
mergeOrderProfileHeaderLabels,
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
} from './orderProfileForm.utils';
|
||||
import type {
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderSchemaVersion,
|
||||
} from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const sampleUploading = ref(false);
|
||||
const sampleInput = ref<HTMLInputElement | null>(null);
|
||||
const editingProfileId = ref<number | null>(null);
|
||||
const editingLockVersion = ref<number | null>(null);
|
||||
const profiles = ref<ShippingOrderDocumentProfile[]>([]);
|
||||
const samples = ref<OrderProfileSampleDocument[]>([]);
|
||||
const sampleSearch = ref('');
|
||||
const preview = ref<OrderProfileSamplePreview | null>(null);
|
||||
const reconstructionPreview = ref<CoordinateReconstructionPreview | null>(null);
|
||||
const reconstructing = ref(false);
|
||||
const reconstructionPreviewFailed = ref(false);
|
||||
const suggesting = ref(false);
|
||||
const suggestingSubrowIndex = ref<number | null>(null);
|
||||
const ocrGenerating = ref(false);
|
||||
const reconstructionMethod = ref<CoordinateReconstructionSettings['method']>('native_pdf_coordinates.v1');
|
||||
const reconstructionConfirmed = ref(false);
|
||||
const reconstructionFieldSignature = ref('');
|
||||
const columnBoundaryInput = ref('0, 0.10, 0.25, 0.33, 0.52, 0.65, 0.77, 0.88, 0.94, 1');
|
||||
const multiSubrowEnabled = ref(false);
|
||||
type SubrowEditor = {
|
||||
role: CoordinateSubrowLayout['role']; row_offset: number; boundaries: string;
|
||||
fields: Array<string | null>; samples: string[][];
|
||||
};
|
||||
const subrowEditors = ref<SubrowEditor[]>([
|
||||
{ role: 'main', row_offset: 0, boundaries: '0, 1', fields: [null], samples: [] },
|
||||
]);
|
||||
const selectedSubrowIndex = ref(0);
|
||||
const publishedSchemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const form = reactive({
|
||||
profile_code: '', display_name: '', schema_version_id: 0,
|
||||
document_id: 0, table_id: '', header_row_index: 0, data_start_row_index: 1,
|
||||
row_structure: 'preserved' as 'preserved' | 'unsupported_row_structure',
|
||||
drop_zero_qty: true, change_note: '',
|
||||
});
|
||||
const columnRules = ref<Array<{ extractor_key: 'direct' | 'temp_internal_parts'; target: string }>>([]);
|
||||
|
||||
const selectedTable = computed<OrderProfileSampleTable | null>(() => (
|
||||
preview.value?.tables.find((item) => item.table_id === form.table_id) || null
|
||||
));
|
||||
const showStandardPreview = computed(() => shouldShowStandardOrderProfilePreview(
|
||||
Boolean(selectedTable.value?.profile_creation_allowed),
|
||||
multiSubrowEnabled.value,
|
||||
Boolean(selectedTable.value?.coordinate_reconstruction_available),
|
||||
));
|
||||
const displayedTable = computed<OrderProfileSampleTable | CoordinateReconstructionPreview | null>(() => (
|
||||
reconstructionPreview.value || selectedTable.value
|
||||
));
|
||||
const mergedHeaderLabels = computed(() => mergeOrderProfileHeaderLabels(
|
||||
displayedTable.value?.rows || [],
|
||||
form.header_row_index,
|
||||
displayedTable.value?.column_count || 0,
|
||||
));
|
||||
const displayedRowRole = (rowIndex: number) => (
|
||||
reconstructionPreview.value?.row_roles[rowIndex] || (rowIndex <= form.header_row_index ? 'header' : 'data')
|
||||
);
|
||||
const displayedSourceRows = (rowIndex: number) => reconstructionPreview.value?.source_row_indices[rowIndex] || [];
|
||||
const visibleSamples = computed(() => {
|
||||
const keyword = sampleSearch.value.trim().toLowerCase();
|
||||
return samples.value.filter((sample) => !keyword || String(sample.filename || '').toLowerCase().includes(keyword));
|
||||
});
|
||||
const selectedSample = computed(() => samples.value.find((sample) => sample.document_id === form.document_id) || null);
|
||||
const selectedSubrow = computed(() => subrowEditors.value[selectedSubrowIndex.value] || subrowEditors.value[0]);
|
||||
const currentProfileIds = computed(() => new Set(
|
||||
profiles.value.filter((profile) => profile.status === 'published').map((profile) => profile.id),
|
||||
));
|
||||
const selectedSchema = computed(() => publishedSchemas.value.find((item) => item.id === form.schema_version_id) || null);
|
||||
const lineFields = computed<ShippingOrderFieldConfig[]>(() => (
|
||||
selectedSchema.value?.definition?.fields.filter((item) => item.enabled !== false && item.scope === 'line') || []
|
||||
));
|
||||
const compositeExtractorAvailable = computed(() => {
|
||||
const codes = new Set(lineFields.value.map((item) => item.field_code));
|
||||
return codes.has('customer_part_number') && codes.has('part_number');
|
||||
});
|
||||
const hasConfiguredColumn = computed(() => columnRules.value.some((item) => (
|
||||
item.extractor_key === 'temp_internal_parts' ? compositeExtractorAvailable.value : Boolean(item.target)
|
||||
)));
|
||||
const duplicateTargets = computed(() => {
|
||||
if (form.row_structure !== 'preserved') return [];
|
||||
return findDuplicateOrderProfileTargets(normalizedRules());
|
||||
});
|
||||
const reconstructionMatchesFields = computed(() => (
|
||||
!reconstructionPreview.value || reconstructionFieldSignature.value === coordinateFieldSignature()
|
||||
));
|
||||
const livePreviewStatusKey = computed(() => {
|
||||
if (reconstructing.value) return 'livePreviewUpdating';
|
||||
if (!subrowEditors.value[0]?.fields.includes('line_no')) return 'livePreviewWaitingLineNo';
|
||||
if (reconstructionPreviewFailed.value) return 'livePreviewFailed';
|
||||
if (reconstructionPreview.value && reconstructionMatchesFields.value) return 'livePreviewReady';
|
||||
return 'livePreviewEmpty';
|
||||
});
|
||||
const canSave = computed(() => Boolean(
|
||||
form.profile_code.trim() && form.display_name.trim() && form.schema_version_id
|
||||
&& form.document_id && form.table_id && displayedTable.value
|
||||
&& (selectedTable.value?.profile_creation_allowed || reconstructionConfirmed.value)
|
||||
&& form.data_start_row_index > form.header_row_index
|
||||
&& form.header_row_index >= 0
|
||||
&& form.data_start_row_index < (displayedTable.value?.row_count || 0)
|
||||
&& duplicateTargets.value.length === 0
|
||||
&& reconstructionMatchesFields.value
|
||||
&& (form.row_structure === 'unsupported_row_structure' || hasConfiguredColumn.value),
|
||||
));
|
||||
|
||||
/** 将 API 错误映射到统一消息;页面不展示后端内部详情。 */
|
||||
const showError = (error: unknown) => {
|
||||
if (error instanceof BusinessError) message.error(t(`errors.codes.${error.code}`, error.message));
|
||||
else message.error(t('admin.shippingOrderProfiles.loadFailed'));
|
||||
};
|
||||
|
||||
/** 加载 Profile、样本和不可变 Schema 版本。 */
|
||||
const load = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const [profileRows, sampleRows, schemaState] = await Promise.all([
|
||||
listOrderDocumentProfiles(), listOrderProfileSamples(), getShippingOrderSchemaState(),
|
||||
]);
|
||||
profiles.value = profileRows;
|
||||
samples.value = sampleRows;
|
||||
publishedSchemas.value = schemaState.versions.filter((item) => item.status !== 'draft' && item.definition);
|
||||
if (!form.schema_version_id) form.schema_version_id = schemaState.versions.find((item) => item.status === 'published')?.id || 0;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 选择样本文档后读取由后端展开的网格。 */
|
||||
const loadPreview = async () => {
|
||||
preview.value = null;
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionConfirmed.value = false;
|
||||
form.table_id = '';
|
||||
if (!form.document_id) return;
|
||||
try {
|
||||
preview.value = await getOrderProfileSampleTables(form.document_id);
|
||||
form.table_id = preview.value.tables[0]?.table_id || '';
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
|
||||
/** 上传管理员专用 PDF/EML 样本并轮询预解析;此入口不创建发货任务或调用 Dify。 */
|
||||
const uploadSample = async (event: Event) => {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
const extension = file.name.split('.').pop()?.toLowerCase();
|
||||
if (extension !== 'pdf' && extension !== 'eml') {
|
||||
message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid'));
|
||||
return;
|
||||
}
|
||||
sampleUploading.value = true;
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
const intake = await createOrderProfileSample(asset.asset_no);
|
||||
for (let attempt = 0; attempt < 30; attempt += 1) {
|
||||
const state = await getOrderProfileSampleStatus(intake.intake_no);
|
||||
if (state.parse_status === 'parsed') break;
|
||||
if (state.parse_status === 'parse_failed') throw new Error(state.error_code || 'sample parse failed');
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 1000));
|
||||
}
|
||||
await load();
|
||||
const uploadedSample = samples.value.find((sample) => sample.intake_no === intake.intake_no);
|
||||
if (uploadedSample) form.document_id = uploadedSample.document_id;
|
||||
message.success(t('admin.shippingOrderProfiles.sampleUploaded'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
sampleUploading.value = false;
|
||||
if (sampleInput.value) sampleInput.value.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
/** 表格变化时按真实列数初始化受控列映射。 */
|
||||
const resetColumns = () => {
|
||||
const count = displayedTable.value?.column_count || 0;
|
||||
columnRules.value = Array.from({ length: count }, () => ({ extractor_key: 'direct', target: '' }));
|
||||
form.header_row_index = 0;
|
||||
form.data_start_row_index = Math.min(1, Math.max((displayedTable.value?.row_count || 1) - 1, 0));
|
||||
};
|
||||
|
||||
/** 清理上一张表的坐标重建编辑状态,避免切换样本后隐藏或污染当前配置区。 */
|
||||
const resetCoordinateReconstructionState = () => {
|
||||
if (reconstructionPreviewTimer) window.clearTimeout(reconstructionPreviewTimer);
|
||||
reconstructionPreviewTimer = null;
|
||||
reconstructionPreviewRequestId += 1;
|
||||
multiSubrowEnabled.value = false;
|
||||
subrowEditors.value = [
|
||||
{ role: 'main', row_offset: 0, boundaries: '0, 1', fields: [null], samples: [] },
|
||||
];
|
||||
selectedSubrowIndex.value = 0;
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
reconstructionFieldSignature.value = '';
|
||||
};
|
||||
|
||||
/** 按重建列数保留已有字段映射,并只补齐或裁掉实际变化的列。 */
|
||||
const resizeColumns = (count: number) => {
|
||||
columnRules.value = Array.from({ length: count }, (_, index) => (
|
||||
columnRules.value[index] || { extractor_key: 'direct', target: '' }
|
||||
));
|
||||
};
|
||||
|
||||
/** 解析 0..1 严格递增边界;单内容块物理行允许只使用 0,1。 */
|
||||
const parseBoundaryInput = (raw: string): number[] | null => {
|
||||
const values = raw.split(',').map((item) => Number(item.trim()));
|
||||
if (values.length < 2 || values.some((value) => !Number.isFinite(value)) || values[0] !== 0 || values[values.length - 1] !== 1
|
||||
|| values.some((value, index) => index > 0 && value <= values[index - 1]!)) return null;
|
||||
return values;
|
||||
};
|
||||
|
||||
/** 边界数量变化时保留已有子行字段映射,并补齐新的列。 */
|
||||
const syncSubrowFields = (editor: SubrowEditor) => {
|
||||
const count = Math.max((parseBoundaryInput(editor.boundaries)?.length || 1) - 1, 0);
|
||||
editor.fields = Array.from({ length: count }, (_, index) => editor.fields[index] || null);
|
||||
};
|
||||
|
||||
/** 返回边界尺的有效刻度;输入异常时保留最小可编辑区间。 */
|
||||
const subrowBoundaries = (editor: SubrowEditor) => parseBoundaryInput(editor.boundaries) || [0, 1];
|
||||
|
||||
/** 拖动内部刻度时限制其不能越过相邻边界,并同步字段列数。 */
|
||||
const updateSubrowBoundary = (editor: SubrowEditor, boundaryIndex: number, rawValue: string) => {
|
||||
const values = [...subrowBoundaries(editor)];
|
||||
const previous = values[boundaryIndex - 1] ?? 0;
|
||||
const next = values[boundaryIndex + 1] ?? 1;
|
||||
values[boundaryIndex] = Math.min(next - 0.01, Math.max(previous + 0.01, Number(rawValue)));
|
||||
editor.boundaries = values.map((value) => Number(value.toFixed(2))).join(', ');
|
||||
syncSubrowFields(editor);
|
||||
};
|
||||
|
||||
/** 只有区间宽度足够容纳两个最小 1% 列时才允许继续拆分。 */
|
||||
const canSplitSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
|
||||
const boundaries = subrowBoundaries(editor);
|
||||
return boundaries[columnIndex + 1]! - boundaries[columnIndex]! >= 0.02;
|
||||
};
|
||||
|
||||
/** 在当前逻辑明细末尾增加任意一条物理子行配置。 */
|
||||
const addSubrow = () => {
|
||||
subrowEditors.value.push({
|
||||
role: 'continuation', row_offset: subrowEditors.value.length,
|
||||
boundaries: '0, 1', fields: [null], samples: [],
|
||||
});
|
||||
selectedSubrowIndex.value = subrowEditors.value.length - 1;
|
||||
};
|
||||
|
||||
/** 删除指定续行并重排 row_offset;首行是新明细锚点,禁止删除。 */
|
||||
const removeSubrow = (index: number) => {
|
||||
if (index <= 0) return;
|
||||
subrowEditors.value.splice(index, 1);
|
||||
subrowEditors.value.forEach((item, rowIndex) => {
|
||||
item.row_offset = rowIndex;
|
||||
item.role = rowIndex === 0 ? 'main' : 'continuation';
|
||||
});
|
||||
selectedSubrowIndex.value = Math.min(selectedSubrowIndex.value, subrowEditors.value.length - 1);
|
||||
};
|
||||
|
||||
/** 在指定列区间中点插入新边界;原列配置保留,新列插入其后等待映射。 */
|
||||
const addSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
|
||||
const boundaries = [...subrowBoundaries(editor)];
|
||||
const midpoint = Number(((boundaries[columnIndex]! + boundaries[columnIndex + 1]!) / 2).toFixed(2));
|
||||
boundaries.splice(columnIndex + 1, 0, midpoint);
|
||||
editor.boundaries = boundaries.join(', ');
|
||||
editor.fields.splice(columnIndex + 1, 0, null);
|
||||
editor.samples.splice(columnIndex + 1, 0, []);
|
||||
};
|
||||
|
||||
/** 删除当前物理行的一列并合并相邻边界;每行至少保留一列。 */
|
||||
const removeSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
|
||||
if (editor.fields.length <= 1) return;
|
||||
const boundaries = [...subrowBoundaries(editor)];
|
||||
boundaries.splice(columnIndex === 0 ? 1 : columnIndex, 1);
|
||||
editor.boundaries = boundaries.join(', ');
|
||||
editor.fields.splice(columnIndex, 1);
|
||||
editor.samples.splice(columnIndex, 1);
|
||||
};
|
||||
|
||||
/** 将多子行编辑器转换为严格契约;主行必须映射 line_no 才能识别新明细。 */
|
||||
const multiSubrowLayouts = (): CoordinateSubrowLayout[] | null => {
|
||||
const result: CoordinateSubrowLayout[] = [];
|
||||
for (const editor of subrowEditors.value) {
|
||||
const boundaries = parseBoundaryInput(editor.boundaries);
|
||||
if (!boundaries) return null;
|
||||
const columnCount = boundaries.length - 1;
|
||||
result.push({
|
||||
role: editor.role, row_offset: editor.row_offset,
|
||||
column_boundaries: boundaries,
|
||||
column_field_codes: Array.from({ length: columnCount }, (_, index) => editor.fields[index] || null),
|
||||
});
|
||||
}
|
||||
const main = result.find((item) => item.role === 'main');
|
||||
return main?.column_field_codes.includes('line_no') ? result : null;
|
||||
};
|
||||
|
||||
/** 将管理员确认的相对列边界转为受控坐标重建参数。 */
|
||||
const coordinateReconstructionSettings = (includeFieldRules = false): CoordinateReconstructionSettings | null => {
|
||||
if (multiSubrowEnabled.value) {
|
||||
const layouts = multiSubrowLayouts();
|
||||
return layouts ? { method: reconstructionMethod.value, column_boundaries: [], subrow_layouts: layouts } : null;
|
||||
}
|
||||
const values = parseBoundaryInput(columnBoundaryInput.value);
|
||||
if (!values) return null;
|
||||
const fieldCodes = includeFieldRules ? columnRules.value.map((item) => (
|
||||
item.extractor_key === 'direct' ? (item.target || null) : 'customer_part_number'
|
||||
)) : [];
|
||||
const lineStartColumn = fieldCodes.findIndex((code) => code === 'line_no');
|
||||
return {
|
||||
method: reconstructionMethod.value,
|
||||
column_boundaries: values,
|
||||
column_field_codes: fieldCodes.some(Boolean) ? fieldCodes : [],
|
||||
line_start_column_index: lineStartColumn >= 0 ? lineStartColumn : 0,
|
||||
};
|
||||
};
|
||||
|
||||
/** 生成影响内容适配和新行判断的列映射签名,用于阻止未复核配置直接保存。 */
|
||||
const coordinateFieldSignature = () => JSON.stringify({
|
||||
columnRules: columnRules.value.map((item) => ({ extractor_key: item.extractor_key, target: item.target })),
|
||||
multiSubrowEnabled: multiSubrowEnabled.value,
|
||||
subrows: subrowEditors.value,
|
||||
});
|
||||
|
||||
/** 用后端冻结坐标生成行版式和边界建议;仅确定性行号自动绑定,其余字段由管理员确认。 */
|
||||
const suggestLayouts = async () => {
|
||||
if (!form.document_id || !form.table_id) return;
|
||||
suggesting.value = true;
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionConfirmed.value = false;
|
||||
try {
|
||||
const suggestion = await suggestOrderProfileCoordinateReconstruction(form.document_id, form.table_id);
|
||||
multiSubrowEnabled.value = true;
|
||||
subrowEditors.value = suggestion.subrow_layouts.map((item) => ({
|
||||
role: item.role,
|
||||
row_offset: item.row_offset,
|
||||
boundaries: item.column_boundaries.join(', '),
|
||||
fields: [...item.suggested_field_codes],
|
||||
samples: item.column_samples,
|
||||
}));
|
||||
selectedSubrowIndex.value = 0;
|
||||
message.success(t('admin.shippingOrderProfiles.layoutSuggestionReady'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
suggesting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 仅重新识别当前物理行,按列位置保留已确认字段,不覆盖其他行版式。 */
|
||||
const suggestCurrentSubrow = async () => {
|
||||
const editor = selectedSubrow.value;
|
||||
if (!editor || !form.document_id || !form.table_id) return;
|
||||
suggestingSubrowIndex.value = editor.row_offset;
|
||||
try {
|
||||
const suggestion = await suggestOrderProfileCoordinateReconstruction(
|
||||
form.document_id, form.table_id, editor.row_offset,
|
||||
);
|
||||
const current = suggestion.subrow_layouts[0];
|
||||
if (!current) return;
|
||||
const previousFields = [...editor.fields];
|
||||
editor.boundaries = current.column_boundaries.join(', ');
|
||||
editor.samples = current.column_samples;
|
||||
editor.fields = current.suggested_field_codes.map((code, index) => code || previousFields[index] || null);
|
||||
message.success(t('admin.shippingOrderProfiles.currentRowSuggestionReady'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
suggestingSubrowIndex.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
/** 对扫描 PDF 生成 OCR 字符坐标,随后重新加载表格并继续人工审核。 */
|
||||
const generateOcrEvidence = async () => {
|
||||
if (!form.document_id || !form.table_id) return;
|
||||
const tableId = form.table_id;
|
||||
ocrGenerating.value = true;
|
||||
try {
|
||||
await generateOrderProfileOcrCoordinateEvidence(form.document_id, form.table_id);
|
||||
reconstructionMethod.value = 'ocr_pdf_coordinates.v1';
|
||||
await loadPreview();
|
||||
form.table_id = preview.value?.tables.some((table) => table.table_id === tableId)
|
||||
? tableId : (preview.value?.tables[0]?.table_id || '');
|
||||
message.success(t('admin.shippingOrderProfiles.ocrEvidenceReady'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
ocrGenerating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
let reconstructionPreviewTimer: ReturnType<typeof window.setTimeout> | null = null;
|
||||
let reconstructionPreviewRequestId = 0;
|
||||
|
||||
/** 请求只读重建候选;自动刷新静默校验,手动刷新继续给出明确错误。 */
|
||||
const runReconstructionPreview = async (silent = false) => {
|
||||
if (multiSubrowEnabled.value && !subrowEditors.value[0]?.fields.includes('line_no')) {
|
||||
if (!silent) message.error(t('admin.shippingOrderProfiles.lineNoRequired'));
|
||||
return;
|
||||
}
|
||||
const settings = coordinateReconstructionSettings(true);
|
||||
if (!settings || !form.document_id || !form.table_id) {
|
||||
if (!silent) message.error(t('admin.shippingOrderProfiles.reconstructionBoundariesInvalid'));
|
||||
return;
|
||||
}
|
||||
const requestId = ++reconstructionPreviewRequestId;
|
||||
reconstructing.value = true;
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
try {
|
||||
const result = await previewOrderProfileCoordinateReconstruction(form.document_id, form.table_id, settings);
|
||||
if (requestId !== reconstructionPreviewRequestId) return;
|
||||
reconstructionPreview.value = result;
|
||||
resizeColumns(reconstructionPreview.value.column_count);
|
||||
if (multiSubrowEnabled.value) {
|
||||
const fieldCodes = multiSubrowLayouts()?.flatMap((item) => item.column_field_codes.filter((code): code is string => Boolean(code))) || [];
|
||||
const uniqueCodes = [...new Set(fieldCodes)];
|
||||
columnRules.value = uniqueCodes.map((target) => ({ extractor_key: 'direct', target }));
|
||||
}
|
||||
reconstructionFieldSignature.value = coordinateFieldSignature();
|
||||
form.header_row_index = 0;
|
||||
form.data_start_row_index = Math.min(1, Math.max(reconstructionPreview.value.row_count - 1, 0));
|
||||
} catch (error) {
|
||||
if (requestId !== reconstructionPreviewRequestId) return;
|
||||
reconstructionPreviewFailed.value = true;
|
||||
if (!silent) showError(error);
|
||||
} finally {
|
||||
if (requestId === reconstructionPreviewRequestId) reconstructing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 手动重建用于显式复核,并保留完整错误反馈。 */
|
||||
const reconstructTable = () => runReconstructionPreview(false);
|
||||
|
||||
/** 映射编辑停止后自动刷新右侧候选,避免每次选择都产生请求。 */
|
||||
const scheduleReconstructionPreview = () => {
|
||||
if (reconstructionPreviewTimer) window.clearTimeout(reconstructionPreviewTimer);
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
if (!multiSubrowEnabled.value || !selectedTable.value?.coordinate_reconstruction_available) return;
|
||||
if (!form.document_id || !form.table_id || !subrowEditors.value[0]?.fields.includes('line_no')) return;
|
||||
if (!coordinateReconstructionSettings(true)) return;
|
||||
reconstructionPreviewTimer = window.setTimeout(() => {
|
||||
reconstructionPreviewTimer = null;
|
||||
void runReconstructionPreview(true);
|
||||
}, 500);
|
||||
};
|
||||
|
||||
/** 转换结构化表单为后端白名单列规则,不提交结构指纹或 HTML。 */
|
||||
const normalizedRules = () => buildOrderProfileColumnRules(
|
||||
columnRules.value, compositeExtractorAvailable.value,
|
||||
);
|
||||
|
||||
/** 模板渲染前确保指定列存在规则对象。 */
|
||||
const columnRule = (columnIndex: number) => {
|
||||
if (!columnRules.value[columnIndex]) {
|
||||
columnRules.value[columnIndex] = { extractor_key: 'direct', target: '' };
|
||||
}
|
||||
return columnRules.value[columnIndex]!;
|
||||
};
|
||||
|
||||
/** 创建或更新草稿;指纹由后端按当前样本 HTML 计算。 */
|
||||
const saveDraft = async () => {
|
||||
if (!canSave.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const payload = {
|
||||
...form,
|
||||
profile_code: form.profile_code.trim().toUpperCase(),
|
||||
display_name: form.display_name.trim(),
|
||||
column_rules: form.row_structure === 'preserved' ? normalizedRules() : [],
|
||||
coordinate_reconstruction: reconstructionConfirmed.value ? coordinateReconstructionSettings(true) : null,
|
||||
};
|
||||
if (editingProfileId.value && editingLockVersion.value !== null) {
|
||||
await updateOrderProfileFromSample(editingProfileId.value, {
|
||||
...payload, expected_lock_version: editingLockVersion.value,
|
||||
});
|
||||
} else {
|
||||
await createOrderProfileFromSample(payload);
|
||||
}
|
||||
message.success(t(editingProfileId.value
|
||||
? 'admin.shippingOrderProfiles.updated'
|
||||
: 'admin.shippingOrderProfiles.created'));
|
||||
editingProfileId.value = null;
|
||||
editingLockVersion.value = null;
|
||||
await load();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 进入草稿配置模式;结构仍必须从管理员随后选择的新样本生成。 */
|
||||
const editDraft = (profile: ShippingOrderDocumentProfile) => {
|
||||
editingProfileId.value = profile.id;
|
||||
editingLockVersion.value = profile.lock_version;
|
||||
form.profile_code = profile.profile_code;
|
||||
form.display_name = profile.display_name;
|
||||
form.schema_version_id = profile.schema_version_id;
|
||||
form.row_structure = profile.definition.row_structure;
|
||||
form.drop_zero_qty = profile.definition.drop_zero_qty;
|
||||
form.change_note = profile.change_note || '';
|
||||
form.document_id = 0;
|
||||
preview.value = null;
|
||||
form.table_id = '';
|
||||
};
|
||||
|
||||
/** 取消草稿编辑并恢复新建模式。 */
|
||||
const cancelEdit = () => {
|
||||
editingProfileId.value = null;
|
||||
editingLockVersion.value = null;
|
||||
form.profile_code = '';
|
||||
form.display_name = '';
|
||||
form.change_note = '';
|
||||
form.document_id = 0;
|
||||
};
|
||||
|
||||
/** 从不可变版本复制下一草稿,并立即进入样本重配模式。 */
|
||||
const createNextVersion = async (profile: ShippingOrderDocumentProfile) => {
|
||||
try {
|
||||
const draft = await cloneOrderDocumentProfile(profile.id);
|
||||
editDraft(draft);
|
||||
message.success(t('admin.shippingOrderProfiles.cloned'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
|
||||
/** 发布草稿并刷新版本列表。 */
|
||||
const publishProfile = async (profile: ShippingOrderDocumentProfile) => {
|
||||
try {
|
||||
await publishOrderDocumentProfile(profile.id, profile.lock_version);
|
||||
message.success(t('admin.shippingOrderProfiles.published'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除错误草稿;发布版本由服务端保护。 */
|
||||
const removeProfile = async (profile: ShippingOrderDocumentProfile) => {
|
||||
if (!window.confirm(t('admin.shippingOrderProfiles.deleteConfirm'))) return;
|
||||
try {
|
||||
await deleteOrderDocumentProfile(profile.id);
|
||||
message.success(t('admin.shippingOrderProfiles.deleted'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除前端专用样本;后端再次校验解析状态、所有权与盲测引用。 */
|
||||
const removeSample = async () => {
|
||||
const sample = selectedSample.value;
|
||||
if (!sample?.can_delete || !window.confirm(t('admin.shippingOrderProfiles.deleteSampleConfirm'))) return;
|
||||
try {
|
||||
await deleteOrderProfileSample(sample.intake_no);
|
||||
await load();
|
||||
form.document_id = samples.value[0]?.document_id || 0;
|
||||
if (!form.document_id) preview.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.sampleDeleted'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
|
||||
/** 统一显示上传时间,避免同名样本在下拉框中不可区分。 */
|
||||
const formatSampleTime = (value?: string | null) => (
|
||||
value ? new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'short' }).format(new Date(value)) : '-'
|
||||
);
|
||||
|
||||
/** 退役当前发布版本;历史运行继续使用冻结快照。 */
|
||||
const retireProfile = async (profile: ShippingOrderDocumentProfile) => {
|
||||
if (!window.confirm(t('admin.shippingOrderProfiles.retireConfirm'))) return;
|
||||
try {
|
||||
await retireOrderDocumentProfile(profile.id);
|
||||
message.success(t('admin.shippingOrderProfiles.retired'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
|
||||
watch(() => form.document_id, loadPreview);
|
||||
watch(() => form.table_id, () => {
|
||||
resetCoordinateReconstructionState();
|
||||
resetColumns();
|
||||
});
|
||||
watch(() => form.header_row_index, (headerRowIndex) => {
|
||||
if (form.data_start_row_index <= headerRowIndex) form.data_start_row_index = headerRowIndex + 1;
|
||||
});
|
||||
watch(columnRules, () => {
|
||||
if (reconstructionConfirmed.value && reconstructionFieldSignature.value !== coordinateFieldSignature()) {
|
||||
reconstructionConfirmed.value = false;
|
||||
}
|
||||
}, { deep: true });
|
||||
watch(multiSubrowEnabled, (enabled) => {
|
||||
if (enabled) subrowEditors.value.forEach(syncSubrowFields);
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
scheduleReconstructionPreview();
|
||||
});
|
||||
watch(subrowEditors, () => {
|
||||
if (reconstructionPreview.value) reconstructionConfirmed.value = false;
|
||||
scheduleReconstructionPreview();
|
||||
}, { deep: true });
|
||||
onMounted(load);
|
||||
import OrderProfileWorkbench from './OrderProfileWorkbench.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="min-h-full bg-slate-50 p-6 text-slate-900">
|
||||
<div class="mx-auto max-w-[1500px] space-y-6">
|
||||
<header>
|
||||
<h1 class="text-2xl font-semibold">{{ t('admin.shippingOrderProfiles.title') }}</h1>
|
||||
<p class="mt-1 text-sm text-slate-500">{{ t('admin.shippingOrderProfiles.subtitle') }}</p>
|
||||
</header>
|
||||
|
||||
<div class="space-y-6">
|
||||
<form class="space-y-5 rounded-xl border border-slate-200 bg-white p-5 shadow-sm" @submit.prevent="saveDraft">
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-100 pb-4">
|
||||
<h2 class="font-semibold">{{ t(editingProfileId ? 'admin.shippingOrderProfiles.editTitle' : 'admin.shippingOrderProfiles.createTitle') }}</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<button v-if="editingProfileId" type="button" class="h-9 rounded-lg px-3 text-sm text-slate-600 hover:bg-slate-100" @click="cancelEdit">{{ t('common.cancel') }}</button>
|
||||
<button type="submit" :disabled="!canSave || saving" class="h-9 rounded-lg bg-blue-600 px-4 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50">
|
||||
{{ saving ? t('admin.shippingOrderProfiles.saving') : t(editingProfileId ? 'admin.shippingOrderProfiles.updateDraft' : 'admin.shippingOrderProfiles.createDraft') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="max-w-[980px]">
|
||||
<label class="block text-xs font-medium text-slate-600">{{ t('admin.shippingOrderProfiles.sample') }}</label>
|
||||
<div class="mt-1.5 flex flex-wrap items-center gap-2">
|
||||
<input v-model="sampleSearch" class="h-9 w-52 rounded-lg border border-slate-300 px-3 text-sm" :placeholder="t('admin.shippingOrderProfiles.searchSample')" />
|
||||
<select v-model.number="form.document_id" class="h-9 min-w-0 flex-1 rounded-lg border border-slate-300 bg-white px-3 text-sm">
|
||||
<option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option>
|
||||
<option v-for="sample in visibleSamples" :key="sample.document_id" :value="sample.document_id">
|
||||
{{ sample.filename || `Document ${sample.document_id}` }} · {{ formatSampleTime(sample.created_at) }} · {{ sample.parse_status }} · {{ sample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}
|
||||
</option>
|
||||
</select>
|
||||
<input ref="sampleInput" class="sr-only" type="file" accept=".pdf,.eml,application/pdf,message/rfc822" @change="uploadSample" />
|
||||
<button type="button" :disabled="sampleUploading" class="h-9 shrink-0 rounded-lg border border-blue-200 px-3 text-sm font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="sampleInput?.click()">
|
||||
{{ sampleUploading ? t('common.loading') : t('admin.shippingOrderProfiles.uploadSample') }}
|
||||
</button>
|
||||
<button type="button" :disabled="!selectedSample?.can_delete" class="h-9 shrink-0 rounded-lg border border-red-200 px-3 text-sm font-medium text-red-600 hover:bg-red-50 disabled:cursor-not-allowed disabled:border-slate-200 disabled:text-slate-400" @click="removeSample">
|
||||
{{ t('admin.shippingOrderProfiles.deleteSample') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="selectedSample" class="mt-1.5 text-xs text-slate-500">
|
||||
{{ t('admin.shippingOrderProfiles.sampleDetails', { time: formatSampleTime(selectedSample.created_at), status: selectedSample.parse_status }) }}
|
||||
· {{ selectedSample.is_template_sample ? t('admin.shippingOrderProfiles.templateSampleOnly') : t('admin.shippingOrderProfiles.businessSampleProtected') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-end gap-x-3 gap-y-3">
|
||||
<label class="w-44 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.table') }}</span>
|
||||
<select v-model="form.table_id" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm" :disabled="!preview">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option>
|
||||
<option v-for="table in preview?.tables || []" :key="table.table_id" :value="table.table_id">P{{ table.page_no }} · {{ table.row_count }}×{{ table.column_count }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="w-52 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.schema') }}</span>
|
||||
<select v-model.number="form.schema_version_id" :disabled="Boolean(editingProfileId)" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm disabled:bg-slate-100">
|
||||
<option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }} · {{ schema.status }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="w-44 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.code') }}</span>
|
||||
<input v-model="form.profile_code" :disabled="Boolean(editingProfileId)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm disabled:bg-slate-100" />
|
||||
</label>
|
||||
<label class="w-72 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.name') }}</span>
|
||||
<input v-model="form.display_name" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" />
|
||||
</label>
|
||||
<label class="mb-2 flex items-center gap-2 whitespace-nowrap text-sm text-slate-700"><input v-model="form.drop_zero_qty" type="checkbox" />{{ t('admin.shippingOrderProfiles.dropZeroQty') }}</label>
|
||||
</div>
|
||||
|
||||
<details class="max-w-[980px] rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
|
||||
<summary class="cursor-pointer text-sm font-medium text-slate-700">{{ t('admin.shippingOrderProfiles.advancedSettings') }}</summary>
|
||||
<div class="mt-3 flex flex-wrap items-end gap-3 border-t border-slate-200 pt-3">
|
||||
<label class="w-72 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.rowStructure') }}</span><select v-model="form.row_structure" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm"><option value="preserved">{{ t('admin.shippingOrderProfiles.rowPreserved') }}</option><option value="unsupported_row_structure">{{ t('admin.shippingOrderProfiles.rowUnsupported') }}</option></select></label>
|
||||
<label class="w-36 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.headerRow') }}</span><input v-model.number="form.header_row_index" type="number" min="0" :max="Math.max((displayedTable?.row_count || 1) - 2, 0)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
|
||||
<label class="w-32 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.dataRow') }}</span><input v-model.number="form.data_start_row_index" type="number" :min="form.header_row_index + 1" :max="Math.max((displayedTable?.row_count || 1) - 1, 0)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
|
||||
<label v-if="editingProfileId" class="w-80 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.changeNote') }}</span><input v-model="form.change_note" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedTable && !selectedTable.profile_creation_allowed" class="overflow-hidden rounded-xl border border-slate-200 bg-slate-50">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-white px-4 py-3">
|
||||
<span class="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-amber-100 text-sm font-bold text-amber-700">!</span>
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.reconstructionRequired') }}</p>
|
||||
<p v-if="selectedTable.coordinate_reconstruction_available" class="mt-1 text-xs leading-5 text-slate-500">{{ t('admin.shippingOrderProfiles.autoSuggestLayoutHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="selectedTable.coordinate_reconstruction_available">
|
||||
<label class="flex items-center gap-2 border-b border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700">
|
||||
<input v-model="multiSubrowEnabled" type="checkbox" />
|
||||
{{ t('admin.shippingOrderProfiles.multiSubrowEnabled') }}
|
||||
</label>
|
||||
<label v-if="!multiSubrowEnabled" class="block p-4 text-xs"><span class="mb-1 block">{{ t('admin.shippingOrderProfiles.columnBoundaries') }}</span><input v-model="columnBoundaryInput" class="w-full rounded-lg border border-slate-300 bg-white px-3 py-2" /></label>
|
||||
<div v-else class="p-3">
|
||||
<div class="grid min-w-0 gap-3 lg:grid-cols-[180px_minmax(0,1fr)]">
|
||||
<aside class="overflow-hidden rounded-lg border border-slate-200 bg-white">
|
||||
<div class="border-b border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600">{{ t('admin.shippingOrderProfiles.physicalRows') }}</div>
|
||||
<div class="p-1.5">
|
||||
<button v-for="(editor, editorIndex) in subrowEditors" :key="editor.row_offset" type="button" class="mb-1 flex h-9 w-full items-center justify-between rounded-md px-2.5 text-left text-sm last:mb-0" :class="selectedSubrowIndex === editorIndex ? 'bg-blue-50 font-medium text-blue-700' : 'text-slate-700 hover:bg-slate-50'" @click="selectedSubrowIndex = editorIndex">
|
||||
<span>{{ t(editorIndex === 0 ? 'admin.shippingOrderProfiles.firstSubrow' : 'admin.shippingOrderProfiles.followingSubrow', { index: editorIndex + 1 }) }}</span>
|
||||
<span class="text-xs opacity-60">{{ editor.fields.length }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex border-t border-slate-200 p-1.5">
|
||||
<button type="button" class="h-8 flex-1 rounded-md text-xs font-medium text-blue-700 hover:bg-blue-50" @click="addSubrow">+ {{ t('admin.shippingOrderProfiles.addSubrow') }}</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section v-if="selectedSubrow" class="min-w-0 overflow-hidden rounded-lg border border-slate-200 bg-white">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200 px-3 py-2">
|
||||
<div><span class="text-sm font-semibold text-slate-900">{{ t(selectedSubrowIndex === 0 ? 'admin.shippingOrderProfiles.firstSubrow' : 'admin.shippingOrderProfiles.followingSubrow', { index: selectedSubrowIndex + 1 }) }}</span><span class="ml-2 text-xs text-slate-400">{{ selectedSubrow.fields.length }} {{ t('admin.shippingOrderProfiles.columnsUnit') }}</span></div>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<button type="button" :disabled="suggestingSubrowIndex !== null" class="h-8 rounded-md border border-blue-200 px-2.5 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="suggestCurrentSubrow">{{ suggestingSubrowIndex === selectedSubrow.row_offset ? t('common.loading') : t('admin.shippingOrderProfiles.suggestCurrentRow') }}</button>
|
||||
<button v-if="selectedSubrowIndex > 0" type="button" class="h-8 rounded-md px-2.5 text-xs font-medium text-red-600 hover:bg-red-50" @click="removeSubrow(selectedSubrowIndex)">{{ t('common.delete') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-3">
|
||||
<div class="mb-2 flex items-center justify-between text-[11px] font-medium text-slate-500">
|
||||
<span>{{ t('admin.shippingOrderProfiles.visualBoundaries') }}</span>
|
||||
<span>{{ t('admin.shippingOrderProfiles.dragBoundaryHint') }}</span>
|
||||
</div>
|
||||
<div class="relative h-12 rounded-md border border-slate-300 bg-slate-50 px-1 pt-1">
|
||||
<div class="flex h-7 overflow-hidden rounded border border-white bg-white shadow-sm">
|
||||
<div v-for="(_, index) in selectedSubrow.fields" :key="index" class="flex min-w-0 items-center justify-center border-r border-blue-100 bg-blue-50/60 px-1 text-[10px] font-medium text-blue-700 last:border-r-0" :style="{ width: `${(subrowBoundaries(selectedSubrow)[index + 1]! - subrowBoundaries(selectedSubrow)[index]!) * 100}%` }">
|
||||
<span class="truncate">{{ index + 1 }} · {{ Math.round((subrowBoundaries(selectedSubrow)[index + 1]! - subrowBoundaries(selectedSubrow)[index]!) * 100) }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<template v-for="(boundary, boundaryIndex) in subrowBoundaries(selectedSubrow).slice(1, -1)" :key="boundaryIndex">
|
||||
<span class="pointer-events-none absolute bottom-1 top-1 w-px bg-blue-500" :style="{ left: `${boundary * 100}%` }" />
|
||||
<input :value="boundary" type="range" min="0.01" max="0.99" step="0.01" class="boundary-slider absolute inset-x-0 top-5 h-5 w-full" :aria-label="t('admin.shippingOrderProfiles.boundaryHandle', { index: boundaryIndex + 1 })" @input="updateSubrowBoundary(selectedSubrow, boundaryIndex + 1, ($event.target as HTMLInputElement).value)" />
|
||||
</template>
|
||||
</div>
|
||||
<div class="mt-3 flex gap-2 overflow-x-auto pb-2">
|
||||
<article v-for="(_, index) in selectedSubrow.fields" :key="index" class="w-52 shrink-0 rounded-lg border border-slate-200 bg-slate-50 p-2.5">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-xs font-semibold text-slate-700">{{ t('admin.shippingOrderProfiles.subrowColumn', { index: index + 1 }) }}</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<button type="button" :disabled="!canSplitSubrowColumn(selectedSubrow, index)" class="rounded px-1.5 py-0.5 text-[11px] font-medium text-blue-700 hover:bg-blue-50 disabled:cursor-not-allowed disabled:text-slate-300 disabled:hover:bg-transparent" @click="addSubrowColumn(selectedSubrow, index)">+ {{ t('admin.shippingOrderProfiles.insertColumnAfter') }}</button>
|
||||
<button v-if="selectedSubrow.fields.length > 1" type="button" class="rounded px-1.5 py-0.5 text-[11px] text-red-600 hover:bg-red-50" @click="removeSubrowColumn(selectedSubrow, index)">{{ t('common.delete') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-2 truncate rounded-md bg-white px-2 py-1.5 text-xs text-slate-500" :title="selectedSubrow.samples[index]?.join(' / ') || '-'">{{ selectedSubrow.samples[index]?.join(' / ') || '-' }}</div>
|
||||
<select v-model="selectedSubrow.fields[index]" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
|
||||
<option :value="null">{{ t('admin.shippingOrderProfiles.ignoreColumn') }}</option>
|
||||
<option v-for="field in lineFields" :key="field.field_id" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option>
|
||||
</select>
|
||||
<div class="mt-2 font-mono text-[10px] text-slate-400">{{ Math.round(subrowBoundaries(selectedSubrow)[index]! * 100) }}%–{{ Math.round(subrowBoundaries(selectedSubrow)[index + 1]! * 100) }}%</div>
|
||||
</article>
|
||||
</div>
|
||||
<details class="mt-2 text-[11px] text-slate-500">
|
||||
<summary class="cursor-pointer select-none font-medium">{{ t('admin.shippingOrderProfiles.preciseBoundaryValues') }}</summary>
|
||||
<input v-model="selectedSubrow.boundaries" class="mt-1.5 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 font-mono text-[11px]" @change="syncSubrowFields(selectedSubrow)" />
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-slate-200 bg-white p-2">
|
||||
<button type="button" :disabled="suggesting" class="h-8 rounded-md border border-blue-200 px-2.5 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="suggestLayouts">{{ suggesting ? t('common.loading') : t('admin.shippingOrderProfiles.autoSuggestAllRows') }}</button>
|
||||
<button type="button" :disabled="reconstructing" class="h-8 rounded-md bg-blue-600 px-3 text-xs font-medium text-white hover:bg-blue-700 disabled:opacity-50" @click="reconstructTable">{{ t('admin.shippingOrderProfiles.reconstructTable') }}</button>
|
||||
</div>
|
||||
<aside class="mt-3 min-w-0 overflow-hidden rounded-lg border border-slate-200 bg-white">
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-200 px-3 py-2">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.livePreview') }}</h3>
|
||||
<p class="mt-0.5 text-[11px]" :class="reconstructionPreviewFailed ? 'text-red-600' : reconstructing ? 'text-blue-600' : 'text-slate-500'">{{ t(`admin.shippingOrderProfiles.${livePreviewStatusKey}`) }}</p>
|
||||
</div>
|
||||
<label v-if="reconstructionPreview" class="flex shrink-0 items-center gap-1.5 text-xs font-medium text-slate-700"><input v-model="reconstructionConfirmed" type="checkbox" />{{ t('admin.shippingOrderProfiles.confirmPreview') }}</label>
|
||||
</div>
|
||||
<div class="max-h-[52vh] min-h-56 overflow-auto">
|
||||
<table v-if="reconstructionPreview" class="min-w-full border-collapse text-xs">
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in reconstructionPreview.rows" :key="rowIndex" :class="displayedRowRole(rowIndex) === 'deleted' ? 'bg-red-50 text-slate-500' : rowIndex === form.header_row_index ? 'bg-blue-50 font-semibold' : ''">
|
||||
<td class="sticky left-0 min-w-20 border border-slate-200 bg-slate-50 px-2 py-1.5 text-[11px] text-slate-500">
|
||||
<div>{{ t(`admin.shippingOrderProfiles.rowRole.${displayedRowRole(rowIndex)}`) }}</div>
|
||||
<div v-if="displayedSourceRows(rowIndex).length" class="mt-0.5">{{ displayedSourceRows(rowIndex).map((value) => value + 1).join(', ') }}</div>
|
||||
</td>
|
||||
<td v-for="(cell, columnIndex) in row" :key="columnIndex" class="max-w-52 whitespace-nowrap border border-slate-200 px-2 py-1.5" :title="cell">{{ cell }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-else class="flex min-h-56 items-center justify-center px-6 text-center text-xs leading-5 text-slate-500">{{ t(`admin.shippingOrderProfiles.${livePreviewStatusKey}`) }}</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 border-t border-slate-200 bg-white px-4 py-2.5">
|
||||
<p class="text-[11px] text-slate-500">{{ t('admin.shippingOrderProfiles.multiSubrowHint') }}</p>
|
||||
<p v-if="reconstructionPreview && !reconstructionMatchesFields" class="text-[11px] font-medium text-amber-700">{{ t('admin.shippingOrderProfiles.rebuildAfterFieldMapping') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 p-4">
|
||||
<p class="text-xs text-amber-900">{{ t('admin.shippingOrderProfiles.reconstructionUnavailable') }}</p>
|
||||
<button type="button" :disabled="ocrGenerating" class="rounded-lg border border-amber-500 bg-white px-3 py-2 text-sm text-amber-900 disabled:opacity-50" @click="generateOcrEvidence">{{ ocrGenerating ? t('common.loading') : t('admin.shippingOrderProfiles.generateOcrEvidence') }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<p v-if="duplicateTargets.length" class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||
{{ t('admin.shippingOrderProfiles.duplicateTargets', { fields: duplicateTargets.join(', ') }) }}
|
||||
</p>
|
||||
<p v-if="selectedTable && !selectedTable.profile_creation_allowed && !reconstructionConfirmed" class="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">
|
||||
{{ t('admin.shippingOrderProfiles.structureBlocked') }}
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<div v-if="showStandardPreview" class="min-w-0 space-y-4">
|
||||
<section v-if="displayedTable && form.header_row_index > 0 && form.row_structure === 'preserved'" class="overflow-hidden rounded-xl border border-blue-200 bg-white shadow-sm">
|
||||
<div class="border-b border-blue-100 bg-blue-50 px-4 py-3">
|
||||
<h3 class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.multiRowHeaderMapping') }}</h3>
|
||||
<p class="mt-1 text-xs text-slate-600">{{ t('admin.shippingOrderProfiles.multiRowHeaderHint', { end: form.header_row_index }) }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2 overflow-x-auto p-3">
|
||||
<article v-for="(label, columnIndex) in mergedHeaderLabels" :key="columnIndex" class="w-52 shrink-0 rounded-lg border border-slate-200 bg-slate-50 p-2.5">
|
||||
<div class="text-[11px] font-semibold text-slate-500">{{ t('admin.shippingOrderProfiles.mergedHeaderColumn', { index: columnIndex + 1 }) }}</div>
|
||||
<div class="mt-1 min-h-10 break-words text-xs font-medium leading-5 text-slate-800">{{ label || '-' }}</div>
|
||||
<select v-model="columnRule(columnIndex).target" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.ignoreColumn') }}</option>
|
||||
<option v-for="field in lineFields" :key="field.field_id" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option>
|
||||
</select>
|
||||
<select v-model="columnRule(columnIndex).extractor_key" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
|
||||
<option value="direct">{{ t('admin.shippingOrderProfiles.direct') }}</option>
|
||||
<option value="temp_internal_parts" :disabled="!compositeExtractorAvailable">{{ t('admin.shippingOrderProfiles.compositePart') }}</option>
|
||||
</select>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
<div class="max-h-[70vh] overflow-auto rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||
<div v-if="reconstructionPreview" class="border-b border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">{{ t('admin.shippingOrderProfiles.reconstructionPreview') }}</div>
|
||||
<table v-if="displayedTable" class="min-w-full border-collapse text-sm">
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in displayedTable.rows" :key="rowIndex" :class="rowIndex <= form.header_row_index ? 'bg-blue-50 font-semibold' : displayedRowRole(rowIndex) === 'deleted' ? 'bg-red-50 text-slate-500' : ''">
|
||||
<td class="sticky left-0 min-w-24 border border-slate-200 bg-slate-50 px-2 py-2 text-xs text-slate-500">
|
||||
<div>{{ rowIndex }}</div>
|
||||
<div v-if="reconstructionPreview" class="mt-1 font-medium" :class="displayedRowRole(rowIndex) === 'deleted' ? 'text-red-600' : 'text-emerald-700'">
|
||||
{{ t(`admin.shippingOrderProfiles.rowRole.${displayedRowRole(rowIndex)}`) }}
|
||||
</div>
|
||||
<div v-if="displayedSourceRows(rowIndex).length" class="mt-1 text-[11px]">
|
||||
{{ t('admin.shippingOrderProfiles.sourceRows', { rows: displayedSourceRows(rowIndex).map((value) => value + 1).join(', ') }) }}
|
||||
</div>
|
||||
</td>
|
||||
<td v-for="(cell, columnIndex) in row" :key="columnIndex" class="max-w-[260px] border border-slate-200 px-3 py-2 align-top">
|
||||
<div class="break-words">{{ cell }}</div>
|
||||
<div v-if="rowIndex === form.header_row_index && form.header_row_index === 0 && form.row_structure === 'preserved' && !multiSubrowEnabled" class="mt-2 space-y-1">
|
||||
<div v-if="columnRule(columnIndex).extractor_key === 'temp_internal_parts'" class="rounded bg-slate-100 px-2 py-1 text-xs text-slate-600">
|
||||
customer_part_number + part_number
|
||||
</div>
|
||||
<select v-else v-model="columnRule(columnIndex).target" class="w-full rounded border border-slate-300 px-2 py-1 text-xs">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.ignoreColumn') }}</option>
|
||||
<option v-for="field in lineFields" :key="field.field_id" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option>
|
||||
</select>
|
||||
<select v-model="columnRule(columnIndex).extractor_key" class="w-full rounded border border-slate-300 px-2 py-1 text-xs">
|
||||
<option value="direct">{{ t('admin.shippingOrderProfiles.direct') }}</option>
|
||||
<option value="temp_internal_parts" :disabled="!compositeExtractorAvailable">{{ t('admin.shippingOrderProfiles.compositePart') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div v-else-if="rowIndex === form.header_row_index && multiSubrowEnabled" class="mt-2 rounded bg-slate-100 px-2 py-1 text-xs text-slate-600">
|
||||
{{ cell }}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-else class="p-10 text-center text-sm text-slate-500">{{ t('admin.shippingOrderProfiles.previewEmpty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||
<div class="border-b border-slate-200 px-5 py-4 font-semibold">{{ t('admin.shippingOrderProfiles.versions') }}</div>
|
||||
<div v-if="loading" class="p-6 text-sm text-slate-500">{{ t('common.loading') }}</div>
|
||||
<div v-else class="divide-y divide-slate-100">
|
||||
<div v-for="profile in profiles" :key="profile.id" class="flex flex-wrap items-center justify-between gap-3 px-5 py-4">
|
||||
<div><div class="font-medium">{{ profile.display_name }} · v{{ profile.version }} <span v-if="currentProfileIds.has(profile.id)" class="rounded bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-800">{{ t('admin.shippingOrderProfiles.currentVersion') }}</span></div><div class="text-xs text-slate-500">{{ profile.profile_code }} · Schema v{{ profile.schema_version }} · {{ profile.status }}<span v-if="profile.published_at"> · {{ t('admin.shippingOrderProfiles.publishedAt', { time: formatSampleTime(profile.published_at) }) }}</span><span v-if="profile.change_note"> · {{ profile.change_note }}</span></div></div>
|
||||
<div class="flex gap-2">
|
||||
<button v-if="profile.status === 'draft'" class="rounded border border-slate-300 px-3 py-1.5 text-sm text-slate-700" @click="editDraft(profile)">{{ t('common.edit') }}</button>
|
||||
<button v-if="profile.status === 'draft'" class="rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700" @click="publishProfile(profile)">{{ t('admin.shippingOrderProfiles.publish') }}</button>
|
||||
<button v-if="profile.status === 'draft'" class="rounded border border-red-300 px-3 py-1.5 text-sm text-red-700" @click="removeProfile(profile)">{{ t('common.delete') }}</button>
|
||||
<button v-if="profile.status === 'published' || profile.status === 'retired'" class="rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700" @click="createNextVersion(profile)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button v-if="profile.status === 'published'" class="rounded border border-amber-300 px-3 py-1.5 text-sm text-amber-700" @click="retireProfile(profile)">{{ t('admin.shippingOrderProfiles.retire') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<OrderProfileWorkbench />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.boundary-slider {
|
||||
appearance: none;
|
||||
background: transparent;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.boundary-slider::-webkit-slider-runnable-track {
|
||||
height: 1px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.boundary-slider::-webkit-slider-thumb {
|
||||
width: 12px;
|
||||
height: 20px;
|
||||
margin-top: -10px;
|
||||
appearance: none;
|
||||
border: 2px solid white;
|
||||
border-radius: 4px;
|
||||
background: #2563eb;
|
||||
box-shadow: 0 0 0 1px #2563eb;
|
||||
cursor: ew-resize;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.boundary-slider::-moz-range-track {
|
||||
height: 1px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.boundary-slider::-moz-range-thumb {
|
||||
width: 10px;
|
||||
height: 18px;
|
||||
border: 2px solid white;
|
||||
border-radius: 4px;
|
||||
background: #2563eb;
|
||||
box-shadow: 0 0 0 1px #2563eb;
|
||||
cursor: ew-resize;
|
||||
pointer-events: auto;
|
||||
}
|
||||
</style>
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
|
||||
用途:展示受控 PDF 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
|
||||
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
|
||||
逻辑:父工作台签发单页令牌并提供分页/保存动作;本组件下载短时 PNG,以三段式工具栏和窄工具轨承载标注交互。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowLeft, ArrowRight, BoxSelect, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Save, ScanLine, Sparkles, TableProperties, Trash2 } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const props = defineProps<{
|
||||
profileId: number | null;
|
||||
grant?: OrderProfilePreviewPageGrant | null;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
selectedRegionId?: string | null;
|
||||
creationKind?: OrderProfileCanvasRegion['kind'] | null;
|
||||
autoSuggestDisabled?: boolean;
|
||||
suggesting?: boolean;
|
||||
suggestionProgress?: string;
|
||||
undoDisabled?: boolean;
|
||||
redoDisabled?: boolean;
|
||||
duplicateDisabled?: boolean;
|
||||
deleteDisabled?: boolean;
|
||||
pageNo: number;
|
||||
pageCount: number;
|
||||
saveDisabled?: boolean;
|
||||
saving?: boolean;
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const emit = defineEmits<{
|
||||
select: [regionId: string];
|
||||
start: [regionId: string];
|
||||
end: [];
|
||||
change: [regionId: string, region: OrderProfileCanvasRegion['region']];
|
||||
create: [region: OrderProfileCanvasRegion['region']];
|
||||
draw: [kind: OrderProfileCanvasRegion['kind']];
|
||||
suggest: [];
|
||||
undo: [];
|
||||
redo: [];
|
||||
duplicate: [];
|
||||
delete: [];
|
||||
save: [];
|
||||
page: [pageNo: number];
|
||||
}>();
|
||||
|
||||
const imageUrl = ref('');
|
||||
const loading = ref(false);
|
||||
const canvas = ref<HTMLElement | null>(null);
|
||||
const viewport = ref<HTMLElement | null>(null);
|
||||
const zoom = ref(1);
|
||||
const toolsOpen = ref(true);
|
||||
const zoomPercent = computed(() => Math.round(zoom.value * 100));
|
||||
const pageInput = ref(props.pageNo);
|
||||
type ResizeHandle = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';
|
||||
type DragMode = 'move' | ResizeHandle;
|
||||
let activeDrag: { id: string; mode: DragMode; startX: number; startY: number; region: OrderProfileCanvasRegion['region'] } | null = null;
|
||||
let activePan: { startX: number; startY: number; scrollLeft: number; scrollTop: number } | null = null;
|
||||
let creationStart: { x: number; y: number } | null = null;
|
||||
const creationRegion = ref<OrderProfileCanvasRegion['region'] | null>(null);
|
||||
|
||||
/** 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。 */
|
||||
const loadPage = async () => {
|
||||
if (!props.profileId || !props.grant) return;
|
||||
loading.value = true;
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages/${props.grant.page_no}?preview_token=${encodeURIComponent(props.grant.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
imageUrl.value = URL.createObjectURL(await response.blob());
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 将指针移动映射为相对坐标;八向手柄独立调整边或角,放大后仍以相对坐标精确落位。 */
|
||||
const move = (event: PointerEvent) => {
|
||||
if (!activeDrag || !canvas.value) return;
|
||||
const bounds = canvas.value.getBoundingClientRect();
|
||||
const dx = (event.clientX - activeDrag.startX) / bounds.width;
|
||||
const dy = (event.clientY - activeDrag.startY) / bounds.height;
|
||||
if (activeDrag.mode !== 'move') {
|
||||
const handle = activeDrag.mode;
|
||||
const prior = activeDrag.region;
|
||||
const next = {
|
||||
x0: handle.includes('w') ? Math.max(0, Math.min(prior.x1 - .01, prior.x0 + dx)) : prior.x0,
|
||||
y0: handle.includes('n') ? Math.max(0, Math.min(prior.y1 - .01, prior.y0 + dy)) : prior.y0,
|
||||
x1: handle.includes('e') ? Math.max(prior.x0 + .01, Math.min(1, prior.x1 + dx)) : prior.x1,
|
||||
y1: handle.includes('s') ? Math.max(prior.y0 + .01, Math.min(1, prior.y1 + dy)) : prior.y1,
|
||||
};
|
||||
emit('change', activeDrag.id, next);
|
||||
return;
|
||||
}
|
||||
const width = activeDrag.region.x1 - activeDrag.region.x0;
|
||||
const height = activeDrag.region.y1 - activeDrag.region.y0;
|
||||
const x0 = Math.max(0, Math.min(1 - width, activeDrag.region.x0 + dx));
|
||||
const y0 = Math.max(0, Math.min(1 - height, activeDrag.region.y0 + dy));
|
||||
emit('change', activeDrag.id, { x0, y0, x1: x0 + width, y1: y0 + height });
|
||||
};
|
||||
|
||||
/** 为单次鼠标手势建立一个撤销边界,避免每个像素移动污染历史。 */
|
||||
const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => {
|
||||
event.preventDefault();
|
||||
emit('select', region.id);
|
||||
emit('start', region.id);
|
||||
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
|
||||
window.addEventListener('pointermove', move);
|
||||
window.addEventListener('pointerup', endMove, { once: true });
|
||||
};
|
||||
|
||||
/** 结束一次区域移动并停止全局事件监听。 */
|
||||
const endMove = () => {
|
||||
activeDrag = null;
|
||||
emit('end');
|
||||
window.removeEventListener('pointermove', move);
|
||||
};
|
||||
/** 未处于绘制模式时以左键拖动画布视口,避免依赖横纵滚动条定位放大页面。 */
|
||||
const beginPan = (event: PointerEvent) => {
|
||||
if (props.creationKind || !viewport.value || event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
activePan = { startX: event.clientX, startY: event.clientY, scrollLeft: viewport.value.scrollLeft, scrollTop: viewport.value.scrollTop };
|
||||
window.addEventListener('pointermove', pan);
|
||||
window.addEventListener('pointerup', endPan, { once: true });
|
||||
};
|
||||
const pan = (event: PointerEvent) => {
|
||||
if (!activePan || !viewport.value) return;
|
||||
viewport.value.scrollLeft = activePan.scrollLeft - (event.clientX - activePan.startX);
|
||||
viewport.value.scrollTop = activePan.scrollTop - (event.clientY - activePan.startY);
|
||||
};
|
||||
const endPan = () => { activePan = null; window.removeEventListener('pointermove', pan); };
|
||||
/** 在启用绘制模式时,把指针位置转换为受约束的相对区域并交由父级创建。 */
|
||||
const beginCreation = (event: PointerEvent) => {
|
||||
if (!props.creationKind || !canvas.value) { beginPan(event); return; }
|
||||
const bounds = canvas.value.getBoundingClientRect();
|
||||
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
|
||||
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
|
||||
creationStart = { x, y };
|
||||
creationRegion.value = { x0: x, y0: y, x1: x, y1: y };
|
||||
window.addEventListener('pointermove', updateCreation);
|
||||
window.addEventListener('pointerup', endCreation, { once: true });
|
||||
};
|
||||
const updateCreation = (event: PointerEvent) => {
|
||||
if (!creationStart || !canvas.value) return;
|
||||
const bounds = canvas.value.getBoundingClientRect();
|
||||
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
|
||||
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
|
||||
creationRegion.value = { x0: Math.min(creationStart.x, x), y0: Math.min(creationStart.y, y), x1: Math.max(creationStart.x, x), y1: Math.max(creationStart.y, y) };
|
||||
};
|
||||
const endCreation = () => {
|
||||
const region = creationRegion.value;
|
||||
if (region && region.x1 - region.x0 >= .01 && region.y1 - region.y0 >= .01) emit('create', region);
|
||||
creationStart = null;
|
||||
creationRegion.value = null;
|
||||
window.removeEventListener('pointermove', updateCreation);
|
||||
};
|
||||
|
||||
const selected = computed(() => new Set([props.selectedRegionId]));
|
||||
/** 以固定步进调整页面倍率;区域采用相对坐标,缩放后仍与图像精确对齐。 */
|
||||
const adjustZoom = (delta: number) => { zoom.value = Math.max(.5, Math.min(4, Math.round((zoom.value + delta) * 100) / 100)); };
|
||||
/** 恢复适合工作台宽度的默认倍率,便于快速定位整页。 */
|
||||
const resetZoom = () => { zoom.value = 1; };
|
||||
/** 在画布上滚动时缩放页面,避免管理员来回点击工具栏中断标注。 */
|
||||
const handleWheel = (event: WheelEvent) => { adjustZoom(event.deltaY < 0 ? .1 : -.1); };
|
||||
/** 校验页码输入并请求父工作台切页;超出范围时吸附到最近有效页。 */
|
||||
const goToPage = () => {
|
||||
const nextPage = Math.max(1, Math.min(props.pageCount || 1, Math.round(Number(pageInput.value) || props.pageNo)));
|
||||
pageInput.value = nextPage;
|
||||
if (nextPage !== props.pageNo) emit('page', nextPage);
|
||||
};
|
||||
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom });
|
||||
watch(() => props.grant?.preview_token, () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, (value) => { pageInput.value = value; });
|
||||
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="canvas-shell" aria-label="Document annotation canvas">
|
||||
<header v-if="imageUrl" class="canvas-toolbar">
|
||||
<div class="toolbar-actions"><button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button><button type="button" :disabled="redoDisabled" :title="t('admin.shippingOrderProfiles.workbench.redo')" @click="emit('redo')"><Redo2 /></button><span class="toolbar-divider" aria-hidden="true" /><button type="button" :disabled="duplicateDisabled" :title="t('admin.shippingOrderProfiles.workbench.duplicateRegionShortcut')" @click="emit('duplicate')"><Copy /></button><button type="button" class="delete-action" :disabled="deleteDisabled" :title="t('admin.shippingOrderProfiles.workbench.deleteRegionShortcut')" @click="emit('delete')"><Trash2 /></button><span class="toolbar-divider" aria-hidden="true" /><button type="button" class="save-action" :disabled="saveDisabled || saving" :title="t('admin.save')" @click="emit('save')"><Save /><span>{{ saving ? t('admin.shippingOrderProfiles.saving') : t('admin.save') }}</span></button></div>
|
||||
<div class="page-control"><button type="button" :disabled="pageNo <= 1" :title="t('admin.shippingOrderExtractionRuns.previous')" @click="emit('page', pageNo - 1)"><ArrowLeft /></button><label><input v-model.number="pageInput" type="number" min="1" :max="pageCount" :aria-label="t('admin.shippingOrderProfiles.workbench.pageNavigation')" @change="goToPage" @keydown.enter.prevent="goToPage" /><span>/ {{ pageCount }}</span></label><button type="button" :disabled="pageNo >= pageCount" :title="t('admin.shippingOrderExtractionRuns.next')" @click="emit('page', pageNo + 1)"><ArrowRight /></button></div>
|
||||
<div class="zoom-control"><button type="button" :disabled="zoom <= .5" :title="t('admin.shippingOrderProfiles.workbench.zoomOut')" @click="adjustZoom(-.25)"><Minus /></button><output>{{ zoomPercent }}%</output><button type="button" :disabled="zoom >= 4" :title="t('admin.shippingOrderProfiles.workbench.zoomIn')" @click="adjustZoom(.25)"><Plus /></button><button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button></div>
|
||||
</header>
|
||||
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</div>
|
||||
<div v-else class="canvas-work-area"><aside class="annotation-tools" :class="{ collapsed: !toolsOpen }"><button type="button" class="tools-toggle" :aria-expanded="toolsOpen" :aria-label="toolsOpen ? t('admin.shippingOrderProfiles.workbench.hideAnnotationTools') : t('admin.shippingOrderProfiles.workbench.showAnnotationTools')" @click="toolsOpen = !toolsOpen"><BoxSelect /><span v-if="toolsOpen">{{ t('admin.shippingOrderProfiles.workbench.annotationTools') }}</span></button><template v-if="toolsOpen"><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawHeader')" :class="{ active: creationKind === 'header_field' }" @click="emit('draw', 'header_field')"><TableProperties /><span>{{ t('admin.shippingOrderProfiles.workbench.header') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawLine')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><ScanLine /><span>{{ t('admin.shippingOrderProfiles.workbench.line') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawField')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.field') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawExclusion')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /><span>{{ t('admin.shippingOrderProfiles.workbench.exclusion') }}</span></button><button type="button" class="suggest" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><Sparkles /><span>{{ suggesting ? t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') : t('admin.shippingOrderProfiles.workbench.autoSuggest') }}</span></button><p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p></template></aside><div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind }" @wheel.prevent="handleWheel"><div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
|
||||
<img :src="imageUrl" alt="Controlled document page preview" draggable="false" />
|
||||
<div
|
||||
v-for="region in regions"
|
||||
:key="region.id"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="region"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }]"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@keydown.enter="emit('select', region.id)"
|
||||
@keydown.space.prevent="emit('select', region.id)"
|
||||
><span class="region-label" @pointerdown.stop="beginDrag($event, region, 'move')">{{ region.label }}</span><template v-if="region.kind === 'line'"><span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" /></template><button v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" /></div>
|
||||
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
|
||||
</div></div></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.canvas-shell { min-height: 36rem; background: #101827; padding: 0 1rem 1rem; overflow: hidden; }.canvas-toolbar { position: sticky; top: 0; z-index: 4; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: .75rem; margin: 0 -1rem 1rem; padding: .55rem 1rem; border-bottom: 1px solid #26354b; background: rgb(15 23 42 / .98); color: #cbd5e1; font-size: .75rem; }.canvas-toolbar>div { display: flex; align-items: center; gap: .35rem; }.canvas-toolbar button { display: inline-flex; min-width: 2rem; height: 2rem; align-items: center; justify-content: center; gap: .35rem; border: 1px solid #475569; border-radius: .35rem; background: #1e293b; padding: .3rem .5rem; color: #e2e8f0; font-size: .72rem; }.canvas-toolbar button:hover { border-color: #60a5fa; background: #26364f; }.canvas-toolbar button:disabled { cursor: not-allowed; opacity: .4; }.canvas-toolbar svg,.annotation-tools svg { width: .95rem; height: .95rem; }.toolbar-actions { justify-self: start; }.toolbar-divider { width: 1px; height: 1.25rem; margin: 0 .15rem; background: #475569; }.toolbar-actions .delete-action:not(:disabled) { color: #fecaca; }.toolbar-actions .delete-action:not(:disabled):hover { border-color: #f87171; background: #7f1d1d; color: #fff; }.toolbar-actions .save-action { border-color: #0284c7; background: #0284c7; padding-inline: .65rem; }.page-control { justify-self: center; }.page-control label { display: flex; height: 2rem; align-items: center; gap: .3rem; border: 1px solid #475569; border-radius: .35rem; background: #0f172a; padding: 0 .45rem; color: #94a3b8; }.page-control input { width: 3rem; border: 0; background: transparent; color: #f8fafc; font: 700 .76rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; text-align: right; outline: 0; }.zoom-control { justify-self: end; }.canvas-toolbar output { min-width: 3.4rem; color: #f8fafc; text-align: center; }.zoom-control .fit-action { padding-inline: .65rem; }
|
||||
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; }
|
||||
.canvas-work-area { display: flex; max-height: 43rem; gap: .6rem; }.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }.canvas-viewport.panning { cursor: grab; }.canvas-viewport.panning:active { cursor: grabbing; }.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }.canvas-stage img { display: block; width: 100%; user-select: none; }.canvas-stage.drawing { cursor: crosshair; }.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 7rem; padding: .35rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }.annotation-tools.collapsed { flex-basis: 2.45rem; padding: .3rem; }.annotation-tools button { display: flex; min-height: 2rem; align-items: center; gap: .4rem; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem .45rem; color: #e2e8f0; font-size: .7rem; text-align: left; white-space: nowrap; }.annotation-tools button:hover,.annotation-tools button.active { border-color: #38bdf8; background: #0c4a6e; color: #f0f9ff; }.annotation-tools .tools-toggle { justify-content: center; }.annotation-tools.collapsed .tools-toggle { padding-inline: 0; }.annotation-tools .suggest { border-color: #0ea5e9; background: #0284c7; font-weight: 700; }.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }.suggestion-progress.failed { color: #fca5a5; }
|
||||
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region-label { position: absolute; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.resize-handle { position: absolute; z-index: 3; width: 10px; height: 10px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; }.handle-n,.handle-s { left: 50%; margin-left: -5px; cursor: ns-resize; }.handle-e,.handle-w { top: 50%; margin-top: -5px; cursor: ew-resize; }.handle-nw,.handle-se { cursor: nwse-resize; }.handle-ne,.handle-sw { cursor: nesw-resize; }.handle-n,.handle-nw,.handle-ne { top: -6px; }.handle-s,.handle-sw,.handle-se { bottom: -6px; }.handle-e,.handle-ne,.handle-se { right: -6px; }.handle-w,.handle-nw,.handle-sw { left: -6px; }
|
||||
.region-header_field { z-index: 2; border: 1.5px solid #f59e0b; background: rgb(245 158 11 / .08); }.region-header_field .region-label,.region-header_field .resize-handle { background: #b45309; }
|
||||
.region-line { z-index: 0; border-color: #a78bfa; background: rgb(167 139 250 / .1); pointer-events: none; }.region-line .region-label,.region-line .line-hit-edge,.region-line.selected .resize-handle { pointer-events: auto; }.region-line .region-label,.region-line .resize-handle { background: #6d28d9; }
|
||||
.line-hit-edge { position: absolute; z-index: 2; display: block; }.line-hit-n,.line-hit-s { right: -6px; left: -6px; height: 12px; cursor: move; }.line-hit-e,.line-hit-w { top: 6px; bottom: 6px; width: 12px; cursor: move; }.line-hit-n { top: -6px; }.line-hit-e { right: -6px; }.line-hit-s { bottom: -6px; }.line-hit-w { left: -6px; }
|
||||
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }.region-exclusion .region-label,.region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region:not(.selected) .resize-handle { display: none; }.region.selected { outline: 3px solid white; outline-offset: 2px; }.region.selected:not(.region-line) { z-index: 4; }
|
||||
.canvas-stage.drawing .region { pointer-events: none; }
|
||||
@media (max-width: 900px) { .canvas-toolbar { grid-template-columns: 1fr auto; }.page-control { grid-column: 1 / -1; grid-row: 2; }.zoom-control { justify-self: end; }.canvas-stage { min-width: 32rem; }.canvas-viewport { max-height: 32rem; } } @media (max-width: 640px) { .canvas-shell { min-height: 24rem; padding-inline: .5rem; }.canvas-toolbar { margin-inline: -.5rem; padding-inline: .5rem; }.toolbar-actions .save-action span,.fit-action { display: none; }.annotation-tools { flex-basis: 2.45rem; }.annotation-tools button span,.suggestion-progress { display: none; } }
|
||||
.tools-toggle span { display: none; }
|
||||
</style>
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileIssuePanel.vue
|
||||
用途:统一呈现工作台保存前的配置问题与局部预览状态。
|
||||
依赖:无。
|
||||
逻辑:父页面计算问题码;本组件只呈现可操作的短提示,不保存样本正文或坐标。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
const props = defineProps<{ issues: string[]; previewState: 'idle' | 'updating' | 'ready' | 'failed'; previewError?: string }>();
|
||||
const { t } = useI18n();
|
||||
const previewStatusLabel = (state: 'idle' | 'updating' | 'ready' | 'failed') => ({
|
||||
idle: t('admin.shippingOrderProfiles.workbench.previewIdle'),
|
||||
updating: t('admin.shippingOrderProfiles.workbench.previewUpdating'),
|
||||
ready: t('admin.shippingOrderProfiles.workbench.previewReady'),
|
||||
failed: t('admin.shippingOrderProfiles.workbench.previewFailed'),
|
||||
}[state]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="issue-panel">
|
||||
<div class="issue-title"><span>{{ t('admin.shippingOrderProfiles.workbench.review') }}</span><span :class="`state-${previewState}`">{{ previewStatusLabel(previewState) }}</span></div>
|
||||
<p v-if="previewState === 'failed' && props.previewError" class="preview-error">{{ props.previewError }}</p>
|
||||
<p v-if="!issues.length" class="issue-empty">{{ t('admin.shippingOrderProfiles.workbench.noIssues') }}</p>
|
||||
<ul v-else><li v-for="issue in issues" :key="issue">{{ issue }}</li></ul>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.issue-panel { border-top: 1px solid #dbe4ef; background: #f8fafc; padding: .75rem 1rem; }
|
||||
.issue-title { display: flex; align-items: center; justify-content: space-between; color: #334155; font: 700 .72rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.issue-title span:last-child { border-radius: 999px; padding: .25rem .5rem; font-size: .65rem; letter-spacing: normal; text-transform: none; }
|
||||
.state-idle { background: #e2e8f0; }.state-updating { background: #dbeafe; color: #1d4ed8; }.state-ready { background: #dcfce7; color: #166534; }.state-failed { background: #fee2e2; color: #b91c1c; }
|
||||
ul { margin: .6rem 0 0; padding-left: 1rem; color: #b45309; font-size: .75rem; line-height: 1.4; }.issue-empty { margin: .5rem 0 0; color: #64748b; font-size: .75rem; }
|
||||
.preview-error { margin: .55rem 0 0; color: #b91c1c; font-size: .75rem; line-height: 1.4; }
|
||||
</style>
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileVersionDrawer.vue
|
||||
用途:将模板历史收进可开合抽屉,避免版本列表占据标注工作面。
|
||||
依赖:ShippingOrderDocumentProfile DTO。
|
||||
逻辑:父页面负责版本动作和盲测流程;抽屉只发出用户意图。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
defineProps<{ open: boolean; profiles: ShippingOrderDocumentProfile[] }>();
|
||||
const { t } = useI18n();
|
||||
defineEmits<{ close: []; edit: [profile: ShippingOrderDocumentProfile]; publish: [profile: ShippingOrderDocumentProfile]; clone: [profile: ShippingOrderDocumentProfile]; migrate: [profile: ShippingOrderDocumentProfile]; retire: [profile: ShippingOrderDocumentProfile]; remove: [profile: ShippingOrderDocumentProfile]; test: [profile: ShippingOrderDocumentProfile] }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside v-if="open" class="drawer" :aria-label="t('admin.shippingOrderProfiles.versions')">
|
||||
<header><strong>{{ t('admin.shippingOrderProfiles.versions') }}</strong><button type="button" @click="$emit('close')">{{ t('common.close') }}</button></header>
|
||||
<article v-for="profile in profiles" :key="profile.id">
|
||||
<div><b>{{ profile.display_name }} · v{{ profile.version }}</b><small>{{ profile.profile_code }} · {{ profile.status }}</small><small v-if="profile.migration_status === 'needs_revalidation'" class="migration-status">{{ t('admin.shippingOrderProfiles.migrationNeedsReview') }}</small></div>
|
||||
<div class="actions">
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('edit', profile)">{{ t('common.edit') }}</button>
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('test', profile)">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</button>
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('publish', profile)">{{ t('admin.shippingOrderProfiles.publish') }}</button>
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('remove', profile)">{{ t('common.delete') }}</button>
|
||||
<button v-if="profile.status !== 'draft'" type="button" @click="$emit('clone', profile)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button v-if="profile.status === 'published' && profile.schema_compatibility?.status === 'breaking'" type="button" @click="$emit('migrate', profile)">{{ t('admin.shippingOrderProfiles.migrateSchema') }}</button>
|
||||
<button v-if="profile.status === 'published'" type="button" @click="$emit('retire', profile)">{{ t('admin.shippingOrderProfiles.retire') }}</button>
|
||||
</div>
|
||||
</article>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.drawer { position: fixed; inset: 0 0 0 auto; z-index: 30; width: min(28rem, 92vw); overflow: auto; border-left: 1px solid #cbd5e1; background: white; box-shadow: -16px 0 36px rgb(15 23 42 / .16); }.drawer header { position: sticky; top: 0; display: flex; justify-content: space-between; border-bottom: 1px solid #e2e8f0; background: #fff; padding: 1rem; }.drawer article { display: grid; gap: .75rem; border-bottom: 1px solid #e2e8f0; padding: 1rem; }.drawer b,.drawer small { display: block; }.drawer small { margin-top: .25rem; color: #64748b; }.actions { display: flex; flex-wrap: wrap; gap: .4rem; }.actions button,.drawer header button { border: 1px solid #cbd5e1; border-radius: .4rem; background: white; padding: .35rem .55rem; font-size: .75rem; }.actions button:hover { background: #f1f5f9; }
|
||||
.drawer small.migration-status { color: #b45309; }
|
||||
</style>
|
||||
+43
@@ -10,6 +10,8 @@ import {
|
||||
buildOrderProfileColumnRules,
|
||||
findDuplicateOrderProfileTargets,
|
||||
mergeOrderProfileHeaderLabels,
|
||||
restoreOrderProfileRegionPageNo,
|
||||
suggestFieldCodeFromHeaders,
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
@@ -68,4 +70,45 @@ describe('order profile form rules', () => {
|
||||
'Vendor Part Number / Manufacturer Part',
|
||||
]);
|
||||
});
|
||||
|
||||
it('restores legacy all-page regions to the first page instead of leaking them onto page two', () => {
|
||||
const base = {
|
||||
region_id: 'legacy', region: { x0: 0, y0: 0, x1: 1, y1: 1 }, header_layouts: [], line_layouts: [],
|
||||
continuation_rule: { allow_cross_page: false, required_anchor_ids: [] }, termination_rules: [], exclusion_regions: [],
|
||||
};
|
||||
|
||||
// 断言旧 all_pages 缺失原始页码时采用首篇迁移策略,精确页与续页语义保持不变。
|
||||
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'all_pages' })).toBe(1);
|
||||
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'continuation_pages' })).toBe(2);
|
||||
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'exact_page', page_no: 7 })).toBe(7);
|
||||
});
|
||||
|
||||
it('suggests a cross-page field only when one confirmed header clearly covers the column', () => {
|
||||
const field = {
|
||||
id: 'field', kind: 'field' as const, label: 'Field', pageNo: 1,
|
||||
region: { x0: .6, y0: .4, x1: .8, y1: .45 },
|
||||
};
|
||||
const headers = [{
|
||||
id: 'header-field', kind: 'header_field' as const, label: 'Delivery Date', pageNo: 2,
|
||||
fieldCode: 'requested_receipt_date', region: { x0: .58, y0: .2, x1: .82, y1: .25 },
|
||||
}];
|
||||
|
||||
// 断言不同页面但同一横向列可形成待确认建议,函数本身不写回字段。
|
||||
expect(suggestFieldCodeFromHeaders(field, headers)).toBe('requested_receipt_date');
|
||||
expect(field.fieldCode).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects ambiguous cross-page header semantics', () => {
|
||||
const field = {
|
||||
id: 'field', kind: 'field' as const, label: 'Field', pageNo: 1,
|
||||
region: { x0: .6, y0: .4, x1: .8, y1: .45 },
|
||||
};
|
||||
const headers = [
|
||||
{ id: 'a', kind: 'header_field' as const, label: 'A', pageNo: 1, fieldCode: 'part_number', region: { x0: .6, y0: .2, x1: .8, y1: .25 } },
|
||||
{ id: 'b', kind: 'header_field' as const, label: 'B', pageNo: 2, fieldCode: 'customer_part_number', region: { x0: .6, y0: .2, x1: .8, y1: .25 } },
|
||||
];
|
||||
|
||||
// 断言两个不同字段以相同覆盖率竞争时保持未映射,禁止静默选择。
|
||||
expect(suggestFieldCodeFromHeaders(field, headers)).toBeNull();
|
||||
});
|
||||
});
|
||||
+42
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import type { OrderProfileColumnRule } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { OrderProfileCanvasRegion, OrderProfileTableRegion } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface OrderProfileColumnSelection {
|
||||
extractor_key: 'direct' | 'temp_internal_parts';
|
||||
@@ -73,3 +74,44 @@ export const findDuplicateOrderProfileTargets = (rules: OrderProfileColumnRule[]
|
||||
const targets = rules.flatMap((item) => item.target_field_codes);
|
||||
return [...new Set(targets.filter((target, index) => targets.indexOf(target) !== index))];
|
||||
};
|
||||
|
||||
/**
|
||||
* 将历史页作用域恢复为单页画布页码;旧 all_pages 缺少原始页号时按首篇样例页迁移。
|
||||
* @param tableRegion - 已保存的 v2 表格区域
|
||||
* @returns 当前画布应显示的 1 基页码
|
||||
*/
|
||||
export const restoreOrderProfileRegionPageNo = (tableRegion: OrderProfileTableRegion): number => {
|
||||
if (tableRegion.page_scope === 'exact_page') return tableRegion.page_no || 1;
|
||||
return tableRegion.page_scope === 'continuation_pages' ? 2 : 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据已确认表头的横向覆盖关系建议明细字段;冲突或覆盖不足时拒绝猜测。
|
||||
* @param fieldRegion - 当前待绑定的明细字段区域
|
||||
* @param headerRegions - 所有页面上已确认 Schema 字段的表头区域
|
||||
* @returns 唯一且覆盖至少一半字段宽度的 field_code,否则返回 null
|
||||
*/
|
||||
export const suggestFieldCodeFromHeaders = (
|
||||
fieldRegion: OrderProfileCanvasRegion,
|
||||
headerRegions: OrderProfileCanvasRegion[],
|
||||
): string | null => {
|
||||
const width = fieldRegion.region.x1 - fieldRegion.region.x0;
|
||||
if (fieldRegion.kind !== 'field' || width <= 0) return null;
|
||||
const candidates = headerRegions
|
||||
.filter((item) => item.kind === 'header_field' && item.fieldCode)
|
||||
.map((item) => ({
|
||||
fieldCode: item.fieldCode!,
|
||||
overlap: Math.max(
|
||||
0,
|
||||
Math.min(fieldRegion.region.x1, item.region.x1) - Math.max(fieldRegion.region.x0, item.region.x0),
|
||||
) / width,
|
||||
}))
|
||||
.filter((item) => item.overlap >= .5)
|
||||
.sort((left, right) => right.overlap - left.overlap);
|
||||
if (!candidates.length) return null;
|
||||
const best = candidates[0]!;
|
||||
const competing = candidates.find((item, index) => (
|
||||
index > 0 && item.fieldCode !== best.fieldCode && Math.abs(item.overlap - best.overlap) < .1
|
||||
));
|
||||
return competing ? null : best.fieldCode;
|
||||
};
|
||||
+66
-11
@@ -21,6 +21,7 @@ import {
|
||||
getShippingOrderSchemaVersion,
|
||||
getShippingOrderSchemaVersionDiff,
|
||||
getShippingOrderSchemaVersionUsage,
|
||||
getShippingOrderSchemaProfileImpact,
|
||||
getShippingOrderExtractionAudit,
|
||||
getShippingOrderSchemaState,
|
||||
getShippingFulfillmentPolicyState,
|
||||
@@ -50,6 +51,7 @@ import type {
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSchemaVersionDiff,
|
||||
ShippingOrderSchemaVersionUsage,
|
||||
ShippingOrderSchemaProfileImpact,
|
||||
ShippingOrderExtractionAudit,
|
||||
ShippingFulfillmentPolicyState,
|
||||
} from '@/features/admin/types/shipping-order-schema.types';
|
||||
@@ -65,6 +67,8 @@ defineProps<{ embedded?: boolean }>();
|
||||
const state = ref<ShippingOrderSchemaState | null>(null);
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const profileImpact = ref<ShippingOrderSchemaProfileImpact | null>(null);
|
||||
const profileImpactOpen = ref(false);
|
||||
const fieldForm = reactive({
|
||||
field_code: '', field_category: 'order_line' as FieldCategory,
|
||||
value_type: 'string' as ShippingOrderField['value_type'], context_provider_option_id: null as number | null,
|
||||
@@ -134,6 +138,16 @@ const selectedExposurePolicies = computed(() => (
|
||||
));
|
||||
const publishedPolicy = computed(() => fulfillmentPolicyState.value?.policies.find((item) => item.status === 'published') || null);
|
||||
const draftPolicy = computed(() => fulfillmentPolicyState.value?.policies.find((item) => item.status === 'draft') || null);
|
||||
const fulfillmentCapabilityLabel = (capabilityCode: string): string => {
|
||||
const labels: Record<string, string> = {
|
||||
'fulfillment.reservation_identity': 'reservationIdentity',
|
||||
'fulfillment.part_number': 'partNumber',
|
||||
'fulfillment.quantity': 'quantity',
|
||||
'routing.inventory_source_hint': 'inventorySourceHint',
|
||||
};
|
||||
const labelKey = labels[capabilityCode];
|
||||
return labelKey ? t(`admin.shippingOrderSchema.fulfillmentCapability.${labelKey}`) : capabilityCode;
|
||||
};
|
||||
const policyFieldsFor = (capability: { scope: string; value_type: string }) => (state.value?.fields || []).filter((field) => (
|
||||
field.status === 'active'
|
||||
&& published.value?.definition?.fields.some((config) => config.field_id === field.id && config.enabled !== false)
|
||||
@@ -699,6 +713,12 @@ const publishDraft = async (): Promise<void> => {
|
||||
if (!draft.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const impact = await getShippingOrderSchemaProfileImpact(draft.value.id);
|
||||
if (impact.summary.breaking_count || impact.summary.review_required_count || impact.summary.draft_impact_count) {
|
||||
profileImpact.value = impact;
|
||||
profileImpactOpen.value = true;
|
||||
return;
|
||||
}
|
||||
await publishShippingOrderSchemaDraft(draft.value.id, draft.value.lock_version);
|
||||
message.success(t('admin.shippingOrderSchema.published'));
|
||||
await load();
|
||||
@@ -708,6 +728,21 @@ const publishDraft = async (): Promise<void> => {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
const confirmPublishWithImpact = async (): Promise<void> => {
|
||||
if (!draft.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
await publishShippingOrderSchemaDraft(draft.value.id, draft.value.lock_version, true);
|
||||
profileImpactOpen.value = false;
|
||||
profileImpact.value = null;
|
||||
message.success(t('admin.shippingOrderSchema.published'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
await handleWriteError(error);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除配置错误的草稿,释放下一版本创建门禁。 */
|
||||
const deleteDraft = async (): Promise<void> => {
|
||||
@@ -865,7 +900,7 @@ onMounted(async () => {
|
||||
<p v-if="!published" class="fulfillment-warning">{{ t('admin.shippingOrderSchema.fulfillmentSchemaRequired') }}</p>
|
||||
<div v-else class="fulfillment-bindings">
|
||||
<label v-for="capability in fulfillmentPolicyState?.capabilities || []" :key="capability.capability_code">
|
||||
<span><strong>{{ t(`admin.shippingOrderSchema.fulfillmentCapability.${capability.capability_code}`) }}</strong><small>{{ capability.required ? t('admin.shippingOrderSchema.fulfillmentRequired') : t('admin.shippingOrderSchema.fulfillmentOptional') }}</small></span>
|
||||
<span><strong>{{ fulfillmentCapabilityLabel(capability.capability_code) }}</strong><small>{{ capability.required ? t('admin.shippingOrderSchema.fulfillmentRequired') : t('admin.shippingOrderSchema.fulfillmentOptional') }}</small></span>
|
||||
<select v-model="fulfillmentBindings[capability.capability_code]" :disabled="saving || Boolean(draftPolicy)">
|
||||
<option value="">{{ t('admin.shippingOrderSchema.fulfillmentSelectField') }}</option>
|
||||
<option v-for="field in policyFieldsFor(capability)" :key="field.id" :value="field.id">{{ displayNameForField(field, 0) }} ({{ field.field_code }})</option>
|
||||
@@ -973,7 +1008,7 @@ onMounted(async () => {
|
||||
</template>
|
||||
</div>
|
||||
<template v-if="!selectedIsContext"><div class="rule-switches"><label><input v-model="selectedRuleConfig.required" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.required') }}</strong></span></label><label><input v-model="selectedRuleConfig.auto_create_key_field" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.autoCreateKeyField') }}</strong></span></label><label><input v-model="selectedRuleConfig.evidence_policy.required" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.evidenceRequired') }}</strong></span></label><label><input v-model="selectedRuleConfig.evidence_policy.allow_single_source" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.allowSingleSource') }}</strong></span></label></div>
|
||||
<details class="advanced-rules"><summary>{{ t('admin.shippingOrderSchema.advancedRules') }}</summary><div class="advanced-content"><div class="rule-grid"><label><span>{{ t('admin.shippingOrderSchema.normalizer') }}</span><select v-model="selectedRuleConfig.normalizer_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_normalizers')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.comparator') }}</span><select v-model="selectedRuleConfig.comparator_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_comparators')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.relationRole') }}</span><select v-model="selectedRuleConfig.relation_role" :disabled="isReadOnly || !selectedDraftField?.enabled"><option :value="null">{{ t('admin.shippingOrderSchema.notSet') }}</option><option v-for="item in state.catalog.relation_roles" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.conflictPolicy') }}</span><select v-model="selectedRuleConfig.evidence_policy.conflict_policy" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in state.catalog.conflict_policies" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label></div><fieldset><legend>{{ t('admin.shippingOrderSchema.validators') }}</legend><div class="check-row"><label v-for="item in compatibleRules(selectedRuleConfig, 'type_validators')" :key="item"><input :checked="selectedRuleConfig.validator_keys.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.validator_keys = toggleValue(selectedRuleConfig.validator_keys, item))">{{ ruleLabel(item) }}</label></div></fieldset><fieldset><legend>{{ t('admin.shippingOrderSchema.sourcePrecedence') }}</legend><div class="check-row"><label v-for="item in state.catalog.source_types" :key="item"><input :checked="selectedRuleConfig.evidence_policy.source_precedence.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.evidence_policy.source_precedence = toggleValue(selectedRuleConfig.evidence_policy.source_precedence, item))">{{ sourceLabel(item) }}</label></div></fieldset></div></details></template>
|
||||
<details class="advanced-rules"><summary>{{ t('admin.shippingOrderSchema.advancedRules') }}</summary><div class="advanced-content"><div class="rule-grid"><label><span>{{ t('admin.shippingOrderSchema.normalizer') }}</span><select v-model="selectedRuleConfig.normalizer_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_normalizers')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.comparator') }}</span><select v-model="selectedRuleConfig.comparator_key" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in compatibleRules(selectedRuleConfig, 'type_comparators')" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.relationRole') }}</span><select v-model="selectedRuleConfig.relation_role" :disabled="isReadOnly || !selectedDraftField?.enabled"><option :value="null">{{ t('admin.shippingOrderSchema.notSet') }}</option><option v-for="item in state.catalog.relation_roles" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label><label><span>{{ t('admin.shippingOrderSchema.conflictPolicy') }}</span><select v-model="selectedRuleConfig.evidence_policy.conflict_policy" :disabled="isReadOnly || !selectedDraftField?.enabled"><option v-for="item in state.catalog.conflict_policies" :key="item" :value="item">{{ ruleLabel(item) }}</option></select></label></div><fieldset v-if="selectedField?.scope === 'line'"><legend>{{ t('admin.shippingOrderSchema.coordinateSources') }}</legend><div class="check-row compact-check-row"><label v-for="item in ['pdf_coordinate', 'ocr_coordinate'] as const" :key="item"><input :checked="selectedRuleConfig.allowed_sources?.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.allowed_sources = toggleValue(selectedRuleConfig.allowed_sources || [], item) as Array<'pdf_coordinate' | 'ocr_coordinate'>)">{{ t(`admin.shippingOrderSchema.coordinateSourceOption.${item}`) }}</label></div><small>{{ t('admin.shippingOrderSchema.coordinateSourcesHint') }}</small></fieldset><fieldset><legend>{{ t('admin.shippingOrderSchema.validators') }}</legend><div class="check-row"><label v-for="item in compatibleRules(selectedRuleConfig, 'type_validators')" :key="item"><input :checked="selectedRuleConfig.validator_keys.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.validator_keys = toggleValue(selectedRuleConfig.validator_keys, item))">{{ ruleLabel(item) }}</label></div></fieldset><fieldset><legend>{{ t('admin.shippingOrderSchema.sourcePrecedence') }}</legend><div class="check-row"><label v-for="item in state.catalog.source_types" :key="item"><input :checked="selectedRuleConfig.evidence_policy.source_precedence.includes(item)" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox" @change="!isReadOnly && (selectedRuleConfig.evidence_policy.source_precedence = toggleValue(selectedRuleConfig.evidence_policy.source_precedence, item))">{{ sourceLabel(item) }}</label></div></fieldset></div></details></template>
|
||||
</div>
|
||||
<footer v-if="!isReadOnly" class="rule-footer"><label><span>{{ t('admin.shippingOrderSchema.changeNote') }}</span><input v-model="changeNote" :placeholder="t('admin.shippingOrderSchema.changeNotePlaceholder')"></label><button :disabled="saving" class="text-danger" @click="deleteDraft">{{ t('admin.shippingOrderSchema.deleteDraft') }}</button></footer>
|
||||
</template>
|
||||
@@ -1021,6 +1056,19 @@ onMounted(async () => {
|
||||
@load-more="selectedVersionUsage && openVersionUsage(selectedVersionUsage.version.id, false)"
|
||||
/>
|
||||
<SchemaExtractionAuditDrawer v-model="extractionAuditOpen" :audit="selectedExtractionAudit" :loading="extractionAuditLoading" />
|
||||
<div v-if="profileImpactOpen && profileImpact" class="impact-overlay" @click.self="profileImpactOpen = false">
|
||||
<section class="impact-dialog">
|
||||
<header><h2>{{ t('admin.shippingOrderSchema.profileImpactTitle') }}</h2><button type="button" class="text-button" @click="profileImpactOpen = false">{{ t('common.close') }}</button></header>
|
||||
<p>{{ t('admin.shippingOrderSchema.profileImpactSummary', profileImpact.summary) }}</p>
|
||||
<div class="impact-list">
|
||||
<article v-for="item in profileImpact.items.filter((entry) => entry.status !== 'compatible')" :key="item.profile_id">
|
||||
<strong>{{ item.profile_code }} · v{{ item.profile_version }}</strong><small>{{ item.profile_status }} · {{ item.status }}</small>
|
||||
<ul><li v-for="change in [...item.breaking_changes, ...item.review_changes]" :key="`${change.field_id}-${change.reason}`">{{ change.field_id }} · {{ change.reason }}</li></ul>
|
||||
</article>
|
||||
</div>
|
||||
<footer><button type="button" class="secondary-button" @click="profileImpactOpen = false">{{ t('common.cancel') }}</button><button type="button" class="primary-button" :disabled="saving" @click="confirmPublishWithImpact">{{ t('admin.shippingOrderSchema.confirmImpactPublish') }}</button></footer>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -1031,6 +1079,9 @@ onMounted(async () => {
|
||||
.secondary-button { border: 1px solid #d7e0ea; background: #fff; color: #475569; }
|
||||
.text-button { background: transparent; color: #64748b; }
|
||||
.primary-button:disabled, .secondary-button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.impact-overlay { position: fixed; z-index: 60; inset: 0; display: grid; place-items: center; background: rgb(15 23 42 / .42); padding: 24px; }
|
||||
.impact-dialog { display: grid; width: min(720px, 96vw); max-height: 82vh; gap: 14px; overflow: hidden; border-radius: 12px; background: #fff; padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24); }
|
||||
.impact-dialog header,.impact-dialog footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; }.impact-dialog h2,.impact-dialog p { margin: 0; }.impact-list { display: grid; gap: 8px; overflow: auto; }.impact-list article { border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px 12px; }.impact-list small { display: block; color: #b45309; }.impact-list ul { margin: 8px 0 0; padding-left: 18px; color: #64748b; font-size: 12px; }
|
||||
.schema-setup { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(240px, .6fr); gap: 24px; border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 24px; }
|
||||
.schema-setup-copy { max-width: 600px; }
|
||||
.schema-setup-kicker { margin: 0 0 6px; color: #0284c7; font-size: 12px; font-weight: 600; }
|
||||
@@ -1051,21 +1102,22 @@ onMounted(async () => {
|
||||
.auto-creation-switch span { display: grid; gap: 3px; }
|
||||
.auto-creation-switch strong { color: #334155; font-size: 13px; }
|
||||
.auto-creation-switch small { color: #64748b; font-size: 11px; }
|
||||
.fulfillment-policy-card { display: grid; gap: 14px; margin: 0 0 16px; border: 1px solid #dbe6ef; border-radius: 10px; background: #fff; padding: 16px; }
|
||||
.fulfillment-policy-card { display: grid; gap: 10px; margin: 0 0 16px; border: 1px solid #dbe6ef; border-radius: 10px; background: #fff; padding: 12px 14px; }
|
||||
.fulfillment-policy-card > header, .fulfillment-policy-card > footer { display: flex; align-items: center; justify-content: space-between; gap: 14px; }
|
||||
.fulfillment-policy-card h2, .fulfillment-policy-card p { margin: 0; }
|
||||
.fulfillment-policy-card header p { color: #0284c7; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.fulfillment-policy-card h2 { margin-top: 3px; color: #1e293b; font-size: 14px; }
|
||||
.fulfillment-policy-card header small, .fulfillment-policy-card footer p { color: #64748b; font-size: 12px; }
|
||||
.fulfillment-policy-card h2 { margin-top: 2px; color: #1e293b; font-size: 14px; }
|
||||
.fulfillment-policy-card header small, .fulfillment-policy-card footer p { color: #64748b; font-size: 11px; }
|
||||
.fulfillment-warning { border-radius: 7px; background: #fff7ed; padding: 9px 11px; color: #9a3412; font-size: 12px; }
|
||||
.fulfillment-bindings { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
|
||||
.fulfillment-bindings { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
|
||||
.fulfillment-bindings label, .fulfillment-policy-card footer label { display: grid; gap: 5px; color: #64748b; font-size: 12px; }
|
||||
.fulfillment-bindings label { grid-template-columns: minmax(0, 1fr) minmax(180px, .8fr); align-items: center; border: 1px solid #edf1f5; border-radius: 7px; padding: 10px; }
|
||||
.fulfillment-bindings label { grid-template-columns: minmax(0, 1fr); align-items: start; border: 1px solid #edf1f5; border-radius: 7px; padding: 8px 9px; }
|
||||
.fulfillment-bindings span { display: grid; gap: 2px; }
|
||||
.fulfillment-bindings strong { color: #334155; font-weight: 600; }
|
||||
.fulfillment-bindings small { color: #94a3b8; font-size: 10px; }
|
||||
.fulfillment-bindings select, .fulfillment-policy-card footer input { min-width: 0; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff; padding: 8px 9px; color: #334155; font: inherit; font-size: 12px; }
|
||||
.fulfillment-bindings select, .fulfillment-policy-card footer input { min-width: 0; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff; padding: 7px 8px; color: #334155; font: inherit; font-size: 12px; }
|
||||
.fulfillment-policy-card footer label { flex: 1; }
|
||||
@media (max-width: 1180px) { .fulfillment-bindings { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 900px) { .fulfillment-bindings { grid-template-columns: 1fr; } }
|
||||
.field-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; border-right: 1px solid #e5ebf1; background: #fbfcfe; }
|
||||
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
|
||||
@@ -1139,8 +1191,8 @@ onMounted(async () => {
|
||||
.context-field-note { display: grid; gap: 5px; border: 1px solid #bae6fd; border-radius: 8px; background: #f0f9ff; padding: 12px; color: #475569; font-size: 12px; line-height: 1.5; }
|
||||
.context-field-note strong { color: #0369a1; font-weight: 650; }
|
||||
.rule-body textarea { min-height: 78px; resize: vertical; }
|
||||
.rule-switches { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
|
||||
.rule-switches label { display: flex; min-height: 48px; align-items: center; gap: 9px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fff; padding: 10px 12px; color: #475569; cursor: pointer; }
|
||||
.rule-switches { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
|
||||
.rule-switches label { display: flex; min-height: 42px; align-items: center; gap: 8px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fff; padding: 8px 10px; color: #475569; cursor: pointer; }
|
||||
.rule-switches label:hover { border-color: #bae6fd; background: #f8fcff; }
|
||||
.rule-switches strong { font-size: 12px; font-weight: 600; }
|
||||
.rule-switches input { width: 16px; height: 16px; flex: 0 0 16px; margin: 0; accent-color: #0ea5e9; }
|
||||
@@ -1152,10 +1204,13 @@ onMounted(async () => {
|
||||
.advanced-content { border-top: 1px solid #edf1f5; padding: 16px; }
|
||||
.advanced-content fieldset { display: grid; gap: 9px; border: 0; margin: 0; padding: 0; }
|
||||
.advanced-content legend { color: #64748b; font-size: 12px; }
|
||||
.advanced-content small { color: #94a3b8; font-size: 11px; line-height: 1.4; }
|
||||
.compact-check-row { gap: 8px; }
|
||||
.compact-check-row label { border: 1px solid #e5ebf1; border-radius: 6px; background: #f8fafc; padding: 5px 8px; font-size: 12px; }
|
||||
.rule-footer { display: flex; flex: 0 0 auto; align-items: flex-end; justify-content: space-between; gap: 16px; border-top: 1px solid #e5ebf1; background: #fbfcfe; padding: 12px 24px; }
|
||||
.rule-footer label { flex: 1; }
|
||||
.text-danger { border: 0; background: transparent; color: #ef4444; font: inherit; font-size: 12px; cursor: pointer; }
|
||||
.rule-empty { display: grid; min-height: 360px; place-items: center; color: #94a3b8; font-size: 13px; }
|
||||
@media (max-width: 900px) { .schema-workbench { height: auto; overflow: visible; grid-template-columns: 1fr; } .field-panel { max-height: 360px; border-right: 0; border-bottom: 1px solid #e2e8f0; } .rule-panel { overflow: visible; } .rule-body { max-height: none; overflow: visible; } .schema-setup { grid-template-columns: 1fr; } .schema-setup-form { border-top: 1px solid #e2e8f0; border-left: 0; padding: 18px 0 0; } .rule-switches { grid-template-columns: 1fr; } }
|
||||
@media (max-width: 900px) { .schema-workbench { height: auto; overflow: visible; grid-template-columns: 1fr; } .field-panel { max-height: 360px; border-right: 0; border-bottom: 1px solid #e2e8f0; } .rule-panel { overflow: visible; } .rule-body { max-height: none; overflow: visible; } .schema-setup { grid-template-columns: 1fr; } .schema-setup-form { border-top: 1px solid #e2e8f0; border-left: 0; padding: 18px 0 0; } .rule-switches { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 640px) { .schema-toolbar, .rule-heading, .rule-footer { align-items: flex-start; flex-direction: column; } .rule-heading-actions { width: 100%; justify-content: space-between; } .schema-workbench { min-height: auto; } .form-grid, .rule-grid, .rule-basics { grid-template-columns: 1fr; } .rule-basics .span-two { grid-column: auto; } .schema-setup, .rule-body { padding: 18px; } }
|
||||
</style>
|
||||
@@ -1,18 +1,24 @@
|
||||
/**
|
||||
* features/admin/types/shipping-order-document-profile.types.ts
|
||||
* 用途:订单文档 Profile、MinerU 样本预览和结构化列规则 DTO。
|
||||
* 用途:订单文档坐标模板 v2、受控样本预览和字段区域 DTO。
|
||||
* 依赖:无。
|
||||
* 逻辑:管理页面只提交样本选择和白名单解析器,不持有或提交 HTML/结构指纹。
|
||||
*/
|
||||
|
||||
export type OrderProfileExtractorKey = 'direct' | 'temp_internal_parts';
|
||||
export type OrderProfileExtractorKey = 'direct' | 'temp_internal_parts' | 'quantity_uom' | 'amount_currency' | 'price_currency';
|
||||
export type OrderProfileEvidenceLevel = 'coordinate' | 'ocr_coordinate';
|
||||
export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate';
|
||||
|
||||
export interface OrderProfileColumnRule {
|
||||
column_index: number;
|
||||
extractor_key: OrderProfileExtractorKey;
|
||||
target_field_codes: string[];
|
||||
target_fields?: Array<{ field_id: string; field_code: string }>;
|
||||
}
|
||||
export interface OrderProfileRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
|
||||
export interface OrderProfileAnchorRule { anchor_id: string; text: string; match_mode: 'exact' | 'contains'; region?: OrderProfileRelativeRegion | null; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileFieldRegion { field_id: string; field_code: string; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string }>; }
|
||||
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; 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: OrderProfileAnchorRule[]; optional_anchors: OrderProfileAnchorRule[]; minimum_score: number; minimum_margin: number; }
|
||||
|
||||
/** 阶段 3 重构前仅用于让旧工作台编译;不能作为 v2 API 请求或持久化定义。 */
|
||||
export interface OrderProfileColumnRule { column_index: number; extractor_key: 'direct' | 'temp_internal_parts'; target_field_codes: string[]; target_fields?: Array<{ field_id: string; field_code: string }>; }
|
||||
|
||||
export interface ShippingOrderDocumentProfile {
|
||||
id: number;
|
||||
@@ -23,16 +29,13 @@ export interface ShippingOrderDocumentProfile {
|
||||
schema_version_id: number;
|
||||
schema_version?: number | null;
|
||||
schema_checksum?: string | null;
|
||||
structure_fingerprint: string;
|
||||
definition: {
|
||||
contract_version: string;
|
||||
structure_fingerprint: string;
|
||||
header_row_index: number;
|
||||
data_start_row_index: number;
|
||||
row_structure: 'preserved' | 'unsupported_row_structure';
|
||||
column_rules: OrderProfileColumnRule[];
|
||||
drop_zero_qty: boolean;
|
||||
coordinate_reconstruction?: CoordinateReconstructionSettings | null;
|
||||
contract_version: 'order_coordinate_profile.v2';
|
||||
document_match: OrderProfileDocumentMatch;
|
||||
table_regions: OrderProfileTableRegion[];
|
||||
/** 阶段 3 前允许旧页面只读显示历史 v1 版本;新写入不会产生这些字段。 */
|
||||
row_structure?: 'preserved' | 'unsupported_row_structure';
|
||||
drop_zero_qty?: boolean;
|
||||
};
|
||||
checksum?: string | null;
|
||||
lock_version: number;
|
||||
@@ -40,6 +43,45 @@ export interface ShippingOrderDocumentProfile {
|
||||
source_profile_id?: number | null;
|
||||
published_at?: string | null;
|
||||
retired_at?: string | null;
|
||||
template_mode?: string;
|
||||
training_sample_count?: number;
|
||||
match_strategy_summary?: Record<string, number | null>;
|
||||
schema_compatibility?: {
|
||||
status: 'compatible' | 'review_required' | 'breaking';
|
||||
auto_upgradable: boolean;
|
||||
renamed_fields: Array<{ field_id: string; from: string; to: string }>;
|
||||
breaking_changes: Array<{ field_id: string; reason: string; before?: string; after?: string; replacement_candidates?: Array<{ field_id: string; field_code?: string; display_name?: string }> }>;
|
||||
review_changes?: Array<{ field_id: string; reason: string; before?: unknown; after?: unknown }>;
|
||||
} | null;
|
||||
migration_status?: 'normal' | 'needs_revalidation' | 'blocked';
|
||||
}
|
||||
|
||||
/** 受控预览授权只对单页生效,令牌不得持久化或复用。 */
|
||||
export interface OrderProfilePreviewPageGrant { page_no: number; preview_token: string; }
|
||||
export interface OrderProfileBoundSample { id: number; document_id: number; table_id?: string | null; sample_role: 'annotation' | 'training'; created_at: string; }
|
||||
export interface OrderProfilePreviewPages { document_id: number; page_count: number; pages: OrderProfilePreviewPageGrant[]; expires_in_seconds: number; }
|
||||
export interface OrderProfilePageTextCandidates { document_id: number; page_no: number; tables: Array<{ table_id: string; row_count: number; column_count: number; rows: string[][] }>; status: 'needs_review'; }
|
||||
/** 发布门禁的脱敏盲测摘要;真值只在管理员添加样本时提交。 */
|
||||
export interface OrderProfileTestSuite {
|
||||
id: number;
|
||||
profile_id: number;
|
||||
profile_checksum: string;
|
||||
status: 'draft' | 'approved' | 'superseded';
|
||||
sample_count: number;
|
||||
approved_at?: string | null;
|
||||
latest_run?: { status: 'passed' | 'failed'; sample_count: number; passed_sample_count: number; failure_codes: string[] } | null;
|
||||
}
|
||||
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
export interface OrderProfileCanvasRegion {
|
||||
id: string;
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'exclusion';
|
||||
label: string;
|
||||
region: OrderProfileRelativeRegion;
|
||||
fieldCode?: string | null;
|
||||
parentId?: string | null;
|
||||
/** 标记所属文档页;画布切页时仅渲染当前页的区域。 */
|
||||
pageNo: number;
|
||||
}
|
||||
|
||||
export interface OrderProfileSampleDocument {
|
||||
@@ -52,7 +94,7 @@ export interface OrderProfileSampleDocument {
|
||||
provider_version?: string | null;
|
||||
table_count: number;
|
||||
created_at?: string | null;
|
||||
purpose: 'shipping_notice' | 'order_document_profile_sample';
|
||||
purpose: 'order_document_profile_sample';
|
||||
parse_status: string;
|
||||
is_template_sample: boolean;
|
||||
can_delete: boolean;
|
||||
@@ -71,6 +113,43 @@ export interface OrderProfileSampleTable {
|
||||
ocr_coordinate_reconstruction_available?: boolean;
|
||||
}
|
||||
|
||||
|
||||
export interface OrderProfileSamplePreview {
|
||||
document: Pick<OrderProfileSampleDocument, 'document_id' | 'intake_id' | 'filename' | 'content_hash'>;
|
||||
tables: OrderProfileSampleTable[];
|
||||
}
|
||||
|
||||
export interface OrderProfileSampleIntake {
|
||||
intake_no: string;
|
||||
parse_status: string;
|
||||
document_count: number;
|
||||
error_code?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateOrderProfileFromSampleInput {
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
definition: ShippingOrderDocumentProfile['definition'];
|
||||
change_note?: string;
|
||||
}
|
||||
|
||||
/** 阶段 3 替换前的旧工作台本地表单形状;服务端会拒绝其提交。 */
|
||||
export interface LegacyCreateOrderProfileFromSampleInput {
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
table_id: string;
|
||||
header_row_index: number;
|
||||
data_start_row_index: number;
|
||||
row_structure: 'preserved' | 'unsupported_row_structure';
|
||||
column_rules: OrderProfileColumnRule[];
|
||||
drop_zero_qty: boolean;
|
||||
coordinate_reconstruction?: CoordinateReconstructionSettings | null;
|
||||
change_note?: string;
|
||||
}
|
||||
export interface CoordinateReconstructionSettings {
|
||||
method: 'native_pdf_coordinates.v1' | 'ocr_pdf_coordinates.v1';
|
||||
column_boundaries: number[];
|
||||
@@ -99,37 +178,15 @@ export interface CoordinateReconstructionPreview {
|
||||
export interface CoordinateSubrowSuggestion extends CoordinateSubrowLayout {
|
||||
column_samples: string[][];
|
||||
suggested_field_codes: Array<string | null>;
|
||||
y0: number;
|
||||
y1: number;
|
||||
region?: OrderProfileRelativeRegion;
|
||||
}
|
||||
|
||||
export interface CoordinateReconstructionSuggestion {
|
||||
table_id: string;
|
||||
table_region?: OrderProfileRelativeRegion;
|
||||
header_regions?: Array<{ region: OrderProfileRelativeRegion; text: string; fields: Array<{ region: OrderProfileRelativeRegion; text: string }> }>;
|
||||
subrow_layouts: CoordinateSubrowSuggestion[];
|
||||
status: 'needs_review';
|
||||
}
|
||||
|
||||
export interface OrderProfileSamplePreview {
|
||||
document: Pick<OrderProfileSampleDocument, 'document_id' | 'intake_id' | 'filename' | 'content_hash'>;
|
||||
tables: OrderProfileSampleTable[];
|
||||
}
|
||||
|
||||
export interface OrderProfileSampleIntake {
|
||||
intake_no: string;
|
||||
parse_status: string;
|
||||
document_count: number;
|
||||
error_code?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateOrderProfileFromSampleInput {
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
table_id: string;
|
||||
header_row_index: number;
|
||||
data_start_row_index: number;
|
||||
row_structure: 'preserved' | 'unsupported_row_structure';
|
||||
column_rules: OrderProfileColumnRule[];
|
||||
drop_zero_qty: boolean;
|
||||
coordinate_reconstruction?: CoordinateReconstructionSettings | null;
|
||||
change_note?: string;
|
||||
}
|
||||
@@ -40,6 +40,8 @@ export interface ShippingOrderFieldConfig {
|
||||
conflict_policy: string;
|
||||
allow_single_source: boolean;
|
||||
};
|
||||
/** 为空时禁止订单坐标模板绑定该字段。 */
|
||||
allowed_sources?: Array<'pdf_coordinate' | 'ocr_coordinate'>;
|
||||
relation_role?: string | null;
|
||||
comparator_key: string;
|
||||
extraction_instruction?: string | null;
|
||||
@@ -155,6 +157,27 @@ export interface ShippingOrderSchemaVersionUsage {
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderSchemaProfileImpact {
|
||||
target_version: ShippingOrderSchemaVersion;
|
||||
summary: { profile_count: number; compatible_count: number; review_required_count: number; breaking_count: number; draft_impact_count: number };
|
||||
items: Array<{
|
||||
profile_id: number;
|
||||
profile_code: string;
|
||||
profile_version: number;
|
||||
profile_status: 'draft' | 'published';
|
||||
source_schema_version_id: number;
|
||||
source_schema_version?: number | null;
|
||||
target_schema_version_id: number;
|
||||
target_schema_version: number;
|
||||
status: 'compatible' | 'review_required' | 'breaking';
|
||||
auto_upgradable: boolean;
|
||||
renamed_fields: Array<{ field_id: string; from: string; to: string }>;
|
||||
breaking_changes: Array<{ field_id: string; reason: string; before?: unknown; after?: unknown }>;
|
||||
review_changes: Array<{ field_id: string; reason: string; before?: unknown; after?: unknown }>;
|
||||
referenced_field_ids: string[];
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionAudit {
|
||||
extraction: ShippingOrderExtractionSummary;
|
||||
schema_version: ShippingOrderSchemaVersion;
|
||||
|
||||
@@ -79,6 +79,9 @@
|
||||
"eyebrow": "Order field template",
|
||||
"title": "Order Template Configuration",
|
||||
"subtitle": "All EML, PDF, and Word orders share one published field contract. Published versions are immutable.",
|
||||
"profileImpactTitle": "Confirm publication impact",
|
||||
"profileImpactSummary": "{profile_count} profiles are involved: {breaking_count} published profiles have breaking impacts, {review_required_count} require review, and {draft_impact_count} drafts are affected.",
|
||||
"confirmImpactPublish": "Confirm impact and publish",
|
||||
"fulfillmentEyebrow": "Shipping fulfillment governance",
|
||||
"fulfillmentTitle": "Field capabilities and shipping policy",
|
||||
"fulfillmentHint": "Only compatible fields from the published Schema can bind to controlled capabilities. Frozen orders retain the full policy snapshot.",
|
||||
@@ -96,10 +99,10 @@
|
||||
"fulfillmentPublished": "Fulfillment policy published; frozen orders are not reinterpreted",
|
||||
"fulfillmentDraftHint": "Policy draft V{version} has locked field bindings. Confirm and publish it.",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "Reservation identity",
|
||||
"fulfillment.part_number": "Part number",
|
||||
"fulfillment.quantity": "Shipping quantity",
|
||||
"routing.inventory_source_hint": "Inventory source routing hint"
|
||||
"reservationIdentity": "Reservation number",
|
||||
"partNumber": "Internal part number",
|
||||
"quantity": "Quantity",
|
||||
"inventorySourceHint": "Inventory source hint"
|
||||
},
|
||||
"schemaName": "Template name",
|
||||
"description": "Description",
|
||||
@@ -308,6 +311,12 @@
|
||||
"enumOptions": "Enum options (comma separated)",
|
||||
"validators": "Content validation",
|
||||
"sourcePrecedence": "Recognizable content sources",
|
||||
"coordinateSources": "Coordinate evidence sources",
|
||||
"coordinateSourcesHint": "Used by order document profile regions. Selecting both only authorizes this field for either template type; it does not merge or vote on coordinates in one extraction. Use PDF coordinates for text-layer PDFs and OCR coordinates for scans.",
|
||||
"coordinateSourceOption": {
|
||||
"pdf_coordinate": "PDF coordinates",
|
||||
"ocr_coordinate": "OCR coordinates"
|
||||
},
|
||||
"extractionInstruction": "Recognition guidance (optional)",
|
||||
"extractionInstructionPlaceholder": "For example: Prefer the manufacturer part number in the order item table",
|
||||
"advancedRules": "Advanced recognition rules",
|
||||
@@ -2501,7 +2510,11 @@
|
||||
"reconstructTable": "Rebuild table candidate",
|
||||
"confirmReconstruction": "I reviewed the rebuilt grid and allow it to be used for this profile draft",
|
||||
"reconstructionPreview": "Logical line reconstruction (continuations merged; manual review required)",
|
||||
"rowRole": { "header": "Field mapping", "data": "Active line", "deleted": "Deleted" },
|
||||
"rowRole": {
|
||||
"header": "Field mapping",
|
||||
"data": "Active line",
|
||||
"deleted": "Deleted"
|
||||
},
|
||||
"sourceRows": "Source visual rows: {rows}",
|
||||
"rebuildAfterFieldMapping": "Field mappings changed. Rebuild the candidate again and review the final logical lines.",
|
||||
"multiSubrowEnabled": "Each line item spans multiple physical rows",
|
||||
@@ -2567,6 +2580,13 @@
|
||||
"code": "Profile code",
|
||||
"name": "Profile name",
|
||||
"schema": "Order schema version",
|
||||
"migrateSchema": "Migrate field version",
|
||||
"migrateSchemaConfirm": "This profile has {count} fields requiring migration. Coordinates will be preserved and an unbound draft will be created. Continue?",
|
||||
"migrateSchemaCreated": "Field migration draft created",
|
||||
"migrationNeedsReview": "Migration draft requires blind-test review",
|
||||
"migrationTitle": "Field version migration",
|
||||
"unbindField": "Unbind and preserve coordinates",
|
||||
"createMigrationDraft": "Create migration draft",
|
||||
"headerRow": "Last header row",
|
||||
"dataRow": "First data row",
|
||||
"multiRowHeaderMapping": "Multi-row header mapping",
|
||||
@@ -2599,6 +2619,120 @@
|
||||
"deleteConfirm": "Delete this profile draft?",
|
||||
"retireConfirm": "Retire the published profile? New runs will no longer use it.",
|
||||
"duplicateTargets": "A target field cannot be mapped from multiple columns: {fields}",
|
||||
"loadFailed": "Failed to load order document profiles"
|
||||
"loadFailed": "Failed to load order document profiles",
|
||||
"candidateCount": "{count} candidates · {status}",
|
||||
"candidateItem": "Candidate {count}",
|
||||
"sourceRows": "Source physical rows: {rows}",
|
||||
"emptyCandidateValue": "No value detected",
|
||||
"noCandidateRows": "No valid item was detected. Check the physical lines, line_no, and field regions.",
|
||||
"blindTest": {
|
||||
"title": "Blind test",
|
||||
"samples": "Samples: {count} · {status}",
|
||||
"notRun": "not run",
|
||||
"expectedRows": "Human truth (JSON array)",
|
||||
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
|
||||
"expectedRowsHint": "Enter at least one human-confirmed line truth; do not copy the candidate output.",
|
||||
"expectedRowsInvalid": "Truth must be a JSON array containing at least one non-empty line object.",
|
||||
"trainingAdded": "Current training sample bound",
|
||||
"addTrainingSample": "Add training sample",
|
||||
"addCurrentSample": "Add current blind sample",
|
||||
"run": "Run",
|
||||
"approve": "Approve"
|
||||
},
|
||||
"workbench": {
|
||||
"intro": "Drag evidence regions on a controlled document page; saved definitions contain no HTML or storage URL.",
|
||||
"openCanvas": "Create draft and open canvas",
|
||||
"loadingPage": "Loading page...",
|
||||
"canvasZoom": "Page zoom",
|
||||
"zoomOut": "Zoom out",
|
||||
"zoomIn": "Zoom in",
|
||||
"fitPage": "Fit page",
|
||||
"hideAnnotationTools": "Hide annotation tools",
|
||||
"showAnnotationTools": "Show annotation tools",
|
||||
"resizeHandle": "Resize region ({direction})",
|
||||
"autoSuggest": "Auto-mark",
|
||||
"autoSuggestRunning": "Auto-marking",
|
||||
"autoSuggestCheckingCoordinates": "Checking character coordinates...",
|
||||
"autoSuggestOcr": "Coordinates are missing; generating OCR coordinate evidence...",
|
||||
"autoSuggestAnalyzing": "Analyzing physical rows and column boundaries...",
|
||||
"autoSuggestApplying": "Generating review markers...",
|
||||
"autoSuggestComplete": "Auto-marking completed. Review the results.",
|
||||
"autoSuggestNoRows": "No item rows were detected for marking.",
|
||||
"autoSuggestFailed": "Auto-marking failed. See the reason below.",
|
||||
"schemaCompatible": "Field-compatible; can be inherited automatically",
|
||||
"schemaBreaking": "Breaking field changes require migration",
|
||||
"regionSuggestionReady": "Review the generated row and column marks, then confirm field bindings before saving.",
|
||||
"unboundColumn": "Unbound column {count}",
|
||||
"drawHeader": "Draw header",
|
||||
"drawLine": "Draw physical line",
|
||||
"drawField": "Draw field",
|
||||
"drawExclusion": "Draw exclusion",
|
||||
"duplicateRegion": "Duplicate region",
|
||||
"duplicateRegionShortcut": "Duplicate region (Ctrl+D)",
|
||||
"uploadSample": "Upload sample",
|
||||
"deleteSample": "Delete sample",
|
||||
"sampleQueued": "Sample uploaded and queued for parsing. It will appear in the sample list when ready.",
|
||||
"deleteSampleConfirm": "Delete template sample {name}? Only samples not bound to a profile or blind test can be deleted.",
|
||||
"regionGuideTitle": "Annotation guide",
|
||||
"regionGuideHeader": "Header: draw only the row containing column names such as ITEM NO, MATERIAL NO, and QUANTITY.",
|
||||
"regionGuideLine": "Physical line: draw the vertical extent of one complete item; for multi-line items, draw each fixed sub-row.",
|
||||
"regionGuideField": "Field: within a physical line, draw only the actual column, then bind its Schema field on the right.",
|
||||
"regionGuideExclusion": "Exclusion: draw deleted markers, totals, footers, and other content that must not become item data.",
|
||||
"selectBoundPdf": "Select a bound PDF sample to load one page.",
|
||||
"canvasUnavailable": "The controlled PDF canvas is temporarily unavailable. Your draft is saved; recognized tables and candidate results remain available for review.",
|
||||
"retryCanvas": "Retry canvas",
|
||||
"recognizedTable": "Recognized table",
|
||||
"noRecognizedTable": "No recognized table is available for this page.",
|
||||
"bindableFields": "Bindable fields",
|
||||
"noBindableFields": "The current schema has no bindable fields.",
|
||||
"review": "Review",
|
||||
"noIssues": "No blocking configuration issue.",
|
||||
"currentConfiguration": "Current configuration",
|
||||
"undo": "Undo",
|
||||
"redo": "Redo",
|
||||
"header": "Header",
|
||||
"matchCurrentHeader": "Match current header",
|
||||
"matchAllHeaders": "Match all headers",
|
||||
"confirmHeaderBinding": "Confirm “{text}” as {field}",
|
||||
"headerBindingUnmapped": "“{text}” does not uniquely match a Schema field. Select one manually.",
|
||||
"applyHeaderBinding": "Apply header column suggestion: {field}",
|
||||
"previewIdle": "Waiting for preview",
|
||||
"previewUpdating": "Updating candidates",
|
||||
"previewReady": "Candidates updated",
|
||||
"previewFailed": "Candidate update failed. Adjust bound fields or try again later.",
|
||||
"coordinateEvidenceUnavailable": "OCR coordinate recovery was attempted, but this sample still cannot produce character-coordinate evidence and cannot be annotated by coordinates.",
|
||||
"mainLine": "Main line",
|
||||
"line": "Physical line",
|
||||
"field": "Field",
|
||||
"exclusion": "Exclusion",
|
||||
"label": "Label",
|
||||
"schemaField": "Schema field",
|
||||
"lineLayout": "Physical line",
|
||||
"selectField": "Select field",
|
||||
"dragHint": "Drag the selected region or its lower-right edge; numeric coordinates stay hidden.",
|
||||
"deleteRegion": "Delete region",
|
||||
"deleteRegionShortcut": "Delete region (Delete)",
|
||||
"chooseRegion": "Choose a region or add one to begin annotation.",
|
||||
"localCandidate": "Local candidate",
|
||||
"rowCount": "{count} rows · {status}",
|
||||
"previewDelay": "Updates 400ms after a region change.",
|
||||
"leaveConfirm": "You have unsaved region changes. Leave this page?",
|
||||
"pageNavigation": "Document pages",
|
||||
"page": "Page {page}",
|
||||
"regionLabels": {
|
||||
"header": "Header {count}",
|
||||
"header_field": "Header field {count}",
|
||||
"line": "Physical line {count}",
|
||||
"field": "Field {count}",
|
||||
"exclusion": "Exclusion {count}"
|
||||
},
|
||||
"issues": {
|
||||
"sample": "Select a controlled sample document.",
|
||||
"table": "Select a table on the current page.",
|
||||
"line": "Add at least one main line layout.",
|
||||
"field": "Bind at least one line field.",
|
||||
"coordinateField": "The current order schema has no enabled line field authorized for PDF-coordinate evidence. Authorize one in the order field template before creating a profile."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,12 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "Another administrator changed the profile. Refresh and try again.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS": "This order document parsing profile already has a draft.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID": "The current order document parsing profile cannot be published.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING": "Bind at least one training sample before publishing.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST": "Complete and approve an independent blind test for the current definition before publishing.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_MULTILINE": "The blind test must include at least one multi-line truth sample before publishing.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE": "This cross-page profile requires a continuation-page blind test sample before publishing.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT": "A blind test sample cannot reuse a training or annotation sample.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_CONFLICT": "This document is already in the current blind test suite.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RETIRE_INVALID": "The current order document parsing profile cannot be retired.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED": "Only a draft order document parsing profile can be deleted.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_CLONE_INVALID": "A new draft can only be created from a published or retired version.",
|
||||
@@ -331,6 +337,9 @@
|
||||
"SHIPPING_CUSTOMER_IMPORT_DECISIONS_REQUIRED": "Resolve all warning rows first.",
|
||||
"SHIPPING_CUSTOMER_IMPORT_ALREADY_PUBLISHED": "The import batch is already published.",
|
||||
"SHIPPING_CUSTOMER_IMPORT_UPLOAD_CONFLICT": "A conflict occurred while staging the import.",
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "A data conflict occurred while publishing the import."
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "A data conflict occurred while publishing the import.",
|
||||
"SHIPPING.ORDER_SCHEMA_PROFILE_IMPACT_CONFIRM_REQUIRED": "This order field version affects existing document profiles. Confirm the impact before publishing.",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID": "The order document profile field migration is invalid.",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_REQUIRED": "Resolve every affected field before creating the migration draft."
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,9 @@
|
||||
"eyebrow": "เทมเพลตฟิลด์คำสั่งซื้อ",
|
||||
"title": "การตั้งค่าเทมเพลตคำสั่งซื้อ",
|
||||
"subtitle": "คำสั่งซื้อ EML, PDF และ Word ทั้งหมดใช้สัญญาฟิลด์ที่เผยแพร่ชุดเดียว และแก้ไขเวอร์ชันที่เผยแพร่แล้วไม่ได้",
|
||||
"profileImpactTitle": "ยืนยันผลกระทบก่อนเผยแพร่",
|
||||
"profileImpactSummary": "มีโปรไฟล์ {profile_count} รายการ: โปรไฟล์ที่เผยแพร่ {breaking_count} รายการมีผลกระทบรุนแรง, {review_required_count} รายการต้องตรวจสอบ และฉบับร่าง {draft_impact_count} รายการได้รับผลกระทบ",
|
||||
"confirmImpactPublish": "ยืนยันผลกระทบและเผยแพร่",
|
||||
"fulfillmentEyebrow": "การกำกับดูแลการจัดส่งของผู้ให้บริการขนส่ง",
|
||||
"fulfillmentTitle": "ความสามารถของฟิลด์และนโยบายการจัดส่ง",
|
||||
"fulfillmentHint": "เฉพาะฟิลด์ที่เข้ากันได้จาก Schema ที่เผยแพร่แล้วเท่านั้นที่ผูกกับความสามารถที่ควบคุมได้ และคำสั่งซื้อที่แช่แข็งจะเก็บสแนปช็อตนโยบายทั้งหมดไว้",
|
||||
@@ -95,10 +98,10 @@
|
||||
"fulfillmentPublished": "เผยแพร่นโยบายการจัดส่งแล้ว คำสั่งซื้อที่แช่แข็งจะไม่ถูกตีความใหม่",
|
||||
"fulfillmentDraftHint": "ร่างนโยบาย V{version} ล็อกการผูกฟิลด์แล้ว โปรดยืนยันและเผยแพร่",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "รหัส Reservation",
|
||||
"fulfillment.part_number": "หมายเลขชิ้นส่วน",
|
||||
"fulfillment.quantity": "จำนวนจัดส่ง",
|
||||
"routing.inventory_source_hint": "คำใบ้การกำหนดเส้นทางแหล่งสต็อก"
|
||||
"reservationIdentity": "หมายเลขจอง",
|
||||
"partNumber": "หมายเลขชิ้นส่วนภายใน",
|
||||
"quantity": "จำนวน",
|
||||
"inventorySourceHint": "คำใบ้แหล่งสต็อก"
|
||||
},
|
||||
"schemaName": "ชื่อเทมเพลต",
|
||||
"description": "คำอธิบาย",
|
||||
@@ -307,6 +310,12 @@
|
||||
"enumOptions": "ตัวเลือก enum (คั่นด้วยจุลภาค)",
|
||||
"validators": "การตรวจสอบเนื้อหา",
|
||||
"sourcePrecedence": "แหล่งเนื้อหาที่อ่านได้",
|
||||
"coordinateSources": "แหล่งหลักฐานพิกัด",
|
||||
"coordinateSourcesHint": "ใช้กับพื้นที่ฟิลด์ของโปรไฟล์เอกสารคำสั่งซื้อ การเลือกทั้งสองเพียงอนุญาตให้ฟิลด์ใช้ได้กับเทมเพลตทั้งสองประเภท ไม่ได้รวมผลหรือลงคะแนนพิกัดในการดึงข้อมูลครั้งเดียว; ใช้ PDF สำหรับไฟล์ที่มีชั้นข้อความ และ OCR สำหรับไฟล์สแกน",
|
||||
"coordinateSourceOption": {
|
||||
"pdf_coordinate": "พิกัด PDF",
|
||||
"ocr_coordinate": "พิกัด OCR"
|
||||
},
|
||||
"extractionInstruction": "คำแนะนำในการอ่านข้อมูล (ไม่บังคับ)",
|
||||
"extractionInstructionPlaceholder": "เช่น ให้อ่านรหัสชิ้นส่วนผู้ผลิตจากตารางรายการสินค้าเป็นลำดับแรก",
|
||||
"advancedRules": "กฎการอ่านขั้นสูง",
|
||||
@@ -2369,7 +2378,11 @@
|
||||
"reconstructTable": "สร้างตารางตัวเลือกใหม่",
|
||||
"confirmReconstruction": "ฉันตรวจทานกริดที่สร้างใหม่แล้ว และอนุญาตให้ใช้กับฉบับร่างนี้",
|
||||
"reconstructionPreview": "รายการตรรกะที่สร้างใหม่ (รวมบรรทัดต่อเนื่องแล้ว ต้องตรวจทานด้วยคน)",
|
||||
"rowRole": { "header": "การแมปฟิลด์", "data": "รายการที่ใช้งาน", "deleted": "ลบแล้ว" },
|
||||
"rowRole": {
|
||||
"header": "การแมปฟิลด์",
|
||||
"data": "รายการที่ใช้งาน",
|
||||
"deleted": "ลบแล้ว"
|
||||
},
|
||||
"sourceRows": "บรรทัดภาพต้นทาง: {rows}",
|
||||
"rebuildAfterFieldMapping": "การแมปฟิลด์เปลี่ยนแปลงแล้ว โปรดสร้างตัวเลือกใหม่อีกครั้งและตรวจทานรายการตรรกะสุดท้าย",
|
||||
"multiSubrowEnabled": "หนึ่งรายการประกอบด้วยหลายบรรทัด",
|
||||
@@ -2435,6 +2448,13 @@
|
||||
"code": "รหัสโปรไฟล์",
|
||||
"name": "ชื่อโปรไฟล์",
|
||||
"schema": "เวอร์ชันสคีมาคำสั่งซื้อ",
|
||||
"migrateSchema": "ย้ายเวอร์ชันฟิลด์",
|
||||
"migrateSchemaConfirm": "โปรไฟล์นี้มีฟิลด์ที่ต้องย้าย {count} รายการ ระบบจะเก็บพิกัดไว้และสร้างฉบับร่างที่ยังไม่ผูกฟิลด์ ดำเนินการต่อหรือไม่",
|
||||
"migrateSchemaCreated": "สร้างฉบับร่างการย้ายฟิลด์แล้ว",
|
||||
"migrationNeedsReview": "ฉบับร่างการย้ายต้องตรวจสอบ blind test ใหม่",
|
||||
"migrationTitle": "การย้ายเวอร์ชันฟิลด์",
|
||||
"unbindField": "ยกเลิกการผูกและเก็บพิกัดไว้",
|
||||
"createMigrationDraft": "สร้างฉบับร่างการย้าย",
|
||||
"headerRow": "แถวหัวตารางสุดท้าย",
|
||||
"dataRow": "แถวข้อมูลแรก",
|
||||
"multiRowHeaderMapping": "การแมปหัวตารางหลายแถว",
|
||||
@@ -2467,6 +2487,120 @@
|
||||
"deleteConfirm": "ยืนยันการลบฉบับร่างโปรไฟล์นี้หรือไม่",
|
||||
"retireConfirm": "ยืนยันยกเลิกใช้งานโปรไฟล์ที่เผยแพร่หรือไม่ งานใหม่จะไม่ใช้งานโปรไฟล์นี้",
|
||||
"duplicateTargets": "ฟิลด์เป้าหมายเดียวกันห้ามแมปจากหลายคอลัมน์: {fields}",
|
||||
"loadFailed": "โหลดโปรไฟล์เอกสารคำสั่งซื้อไม่สำเร็จ"
|
||||
"loadFailed": "โหลดโปรไฟล์เอกสารคำสั่งซื้อไม่สำเร็จ",
|
||||
"candidateCount": "{count} รายการ · {status}",
|
||||
"candidateItem": "รายการ {count}",
|
||||
"sourceRows": "แถวจริงต้นทาง: {rows}",
|
||||
"emptyCandidateValue": "ไม่พบค่า",
|
||||
"noCandidateRows": "ไม่พบรายการที่ถูกต้อง โปรดตรวจสอบแถวจริง line_no และขอบเขตฟิลด์",
|
||||
"blindTest": {
|
||||
"title": "การทดสอบแบบปิดบัง",
|
||||
"samples": "ตัวอย่าง: {count} · {status}",
|
||||
"notRun": "ยังไม่ดำเนินการ",
|
||||
"expectedRows": "ข้อมูลจริงที่ยืนยันโดยคน (อาร์เรย์ JSON)",
|
||||
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
|
||||
"expectedRowsHint": "กรอกข้อมูลจริงของรายการที่มนุษย์ยืนยันอย่างน้อยหนึ่งรายการ ห้ามคัดลอกผลลัพธ์ตัวเลือก.",
|
||||
"expectedRowsInvalid": "ข้อมูลจริงต้องเป็นอาร์เรย์ JSON ที่มีอ็อบเจ็กต์รายการที่ไม่ว่างอย่างน้อยหนึ่งรายการ.",
|
||||
"trainingAdded": "ผูกตัวอย่างการฝึกปัจจุบันแล้ว",
|
||||
"addTrainingSample": "เพิ่มตัวอย่างการฝึก",
|
||||
"addCurrentSample": "เพิ่มตัวอย่างทดสอบปัจจุบัน",
|
||||
"run": "ดำเนินการ",
|
||||
"approve": "อนุมัติ"
|
||||
},
|
||||
"workbench": {
|
||||
"intro": "ลากพื้นที่หลักฐานบนหน้าเอกสารที่ควบคุมไว้ คำนิยามที่บันทึกไม่มี HTML หรือ URL ที่เก็บข้อมูล",
|
||||
"openCanvas": "สร้างฉบับร่างและเปิดผืนงาน",
|
||||
"loadingPage": "กำลังโหลดหน้า...",
|
||||
"canvasZoom": "การซูมหน้า",
|
||||
"zoomOut": "ย่อ",
|
||||
"zoomIn": "ขยาย",
|
||||
"fitPage": "พอดีหน้า",
|
||||
"hideAnnotationTools": "ซ่อนเครื่องมือทำเครื่องหมาย",
|
||||
"showAnnotationTools": "แสดงเครื่องมือทำเครื่องหมาย",
|
||||
"resizeHandle": "ปรับขอบเขตพื้นที่ ({direction})",
|
||||
"autoSuggest": "ทำเครื่องหมายอัตโนมัติ",
|
||||
"autoSuggestRunning": "กำลังทำเครื่องหมายอัตโนมัติ",
|
||||
"autoSuggestCheckingCoordinates": "กำลังตรวจสอบพิกัดอักขระ...",
|
||||
"autoSuggestOcr": "ไม่มีพิกัด กำลังสร้างหลักฐานพิกัดด้วย OCR...",
|
||||
"autoSuggestAnalyzing": "กำลังวิเคราะห์แถวจริงและขอบเขตคอลัมน์...",
|
||||
"autoSuggestApplying": "กำลังสร้างเครื่องหมายสำหรับตรวจทาน...",
|
||||
"autoSuggestComplete": "ทำเครื่องหมายอัตโนมัติเสร็จแล้ว โปรดตรวจทานผลลัพธ์",
|
||||
"autoSuggestNoRows": "ไม่พบแถวรายการสำหรับทำเครื่องหมาย",
|
||||
"autoSuggestFailed": "ทำเครื่องหมายอัตโนมัติไม่สำเร็จ โปรดดูสาเหตุด้านล่าง",
|
||||
"schemaCompatible": "ฟิลด์เข้ากันได้ สามารถสืบทอดอัตโนมัติ",
|
||||
"schemaBreaking": "การเปลี่ยนแปลงฟิลด์ที่ไม่เข้ากันต้องย้ายข้อมูล",
|
||||
"regionSuggestionReady": "สร้างเครื่องหมายแถวและคอลัมน์เพื่อการตรวจทานแล้ว โปรดยืนยันการผูกฟิลด์ก่อนบันทึก",
|
||||
"unboundColumn": "คอลัมน์ที่ยังไม่ผูก {count}",
|
||||
"drawHeader": "วาดหัวตาราง",
|
||||
"drawLine": "วาดแถวจริง",
|
||||
"drawField": "วาดฟิลด์",
|
||||
"drawExclusion": "วาดพื้นที่ยกเว้น",
|
||||
"duplicateRegion": "คัดลอกพื้นที่",
|
||||
"duplicateRegionShortcut": "คัดลอกพื้นที่ (Ctrl+D)",
|
||||
"uploadSample": "อัปโหลดตัวอย่าง",
|
||||
"deleteSample": "ลบตัวอย่าง",
|
||||
"sampleQueued": "อัปโหลดตัวอย่างและเข้าคิววิเคราะห์แล้ว จะแสดงในรายการเมื่อพร้อม",
|
||||
"deleteSampleConfirm": "ลบตัวอย่างเทมเพลต {name} หรือไม่ เฉพาะตัวอย่างที่ไม่ผูกกับโปรไฟล์หรือการทดสอบแบบปิดบังเท่านั้นที่ลบได้",
|
||||
"regionGuideTitle": "คำแนะนำการทำเครื่องหมาย",
|
||||
"regionGuideHeader": "หัวตาราง: วาดเฉพาะแถวชื่อคอลัมน์ เช่น ITEM NO, MATERIAL NO และ QUANTITY",
|
||||
"regionGuideLine": "แถวจริง: วาดขอบเขตแนวตั้งของหนึ่งรายการทั้งหมด หากรายการมีหลายบรรทัดให้วาดแต่ละแถวย่อยคงที่",
|
||||
"regionGuideField": "ฟิลด์: ในแถวจริงให้วาดเฉพาะคอลัมน์จริง แล้วผูกฟิลด์ Schema ด้านขวา",
|
||||
"regionGuideExclusion": "พื้นที่ยกเว้น: วาดข้อความลบ ยอดรวม ส่วนท้าย และเนื้อหาอื่นที่ต้องไม่เป็นข้อมูลรายการ",
|
||||
"selectBoundPdf": "เลือกตัวอย่าง PDF ที่ผูกไว้เพื่อโหลดหนึ่งหน้า",
|
||||
"canvasUnavailable": "ผืนงาน PDF ที่ควบคุมไว้ใช้งานไม่ได้ชั่วคราว ฉบับร่างถูกบันทึกแล้ว และยังตรวจทานตารางกับผลลัพธ์ตัวเลือกได้",
|
||||
"retryCanvas": "ลองผืนงานอีกครั้ง",
|
||||
"recognizedTable": "ตารางที่ตรวจพบ",
|
||||
"noRecognizedTable": "ไม่มีตารางที่ตรวจพบให้แสดงในหน้านี้",
|
||||
"bindableFields": "ฟิลด์ที่ผูกได้",
|
||||
"noBindableFields": "Schema ปัจจุบันไม่มีฟิลด์ที่ผูกได้",
|
||||
"review": "ตรวจทาน",
|
||||
"noIssues": "ไม่มีปัญหาการตั้งค่าที่ขัดขวาง",
|
||||
"currentConfiguration": "การตั้งค่าปัจจุบัน",
|
||||
"undo": "เลิกทำ",
|
||||
"redo": "ทำซ้ำ",
|
||||
"header": "หัวตาราง",
|
||||
"matchCurrentHeader": "จับคู่หัวตารางปัจจุบัน",
|
||||
"matchAllHeaders": "จับคู่หัวตารางทั้งหมด",
|
||||
"confirmHeaderBinding": "ยืนยัน “{text}” เป็น {field}",
|
||||
"headerBindingUnmapped": "“{text}” ไม่ตรงกับฟิลด์ Schema แบบเฉพาะเจาะจง โปรดเลือกด้วยตนเอง",
|
||||
"applyHeaderBinding": "ใช้คำแนะนำคอลัมน์จากหัวตาราง: {field}",
|
||||
"previewIdle": "รอการแสดงตัวอย่าง",
|
||||
"previewUpdating": "กำลังอัปเดตผลลัพธ์",
|
||||
"previewReady": "อัปเดตผลลัพธ์แล้ว",
|
||||
"previewFailed": "อัปเดตผลลัพธ์ไม่สำเร็จ โปรดปรับฟิลด์ที่ผูกไว้หรือลองใหม่ภายหลัง",
|
||||
"coordinateEvidenceUnavailable": "ระบบได้ลองสร้างหลักฐานพิกัดด้วย OCR แล้ว แต่ตัวอย่างนี้ยังสร้างพิกัดระดับอักขระไม่ได้ จึงไม่รองรับการทำเครื่องหมายด้วยพิกัด",
|
||||
"mainLine": "แถวหลัก",
|
||||
"line": "แถวจริง",
|
||||
"field": "ฟิลด์",
|
||||
"exclusion": "พื้นที่ยกเว้น",
|
||||
"label": "ป้ายกำกับ",
|
||||
"schemaField": "ฟิลด์ Schema",
|
||||
"lineLayout": "แถวจริงที่สังกัด",
|
||||
"selectField": "เลือกฟิลด์",
|
||||
"dragHint": "ลากพื้นที่ที่เลือกหรือขอบล่างขวาเพื่อกำหนดตำแหน่ง โดยซ่อนตัวเลขพิกัดไว้",
|
||||
"deleteRegion": "ลบพื้นที่",
|
||||
"deleteRegionShortcut": "ลบพื้นที่ (Delete)",
|
||||
"chooseRegion": "เลือกหรือเพิ่มพื้นที่เพื่อเริ่มทำคำอธิบายประกอบ",
|
||||
"localCandidate": "ผลลัพธ์เฉพาะส่วน",
|
||||
"rowCount": "{count} แถว · {status}",
|
||||
"previewDelay": "อัปเดต 400ms หลังพื้นที่เปลี่ยน",
|
||||
"leaveConfirm": "มีการแก้ไขพื้นที่ที่ยังไม่บันทึก ต้องการออกจากหน้านี้หรือไม่",
|
||||
"pageNavigation": "หน้าเอกสาร",
|
||||
"page": "หน้า {page}",
|
||||
"regionLabels": {
|
||||
"header": "หัวตาราง {count}",
|
||||
"header_field": "ฟิลด์หัวตาราง {count}",
|
||||
"line": "แถวจริง {count}",
|
||||
"field": "ฟิลด์ {count}",
|
||||
"exclusion": "พื้นที่ยกเว้น {count}"
|
||||
},
|
||||
"issues": {
|
||||
"sample": "เลือกเอกสารตัวอย่างที่ควบคุมไว้",
|
||||
"table": "เลือกตารางบนหน้าปัจจุบัน",
|
||||
"line": "เพิ่มโครงร่างแถวหลักอย่างน้อยหนึ่งรายการ",
|
||||
"field": "ผูกฟิลด์รายละเอียดอย่างน้อยหนึ่งรายการ",
|
||||
"coordinateField": "เวอร์ชันฟิลด์คำสั่งซื้อปัจจุบันไม่มีฟิลด์รายการที่เปิดใช้และได้รับอนุญาตให้ใช้หลักฐานพิกัด PDF โปรดอนุญาตในเทมเพลตฟิลด์คำสั่งซื้อก่อนสร้างโปรไฟล์"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,12 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "ผู้ดูแลระบบรายอื่นแก้ไขโปรไฟล์แล้ว โปรดรีเฟรชแล้วลองใหม่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS": "โปรไฟล์เอกสารคำสั่งซื้อนี้มีฉบับร่างอยู่แล้ว",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID": "ไม่สามารถเผยแพร่โปรไฟล์เอกสารคำสั่งซื้อปัจจุบัน",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING": "ต้องผูกตัวอย่างการฝึกอย่างน้อยหนึ่งรายการก่อนเผยแพร่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST": "ต้องทำและอนุมัติการทดสอบแบบปิดบังที่เป็นอิสระสำหรับคำนิยามปัจจุบันก่อนเผยแพร่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_MULTILINE": "การทดสอบแบบปิดบังต้องมีตัวอย่างข้อมูลจริงแบบหลายรายการอย่างน้อยหนึ่งรายการก่อนเผยแพร่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE": "โปรไฟล์ข้ามหน้านี้ต้องมีตัวอย่างการทดสอบแบบปิดบังของหน้าต่อเนื่องก่อนเผยแพร่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT": "ตัวอย่างการทดสอบแบบปิดบังห้ามใช้ซ้ำกับตัวอย่างการฝึกหรือการทำคำอธิบายประกอบ",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_CONFLICT": "เอกสารนี้อยู่ในชุดการทดสอบแบบปิดบังปัจจุบันแล้ว",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RETIRE_INVALID": "ไม่สามารถเลิกใช้โปรไฟล์เอกสารคำสั่งซื้อปัจจุบัน",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED": "ลบได้เฉพาะโปรไฟล์เอกสารคำสั่งซื้อฉบับร่าง",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_CLONE_INVALID": "สร้างฉบับร่างใหม่ได้จากเวอร์ชันที่เผยแพร่หรือเลิกใช้งานแล้วเท่านั้น",
|
||||
@@ -331,6 +337,9 @@
|
||||
"SHIPPING_CUSTOMER_IMPORT_DECISIONS_REQUIRED": "จัดการแถวคำเตือนทั้งหมดก่อน",
|
||||
"SHIPPING_CUSTOMER_IMPORT_ALREADY_PUBLISHED": "ชุดนำเข้าเผยแพร่แล้ว",
|
||||
"SHIPPING_CUSTOMER_IMPORT_UPLOAD_CONFLICT": "เกิดข้อขัดแย้งระหว่างอัปโหลด",
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "เกิดข้อขัดแย้งของข้อมูลระหว่างเผยแพร่"
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "เกิดข้อขัดแย้งของข้อมูลระหว่างเผยแพร่",
|
||||
"SHIPPING.ORDER_SCHEMA_PROFILE_IMPACT_CONFIRM_REQUIRED": "เวอร์ชันฟิลด์คำสั่งซื้อนี้มีผลต่อโปรไฟล์เอกสารที่มีอยู่ โปรดยืนยันผลกระทบก่อนเผยแพร่",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID": "การกำหนดการย้ายฟิลด์ของโปรไฟล์เอกสารคำสั่งซื้อไม่ถูกต้อง",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_REQUIRED": "โปรดจัดการฟิลด์ที่ได้รับผลกระทบทั้งหมดก่อนสร้างฉบับร่างการย้าย"
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,9 @@
|
||||
"eyebrow": "订单字段模板",
|
||||
"title": "订单模板配置",
|
||||
"subtitle": "所有 EML、PDF 和 Word 订单共享同一份已发布字段契约;发布后版本不可原地修改。",
|
||||
"profileImpactTitle": "发布影响确认",
|
||||
"profileImpactSummary": "涉及 {profile_count} 个模板:{breaking_count} 个已发布模板存在破坏性影响,{review_required_count} 个需要复核,{draft_impact_count} 个草稿受影响。",
|
||||
"confirmImpactPublish": "确认影响并发布",
|
||||
"fulfillmentEyebrow": "货代履约治理",
|
||||
"fulfillmentTitle": "字段能力与发货策略",
|
||||
"fulfillmentHint": "仅可把已发布 Schema 中作用域和格式兼容的字段绑定到受控能力;冻结订单会保留完整策略快照。",
|
||||
@@ -96,10 +99,10 @@
|
||||
"fulfillmentPublished": "履约策略已发布,历史冻结订单不会被重解释",
|
||||
"fulfillmentDraftHint": "策略草稿 V{version} 已锁定字段绑定,请确认后发布。",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "Reservation 标识",
|
||||
"fulfillment.part_number": "内部料号",
|
||||
"fulfillment.quantity": "发货数量",
|
||||
"routing.inventory_source_hint": "库存源路由线索"
|
||||
"reservationIdentity": "预约单号",
|
||||
"partNumber": "内部料号",
|
||||
"quantity": "数量",
|
||||
"inventorySourceHint": "库存源线索"
|
||||
},
|
||||
"schemaName": "模板名称",
|
||||
"description": "说明",
|
||||
@@ -337,6 +340,12 @@
|
||||
"enumOptions": "枚举选项(逗号分隔)",
|
||||
"validators": "内容校验",
|
||||
"sourcePrecedence": "可识别的内容来源",
|
||||
"coordinateSources": "坐标取证来源",
|
||||
"coordinateSourcesHint": "用于订单文档模板的字段区域取值。两项都选仅表示该字段可用于两类模板,不会在同一次识别中合并或投票;有文本层选 PDF 坐标,扫描件选 OCR 坐标。",
|
||||
"coordinateSourceOption": {
|
||||
"pdf_coordinate": "PDF 坐标",
|
||||
"ocr_coordinate": "OCR 坐标"
|
||||
},
|
||||
"extractionInstruction": "识别说明(可选)",
|
||||
"extractionInstructionPlaceholder": "例如:优先识别订单明细表中的制造商料号",
|
||||
"advancedRules": "高级识别规则",
|
||||
@@ -2479,7 +2488,11 @@
|
||||
"reconstructTable": "重建表格候选",
|
||||
"confirmReconstruction": "我已审核重建网格,允许将其用于此模板草稿",
|
||||
"reconstructionPreview": "逻辑明细重建候选(续行已合并,待人工审核)",
|
||||
"rowRole": { "header": "字段映射", "data": "有效明细", "deleted": "已删除" },
|
||||
"rowRole": {
|
||||
"header": "字段映射",
|
||||
"data": "有效明细",
|
||||
"deleted": "已删除"
|
||||
},
|
||||
"sourceRows": "来源物理行:{rows}",
|
||||
"rebuildAfterFieldMapping": "字段映射已变化,请再次点击“重建表格候选”并审核最终逻辑明细。",
|
||||
"multiSubrowEnabled": "此模板的一条明细由多行组成",
|
||||
@@ -2545,6 +2558,13 @@
|
||||
"code": "模板编码",
|
||||
"name": "模板名称",
|
||||
"schema": "订单字段版本",
|
||||
"migrateSchema": "迁移字段版本",
|
||||
"migrateSchemaConfirm": "该模板有 {count} 个字段需要迁移。将保留坐标并生成待绑定草稿,是否继续?",
|
||||
"migrateSchemaCreated": "已创建字段迁移草稿",
|
||||
"migrationNeedsReview": "迁移草稿需要重新盲测",
|
||||
"migrationTitle": "字段版本迁移",
|
||||
"unbindField": "解除绑定并保留坐标",
|
||||
"createMigrationDraft": "创建迁移草稿",
|
||||
"headerRow": "表头结束行",
|
||||
"dataRow": "数据起始行",
|
||||
"multiRowHeaderMapping": "多行表头字段映射",
|
||||
@@ -2577,6 +2597,120 @@
|
||||
"deleteConfirm": "确认删除此模板草稿?",
|
||||
"retireConfirm": "确认退役当前发布模板?新运行将不再使用它。",
|
||||
"duplicateTargets": "同一目标字段不能由多列重复映射:{fields}",
|
||||
"loadFailed": "订单文档模板加载失败"
|
||||
"loadFailed": "订单文档模板加载失败",
|
||||
"candidateCount": "{count} 条候选 · {status}",
|
||||
"candidateItem": "候选 {count}",
|
||||
"sourceRows": "来源物理行:{rows}",
|
||||
"emptyCandidateValue": "未识别到值",
|
||||
"noCandidateRows": "当前标注没有识别到有效明细,请检查物理行、line_no 和字段范围。",
|
||||
"blindTest": {
|
||||
"title": "盲测",
|
||||
"samples": "样本:{count} · {status}",
|
||||
"notRun": "未执行",
|
||||
"expectedRows": "人工真值(JSON 数组)",
|
||||
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
|
||||
"expectedRowsHint": "请输入至少一条人工确认的明细真值;不能复制候选结果。",
|
||||
"expectedRowsInvalid": "真值必须是至少包含一条非空明细对象的 JSON 数组。",
|
||||
"trainingAdded": "已绑定当前训练样本",
|
||||
"addTrainingSample": "添加训练样本",
|
||||
"addCurrentSample": "添加当前盲测样本",
|
||||
"run": "执行",
|
||||
"approve": "批准"
|
||||
},
|
||||
"workbench": {
|
||||
"intro": "在受控文档页面拖拽证据区域;保存定义不含 HTML 或存储地址。",
|
||||
"openCanvas": "创建草稿并打开画布",
|
||||
"loadingPage": "正在加载页面…",
|
||||
"canvasZoom": "页面缩放",
|
||||
"zoomOut": "缩小",
|
||||
"zoomIn": "放大",
|
||||
"fitPage": "适合页面",
|
||||
"hideAnnotationTools": "隐藏标注工具",
|
||||
"showAnnotationTools": "显示标注工具",
|
||||
"resizeHandle": "调整区域边界({direction})",
|
||||
"autoSuggest": "自动标记",
|
||||
"autoSuggestRunning": "正在自动标记",
|
||||
"autoSuggestCheckingCoordinates": "正在检查字符坐标…",
|
||||
"autoSuggestOcr": "缺少坐标,正在生成 OCR 坐标证据…",
|
||||
"autoSuggestAnalyzing": "正在分析物理行与列边界…",
|
||||
"autoSuggestApplying": "正在生成待复核标记…",
|
||||
"autoSuggestComplete": "自动标记完成,请复核结果。",
|
||||
"autoSuggestNoRows": "未检测到可用于标记的明细行。",
|
||||
"autoSuggestFailed": "自动标记失败,请查看下方原因。",
|
||||
"schemaCompatible": "字段兼容,可自动继承",
|
||||
"schemaBreaking": "字段版本存在不兼容变更,需要迁移",
|
||||
"regionSuggestionReady": "已生成待复核的行和列标记,请确认字段绑定后保存。",
|
||||
"unboundColumn": "待绑定列 {count}",
|
||||
"drawHeader": "绘制表头",
|
||||
"drawLine": "绘制物理行",
|
||||
"drawField": "绘制字段",
|
||||
"drawExclusion": "绘制排除区",
|
||||
"duplicateRegion": "复制区域",
|
||||
"duplicateRegionShortcut": "复制区域(Ctrl+D)",
|
||||
"uploadSample": "上传样本",
|
||||
"deleteSample": "删除样本",
|
||||
"sampleQueued": "样本已上传,正在解析;完成后将出现在样本文档列表。",
|
||||
"deleteSampleConfirm": "确认删除模板样本 {name}?未绑定模板或盲测的样本才可删除。",
|
||||
"regionGuideTitle": "标记说明",
|
||||
"regionGuideHeader": "表头:只框列名所在的一行,例如 ITEM NO、MATERIAL NO、QUANTITY。",
|
||||
"regionGuideLine": "物理行:框一条完整明细的上下范围;多行明细时每个固定子行各绘制一个物理行。",
|
||||
"regionGuideField": "字段:在物理行内只框一个字段的实际列,再绑定右侧 Schema 字段。",
|
||||
"regionGuideExclusion": "排除区:框删除提示、合计、页脚等不应作为明细识别的内容。",
|
||||
"selectBoundPdf": "选择已绑定的 PDF 样本以加载页面。",
|
||||
"canvasUnavailable": "受控 PDF 画布暂不可用;草稿已保存,仍可复核识别表格与候选结果。",
|
||||
"retryCanvas": "重试画布",
|
||||
"recognizedTable": "识别到的表格",
|
||||
"noRecognizedTable": "当前页没有可显示的识别表格。",
|
||||
"bindableFields": "可绑定字段",
|
||||
"noBindableFields": "当前 Schema 没有可绑定字段。",
|
||||
"review": "复核",
|
||||
"noIssues": "没有阻断配置问题。",
|
||||
"currentConfiguration": "当前配置",
|
||||
"undo": "撤销",
|
||||
"redo": "重做",
|
||||
"header": "表头",
|
||||
"matchCurrentHeader": "匹配当前表头",
|
||||
"matchAllHeaders": "匹配全部表头",
|
||||
"confirmHeaderBinding": "确认“{text}”绑定为 {field}",
|
||||
"headerBindingUnmapped": "“{text}”未唯一匹配 Schema 字段,请手动选择",
|
||||
"applyHeaderBinding": "采用表头列建议:{field}",
|
||||
"previewIdle": "等待预览",
|
||||
"previewUpdating": "正在更新候选",
|
||||
"previewReady": "候选已更新",
|
||||
"previewFailed": "候选更新失败,请调整已绑定字段或稍后重试",
|
||||
"coordinateEvidenceUnavailable": "已自动尝试 OCR 坐标补证,但当前样本仍无法生成字符坐标证据,不能进行坐标标注。",
|
||||
"mainLine": "主行",
|
||||
"line": "物理行",
|
||||
"field": "字段",
|
||||
"exclusion": "排除区",
|
||||
"label": "标签",
|
||||
"schemaField": "Schema 字段",
|
||||
"lineLayout": "所属物理行",
|
||||
"selectField": "选择字段",
|
||||
"dragHint": "在页面上拖动或拖右下角边界定位;刻意不显示坐标数字。",
|
||||
"deleteRegion": "删除区域",
|
||||
"deleteRegionShortcut": "删除区域(Delete)",
|
||||
"chooseRegion": "选择一个区域或添加区域后开始标注。",
|
||||
"localCandidate": "局部候选",
|
||||
"rowCount": "{count} 行 · {status}",
|
||||
"previewDelay": "区域变化 400ms 后更新。",
|
||||
"leaveConfirm": "当前区域修改尚未保存,确定离开吗?",
|
||||
"pageNavigation": "文档页码",
|
||||
"page": "第 {page} 页",
|
||||
"regionLabels": {
|
||||
"header": "表头 {count}",
|
||||
"header_field": "表头字段 {count}",
|
||||
"line": "物理行 {count}",
|
||||
"field": "字段 {count}",
|
||||
"exclusion": "排除区 {count}"
|
||||
},
|
||||
"issues": {
|
||||
"sample": "请选择受控样本文档。",
|
||||
"table": "请选择当前页的表格。",
|
||||
"line": "请至少添加一个主行布局。",
|
||||
"field": "请至少绑定一个明细字段。",
|
||||
"coordinateField": "当前订单字段版本没有授权 PDF 坐标来源的启用明细字段,请先在订单字段模板中授权后再创建。"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,12 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "订单文档解析模板已被其他管理员修改,请刷新后重试。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS": "该订单文档解析模板已有草稿版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID": "当前订单文档解析模板不能发布。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING": "发布前必须至少绑定一个训练样本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST": "发布前必须完成当前定义的独立盲测并获得批准。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_MULTILINE": "发布前盲测必须包含至少一份多明细真值样本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE": "该跨页模板发布前盲测必须包含续页样本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT": "盲测样本不能复用训练或标注样本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_CONFLICT": "该文档已在当前盲测集中。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RETIRE_INVALID": "当前订单文档解析模板不能退役。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED": "只有草稿订单文档解析模板可以删除。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_CLONE_INVALID": "只能从已发布或已退役版本创建新草稿。",
|
||||
@@ -331,6 +337,9 @@
|
||||
"SHIPPING_CUSTOMER_IMPORT_DECISIONS_REQUIRED": "请先处理全部警告行。",
|
||||
"SHIPPING_CUSTOMER_IMPORT_ALREADY_PUBLISHED": "导入批次已发布。",
|
||||
"SHIPPING_CUSTOMER_IMPORT_UPLOAD_CONFLICT": "上传导入批次时发生冲突。",
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "发布导入批次时发生数据冲突。"
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "发布导入批次时发生数据冲突。",
|
||||
"SHIPPING.ORDER_SCHEMA_PROFILE_IMPACT_CONFIRM_REQUIRED": "订单字段版本会影响现有文档模板,请确认影响后再发布。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID": "订单文档模板字段迁移配置无效。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_REQUIRED": "请处理全部受影响字段后再创建迁移草稿。"
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,9 @@
|
||||
"eyebrow": "訂單欄位範本",
|
||||
"title": "訂單範本設定",
|
||||
"subtitle": "所有 EML、PDF 和 Word 訂單共享同一份已發布欄位契約;發布後版本不可原地修改。",
|
||||
"profileImpactTitle": "發布影響確認",
|
||||
"profileImpactSummary": "涉及 {profile_count} 個範本:{breaking_count} 個已發布範本存在破壞性影響,{review_required_count} 個需要複核,{draft_impact_count} 個草稿受影響。",
|
||||
"confirmImpactPublish": "確認影響並發布",
|
||||
"fulfillmentEyebrow": "貨代履約治理",
|
||||
"fulfillmentTitle": "欄位能力與出貨策略",
|
||||
"fulfillmentHint": "只能把已發布 Schema 中範圍和格式相容的欄位綁定到受控能力;凍結訂單會保留完整策略快照。",
|
||||
@@ -95,10 +98,10 @@
|
||||
"fulfillmentPublished": "履約策略已發布,歷史凍結訂單不會被重新解讀",
|
||||
"fulfillmentDraftHint": "策略草稿 V{version} 已鎖定欄位綁定,請確認後發布。",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "Reservation 識別",
|
||||
"fulfillment.part_number": "內部料號",
|
||||
"fulfillment.quantity": "出貨數量",
|
||||
"routing.inventory_source_hint": "庫存來源路由線索"
|
||||
"reservationIdentity": "預約單號",
|
||||
"partNumber": "內部料號",
|
||||
"quantity": "數量",
|
||||
"inventorySourceHint": "庫存來源線索"
|
||||
},
|
||||
"schemaName": "範本名稱",
|
||||
"description": "說明",
|
||||
@@ -307,6 +310,12 @@
|
||||
"enumOptions": "列舉選項(逗號分隔)",
|
||||
"validators": "內容校驗",
|
||||
"sourcePrecedence": "可識別的內容來源",
|
||||
"coordinateSources": "座標取證來源",
|
||||
"coordinateSourcesHint": "用於訂單文件範本的欄位區域取值。兩項都選僅表示該欄位可用於兩類範本,不會在同一次識別中合併或投票;有文字層選 PDF 座標,掃描件選 OCR 座標。",
|
||||
"coordinateSourceOption": {
|
||||
"pdf_coordinate": "PDF 座標",
|
||||
"ocr_coordinate": "OCR 座標"
|
||||
},
|
||||
"extractionInstruction": "識別說明(可選)",
|
||||
"extractionInstructionPlaceholder": "例如:優先識別訂單明細表中的製造商料號",
|
||||
"advancedRules": "進階識別規則",
|
||||
@@ -2369,7 +2378,11 @@
|
||||
"reconstructTable": "重建表格候選",
|
||||
"confirmReconstruction": "我已複核重建網格,允許將其用於此範本草稿",
|
||||
"reconstructionPreview": "邏輯明細重建候選(續行已合併,需人工複核)",
|
||||
"rowRole": { "header": "欄位映射", "data": "有效明細", "deleted": "已刪除" },
|
||||
"rowRole": {
|
||||
"header": "欄位映射",
|
||||
"data": "有效明細",
|
||||
"deleted": "已刪除"
|
||||
},
|
||||
"sourceRows": "來源實體行:{rows}",
|
||||
"rebuildAfterFieldMapping": "欄位映射已變更,請再次點擊「重建表格候選」並複核最終邏輯明細。",
|
||||
"multiSubrowEnabled": "此範本的一筆明細由多行組成",
|
||||
@@ -2435,6 +2448,13 @@
|
||||
"code": "範本編碼",
|
||||
"name": "範本名稱",
|
||||
"schema": "訂單欄位版本",
|
||||
"migrateSchema": "遷移欄位版本",
|
||||
"migrateSchemaConfirm": "此模板有 {count} 個欄位需要遷移。將保留座標並建立待綁定草稿,是否繼續?",
|
||||
"migrateSchemaCreated": "已建立欄位遷移草稿",
|
||||
"migrationNeedsReview": "遷移草稿需要重新盲測",
|
||||
"migrationTitle": "欄位版本遷移",
|
||||
"unbindField": "解除綁定並保留座標",
|
||||
"createMigrationDraft": "建立遷移草稿",
|
||||
"headerRow": "表頭結束列",
|
||||
"dataRow": "資料起始列",
|
||||
"multiRowHeaderMapping": "多列表頭欄位對應",
|
||||
@@ -2467,6 +2487,120 @@
|
||||
"deleteConfirm": "確認刪除此範本草稿?",
|
||||
"retireConfirm": "確認退役目前發布範本?新執行將不再使用它。",
|
||||
"duplicateTargets": "同一目標欄位不可由多欄重複對應:{fields}",
|
||||
"loadFailed": "訂單文件範本載入失敗"
|
||||
"loadFailed": "訂單文件範本載入失敗",
|
||||
"candidateCount": "{count} 筆候選 · {status}",
|
||||
"candidateItem": "候選 {count}",
|
||||
"sourceRows": "來源實體行:{rows}",
|
||||
"emptyCandidateValue": "未識別到值",
|
||||
"noCandidateRows": "目前標註未識別到有效明細,請檢查實體行、line_no 與欄位範圍。",
|
||||
"blindTest": {
|
||||
"title": "盲測",
|
||||
"samples": "樣本:{count} · {status}",
|
||||
"notRun": "尚未執行",
|
||||
"expectedRows": "人工真值(JSON 陣列)",
|
||||
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
|
||||
"expectedRowsHint": "請輸入至少一筆人工確認的明細真值;不可複製候選結果。",
|
||||
"expectedRowsInvalid": "真值必須是至少包含一個非空明細物件的 JSON 陣列。",
|
||||
"trainingAdded": "已綁定目前訓練樣本",
|
||||
"addTrainingSample": "新增訓練樣本",
|
||||
"addCurrentSample": "新增目前盲測樣本",
|
||||
"run": "執行",
|
||||
"approve": "批准"
|
||||
},
|
||||
"workbench": {
|
||||
"intro": "在受控文件頁面拖曳證據區域;儲存定義不含 HTML 或儲存位址。",
|
||||
"openCanvas": "建立草稿並開啟畫布",
|
||||
"loadingPage": "正在載入頁面…",
|
||||
"canvasZoom": "頁面縮放",
|
||||
"zoomOut": "縮小",
|
||||
"zoomIn": "放大",
|
||||
"fitPage": "適合頁面",
|
||||
"hideAnnotationTools": "隱藏標注工具",
|
||||
"showAnnotationTools": "顯示標注工具",
|
||||
"resizeHandle": "調整區域邊界({direction})",
|
||||
"autoSuggest": "自動標記",
|
||||
"autoSuggestRunning": "正在自動標記",
|
||||
"autoSuggestCheckingCoordinates": "正在檢查字元座標…",
|
||||
"autoSuggestOcr": "缺少座標,正在產生 OCR 座標證據…",
|
||||
"autoSuggestAnalyzing": "正在分析實體行與欄位邊界…",
|
||||
"autoSuggestApplying": "正在產生待複核標記…",
|
||||
"autoSuggestComplete": "自動標記完成,請複核結果。",
|
||||
"autoSuggestNoRows": "未偵測到可用於標記的明細行。",
|
||||
"autoSuggestFailed": "自動標記失敗,請查看下方原因。",
|
||||
"schemaCompatible": "欄位相容,可自動繼承",
|
||||
"schemaBreaking": "欄位版本存在不相容變更,需要遷移",
|
||||
"regionSuggestionReady": "已產生待複核的行和欄位標記,請確認欄位綁定後儲存。",
|
||||
"unboundColumn": "待綁定欄 {count}",
|
||||
"drawHeader": "繪製表頭",
|
||||
"drawLine": "繪製實體行",
|
||||
"drawField": "繪製欄位",
|
||||
"drawExclusion": "繪製排除區",
|
||||
"duplicateRegion": "複製區域",
|
||||
"duplicateRegionShortcut": "複製區域(Ctrl+D)",
|
||||
"uploadSample": "上傳樣本",
|
||||
"deleteSample": "刪除樣本",
|
||||
"sampleQueued": "樣本已上傳,正在解析;完成後將出現在樣本文件清單。",
|
||||
"deleteSampleConfirm": "確認刪除範本樣本 {name}?只有未綁定範本或盲測的樣本可刪除。",
|
||||
"regionGuideTitle": "標記說明",
|
||||
"regionGuideHeader": "表頭:只框欄名所在的一行,例如 ITEM NO、MATERIAL NO、QUANTITY。",
|
||||
"regionGuideLine": "實體行:框一筆完整明細的上下範圍;多行明細時每個固定子行各繪製一個實體行。",
|
||||
"regionGuideField": "欄位:在實體行內只框一個欄位的實際欄,再綁定右側 Schema 欄位。",
|
||||
"regionGuideExclusion": "排除區:框刪除提示、合計、頁尾等不應作為明細識別的內容。",
|
||||
"selectBoundPdf": "選擇已綁定的 PDF 樣本以載入頁面。",
|
||||
"canvasUnavailable": "受控 PDF 畫布暫時無法使用;草稿已儲存,仍可複核識別表格與候選結果。",
|
||||
"retryCanvas": "重試畫布",
|
||||
"recognizedTable": "識別到的表格",
|
||||
"noRecognizedTable": "目前頁面沒有可顯示的識別表格。",
|
||||
"bindableFields": "可綁定欄位",
|
||||
"noBindableFields": "目前 Schema 沒有可綁定欄位。",
|
||||
"review": "複核",
|
||||
"noIssues": "沒有阻斷設定問題。",
|
||||
"currentConfiguration": "目前設定",
|
||||
"undo": "復原",
|
||||
"redo": "重做",
|
||||
"header": "表頭",
|
||||
"matchCurrentHeader": "比對目前表頭",
|
||||
"matchAllHeaders": "比對全部表頭",
|
||||
"confirmHeaderBinding": "確認「{text}」綁定為 {field}",
|
||||
"headerBindingUnmapped": "「{text}」未唯一比對 Schema 欄位,請手動選擇",
|
||||
"applyHeaderBinding": "採用表頭欄位建議:{field}",
|
||||
"previewIdle": "等待預覽",
|
||||
"previewUpdating": "正在更新候選結果",
|
||||
"previewReady": "候選結果已更新",
|
||||
"previewFailed": "候選結果更新失敗,請調整已綁定欄位或稍後重試",
|
||||
"coordinateEvidenceUnavailable": "已自動嘗試 OCR 座標補證,但目前樣本仍無法產生字元座標證據,不能進行座標標註。",
|
||||
"mainLine": "主行",
|
||||
"line": "實體行",
|
||||
"field": "欄位",
|
||||
"exclusion": "排除區",
|
||||
"label": "標籤",
|
||||
"schemaField": "Schema 欄位",
|
||||
"lineLayout": "所屬實體行",
|
||||
"selectField": "選擇欄位",
|
||||
"dragHint": "在頁面拖曳或拖右下角邊界定位;刻意不顯示座標數字。",
|
||||
"deleteRegion": "刪除區域",
|
||||
"deleteRegionShortcut": "刪除區域(Delete)",
|
||||
"chooseRegion": "選擇一個區域或新增區域後開始標註。",
|
||||
"localCandidate": "局部候選",
|
||||
"rowCount": "{count} 行 · {status}",
|
||||
"previewDelay": "區域變更 400ms 後更新。",
|
||||
"leaveConfirm": "目前區域修改尚未儲存,確定離開嗎?",
|
||||
"pageNavigation": "文件頁碼",
|
||||
"page": "第 {page} 頁",
|
||||
"regionLabels": {
|
||||
"header": "表頭 {count}",
|
||||
"header_field": "表頭欄位 {count}",
|
||||
"line": "實體行 {count}",
|
||||
"field": "欄位 {count}",
|
||||
"exclusion": "排除區 {count}"
|
||||
},
|
||||
"issues": {
|
||||
"sample": "請選擇受控樣本文檔。",
|
||||
"table": "請選擇目前頁面的表格。",
|
||||
"line": "請至少新增一個主行布局。",
|
||||
"field": "請至少綁定一個明細欄位。",
|
||||
"coordinateField": "目前訂單欄位版本沒有授權 PDF 座標來源的啟用明細欄位,請先在訂單欄位範本中授權後再建立。"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,12 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "訂單文件解析範本已被其他管理員修改,請重新整理後再試。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS": "此訂單文件解析範本已有草稿版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID": "目前訂單文件解析範本不能發布。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING": "發布前必須至少綁定一個訓練樣本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST": "發布前必須完成目前定義的獨立盲測並獲得批准。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_MULTILINE": "發布前盲測必須包含至少一份多明細真值樣本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE": "此跨頁範本發布前盲測必須包含續頁樣本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT": "盲測樣本不可重用訓練或標註樣本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_CONFLICT": "該文件已在目前盲測集中。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RETIRE_INVALID": "目前訂單文件解析範本不能退役。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED": "只有草稿訂單文件解析範本可以刪除。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_CLONE_INVALID": "只能從已發布或已退役版本建立新草稿。",
|
||||
@@ -331,6 +337,9 @@
|
||||
"SHIPPING_CUSTOMER_IMPORT_DECISIONS_REQUIRED": "請先處理全部警告行。",
|
||||
"SHIPPING_CUSTOMER_IMPORT_ALREADY_PUBLISHED": "匯入批次已發佈。",
|
||||
"SHIPPING_CUSTOMER_IMPORT_UPLOAD_CONFLICT": "上傳匯入批次時發生衝突。",
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "發佈匯入批次時發生資料衝突。"
|
||||
"SHIPPING_CUSTOMER_IMPORT_PUBLISH_CONFLICT": "發佈匯入批次時發生資料衝突。",
|
||||
"SHIPPING.ORDER_SCHEMA_PROFILE_IMPACT_CONFIRM_REQUIRED": "訂單欄位版本會影響現有文件範本,請確認影響後再發布。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID": "訂單文件範本欄位遷移設定無效。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_REQUIRED": "請處理全部受影響欄位後再建立遷移草稿。"
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,14 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED` | 真实上传浏览器自动化总开关,默认 `false` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT` | 最终提交二次确认,默认 `false` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL` | 非 DSV 站点的已审核上传页面 URL(仅由受控环境变量注入) |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` | DSV Portal 入口;Worker 复用登录态,优先 `My Applications > Upload Tool`,再退回 `Apps > Upload Tool` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR` | 文件输入框 CSS selector |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR` | 提交按钮 CSS selector |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR` | 成功状态 CSS selector;未出现不得回调成功 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR` | 可选的货代回执号 CSS selector |
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | 与后端 `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 一致;Worker 在 **inventory_triggers** 目录写哨兵 `.hxops_rpa_shared_mount` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 |
|
||||
@@ -38,6 +46,19 @@ Windows test/prod 部署脚本:`scripts/rpa/set_rpa_worker_env.ps1`(详见 `
|
||||
`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。历史 `FREIGHT_RPA_*`、`SHIPPING_RPA_*`
|
||||
仅在迁移期兼容读取,不得用于新部署。
|
||||
|
||||
### DSV WMS Upload Tool
|
||||
|
||||
已确认 DSV 上传页为 `WMS Upload Tool > Upload`,页面有 `Browse` 文件选择入口和
|
||||
`History` 查询入口。`Browse` 的真实 DOM 是 `<input id="file2" type="file">`,因此
|
||||
DSV Worker 默认使用 `#file2`,也可用 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR`
|
||||
覆盖。选择文件后出现的真实提交控件为 `<button class="btn btn-primary upload-button">`
|
||||
(文案 `Process File`),DSV Worker 默认使用
|
||||
`button.upload-button:has-text("Process File")`,亦可通过
|
||||
`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR` 覆盖。DSV 成功不依赖 toast:Worker
|
||||
切换到 `History`,仅在同名文件行同时存在绿色
|
||||
`em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #` 时回调成功,Reference
|
||||
作为货代回执号。CRANE 上传路径尚未确认,Worker 会显式失败,绝不会误用 DSV 页面。
|
||||
|
||||
## 部署、启动与停止手册
|
||||
|
||||
本节说明库存 RPA 测试导出的三种运行方式:
|
||||
|
||||
@@ -27,6 +27,11 @@ Optional:
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
|
||||
SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1166,6 +1171,197 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
|
||||
|
||||
def _upload_worker_enabled() -> bool:
|
||||
"""返回上传浏览器自动化开关;默认关闭,避免仅部署 Worker 就提交货代文件。"""
|
||||
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false").lower() == "true"
|
||||
|
||||
|
||||
def _upload_submit_confirmed() -> bool:
|
||||
"""返回真实提交二次确认开关;页面填文件与最终提交必须显式分开授权。"""
|
||||
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "false").lower() == "true"
|
||||
|
||||
|
||||
def _click_dsv_upload_tool_entry(page: Any, *, section: str | None = None) -> bool:
|
||||
"""点击已确认的 DSV Upload Tool 入口;返回是否已打开 WMS 上传页。"""
|
||||
section_selector = (
|
||||
f":has-text({json.dumps(section)})" if section else ""
|
||||
)
|
||||
selectors = (
|
||||
f"{section_selector} a:has-text('Upload Tool')" if section else "",
|
||||
f"{section_selector} button:has-text('Upload Tool')" if section else "",
|
||||
"a:has-text('Upload Tool')" if not section else "",
|
||||
"button:has-text('Upload Tool')" if not section else "",
|
||||
"[role='link']:has-text('Upload Tool')" if not section else "",
|
||||
)
|
||||
for selector in (item for item in selectors if item):
|
||||
try:
|
||||
locator = page.locator(selector).first
|
||||
locator.wait_for(state="visible", timeout=3_000)
|
||||
locator.click(timeout=3_000)
|
||||
page.get_by_text("WMS Upload Tool", exact=False).first.wait_for(
|
||||
state="visible", timeout=_browser_timeout_ms()
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _navigate_dsv_to_upload_tool(page: Any, entry_url: str) -> None:
|
||||
"""
|
||||
复用 DSV 登录态进入 WMS Upload Tool,优先首页入口,再退回 Apps 菜单。
|
||||
|
||||
Args:
|
||||
page: 已由 Worker 创建的 Playwright 页面。
|
||||
entry_url: 已审核的 DSV Portal 入口,不允许用代码猜测站点地址。
|
||||
|
||||
Raises:
|
||||
RuntimeError: Portal 未提供截图已确认的任一 Upload Tool 入口时抛出。
|
||||
"""
|
||||
_ensure_dsv_session(page, entry_url)
|
||||
if _click_dsv_upload_tool_entry(page, section="My Applications"):
|
||||
return
|
||||
|
||||
for selector in (
|
||||
"nav a:has-text('Apps')",
|
||||
"a.nav-link:has-text('Apps')",
|
||||
"[role='button']:has-text('Apps')",
|
||||
):
|
||||
try:
|
||||
apps = page.locator(selector).first
|
||||
apps.wait_for(state="visible", timeout=3_000)
|
||||
apps.click(timeout=3_000, force=True)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if _click_dsv_upload_tool_entry(page):
|
||||
return
|
||||
raise RuntimeError("DSV WMS Upload Tool was not found via My Applications or Apps")
|
||||
|
||||
|
||||
def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> str:
|
||||
"""仅以 DSV History 的同名绿色行和 Reference # 确认上传受理。"""
|
||||
try:
|
||||
page.get_by_text("History", exact=True).first.click(timeout=_browser_timeout_ms())
|
||||
except Exception as exc:
|
||||
raise RuntimeError("DSV Upload History tab was not available") from exc
|
||||
|
||||
receipt_script = """
|
||||
({ filename }) => {
|
||||
const clean = (value) => String(value || '').replace(/\\s+/g, ' ').trim();
|
||||
for (const table of document.querySelectorAll('table')) {
|
||||
const headers = Array.from(table.querySelectorAll('thead th')).map((node) => clean(node.textContent));
|
||||
const filenameIndex = headers.findIndex((value) => value.toLowerCase() === 'filename');
|
||||
const referenceIndex = headers.findIndex((value) => value.toLowerCase() === 'reference #');
|
||||
if (filenameIndex < 0 || referenceIndex < 0) continue;
|
||||
for (const row of table.querySelectorAll('tbody tr')) {
|
||||
const cells = Array.from(row.querySelectorAll(':scope > td'));
|
||||
if (clean(cells[filenameIndex]?.textContent) !== filename) continue;
|
||||
return {
|
||||
found: true,
|
||||
succeeded: Boolean(row.querySelector('em.fa.fa-circle.success-color.status-icon')),
|
||||
reference: clean(cells[referenceIndex]?.textContent),
|
||||
};
|
||||
}
|
||||
}
|
||||
return { found: false, succeeded: false, reference: '' };
|
||||
}
|
||||
"""
|
||||
deadline = time.monotonic() + (_browser_timeout_ms() / 1000)
|
||||
last_state: dict[str, Any] = {"found": False, "succeeded": False, "reference": ""}
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = page.evaluate(receipt_script, {"filename": filename}) or {}
|
||||
last_state = state if isinstance(state, dict) else last_state
|
||||
except Exception:
|
||||
last_state = {"found": False, "succeeded": False, "reference": ""}
|
||||
reference = str(last_state.get("reference") or "").strip()
|
||||
if bool(last_state.get("succeeded")) and reference:
|
||||
return reference
|
||||
time.sleep(1)
|
||||
raise RuntimeError(
|
||||
"DSV upload History did not confirm a green success status and Reference # "
|
||||
f"for {filename!r}; last_state={last_state}"
|
||||
)
|
||||
|
||||
|
||||
def _upload_shipment_with_browser(
|
||||
file_path: Path, *, connector_type: str = "", dsv_entry_url: str = ""
|
||||
) -> str | None:
|
||||
"""
|
||||
在受控配置下执行货代 Excel 上传,并以页面成功证据作为回调成功前提。
|
||||
|
||||
触发条件:仅当 Worker 非 mock、上传与最终提交两个开关均为 true,且 URL、文件
|
||||
控件、提交控件和成功标识均已配置时执行。未满足任何条件时抛异常并回调失败,绝不
|
||||
猜测站点、选择器或提交按钮。
|
||||
|
||||
Args:
|
||||
file_path: 已由 HXOPS 写入共享上传队列且存在的 Excel 文件。
|
||||
|
||||
Returns:
|
||||
可选货代回执号;页面未配置回执选择器时返回 None。
|
||||
"""
|
||||
if not _upload_worker_enabled():
|
||||
raise RuntimeError("upload RPA is disabled; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=true after validation")
|
||||
if not _upload_submit_confirmed():
|
||||
raise RuntimeError("upload RPA submit is not confirmed; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=true after dry run")
|
||||
normalized_connector = _worker_connector_type({"connector_type": connector_type}) if connector_type else ""
|
||||
upload_url = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL")
|
||||
file_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR")
|
||||
submit_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR")
|
||||
success_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR")
|
||||
if normalized_connector == "crane_footprint":
|
||||
raise RuntimeError("CRANE upload RPA is not implemented because its upload path is unverified")
|
||||
if normalized_connector == "dsv360":
|
||||
dsv_entry_url = dsv_entry_url or _env("SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL")
|
||||
if not dsv_entry_url:
|
||||
raise RuntimeError("DSV upload RPA requires a reviewed DSV upload entry URL")
|
||||
# DSV WMS Upload Tool 已在真实页面确认 Browse 与 Process File 的 DOM。
|
||||
file_selector = file_selector or "#file2"
|
||||
submit_selector = submit_selector or 'button.upload-button:has-text("Process File")'
|
||||
elif not upload_url:
|
||||
raise RuntimeError("upload RPA configuration requires a reviewed upload URL")
|
||||
if not all((file_selector, submit_selector)) or (
|
||||
normalized_connector != "dsv360" and not success_selector
|
||||
):
|
||||
raise RuntimeError("upload RPA configuration requires file, submit and success selectors")
|
||||
|
||||
playwright = context = runtime_profile_dir = None
|
||||
failed = False
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(file_path.parent)
|
||||
if normalized_connector == "dsv360":
|
||||
_navigate_dsv_to_upload_tool(page, dsv_entry_url)
|
||||
else:
|
||||
page.goto(upload_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||||
file_input = page.locator(file_selector).first
|
||||
file_input.set_input_files(str(file_path), timeout=_browser_timeout_ms())
|
||||
submit = page.locator(submit_selector).first
|
||||
submit.click(timeout=_browser_timeout_ms())
|
||||
if normalized_connector == "dsv360":
|
||||
return _wait_for_dsv_upload_history_receipt(page, file_path.name)
|
||||
page.locator(success_selector).first.wait_for(state="visible", timeout=_browser_timeout_ms())
|
||||
receipt_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR")
|
||||
if not receipt_selector:
|
||||
return None
|
||||
receipt = page.locator(receipt_selector).first
|
||||
return str(receipt.text_content(timeout=_browser_timeout_ms()) or "").strip() or None
|
||||
except Exception:
|
||||
failed = True
|
||||
raise
|
||||
finally:
|
||||
if failed and _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true":
|
||||
print("[browser] keeping browser open after upload error because SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR=true")
|
||||
while True:
|
||||
time.sleep(3600)
|
||||
if context is not None:
|
||||
context.close()
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
if runtime_profile_dir is not None:
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
@@ -1178,26 +1374,34 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
return
|
||||
|
||||
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
if not mock:
|
||||
print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}")
|
||||
return
|
||||
|
||||
if file_path and not Path(file_path).is_file():
|
||||
if not file_path or not Path(file_path).is_file():
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"success": False,
|
||||
"error_message": f"queue file missing: {file_path}",
|
||||
"error_message": f"queue file missing: {file_path or '<empty>'}",
|
||||
})
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
return
|
||||
|
||||
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
|
||||
try:
|
||||
if mock:
|
||||
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
|
||||
else:
|
||||
connector_type = str(body.get("inventory_connector_type") or "").strip()
|
||||
dsv_entry_url = str(body.get("inventory_entry_url") or "").strip()
|
||||
# 兼容旧 trigger;新 trigger 才携带站点路由信息并进入专用 Driver。
|
||||
ref = (
|
||||
_upload_shipment_with_browser(
|
||||
Path(file_path), connector_type=connector_type, dsv_entry_url=dsv_entry_url
|
||||
)
|
||||
if connector_type
|
||||
else _upload_shipment_with_browser(Path(file_path))
|
||||
)
|
||||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
@@ -1206,9 +1410,19 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
"freight_ref_no": ref,
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] mock upload done for {task_no} ref={ref}")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
print(f"[upload] {'mock' if mock else 'browser'} upload done for {task_no} ref={ref or '-'}")
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"success": False,
|
||||
"error_message": str(exc)[:500],
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed after upload failure")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
|
||||
|
||||
def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
|
||||
@@ -90,6 +90,9 @@ $Vars = [ordered]@{
|
||||
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR" = Join-Path $DataRoot "inventory_drop"
|
||||
"SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR" = Join-Path $DataRoot "upload_triggers"
|
||||
"SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR" = Join-Path $DataRoot "upload_queue"
|
||||
# 上传站点配置通过受控环境变量单独注入;部署脚本永远不默认开启浏览器提交。
|
||||
"SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED" = "false"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT" = "false"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR" = Join-Path $DataRoot "browser_profile"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_LOG_FILE" = Join-Path $DataRoot "logs\worker.log"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES" = "10485760"
|
||||
|
||||
Reference in new issue
Block a user