feat(shipping-order): 迭代货代订单提取与履约全流程功能

添加订单字段自动标注配置,默认仅关键字段参与自动框选
完善字段规范化逻辑,支持更多日期格式解析
添加订单候选人工采纳、驳回的完整流程,包含API、前端交互与状态管理
完善盲测功能,支持订单级字段真值校验,调整盲测集唯一性约束
加固库存校验逻辑,防止重复预约与数量不一致问题
优化坐标匹配逻辑,支持表格外的锚点定位
新增上传结果未知的状态处理,完善任务状态机
更新多语言文案与文档说明,补充功能细节
修复订单合并、重解析的边缘情况问题
补充相关测试用例,完善质量保障
This commit is contained in:
hugo committed 2026-07-27 20:48:40 +08:00
1 parent 11079910ec
commit 90f77634d6
76 files changed
+5056 -338

No files matched your search

@@ -102,6 +102,20 @@ def suggest_order_document_profile_coordinate_reconstruction():
return _ok(service.suggest_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id())) return _ok(service.suggest_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/order-document-profile-samples/order-field-suggestions', methods=['POST'])
@require_admin
def suggest_order_document_profile_order_fields():
"""从整页坐标与冻结 Header Schema 提供订单字段待复核候选。"""
return _private_ok(service.suggest_order_field_layouts(request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/order-document-profile-samples/order-field-values-preview', methods=['POST'])
@require_admin
def preview_order_document_profile_order_field_values():
"""按当前草稿定义读取订单字段候选值,页面刷新后仍可恢复复核证据。"""
return _private_ok(service.preview_order_field_values(request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/order-document-profile-samples/ocr-coordinate-evidence', methods=['POST']) @admin_bp.route('/shipping-notice/order-document-profile-samples/ocr-coordinate-evidence', methods=['POST'])
@require_admin @require_admin
def generate_order_document_profile_ocr_coordinate_evidence(): def generate_order_document_profile_ocr_coordinate_evidence():
@@ -306,7 +320,38 @@ def add_order_document_profile_test_sample(suite_id: int):
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
return _ok(quality.add_sample( return _ok(quality.add_sample(
suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''), suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''),
expected_rows=data.get('expected_rows'), actor_id=_actor_id(), expected_rows=data.get('expected_rows'), expected_order_fields=data.get('expected_order_fields'), actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/available-samples', methods=['GET'])
@require_admin
def list_order_document_profile_test_available_samples(suite_id: int):
"""列出未参与当前模板建模、可用于盲测复核的同类样本。"""
from app.services.shipping_notice import document_profile_quality_service as quality
return _ok(quality.list_independent_samples(suite_id=suite_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/candidate-preview', methods=['POST'])
@require_admin
def preview_order_document_profile_test_candidate(suite_id: int):
"""运行独立样本并返回字段与明细候选,供管理员逐项勾选复核。"""
from app.services.shipping_notice import document_profile_quality_service as quality
data = request.get_json(silent=True) or {}
return _private_ok(quality.preview_independent_sample(
suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''), actor_id=_actor_id(),
))
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/reviewed-samples', methods=['POST'])
@require_admin
def confirm_order_document_profile_test_reviews(suite_id: int):
"""将用户对自动候选的正确/错误勾选固化为现有盲测真值。"""
from app.services.shipping_notice import document_profile_quality_service as quality
data = request.get_json(silent=True) or {}
return _ok(quality.confirm_sample_reviews(
suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''),
row_reviews=data.get('row_reviews'), order_field_reviews=data.get('order_field_reviews'), actor_id=_actor_id(),
), status=201) ), status=201)
@@ -1198,6 +1198,27 @@ def workspace_update_shipping_notice_candidate(candidate_no: str):
) )
@workspace_shipping_notice_bp.route('/shipping-notice/candidates/<candidate_no>/promote', methods=['POST'])
def workspace_promote_shipping_notice_candidate(candidate_no: str):
"""人工采纳 Dify 兜底识别的 Candidate。"""
user = _require_user()
from app.services.shipping_notice.candidate_service import promote_candidate
return _ok(promote_candidate(user_id=user.id, candidate_no=candidate_no))
@workspace_shipping_notice_bp.route('/shipping-notice/candidates/<candidate_no>/reject', methods=['POST'])
def workspace_reject_shipping_notice_candidate(candidate_no: str):
"""人工驳回尚未进入履约的 Candidate。"""
user = _require_user()
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
raise ValidationError('请求体必须为对象')
from app.services.shipping_notice.candidate_service import reject_candidate
return _ok(reject_candidate(user_id=user.id, candidate_no=candidate_no, reason=body.get('reason')))
@workspace_shipping_notice_bp.route( @workspace_shipping_notice_bp.route(
'/shipping-notice/candidates/<candidate_no>/duplicate-refresh', '/shipping-notice/candidates/<candidate_no>/duplicate-refresh',
methods=['POST'], methods=['POST'],
+20 -1
View File
@@ -571,6 +571,14 @@ class ShippingNoticeCandidate(Base):
__tablename__ = 'shipping_notice_candidates' __tablename__ = 'shipping_notice_candidates'
__table_args__ = ( __table_args__ = (
CheckConstraint(
"candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')",
name='ck_shipping_notice_candidates_status',
),
CheckConstraint(
"acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')",
name='ck_shipping_notice_candidates_acceptance_mode',
),
UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'), UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
UniqueConstraint( UniqueConstraint(
'intake_id', 'candidate_key', 'order_extraction_run_id', 'intake_id', 'candidate_key', 'order_extraction_run_id',
@@ -590,6 +598,7 @@ class ShippingNoticeCandidate(Base):
'business_fingerprint', 'business_fingerprint',
), ),
Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'), Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'),
Index('ix_shipping_notice_candidates_fulfillment_gate', 'candidate_status', 'is_current_version'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
@@ -613,6 +622,7 @@ class ShippingNoticeCandidate(Base):
Boolean, default=True, server_default=text('true'), nullable=False, index=True, Boolean, default=True, server_default=text('true'), nullable=False, index=True,
) )
selected_before_superseded: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True) selected_before_superseded: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
candidate_status_before_superseded: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
@@ -628,7 +638,16 @@ class ShippingNoticeCandidate(Base):
nullable=False, nullable=False,
) )
conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
selected: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), nullable=False) # `selected` is a legacy UI projection. Fulfillment must use candidate_status.
candidate_status: Mapped[str] = mapped_column(
String(32), default='provisional', server_default=text("'provisional'"), nullable=False, index=True,
)
acceptance_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
accepted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
accepted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
acceptance_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
acceptance_policy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
selected: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'), nullable=False)
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
@@ -22,7 +22,7 @@ class ShippingDocumentProfileTestSuite(Base):
__tablename__ = 'shipping_document_profile_test_suites' __tablename__ = 'shipping_document_profile_test_suites'
__table_args__ = ( __table_args__ = (
UniqueConstraint('profile_id', name='uq_shipping_document_profile_test_suites_profile'), UniqueConstraint('profile_id', 'profile_checksum', name='uq_shipping_document_profile_test_suites_profile_checksum'),
CheckConstraint("status IN ('draft', 'approved', 'superseded')", name='ck_shipping_document_profile_test_suites_status'), CheckConstraint("status IN ('draft', 'approved', 'superseded')", name='ck_shipping_document_profile_test_suites_status'),
) )
@@ -45,7 +45,7 @@ class ShippingDocumentProfileTestSuite(Base):
class ShippingDocumentProfileTestSample(Base): class ShippingDocumentProfileTestSample(Base):
"""盲测样本文档及管理员确认的字段期望值;不与建 Profile 的样本自动复用。""" """盲测样本文档及管理员确认的明细/订单字段真值;不与建 Profile 的样本自动复用。"""
__tablename__ = 'shipping_document_profile_test_samples' __tablename__ = 'shipping_document_profile_test_samples'
__table_args__ = ( __table_args__ = (
@@ -57,6 +57,7 @@ class ShippingDocumentProfileTestSample(Base):
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False) document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
table_id: Mapped[str] = mapped_column(String(128), nullable=False) table_id: Mapped[str] = mapped_column(String(128), nullable=False)
expected_rows_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) expected_rows_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
expected_order_fields_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False) created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -612,18 +612,6 @@ def create_shipping_batch_from_candidates(
) )
if intake.expires_at and intake.expires_at < now: if intake.expires_at and intake.expires_at < now:
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期') raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期')
if not candidate.selected:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中')
if not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
if candidate.consumed_task_id is not None:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
raise ConflictError(
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
message='订单候选仍有字段冲突或未完成审核',
details={'candidate_no': candidate.candidate_no, 'conflicts': list(candidate.conflicts_json or [])},
)
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id)) document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
if document is None or document.parse_status != 'parsed': if document is None or document.parse_status != 'parsed':
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DOCUMENT_INVALID', message='订单候选主附件不可用') raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DOCUMENT_INVALID', message='订单候选主附件不可用')
@@ -728,6 +716,8 @@ def create_shipping_batch_from_candidates(
}) })
candidate.updated_at = now candidate.updated_at = now
continue continue
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
ensure_candidate_fulfillment_ready(candidate)
create_items.append(candidate_to_notice_item(candidate, intake, document)) create_items.append(candidate_to_notice_item(candidate, intake, document))
create_candidates.append(candidate) create_candidates.append(candidate)
@@ -905,6 +895,7 @@ def create_shipping_batch_from_intakes(
ShippingNoticeIntake.user_id == int(user_id), ShippingNoticeIntake.user_id == int(user_id),
ShippingNoticeIntake.intake_no.in_(normalized), ShippingNoticeIntake.intake_no.in_(normalized),
ShippingNoticeCandidate.selected.is_(True), ShippingNoticeCandidate.selected.is_(True),
ShippingNoticeCandidate.candidate_status == 'accepted',
ShippingNoticeCandidate.consumed_task_id.is_(None), ShippingNoticeCandidate.consumed_task_id.is_(None),
) )
.order_by(ShippingNoticeCandidate.id.asc()) .order_by(ShippingNoticeCandidate.id.asc())
@@ -23,6 +23,26 @@ from app.services.shipping_notice.intake_service import can_force_create_shippin
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'}) _ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None:
"""统一履约门禁:只有已接受、当前且无阻断问题的 Candidate 才能建单。"""
if str(candidate.candidate_status or '') != 'accepted':
raise ConflictError(
code='SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED',
message='订单候选尚未被接受,不能进入履约',
)
if not candidate.selected:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中')
if not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
if candidate.consumed_task_id is not None:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
raise ConflictError(
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
message='订单候选仍有字段冲突或未完成审核',
)
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]: def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
"""按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。""" """按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。"""
query = ( query = (
@@ -97,7 +117,8 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None =
if selected is not None: if selected is not None:
if not isinstance(selected, bool): if not isinstance(selected, bool):
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值') raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值')
candidate.selected = selected # Selection is retained for legacy batch APIs but may not bypass acceptance.
candidate.selected = selected if candidate.candidate_status == 'accepted' else False
if business_summary is not None: if business_summary is not None:
if not isinstance(business_summary, dict): if not isinstance(business_summary, dict):
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象') raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象')
@@ -126,6 +147,66 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None =
return _serialize_candidate_brief(candidate) return _serialize_candidate_brief(candidate)
def _append_candidate_decision_history(candidate: ShippingNoticeCandidate, *, action: str, user_id: int, reason: str | None = None) -> None:
"""记录人工采纳或驳回事件,便于审核回放。"""
structured = dict(candidate.structured_result_json or {})
history = list(structured.get('manual_review_history') or [])
history.append({
'action': action,
'actor_user_id': int(user_id),
'reason': str(reason or '').strip() or None,
'decided_at': datetime.utcnow().isoformat(),
})
structured['manual_review_history'] = history
candidate.structured_result_json = structured
def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
"""人工采纳 Dify 兜底 Candidate;重复采纳请求保持幂等。"""
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
if candidate.candidate_status == 'accepted':
return _serialize_candidate_brief(candidate)
if candidate.candidate_status != 'provisional':
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选已被驳回或过期')
if str(candidate.extraction_source or '') not in {'dify_workflow', 'manual'}:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_PROMOTION_FORBIDDEN', message='仅 Dify 兜底候选允许人工采纳')
if candidate.consumed_task_id is not None or not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选不可再采纳')
_refresh_candidate(candidate, intake, document)
if candidate.validation_status != 'ready' or candidate.conflicts_json or candidate.duplicate_status not in {'none', 'unchecked'}:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', message='请先完成字段和重复审核')
candidate.candidate_status = 'accepted'
candidate.acceptance_mode = 'manual'
candidate.accepted_at = datetime.utcnow()
candidate.accepted_by_id = int(user_id)
candidate.acceptance_reason = 'dify_candidate_promoted'
candidate.acceptance_policy_version = 'manual-review-v1'
candidate.selected = True
_append_candidate_decision_history(candidate, action='promoted', user_id=user_id)
db.session.commit()
return _serialize_candidate_brief(candidate)
def reject_candidate(*, user_id: int, candidate_no: str, reason: str | None = None) -> dict[str, Any]:
"""人工驳回未消费 Candidate,并保留审计原因。"""
candidate, intake, _document = _candidate_for_user(candidate_no, user_id, lock=True)
if candidate.candidate_status == 'rejected':
return _serialize_candidate_brief(candidate)
if candidate.candidate_status != 'provisional' or candidate.consumed_task_id is not None or not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选不可再驳回')
candidate.candidate_status = 'rejected'
candidate.selected = False
candidate.acceptance_mode = None
candidate.accepted_at = None
candidate.accepted_by_id = None
candidate.acceptance_reason = str(reason or '').strip() or 'manual_rejected'
candidate.acceptance_policy_version = 'manual-review-v1'
candidate.updated_at = datetime.utcnow()
_append_candidate_decision_history(candidate, action='rejected', user_id=user_id, reason=reason)
db.session.commit()
return _serialize_candidate_brief(candidate)
def refresh_candidate_duplicate(*, user_id: int, candidate_no: str) -> dict[str, Any]: def refresh_candidate_duplicate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
"""刷新单个 Candidate 的重复检测结果并清除陈旧决策。""" """刷新单个 Candidate 的重复检测结果并清除陈旧决策。"""
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True) candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
@@ -19,6 +19,7 @@ CP_CUSTOMER_REVIEW = "customer_review"
CP_TASK_EXISTS = "task_exists" CP_TASK_EXISTS = "task_exists"
CP_RSV_REQ = "rsv_req" CP_RSV_REQ = "rsv_req"
CP_UPLOAD_FAILED = "upload_failed" CP_UPLOAD_FAILED = "upload_failed"
CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
CP_WAITING_UPLOAD = "waiting_upload" CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected" CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from process_status) # Derived UI checkpoints (no separate pending_human_reason; from process_status)
@@ -51,3 +52,4 @@ PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed" PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
@@ -233,8 +233,9 @@ def _upsert_candidate(
intake_id=int(intake.id), intake_id=int(intake.id),
primary_document_id=int(document.id), primary_document_id=int(document.id),
candidate_key=str(candidate_key), candidate_key=str(candidate_key),
selected=True, selected=False,
validation_status='pending', validation_status='pending',
candidate_status='provisional',
) )
db.session.add(row) db.session.add(row)
row.primary_document_id = int(document.id) row.primary_document_id = int(document.id)
@@ -336,6 +337,11 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
else {} else {}
) )
document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id)) document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id))
action_buttons: list[str] = []
if cand.candidate_status == 'provisional' and cand.consumed_task_id is None and cand.is_current_version:
action_buttons.extend(['edit', 'evidence', 'reject'])
if cand.validation_status == 'ready' and not blocking:
action_buttons.append('promote')
return { return {
'candidate_no': cand.candidate_no, 'candidate_no': cand.candidate_no,
'primary_document_id': cand.primary_document_id, 'primary_document_id': cand.primary_document_id,
@@ -343,6 +349,14 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
'po_number': cand.po_number, 'po_number': cand.po_number,
'confidence': cand.confidence, 'confidence': cand.confidence,
'validation_status': cand.validation_status, 'validation_status': cand.validation_status,
'candidate_status': cand.candidate_status,
'acceptance_mode': cand.acceptance_mode,
'accepted_at': cand.accepted_at.isoformat() if cand.accepted_at else None,
'accepted_by_id': cand.accepted_by_id,
'acceptance_reason': cand.acceptance_reason,
'acceptance_policy_version': cand.acceptance_policy_version,
'extraction_source': cand.extraction_source,
'action_buttons': action_buttons,
'selected': bool(cand.selected), 'selected': bool(cand.selected),
'business_fingerprint': cand.business_fingerprint, 'business_fingerprint': cand.business_fingerprint,
'fingerprint_strength': cand.fingerprint_strength, 'fingerprint_strength': cand.fingerprint_strength,
@@ -132,6 +132,8 @@ class CoordinateHeaderFieldRegionSuggestion(CoordinateReconstructionModel):
region: LayoutBBox region: LayoutBBox
text: str = '' text: str = ''
field_code: str | None = None
confidence: Literal['exact_alias', 'ambiguous', 'unmapped'] = 'unmapped'
class HeaderFieldSuggestion(CoordinateReconstructionModel): class HeaderFieldSuggestion(CoordinateReconstructionModel):
@@ -0,0 +1,489 @@
"""
backend/app/services/shipping_notice/document_layout/order_field_extraction.py
用途:从冻结的整页 PDF/OCR 字符坐标中确定性提取独立订单级字段。
依赖:OrderCoordinateProfileV2、冻结 Schema 字段规则和 LayoutBBox。
逻辑:订单工作流先唯一匹配模板,再调用本模块;本模块仅返回可追溯候选,绝不回读资产、数据库或调用模型。
"""
from __future__ import annotations
import re
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRelativeRegion,
AnchorRule,
OrderCoordinateProfileV2,
OrderFieldLayout,
RelativeRegion,
)
from app.services.shipping_notice.order_schema.field_rules import (
normalize_order_field_value,
validate_order_field_value,
)
class OrderFieldExtraction(BaseModel):
"""表示单个订单字段的脱敏运行期候选及其最小坐标证据。"""
model_config = ConfigDict(extra='forbid')
field_id: str
field_code: str
value: Any = None
status: Literal['confirmed', 'needs_review', 'unavailable']
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
page_no: int | None = Field(default=None, ge=1)
anchor_bbox: LayoutBBox | None = None
value_bbox: LayoutBBox | None = None
glyph_indices: list[int] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
def extract_order_fields(
*, profile: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]],
coordinate_evidence: dict[str, Any],
) -> list[OrderFieldExtraction]:
"""
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
Args:
profile: Run 冻结的 v2 坐标模板,不得包含待重新绑定字段。
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
Returns:
每个已绑定布局对应一个候选,按模板声明顺序返回。
"""
return [
_extract_layout(layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence)
for layout in profile.order_field_layouts
]
def _extract_layout(
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
) -> OrderFieldExtraction:
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
config = schema_fields.get(layout.field_id)
if config is None or not config.get('enabled', True) or config.get('scope') != 'header':
return _unavailable(layout, 'order_field_schema_binding_invalid')
pages = coordinate_evidence.get('pages') if isinstance(coordinate_evidence.get('pages'), dict) else {}
glyph_pages = coordinate_evidence.get('page_glyphs') if isinstance(coordinate_evidence.get('page_glyphs'), dict) else {}
sources = coordinate_evidence.get('sources') if isinstance(coordinate_evidence.get('sources'), dict) else {}
page_sources = sources.get('pages') if isinstance(sources.get('pages'), dict) else {}
candidates: list[tuple[int, list[dict[str, Any]], float, float, str]] = []
for raw_page_no, page in pages.items():
try:
page_no, width, height = int(raw_page_no), float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError):
continue
if not _layout_applies_to_page(layout, page_no) or width <= 0 or height <= 0:
continue
glyphs = glyph_pages.get(str(page_no))
source = str(page_sources.get(str(page_no)) or '')
if isinstance(glyphs, list) and source in {'pdf_coordinate', 'ocr_coordinate'}:
valid_glyphs = []
for item in glyphs:
if not isinstance(item, dict):
continue
try:
_glyph_bbox(item)
except Exception:
continue
valid_glyphs.append(item)
candidates.append((page_no, valid_glyphs, width, height, source))
if not candidates:
return _unavailable(layout, 'order_field_page_coordinate_evidence_missing')
results: list[OrderFieldExtraction] = []
for page_no, glyphs, width, height, source in candidates:
if not _source_allowed(layout, config=config, source=source):
results.append(_unavailable(layout, 'order_field_coordinate_source_not_allowed', page_no=page_no, source=source))
continue
if layout.anchor is None:
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None,
fallback=True,
))
continue
matches = _find_anchor_matches(glyphs, layout.anchor, page_width=width, page_height=height)
if not matches:
reference_anchor = (
_anchor_from_reference_region(
glyphs, anchor=layout.anchor, page_width=width, page_height=height,
)
if _is_placeholder_anchor_text(layout.anchor.text) else None
)
if reference_anchor is not None:
# Legacy manual regions can contain a placeholder label rather than
# the PDF text. The reference box is evidence of administrator
# intent, but it must remain review-only until the label is fixed.
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_anchor_region(layout.value_region, reference_anchor),
anchor_bbox=reference_anchor, fallback=False,
review_issue='order_field_anchor_text_mismatch',
))
continue
results.append(_unavailable(layout, 'order_field_anchor_missing', page_no=page_no, source=source))
continue
if len(matches) != 1:
results.append(OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
page_no=page_no, issues=['order_field_anchor_ambiguous'],
))
continue
anchor_bbox, _indices = matches[0]
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_anchor_region(layout.value_region, anchor_bbox), anchor_bbox=anchor_bbox, fallback=False,
))
usable = [item for item in results if item.status != 'unavailable']
if len(usable) == 1:
return usable[0]
if not usable:
return results[0] if results else _unavailable(layout, 'order_field_page_coordinate_evidence_missing')
values = {repr(item.value) for item in usable if item.value is not None}
# Repeated page headers are corroborating evidence, not a second business value.
# An ambiguous value on any selected page must still stop automatic acceptance.
if len(values) == 1 and not any(item.status == 'needs_review' for item in usable):
return usable[0]
first = usable[0].model_copy(deep=True)
first.status = 'needs_review'
first.issues = sorted(set(first.issues + ['order_field_page_value_conflict']))
return first
def _read_value_region(
*, layout: OrderFieldLayout, config: dict[str, Any], glyphs: list[dict[str, Any]], page_no: int,
source: str, region: LayoutBBox, anchor_bbox: LayoutBBox | None, fallback: bool,
review_issue: str | None = None,
) -> OrderFieldExtraction:
"""按视觉行合并值区文字,多行模式先以停止标签截断,再执行 Schema 规范化与校验。
``right_of_anchor`` 使用锚点右侧的同一连续文本段,而不是严格依赖值框的
左边界;这能避免标签后的冒号进入值,也能容忍框选末尾少量字符。
"""
selected = (
_inline_right_of_anchor_glyphs(glyphs=glyphs, anchor_bbox=anchor_bbox, region=region)
if layout.value_mode == 'right_of_anchor' and anchor_bbox is not None
else [(index, item) for index, item in enumerate(glyphs) if _glyph_center_inside(item, region)]
)
if layout.value_mode == 'multi_line':
selected = _stop_before_anchor(
selected, glyphs=glyphs, stop_anchors=layout.stop_anchors, anchor_bbox=anchor_bbox,
)
text = _render_value(selected, multi_line=layout.value_mode == 'multi_line')
if layout.value_mode != 'multi_line':
text = text.split('\n', 1)[0].strip()
if layout.value_mode == 'right_of_anchor':
text = text.lstrip(':: ').strip()
if str(config.get('value_type') or '') == 'date':
text = _recover_trailing_date_glyph(text=text, glyphs=glyphs, region=region)
if not text:
return _unavailable(layout, 'order_field_value_missing', page_no=page_no, source=source, anchor_bbox=anchor_bbox, value_bbox=region)
try:
value = normalize_order_field_value(text, config)
except Exception:
return _review(layout, 'order_field_normalization_failed', page_no, source, anchor_bbox, region, selected)
if value is None or not validate_order_field_value(value, config):
return _review(layout, 'order_field_validation_failed', page_no, source, anchor_bbox, region, selected)
status: Literal['confirmed', 'needs_review'] = 'needs_review' if fallback or source != 'pdf_coordinate' or review_issue else 'confirmed'
issues = ['order_field_fallback_value_region'] if fallback else []
if source == 'ocr_coordinate':
issues.append('order_field_ocr_coordinate_needs_review')
if review_issue:
issues.append(review_issue)
return OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, value=value, status=status, source=source,
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=region,
glyph_indices=[index for index, _item in selected], issues=issues,
)
def _inline_right_of_anchor_glyphs(
*, glyphs: list[dict[str, Any]], anchor_bbox: LayoutBBox, region: LayoutBBox,
) -> list[tuple[int, dict[str, Any]]]:
"""读取值框内标签右侧的文本,仅在框尾补齐被截断的同一个词。
管理员的值框是字段分隔的主证据,不能按整行连续文本扩展。仅当框尾
截在英文/数字词中间时,才追加紧邻字符直至一个正常词间隔;这不会吞入
下一个字段,即使两个字段落在同一视觉行。
Args:
glyphs: 当前页面冻结的字符坐标。
anchor_bbox: 已唯一定位的标签字符联合框。
region: 管理员配置的相对值区投影框。
Returns:
值框内文本及其被截断的当前词的原始 glyph 索引和字符。
"""
anchor_center_y = (anchor_bbox.y0 + anchor_bbox.y1) / 2
same_line = [
(index, glyph) for index, glyph in enumerate(glyphs)
if _glyph_bbox(glyph).x0 >= anchor_bbox.x1
and region.y0 <= (_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2 <= region.y1
and abs(((_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2) - anchor_center_y)
<= max(anchor_bbox.y1 - anchor_bbox.y0, _glyph_bbox(glyph).y1 - _glyph_bbox(glyph).y0) * .55
]
ordered = sorted(same_line, key=lambda item: _glyph_bbox(item[1]).x0)
selected = [item for item in ordered if _glyph_center_inside(item[1], region)]
if not selected:
return []
last_position = next(
(position for position in range(len(ordered) - 1, -1, -1) if ordered[position][0] == selected[-1][0]),
-1,
)
previous = _glyph_bbox(selected[-1][1])
for item in ordered[last_position + 1:]:
bbox = _glyph_bbox(item[1])
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, .01)
# A normal word gap terminates the only permitted overrun. This admits
# ``Corporati`` -> ``Corporation`` but not a following address/field.
if bbox.x0 - previous.x1 > typical_width * .75:
break
selected.append(item)
previous = bbox
return selected
def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], region: LayoutBBox) -> str:
"""补入紧贴日期值框右缘的单个数字,容忍管理员框选少一个字宽但不扩展到下一字段。"""
compact = re.sub(r'\s+', '', text)
if not re.fullmatch(r'(?:\d{4}[-/.]\d{1,2}[-/.]\d{1,2}|\d{1,2}[-/.]\d{1,2}[-/.]\d{1,3})', compact):
return text
candidates = []
for glyph in glyphs:
try:
bbox = _glyph_bbox(glyph)
except Exception:
continue
if not str(glyph.get('text') or '').isdigit() or bbox.y1 < region.y0 or bbox.y0 > region.y1:
continue
glyph_width = max(bbox.x1 - bbox.x0, .01)
if 0 <= bbox.x0 - region.x1 <= glyph_width * 1.5:
candidates.append((bbox.x0, str(glyph.get('text') or '')))
if len(candidates) != 1:
return text
return f'{text}{candidates[0][1]}'
def _find_anchor_matches(
glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None,
) -> list[tuple[LayoutBBox, list[int]]]:
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
expected = [anchor.text, *anchor.aliases]
matches: list[tuple[LayoutBBox, list[int]]] = []
for row in _visual_rows(list(enumerate(glyphs))):
# PDFium does not emit whitespace glyphs consistently, so labels are compared
# after whitespace folding while preserving a mapping back to real characters.
compact: list[tuple[int, dict[str, Any]]] = [
pair for pair in row if str(pair[1].get('text') or '').strip()
]
row_text = ''.join(str(item.get('text') or '') for _index, item in compact)
folded = row_text.casefold()
for label in expected:
normalized = re.sub(r'\s+', '', label).casefold()
start = 0
while normalized and (position := folded.find(normalized, start)) >= 0:
consumed = compact[position:position + len(normalized)]
if len(consumed) == len(normalized) and _anchor_occurrence_is_exact(
compact, position=position, length=len(normalized), anchor=anchor,
):
bbox = _union_bbox([item for _index, item in consumed])
if _anchor_bbox_in_reference_region(
bbox, anchor=anchor, page_width=page_width, page_height=page_height,
):
matches.append((bbox, [index for index, _item in consumed]))
start = position + max(len(label), 1)
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
for bbox, indices in matches:
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
return list(unique.values())
def _anchor_occurrence_is_exact(
row: list[tuple[int, dict[str, Any]]], *, position: int, length: int, anchor: AnchorRule,
) -> bool:
"""精确模式拒绝嵌入其他字母数字串的标签,contains 模式才允许局部命中。"""
if anchor.match_mode != 'exact':
return True
before = row[position - 1][1] if position else None
first = row[position][1]
last = row[position + length - 1][1]
after = row[position + length][1] if position + length < len(row) else None
return not (
(before is not None and str(before.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(before, first))
or (after is not None and str(after.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(last, after))
)
def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) -> bool:
"""PDFium 常省略空白 glyph;相邻字符间的大间隔仍视为精确标签的词边界。"""
left_bbox, right_bbox = _glyph_bbox(left), _glyph_bbox(right)
typical_width = max(((left_bbox.x1 - left_bbox.x0) + (right_bbox.x1 - right_bbox.x0)) / 2, 0.01)
return right_bbox.x0 - left_bbox.x1 > typical_width * 0.75
def _anchor_bbox_in_reference_region(
bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None,
) -> bool:
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
if anchor.region is None:
return True
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
return False
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region)
def _anchor_from_reference_region(
glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float,
) -> LayoutBBox | None:
"""为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。"""
if anchor.region is None:
return None
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)]
return _union_bbox(selected) if selected else None
def _is_placeholder_anchor_text(value: str) -> bool:
"""仅兼容工作台历史默认名;任何管理员自定义标签不匹配时仍必须失败关闭。"""
return re.fullmatch(r'订单字段标签\s*\d*', value.strip()) is not None
def _stop_before_anchor(
selected: list[tuple[int, dict[str, Any]]], *, glyphs: list[dict[str, Any]], stop_anchors: list[AnchorRule],
anchor_bbox: LayoutBBox | None,
) -> list[tuple[int, dict[str, Any]]]:
"""多行值仅在当前锚点之后遇到首个停止标签时截断,避免页眉同名标签误伤。"""
stop_y: float | None = None
for anchor in stop_anchors:
for bbox, _indices in _find_anchor_matches(glyphs, anchor):
if anchor_bbox is not None and bbox.y0 <= anchor_bbox.y1:
continue
stop_y = bbox.y0 if stop_y is None else min(stop_y, bbox.y0)
return selected if stop_y is None else [item for item in selected if _glyph_bbox(item[1]).y0 < stop_y]
def _render_value(selected: list[tuple[int, dict[str, Any]]], *, multi_line: bool) -> str:
"""按 y 聚类、x 排序渲染字符,保留多行字段的换行而不伪造空格。"""
rows = _visual_rows(selected)
rendered = [_render_visual_row(row) for row in rows]
return ('\n' if multi_line else ' ').join(item for item in rendered if item).strip()
def _render_visual_row(row: list[tuple[int, dict[str, Any]]]) -> str:
"""以字距推断缺失的 PDF 空白;仅大于常规字符间隔时补一个普通空格。"""
rendered: list[str] = []
previous: LayoutBBox | None = None
for _index, glyph in row:
bbox = _glyph_bbox(glyph)
if previous is not None:
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, 0.01)
if bbox.x0 - previous.x1 > typical_width * 0.75:
rendered.append(' ')
rendered.append(str(glyph.get('text') or ''))
previous = bbox
return ''.join(rendered).strip()
def _visual_rows(items: list[tuple[int, dict[str, Any]]]) -> list[list[tuple[int, dict[str, Any]]]]:
"""将 bbox 中心 y 接近的字符归为视觉行,避免扫描页的微小坐标抖动拆行。"""
rows: list[list[tuple[int, dict[str, Any]]]] = []
for item in sorted(items, key=lambda pair: (_glyph_bbox(pair[1]).y0, _glyph_bbox(pair[1]).x0)):
bbox = _glyph_bbox(item[1])
if rows:
previous = rows[-1]
reference = _glyph_bbox(previous[0][1])
tolerance = max((reference.y1 - reference.y0), (bbox.y1 - bbox.y0)) * 0.55
if abs(((bbox.y0 + bbox.y1) / 2) - ((reference.y0 + reference.y1) / 2)) <= tolerance:
previous.append(item)
continue
rows.append([item])
return [sorted(row, key=lambda pair: _glyph_bbox(pair[1]).x0) for row in rows]
def _layout_applies_to_page(layout: OrderFieldLayout, page_no: int) -> bool:
"""执行订单字段页域;后续页重复值只在 all_pages 明确声明时作为冲突证据读取。"""
return (
(layout.page_scope == 'first_page' and page_no == 1)
or layout.page_scope == 'all_pages'
or (layout.page_scope == 'exact_page' and page_no == layout.page_no)
)
def _source_allowed(layout: OrderFieldLayout, *, config: dict[str, Any], source: str) -> bool:
"""同时满足布局和 Schema 的坐标来源授权,OCR 永远不提升为 confirmed。"""
allowed = set(config.get('allowed_sources') or [])
if source not in allowed:
return False
required_levels = [layout.minimum_evidence_level]
if layout.anchor is not None:
required_levels.append(layout.anchor.minimum_evidence_level)
return not ('coordinate' in required_levels and source != 'pdf_coordinate')
def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox:
"""将固定低可靠度归一化页区投影为当前页面绝对框。"""
if region is None:
raise ValueError('fallback order field region is required')
return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height)
def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox:
"""用标签框宽高投影相对值区,使整页平移或缩放不改变读取关系。"""
if region is None:
raise ValueError('anchored order field region is required')
width, height = anchor.x1 - anchor.x0, anchor.y1 - anchor.y0
return LayoutBBox(
x0=anchor.x0 + region.x0 * width, y0=anchor.y0 + region.y0 * height,
x1=anchor.x0 + region.x1 * width, y1=anchor.y0 + region.y1 * height,
)
def _glyph_bbox(glyph: dict[str, Any]) -> LayoutBBox:
"""严格解析一枚冻结 glyph 的 bbox;坏坐标不会被修正后参与提取。"""
return LayoutBBox.model_validate(glyph.get('bbox'))
def _glyph_center_inside(glyph: dict[str, Any], region: LayoutBBox) -> bool:
"""判断字符中心是否处于值区,边界字符仍归属到管理员确认的区域。"""
try:
bbox = _glyph_bbox(glyph)
except Exception:
return False
return region.x0 <= (bbox.x0 + bbox.x1) / 2 <= region.x1 and region.y0 <= (bbox.y0 + bbox.y1) / 2 <= region.y1
def _union_bbox(glyphs: list[dict[str, Any]]) -> LayoutBBox:
"""求连续标签字符的最小联合框,作为相对值区投影的唯一参考。"""
boxes = [_glyph_bbox(item) for item in glyphs]
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 _unavailable(
layout: OrderFieldLayout, issue: str, *, page_no: int | None = None, source: str | None = None,
anchor_bbox: LayoutBBox | None = None, value_bbox: LayoutBBox | None = None,
) -> OrderFieldExtraction:
"""构造无可用坐标证据的失败关闭结果。"""
return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue])
def _review(
layout: OrderFieldLayout, issue: str, page_no: int, source: str, anchor_bbox: LayoutBBox | None,
value_bbox: LayoutBBox, selected: list[tuple[int, dict[str, Any]]],
) -> OrderFieldExtraction:
"""构造带最小证据索引的人工复核候选。"""
return OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox,
glyph_indices=[index for index, _item in selected], issues=[issue],
)
@@ -62,15 +62,82 @@ class RelativeRegion(OrderProfileModel):
return self return self
class AnchorRelativeRegion(OrderProfileModel):
"""表示相对锚点框宽高的值区偏移;允许标签右侧或下方落在锚点外。"""
# Address values can be much wider than short labels such as "BILL TO".
# Keep a finite bound while accepting the deterministic suggestion geometry.
x0: float = Field(ge=-12, le=12)
y0: float = Field(ge=-12, le=12)
x1: float = Field(ge=-12, le=12)
y1: float = Field(ge=-12, le=12)
@model_validator(mode='after')
def validate_area(self) -> 'AnchorRelativeRegion':
"""拒绝零面积和反向偏移区域,确保运行期投影只有一个解释。"""
if self.x0 >= self.x1 or self.y0 >= self.y1:
raise ValueError('anchor-relative region must have positive area')
return self
class AnchorRule(OrderProfileModel): class AnchorRule(OrderProfileModel):
"""定义模板匹配或行启动使用的稳定静态文字锚点。""" """定义模板匹配或行启动使用的稳定静态文字锚点。"""
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
text: str = Field(min_length=1, max_length=160) text: str = Field(min_length=1, max_length=160)
aliases: list[str] = Field(default_factory=list, max_length=16)
match_mode: Literal['exact', 'contains'] = 'contains' match_mode: Literal['exact', 'contains'] = 'contains'
region: RelativeRegion | None = None region: RelativeRegion | None = None
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate' minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
@model_validator(mode='after')
def validate_aliases(self) -> 'AnchorRule':
"""只接受有限、去重的精确别名,避免把模糊词表当作自由匹配规则。"""
aliases = [item.strip() for item in self.aliases]
if any(not item for item in aliases) or len({item.casefold() for item in aliases}) != len(aliases):
raise ValueError('anchor aliases must be non-empty and unique')
if self.text.casefold() in {item.casefold() for item in aliases}:
raise ValueError('anchor aliases must not repeat anchor text')
return self
class OrderFieldLayout(OrderProfileModel):
"""定义独立订单级字段的锚点和值区;它绝不属于表头或物理明细行。"""
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
field_id: str = Field(min_length=1, max_length=128)
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
page_no: int | None = Field(default=None, ge=1)
anchor: AnchorRule | None = None
# Anchored values use offsets relative to the anchor bbox; fixed-position
# fallback values are stored separately so they cannot be mistaken for anchors.
value_region: AnchorRelativeRegion | None = None
fallback_value_region: RelativeRegion | None = None
value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line'
stop_anchors: list[AnchorRule] = Field(default_factory=list)
normalizer_key: str | None = Field(default=None, min_length=1, max_length=64)
required: bool = False
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
@model_validator(mode='after')
def validate_order_field_layout(self) -> 'OrderFieldLayout':
"""限制无锚点回退为单页值区,并要求多行字段有明确停止证据。"""
if self.page_scope == 'exact_page' and self.page_no is None:
raise ValueError('exact_page order field 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 order field')
if self.anchor is None:
if self.page_scope == 'all_pages':
raise ValueError('value-only order field must have a bounded page scope')
if self.value_region is not None or self.fallback_value_region is None:
raise ValueError('value-only order field requires one fallback value region')
elif self.value_region is None or self.fallback_value_region is not None:
raise ValueError('anchored order field requires one anchor-relative value region')
if self.value_mode == 'multi_line' and not self.stop_anchors:
raise ValueError('multi-line order field requires stop anchors')
return self
class FieldRegion(OrderProfileModel): class FieldRegion(OrderProfileModel):
"""将一个管理员确认的坐标区域绑定至稳定 Schema field_code。""" """将一个管理员确认的坐标区域绑定至稳定 Schema field_code。"""
@@ -141,12 +208,40 @@ class TerminationRule(OrderProfileModel):
class DraftUnboundFieldRegion(OrderProfileModel): class DraftUnboundFieldRegion(OrderProfileModel):
"""草稿阶段尚未绑定 Schema 的字段框;运行和发布均不得使用。""" """草稿阶段尚未绑定 Schema 的字段框;仅迁移遗留项要求重新绑定。"""
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$') 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}$') parent_layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
label: str = Field(min_length=1, max_length=160) label: str = Field(min_length=1, max_length=160)
region: RelativeRegion region: RelativeRegion
requires_rebinding: bool = False
class DraftUnboundOrderFieldLayout(OrderProfileModel):
"""Schema 迁移后暂失绑定的订单字段区域;保留证据布局但禁止发布或运行。"""
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
label: str = Field(min_length=1, max_length=160)
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
page_no: int | None = Field(default=None, ge=1)
anchor: AnchorRule | None = None
value_region: AnchorRelativeRegion | None = None
fallback_value_region: RelativeRegion | None = None
value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line'
stop_anchors: list[AnchorRule] = Field(default_factory=list)
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
@model_validator(mode='after')
def validate_unbound_order_field_layout(self) -> 'DraftUnboundOrderFieldLayout':
"""复用订单字段的区域互斥与页作用域规则,避免迁移草稿保存坏坐标。"""
OrderFieldLayout(
layout_id=self.layout_id, field_id='draft_unbound', field_code='draft_unbound',
page_scope=self.page_scope, page_no=self.page_no, anchor=self.anchor,
value_region=self.value_region, fallback_value_region=self.fallback_value_region,
value_mode=self.value_mode, stop_anchors=self.stop_anchors,
minimum_evidence_level=self.minimum_evidence_level,
)
return self
class TableRegionProfile(OrderProfileModel): class TableRegionProfile(OrderProfileModel):
@@ -230,6 +325,8 @@ class OrderCoordinateProfileV2(OrderProfileModel):
version: int = Field(ge=1) version: int = Field(ge=1)
document_match: DocumentMatchProfile document_match: DocumentMatchProfile
table_regions: list[TableRegionProfile] = Field(min_length=1) table_regions: list[TableRegionProfile] = Field(min_length=1)
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
@model_validator(mode='after') @model_validator(mode='after')
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2': def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
@@ -246,6 +343,15 @@ class OrderCoordinateProfileV2(OrderProfileModel):
for table in self.table_regions: for table in self.table_regions:
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids): if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
raise ValueError('cross-page continuation anchor must be a document match anchor') raise ValueError('cross-page continuation anchor must be a document match anchor')
order_layout_ids = [item.layout_id for item in self.order_field_layouts]
if len(order_layout_ids) != len(set(order_layout_ids)):
raise ValueError('order field layout ids must be unique')
order_field_codes = [item.field_code for item in self.order_field_layouts]
if len(order_field_codes) != len(set(order_field_codes)):
raise ValueError('order field may bind only once')
unbound_ids = [item.layout_id for item in self.draft_unbound_order_field_layouts]
if len(unbound_ids) != len(set(unbound_ids)) or set(unbound_ids) & set(order_layout_ids):
raise ValueError('bound and unbound order field layout ids must be unique')
return self return self
@@ -45,6 +45,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
if not tables or not pages or not glyph_tables: if not tables or not pages or not glyph_tables:
return ProfileMatchResult(status='evidence_insufficient') return ProfileMatchResult(status='evidence_insufficient')
@@ -57,6 +58,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
profile = OrderCoordinateProfileV2( profile = OrderCoordinateProfileV2(
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0), 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'), document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
) )
except (TypeError, ValueError): except (TypeError, ValueError):
continue continue
@@ -64,11 +66,15 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
if len(tables) < len(profile.table_regions): if len(tables) < len(profile.table_regions):
reasons.append('table_region_count_insufficient') reasons.append('table_region_count_insufficient')
required = profile.document_match.required_anchors 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] required_hits = [_anchor_present(
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
) for anchor in required]
if not all(required_hits): if not all(required_hits):
reasons.append('required_anchor_missing') reasons.append('required_anchor_missing')
optional = profile.document_match.optional_anchors 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) optional_hits = sum(_anchor_present(
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
) for anchor in optional)
hard_match = not reasons hard_match = not reasons
# Required evidence is mandatory rather than a soft score. Optional evidence only separates already valid templates. # 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) score = 1.0 if not optional else 0.8 + 0.2 * optional_hits / len(optional)
@@ -92,14 +98,26 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
) )
def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any], pages: dict[str, Any]) -> bool: def _anchor_present(
"""检查静态锚点是否在指定页面区域出现;不读取订单业务字段或 HTML 网格。""" anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any],
page_glyphs: dict[str, Any], pages: dict[str, Any],
) -> bool:
"""检查静态锚点是否在整页冻结字符中出现;旧快照才受限回退到表内证据。"""
expected = str(anchor.get('text') or '').strip() expected = str(anchor.get('text') or '').strip()
if not expected: candidates = [expected, *[str(item).strip() for item in anchor.get('aliases') or []]]
if not expected or not all(candidates):
return False return False
for table in tables: page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
glyphs = glyph_tables.get(str(table.get('table_id') or '')) for page_no in page_numbers:
page = pages.get(str(table.get('page_no') or '')) glyphs = page_glyphs.get(page_no)
# v1 frozen snapshots do not have page glyphs. Preserve historical matching
# rather than silently invalidating published profiles, but never merge rows here.
if not isinstance(glyphs, list):
glyphs = [
glyph for table in tables if str(table.get('page_no') or '') == page_no
for glyph in (glyph_tables.get(str(table.get('table_id') or '')) or [])
]
page = pages.get(page_no)
if not isinstance(glyphs, list) or not isinstance(page, dict): if not isinstance(glyphs, list) or not isinstance(page, dict):
continue continue
selected = glyphs selected = glyphs
@@ -115,8 +133,8 @@ def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], gly
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1] 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)))) 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 str(anchor.get('match_mode') or 'contains') == 'exact':
if expected.casefold() == text.casefold(): if any(candidate.casefold() == text.casefold() for candidate in candidates):
return True return True
elif expected.casefold() in text.casefold(): elif any(candidate.casefold() in text.casefold() for candidate in candidates):
return True return True
return False return False
@@ -175,7 +175,7 @@ def build_mineru_table_snapshot(
content=content, mineru=candidate, content=content, mineru=candidate,
) )
snapshot['layout_candidate'] = layout.model_dump(mode='json') snapshot['layout_candidate'] = layout.model_dump(mode='json')
# 仅保存表格范围内的原生字符坐标,供管理员确认后的坐标模板在 Run 冻结快照中复现。 # 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
snapshot['coordinate_evidence'] = _table_coordinate_evidence( snapshot['coordinate_evidence'] = _table_coordinate_evidence(
content=content, tables=tables, content=content, tables=tables,
) )
@@ -187,7 +187,7 @@ def build_mineru_table_snapshot(
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]: def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
"""保存表内字符和内部页尺寸,使 v2 页面相对坐标可在冻结 Run 中精确换算。""" """保存表内及整页原生字符和页尺寸,分别供明细与订单级字段确定性重放。"""
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages 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)} pages = {item.page_no: item for item in extract_native_pdf_pages(content)}
@@ -211,9 +211,34 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
glyphs.append(item.model_dump(mode='json')) glyphs.append(item.model_dump(mode='json'))
if glyphs: if glyphs:
evidence[table_id] = glyphs evidence[table_id] = glyphs
page_glyphs: dict[str, list[dict[str, Any]]] = {}
page_sources: dict[str, str] = {}
for page_no, page in pages.items():
native_glyphs = [item.model_dump(mode='json') for item in page.characters]
if native_glyphs:
page_glyphs[str(page_no)] = native_glyphs
page_sources[str(page_no)] = 'pdf_coordinate'
continue
# Only scanned pages without a usable native text layer trigger OCR. OCR failure
# intentionally leaves this page without order-field evidence rather than guessing.
try:
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
ocr_glyphs = _ocr_page_characters(ocr_lines)
except Exception:
ocr_glyphs = []
if ocr_glyphs:
page_glyphs[str(page_no)] = ocr_glyphs
page_sources[str(page_no)] = 'ocr_coordinate'
return { return {
'version': 'shipping_order_coordinate_evidence.v1', 'version': 'shipping_order_coordinate_evidence.v1',
'tables': evidence, 'tables': evidence,
# 订单字段锚点可能位于表格外;只保存同一冻结 PDF 的最小字符证据,不向 Dify 暴露。
'page_glyphs': page_glyphs,
'sources': {
'pages': page_sources,
},
# Internal runtime metadata only. It is removed with layout_snapshot before Dify input. # Internal runtime metadata only. It is removed with layout_snapshot before Dify input.
'pages': { 'pages': {
str(page_no): {'width': page.width, 'height': page.height} str(page_no): {'width': page.width, 'height': page.height}
@@ -222,6 +247,29 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
} }
def _ocr_page_characters(lines: list[Any]) -> list[dict[str, Any]]:
"""把整页 OCR 行均匀拆成字符证据;仅服务订单字段锚点,不参与表格 cell 自动接受。"""
result: list[dict[str, Any]] = []
source_index = 0
for line in lines:
text = str(getattr(line, 'text', '') or '').strip()
bbox = getattr(line, 'bbox', None)
if not text or bbox is None:
continue
width = (bbox.x1 - bbox.x0) / len(text)
if width <= 0:
continue
for index, character in enumerate(text):
if character.isspace():
continue
result.append({'text': character, 'source_index': source_index, 'bbox': {
'x0': bbox.x0 + index * width, 'y0': bbox.y0,
'x1': bbox.x0 + (index + 1) * width, 'y1': bbox.y1,
}})
source_index += 1
return result
def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None: def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None:
"""就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。""" """就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。"""
meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {} meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {}
@@ -3,12 +3,13 @@ services/shipping_notice/document_profile_quality_service.py
用途:治理订单文档 Profile 的盲测样本、执行结果和确定性自动建单资格。 用途:治理订单文档 Profile 的盲测样本、执行结果和确定性自动建单资格。
依赖:Profile 服务、MinerU 当前布局快照、Profile 纯解析器与质量 ORM 模型。 依赖:Profile 服务、MinerU 当前布局快照、Profile 纯解析器与质量 ORM 模型。
逻辑:管理员先固化独立样本的期望行,服务按冻结 Profile 执行比对;至少三份样本全部通过并批准后才放行自动建单。 逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;样本通过并批准后才放行自动建单。
""" """
from __future__ import annotations from __future__ import annotations
from datetime import datetime from datetime import datetime
from decimal import Decimal
from typing import Any from typing import Any
from app import db from app import db
@@ -18,7 +19,9 @@ from app.models import (
ShippingDocumentProfileTestSample, ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite, ShippingDocumentProfileTestSuite,
ShippingNoticeDocument, ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocumentProfile, ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileSample,
) )
from app.services.shipping_notice.document_layout.html_table import parse_html_grid 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.lifecycle import current_layout_snapshot
@@ -28,12 +31,20 @@ from app.services.shipping_notice.document_layout.order_profile import (
reconstruct_order_profile_html, reconstruct_order_profile_html,
) )
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows 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.document_layout.order_field_extraction import (
_is_placeholder_anchor_text, extract_order_fields,
)
from app.services.shipping_notice.order_document_profile_service import (
_audit, _definition_contract, _ensure_page_coordinate_evidence,
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
MINIMUM_BLIND_SAMPLES = 3 # 日常模板维护采用一份独立样本门槛;字段 confirmed、人工真值一致、
HEADERLESS_MINIMUM_BLIND_SAMPLES = 5 # 多明细和声明的跨页覆盖等质量门禁仍然生效。
MINIMUM_BLIND_SAMPLES = 1
HEADERLESS_MINIMUM_BLIND_SAMPLES = 1
def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str: def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str:
@@ -101,6 +112,76 @@ def _coordinate_table_available(document_id: int, table_id: str) -> bool:
) )
def _ensure_order_field_evidence(
*, document: ShippingNoticeDocument, layout: dict[str, Any], parser: OrderCoordinateProfileV2,
) -> dict[str, Any]:
"""补齐模板订单字段涉及页面的整页字符坐标;表内坐标不能替代锚点证据。"""
required_pages: set[int] = set()
pages = (layout.get('coordinate_evidence') or {}).get('pages') if isinstance(layout.get('coordinate_evidence'), dict) else {}
known_pages = {int(page_no) for page_no in (pages or {}) if str(page_no).isdigit()}
for field in parser.order_field_layouts:
if field.page_scope == 'exact_page' and field.page_no:
required_pages.add(field.page_no)
elif field.page_scope == 'first_page':
required_pages.add(1)
else:
required_pages.update(known_pages)
for page_no in sorted(required_pages):
layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=page_no)
return layout
def _has_matching_key_order_field(
*, parser: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], layout: dict[str, Any],
) -> bool:
"""筛除没有任何真实订单锚点命中的异版样本,避免盲测页面只展示 unavailable。"""
key_layouts = [
item for item in parser.order_field_layouts
if item.anchor is not None and not _is_placeholder_anchor_text(item.anchor.text)
]
if not key_layouts:
# Historical templates that only have manually named anchors retain the
# existing compatibility path; their evidence remains needs_review.
return True
extracted = {
item.field_code: item
for item in extract_order_fields(
profile=parser, schema_fields=schema_fields,
coordinate_evidence=layout.get('coordinate_evidence') or {},
)
}
return any(
extracted.get(item.field_code) is not None
and extracted[item.field_code].status != 'unavailable'
for item in key_layouts
)
def _order_field_quality_failures(
*, parser: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], layout: dict[str, Any],
expected_values: dict[str, Any], sample_id: int,
) -> list[str]:
"""将订单字段的坐标/格式状态纳入盲测;任何非 confirmed 结果都不能成为发布依据。"""
if not parser.order_field_layouts:
return []
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
failures: list[str] = []
for candidate in extract_order_fields(
profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence,
):
if candidate.status != 'confirmed':
failures.append(f'sample:{sample_id}:order_field:{candidate.field_code}:{candidate.status}')
else:
config = schema_fields.get(candidate.field_id)
try:
expected = normalize_order_field_value(expected_values.get(candidate.field_code), config or {})
except Exception:
expected = None
if candidate.value != expected:
failures.append(f'sample:{sample_id}:order_field:{candidate.field_code}:mismatch')
return failures
def _expected_rows(raw: Any) -> list[dict[str, Any]]: 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): if not isinstance(raw, list) or not raw or any(not isinstance(item, dict) or not item for item in raw):
@@ -108,24 +189,219 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]:
return [dict(item) for item in raw] return [dict(item) for item in raw]
def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]:
"""校验订单字段盲测真值;有订单布局时要求按 stable field_code 提供完整映射。"""
layouts = parser.order_field_layouts if isinstance(parser, OrderCoordinateProfileV2) else []
if not layouts:
return {}
if not isinstance(raw, dict):
raise ValidationError('expected_order_fields is required for order field layouts', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_codes = {item.field_code for item in layouts}
if set(raw) != expected_codes or any(value in (None, '') for value in raw.values()):
raise ValidationError('expected_order_fields must contain every configured order field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
return dict(raw)
def _candidate_for_sample(
*, profile: ShippingOrderDocumentProfile, document_id: int, table_id: str,
) -> dict[str, Any]:
"""运行当前 Profile 并返回供盲测复核的脱敏字段候选,不写入任何真值或执行记录。"""
parser = _definition_contract(profile)
document = db.session.get(ShippingNoticeDocument, int(document_id))
layout = current_layout_snapshot(document) if document is not None else None
if document is None or not layout:
raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
if isinstance(parser, OrderCoordinateProfileV2):
layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser)
if not _coordinate_table_available(document_id, table_id):
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
raw_table = next((
item for item in layout.get('tables') or []
if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)
), None)
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get(str((raw_table or {}).get('page_no') or ''))
characters = (evidence.get('tables') or {}).get(str(table_id))
if not isinstance(raw_table, dict) or not isinstance(page, dict) or not isinstance(characters, list):
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
try:
table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])}
except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
rows: list[dict[str, Any]] = []
for region in parser.table_regions:
# Header-only pages can carry order fields without a physical line
# layout. They are valid template regions, but cannot reconstruct rows.
if not region.line_layouts:
continue
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)
order_fields = [
{
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
'page_no': item.page_no, 'issues': list(item.issues),
}
for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence)
]
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
contract = compile_table_header_contract(profile.schema_version.definition_json or {})
parsed = parse_html_table_with_order_profile(_table_html(document.id, table_id), table_id=table_id, profile=parser, contract=contract)
return {
'document_id': document.id, 'table_id': str(table_id),
'rows': [dict(row.fields) for row in parsed.rows if row.status == 'parsed'], 'order_fields': [],
}
def _json_value(value: Any) -> Any:
"""将日期和 Decimal 等运行期字段转换为 API/JSON 可展示的稳定值。"""
if isinstance(value, Decimal):
return str(value)
return value.isoformat() if hasattr(value, 'isoformat') else value
def list_independent_samples(*, suite_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')
profile = _profile(suite.profile_id)
parser = _definition_contract(profile)
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
}
excluded = {
item.document_id for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
} | {item.document_id for item in suite.samples}
result: list[dict[str, Any]] = []
documents = ShippingNoticeDocument.query.join(
ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id,
).filter(
ShippingNoticeIntake.purpose == 'order_document_profile_sample',
).order_by(ShippingNoticeDocument.created_at.desc()).limit(200).all()
for document in documents:
if document.id in excluded:
continue
layout = current_layout_snapshot(document) or {}
if isinstance(parser, OrderCoordinateProfileV2):
layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser)
if not _has_matching_key_order_field(parser=parser, schema_fields=schema_fields, layout=layout):
continue
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
if layout.get('status') != 'ready' or not tables:
continue
for table in tables:
if not isinstance(table, dict) or not str(table.get('table_id') or ''):
continue
if isinstance(parser, OrderCoordinateProfileV2) and not _coordinate_table_available(document.id, str(table['table_id'])):
continue
result.append({
'document_id': document.id, 'table_id': str(table['table_id']),
'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '',
})
return {'samples': result}
def preview_independent_sample(*, suite_id: int, document_id: int, table_id: str, actor_id: int) -> dict[str, Any]:
"""读取一份可用独立样本的自动候选;复核确认前不写入盲测真值。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None or suite.status != 'draft':
raise ConflictError('Blind test suite is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE')
available = {
(item['document_id'], item['table_id'])
for item in list_independent_samples(suite_id=suite.id, actor_id=actor_id)['samples']
}
if (int(document_id), str(table_id)) not in available:
raise ConflictError('Blind test sample must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT')
return _candidate_for_sample(profile=_profile(suite.profile_id), document_id=int(document_id), table_id=str(table_id))
def confirm_sample_reviews(*, suite_id: int, document_id: int, table_id: str, row_reviews: Any, order_field_reviews: Any, actor_id: int) -> dict[str, Any]:
"""把逐项正确/错误复核转换为既有盲测真值;未确认或错误未修正时拒绝写入。"""
candidate = preview_independent_sample(
suite_id=suite_id, document_id=document_id, table_id=table_id, actor_id=actor_id,
)
if not isinstance(row_reviews, list) or len(row_reviews) != len(candidate['rows']):
raise ValidationError('Every candidate row requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_rows: list[dict[str, Any]] = []
for index, review in enumerate(row_reviews):
if not isinstance(review, dict) or review.get('correct') not in {True, False}:
raise ValidationError('Every candidate row requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
values = candidate['rows'][index] if review['correct'] else review.get('values')
if not isinstance(values, dict) or not values:
raise ValidationError('Incorrect row requires corrected values', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_rows.append(dict(values))
expected_order_fields: dict[str, Any] = {}
for field in candidate['order_fields']:
review = order_field_reviews.get(field['field_code']) if isinstance(order_field_reviews, dict) else None
if not isinstance(review, dict) or review.get('correct') not in {True, False}:
raise ValidationError('Every order field requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
value = field['value'] if review['correct'] else review.get('value')
if value in (None, ''):
raise ValidationError('Incorrect order field requires a corrected value', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_order_fields[field['field_code']] = value
return add_sample(
suite_id=suite_id, document_id=document_id, table_id=table_id, expected_rows=expected_rows,
expected_order_fields=expected_order_fields, actor_id=actor_id,
)
def create_suite(*, profile_id: int, actor_id: int) -> dict[str, Any]: def create_suite(*, profile_id: int, actor_id: int) -> dict[str, Any]:
"""为草稿或发布 Profile 建立唯一盲测集;发布前完成审批以形成真正发布门禁。""" """为当前 Profile checksum 建立独立盲测集,并将过期草稿集转为 superseded。
核心逻辑:模板保存会改变草稿 definition hash,旧盲测真值不能为新定义背书。
同一模板因此按 checksum 保留历史集;再次打开盲测时只返回当前定义对应的集。
Args:
profile_id: 草稿或发布 Profile 主键。
actor_id: 管理员主键,用于写入创建/过期审计。
Returns:
当前 Profile checksum 对应的可维护盲测集摘要。
"""
profile = _profile(profile_id) profile = _profile(profile_id)
existing = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first() checksum = _quality_checksum(profile)
existing = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=checksum,
).one_or_none()
if existing is not None: if existing is not None:
return serialize_suite(existing) return serialize_suite(existing)
stale_suites = ShippingDocumentProfileTestSuite.query.filter(
ShippingDocumentProfileTestSuite.profile_id == profile.id,
ShippingDocumentProfileTestSuite.status == 'draft',
ShippingDocumentProfileTestSuite.profile_checksum != checksum,
).all()
for stale in stale_suites:
stale.status = 'superseded'
_audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={
'suite_id': stale.id,
})
suite = ShippingDocumentProfileTestSuite( suite = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=_quality_checksum(profile), created_by_id=actor_id, profile_id=profile.id, profile_checksum=checksum, created_by_id=actor_id,
) )
db.session.add(suite) db.session.add(suite)
_audit(profile_id=profile.id, event_type='blind_test_suite_created', actor_id=actor_id, detail={ _audit(profile_id=profile.id, event_type='blind_test_suite_created', actor_id=actor_id, detail={
'profile_checksum': _quality_checksum(profile), 'profile_checksum': checksum,
}) })
db.session.commit() db.session.commit()
return serialize_suite(suite) return serialize_suite(suite)
def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows: Any, actor_id: int) -> dict[str, Any]: def add_sample(
*, suite_id: int, document_id: int, table_id: str, expected_rows: Any,
expected_order_fields: Any = None, actor_id: int,
) -> dict[str, Any]:
"""增加独立盲测样本;批准后禁止继续更改真值。""" """增加独立盲测样本;批准后禁止继续更改真值。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id)) suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None: if suite is None:
@@ -144,7 +420,9 @@ def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows:
_table_html(document_id, table_id) _table_html(document_id, table_id)
sample = ShippingDocumentProfileTestSample( sample = ShippingDocumentProfileTestSample(
suite_id=suite.id, document_id=int(document_id), table_id=str(table_id), 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, expected_rows_json=_expected_rows(expected_rows),
expected_order_fields_json=_expected_order_fields(expected_order_fields, parser=parser),
created_by_id=actor_id,
) )
db.session.add(sample) db.session.add(sample)
try: try:
@@ -189,12 +467,24 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
raise ConflictError('Profile changed after test suite creation', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_STALE') 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 {}) contract = compile_table_header_contract(profile.schema_version.definition_json or {})
parser = _definition_contract(profile) parser = _definition_contract(profile)
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
}
failures: list[str] = [] failures: list[str] = []
passed = 0 passed = 0
for sample in suite.samples: for sample in suite.samples:
document = db.session.get(ShippingNoticeDocument, sample.document_id) document = db.session.get(ShippingNoticeDocument, sample.document_id)
layout = current_layout_snapshot(document) if document is not None else None layout = current_layout_snapshot(document) if document is not None else None
if isinstance(parser, OrderCoordinateProfileV2): if isinstance(parser, OrderCoordinateProfileV2):
field_failures = _order_field_quality_failures(
parser=parser, schema_fields=schema_fields, layout=layout or {},
expected_values=dict(sample.expected_order_fields_json or {}), sample_id=sample.id,
)
if field_failures:
failures.extend(field_failures)
continue
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {} 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 {} 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 characters = (evidence.get('tables') or {}).get(sample.table_id) if isinstance(evidence.get('tables'), dict) else None
@@ -210,6 +500,10 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
continue continue
actual_rows: list[dict[str, Any]] = [] actual_rows: list[dict[str, Any]] = []
for region in parser.table_regions: for region in parser.table_regions:
# See candidate preview: a header-only page is evidence for order
# fields only and must not be sent to the line reconstruction engine.
if not region.line_layouts:
continue
actual_rows.extend(item.fields for item in reconstruct_coordinate_profile_rows( 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, 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(), line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
@@ -345,12 +639,53 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile,
run.profile_checksum = published_checksum run.profile_checksum = published_checksum
def _serialize_suite_sample(sample: ShippingDocumentProfileTestSample) -> dict[str, Any]:
"""返回单份盲测样本的安全展示信息。
核心逻辑:从当前布局快照反查表格所在页,仅公开文件名、文档和表格标识,
不向工作台回传人工真值或订单正文。
Args:
sample: 已属于盲测集的样本 ORM 记录。
Returns:
可用于工作台已加入样本清单的脱敏摘要。
"""
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,
)
return {
'id': sample.id,
'document_id': sample.document_id,
'table_id': sample.table_id,
'filename': str(document.filename or '') if document is not None else '',
'page_no': int(table.get('page_no') or 1) if isinstance(table, dict) else 1,
}
def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]: def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
"""返回不含订单正文的盲测治理摘要,供管理端确认发布状态。""" """返回不含订单正文及真值的盲测治理摘要,供管理端维护与确认发布状态。
核心逻辑:保留运行门禁汇总,并附带可删除样本的最小定位信息;真值仍只在
服务端保存,避免通过摘要接口泄露订单内容。
Args:
suite: 当前 Profile checksum 对应的盲测集。
Returns:
含样本清单、执行摘要与批准状态的管理端 DTO。
"""
latest = suite.runs[-1] if suite.runs else None latest = suite.runs[-1] if suite.runs else None
return { return {
'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum, 'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum,
'status': suite.status, 'sample_count': len(suite.samples), 'status': suite.status, 'sample_count': len(suite.samples),
'samples': [_serialize_suite_sample(sample) for sample in suite.samples],
'approved_at': suite.approved_at.isoformat() if suite.approved_at else None, 'approved_at': suite.approved_at.isoformat() if suite.approved_at else None,
'latest_run': None if latest is None else { 'latest_run': None if latest is None else {
'status': latest.status, 'sample_count': latest.sample_count, 'status': latest.status, 'sample_count': latest.sample_count,
@@ -19,7 +19,7 @@ from flask import current_app
from app import db from app import db
from app.core.errors import ConflictError, ValidationError from app.core.errors import ConflictError, ValidationError
from app.models import ShippingTask, ShippingTaskEvent from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING, PH_UPLOAD_RESULT_UNKNOWN
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
from app.services.shipping_notice.inventory_workflow import ( from app.services.shipping_notice.inventory_workflow import (
@@ -40,6 +40,7 @@ from app.services.shipping_notice.rpa import write_upload_trigger
from app.services.shipping_notice.upload_attempt_service import ( from app.services.shipping_notice.upload_attempt_service import (
complete_attempt, complete_attempt,
current_upload_artifact, current_upload_artifact,
mark_attempt_result_unknown,
record_manual_upload, record_manual_upload,
start_rpa_attempt, start_rpa_attempt,
) )
@@ -734,15 +735,28 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
) )
last_failed = latest_event(task, "upload_rpa_failed") last_failed = latest_event(task, "upload_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at): if not last_failed or (last_failed.created_at < last_trigger.created_at):
attempt_id = (last_trigger.detail_json or {}).get('attempt_id') if isinstance(last_trigger.detail_json, dict) else None
from app.models import ShippingUploadAttempt
timed_out_attempt = db.session.get(ShippingUploadAttempt, attempt_id) if attempt_id else None
if timed_out_attempt is not None:
mark_attempt_result_unknown(timed_out_attempt)
task.error_message = t("workflow.fulfillment.upload_timeout_error", lang=lang).format( task.error_message = t("workflow.fulfillment.upload_timeout_error", lang=lang).format(
timeout=timeout_seconds timeout=timeout_seconds
) )
task.pending_human_reason = PH_UPLOAD_RESULT_UNKNOWN
task.upload_status = 'unknown'
log_task_event( log_task_event(
task, task,
"upload_rpa_failed", "upload_rpa_result_unknown",
{"error": "timeout", "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, {"error": "timeout", "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
) )
db.session.flush() db.session.commit()
return tool_response(
status="needs_human",
task=task,
message='货代上传结果未知,已冻结重试;请先核对货代结果并登记回执或明确拒绝。',
data=serialize_task_for_tool(task),
)
attempts = upload_rpa_attempts(task) attempts = upload_rpa_attempts(task)
if attempts >= max_attempts: if attempts >= max_attempts:
@@ -2,8 +2,9 @@
backend/app/services/shipping_notice/order_document_profile_service.py backend/app/services/shipping_notice/order_document_profile_service.py
用途:管理订单文档模板 Profile 的草稿、发布、退役和 Run 冻结快照。 用途:管理订单文档模板 Profile 的草稿、发布、退役和 Run 冻结快照。
依赖:ShippingOrderDocumentProfile、订单 Schema 版本、document_layout.order_profile 纯契约。 依赖:ShippingOrderDocumentProfile、盲测套件模型、订单 Schema 版本、document_layout.order_profile 纯契约。
逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本。 逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本;
删除草稿前先清理关联盲测套件,避免 suites.profile_id 外键 500。
""" """
from __future__ import annotations from __future__ import annotations
@@ -25,6 +26,7 @@ from app.extensions import db
from app.models import ( from app.models import (
FileAsset, FileAsset,
ShippingDocumentProfileTestSample, ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
ShippingNoticeDocument, ShippingNoticeDocument,
ShippingNoticeIntake, ShippingNoticeIntake,
ShippingOrderDocumentProfile, ShippingOrderDocumentProfile,
@@ -48,6 +50,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
order_profile_structure_fingerprint, order_profile_structure_fingerprint,
reconstruct_order_profile_html, reconstruct_order_profile_html,
) )
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.order_schema.compatibility import ( from app.services.shipping_notice.order_schema.compatibility import (
compare_profile_schema, compare_profile_schema,
is_replacement_compatible, is_replacement_compatible,
@@ -76,6 +79,7 @@ def _match_summary(definition: dict[str, Any]) -> dict[str, Any]:
'minimum_score': match.get('minimum_score'), 'minimum_score': match.get('minimum_score'),
'minimum_margin': match.get('minimum_margin'), 'minimum_margin': match.get('minimum_margin'),
'table_region_count': len(definition.get('table_regions') or []), 'table_region_count': len(definition.get('table_regions') or []),
'order_field_layout_count': len(definition.get('order_field_layouts') or []),
} }
@@ -100,6 +104,7 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]:
line_layout_count = 0 line_layout_count = 0
header_layout_count = 0 header_layout_count = 0
field_codes: set[str] = set() field_codes: set[str] = set()
order_field_count = 0
for table_region in table_regions: for table_region in table_regions:
if not isinstance(table_region, dict): if not isinstance(table_region, dict):
continue continue
@@ -111,9 +116,14 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]:
for field_region in line_layout.get('field_regions') or []: for field_region in line_layout.get('field_regions') or []:
if isinstance(field_region, dict) and field_region.get('field_code'): if isinstance(field_region, dict) and field_region.get('field_code'):
field_codes.add(str(field_region['field_code'])) field_codes.add(str(field_region['field_code']))
for order_field in definition.get('order_field_layouts') or []:
if isinstance(order_field, dict) and order_field.get('field_code'):
field_codes.add(str(order_field['field_code']))
order_field_count += 1
return { return {
'table_region_count': len(table_regions), 'header_layout_count': header_layout_count, 'table_region_count': len(table_regions), 'header_layout_count': header_layout_count,
'line_layout_count': line_layout_count, 'bound_field_count': len(field_codes), 'line_layout_count': line_layout_count, 'order_field_layout_count': order_field_count,
'bound_field_count': len(field_codes),
} }
@@ -220,6 +230,8 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
normalized = { normalized = {
'document_match': raw.get('document_match'), 'document_match': raw.get('document_match'),
'table_regions': raw.get('table_regions'), 'table_regions': raw.get('table_regions'),
'order_field_layouts': raw.get('order_field_layouts') or [],
'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [],
} }
for table_region in normalized['table_regions'] or []: for table_region in normalized['table_regions'] or []:
if not isinstance(table_region, dict): if not isinstance(table_region, dict):
@@ -258,12 +270,52 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
{'field_id': str(profile_fields[target]['field_id']), 'field_code': target} {'field_id': str(profile_fields[target]['field_id']), 'field_code': target}
for target in sorted(outputs) for target in sorted(outputs)
] ]
for order_field in normalized['order_field_layouts']:
if not isinstance(order_field, dict):
continue
code = str(order_field.get('field_code') or '').strip()
field = profile_fields.get(code)
if field is None or field.get('scope') != 'header':
raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
order_field['field_id'] = str(field['field_id'])
normalizer = order_field.get('normalizer_key')
if normalizer is not None and normalizer != field.get('normalizer_key'):
raise ValidationError('Order field normalizer must match Schema', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
order_field['normalizer_key'] = field.get('normalizer_key')
# `ocr_coordinate` is a minimum level, not an OCR-only restriction: native PDF
# coordinates are stronger evidence and remain valid at runtime.
allowed_sources = (
['pdf_coordinate']
if order_field.get('minimum_evidence_level', 'coordinate') == 'coordinate'
else ['pdf_coordinate', 'ocr_coordinate']
)
schema_sources = field.get('allowed_sources')
if not isinstance(schema_sources, list) or not set(allowed_sources) & set(schema_sources):
raise ValidationError('Schema field does not allow order field coordinate source', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
order_field_codes = [
str(item.get('field_code') or '').strip()
for item in normalized['order_field_layouts']
if isinstance(item, dict) and str(item.get('field_code') or '').strip()
]
duplicate_order_field_codes = sorted({
code for code in order_field_codes if order_field_codes.count(code) > 1
})
if duplicate_order_field_codes:
# Expose the duplicate Schema codes before Pydantic returns a generic
# contract error, so the workbench can direct the administrator to it.
raise ValidationError(
'Order field may bind only once',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
details={'reason': 'order_field_duplicate', 'field_codes': duplicate_order_field_codes},
)
try: try:
contract = OrderCoordinateProfileV2( contract = OrderCoordinateProfileV2(
profile_code='VALIDATION_PROFILE', profile_code='VALIDATION_PROFILE',
version=1, version=1,
document_match=normalized['document_match'], document_match=normalized['document_match'],
table_regions=normalized['table_regions'], table_regions=normalized['table_regions'],
order_field_layouts=normalized['order_field_layouts'],
draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'],
) )
except (TypeError, ValueError) as exc: except (TypeError, ValueError) as exc:
raise ValidationError( raise ValidationError(
@@ -273,6 +325,8 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
'contract_version': contract.contract_version, 'contract_version': contract.contract_version,
'document_match': contract.document_match.model_dump(), 'document_match': contract.document_match.model_dump(),
'table_regions': [item.model_dump() for item in contract.table_regions], 'table_regions': [item.model_dump() for item in contract.table_regions],
'order_field_layouts': [item.model_dump() for item in contract.order_field_layouts],
'draft_unbound_order_field_layouts': [item.model_dump() for item in contract.draft_unbound_order_field_layouts],
} }
@@ -293,6 +347,8 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina
version=profile.version, version=profile.version,
document_match=definition.get('document_match'), document_match=definition.get('document_match'),
table_regions=definition.get('table_regions'), table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
) )
@@ -489,6 +545,7 @@ def preview_profile_region(
contract = OrderCoordinateProfileV2( contract = OrderCoordinateProfileV2(
profile_code=profile.profile_code, version=profile.version, profile_code=profile.profile_code, version=profile.version,
document_match=definition['document_match'], table_regions=definition['table_regions'], document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
) )
table_id = str(data.get('table_id') or '').strip() table_id = str(data.get('table_id') or '').strip()
layout = _document_layout(document) layout = _document_layout(document)
@@ -587,6 +644,7 @@ def suggest_profile_header(
contract = OrderCoordinateProfileV2( contract = OrderCoordinateProfileV2(
profile_code=profile.profile_code, version=profile.version, profile_code=profile.profile_code, version=profile.version,
document_match=definition['document_match'], table_regions=definition['table_regions'], document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
) )
table_id = str(data.get('table_id') or '').strip() table_id = str(data.get('table_id') or '').strip()
layout = _document_layout(document) layout = _document_layout(document)
@@ -735,6 +793,359 @@ def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[s
return [item for item in characters if isinstance(item, dict)] return [item for item in characters if isinstance(item, dict)]
def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tuple[list[dict[str, Any]], str | None]:
"""读取整页字符证据供订单字段锚点建议使用,绝不以表格坐标代替页面坐标。"""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no))
source = (evidence.get('sources') or {}).get('pages', {}).get(str(page_no))
if not isinstance(glyphs, list):
return [], None
return [item for item in glyphs if isinstance(item, dict)], str(source or '') or None
def _ensure_page_coordinate_evidence(
*, document: ShippingNoticeDocument, layout: dict[str, Any], page_no: int,
) -> dict[str, Any]:
"""为历史表格样本补齐整页坐标,避免订单抬头因仅存表内字符而无法自动标记。"""
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
if glyphs and source in {'pdf_coordinate', 'ocr_coordinate'}:
return layout
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
asset = db.session.get(FileAsset, document.asset_id)
if asset is None:
return layout
try:
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
native_page = next(item for item in extract_native_pdf_pages(read_asset_bytes(asset)) if item.page_no == page_no)
page_glyphs = [item.model_dump(mode='json') for item in native_page.characters]
page_source = 'pdf_coordinate'
if not page_glyphs:
page_glyphs = _ocr_lines_to_page_characters(
lines=extract_ocr_lines(native_page.image, page_width=native_page.width, page_height=native_page.height),
)
page_source = 'ocr_coordinate'
if not page_glyphs:
return layout
next_snapshot = dict(layout)
evidence = dict(next_snapshot.get('coordinate_evidence') or {})
pages = dict(evidence.get('pages') or {})
pages[str(page_no)] = {'width': native_page.width, 'height': native_page.height}
page_map = dict(evidence.get('page_glyphs') or {})
page_map[str(page_no)] = page_glyphs
sources = dict(evidence.get('sources') or {})
source_pages = dict(sources.get('pages') or {})
source_pages[str(page_no)] = page_source
sources['pages'] = source_pages
next_snapshot['coordinate_evidence'] = {**evidence, 'pages': pages, 'page_glyphs': page_map, 'sources': sources}
record_inline_layout_snapshot(
document, next_snapshot,
parser_key=f'mineru-pipeline+{page_source}:shipping_order_page_coordinate_evidence.v1',
)
db.session.commit()
return next_snapshot
except Exception:
# A suggestion is optional. Preserve existing table annotation behavior if the source cannot be reread.
return layout
def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, float], list[dict[str, Any]]]]:
"""将同一视觉行的字符压缩为文本和包围盒,供保守的标签精确匹配。"""
rows: list[list[dict[str, Any]]] = []
for glyph in sorted(glyphs, key=lambda item: (float((item.get('bbox') or {}).get('y0', 0)), float((item.get('bbox') or {}).get('x0', 0)))):
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not bbox or not str(glyph.get('text') or '').strip():
continue
center_y = (float(bbox.get('y0', 0)) + float(bbox.get('y1', 0))) / 2
if rows:
previous = rows[-1][0].get('bbox') or {}
previous_y = (float(previous.get('y0', 0)) + float(previous.get('y1', 0))) / 2
height = max(1.0, float(previous.get('y1', 0)) - float(previous.get('y0', 0)))
if abs(center_y - previous_y) <= height * .65:
rows[-1].append(glyph)
continue
rows.append([glyph])
result: list[tuple[str, dict[str, float], list[dict[str, Any]]]] = []
for row in rows:
ordered = sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
boxes = [item['bbox'] for item in ordered]
parts: list[str] = []
previous_x1: float | None = None
previous_width = 0.0
for item in ordered:
box = item['bbox']
x0, x1 = float(box['x0']), float(box['x1'])
# Native PDF glyph streams usually omit whitespace. Restore a visual word gap
# so suggested anchor text remains usable in the workbench and template config.
if previous_x1 is not None and x0 - previous_x1 > max(1.5, previous_width * 1.45):
parts.append(' ')
parts.append(str(item.get('text') or ''))
previous_x1, previous_width = x1, max(1.0, x1 - x0)
result.append((
''.join(parts),
{'x0': min(float(box['x0']) for box in boxes), 'y0': min(float(box['y0']) for box in boxes),
'x1': max(float(box['x1']) for box in boxes), 'y1': max(float(box['y1']) for box in boxes)},
ordered,
))
return result
def _anchor_text_key(value: str) -> str:
"""按标签语义比较,忽略空白和常见分隔符但不尝试模糊纠错。"""
return re.sub(r'[^\w]+', '', value, flags=re.UNICODE).casefold()
def _inline_anchor_and_value_regions(
*, text: str, line_bbox: dict[str, float], glyphs: list[dict[str, Any]], label: str, width: float, height: float,
) -> tuple[dict[str, float], dict[str, float], str]:
"""从字符 bbox 切分同行标签和值,绝不把同一行其他字段扩展进值框。"""
label_key = _anchor_text_key(label)
consumed: list[dict[str, Any]] = []
consumed_start = 0
key = ''
for index, glyph in enumerate(glyphs):
glyph_key = _anchor_text_key(str(glyph.get('text') or ''))
if not glyph_key:
continue
if label_key.startswith(key + glyph_key):
if not consumed:
consumed_start = index
consumed.append(glyph)
key += glyph_key
if key == label_key:
break
elif not consumed:
continue
else:
break
if not consumed or key != label_key:
consumed = glyphs[:1]
consumed_start = 0
# Consume the label separator but never add it to the value area.
anchor_glyphs = list(consumed)
after_label = glyphs[consumed_start + len(consumed):]
while after_label and str(after_label[0].get('text') or '') in ':: ':
anchor_glyphs.append(after_label.pop(0))
anchor_boxes = [item['bbox'] for item in anchor_glyphs]
anchor = {
'x0': max(0.0, min(1.0, min(float(box['x0']) for box in anchor_boxes) / width)),
'y0': max(0.0, min(1.0, min(float(box['y0']) for box in anchor_boxes) / height)),
'x1': max(0.0, min(1.0, max(float(box['x1']) for box in anchor_boxes) / width)),
'y1': max(0.0, min(1.0, max(float(box['y1']) for box in anchor_boxes) / height)),
}
if after_label:
normalized_text = text.casefold()
label_start = normalized_text.find(label.casefold())
label_end = label_start + len(label) if label_start >= 0 else len(label)
while label_end < len(text) and text[label_end] in ':: ':
label_end += 1
inline_value_text = text[label_end:].strip()
# PDF text can place independent key/value groups on the same visual row
# without a large glyph gap. Stop before the next explicit ``LABEL:``.
next_label = re.search(r'\s+[A-Za-z][A-Za-z0-9 ]{1,30}[::]', inline_value_text)
value_char_limit = (
len([char for char in inline_value_text[:next_label.start()] if not char.isspace()])
if next_label else None
)
# A large character gap starts the next key/value group on a shared visual
# row. Keep only the first contiguous value rather than swallowing it.
value_glyphs = [after_label[0]]
for glyph in after_label[1:]:
previous = value_glyphs[-1]['bbox']
current = glyph['bbox']
previous_width = max(1.0, float(previous['x1']) - float(previous['x0']))
if float(current['x0']) - float(previous['x1']) > previous_width * 3.5:
break
value_glyphs.append(glyph)
if value_char_limit is not None:
value_glyphs = value_glyphs[:max(1, value_char_limit)]
value_boxes = [item['bbox'] for item in value_glyphs]
# A relative percentage becomes visibly huge on tall PDFs. Keep the visual
# breathing room to at most one native page pixel around a single-line value.
vertical_padding = min(.0015, 1.0 / max(1.0, height))
value = {
'x0': max(anchor['x1'] + .003, min(float(box['x0']) for box in value_boxes) / width - .003),
'y0': max(0.0, min(float(box['y0']) for box in value_boxes) / height - vertical_padding),
'x1': min(.99, max(float(box['x1']) for box in value_boxes) / width + .003),
'y1': min(1.0, max(float(box['y1']) for box in value_boxes) / height + vertical_padding),
}
return anchor, value, 'right_of_anchor'
value = {
'x0': anchor['x0'], 'y0': min(.98, anchor['y1'] + .012),
'x1': min(.96, max(anchor['x1'] + .2, anchor['x0'] + .45)), 'y1': min(1.0, anchor['y1'] + .075),
}
return anchor, value, 'below_anchor'
def _inline_value_text(*, text: str, label: str) -> str:
"""返回与同行值框一致的首个值文本,供候选面板展示而不重复读取 PDF。"""
start = text.casefold().find(label.casefold())
suffix = text[start + len(label):] if start >= 0 else ''
suffix = suffix.lstrip(':: ').strip()
next_label = re.search(r'\s+[A-Za-z][A-Za-z0-9 ]{1,30}[::]', suffix)
return (suffix[:next_label.start()] if next_label else suffix).strip()
def _generic_order_label_candidates(
*, lines: list[tuple[str, dict[str, float], list[dict[str, Any]]]], width: float, height: float,
table_start_y: float | None, known_anchor_keys: set[str], bound_line_indexes: set[int], source: str,
) -> list[dict[str, Any]]:
"""为尚未配置 Schema 别名的 ``LABEL: value`` 生成未绑定订单字段候选。"""
candidates: list[dict[str, Any]] = []
for line_index, (text, bbox, glyphs) in enumerate(lines):
# 只取明细表前的上半段抬头;紧贴表格的 QUALITY/SHIPMENT 等条款不属于订单字段。
if table_start_y is not None and bbox['y0'] >= table_start_y - height * .18:
continue
match = re.match(r'^\s*([^::]{2,42}?)[::]', text)
if match is None:
continue
label = match.group(1).strip()
key = _anchor_text_key(label)
if line_index in bound_line_indexes or len(key) < 2 or key in known_anchor_keys or len(label.split()) > 3:
continue
anchor, value_region, value_mode = _inline_anchor_and_value_regions(
text=text, line_bbox=bbox, glyphs=glyphs, label=label, width=width, height=height,
)
candidates.append({
'field_id': '', 'field_code': '', 'display_name': label, 'source': source,
'status': 'suggested', 'binding_status': 'unbound', 'anchor_text': label,
'anchor_region': anchor,
'value_region': value_region, 'value_mode': value_mode,
'suggested_value': _inline_value_text(text=text, label=label),
'issue': 'order_field_schema_binding_required',
})
return candidates
def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
按当前未保存的 v2 定义重读订单字段值,供工作台刷新后展示复核证据。
浏览器只能提交当前样本与受控定义;读取复用正式运行期锚点/相对区域算法,
因此通用 Ship To、Bill To 标签不会依赖自动建议的标签过滤范围。
"""
try:
document_id = int(data.get('document_id'))
page_no = int(data.get('page_no') or 1)
except (TypeError, ValueError) as exc:
raise ValidationError('document_id or page_no is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
document = db.session.get(ShippingNoticeDocument, document_id)
if document is None:
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
schema_version = _require_schema_version(data.get('schema_version_id'))
definition = _normalize_definition(data.get('definition'), schema_version=schema_version)
profile = OrderCoordinateProfileV2(
profile_code='WORKBENCH_PREVIEW', version=1,
document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
draft_unbound_order_field_layouts=definition['draft_unbound_order_field_layouts'],
)
layout = _ensure_page_coordinate_evidence(
document=document, layout=_document_layout(document), page_no=page_no,
)
fields_by_id = {
str(field['field_id']): field
for field in _schema_profile_fields(schema_version).values()
if field.get('scope') == 'header'
}
return {
'page_no': page_no,
'fields': [
item.model_dump(mode='json')
for item in extract_order_fields(
profile=profile, schema_fields=fields_by_id,
coordinate_evidence=layout.get('coordinate_evidence') or {},
)
if item.page_no == page_no
],
}
def suggest_order_field_layouts(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
从冻结 Schema 的 Header 标签别名生成订单级字段的待复核锚点和值区建议。
只使用整页 PDF/OCR 字符坐标;标签不唯一、无坐标或 Schema 未授权时保留问题码,
绝不自动绑定或发布任何字段。
"""
try:
document_id = int(data.get('document_id'))
page_no = int(data.get('page_no') or 1)
except (TypeError, ValueError) as exc:
raise ValidationError('document_id or page_no is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
document = db.session.get(ShippingNoticeDocument, document_id)
if document is None:
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
schema_version = _require_schema_version(data.get('schema_version_id'))
layout = _document_layout(document)
layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=page_no)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page = (evidence.get('pages') or {}).get(str(page_no))
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
if not isinstance(page, dict) or not glyphs or source not in {'pdf_coordinate', 'ocr_coordinate'}:
return {'page_no': page_no, 'order_field_candidates': [], 'issues': ['order_field_page_coordinate_unavailable'], 'status': 'needs_review'}
try:
width, height = float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('Page coordinate evidence is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
lines = _page_text_lines(glyphs)
candidates: list[dict[str, Any]] = []
known_anchor_keys: set[str] = set()
bound_line_indexes: set[int] = set()
for field in (schema_version.definition_json or {}).get('fields') or []:
if (
not isinstance(field, dict)
or field.get('enabled') is False
or field.get('auto_annotation_enabled', True) is False
or field.get('scope') != 'header'
):
continue
if source not in set(field.get('allowed_sources') or []):
continue
labels = [str(field.get('display_name') or '').strip(), *[str(item).strip() for item in field.get('aliases') or []]]
# Display text and alias often differ only by whitespace/case; count each visual hit once.
labels = list({key: item for item in labels if len(key := _anchor_text_key(item)) >= 2}.values())
known_anchor_keys.update(_anchor_text_key(item) for item in labels)
hits = [
(line_index, label, bbox)
for line_index, (text, bbox, _) in enumerate(lines)
for label in labels if _anchor_text_key(label) in _anchor_text_key(text)
]
base = {'field_id': str(field.get('field_id') or ''), 'field_code': str(field.get('field_code') or ''),
'display_name': str(field.get('display_name') or field.get('field_code') or ''), 'source': source}
if len(hits) != 1:
candidates.append({**base, 'status': 'ambiguous' if len(hits) > 1 else 'unavailable',
'issue': 'order_field_anchor_ambiguous' if len(hits) > 1 else 'order_field_anchor_not_found'})
continue
line_index, label, bbox = hits[0]
bound_line_indexes.add(line_index)
text, _, line_glyphs = lines[line_index]
anchor, value_region, value_mode = _inline_anchor_and_value_regions(
text=text, line_bbox=bbox, glyphs=line_glyphs, label=label, width=width, height=height,
)
candidates.append({**base, 'status': 'suggested', 'anchor_text': label, 'anchor_region': anchor,
'value_region': value_region, 'value_mode': value_mode,
'suggested_value': _inline_value_text(text=text, label=label),
'binding_status': 'bound', 'issue': None})
table_starts = [
float(item.get('bbox', {}).get('y0')) for item in layout.get('tables') or []
if isinstance(item, dict) and isinstance(item.get('bbox'), dict) and item.get('bbox', {}).get('y0') is not None
]
candidates.extend(_generic_order_label_candidates(
lines=lines, width=width, height=height, table_start_y=min(table_starts) if table_starts else None,
known_anchor_keys=known_anchor_keys, bound_line_indexes=bound_line_indexes, source=source,
))
_audit(profile_id=None, document_id=document.id, event_type='order_field_suggestions_viewed', actor_id=actor_id, detail={
'page_no': page_no, 'candidate_count': len(candidates), 'suggested_count': sum(item['status'] == 'suggested' for item in candidates),
})
db.session.commit()
return {'page_no': page_no, 'order_field_candidates': candidates, 'issues': [], 'status': 'needs_review'}
def generate_ocr_coordinate_evidence(*, document_id: int, table_id: str, actor_id: int | None) -> dict[str, Any]: def generate_ocr_coordinate_evidence(*, document_id: int, table_id: str, actor_id: int | None) -> dict[str, Any]:
""" """
为指定 PDF 表格补齐字符坐标证据;优先恢复原生文字层,仅在无文字层时执行 OCR。 为指定 PDF 表格补齐字符坐标证据;优先恢复原生文字层,仅在无文字层时执行 OCR。
@@ -853,6 +1264,27 @@ def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) ->
return result return result
def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]:
"""将 OCR 行拆为整页字符坐标,专供订单抬头锚点候选,不与表格 cell 证据混用。"""
result: list[dict[str, Any]] = []
source_index = 0
for line in lines:
text = str(line.text or '')
box = line.bbox
if not text:
continue
width = (box.x1 - box.x0) / len(text)
for index, character in enumerate(text):
if not character.strip():
continue
result.append({'text': character, 'source_index': source_index, 'bbox': {
'x0': box.x0 + index * width, 'y0': box.y0,
'x1': box.x0 + (index + 1) * width, 'y1': box.y1,
}})
source_index += 1
return result
def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, Any], raw_settings: Any) -> str: def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, Any], raw_settings: Any) -> str:
"""从持久化坐标证据和管理员确认的边界生成可审核重建表,缺任一条件均拒绝。""" """从持久化坐标证据和管理员确认的边界生成可审核重建表,缺任一条件均拒绝。"""
try: try:
@@ -1111,7 +1543,7 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
data: document_id、table_id,以及可选的非负 row_offset。省略 row_offset 时建议全部行。 data: document_id、table_id,以及可选的非负 row_offset。省略 row_offset 时建议全部行。
actor_id: 当前管理员 ID;保留与预览接口一致的授权边界。 actor_id: 当前管理员 ID;保留与预览接口一致的授权边界。
Returns: Returns:
仅含相对边界、少量列示例及确定性 line_no 建议的待审核配置;指定行时只返回该行。 仅含相对边界、少量列示例及字段规则驱动的待审核绑定;指定行时只返回该行。
""" """
try: try:
document_id = int(data.get('document_id')) document_id = int(data.get('document_id'))
@@ -1129,6 +1561,14 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
characters = _coordinate_characters(layout, table_id) characters = _coordinate_characters(layout, table_id)
if raw_table is None or not characters or not isinstance(raw_table.get('bbox'), dict): if raw_table is None or not characters or not isinstance(raw_table.get('bbox'), dict):
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE')
schema_fields: list[dict[str, Any]] = []
if data.get('schema_version_id') is not None:
version = _require_schema_version(data.get('schema_version_id'))
schema_fields = [
field for field in _schema_fields(version).values()
if field.get('auto_annotation_enabled', True)
and set(field.get('allowed_sources') or []) & {'pdf_coordinate', 'ocr_coordinate'}
]
suggestions = suggest_multi_subrow_layouts( suggestions = suggest_multi_subrow_layouts(
characters=characters, table_bbox=raw_table['bbox'], characters=characters, table_bbox=raw_table['bbox'],
) )
@@ -1162,9 +1602,50 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
} }
except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc: except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc:
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
header_suggestions = suggest_header_regions(characters=characters, table_bbox=raw_table['bbox'])
# Only exact, unique aliases can bind a column. Position is considered only after
# the label itself is proven, preventing shifted documents from remapping fields.
aliases: dict[str, str | None] = {}
for field in schema_fields:
code = str(field.get('field_code') or '').strip()
# A schema code is a stable, deterministic label variant: `unit_price`
# normalizes to `UNIT PRICE`. Include it alongside maintained aliases so
# common table headers bind without positional guessing.
for value in (code.replace('_', ' '), field.get('display_name'), *(field.get('aliases') or [])):
key = _anchor_text_key(str(value or ''))
if key:
aliases[key] = code if aliases.get(key, code) == code else None
for header in header_suggestions:
for field in header.fields:
key = _anchor_text_key(field.text)
code = aliases.get(key)
field.field_code = code
field.confidence = 'exact_alias' if code else ('ambiguous' if key in aliases else 'unmapped')
serialized = [] serialized = []
for item in suggestions: for item in suggestions:
payload = item.model_dump() payload = item.model_dump()
if item.row_offset == 0 and schema_fields:
mapped_codes: list[str | None] = [None] * (len(item.column_boundaries) - 1)
mapped_indexes: dict[int, list[str]] = {}
for header in header_suggestions:
for field in header.fields:
if not field.field_code:
continue
center = (field.region.x0 + field.region.x1) / 2
column_index = min(
range(len(mapped_codes)),
key=lambda index: abs(
center - (item.column_boundaries[index] + item.column_boundaries[index + 1]) / 2,
),
)
mapped_indexes.setdefault(column_index, []).append(field.field_code)
for column_index, codes in mapped_indexes.items():
# Multiple exact labels pointing to one reconstructed column is still
# ambiguous; retain the visual candidate but require manual binding.
if len(set(codes)) == 1:
mapped_codes[column_index] = codes[0]
payload['suggested_field_codes'] = mapped_codes
payload['region'] = { payload['region'] = {
'x0': table_region['x0'], 'x0': table_region['x0'],
'x1': table_region['x1'], 'x1': table_region['x1'],
@@ -1173,7 +1654,7 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
} }
serialized.append(payload) serialized.append(payload)
serialized_headers = [] serialized_headers = []
for item in suggest_header_regions(characters=characters, table_bbox=raw_table['bbox']): for item in header_suggestions:
payload = item.model_dump() payload = item.model_dump()
region = payload['region'] region = payload['region']
payload['region'] = { payload['region'] = {
@@ -1428,6 +1909,37 @@ def create_schema_migration_draft(
if isinstance(item, dict) and item.get('field_id') and item.get('enabled', True) if isinstance(item, dict) and item.get('field_id') and item.get('enabled', True)
} }
definition = remap_profile_field_codes(source.definition_json or {}, target_schema.definition_json or {}) definition = remap_profile_field_codes(source.definition_json or {}, target_schema.definition_json or {})
unbound_order_fields = list(definition.get('draft_unbound_order_field_layouts') or [])
retained_order_fields: list[dict[str, Any]] = []
for field in definition.get('order_field_layouts') or []:
if not isinstance(field, dict):
continue
field_id = str(field.get('field_id') or '')
if field_id not in breaking_ids:
retained_order_fields.append(field)
continue
resolution = resolutions[field_id]
replacement_id = str(resolution.get('replacement_field_id') or '') if isinstance(resolution, dict) else ''
if replacement_id:
replacement = target_fields.get(replacement_id)
original = next((item for item in (source_schema.definition_json or {}).get('fields') or []
if isinstance(item, dict) and str(item.get('field_id')) == field_id), None)
if replacement is None or original is None or not is_replacement_compatible(
original, replacement, source_field_id=field_id, candidate_field_id=replacement_id,
):
raise ValidationError('Replacement field is not contract-compatible', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID')
field['field_id'] = replacement_id
field['field_code'] = str(replacement.get('field_code') or '')
retained_order_fields.append(field)
elif isinstance(resolution, dict) and resolution.get('action') == 'unbind':
unbound_order_fields.append({
key: value for key, value in field.items()
if key not in {'field_id', 'field_code', 'normalizer_key', 'required'}
} | {'label': str(field.get('field_code') or field_id)})
else:
raise ValidationError('Migration resolution is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID')
definition['order_field_layouts'] = retained_order_fields
definition['draft_unbound_order_field_layouts'] = unbound_order_fields
for table in definition.get('table_regions') or []: for table in definition.get('table_regions') or []:
if not isinstance(table, dict): if not isinstance(table, dict):
continue continue
@@ -1485,6 +1997,8 @@ def create_schema_migration_draft(
'parent_layout_id': str(layout.get('layout_id') or ''), 'parent_layout_id': str(layout.get('layout_id') or ''),
'label': str(field.get('field_code') or field_id), 'label': str(field.get('field_code') or field_id),
'region': field.get('region'), 'region': field.get('region'),
# Schema-breaking migrations require an explicit field decision.
'requires_rebinding': True,
}) })
else: else:
raise ValidationError( raise ValidationError(
@@ -1561,14 +2075,21 @@ def publish(
code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT', code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
) )
if any( if any(
table.get('draft_unbound_field_regions') item.get('requires_rebinding')
for table in (profile.definition_json or {}).get('table_regions', []) for table in (profile.definition_json or {}).get('table_regions', [])
if isinstance(table, dict) if isinstance(table, dict)
for item in (table.get('draft_unbound_field_regions') or [])
if isinstance(item, dict)
): ):
raise ValidationError( raise ValidationError(
'All draft field regions must be bound before publish', 'All draft field regions must be bound before publish',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
) )
if (profile.definition_json or {}).get('draft_unbound_order_field_layouts'):
raise ValidationError(
'All draft order field layouts must be bound before publish',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
# 发布前先以草稿定义 checksum 执行训练/盲测门禁;不能先发布再补测。 # 发布前先以草稿定义 checksum 执行训练/盲测门禁;不能先发布再补测。
from app.services.shipping_notice.document_profile_quality_service import ( from app.services.shipping_notice.document_profile_quality_service import (
assert_profile_publishable, assert_profile_publishable,
@@ -1629,7 +2150,12 @@ def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]:
def delete_draft(profile_id: int) -> None: def delete_draft(profile_id: int) -> None:
"""删除未发布草稿;不可变版本永久保留审计。""" """
删除未发布草稿及其草稿盲测集;已发布/退役版本永久保留审计。
核心逻辑:草稿允许绑定独立盲测套件,但 suites.profile_id 外键无 CASCADE;
删除前先移除 suite(samples/runs 由 ORM cascade 清理),避免 IntegrityError 500。
"""
profile = db.session.get(ShippingOrderDocumentProfile, profile_id) profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
if profile is None: if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -1638,6 +2164,12 @@ def delete_draft(profile_id: int) -> None:
'Only draft order document profile can be deleted', 'Only draft order document profile can be deleted',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED', code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED',
) )
# [STEP 1] 先清盲测套件;samples/runs 随 suite cascade delete-orphan
suite = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first()
if suite is not None:
db.session.delete(suite)
db.session.flush()
# [STEP 2] 删除草稿 Profile 本体(样本表已有 DB CASCADE)
db.session.delete(profile) db.session.delete(profile)
db.session.commit() db.session.commit()
@@ -417,7 +417,8 @@ def persist_order_extraction_result(
candidate.order_extraction_id = int(dynamic['extraction'].id) candidate.order_extraction_id = int(dynamic['extraction'].id)
candidate.order_extraction_run_id = int(run_id) if run_id is not None else None candidate.order_extraction_run_id = int(run_id) if run_id is not None else None
candidate.is_current_version = True candidate.is_current_version = True
candidate.extraction_source = extraction_source automatic_acceptance = raw_order.get('_hxops_acceptance') == 'approved_deterministic_profile_v1'
candidate.extraction_source = 'approved_deterministic_profile' if automatic_acceptance else extraction_source
candidate.classification_confidence = classification_confidence candidate.classification_confidence = classification_confidence
candidate.field_confidence_json = field_confidence candidate.field_confidence_json = field_confidence
candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields']) candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields'])
@@ -426,7 +427,14 @@ def persist_order_extraction_result(
candidate.confidence = classification_confidence candidate.confidence = classification_confidence
candidate.conflicts_json = blocking_conflicts candidate.conflicts_json = blocking_conflicts
candidate.validation_status = 'ready' if not reasons else 'needs_review' candidate.validation_status = 'ready' if not reasons else 'needs_review'
candidate.selected = not reasons # Only the backend's frozen approved-profile marker can automatically accept.
candidate.candidate_status = 'accepted' if automatic_acceptance else 'provisional'
candidate.acceptance_mode = 'automatic' if automatic_acceptance else None
candidate.accepted_at = datetime.utcnow() if automatic_acceptance else None
candidate.accepted_by_id = None
candidate.acceptance_reason = 'approved_deterministic_profile' if automatic_acceptance else None
candidate.acceptance_policy_version = 'deterministic-profile-v1' if automatic_acceptance else None
candidate.selected = bool(automatic_acceptance)
identity = build_business_fingerprint(normalized) identity = build_business_fingerprint(normalized)
content = build_content_fingerprint(normalized) content = build_content_fingerprint(normalized)
candidate.business_fingerprint = identity.get('fingerprint') candidate.business_fingerprint = identity.get('fingerprint')
@@ -493,12 +501,44 @@ def persist_order_extraction_result(
candidate.duplicate_target_task_no = str(matches[0].get('task_no') or '').strip().upper() or None candidate.duplicate_target_task_no = str(matches[0].get('task_no') or '').strip().upper() or None
# [STEP] 仅无审核阻断原因时才选中自动打开;证据/冲突失败必须保持未选中, # [STEP] 仅无审核阻断原因时才选中自动打开;证据/冲突失败必须保持未选中,
# 否则同 Intake 其它 ready Candidate 会被 selection 门禁整批挡住。 # 否则同 Intake 其它 ready Candidate 会被 selection 门禁整批挡住。
candidate.selected = not reasons candidate.selected = False
candidate.validation_status = 'ready' if not reasons else 'needs_review' candidate.validation_status = 'ready' if not reasons else 'needs_review'
elif duplicate.get('blocking'): elif duplicate.get('blocking'):
reasons.append('duplicate_decision_required') reasons.append('duplicate_decision_required')
candidate.selected = False candidate.selected = False
candidate.validation_status = 'needs_review' candidate.validation_status = 'needs_review'
# An approved template is automatic only after the same strict field and
# duplicate gates as a manual decision. A partial parse stays provisional.
automatic_eligible = (
automatic_acceptance
and not reasons
and candidate.validation_status == 'ready'
and not duplicate.get('blocking')
)
open_existing_eligible = (
candidate.duplicate_resolution == 'open_existing'
and bool(candidate.duplicate_target_task_no)
and not reasons
and candidate.validation_status == 'ready'
)
if open_existing_eligible:
# This does not admit a Dify result into new fulfillment. It only
# selects a strong duplicate for the dedicated existing-task path.
# Candidate acceptance remains exclusively automatic/manual/legacy.
candidate.candidate_status = 'provisional'
candidate.acceptance_mode = None
candidate.accepted_at = None
candidate.accepted_by_id = None
candidate.acceptance_reason = None
candidate.acceptance_policy_version = None
candidate.selected = True
elif not automatic_eligible:
candidate.candidate_status = 'provisional'
candidate.acceptance_mode = None
candidate.accepted_at = None
candidate.acceptance_reason = None
candidate.acceptance_policy_version = None
candidate.selected = False
candidate.updated_at = datetime.utcnow() candidate.updated_at = datetime.utcnow()
# Candidate 已关联本轮受控 FieldValue 后刷新影子识别;不读取其 LLM 摘要,也不触发自动确认。 # Candidate 已关联本轮受控 FieldValue 后刷新影子识别;不读取其 LLM 摘要,也不触发自动确认。
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution_safely from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution_safely
@@ -506,10 +546,17 @@ def persist_order_extraction_result(
refresh_candidate_shadow_resolution_safely(candidate) refresh_candidate_shadow_resolution_safely(candidate)
document_candidate_keys[int(document.id)].append(candidate_key) document_candidate_keys[int(document.id)].append(candidate_key)
document_has_pending[int(document.id)] = document_has_pending[int(document.id)] or bool(reasons) document_has_pending[int(document.id)] = document_has_pending[int(document.id)] or bool(reasons)
if candidate.selected and candidate.validation_status == 'ready' and auto_create_enabled: if (
candidate.selected
and candidate.validation_status == 'ready'
and (
(candidate.candidate_status == 'accepted' and auto_create_enabled)
or candidate.duplicate_resolution == 'open_existing'
)
):
auto_candidates.append(candidate) auto_candidates.append(candidate)
else: else:
if candidate.validation_status == 'ready' and not auto_create_enabled: if candidate.candidate_status != 'accepted' and candidate.validation_status == 'ready' and not auto_create_enabled:
candidate.selected = False candidate.selected = False
reasons.append('auto_create_disabled') reasons.append('auto_create_disabled')
pending_item = { pending_item = {
@@ -168,6 +168,9 @@ def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[s
po_numbers, line_keys = _order_identity(order, codes) po_numbers, line_keys = _order_identity(order, codes)
match = None match = None
for candidate in merged: for candidate in merged:
# A Dify order may never inherit an approved-profile acceptance marker.
if candidate.get('_hxops_acceptance') != order.get('_hxops_acceptance'):
continue
if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no: if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no:
continue continue
candidate_pos, candidate_lines = _order_identity(candidate, codes) candidate_pos, candidate_lines = _order_identity(candidate, codes)
@@ -380,8 +380,15 @@ def create_order_extraction_run(
capability_code='shipping.order_extraction', capability_code='shipping.order_extraction',
) )
schema_version = published_version() schema_version = published_version()
binding_auto_create_enabled = bool((binding.config_json or {}).get('auto_create_enabled'))
from app.services.shipping_notice.order_schema.service import get_auto_creation_policy
schema_auto_creation_policy = get_auto_creation_policy()
effective_auto_create_enabled = bool(
schema_auto_creation_policy.get('enabled') and binding_auto_create_enabled
)
quality_batch_id = binding.quality_batch_id quality_batch_id = binding.quality_batch_id
if bool((binding.config_json or {}).get('auto_create_enabled')): if effective_auto_create_enabled:
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
require_approved_quality_batch( require_approved_quality_batch(
@@ -413,9 +420,14 @@ def create_order_extraction_run(
intakes=intakes, intakes=intakes,
schema_version=schema_version, schema_version=schema_version,
) )
# 自动建单总开关与字段模板一起冻结,后续管理员变更不影响已创建 Run。 # 自动建单必须同时通过 Schema 总开关、运行能力绑定和质量批次;任何一层关闭
from app.services.shipping_notice.order_schema.service import get_auto_creation_policy # 都冻结为影子模式,避免仅改 Schema 意外恢复自动履约。
snapshot['auto_creation_policy'] = get_auto_creation_policy() snapshot['auto_creation_policy'] = {
**schema_auto_creation_policy,
'enabled': effective_auto_create_enabled,
'schema_enabled': bool(schema_auto_creation_policy.get('enabled')),
'runtime_binding_enabled': binding_auto_create_enabled,
}
snapshot_hash = _sha256(snapshot) snapshot_hash = _sha256(snapshot)
idempotency_key = _sha256({ idempotency_key = _sha256({
'user_id': user.id, 'user_id': user.id,
@@ -458,7 +470,7 @@ def create_order_extraction_run(
runtime_binding_id=binding.id, runtime_binding_id=binding.id,
provider_agent_id=binding.provider_agent_id, provider_agent_id=binding.provider_agent_id,
quality_batch_id=quality_batch_id, quality_batch_id=quality_batch_id,
provider_config_json=binding_config, provider_config_json={**binding_config, 'auto_create_enabled': effective_auto_create_enabled},
provider_snapshot_json={ provider_snapshot_json={
'provider_agent_id': binding.provider_agent_id, 'provider_agent_id': binding.provider_agent_id,
'runtime_provider': binding.provider_agent.runtime_provider, 'runtime_provider': binding.provider_agent.runtime_provider,
@@ -599,7 +611,9 @@ def reparse_order_extraction_run(
).all() ).all()
for candidate in source_candidates: for candidate in source_candidates:
candidate.selected_before_superseded = bool(candidate.selected) candidate.selected_before_superseded = bool(candidate.selected)
candidate.candidate_status_before_superseded = candidate.candidate_status
candidate.selected = False candidate.selected = False
candidate.candidate_status = 'expired'
candidate.is_current_version = False candidate.is_current_version = False
source.superseded_by_run_id = run.id source.superseded_by_run_id = run.id
source.superseded_at = datetime.utcnow() source.superseded_at = datetime.utcnow()
@@ -1252,6 +1266,8 @@ def _restore_candidates_after_failed_reparse(run: ShippingOrderExtractionRun) ->
candidate.is_current_version = True candidate.is_current_version = True
candidate.selected = bool(candidate.selected_before_superseded) candidate.selected = bool(candidate.selected_before_superseded)
candidate.selected_before_superseded = None candidate.selected_before_superseded = None
candidate.candidate_status = candidate.candidate_status_before_superseded or 'provisional'
candidate.candidate_status_before_superseded = None
source.superseded_by_run_id = None source.superseded_by_run_id = None
source.superseded_at = None source.superseded_at = None
@@ -26,6 +26,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
) )
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract 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.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles 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 from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
@@ -679,6 +680,10 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[
if isinstance(raw, dict) and 'orders' in raw: if isinstance(raw, dict) and 'orders' in raw:
raw = raw['orders'] raw = raw['orders']
continue continue
# Only the documented data wrapper is accepted; do not search arbitrary JSON.
if isinstance(raw, dict) and isinstance(raw.get('data'), dict) and 'orders' in raw['data']:
raw = raw['data']['orders']
continue
if not isinstance(raw, str) or json_decode_count >= 2: if not isinstance(raw, str) or json_decode_count >= 2:
break break
try: try:
@@ -711,6 +716,11 @@ def validate_unit_orders(
} }
evidence_text = frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '') evidence_text = frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '')
for order in orders: for order in orders:
if strict_provider_evidence and any(str(key).startswith('_hxops_') for key in order):
raise ValidationError(
'Workflow order contains reserved HXOPS fields',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
if str(order.get('source_intake_no') or '').strip().upper() != intake_no: if str(order.get('source_intake_no') or '').strip().upper() != intake_no:
raise ValidationError( raise ValidationError(
'Unit order source intake does not match the extraction unit', 'Unit order source intake does not match the extraction unit',
@@ -734,7 +744,19 @@ def validate_unit_orders(
'Unit order contains a field outside the frozen extraction contract', 'Unit order contains a field outside the frozen extraction contract',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
) )
if strict_provider_evidence and any(str(key).startswith('_hxops_') for key in field):
raise ValidationError(
'Workflow field contains reserved HXOPS fields',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
for observation in field.get('observations') or [] if isinstance(field, dict) else []: for observation in field.get('observations') or [] if isinstance(field, dict) else []:
if strict_provider_evidence and isinstance(observation, dict) and any(
str(key).startswith('_hxops_') for key in observation
):
raise ValidationError(
'Workflow observation contains reserved HXOPS fields',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
if not isinstance(observation, dict) or int(observation.get('document_id') or 0) != int(unit.document_id): if not isinstance(observation, dict) or int(observation.get('document_id') or 0) != int(unit.document_id):
raise ValidationError( raise ValidationError(
'Unit observation references another document', 'Unit observation references another document',
@@ -748,7 +770,7 @@ def validate_unit_orders(
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
) )
_validate_locked_layout_fields(document, orders=orders) _validate_locked_layout_fields(document, orders=orders)
return orders return _merge_confirmed_profile_order_fields(run, unit=unit, orders=orders)
def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dict[str, Any]]) -> None: def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dict[str, Any]]) -> None:
@@ -798,6 +820,63 @@ def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dic
) )
def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""注入 confirmed 订单字段并拒绝 Provider 显式冲突;Provider 省略它们是合法的。"""
locked = {
str(item.get('field_id') or ''): item for item in _confirmed_profile_order_fields(run, unit=unit)
if item.get('field_id')
}
if not locked:
return orders
for order in orders:
returned: dict[str, set[str]] = {}
for field in order.get('header_fields') or []:
if not isinstance(field, dict) or str(field.get('field_id') or '') not in locked:
continue
for observation in field.get('observations') or []:
if isinstance(observation, dict):
returned.setdefault(str(field['field_id']), set()).add(
json.dumps(observation.get('value'), ensure_ascii=False, sort_keys=True),
)
expected = {
field_id: {json.dumps(item.get('value'), ensure_ascii=False, sort_keys=True)}
for field_id, item in locked.items()
}
# Missing fields are expected: Dify never receives coordinate template values.
if any(returned.get(field_id, values) != values for field_id, values in expected.items() if field_id in returned):
raise ValidationError(
'Workflow changed a confirmed order field',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
header_fields = order.get('header_fields') if isinstance(order.get('header_fields'), list) else []
by_id = {str(item.get('field_id') or ''): item for item in header_fields if isinstance(item, dict)}
for field_id, candidate in locked.items():
# Replace any agreeing Provider observation with immutable coordinate evidence.
field = by_id.get(field_id)
observation = {
'value': candidate.get('value'), 'document_id': int(unit.document_id),
'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0,
'layout_evidence': {
'page_no': candidate.get('page_no'), 'source': candidate.get('source'),
'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'),
'glyph_indices': list(candidate.get('glyph_indices') or []),
},
}
if field is None:
header_fields.append({
'field_id': field_id, 'observations': [observation],
'_hxops_order_field_evidence': True,
})
else:
field['observations'] = [observation]
field['_hxops_order_field_evidence'] = True
order['header_fields'] = header_fields
# Only HXOPS can set this marker. Provider validation ran before this point;
# it grants coordinate evidence only, never automatic order acceptance.
order['_hxops_order_field_evidence'] = True
return orders
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None: def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
"""仅由盲测批准的唯一 Profile 实测行生成零 Provider 订单;其余交给模型补充。""" """仅由盲测批准的唯一 Profile 实测行生成零 Provider 订单;其余交给模型补充。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -819,10 +898,17 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也回退 Dify/人工。 # 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也回退 Dify/人工。
if len(profile_result.get('tables') or []) != 1 or len(approved_tables) != 1: if len(profile_result.get('tables') or []) != 1 or len(approved_tables) != 1:
return None return None
confirmed_order_fields = _confirmed_profile_order_fields(run, unit=unit)
order = _build_approved_profile_order( order = _build_approved_profile_order(
unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0], unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0],
confirmed_order_fields=confirmed_order_fields,
) )
return [order] if order is not None else None if order is None:
return None
if confirmed_order_fields:
# `_build_approved_profile_order` has already merged and validated these fields.
pass
return [order]
def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2: def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
@@ -831,12 +917,13 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
return OrderCoordinateProfileV2( return OrderCoordinateProfileV2(
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0), 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'), document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
) )
def _build_approved_profile_order( def _build_approved_profile_order(
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any], *, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
table: dict[str, Any], table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
""" """
把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。 把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。
@@ -847,6 +934,7 @@ def _build_approved_profile_order(
schema: Dify 抽取契约元信息。 schema: Dify 抽取契约元信息。
definition: Run 冻结 Schema 完整定义,用于 required/scope 门禁。 definition: Run 冻结 Schema 完整定义,用于 required/scope 门禁。
table: `_profile_table_candidates` 产生且已批准的单个表解析结果。 table: `_profile_table_candidates` 产生且已批准的单个表解析结果。
confirmed_order_fields: 同一冻结模板产生的 confirmed 订单字段,作为独立 Header 证据合并。
Returns: Returns:
完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。 完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。
@@ -889,9 +977,28 @@ def _build_approved_profile_order(
if len(unique) != 1: if len(unique) != 1:
return None return None
header_fields.append({'field_id': field_id, 'observations': [observations[0]]}) header_fields.append({'field_id': field_id, 'observations': [observations[0]]})
present_header = {item['field_id'] for item in header_fields}
for candidate in confirmed_order_fields or []:
field_id = str(candidate.get('field_id') or '')
if not field_id:
continue
if field_id in present_header:
# Header table evidence and independent order-field evidence must never silently compete.
return None
header_fields.append({'field_id': field_id, '_hxops_order_field_evidence': True, 'observations': [{
'value': candidate.get('value'), 'document_id': int(unit.document_id),
'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0,
# Kept only in the internal deterministic result. The Dify manifest strips
# layout payloads and strict Provider validation rejects `_hxops_*` markers.
'layout_evidence': {
'page_no': candidate.get('page_no'), 'source': candidate.get('source'),
'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'),
'glyph_indices': list(candidate.get('glyph_indices') or []),
},
}]})
present_header.add(field_id)
if not line_groups: if not line_groups:
return None return None
present_header = {item['field_id'] for item in header_fields}
for config in fields: for config in fields:
if not config.get('required'): if not config.get('required'):
continue continue
@@ -908,9 +1015,47 @@ def _build_approved_profile_order(
'source_intake_no': str(intake.get('intake_no') or ''), 'source_intake_no': str(intake.get('intake_no') or ''),
'primary_document_id': int(unit.document_id), 'primary_document_id': int(unit.document_id),
'header_fields': header_fields, 'lines': line_groups, 'conflicts': [], 'header_fields': header_fields, 'lines': line_groups, 'conflicts': [],
# Only this frozen approved-profile builder may add this internal marker.
'_hxops_acceptance': 'approved_deterministic_profile_v1',
} }
def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, Any]]:
"""读取唯一匹配 v2 模板的 confirmed 订单字段;无页级证据或歧义时返回空锁集。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
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 {}
schema_fields = {
str(item.get('field_id') or ''): item for item in definition.get('fields') or []
if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'header'
}
profiles = [
item for item in snapshot.get('order_document_profiles') or []
if isinstance(item, dict) and int(item.get('schema_version_id') or 0) == int(run.schema_version_id)
and isinstance(item.get('definition'), dict)
and item['definition'].get('contract_version') == 'order_coordinate_profile.v2'
]
_intake, document = _unit_snapshot(run, unit)
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
if not profiles or layout.get('status') != 'ready':
return []
match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
if match.status != 'unique_match':
return []
raw = next((
item for item in 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
), None)
if raw is None:
return []
candidates = extract_order_fields(
profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields,
coordinate_evidence=layout.get('coordinate_evidence') or {},
)
return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed']
def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]: def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""调用绑定 Provider 的 Workflow,并把网络异常归类为可重试业务错误。""" """调用绑定 Provider 的 Workflow,并把网络异常归类为可重试业务错误。"""
try: try:
@@ -36,6 +36,9 @@ def referenced_field_ids(profile_definition: dict[str, Any] | None) -> set[str]:
for target in field.get('target_fields') or []: for target in field.get('target_fields') or []:
if isinstance(target, dict) and target.get('field_id'): if isinstance(target, dict) and target.get('field_id'):
result.add(str(target['field_id'])) result.add(str(target['field_id']))
for field in (profile_definition or {}).get('order_field_layouts') or []:
if isinstance(field, dict) and field.get('field_id'):
result.add(str(field['field_id']))
return result return result
@@ -191,4 +194,10 @@ def remap_profile_field_codes(
values = layout.get(key) values = layout.get(key)
if isinstance(values, list): if isinstance(values, list):
layout[key] = [code_map.get(str(code), code) for code in values] layout[key] = [code_map.get(str(code), code) for code in values]
for field in result.get('order_field_layouts') or []:
if not isinstance(field, dict):
continue
target_field = target.get(str(field.get('field_id') or ''))
if target_field:
field['field_code'] = target_field.get('field_code')
return result return result
@@ -14,6 +14,7 @@ from typing import Any
_SCALAR_KEYS = ( _SCALAR_KEYS = (
'field_code', 'scope', 'value_type', 'field_category', 'collection_mode', 'enabled', 'field_code', 'scope', 'value_type', 'field_category', 'collection_mode', 'enabled',
'display_name', 'description', 'business_purpose', 'required', 'normalizer_key', 'display_name', 'description', 'business_purpose', 'required', 'normalizer_key',
'auto_annotation_enabled',
'relation_role', 'comparator_key', 'extraction_instruction', 'context_source', 'relation_role', 'comparator_key', 'extraction_instruction', 'context_source',
'sensitivity_level', 'dify_exposure_policy', 'available_for_customer_identity', 'sequence', 'sensitivity_level', 'dify_exposure_policy', 'available_for_customer_identity', 'sequence',
) )
@@ -8,7 +8,7 @@ backend/app/services/shipping_notice/order_schema/field_rules.py
from __future__ import annotations from __future__ import annotations
from datetime import date from datetime import date, datetime
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
from typing import Any from typing import Any
@@ -28,8 +28,16 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
if value_type == 'integer': if value_type == 'integer':
return int(str(value).replace(',', '').strip()) return int(str(value).replace(',', '').strip())
if value_type == 'date': if value_type == 'date':
text = str(value).strip().replace('/', '-').replace('.', '-') text = str(value).strip()
return date.fromisoformat(text) # Purchase orders commonly print US-style dates (for example
# ``06/20/2026``). Accept only explicit, deterministic layouts so
# we restore coordinate candidates without treating free text as a date.
for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', '%Y%m%d', '%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'):
try:
return datetime.strptime(text, pattern).date()
except ValueError:
continue
raise ValueError('invalid date')
if value_type == 'boolean': if value_type == 'boolean':
if isinstance(value, bool): if isinstance(value, bool):
return value return value
@@ -178,6 +178,15 @@ def _verified_observations(
quote = str(item.get('quote') or '').strip() quote = str(item.get('quote') or '').strip()
if document is None or value is None or not _validate(value, config): if document is None or value is None or not _validate(value, config):
continue continue
layout_evidence = item.get('layout_evidence') if raw.get('_hxops_order_field_evidence') is True else None
if isinstance(layout_evidence, dict) and _valid_coordinate_evidence(layout_evidence):
verified.append({
'value': value, 'document': document, 'quote': quote or str(value), 'confidence': 1.0,
'source_type': 'attachment_coordinate', 'extractor': 'order_profile_order_field',
'evidence_ref': f"document:{int(document.id)}:order-field:{config['field_id']}:page:{int(layout_evidence['page_no'])}",
'evidence_metadata': {'kind': 'order_field_coordinate', **layout_evidence},
})
continue
frozen_text = str((frozen_evidence_text_by_document or {}).get(int(document.id)) or '') frozen_text = str((frozen_evidence_text_by_document or {}).get(int(document.id)) or '')
source_texts = [frozen_text, str(document.extracted_text or '')] source_texts = [frozen_text, str(document.extracted_text or '')]
if not quote or not any(quote in text for text in source_texts if text): if not quote or not any(quote in text for text in source_texts if text):
@@ -203,6 +212,16 @@ def _verified_observations(
return verified return verified
def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool:
"""只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。"""
return (
str(raw.get('source') or '') == 'pdf_coordinate'
and isinstance(raw.get('page_no'), int) and raw['page_no'] >= 1
and isinstance(raw.get('anchor_bbox'), dict) and isinstance(raw.get('value_bbox'), dict)
and isinstance(raw.get('glyph_indices'), list) and bool(raw['glyph_indices'])
)
def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]: def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]:
"""按一致性、来源优先级和冲突策略选择字段值。""" """按一致性、来源优先级和冲突策略选择字段值。"""
if not observations: if not observations:
@@ -1124,6 +1124,13 @@ def _coordinate_sources(value: Any) -> list[str]:
return sources return sources
def _default_auto_annotation_enabled(raw: dict[str, Any]) -> bool:
"""仅让必填或建单关键字段默认参与画布自动标记,避免可选字段淹没候选。"""
return bool(raw.get('required')) or bool(raw.get('auto_create_key_field')) or (
str(raw.get('business_purpose') or 'general') != 'general'
)
def save_draft( def save_draft(
version_id: int, data: dict[str, Any], *, actor_id: int | None = None, version_id: int, data: dict[str, Any], *, actor_id: int | None = None,
request_id: str | None = None, request_id: str | None = None,
@@ -1170,9 +1177,10 @@ def save_draft(
validators = _string_list(raw.get('validator_keys', []), field='validator_keys') validators = _string_list(raw.get('validator_keys', []), field='validator_keys')
aliases = _string_list(raw.get('aliases', []), field='aliases') aliases = _string_list(raw.get('aliases', []), field='aliases')
enum_options = _string_list(raw.get('enum_options', []), field='enum_options') enum_options = _string_list(raw.get('enum_options', []), field='enum_options')
auto_annotation_enabled = raw.get('auto_annotation_enabled', _default_auto_annotation_enabled(raw))
relation_role = str(raw.get('relation_role') or '').strip() or None relation_role = str(raw.get('relation_role') or '').strip() or None
required = raw.get('required', False) required = raw.get('required', False)
if not isinstance(enabled, bool) or not isinstance(required, bool): if not isinstance(enabled, bool) or not isinstance(required, bool) or not isinstance(auto_annotation_enabled, bool):
raise ValidationError('required must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') raise ValidationError('required must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if not display_name or normalizer not in NORMALIZERS or comparator not in COMPARATORS: if not display_name or normalizer not in NORMALIZERS or comparator not in COMPARATORS:
raise ValidationError('field display or transformation config is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') raise ValidationError('field display or transformation config is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
@@ -1234,6 +1242,7 @@ def save_draft(
'minimum_confidence': round(minimum_confidence, 2) if minimum_confidence is not None else None, 'minimum_confidence': round(minimum_confidence, 2) if minimum_confidence is not None else None,
'required': required, 'required': required,
'aliases': aliases, 'aliases': aliases,
'auto_annotation_enabled': auto_annotation_enabled,
'normalizer_key': normalizer, 'normalizer_key': normalizer,
'validator_keys': validators, 'validator_keys': validators,
'enum_options': enum_options, 'enum_options': enum_options,
@@ -145,6 +145,7 @@ def record_inventory_verification(
db.session.add(verification) db.session.add(verification)
db.session.flush() db.session.flush()
available_count = 0 available_count = 0
seen_reservation_ids: set[str] = set()
for item in line_results: for item in line_results:
reservation_id = validated_reservation_id(item.get('reservation_id')) reservation_id = validated_reservation_id(item.get('reservation_id'))
part_number = str(item.get('part_number') or '').strip() part_number = str(item.get('part_number') or '').strip()
@@ -152,6 +153,11 @@ def record_inventory_verification(
if reservation is None or reservation.part_number != part_number: if reservation is None or reservation.part_number != part_number:
raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH') raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
required = _decimal(item.get('required_qty')) required = _decimal(item.get('required_qty'))
# The frozen order is the quantity authority. A reduced or duplicate result
# must not turn an insufficient reservation into an exportable line.
if reservation_id in seen_reservation_ids or required != reservation.required_qty:
raise ValidationError('Inventory result quantity is inconsistent with the frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
seen_reservation_ids.add(reservation_id)
available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0') available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0')
status = 'available' if available >= required else 'shortage' status = 'available' if available >= required else 'shortage'
db.session.add(ShippingInventoryVerificationLine( db.session.add(ShippingInventoryVerificationLine(
@@ -36,6 +36,7 @@ from app.services.shipping_notice.constants import (
CP_UPLOADED, CP_UPLOADED,
CP_COMPLETED, CP_COMPLETED,
CP_UPLOAD_FAILED, CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_UPLOAD_REQ, CP_UPLOAD_REQ,
CP_WAITING_UPLOAD, CP_WAITING_UPLOAD,
PH_INV_UNAVAIL, PH_INV_UNAVAIL,
@@ -48,6 +49,7 @@ from app.services.shipping_notice.constants import (
PH_SHORTAGE, PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED, PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING, PH_UPLOAD_RPA_PENDING,
PH_UPLOAD_RESULT_UNKNOWN,
RS_CONFIRMED, RS_CONFIRMED,
RS_PARSE_REVIEW, RS_PARSE_REVIEW,
RS_REJECTED, RS_REJECTED,
@@ -121,6 +123,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"), CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"), CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"), CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
CP_UPLOAD_RESULT_UNKNOWN: ("refresh", "download_excel", "mark_manual_uploaded"),
CP_READY_MATCH: ("match_inventory",), CP_READY_MATCH: ("match_inventory",),
CP_READY_EXPORT: ("generate_excel",), CP_READY_EXPORT: ("generate_excel",),
CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"), CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"),
@@ -355,6 +358,11 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
checkpoint=CP_UPLOAD_FAILED, checkpoint=CP_UPLOAD_FAILED,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]), human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
) )
if reason == PH_UPLOAD_RESULT_UNKNOWN:
return TaskUiState(
checkpoint=CP_UPLOAD_RESULT_UNKNOWN,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
)
if reason == PH_RPA_PENDING or ( if reason == PH_RPA_PENDING or (
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
): ):
@@ -15,7 +15,7 @@ from typing import Any
from app.models import ShippingNoticeCandidate, ShippingTask from app.models import ShippingNoticeCandidate, ShippingTask
from app.services.shipping_notice.constants import PH_RSV_REQ from app.services.shipping_notice.constants import PH_RSV_REQ
from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues from app.services.shipping_notice.reservation_gate import reservation_gate_issues, task_reservation_gate_issues
from app.services.shipping_notice.reservation_id import ( from app.services.shipping_notice.reservation_id import (
is_valid_reservation_id, is_valid_reservation_id,
validated_reservation_id, validated_reservation_id,
@@ -41,6 +41,13 @@ RECONCILE_FIELDS: tuple[str, ...] = (
) )
def _reconciliation_reservation_issues(task: ShippingTask) -> list[dict[str, Any]]:
"""回填旧任务时以当前已接受订单字段投影状态;下游履约仍强制冻结 Snapshot。"""
if task.order_snapshot_id:
return task_reservation_gate_issues(task)
return reservation_gate_issues(current_line_field_values(task))
def _normalized_qty(value: Any) -> str: def _normalized_qty(value: Any) -> str:
"""数量稳定比较值。""" """数量稳定比较值。"""
try: try:
@@ -307,7 +314,7 @@ def apply_candidate_reconciliation_plan(
], ],
) )
open_rows = list_open_field_conflicts(task) open_rows = list_open_field_conflicts(task)
issues = task_reservation_gate_issues(task) issues = _reconciliation_reservation_issues(task)
step_payload = dict(task.step_payload_json or {}) step_payload = dict(task.step_payload_json or {})
step_payload['parse_validation'] = { step_payload['parse_validation'] = {
'status': 'needs_review', 'status': 'needs_review',
@@ -345,7 +352,7 @@ def apply_candidate_reconciliation_plan(
'updated_line_indexes': [], 'updated_line_indexes': [],
} }
issues = task_reservation_gate_issues(task) issues = _reconciliation_reservation_issues(task)
open_rows = list_open_field_conflicts(task) open_rows = list_open_field_conflicts(task)
step_payload = dict(task.step_payload_json or {}) step_payload = dict(task.step_payload_json or {})
step_payload['parse_validation'] = { step_payload['parse_validation'] = {
@@ -77,7 +77,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]:
"""按当前字段目录顺序展示锁定 Schema 字段,历史缺失字段回退版本 sequence。""" """按当前字段目录顺序展示锁定 Schema 字段,历史缺失字段回退版本 sequence。"""
extraction = _current_extraction(task) extraction = _current_extraction(task)
global_sequences = { global_sequences = {
field.id: int(field.display_sequence or 0) str(field.field_code): int(field.display_sequence or 0)
for field in ShippingOrderField.query.filter_by(schema_id=extraction.schema_version.schema_id).all() for field in ShippingOrderField.query.filter_by(schema_id=extraction.schema_version.schema_id).all()
} }
fields = sorted( fields = sorted(
@@ -86,7 +86,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]:
if item.get('enabled', True) if item.get('enabled', True)
], ],
key=lambda item: ( key=lambda item: (
global_sequences.get(str(item.get('field_id')), 1_000_000 + int(item.get('sequence') or 0)), global_sequences.get(str(item.get('field_code')), 1_000_000 + int(item.get('sequence') or 0)),
int(item.get('sequence') or 0), int(item.get('sequence') or 0),
str(item.get('field_code') or ''), str(item.get('field_code') or ''),
), ),
@@ -26,6 +26,7 @@ from app.services.shipping_notice.constants import (
CP_RSV_REQ, CP_RSV_REQ,
CP_UPLOADED, CP_UPLOADED,
CP_UPLOAD_FAILED, CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_UPLOAD_REQ, CP_UPLOAD_REQ,
CP_WAITING_UPLOAD, CP_WAITING_UPLOAD,
PH_INV_UNAVAIL, PH_INV_UNAVAIL,
@@ -88,6 +89,7 @@ _BLOCKED_CHECKPOINTS = {
CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_REQ, CP_UPLOAD_REQ,
CP_UPLOAD_FAILED, CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
} }
@@ -50,9 +50,13 @@ def start_rpa_attempt(task: ShippingTask, *, artifact_id: int | None = None, ide
if existing is not None: if existing is not None:
if existing.artifact_id != artifact.id: if existing.artifact_id != artifact.id:
raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT') raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT')
if existing.status == 'timed_out':
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
return existing return existing
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first(): if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED') raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='timed_out').first():
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1) attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1)
attempt = ShippingUploadAttempt( attempt = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key, artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key,
@@ -96,7 +100,7 @@ def complete_attempt(
raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED') raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED')
if attempt.status == 'succeeded' or artifact.status == 'uploaded': if attempt.status == 'succeeded' or artifact.status == 'uploaded':
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE') raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running'}: if attempt.status not in {'pending', 'running', 'timed_out'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE') raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
attempt.callback_id = callback attempt.callback_id = callback
attempt.finished_at = datetime.utcnow() attempt.finished_at = datetime.utcnow()
@@ -115,6 +119,13 @@ def complete_attempt(
task.freight_ref_no = attempt.freight_ref_no task.freight_ref_no = attempt.freight_ref_no
_aggregate_task_upload_status(task) _aggregate_task_upload_status(task)
else: else:
# A missing callback may conceal a completed freight submission. A late
# transport error is not enough to safely release or retry that Artifact.
if attempt.status == 'timed_out' and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
db.session.flush()
return attempt
attempt.status = 'failed' attempt.status = 'failed'
message = str(error_message or 'RPA upload failed')[:500] message = str(error_message or 'RPA upload failed')[:500]
attempt.error_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED' attempt.error_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED'
@@ -126,6 +137,18 @@ def complete_attempt(
return attempt return attempt
def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploadAttempt:
"""超时后冻结 Artifact;仅迟到成功回调或货代明确拒绝才能解除未知结果。"""
if attempt.status != 'running':
return attempt
attempt.status = 'timed_out'
attempt.finished_at = datetime.utcnow()
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = 'RPA callback timed out; freight submission must be reconciled before retry'
db.session.flush()
return attempt
def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt: def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt:
"""登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。""" """登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。"""
asset_no = str(evidence_asset_no or '').strip() asset_no = str(evidence_asset_no or '').strip()
@@ -0,0 +1,71 @@
"""add shipping candidate acceptance lifecycle
Revision ID: 029f0a1b2c3d
Revises: 028e9f0a1b2c
Create Date: 2026-07-27 10:00:00.000000
用途:将 Candidate 的人工选择投影与是否可履约的接受状态分离。
依赖:shipping_notice_candidates、shipping_tasks、users。
逻辑:已消费候选可安全回填 accepted;未消费历史候选一律回填 provisional,避免历史
selected 标记绕过新的接受门禁。
"""
from alembic import op
import sqlalchemy as sa
revision = '029f0a1b2c3d'
down_revision = '028e9f0a1b2c'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增接受生命周期字段并以保守规则回填历史数据。"""
with op.batch_alter_table('shipping_notice_candidates') as batch:
batch.add_column(sa.Column('candidate_status', sa.String(length=32), server_default='provisional', nullable=False))
batch.add_column(sa.Column('candidate_status_before_superseded', sa.String(length=32), nullable=True))
batch.add_column(sa.Column('acceptance_mode', sa.String(length=32), nullable=True))
batch.add_column(sa.Column('accepted_at', sa.DateTime(), nullable=True))
batch.add_column(sa.Column('accepted_by_id', sa.Integer(), nullable=True))
batch.add_column(sa.Column('acceptance_reason', sa.Text(), nullable=True))
batch.add_column(sa.Column('acceptance_policy_version', sa.String(length=64), nullable=True))
batch.create_check_constraint(
'ck_shipping_notice_candidates_status',
"candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')",
)
batch.create_check_constraint(
'ck_shipping_notice_candidates_acceptance_mode',
"acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')",
)
batch.create_foreign_key(
'fk_shipping_notice_candidates_accepted_by_id', 'users', ['accepted_by_id'], ['id'],
)
batch.create_index(
'ix_shipping_notice_candidates_fulfillment_gate', ['candidate_status', 'is_current_version'],
)
batch.alter_column('selected', server_default=sa.text('false'))
# A consumed Candidate has an existing Task and is the only historical state that proves acceptance.
op.execute(
"UPDATE shipping_notice_candidates "
"SET candidate_status = 'accepted', acceptance_mode = 'legacy' "
"WHERE consumed_task_id IS NOT NULL"
)
def downgrade() -> None:
"""移除生命周期字段;旧 selected 投影保持原值以支持回滚。"""
with op.batch_alter_table('shipping_notice_candidates') as batch:
batch.alter_column('selected', server_default=sa.text('true'))
batch.drop_index('ix_shipping_notice_candidates_fulfillment_gate')
batch.drop_constraint('ck_shipping_notice_candidates_acceptance_mode', type_='check')
batch.drop_constraint('ck_shipping_notice_candidates_status', type_='check')
batch.drop_constraint('fk_shipping_notice_candidates_accepted_by_id', type_='foreignkey')
batch.drop_column('acceptance_policy_version')
batch.drop_column('acceptance_reason')
batch.drop_column('accepted_by_id')
batch.drop_column('accepted_at')
batch.drop_column('acceptance_mode')
batch.drop_column('candidate_status_before_superseded')
batch.drop_column('candidate_status')
@@ -0,0 +1,31 @@
"""add order field blind test truth
Revision ID: 02af0b1c2d3e
Revises: 029f0a1b2c3d
Create Date: 2026-07-27 11:10:00.000000
用途:为订单文档模板盲测保存订单级字段的人工真值。
依赖:shipping_document_profile_test_samples。
逻辑:历史样本默认空对象,只有配置订单字段的新模板在服务层要求完整真值,避免旧模板迁移后失效。
"""
from alembic import op
import sqlalchemy as sa
revision = '02af0b1c2d3e'
down_revision = '029f0a1b2c3d'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增订单字段盲测真值列,并为历史明细模板安全回填空对象。"""
with op.batch_alter_table('shipping_document_profile_test_samples') as batch:
batch.add_column(sa.Column('expected_order_fields_json', sa.JSON(), nullable=False, server_default=sa.text("'{}'")))
def downgrade() -> None:
"""删除订单字段盲测真值列,回退到仅校验明细行的历史契约。"""
with op.batch_alter_table('shipping_document_profile_test_samples') as batch:
batch.drop_column('expected_order_fields_json')
@@ -0,0 +1,67 @@
"""backfill order schema auto annotation
Revision ID: 03bf1c2d3e4f
Revises: 02af0b1c2d3e
Create Date: 2026-07-27 12:20:00.000000
用途:为已存在的订单 Schema 字段规则补齐自动标记开关。
依赖:shipping_order_schema_versions.definition_json。
逻辑:历史字段默认参与自动标记,保持其先前的别名和坐标来源行为;管理员可在后续草稿中逐字段关闭。
"""
from __future__ import annotations
import copy
from alembic import op
import sqlalchemy as sa
revision = '03bf1c2d3e4f'
down_revision = '02af0b1c2d3e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""为现有版本 JSON 的每个字段写入兼容默认值,不改变其他配置。"""
bind = op.get_bind()
versions = sa.table(
'shipping_order_schema_versions',
sa.column('id', sa.Integer),
sa.column('definition_json', sa.JSON),
)
for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings():
definition = copy.deepcopy(row['definition_json'] or {})
fields = definition.get('fields') if isinstance(definition.get('fields'), list) else []
changed = False
for field in fields:
if isinstance(field, dict) and 'auto_annotation_enabled' not in field:
field['auto_annotation_enabled'] = True
changed = True
if changed:
bind.execute(
versions.update().where(versions.c.id == row['id']).values(definition_json=definition),
)
def downgrade() -> None:
"""移除回填键;运行时代码仍对缺失键按 True 兼容。"""
bind = op.get_bind()
versions = sa.table(
'shipping_order_schema_versions',
sa.column('id', sa.Integer),
sa.column('definition_json', sa.JSON),
)
for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings():
definition = copy.deepcopy(row['definition_json'] or {})
fields = definition.get('fields') if isinstance(definition.get('fields'), list) else []
changed = False
for field in fields:
if isinstance(field, dict) and 'auto_annotation_enabled' in field:
field.pop('auto_annotation_enabled')
changed = True
if changed:
bind.execute(
versions.update().where(versions.c.id == row['id']).values(definition_json=definition),
)
@@ -0,0 +1,76 @@
"""limit order schema auto annotation
Revision ID: 04cf1d2e3f4a
Revises: 03bf1c2d3e4f
Create Date: 2026-07-27 12:30:00.000000
用途:将历史 Schema 的自动标记范围收敛为关键字段。
依赖:shipping_order_schema_versions.definition_json。
逻辑:仅保留业务必填、自动建单关键或具名业务用途字段,避免可选字段在模板画布产生大量无关候选。
"""
from __future__ import annotations
import copy
from alembic import op
import sqlalchemy as sa
revision = '04cf1d2e3f4a'
down_revision = '03bf1c2d3e4f'
branch_labels = None
depends_on = None
def _is_key_field(field: dict) -> bool:
"""保持与 Schema 保存默认值一致的关键字段判定,迁移不靠字段编码硬编码。"""
return bool(field.get('required')) or bool(field.get('auto_create_key_field')) or (
str(field.get('business_purpose') or 'general') != 'general'
)
def upgrade() -> None:
"""将当前环境历史版本收敛为关键字段白名单,不改变字段语义或坐标来源。"""
bind = op.get_bind()
versions = sa.table(
'shipping_order_schema_versions',
sa.column('id', sa.Integer),
sa.column('definition_json', sa.JSON),
)
for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings():
definition = copy.deepcopy(row['definition_json'] or {})
fields = definition.get('fields') if isinstance(definition.get('fields'), list) else []
changed = False
for field in fields:
if isinstance(field, dict):
enabled = _is_key_field(field)
if field.get('auto_annotation_enabled') != enabled:
field['auto_annotation_enabled'] = enabled
changed = True
if changed:
bind.execute(
versions.update().where(versions.c.id == row['id']).values(definition_json=definition),
)
def downgrade() -> None:
"""回退为上一个迁移的兼容全开状态,不改变其他字段配置。"""
bind = op.get_bind()
versions = sa.table(
'shipping_order_schema_versions',
sa.column('id', sa.Integer),
sa.column('definition_json', sa.JSON),
)
for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings():
definition = copy.deepcopy(row['definition_json'] or {})
fields = definition.get('fields') if isinstance(definition.get('fields'), list) else []
changed = False
for field in fields:
if isinstance(field, dict) and field.get('auto_annotation_enabled') is not True:
field['auto_annotation_enabled'] = True
changed = True
if changed:
bind.execute(
versions.update().where(versions.c.id == row['id']).values(definition_json=definition),
)
@@ -0,0 +1,35 @@
"""version blind test suites by profile checksum
Revision ID: 05df1e2f3a4b
Revises: 04cf1d2e3f4a
Create Date: 2026-07-27 19:15:00.000000
用途:允许同一订单模板在定义变更后保留旧盲测审计,并为新 checksum 建立新盲测集。
依赖:shipping_document_profile_test_suites。
逻辑:旧的 profile 单列唯一约束会阻止新草稿盲测;迁移改为 profile/checksum 联合唯一。
"""
from alembic import op
revision = '05df1e2f3a4b'
down_revision = '04cf1d2e3f4a'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""将盲测集唯一性由 Profile 维度扩展到 Profile checksum 维度。"""
with op.batch_alter_table('shipping_document_profile_test_suites') as batch:
batch.drop_constraint('uq_shipping_document_profile_test_suites_profile', type_='unique')
batch.create_unique_constraint(
'uq_shipping_document_profile_test_suites_profile_checksum',
['profile_id', 'profile_checksum'],
)
def downgrade() -> None:
"""回退为每个 Profile 仅一个盲测集的历史约束。"""
with op.batch_alter_table('shipping_document_profile_test_suites') as batch:
batch.drop_constraint('uq_shipping_document_profile_test_suites_profile_checksum', type_='unique')
batch.create_unique_constraint('uq_shipping_document_profile_test_suites_profile', ['profile_id'])
@@ -3,7 +3,7 @@ backend/tests/test_shipping_document_profile_quality.py
用途:验证订单文档模板的独立盲测、批准资格和冻结 checksum 门禁。 用途:验证订单文档模板的独立盲测、批准资格和冻结 checksum 门禁。
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。 依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
逻辑:管理员固化三份独立样本真值;全部通过且批准后才可放行确定性自动建单。 逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。
""" """
from __future__ import annotations from __future__ import annotations
@@ -111,17 +111,12 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
return profile, user, documents return profile, user, documents
def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(app): def test_profile_auto_create_requires_one_passing_blind_sample_and_approval(app):
"""关键断言:三样本全通过和管理员批准缺一不可,批准后样本不可篡改。""" """关键断言:一份独立样本通过并经批准后才能放行,批准后样本不可篡改。"""
with app.app_context(): with app.app_context():
profile, user, documents = _published_profile_with_samples() profile, user, documents = _published_profile_with_samples()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
for document in documents[:2]:
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,
)
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id) executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'failed' assert executed['latest_run']['status'] == 'failed'
with pytest.raises(Exception) as caught: with pytest.raises(Exception) as caught:
@@ -129,10 +124,11 @@ def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(a
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY' assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
quality.add_sample( quality.add_sample(
suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', 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, expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
) )
quality.execute_suite(suite_id=suite['id'], actor_id=user.id) executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'passed'
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id) approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert approved['status'] == 'approved' assert approved['status'] == 'approved'
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
@@ -144,6 +140,43 @@ 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' assert getattr(immutable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
def test_independent_sample_review_reuses_existing_truth_and_excludes_training_input(app):
"""关键断言:只展示同类未建模样本,逐项确认后才将候选写为既有盲测真值。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
# 仅专用模板样本可供日常盲测选择;训练文档必须始终被排除。
for document in documents:
db.session.get(ShippingNoticeIntake, document.intake_id).purpose = 'order_document_profile_sample'
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)
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
assert {item['document_id'] for item in available} == {documents[1].id, documents[2].id}
candidate = quality.preview_independent_sample(
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', actor_id=user.id,
)
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': 3}]
with pytest.raises(Exception) as incomplete:
quality.confirm_sample_reviews(
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1',
row_reviews=[{'correct': None, 'values': candidate['rows'][0]}],
order_field_reviews={}, actor_id=user.id,
)
assert getattr(incomplete.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
confirmed = quality.confirm_sample_reviews(
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1',
row_reviews=[{'correct': True, 'values': {}}], order_field_reviews={}, actor_id=user.id,
)
assert confirmed['sample_count'] == 1
sample = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0]
assert sample.expected_rows_json == candidate['rows']
def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app): def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app):
"""v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。""" """v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。"""
with app.app_context(): with app.app_context():
@@ -178,6 +211,44 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes'] assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
def test_coordinate_blind_preview_skips_header_only_regions(app):
"""关键断言:仅含订单字段的页不重建物理行,候选预览不会因空布局报 500。"""
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', 'page_scope': 'exact_page', 'page_no': 1,
'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': 'part-id', 'field_code': 'part_number',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'allowed_sources': ['pdf_coordinate']}],
}]},
{'region_id': 'header_only', 'page_scope': 'exact_page', 'page_no': 2,
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'header_layouts': [{'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}, 'field_regions': []}],
'line_layouts': []},
],
}
for document in documents:
glyphs = [
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 20, 'x1': 23 + index * 4, 'y1': 30}}
for index, char in enumerate('PN-1')
]
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)
candidate = quality._candidate_for_sample(profile=profile, document_id=documents[0].id, table_id='table-1')
assert suite['id'] > 0
assert candidate['rows'] == []
def test_profile_checksum_change_invalidates_approved_quality_credential(app): def test_profile_checksum_change_invalidates_approved_quality_credential(app):
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。""" """关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
with app.app_context(): with app.app_context():
@@ -195,6 +266,21 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
def test_profile_change_supersedes_stale_draft_suite_and_creates_current_suite(app):
"""保存模板后必须建立新 checksum 的盲测集,旧草稿真值不得继续阻断或背书。"""
with app.app_context():
profile, user, _documents = _published_profile_with_samples()
stale = quality.create_suite(profile_id=profile.id, actor_id=user.id)
profile.checksum = 'd' * 64
db.session.commit()
current = quality.create_suite(profile_id=profile.id, actor_id=user.id)
assert current['id'] != stale['id']
assert current['profile_checksum'] == 'd' * 64
stale_suite = db.session.get(ShippingDocumentProfileTestSuite, stale['id'])
assert stale_suite.status == 'superseded'
def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(app): def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(app):
"""盲测草稿可受控删除样本并留痕,批准后的真值不得再被篡改。""" """盲测草稿可受控删除样本并留痕,批准后的真值不得再被篡改。"""
with app.app_context(): with app.app_context():
@@ -205,8 +291,15 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id, expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
) )
sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
serialized = quality.serialize_suite(db.session.get(ShippingDocumentProfileTestSuite, suite['id']))
# 关键断言:工作台只得到移除定位信息,绝不返回人工确认的字段真值。
assert serialized['samples'] == [{
'id': sample_id, 'document_id': documents[0].id, 'table_id': 'table-1',
'filename': 'q0.pdf', 'page_no': 1,
}]
removed = quality.remove_sample(suite_id=suite['id'], sample_id=sample_id, actor_id=user.id) removed = quality.remove_sample(suite_id=suite['id'], sample_id=sample_id, actor_id=user.id)
assert removed['sample_count'] == 0 assert removed['sample_count'] == 0
assert removed['samples'] == []
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by( audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
ShippingOrderDocumentProfileAudit.id.desc(), ShippingOrderDocumentProfileAudit.id.desc(),
).first() ).first()
@@ -244,7 +337,7 @@ def test_draft_publish_requires_independent_training_and_multiline_blind_gate(ap
assert getattr(missing_suite.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST' 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) 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. # One independent sample is enough, but it must still be genuine multi-line evidence.
record_inline_layout_snapshot(documents[1], { record_inline_layout_snapshot(documents[1], {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', '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>'}], '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>'}],
@@ -252,28 +345,9 @@ def test_draft_publish_requires_independent_training_and_multiline_blind_gate(ap
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[ 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}, {'part_number': 'PN-1', 'qty': 3}, {'part_number': 'PN-2', 'qty': 4},
], actor_id=user.id) ], 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) executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes'] assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
quality.approve_suite(suite_id=suite['id'], actor_id=user.id) 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) assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.structure_fingerprint)
@@ -78,6 +78,55 @@ def test_candidate_content_fingerprint_migration_upgrade_and_downgrade():
migration.op = original_op migration.op = original_op
def test_candidate_acceptance_lifecycle_migration_is_conservative_and_reversible():
"""迁移只自动接受已消费记录,未消费 legacy selected 记录必须保持 provisional。"""
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_notice_candidates', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('selected', sa.Boolean(), nullable=False, server_default=sa.text('true')),
sa.Column('is_current_version', sa.Boolean(), nullable=False, server_default=sa.text('true')),
sa.Column('consumed_task_id', sa.Integer(), nullable=True),
)
metadata.create_all(engine)
migration = importlib.import_module(
'migrations.versions.029f0a1b2c3d_add_shipping_candidate_acceptance_lifecycle'
)
with engine.begin() as connection:
connection.execute(sa.text(
"INSERT INTO shipping_notice_candidates (id, selected, is_current_version, consumed_task_id) "
"VALUES (1, 1, 1, NULL), (2, 1, 1, 99)"
))
operations = Operations(MigrationContext.configure(connection))
original_op = migration.op
migration.op = operations
try:
migration.upgrade()
inspector = sa.inspect(connection)
columns = {column['name'] for column in inspector.get_columns('shipping_notice_candidates')}
assert {
'candidate_status', 'candidate_status_before_superseded', 'acceptance_mode',
'accepted_at', 'accepted_by_id', 'acceptance_reason', 'acceptance_policy_version',
} <= columns
statuses = connection.execute(sa.text(
'SELECT id, candidate_status, acceptance_mode FROM shipping_notice_candidates ORDER BY id'
)).all()
assert statuses == [(1, 'provisional', None), (2, 'accepted', 'legacy')]
assert 'ix_shipping_notice_candidates_fulfillment_gate' in {
index['name'] for index in inspector.get_indexes('shipping_notice_candidates')
}
migration.downgrade()
columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_notice_candidates')}
assert 'candidate_status' not in columns
assert 'acceptance_mode' not in columns
finally:
migration.op = original_op
def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None: def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None:
"""创建 e0f1 迁移所需的 d9 版本最小表结构与旧唯一约束。""" """创建 e0f1 迁移所需的 d9 版本最小表结构与旧唯一约束。"""
metadata = sa.MetaData() metadata = sa.MetaData()
@@ -117,6 +117,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
}, },
validation_status='needs_review', validation_status='needs_review',
conflicts_json=[{'field': 'qty'}], conflicts_json=[{'field': 'qty'}],
extraction_source='dify_workflow',
selected=True, selected=True,
duplicate_resolution='open_existing', duplicate_resolution='open_existing',
duplicate_target_task_no=existing.task_no, duplicate_target_task_no=existing.task_no,
@@ -143,10 +144,40 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
patched = patch_response.get_json()['data'] patched = patch_response.get_json()['data']
assert patched['selected'] is False assert patched['selected'] is False
assert patched['validation_status'] == 'ready' assert patched['validation_status'] == 'ready'
# 模拟重复任务在审核完成前被关闭,采纳必须重新通过实时重复门禁。
with app.app_context():
existing = ShippingTask.query.filter_by(task_no='SN-CANDIDATE-EXISTING-001').one()
db.session.delete(existing)
db.session.commit()
promote_response = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote',
headers=owner_headers,
)
assert promote_response.status_code == 200
promoted = promote_response.get_json()['data']
assert promoted['candidate_status'] == 'accepted'
assert promoted['acceptance_mode'] == 'manual'
assert promoted['selected'] is True
repeated = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote',
headers=owner_headers,
)
assert repeated.status_code == 200
assert repeated.get_json()['data']['candidate_status'] == 'accepted'
assert patched['conflicts'] == [] assert patched['conflicts'] == []
assert patched['content_fingerprint'] assert patched['content_fingerprint']
assert patched['duplicate_resolution'] is None assert patched['duplicate_resolution'] is None
with app.app_context():
db.session.add(ShippingTask(
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
source_content_hash='candidate-api-content-hash', process_status='created',
))
db.session.commit()
forbidden = client.patch( forbidden = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001', '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={'selected': True}, json={'selected': True},
@@ -349,6 +380,7 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app
validation_status='ready', validation_status='ready',
conflicts_json=[], conflicts_json=[],
selected=True, selected=True,
candidate_status='accepted',
duplicate_status='none', duplicate_status='none',
) )
db.session.add(candidate) db.session.add(candidate)
@@ -402,6 +434,25 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app
assert none_selected.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED' assert none_selected.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED'
def test_candidate_batch_gate_requires_accepted_lifecycle(app, shipping_user):
"""provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。"""
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
with app.app_context():
candidate = ShippingNoticeCandidate(
candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate',
intake_id=1, primary_document_id=1, selected=True,
candidate_status='provisional', is_current_version=True,
validation_status='ready', conflicts_json=[],
)
with pytest.raises(ConflictError) as provisional:
ensure_candidate_fulfillment_ready(candidate)
assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED'
candidate.candidate_status = 'accepted'
ensure_candidate_fulfillment_ready(candidate)
def test_candidate_era_intake_without_candidates_cannot_fallback_to_single_eml_task(app, shipping_user): def test_candidate_era_intake_without_candidates_cannot_fallback_to_single_eml_task(app, shipping_user):
"""v6 Intake 无 Candidate 时必须阻断,不得退回整封 EML 建一个旧式 Task。""" """v6 Intake 无 Candidate 时必须阻断,不得退回整封 EML 建一个旧式 Task。"""
with app.app_context(): with app.app_context():
@@ -551,6 +602,7 @@ def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping
validation_status='ready', validation_status='ready',
conflicts_json=[], conflicts_json=[],
selected=True, selected=True,
candidate_status='accepted',
business_fingerprint=identity['fingerprint'], business_fingerprint=identity['fingerprint'],
fingerprint_version=identity['version'], fingerprint_version=identity['version'],
fingerprint_strength=identity['strength'], fingerprint_strength=identity['strength'],
@@ -28,6 +28,7 @@ from app.models import (
ShippingTask, ShippingTask,
ShippingTaskEvent, ShippingTaskEvent,
ShippingOrderExtraction, ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision, ShippingOrderFieldDecision,
ShippingOrderFieldValue, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderLine,
@@ -37,6 +38,7 @@ from app.models import (
from app.services.chat.log_service import merge_chat_log_payload from app.services.chat.log_service import merge_chat_log_payload
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.order_extraction import persist_order_extraction_result from app.services.shipping_notice.order_extraction import persist_order_extraction_result
from app.services.shipping_notice.order_extraction_workflow import parse_order_extraction_workflow_result
from app.services.shipping_notice.open_existing_reservation_backfill import ( from app.services.shipping_notice.open_existing_reservation_backfill import (
backfill_exact_file_open_existing_reservations, backfill_exact_file_open_existing_reservations,
) )
@@ -449,11 +451,9 @@ def test_order_field_display_uses_current_catalog_sequence(app):
with app.app_context(): with app.app_context():
_ensure_order_schema() _ensure_order_schema()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
fields = [dict(item) for item in (version.definition_json or {}).get('fields') or []] sequence_by_code = {'part_number': 1, 'qty': 2, 'reservation_id': 3, 'po_number': 4}
sequence_by_code = {'qty': 1, 'part_number': 2, 'reservation_id': 3, 'po_number': 4} for field in ShippingOrderField.query.filter_by(schema_id=version.schema_id).all():
for field in fields: field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
field['sequence'] = sequence_by_code.get(str(field.get('field_code')), 99)
version.definition_json = {**(version.definition_json or {}), 'fields': fields}
task = ShippingTask( task = ShippingTask(
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual', task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}], po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
@@ -522,8 +522,8 @@ def _add_extraction_intake(
return intake, document return intake, document
def test_persist_order_extraction_result_supports_multiple_orders_partial_success_and_replay(app): def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_replayable(app):
"""一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。""" """Provider 结果无论置信度高低均先形成 provisional Candidate,重试只回放。"""
with app.app_context(): with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input() user, session, intake, document, runtime_context = _seed_extraction_input()
context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context})
@@ -559,26 +559,20 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes
} }
result = _persist_test_orders(payload) result = _persist_test_orders(payload)
# 断言一附件拆成两个 Candidate,仅高置信订单创建 Task,Intake 保留为部分完成。 # Dify/Provider 结果不得直接建单;阶段二才允许受控确定性模板自动接受。
assert result['created_count'] == 1 assert result['created_count'] == 0
assert result['opened_existing_count'] == 0 assert result['opened_existing_count'] == 0
assert result['pending_count'] == 1 assert result['pending_count'] == 2
assert result['non_shipping_count'] == 0 assert result['non_shipping_count'] == 0
assert result['created_with_missing_fields_count'] == 1 assert result['created_with_missing_fields_count'] == 0
assert result['message'] == ( assert result['batch_no'] is None
'已创建 1 个发货任务;另有 1 个订单需要补充信息或处理冲突。'
'其中 1 个新建任务仍缺少 Reservation ID,可通过自然对话补充。'
)
assert result['batch_no']
candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all() candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all()
assert len(candidates) == 2 assert len(candidates) == 2
assert len({item.candidate_key for item in candidates}) == 2 assert len({item.candidate_key for item in candidates}) == 2
assert {item.candidate_status for item in candidates} == {'provisional'}
assert all(item.selected is False for item in candidates)
tasks = ShippingTask.query.filter_by(user_id=int(user.id)).all() tasks = ShippingTask.query.filter_by(user_id=int(user.id)).all()
assert len(tasks) == 1 assert tasks == []
task = tasks[0]
assert task.process_status == 'pending_review'
assert task.pending_human_reason == 'rsv_req'
assert (task.step_payload_json or {})['process_field_gate']['missing_fields'] == ['reservation_id']
db.session.refresh(intake) db.session.refresh(intake)
assert intake.parse_status == 'parsed' assert intake.parse_status == 'parsed'
# 低置信订单仍未消费,因此 Intake 抽取终态必须保留为 partially_completed。 # 低置信订单仍未消费,因此 Intake 抽取终态必须保留为 partially_completed。
@@ -586,35 +580,13 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes
db.session.refresh(document) db.session.refresh(document)
assert len((document.order_extraction_result_json or {})['candidate_keys']) == 2 assert len((document.order_extraction_result_json or {})['candidate_keys']) == 2
# 断言后台或自然语言“继续”无法绕过字段门禁进入库存流程。
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
progress = auto_progress({'task_id': task.task_no})
assert progress['status'] == 'needs_human'
assert progress['checkpoint'] == 'rsv_req'
assert 'ensure_inventory' in progress['forbidden_next_tools']
replay = _persist_test_orders(payload) replay = _persist_test_orders(payload)
assert replay['idempotent_replay'] is True assert replay['idempotent_replay'] is True
assert replay['created_count'] == 1 assert replay['created_count'] == 0
assert replay['opened_existing_count'] == 0 assert replay['opened_existing_count'] == 0
assert replay['pending_count'] == 1 assert replay['pending_count'] == 2
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1 assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2 assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2
edit_result = update_notice_line({
'task_id': task.task_no,
'line_index': 0,
'patch': {
'reservation_id': '1000140351',
},
'comment': '用户通过自然对话补齐流程字段',
})
db.session.refresh(task)
# 断言既有行更新 Tool 可完成自然对话补字段,并清除旧流程字段门禁。
assert edit_result['status'] == 'ok'
assert task.pending_human_reason == 'low_confidence'
assert 'process_field_gate' not in (task.step_payload_json or {})
assert task.current_order_extraction_id is not None
assert session.user_id == user.id assert session.user_id == user.id
@@ -642,10 +614,38 @@ def test_shadow_mode_persists_ready_candidate_without_creating_task(app):
assert result['pending_count'] == 1 assert result['pending_count'] == 1
assert result['pending_orders'][0]['reasons'] == ['auto_create_disabled'] assert result['pending_orders'][0]['reasons'] == ['auto_create_disabled']
assert candidate.validation_status == 'ready' assert candidate.validation_status == 'ready'
assert candidate.candidate_status == 'provisional'
assert candidate.selected is False assert candidate.selected is False
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0 assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
def test_approved_deterministic_marker_is_the_only_automatic_acceptance_source(app):
"""已批准固定模板的后端标记可自动接受;普通 Provider 结果仍须人工采纳。"""
with app.app_context():
_user, _session, intake, document, runtime_context = _seed_extraction_input()
context = _build_test_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no, document_id=int(document.id), po_number='4510000001',
part_number='SKU-A', qty=10, include_process_fields=True,
)
order['_hxops_acceptance'] = 'approved_deterministic_profile_v1'
_persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
assert candidate.candidate_status == 'accepted'
assert candidate.acceptance_mode == 'automatic'
assert candidate.extraction_source == 'approved_deterministic_profile'
assert candidate.selected is True
def test_workflow_result_accepts_only_documented_data_orders_wrapper():
"""Dify End 允许 data.orders 包装,但不把内部接受字段当作可信输入。"""
assert parse_order_extraction_workflow_result({
'status': 'succeeded', 'outputs': {'orders': {'data': {'orders': [{'id': 'one'}]}}},
}) == [{'id': 'one'}]
def test_persist_order_extraction_result_consumes_empty_and_confident_non_shipping_results(app): def test_persist_order_extraction_result_consumes_empty_and_confident_non_shipping_results(app):
"""空 orders[] 与高置信非发货分类均不生成 Candidate,并返回明确的未建单事实。""" """空 orders[] 与高置信非发货分类均不生成 Candidate,并返回明确的未建单事实。"""
with app.app_context(): with app.app_context():
@@ -128,6 +128,195 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_
assert saved['definition']['contract_version'] == 'order_coordinate_profile.v2' assert saved['definition']['contract_version'] == 'order_coordinate_profile.v2'
def test_order_field_layout_is_independent_from_line_layout_and_freezes_header_field(app):
"""订单级字段必须冻结 Header 身份,且不写入表头或物理行字段区域。"""
with app.app_context():
schema = _schema_version()
schema.definition_json['fields'].append({
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
})
definition = _coordinate_definition()
definition['order_field_layouts'] = [{
'layout_id': 'po_number', 'field_id': 'forged', 'field_code': 'po_number',
'page_scope': 'first_page',
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO', 'aliases': ['PO NUMBER']},
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': True,
'minimum_evidence_level': 'coordinate',
}]
saved = service.save_draft({
'profile_code': 'ORDER_FIELD', 'display_name': 'Order field',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
order_field = saved['definition']['order_field_layouts'][0]
assert order_field['field_id'] == 'po-field'
assert order_field['anchor']['aliases'] == ['PO NUMBER']
assert all(
item['field_code'] != 'po_number'
for item in saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions']
)
def test_order_field_layout_duplicate_returns_bound_schema_code(app):
"""同一 Header 字段重复绑定时必须返回具体字段编码,不能退化成泛化契约错误。"""
with app.app_context():
schema = _schema_version()
schema.definition_json['fields'].append({
'field_id': 'ship-to-field', 'field_code': 'ship_to_customer', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
})
definition = _coordinate_definition()
definition['order_field_layouts'] = [
{
'layout_id': f'ship_to_{index}', 'field_id': '', 'field_code': 'ship_to_customer',
'page_scope': 'exact_page', 'page_no': 1,
'anchor': {'anchor_id': f'ship_to_label_{index}', 'text': f'SHIP TO {index}'},
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
'minimum_evidence_level': 'coordinate',
}
for index in (1, 2)
]
with pytest.raises(Exception) as caught:
service.save_draft({
'profile_code': 'ORDER_FIELD_DUPLICATE', 'display_name': 'Order field duplicate',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
# 关键断言:前端可用 details 精确指出重复字段,而不是只能显示通用配置无效。
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
assert getattr(caught.value, 'details', {}).get('field_codes') == ['ship_to_customer']
def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
"""账款客户和地址同一行时可共享标签证据,但必须各自保存为独立字段布局。"""
with app.app_context():
schema = _schema_version()
schema.definition_json['fields'].extend([
{
'field_id': 'bill-to-customer', 'field_code': 'bill_to_customer', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'bill-to-address', 'field_code': 'bill_to_address', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
},
])
definition = _coordinate_definition()
shared_anchor = {
'anchor_id': 'invoice_bill_sold_to', 'text': 'INVOICE BILL/SOLD TO',
'region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .25},
}
definition['order_field_layouts'] = [
{
'layout_id': 'bill_to_customer_layout', 'field_id': '', 'field_code': 'bill_to_customer',
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
'value_region': {'x0': 1, 'y0': 0, 'x1': 3, 'y1': 1},
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
'minimum_evidence_level': 'coordinate',
},
{
'layout_id': 'bill_to_address_layout', 'field_id': '', 'field_code': 'bill_to_address',
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
'value_region': {'x0': 3, 'y0': 0, 'x1': 10, 'y1': 1},
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
'minimum_evidence_level': 'coordinate',
},
]
saved = service.save_draft({
'profile_code': 'BILL_TO_SHARED_ANCHOR', 'display_name': 'Bill to shared anchor',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
# 关键断言:共享标签没有重复绑定 Schema 字段,也不会复用 layout_id。
assert [item['layout_id'] for item in saved['definition']['order_field_layouts']] == [
'bill_to_customer_layout', 'bill_to_address_layout',
]
def test_order_field_layout_rejects_line_field_and_unbounded_value_only_mode(app):
"""订单字段不得借用明细字段;无锚点坐标回退必须限制在单页。"""
with app.app_context():
schema = _schema_version()
definition = _coordinate_definition()
definition['order_field_layouts'] = [{
'layout_id': 'invalid_line', 'field_id': '', 'field_code': 'part_number',
'page_scope': 'all_pages', 'anchor': None,
'value_region': None,
'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16},
'value_mode': 'single_line', 'stop_anchors': [], 'required': False,
'minimum_evidence_level': 'coordinate',
}]
with pytest.raises(Exception) as caught:
service.save_draft({
'profile_code': 'INVALID_ORDER_FIELD', 'display_name': 'Invalid order field',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
def test_order_field_layout_freezes_schema_normalizer_and_rejects_a_mismatch(app):
"""订单字段不能让浏览器替换 Schema 的规范化策略,保存结果必须冻结 Schema key。"""
with app.app_context():
schema = _schema_version()
schema.definition_json['fields'].append({
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'uppercase_trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
})
definition = _coordinate_definition()
definition['order_field_layouts'] = [{
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
'page_scope': 'exact_page', 'page_no': 1,
'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16},
'value_mode': 'single_line', 'stop_anchors': [], 'required': False,
'minimum_evidence_level': 'coordinate',
}]
saved = service.save_draft({
'profile_code': 'ORDER_FIELD_NORMALIZER', 'display_name': 'Order field normalizer',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
assert saved['definition']['order_field_layouts'][0]['normalizer_key'] == 'uppercase_trim'
definition['order_field_layouts'][0]['normalizer_key'] = 'trim'
with pytest.raises(Exception) as caught:
service.save_draft({
'profile_code': 'ORDER_FIELD_BAD_NORMALIZER', 'display_name': 'Bad normalizer',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
def test_order_field_ocr_minimum_level_keeps_native_pdf_as_stronger_allowed_source(app):
"""OCR 最低证据允许更强的原生 PDF 坐标,不能把 Schema 授权错误收窄为 OCR-only。"""
with app.app_context():
schema = _schema_version()
schema.definition_json['fields'].append({
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
})
definition = _coordinate_definition()
definition['order_field_layouts'] = [{
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
'page_scope': 'first_page', 'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor',
'stop_anchors': [], 'required': False, 'minimum_evidence_level': 'ocr_coordinate',
}]
saved = service.save_draft({
'profile_code': 'ORDER_FIELD_OCR_MINIMUM', 'display_name': 'Order field OCR minimum',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
assert saved['definition']['order_field_layouts'][0]['minimum_evidence_level'] == 'ocr_coordinate'
def test_composite_coordinate_binding_freezes_all_registered_output_fields(app): def test_composite_coordinate_binding_freezes_all_registered_output_fields(app):
"""复合解析器的辅助输出也必须以 field_id 冻结;缺少任何输出字段时拒绝保存。""" """复合解析器的辅助输出也必须以 field_id 冻结;缺少任何输出字段时拒绝保存。"""
with app.app_context(): with app.app_context():
@@ -359,6 +548,58 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0] field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
assert field['field_id'] == 'replacement-field' assert field['field_id'] == 'replacement-field'
assert field['field_code'] == 'supplier_part_number' assert field['field_code'] == 'supplier_part_number'
def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publish(app, monkeypatch):
"""删除订单字段时保留锚点/值区,并在管理员重新绑定前阻止新模板发布。"""
with app.app_context():
monkeypatch.setattr(
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
)
source_schema = _schema_version()
source_schema.definition_json = {
**source_schema.definition_json,
'fields': [*source_schema.definition_json['fields'], {
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
}],
}
db.session.commit()
definition = _coordinate_definition()
definition['order_field_layouts'] = [{
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
'page_scope': 'first_page',
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO'},
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
'minimum_evidence_level': 'coordinate',
}]
draft = service.save_draft({
'profile_code': 'ORDER_FIELD_MIGRATION', 'display_name': 'Order field migration',
'schema_version_id': source_schema.id, 'definition': definition,
}, actor_id=None)
published = service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
source_schema.status = 'retired'
target_schema = ShippingOrderSchemaVersion(
schema_id=source_schema.schema_id, version=2, status='published', checksum='d' * 64,
published_at=datetime.utcnow(), definition_json={'fields': [
dict(item) for item in source_schema.definition_json['fields'] if item['field_id'] != 'po-field'
]},
)
db.session.add(target_schema)
db.session.commit()
migrated = service.create_schema_migration_draft(
published['id'], target_schema_version_id=target_schema.id,
resolutions={'po-field': {'action': 'unbind'}}, actor_id=None,
)
assert migrated['definition']['order_field_layouts'] == []
unbound = migrated['definition']['draft_unbound_order_field_layouts'][0]
assert unbound['layout_id'] == 'po_number'
assert unbound['anchor']['text'] == 'PO NO'
with pytest.raises(Exception) as caught:
service.publish(migrated['id'], actor_id=None, expected_lock_version=migrated['lock_version'])
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
assert migrated['migration_status'] == 'needs_revalidation' assert migrated['migration_status'] == 'needs_revalidation'
model = db.session.get(ShippingOrderDocumentProfile, migrated['id']) model = db.session.get(ShippingOrderDocumentProfile, migrated['id'])
@@ -1106,6 +1347,36 @@ def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, m
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED' assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED'
def test_delete_draft_cascades_blind_test_suite(app):
"""关键断言:删除草稿 Profile 时一并清理盲测套件,避免外键约束导致 500。"""
with app.app_context():
user = User(username='draft-delete-admin', email='draft-delete@example.com', role='admin', status='active')
schema = _schema_version()
db.session.add(user)
db.session.flush()
profile = ShippingOrderDocumentProfile(
profile_code='DRAFT_DELETE_SUITE', display_name='Draft delete suite', version=1,
status='draft', schema_version_id=schema.id,
structure_fingerprint='3' * 64, definition_json={}, checksum='3' * 64,
lock_version=1,
)
db.session.add(profile)
db.session.flush()
suite = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=profile.checksum or profile.structure_fingerprint,
created_by_id=user.id,
)
db.session.add(suite)
db.session.commit()
suite_id = suite.id
profile_id = profile.id
service.delete_draft(profile_id)
assert db.session.get(ShippingOrderDocumentProfile, profile_id) is None
assert db.session.get(ShippingDocumentProfileTestSuite, suite_id) is None
def test_profile_rejects_legacy_grid_definition(app): def test_profile_rejects_legacy_grid_definition(app):
"""关键断言:新 Profile 不能再混入 HTML 网格、表头行号或固定列映射。""" """关键断言:新 Profile 不能再混入 HTML 网格、表头行号或固定列映射。"""
with app.app_context(): with app.app_context():
@@ -1169,8 +1440,8 @@ def test_workbench_draft_can_save_without_bound_fields(app):
assert saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'] == [] assert saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'] == []
def test_workbench_draft_preserves_unbound_regions_but_publish_rejects_them(app): def test_workbench_auto_suggested_unbound_regions_do_not_block_publish(app, monkeypatch):
"""未绑定框可随草稿恢复,但在完成 Schema 绑定前禁止发布。""" """自动标记的非关键候选可保留展示,不能阻断已经通过质量门禁的模板发布。"""
with app.app_context(): with app.app_context():
schema = _schema_version() schema = _schema_version()
saved = service.save_draft({ saved = service.save_draft({
@@ -1194,6 +1465,29 @@ def test_workbench_draft_preserves_unbound_regions_but_publish_rejects_them(app)
}, },
}, actor_id=None) }, actor_id=None)
assert saved['definition']['table_regions'][0]['draft_unbound_field_regions'][0]['label'] == '未绑定列 1' assert saved['definition']['table_regions'][0]['draft_unbound_field_regions'][0]['label'] == '未绑定列 1'
monkeypatch.setattr(
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
)
assert service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version'])['status'] == 'published'
def test_schema_migration_unbound_regions_still_block_publish(app, monkeypatch):
"""只有 Schema breaking migration 明确遗留的待绑定区域才会阻止发布。"""
with app.app_context():
schema = _schema_version()
payload = _coordinate_definition()
payload['table_regions'][0]['draft_unbound_field_regions'] = [{
'region_id': 'migration-main-part-field', 'parent_layout_id': 'main',
'label': 'part_number', 'region': {'x0': .1, 'y0': .4, 'x1': .3, 'y1': .5},
'requires_rebinding': True,
}]
saved = service.save_draft({
'profile_code': 'UNBOUND_MIGRATION', 'display_name': 'Unbound migration',
'schema_version_id': schema.id, 'definition': payload,
}, actor_id=None)
monkeypatch.setattr(
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
)
with pytest.raises(Exception) as caught: with pytest.raises(Exception) as caught:
service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version']) service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version'])
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID' assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
@@ -1358,3 +1652,294 @@ def test_coordinate_suggestion_can_return_only_requested_physical_row(app, monke
# 当前行识别只返回 row_offset=1,首行建议不会混入响应。 # 当前行识别只返回 row_offset=1,首行建议不会混入响应。
assert [item['row_offset'] for item in result['subrow_layouts']] == [1] assert [item['row_offset'] for item in result['subrow_layouts']] == [1]
assert result['subrow_layouts'][0]['column_samples'] == [['VENDOR-20']] assert result['subrow_layouts'][0]['column_samples'] == [['VENDOR-20']]
def test_coordinate_suggestion_binds_line_columns_from_enabled_field_rules(app, monkeypatch):
"""明细表头仅在唯一别名且字段启用自动标记时绑定相应列。"""
characters = []
source_index = 0
for row_index, row in enumerate([
[('ITEMNO', 12), ('MATERIALNO', 100), ('QTY', 270)],
[('00020', 12), ('PART-20', 100), ('36', 270)],
]):
for text, x0 in row:
for character_index, character in enumerate(text):
if character == ' ':
continue
characters.append({
'text': character, 'source_index': source_index,
'bbox': {
'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20,
'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20,
},
})
source_index += 1
layout = {
'tables': [{'table_id': 'schema-suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70},
'html': '<table><tr><td>broken</td></tr></table>'}],
'coordinate_evidence': {'tables': {'schema-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}},
}
version = SimpleNamespace(definition_json={'fields': [
{'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True,
'display_name': 'Item number', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True,
'display_name': 'Material number', 'aliases': ['MATERIAL NO'], 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'enabled': True,
'display_name': 'Quantity', 'aliases': ['QTY'], 'allowed_sources': ['pdf_coordinate'],
'auto_annotation_enabled': False},
]})
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 106 else None)
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
with app.app_context():
result = service.suggest_coordinate_reconstruction(
{'document_id': 106, 'table_id': 'schema-suggest', 'schema_version_id': 1}, actor_id=None,
)
header_codes = [field['field_code'] for field in result['header_regions'][0]['fields']]
assert header_codes == ['line_no', 'part_number', None]
# The disabled automatic marker never produces a table-header or detail-column binding.
assert result['subrow_layouts'][0]['suggested_field_codes'] == ['line_no', 'part_number', None]
def test_coordinate_suggestion_binds_line_columns_from_normalized_field_codes(app, monkeypatch):
"""没有维护别名时,稳定 field_code 仍可精确对应常见空格表头。"""
characters = []
for row_index, row in enumerate([
[('ITEM NO', 12), ('UNIT PRICE', 90), ('ORDER QUANTITY', 210)],
[('00020', 12), ('941.760000', 90), ('30', 210)],
]):
for text, x0 in row:
for character_index, character in enumerate(text):
if character != ' ':
characters.append({'text': character, 'bbox': {
'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20,
'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20,
}})
layout = {
'tables': [{'table_id': 'code-suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70}}],
'coordinate_evidence': {'tables': {'code-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}},
}
version = SimpleNamespace(definition_json={'fields': [
{'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True,
'display_name': '项次', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line', 'enabled': True,
'display_name': '单价', 'aliases': [], 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'quantity', 'field_code': 'order_quantity', 'scope': 'line', 'enabled': True,
'display_name': '数量', 'aliases': [], 'allowed_sources': ['pdf_coordinate']},
]})
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 107 else None)
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
with app.app_context():
result = service.suggest_coordinate_reconstruction(
{'document_id': 107, 'table_id': 'code-suggest', 'schema_version_id': 1}, actor_id=None,
)
assert result['subrow_layouts'][0]['suggested_field_codes'] == [
'line_no', 'unit_price', 'order_quantity',
]
def test_order_field_suggestions_use_page_glyphs_and_never_auto_confirm(app, monkeypatch):
"""订单字段自动标记只从整页唯一标签生成 needs_review 的锚点和值区候选。"""
glyphs = []
for text, x0, y0 in [('PO NO: 45001', 20, 20), ('BILL TO: ACME', 20, 45), ('PO NO: duplicate', 20, 70)]:
for index, character in enumerate(text):
if character != ' ':
glyphs.append({'text': character, 'bbox': {
'x0': x0 + index * 5, 'y0': y0, 'x1': x0 + index * 5 + 4, 'y1': y0 + 8,
}})
layout = {
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
'coordinate_evidence': {
'pages': {'1': {'width': 300, 'height': 200}},
'page_glyphs': {'1': glyphs},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
}
version = type('Version', (), {'definition_json': {'fields': [
{'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'PO Number', 'scope': 'header',
'aliases': ['PO NO'], 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'bill', 'field_code': 'bill_to', 'display_name': 'Bill To', 'scope': 'header',
'aliases': ['BILL TO'], 'allowed_sources': ['pdf_coordinate']},
]}})()
document = type('Document', (), {'id': 104})()
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 104 else None)
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
with app.app_context():
result = service.suggest_order_field_layouts(
{'document_id': 104, 'schema_version_id': 1, 'page_no': 1}, actor_id=None,
)
by_code = {item['field_code']: item for item in result['order_field_candidates']}
assert result['status'] == 'needs_review'
assert by_code['bill_to']['status'] == 'suggested'
assert by_code['bill_to']['value_mode'] == 'right_of_anchor'
assert by_code['customer_po']['status'] == 'ambiguous'
def test_order_field_suggestions_keep_unbound_visual_labels_for_manual_binding(app, monkeypatch):
"""未维护别名的订单抬头标签仍要出现成对框选,管理员随后在工作台绑定 Schema。"""
glyphs = []
for index, character in enumerate('PURCHASE ORDER DATE: 06/20/2026'):
if character != ' ':
glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28}})
layout = {
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
}
version = type('Version', (), {'definition_json': {'fields': []}})()
document = type('Document', (), {'id': 105})()
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 105 else None)
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
with app.app_context():
result = service.suggest_order_field_layouts({'document_id': 105, 'schema_version_id': 1}, actor_id=None)
candidate = result['order_field_candidates'][0]
assert candidate['binding_status'] == 'unbound'
assert candidate['anchor_text'] == 'PURCHASE ORDER DATE'
assert candidate['field_code'] == ''
def test_order_field_suggestions_backfill_page_glyphs_for_legacy_table_only_snapshot(app, monkeypatch):
"""历史样本仅有表内字符时,建议前必须补齐整页证据以识别表格外的订单抬头。"""
document = type('Document', (), {'id': 106, 'asset_id': 3, 'filename': 'legacy.pdf'})()
asset = object()
layout = {
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'tables': {'lines': []}},
}
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 106 else asset if object_id == 3 else None)
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
monkeypatch.setattr(service, '_require_schema_version', lambda value: type('Version', (), {'definition_json': {'fields': []}})())
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **kwargs: {
**layout, 'coordinate_evidence': {**layout['coordinate_evidence'],
'page_glyphs': {'1': [{'text': 'P', 'bbox': {'x0': 20, 'y0': 20, 'x1': 24, 'y1': 28}}, {'text': 'O', 'bbox': {'x0': 25, 'y0': 20, 'x1': 29, 'y1': 28}}, {'text': ':', 'bbox': {'x0': 30, 'y0': 20, 'x1': 34, 'y1': 28}}]},
'sources': {'pages': {'1': 'pdf_coordinate'}}},
})
with app.app_context():
result = service.suggest_order_field_layouts({'document_id': 106, 'schema_version_id': 1}, actor_id=None)
assert result['order_field_candidates'][0]['anchor_text'] == 'PO'
def test_order_field_suggestions_split_inline_label_from_value_and_exclude_terms(app, monkeypatch):
"""标签框只覆盖冒号前文本,值框只覆盖同一行值;表格前条款不应成为未绑定订单字段。"""
glyphs = []
for text, y0 in [('PURCHASE ORDER DATE: 06/20/2026', 20), ('QUALITY: IF ANY DISCREPANCY FOUND', 85)]:
for index, character in enumerate(text):
if character != ' ':
glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': y0, 'x1': 24 + index * 5, 'y1': y0 + 8}})
layout = {
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
}
document = type('Document', (), {'id': 107})()
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 107 else None)
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
monkeypatch.setattr(service, '_require_schema_version', lambda value: type('Version', (), {'definition_json': {'fields': []}})())
with app.app_context():
result = service.suggest_order_field_layouts({'document_id': 107, 'schema_version_id': 1}, actor_id=None)
candidate = result['order_field_candidates'][0]
assert candidate['anchor_region']['x1'] < candidate['value_region']['x0']
assert candidate['value_region']['x1'] < .75
assert all(item['anchor_text'] != 'QUALITY' for item in result['order_field_candidates'])
def test_order_field_suggestions_keep_value_box_to_first_same_line_value_group(app, monkeypatch):
"""同一视觉行含多个键值组时,首个订单字段值框不得吞掉下一个字段。"""
glyphs = []
for text, x0 in [('PO NO: 451883152', 20), ('VERSION: 2', 190)]:
for index, character in enumerate(text):
if character != ' ':
glyphs.append({'text': character, 'bbox': {
'x0': x0 + index * 5, 'y0': 20, 'x1': x0 + index * 5 + 4, 'y1': 28,
}})
layout = {
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
}
version = type('Version', (), {'definition_json': {'fields': [{
'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'Customer PO', 'aliases': ['PO NO'],
'scope': 'header', 'allowed_sources': ['pdf_coordinate'], 'auto_annotation_enabled': True,
}]}})()
document = type('Document', (), {'id': 109})()
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 109 else None)
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
with app.app_context():
result = service.suggest_order_field_layouts({'document_id': 109, 'schema_version_id': 1}, actor_id=None)
candidate = result['order_field_candidates'][0]
# VERSION starts at 190/300. The PO value box must end before that next key/value group.
assert candidate['value_region']['x1'] < .64
def test_order_field_suggestions_stop_value_before_adjacent_same_line_label(app, monkeypatch):
"""无明显字间距时,值框仍须在同一行下一个标签冒号前停止。"""
glyphs = []
text = 'PO NO: 451883152 VERSION: 2'
for index, character in enumerate(text):
if character != ' ':
glyphs.append({'text': character, 'bbox': {
'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28,
}})
layout = {
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
}
version = type('Version', (), {'definition_json': {'fields': [{
'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'Customer PO', 'aliases': ['PO NO'],
'scope': 'header', 'allowed_sources': ['pdf_coordinate'], 'auto_annotation_enabled': True,
}]}})()
document = type('Document', (), {'id': 110})()
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 110 else None)
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
with app.app_context():
result = service.suggest_order_field_layouts({'document_id': 110, 'schema_version_id': 1}, actor_id=None)
# VERSION begins at character 17, x=105; the PO value must stop before it.
candidate = result['order_field_candidates'][0]
assert candidate['value_region']['x1'] < .36
assert candidate['suggested_value'] == '451883152'
# An 8px text line on a 200px page gets at most 1px top/bottom padding.
value_region = result['order_field_candidates'][0]['value_region']
assert value_region['y1'] - value_region['y0'] <= .05
def test_order_field_suggestions_do_not_duplicate_bound_schema_field_as_unbound_label(app, monkeypatch):
"""同一视觉行已绑定 order_date 时,完整文档标签不得再生成第二个未绑定候选。"""
glyphs = []
for index, character in enumerate('PURCHASE ORDER DATE: 06/20/2026'):
if character != ' ':
glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28}})
layout = {
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
}
document = type('Document', (), {'id': 108})()
version = type('Version', (), {'definition_json': {'fields': [{
'field_id': 'date', 'field_code': 'order_date', 'display_name': 'Order Date', 'aliases': [],
'scope': 'header', 'allowed_sources': ['pdf_coordinate'],
}]}})()
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 108 else None)
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
with app.app_context():
result = service.suggest_order_field_layouts({'document_id': 108, 'schema_version_id': 1}, actor_id=None)
assert [(item['field_code'], item.get('binding_status')) for item in result['order_field_candidates']] == [('order_date', 'bound')]
@@ -21,6 +21,8 @@ from app.jobs.queue import claim_next_job
from app.jobs.types import JobType from app.jobs.types import JobType
from app.models import ( from app.models import (
Agent, Agent,
AgentRuntimeBinding,
ShippingOrderSchema,
ShippingOrderExtractionQualityBatch, ShippingOrderExtractionQualityBatch,
ShippingOrderExtractionQualityLabel, ShippingOrderExtractionQualityLabel,
ShippingOrderExtractionRun, ShippingOrderExtractionRun,
@@ -253,6 +255,9 @@ def test_approved_batch_is_listed_and_frozen_on_run(app):
provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id, provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id,
config={'auto_create_enabled': True}, config={'auto_create_enabled': True},
) )
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one()
schema.auto_creation_policy_json = {'enabled': True}
db.session.commit()
listed = list_approved_quality_batches(owner_agent_id=owner.id) listed = list_approved_quality_batches(owner_agent_id=owner.id)
run, reused = create_order_extraction_run( run, reused = create_order_extraction_run(
@@ -279,6 +284,30 @@ def test_approved_batch_is_listed_and_frozen_on_run(app):
assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED' assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED'
def test_disabled_schema_keeps_runtime_auto_create_binding_in_shadow_mode(app):
"""质量批次已配置时,Schema 总开关关闭仍可创建影子 Run,且不得触发自动建单。"""
with app.app_context():
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-SHADOW')
provider = Agent.query.filter_by(exposure_mode='internal').first()
binding = AgentRuntimeBinding.query.filter_by(
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
).one()
binding.config_json = {'timeout_seconds': 900, 'max_attempts': 3, 'auto_create_enabled': True}
binding.provider_agent_id = provider.id
# The missing quality batch is intentional: schema-disabled execution is shadow-only.
binding.quality_batch_id = None
db.session.commit()
run, reused = create_order_extraction_run(
user=user, agent_id=owner.id, conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
assert reused is False
assert run.provider_config_json['auto_create_enabled'] is False
assert run.input_snapshot_json['auto_creation_policy']['schema_enabled'] is False
assert run.input_snapshot_json['auto_creation_policy']['runtime_binding_enabled'] is True
def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client): def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client):
"""质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。""" """质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。"""
with app.app_context(): with app.app_context():
@@ -206,6 +206,29 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
assert ShippingOrderExtractionUnit.query.count() == 1 assert ShippingOrderExtractionUnit.query.count() == 1
def test_schema_auto_create_switch_cannot_bypass_disabled_runtime_binding(app):
"""Schema 总开关开启时,未显式启用 Runtime Binding 的 Run 仍必须保持影子模式。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-CREATE-GATE')
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one()
schema.auto_creation_policy_json = {'enabled': True}
db.session.commit()
run, reused = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
assert reused is False
assert run.provider_config_json['auto_create_enabled'] is False
policy = run.input_snapshot_json['auto_creation_policy']
assert policy == {
'enabled': False,
'schema_enabled': True,
'runtime_binding_enabled': False,
}
def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app): def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app):
"""Run v3 应冻结真实 layout cell 映射,但 Workflow Manifest 必须完全剥离内部证据。""" """Run v3 应冻结真实 layout cell 映射,但 Workflow Manifest 必须完全剥离内部证据。"""
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
@@ -1383,7 +1406,7 @@ def test_failed_reparse_restores_source_candidate_version(app):
candidate = ShippingNoticeCandidate( candidate = ShippingNoticeCandidate(
candidate_no='SNC-REPARSE-RESTORE', intake_id=intake.id, primary_document_id=document.id, candidate_no='SNC-REPARSE-RESTORE', intake_id=intake.id, primary_document_id=document.id,
candidate_key='restore-version', order_extraction_run_id=source.id, candidate_key='restore-version', order_extraction_run_id=source.id,
selected=True, is_current_version=True, validation_status='ready', selected=True, candidate_status='accepted', is_current_version=True, validation_status='ready',
) )
db.session.add(candidate) db.session.add(candidate)
db.session.commit() db.session.commit()
@@ -1395,6 +1418,8 @@ def test_failed_reparse_restores_source_candidate_version(app):
assert candidate.is_current_version is False assert candidate.is_current_version is False
assert candidate.selected is False assert candidate.selected is False
assert candidate.selected_before_superseded is True assert candidate.selected_before_superseded is True
assert candidate.candidate_status == 'expired'
assert candidate.candidate_status_before_superseded == 'accepted'
transition_order_extraction_run(replacement, target_status='running') transition_order_extraction_run(replacement, target_status='running')
transition_order_extraction_run(replacement, target_status='failed', error_message='provider unavailable') transition_order_extraction_run(replacement, target_status='failed', error_message='provider unavailable')
db.session.flush() db.session.flush()
@@ -1402,6 +1427,8 @@ def test_failed_reparse_restores_source_candidate_version(app):
assert candidate.is_current_version is True assert candidate.is_current_version is True
assert candidate.selected is True assert candidate.selected is True
assert candidate.selected_before_superseded is None assert candidate.selected_before_superseded is None
assert candidate.candidate_status == 'accepted'
assert candidate.candidate_status_before_superseded is None
assert source.superseded_by_run_id is None assert source.superseded_by_run_id is None
@@ -0,0 +1,437 @@
"""
tests/test_shipping_order_field_extraction.py
用途:验证订单级字段锚点/相对区域确定性读取的失败关闭边界。
依赖:order_field_extraction、订单 Profile 与冻结 Schema 字段规则。
逻辑:覆盖独立订单字段,不经过明细物理行或 Dify,防止两类区域重新耦合。
"""
from __future__ import annotations
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
from app.services.shipping_notice.document_layout.runtime import _ocr_page_characters
from app.services.shipping_notice.document_profile_quality_service import _order_field_quality_failures
from app.core.errors import ValidationError
from app.services.shipping_notice.order_extraction_workflow import (
_build_approved_profile_order,
_merge_confirmed_profile_order_fields,
)
def _glyphs(*lines: tuple[str, float, float]) -> list[dict]:
"""将测试文字按字符展开为坐标 glyph,模拟 PDFium 不保留空白字符的输出。"""
result = []
for text, x, y in lines:
offset = 0
for character in text:
if character != ' ':
result.append({'text': character, 'bbox': {'x0': x + offset * 4, 'y0': y, 'x1': x + offset * 4 + 3, 'y1': y + 8}})
offset += 1
return result
def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfileV2:
"""构造包含一个独立 header 字段的最小合法 v2 Profile。"""
return OrderCoordinateProfileV2.model_validate({
'profile_code': 'ORDER-FIELD-TEST', 'version': 1,
'document_match': {'required_anchors': []},
'table_regions': [{'region_id': 'lines', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .9}, 'line_layouts': [], 'header_layouts': [{'layout_id': 'headers', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .7}}]}],
'order_field_layouts': [{
'layout_id': 'po_field', 'field_id': 'po-id', 'field_code': 'customer_po',
'page_scope': page_scope, **layout,
}],
})
def _schema(**overrides: object) -> dict[str, dict]:
"""提供允许 PDF/OCR 坐标且默认 string 的冻结 Header Schema 字段。"""
return {'po-id': {
'field_id': 'po-id', 'field_code': 'customer_po', 'scope': 'header', 'enabled': True,
'value_type': 'string', 'normalizer_key': 'trim', 'validator_keys': ['non_empty'],
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'], **overrides,
}}
def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -> dict:
"""构造冻结页级证据;故意不提供 tables,证明订单字段不依赖明细区。"""
return {
'pages': {page: {'width': 200, 'height': 200} for page in pages},
'page_glyphs': pages,
'sources': {'pages': {page: source for page in pages}},
}
def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
"""唯一 PO 标签右侧的原生字符经规范化后可确认为独立订单字段。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor',
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('PO NO 45001', 20, 20))},
))[0]
# 关键断言:独立字段不依赖 table glyph,唯一锚点的 PDF 坐标才可提升 confirmed。
assert result.status == 'confirmed'
assert result.value == '45001'
assert result.source == 'pdf_coordinate'
def test_wide_address_value_region_is_valid_relative_to_short_anchor():
"""地址值框可比短标签宽得多,自动标记后保存不得被相对区域上限拒绝。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
'value_region': {'x0': 1.1, 'y0': 0, 'x1': 10.5, 'y1': 1},
'value_mode': 'right_of_anchor',
})
# 关键断言:仍有有限上限,但自动建议的长地址几何属于合法模板定义。
assert profile.order_field_layouts[0].value_region.x1 == 10.5
def test_duplicate_anchor_requires_review_instead_of_selecting_one():
"""同页两个 PO 标签存在歧义,绝不按先后顺序静默选择。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('PO NO 1', 20, 20), ('PO NO 2', 20, 50))},
))[0]
# 关键断言:多锚点只能进入人工复核。
assert result.status == 'needs_review'
assert result.issues == ['order_field_anchor_ambiguous']
def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrences():
"""锚点参考区与精确匹配共同排除页眉重复标签和更长单词中的局部文本。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'po', 'text': 'PO', 'match_mode': 'exact', 'region': {'x0': 0, 'y0': .1, 'x1': .8, 'y1': .3}},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('PONUMBER 999', 20, 8), ('PO 45001', 20, 30), ('PO 111', 20, 120))},
))[0]
# 关键断言:只允许参考区内独立 PO,避免选择页眉或 PONUMBER 的局部命中。
assert result.status == 'confirmed'
assert result.value == '45001'
def test_legacy_placeholder_anchor_uses_its_reference_region_as_review_only_evidence():
"""历史手工默认标签不能丢值,但只能按原标注框降级为人工复核。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'ship_to', 'text': '订单字段标签 1',
'region': {'x0': .08, 'y0': .1, 'x1': .35, 'y1': .2},
},
'value_region': {'x0': 1.1, 'y0': 0, 'x1': 5, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('SHIP TO PARTY ACME', 20, 30))},
))[0]
# 关键断言:占位标签不会伪装成已确认,但原锚点框内的值仍可恢复展示。
assert result.status == 'needs_review'
assert result.value == 'ACME'
assert result.issues == ['order_field_anchor_text_mismatch']
def test_non_placeholder_anchor_text_with_reference_region_still_fails_closed():
"""管理员自定义标签写错时不可退化为坐标猜值,避免历史兼容绕过锚点门禁。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'ship_to', 'text': 'WRONG LABEL',
'region': {'x0': .08, 'y0': .1, 'x1': .35, 'y1': .2},
},
'value_region': {'x0': 1.1, 'y0': 0, 'x1': 5, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('SHIP TO PARTY ACME', 20, 30))},
))[0]
# 关键断言:兼容范围仅限系统默认占位标签,普通错配仍不可用。
assert result.status == 'unavailable'
assert result.issues == ['order_field_anchor_missing']
def test_all_pages_conflicting_repeated_value_requires_review():
"""每页重复字段值不一致必须记录冲突,不能将首页值静默确认为正式结果。"""
profile = _profile(page_scope='all_pages', layout={
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('PO NO 45001', 20, 20)), '2': _glyphs(('PO NO 45002', 20, 20))},
))[0]
# 关键断言:多页冲突只能进入人工复核。
assert result.status == 'needs_review'
assert 'order_field_page_value_conflict' in result.issues
def test_missing_page_evidence_and_anchor_fail_closed():
"""没有整页坐标或找不到标签时均不可用,禁止退回表格/绝对坐标猜值。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
no_page = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence={'pages': {'1': {'width': 200, 'height': 200}}})[0]
no_anchor = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('ORDER 1', 20, 20))},
))[0]
# 关键断言:两种证据缺口都没有可用值。
assert no_page.status == 'unavailable'
assert no_anchor.status == 'unavailable'
def test_fallback_and_ocr_never_become_confirmed():
"""无锚点固定区和 OCR 字符均只可生成待复核候选。"""
fallback = _profile(layout={
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2},
})
fallback_result = extract_order_fields(profile=fallback, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('45001', 30, 20))},
))[0]
anchored = _profile(layout={
'anchor': {'anchor_id': 'po', 'text': 'PO NO', 'minimum_evidence_level': 'ocr_coordinate'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, 'minimum_evidence_level': 'ocr_coordinate',
})
ocr_result = extract_order_fields(profile=anchored, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('PO NO 45001', 20, 20))}, source='ocr_coordinate',
))[0]
# 关键断言:低可靠度模式与 OCR 必须保留人工复核状态。
assert fallback_result.status == 'needs_review'
assert ocr_result.status == 'needs_review'
def test_multiline_stops_at_next_label_and_type_failure_requires_review():
"""地址值在下一个标签前截断;日期格式无效不能绕过 Schema validator。"""
address = _profile(layout={
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
'value_region': {'x0': 0, 'y0': 1.1, 'x1': 5, 'y1': 5}, 'value_mode': 'multi_line',
'stop_anchors': [{'anchor_id': 'ship_to', 'text': 'SHIP TO'}],
})
address_result = extract_order_fields(profile=address, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('BILL TO', 20, 20), ('ABC COMPANY', 20, 34), ('ROAD 1', 20, 46), ('SHIP TO NEXT', 20, 60))},
))[0]
date = _profile(layout={
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
date_result = extract_order_fields(profile=date, schema_fields=_schema(value_type='date', validator_keys=['iso_date']), coordinate_evidence=_evidence(
pages={'1': _glyphs(('DATE invalid', 20, 20))},
))[0]
# 关键断言:地址不包含下一个区块,错误类型值不作为正式结果。
assert address_result.value == 'ABC COMPANY\nROAD 1'
assert date_result.status == 'needs_review'
assert date_result.issues == ['order_field_normalization_failed']
def test_common_purchase_order_slash_date_is_normalized():
"""美式订单日期应进入受控日期类型,而不是被误判为格式异常。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(
field_code='order_date', value_type='date', validator_keys=['iso_date'],
), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/20/2026', 20, 20))}))[0]
# 关键断言:运行期值保持 date 对象,后续 JSON 序列化统一输出 ISO 日期。
assert result.status == 'confirmed'
assert result.value.isoformat() == '2026-06-20'
def test_date_recovers_one_glyph_just_outside_value_frame():
"""关键断言:日期值框少一个字符宽时仅补紧邻末尾数字,避免候选无故消失。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
# The right edge falls just before the final ``6`` of 06/20/2026.
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 3.73, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(
field_code='order_date', value_type='date', validator_keys=['iso_date'],
), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/20/2026', 20, 20))}))[0]
# 断言仅相邻一个字宽的末尾数字可恢复为完整的受控日期。
assert result.status == 'confirmed'
assert result.value.isoformat() == '2026-06-20'
def test_right_of_anchor_recovers_a_customer_name_cut_off_by_value_frame():
"""客户值框截在单词中间时,应跳过冒号并补全同一连续公司名称。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
# Right edge cuts ``Corporation`` before its last three characters.
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 3.5, 'y1': 1}, 'value_mode': 'right_of_anchor',
})
result = extract_order_fields(profile=profile, schema_fields=_schema(
field_code='bill_to_customer',
), coordinate_evidence=_evidence(pages={'1': _glyphs((
'BILL TO: Inventec Corporation BILL ADDRESS: 66 Street', 20, 20,
))}))[0]
# 关键断言:不能回传 ``: Inventec Corporati``,也不能吞入右侧地址字段。
assert result.status == 'confirmed'
assert result.value == 'Inventec Corporation'
def test_right_of_anchor_never_extends_from_customer_value_box_into_address():
"""同一行客户和地址相邻时,客户值框不得扩展跨过词间隔。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
# This box already contains the full company name but ends before the address.
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 4.25, 'y1': 1}, 'value_mode': 'right_of_anchor',
})
result = extract_order_fields(profile=profile, schema_fields=_schema(
field_code='bill_to_customer',
), coordinate_evidence=_evidence(pages={'1': _glyphs((
'BILL TO: Inventec Corporation 66 Hou-Kang Street', 20, 20,
))}))[0]
# 关键断言:框尾后的地址首字符必须因词间隔被拒绝,不能混入客户名称。
assert result.status == 'confirmed'
assert result.value == 'Inventec Corporation'
def test_multiline_stop_anchor_ignores_same_label_above_current_anchor():
"""页眉或其他区块中位于当前锚点上方的停止标签,不能截断账款地址。"""
address = _profile(layout={
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
'value_region': {'x0': 0, 'y0': 1.1, 'x1': 5, 'y1': 5}, 'value_mode': 'multi_line',
'stop_anchors': [{'anchor_id': 'ship_to', 'text': 'SHIP TO'}],
})
result = extract_order_fields(profile=address, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(
('SHIP TO HEADER', 20, 8), ('BILL TO', 20, 30), ('ABC COMPANY', 20, 44),
('ROAD 1', 20, 56), ('SHIP TO NEXT', 20, 72),
)},
))[0]
# 关键断言:只以当前 BILL TO 后的 SHIP TO 作为停止条件。
assert result.status == 'confirmed'
assert result.value == 'ABC COMPANY\nROAD 1'
def test_page_ocr_character_builder_preserves_page_coordinates_without_native_fallback():
"""扫描页 OCR 仅在原生字符缺失时可生成页级证据,空白字符不应成为可选锚点。"""
class _Box:
x0, y0, x1, y1 = 10, 20, 30, 28
class _Line:
text, bbox = 'PO 1', _Box()
glyphs = _ocr_page_characters([_Line()])
# 关键断言:OCR 字符保留原页 y 坐标且剔除空白,供后续明确标为 ocr_coordinate。
assert [item['text'] for item in glyphs] == ['P', 'O', '1']
assert glyphs[0]['bbox']['y0'] == 20
def test_quality_gate_rejects_unavailable_or_low_reliability_order_field_candidates():
"""盲测必须将订单字段的锚点缺失和固定坐标回退标为失败,而不是只核对明细行。"""
anchored = _profile(layout={
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
missing = _order_field_quality_failures(
parser=anchored, schema_fields=_schema(), sample_id=7,
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('ORDER 1', 20, 20))})}, expected_values={'customer_po': '45001'},
)
fallback = _profile(layout={'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2}})
low_reliability = _order_field_quality_failures(
parser=fallback, schema_fields=_schema(), sample_id=8,
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('45001', 30, 20))})}, expected_values={'customer_po': '45001'},
)
# 关键断言:没有 confirmed 证据的订单字段阻断盲测凭证。
assert missing == ['sample:7:order_field:customer_po:unavailable']
assert low_reliability == ['sample:8:order_field:customer_po:needs_review']
def test_quality_gate_compares_confirmed_order_field_value_with_human_truth():
"""状态为 confirmed 仍必须逐字段等于人工真值,防止读到错误但格式合法的 PO。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
failures = _order_field_quality_failures(
parser=profile, schema_fields=_schema(), sample_id=9,
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('PO NO 45001', 20, 20))})},
expected_values={'customer_po': '45002'},
)
# 关键断言:格式合法但与人工真值不同的字段必须阻断盲测。
assert failures == ['sample:9:order_field:customer_po:mismatch']
def test_quality_gate_normalizes_order_field_truth_before_comparison():
"""JSON 盲测真值的日期字符串须按冻结 Schema 规范化后再与提取值比较。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
schema = _schema(field_code='order_date', value_type='date', validator_keys=['iso_date'])
profile.order_field_layouts[0].field_code = 'order_date'
failures = _order_field_quality_failures(
parser=profile, schema_fields=schema, sample_id=10,
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('DATE 2026-08-01', 20, 20))})},
expected_values={'order_date': '2026-08-01'},
)
# 关键断言:同一日期的 JSON 字符串与运行时 date 对象不应产生伪 mismatch。
assert failures == []
def test_deterministic_order_merges_confirmed_order_field_and_required_header_gate():
"""确定性建单将独立 confirmed 字段合并为 Header,并用它满足必填订单字段。"""
order = _build_approved_profile_order(
unit=type('Unit', (), {'document_id': 42})(), intake={'intake_no': 'SNI-1'},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
definition={'fields': [
{'field_id': 'po-id', 'field_code': 'customer_po', 'scope': 'header', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'},
]},
table={'rows': [{'status': 'parsed', 'issues': [], 'fields': [{'field_id': 'qty-id', 'value': 3, 'quote': '3'}]}]},
confirmed_order_fields=[{
'field_id': 'po-id', 'value': '45001', 'page_no': 1, 'source': 'pdf_coordinate',
'anchor_bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
'value_bbox': {'x0': 25, 'y0': 10, 'x1': 50, 'y1': 20}, 'glyph_indices': [4, 5, 6],
}],
)
# 关键断言:订单字段与明细字段严格分域后仍可在最终订单 Header 合并。
assert order is not None
assert {field['field_id'] for field in order['header_fields']} == {'po-id'}
assert order['header_fields'][0]['observations'][0]['layout_evidence']['page_no'] == 1
def test_provider_omission_is_merged_but_override_of_confirmed_order_field_is_rejected(monkeypatch):
"""Dify 不接收 confirmed 字段可省略;若自行返回冲突值,HXOPS 必须拒绝。"""
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._confirmed_profile_order_fields',
lambda _run, unit: [{'field_id': 'po-id', 'value': '45001'}],
)
unit = type('Unit', (), {'document_id': 42})()
omitted = [{'header_fields': []}]
merged = _merge_confirmed_profile_order_fields(object(), unit=unit, orders=omitted)
field = merged[0]['header_fields'][0]
assert field['field_id'] == 'po-id'
assert field['observations'][0]['value'] == '45001'
assert field['_hxops_order_field_evidence'] is True
assert merged[0]['_hxops_order_field_evidence'] is True
invalid = [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'DIFF'}]}]}]
# 关键断言:模型不可覆盖模板已确认的订单字段。
try:
_merge_confirmed_profile_order_fields(object(), unit=unit, orders=invalid)
except ValidationError as error:
assert error.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
else:
raise AssertionError('confirmed order field override must be rejected')
@@ -52,3 +52,22 @@ def test_profile_matcher_requires_optional_score_threshold():
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。""" """可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout()) result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout())
assert result.status == 'no_match' assert result.status == 'no_match'
def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
"""模板静态锚点可位于表格外,必须从页级冻结证据匹配而非只读表内字符。"""
layout = _layout('LINE ITEMS')
layout['coordinate_evidence']['page_glyphs'] = {'1': [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate('PURCHASE ORDER')
]}
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
# 关键断言:订单字段模板不再要求业务锚点错误地落在明细表格中。
assert result.status == 'unique_match'
def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence():
"""缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。"""
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match'
@@ -340,6 +340,42 @@ def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]:
return int(intake.id), [body, pdf], int(user.id) return int(intake.id), [body, pdf], int(user.id)
def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_marked_only(app):
"""确认订单字段必须保留坐标元数据;未经过 Workflow 注入的标记不得提升 Provider 证据。"""
with app.app_context():
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
po = service.save_field({'field_code': 'customer_po', 'scope': 'header', 'value_type': 'string'}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
published = _save_and_publish(draft, [_config(po['id'], '客户 PO', value_type='string')])
intake_id, documents, actor_id = _seed_documents()
coordinate = {
'page_no': 1, 'source': 'pdf_coordinate',
'anchor_bbox': {'x0': 10, 'y0': 10, 'x1': 30, 'y1': 20},
'value_bbox': {'x0': 35, 'y0': 10, 'x1': 70, 'y1': 20},
'glyph_indices': [4, 5, 6, 7, 8],
}
result = persist_dynamic_order(
raw_order={
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'header_fields': [{'field_id': po['id'], '_hxops_order_field_evidence': True, 'observations': [{
'value': 'PO-100', 'document_id': documents[1].id, 'quote': 'PO-100',
'layout_evidence': coordinate,
}]}],
'lines': [],
},
intake_id=intake_id, snapshot_hash='o' * 64, documents=documents, actor_id=actor_id,
)
observation = ShippingOrderFieldObservation.query.filter_by(
extraction_id=result['extraction'].id, field_id=po['id'],
).one()
# 关键断言:最终记录可追溯到页号、锚点/值框与字符索引,而非 Provider 自报置信度。
assert observation.evidence_verified is True
assert observation.extractor == 'order_profile_order_field'
assert observation.evidence_metadata_json == {'kind': 'order_field_coordinate', **coordinate}
assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1'
def test_dynamic_schema_contract_and_cross_document_persistence(app): def test_dynamic_schema_contract_and_cross_document_persistence(app):
"""同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。""" """同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。"""
with app.app_context(): with app.app_context():
@@ -48,6 +48,37 @@ def test_rolling_verification_keeps_shortage_pending_and_later_releases_it(app):
assert second.result_json['available_count'] == 1 assert second.result_json['available_count'] == 1
def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app):
"""关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。"""
with app.app_context():
task, user = _build_accepted_order(suffix='quantity-authority')
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
db.session.commit()
line = snapshot.lines[0]
frozen_quantity = str(line.qty)
result = {
'reservation_id': line.reservation_id,
'part_number': line.part_number,
'required_qty': '1',
'available_qty': '1',
'line_status': 'ok',
}
with pytest.raises(ValidationError) as quantity_error:
record_inventory_verification(
task, inventory_snapshot_id=None, source_config_version='v1', line_results=[result],
)
assert quantity_error.value.code == 'SHIPPING.RESERVATION_MISMATCH'
db.session.rollback()
result['required_qty'] = frozen_quantity
with pytest.raises(ValidationError) as duplicate_error:
record_inventory_verification(
task, inventory_snapshot_id=None, source_config_version='v1', line_results=[result, result.copy()],
)
assert duplicate_error.value.code == 'SHIPPING.RESERVATION_MISMATCH'
def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app): def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app):
"""A/B 首轮占用后,C 补货只能进入第二轮;首轮 Artifact 不得被覆盖或重复占用。""" """A/B 首轮占用后,C 补货只能进入第二轮;首轮 Artifact 不得被覆盖或重复占用。"""
with app.app_context(): with app.app_context():
+53 -1
View File
@@ -18,7 +18,8 @@ from app.models import (
ShippingUploadAttempt, ShippingUploadAttempt,
) )
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success 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 from app.services.shipping_notice.upload_attempt_service import complete_attempt, mark_attempt_result_unknown, start_rpa_attempt, void_rejected_artifact
from app.services.shipping_notice.state_machine import resolve_task_ui_state
def _ready_artifact() -> tuple[ShippingTask, ShippingExportArtifact, ShippingReservation]: def _ready_artifact() -> tuple[ShippingTask, ShippingExportArtifact, ShippingReservation]:
@@ -91,6 +92,57 @@ def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app):
assert start_rpa_attempt(task, artifact_id=artifact.id).attempt_no == 2 assert start_rpa_attempt(task, artifact_id=artifact.id).attempt_no == 2
def test_timed_out_upload_is_frozen_until_reconciled(app):
"""关键断言:回调超时不是失败,禁止重传;迟到成功或货代明确拒绝才可收口。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
mark_attempt_result_unknown(attempt)
with pytest.raises(ConflictError) as retry_error:
start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key=attempt.idempotency_key)
assert retry_error.value.code == 'SHIPPING.UPLOAD_RESULT_UNKNOWN'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading'
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
complete_attempt(attempt, success=True, callback_id='late-success', freight_ref_no='F-LATE')
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app):
"""关键断言:未知结果只允许核对或凭回执收口,UI 不得暴露重试上传动作。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
mark_attempt_result_unknown(attempt)
task.pending_human_reason = 'upload_result_unknown'
task.upload_status = 'unknown'
state = resolve_task_ui_state(task)
assert state.checkpoint == 'upload_result_unknown'
assert state.human_options == ['refresh', 'download_excel', 'mark_manual_uploaded']
assert 'retry_upload' not in state.human_options
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
def test_timed_out_upload_requires_explicit_rejection_before_release(app):
"""关键断言:未知结果中的普通失败不释放预约单,明确拒绝并授权作废才允许恢复。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
mark_attempt_result_unknown(attempt)
complete_attempt(attempt, success=False, callback_id='late-network-error', error_message='network timeout')
assert attempt.status == 'timed_out'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading'
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
complete_attempt(attempt, success=False, callback_id='late-freight-rejection', error_message='freight_rejected: invalid document')
void_rejected_artifact(task, artifact_id=artifact.id, operator_id=1, reason='货代明确拒绝')
assert db.session.get(ShippingReservation, reservation.id).status == 'pending'
def test_only_explicit_rejection_can_void_and_release_artifact(app): def test_only_explicit_rejection_can_void_and_release_artifact(app):
"""网络失败不能释放预约单;货代明确拒绝且有授权后才可重新进入库存核验。""" """网络失败不能释放预约单;货代明确拒绝且有授权后才可重新进入库存核验。"""
with app.app_context(): with app.app_context():
+3 -1
View File
@@ -4,6 +4,8 @@
- 管理员在受控低清 PDF 画布上配置表头、明细物理行和字段区域,不输入坐标数字;翻页按页加载,离开未保存草稿必须确认。 - 管理员在受控低清 PDF 画布上配置表头、明细物理行和字段区域,不输入坐标数字;翻页按页加载,离开未保存草稿必须确认。
- 表头行与明细行分别配置。表头识别只能给出当前冻结 Schema 的唯一精确别名建议,不能覆盖人工字段绑定;字段缺失、重复或不确定时保持未映射。 - 表头行与明细行分别配置。表头识别只能给出当前冻结 Schema 的唯一精确别名建议,不能覆盖人工字段绑定;字段缺失、重复或不确定时保持未映射。
- 订单级字段作为独立标注域:管理员可用标签锚点、相对值区、多行停止标签和受控规范化配置 Header 字段;不得把账款/送货客户、地址、PO 等标为明细表头或物理行字段。发布前盲测须验证每个订单字段的人工真值与页级字符坐标证据,`confirmed` 字段不可被 Dify 覆盖。
- 字段规则版本必须保留:文档模板绑定稳定 `field_id` 与创建时 Schema 快照。新增或调整 Schema 版本不得清空既有模板绑定;仅发生字段语义、作用域、类型或证据能力等破坏性变化时,才要求受影响字段显式迁移和重新盲测。
## 设备维保助手补充需求 ## 设备维保助手补充需求
@@ -590,6 +592,6 @@
- L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。 - L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。
- 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。 - 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。
- 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。 - 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。
- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;常规模板至少 3 份独立样本(无表头模板至少 5 份),其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。所有样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。 - **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;所有模板最低仅需 1 份独立样本,其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。
- **Dify 证据边界**:Dify 输出只能使用冻结 `extraction_contract` 中的 field_id,所有 Observation 必须引用当前 Unit 文档且 quote 可在冻结输入中逐字验证;不得回传确定性上下文字段或覆盖已锁定值。Dify 画布由管理员在最终验收时手工配置,HXOPS 不修改画布。 - **Dify 证据边界**:Dify 输出只能使用冻结 `extraction_contract` 中的 field_id,所有 Observation 必须引用当前 Unit 文档且 quote 可在冻结输入中逐字验证;不得回传确定性上下文字段或覆盖已锁定值。Dify 画布由管理员在最终验收时手工配置,HXOPS 不修改画布。
- **客户绑定与冻结**:订单原文、按 `order-customer-fingerprint.v1` 标准化生成的身份指纹、正式 `customer_id` 三层分离保存。Bill-to 是订购客户;只有已人工确认并写明理由的 Bill-to 匹配可以冻结为 Snapshot。调用方不能在冻结请求中自由传入客户或简码;Snapshot 固化客户简码和匹配规则版本,客户后续改名、合并或规则变化不回写历史。 - **客户绑定与冻结**:订单原文、按 `order-customer-fingerprint.v1` 标准化生成的身份指纹、正式 `customer_id` 三层分离保存。Bill-to 是订购客户;只有已人工确认并写明理由的 Bill-to 匹配可以冻结为 Snapshot。调用方不能在冻结请求中自由传入客户或简码;Snapshot 固化客户简码和匹配规则版本,客户后续改名、合并或规则变化不回写历史。
@@ -10,10 +10,13 @@
2. `parse_and_prepare_input` 直接读取 `manifest.document` 和可选的 `manifest.structured_table_candidates`;不得读取其他文档集合、确定性表格内部载荷或任何输入格式分支。 2. `parse_and_prepare_input` 直接读取 `manifest.document` 和可选的 `manifest.structured_table_candidates`;不得读取其他文档集合、确定性表格内部载荷或任何输入格式分支。
3. Code 节点不得期待或生成 HTML、bbox、token、cell_id、evidence_ref、field_code。结构化候选字段仅为 `column_index/field_id/value/quote`;表/行同时带 `status/issues`,候选顶层带 `field_policy`。 3. Code 节点不得期待或生成 HTML、bbox、token、cell_id、evidence_ref、field_code。结构化候选字段仅为 `column_index/field_id/value/quote`;表/行同时带 `status/issues`,候选顶层带 `field_policy`。
4. LLM 对 `field_policy=locked` 的字段必须原样保留稳定 `field_id/value/quote`,只能补充缺失字段;对 `suggested` 候选可结合当前文档短文本判断,但不得把自然语言表头改写为其他 field_id。 4. LLM 对 `field_policy=locked` 的字段必须原样保留稳定 `field_id/value/quote`,只能补充缺失字段;对 `suggested` 候选可结合当前文档短文本判断,但不得把自然语言表头改写为其他 field_id。
5. `unit.intake_no` 必须写入每个订单 `source_intake_no`;`unit.document_id` 必须写入 `primary_document_id` 及每条 Observation 的 `document_id`。End 仍只输出 String 类型 `orders`,内容必须是 JSON 数组,不得附加 think/XML/Markdown 标签。 5. HXOPS 的订单级字段模板在后端以页级字符坐标提取。模板已产生 `confirmed` 的 Header 字段不会注入 Dify,Dify 省略这些字段是合法的;Dify 只补充未配置、`needs_review` 或 `unavailable` 的 Header 字段。若 Workflow 仍输出同一已确认 `field_id`,其值必须与后端结果一致;发生冲突时 HXOPS 会拒绝该 Unit 输出,并以自己的页级坐标 Observation 替换一致的 Provider Observation。
6. 用 Dify 画布测试至少覆盖:无表格、needs_review 候选、locked 候选、零订单、多订单、缺 Reservation。确认输出合法后发布 Workflow;已创建 Run 不会随配置变更改变其冻结输入。 6. `unit.intake_no` 必须写入每个订单 `source_intake_no`;`unit.document_id` 必须写入 `primary_document_id` 及每条 Observation 的 `document_id`。End 输出 String 类型 `orders`;内容可为 JSON 数组、`{"orders":[...]}` 或 `{"data":{"orders":[...]}}`,不得附加 think/XML/Markdown 标签。
7. 关闭 `retriever_resource`;该 Workflow 不得有知识库检索、工具调用、外部 HTTP、数据库读取或其他可取得 Unit 外信息的节点。
8. LLM 节点必须显式设置 Temperature `0`、Top P `0.1`;关闭 Streaming、Memory 和 Conversation History;模型支持时启用 JSON Object 响应格式。不得依赖 Provider 默认参数。
9. 用 Dify 画布测试至少覆盖:无表格、needs_review 候选、locked 候选、零订单、多订单、缺 Reservation,以及已确认订单字段原样保留与未确认订单字段补充。确认输出合法后发布 Workflow;已创建 Run 不会随配置变更改变其冻结输入。
人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。不得在 Code 节点自行把候选提升为 accepted,不得据此开启自动建单,也不得宣称达到 95% 准确率。 人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。Dify 结果无论置信度多高一律为 provisional,必须由用户在 HXOPS 人工采纳后才能进入履约;不得在 Code 节点输出 `_hxops_*` 内部字段、自行把候选提升为 accepted、开启自动建单或宣称达到 95% 准确率。唯一已发布且盲测批准的确定性模板由 HXOPS 后端标记为自动采纳,Dify 不能模拟该标记。
### 单文档证据与跨文档订单的边界(必须遵守) ### 单文档证据与跨文档订单的边界(必须遵守)
@@ -25,6 +28,7 @@
- 单文档完全没有可证明字段时,LLM 返回 `{"orders":[]}`,属于成功空结果,不是校验失败。 - 单文档完全没有可证明字段时,LLM 返回 `{"orders":[]}`,属于成功空结果,不是校验失败。
- 只有 JSON 无法解析、订单/字段结构损坏、Schema/Intake/Document 不一致、Observation 指向其他 Document 等协议或来源越界,才进入失败分支。 - 只有 JSON 无法解析、订单/字段结构损坏、Schema/Intake/Document 不一致、Observation 指向其他 Document 等协议或来源越界,才进入失败分支。
- Dify 不可把没有锚点的 EML 证据猜测性并入某份 PDF;是否能合并、是否能创建订单只能由 HXOPS 后端决定。 - Dify 不可把没有锚点的 EML 证据猜测性并入某份 PDF;是否能合并、是否能创建订单只能由 HXOPS 后端决定。
- 当前 Document 之外的任何邮件正文、附件或既有 Run 数据均不可读取、引用或作为“优先证据”。例如 AWS 料号只有在当前 `document_json` 中存在明确标签和逐字证据时才能返回;不得因其他 Unit 的 AWS 料号覆盖或补全当前 Unit 的 `Material` 等字段。
Reservation 的最终裁决也在 HXOPS:PDF 缺少 `reservation_id` 时,Dify 必须照常返回其可证明的 PO、料号、数量、项次等字段;EML 若有明确 Reservation 也只返回该 Document 自己的 Observation。后端仅在同 Intake、同 PO 下,且邮件/PDF 行可通过**唯一且一致**的 `part_number` 或 `line_no` 关联时,才把合法 Reservation 合并到最终行。重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点时都不得自动补入,必须保留证据并进入 `needs_review`。 Reservation 的最终裁决也在 HXOPS:PDF 缺少 `reservation_id` 时,Dify 必须照常返回其可证明的 PO、料号、数量、项次等字段;EML 若有明确 Reservation 也只返回该 Document 自己的 Observation。后端仅在同 Intake、同 PO 下,且邮件/PDF 行可通过**唯一且一致**的 `part_number` 或 `line_no` 关联时,才把合法 Reservation 合并到最终行。重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点时都不得自动补入,必须保留证据并进入 `needs_review`。
@@ -47,6 +51,9 @@ HXOPS 的“按当前规则重新识别”不会调用新的 Dify 节点,也
- [ ] 人工单元格真值和真实质量/性能指标全部达到 `technical.md` 阈值。 - [ ] 人工单元格真值和真实质量/性能指标全部达到 `technical.md` 阈值。
- [ ] Dify 已发布本手册定义的唯一画布,Start 仍只有 String `execution_manifest`。 - [ ] Dify 已发布本手册定义的唯一画布,Start 仍只有 String `execution_manifest`。
- [ ] 已关闭 Retriever Resource,且画布没有知识库检索、工具、HTTP 或跨文档读取节点。
- [ ] LLM 参数已显式设置为 Temperature `0`、Top P `0.1`,并关闭 Streaming、Memory、Conversation History;支持时启用 JSON Object 输出。
- [ ] 提示词只允许使用当前 `document_json`;未以其他邮件正文或附件的 AWS 料号、PO、Reservation 等信息补全当前 Unit。
- [ ] 保持 `auto_create_enabled=false` 完成至少 20 个测试环境真实 Run。 - [ ] 保持 `auto_create_enabled=false` 完成至少 20 个测试环境真实 Run。
- [ ] 管理员诊断中证据追溯率、issue code 和失败单元均可解释;无错误合并、错误拆分或错误 Task。 - [ ] 管理员诊断中证据追溯率、issue code 和失败单元均可解释;无错误合并、错误拆分或错误 Task。
- [ ] 业务负责人和技术负责人书面批准后才开启自动建单。 - [ ] 业务负责人和技术负责人书面批准后才开启自动建单。
@@ -77,7 +84,7 @@ Start
false -> Code: raise_validation_error -> Workflow Failed false -> Code: raise_validation_error -> Workflow Failed
``` ```
End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错误伪装为成功的空订单。 End 只能输出 `orders`。HXOPS 兼容 End 将其包装为 `data.orders`,但不接受任意深层 JSON 搜索。失败分支必须抛出异常,不能将校验错误伪装为成功的空订单。
## 3. Start 节点 ## 3. Start 节点
@@ -278,7 +285,7 @@ def main(execution_manifest: str):
## 5. LLM 节点:extract_orders ## 5. LLM 节点:extract_orders
建议参数:Temperature `0`,Top P `0.1`,Streaming/Memory/Conversation History 全部关闭;支持时启用 JSON Object 响应格式。Reasoning 不得接入正文或输出。 必须显式设置:Temperature `0`,Top P `0.1`,Streaming/Memory/Conversation History 全部关闭;支持时启用 JSON Object 响应格式。Reasoning 不得接入正文或输出。禁止保留空参数而依赖 Provider 默认值。
输入变量:`run_no`、`unit_id`、`source_intake_no`、`primary_document_id`、`schema_contract_json`、`document_json`、`table_candidates_json`、`readonly_context_json`、`header_field_ids_json`、`line_field_ids_json`,均来自 `parse_and_prepare_input`。 输入变量:`run_no`、`unit_id`、`source_intake_no`、`primary_document_id`、`schema_contract_json`、`document_json`、`table_candidates_json`、`readonly_context_json`、`header_field_ids_json`、`line_field_ids_json`,均来自 `parse_and_prepare_input`。
@@ -303,7 +310,7 @@ classification 必须根据当前 document_json.extracted_text 独立判断。do
必须严格匹配 schema 中每个 field_id 的 value_type:decimal/integer 必须返回 JSON 数字;boolean 必须返回 JSON 布尔值;date 的 value 必须为 `YYYY-MM-DD`。例如原文 `06/22/2026` 的 date value 必须输出 `2026-06-22`,但 quote 仍保留原文 `06/22/2026`。不符合类型或无法规范化时省略字段,不得原样输出非 ISO 日期。 必须严格匹配 schema 中每个 field_id 的 value_type:decimal/integer 必须返回 JSON 数字;boolean 必须返回 JSON 布尔值;date 的 value 必须为 `YYYY-MM-DD`。例如原文 `06/22/2026` 的 date value 必须输出 `2026-06-22`,但 quote 仍保留原文 `06/22/2026`。不符合类型或无法规范化时省略字段,不得原样输出非 ISO 日期。
高风险行字段不得按位置或猜测映射:`line_no` 只能是订单行号(如 `00010`);`part_number` 是 HXOPS 内部料号,通常来自明确的 MPN、Supplier Part Number、Vendor Part Number 等供应商/制造商语义;`customer_part_number` 通常来自客户订单中的 `Material`、`Material No`、`Material Number`;`reservation_id` 只能是原文明确标注的 Reservation ID;`inventory_source_hint` 只能是明确库存源/仓库提示,绝不能填行号;`aws_part_number` 只能来自明确标注的 AWS SKU、AWS Part Number、APN 或同等 AWS 语义。若邮件正文或任一附件已有明确 AWS 料号,必须优先使用该证据,不能用 Material 覆盖。不得以料号、行号、描述、金额或数量互相替代。已发布的精确模板 Profile 可以覆盖裸表头的通常语义;例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法契约,Dify 不得重新改写。 高风险行字段不得按位置或猜测映射:`line_no` 只能是订单行号(如 `00010`);`part_number` 是 HXOPS 内部料号,通常来自明确的 MPN、Supplier Part Number、Vendor Part Number 等供应商/制造商语义;`customer_part_number` 通常来自客户订单中的 `Material`、`Material No`、`Material Number`;`reservation_id` 只能是原文明确标注的 Reservation ID;`inventory_source_hint` 只能是明确库存源/仓库提示,绝不能填行号;`aws_part_number` 只能来自**当前 `document_json`** 中明确标注的 AWS SKU、AWS Part Number、APN 或同等 AWS 语义。不得读取或用邮件正文、其他附件或其他 Unit 的 AWS 料号覆盖当前 Document 的 Material。不得以料号、行号、描述、金额或数量互相替代。已发布的精确模板 Profile 可以覆盖裸表头的通常语义;例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法契约,Dify 不得重新改写。
`Item deleted`、`Cancelled` 等删除标记可能独占一行并作用于前一条视觉明细,而非标记后的下一条明细。只有 `table_candidates_json` 已按版面行关系明确将候选行标记为 `role=deleted` 时,才忽略该行;纯文本或拆行文本中不得自行推断删除标记归属,也不得自动删除任何订单行,应保留候选并进入后续复核。若 Reservation ID 没有 `Reservation ID`、`COM ID`、`Reservation Order`、`Reservation No`、`Resv ID`、`PR Number` 或 `External reservation ID` 等明确标签和对应的 5 位或 10 位纯数字,必须省略 `reservation_id`;`EXW AWS HUB`、仓库/站点、贸易术语、项次和料号绝不能填入该字段。 `Item deleted`、`Cancelled` 等删除标记可能独占一行并作用于前一条视觉明细,而非标记后的下一条明细。只有 `table_candidates_json` 已按版面行关系明确将候选行标记为 `role=deleted` 时,才忽略该行;纯文本或拆行文本中不得自行推断删除标记归属,也不得自动删除任何订单行,应保留候选并进入后续复核。若 Reservation ID 没有 `Reservation ID`、`COM ID`、`Reservation Order`、`Reservation No`、`Resv ID`、`PR Number` 或 `External reservation ID` 等明确标签和对应的 5 位或 10 位纯数字,必须省略 `reservation_id`;`EXW AWS HUB`、仓库/站点、贸易术语、项次和料号绝不能填入该字段。
+5 -2
View File
@@ -89,7 +89,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
**阶段 6 Dify 手工配置**:无需修改画布。预算、Provider 并发和熔断全部由 HXOPS 管理;Dify 继续保持单文档无状态执行。管理员只在 HXOPS Runtime Binding 配置治理参数,不要在 Dify 内复制限流、循环重试或熔断逻辑。 **阶段 6 Dify 手工配置**:无需修改画布。预算、Provider 并发和熔断全部由 HXOPS 管理;Dify 继续保持单文档无状态执行。管理员只在 HXOPS Runtime Binding 配置治理参数,不要在 Dify 内复制限流、循环重试或熔断逻辑。
**阶段 7 当前结论(2026-07-21)**:自动建单由 Run 冻结的 `auto_create_enabled` 硬门禁控制,默认 `false`。关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别;满足全部业务门禁的 Candidate 保持 `validation_status=ready`、`selected=false`,增加 `auto_create_disabled` 待审原因,不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。生产代码和测试只维护唯一 Manifest 契约。 **阶段 7 当前结论(2026-07-21)**:自动建单由 Run 冻结的 `auto_create_enabled` 硬门禁控制,默认 `false`;它必须同时满足 Schema 总开关、`shipping.order_extraction` Runtime Binding 显式开启及已批准质量批次,任一层关闭即冻结为影子模式。关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别;满足全部业务门禁的 Candidate 保持 `validation_status=ready`、`selected=false`,增加 `auto_create_disabled` 待审原因,不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。生产代码和测试只维护唯一 Manifest 契约。
### L5 紧凑模型契约(2026-07-22) ### L5 紧凑模型契约(2026-07-22)
@@ -118,7 +118,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
### L7 影子与正式切换准备(2026-07-22) ### L7 影子与正式切换准备(2026-07-22)
- 纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。Profile 发布本身只提供紧凑候选;只有唯一命中的 Profile 已完成独立盲测资格(至少 3 样本全通过、管理员批准且 checksum 未漂移)时,才可由该 Profile 的实际解析行零 Provider 建单。 - 纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。Profile 发布本身只提供紧凑候选;只有唯一命中的 Profile 已完成独立盲测资格(至少 1 份样本通过、管理员批准且 checksum 未漂移)时,才可由该 Profile 的实际解析行零 Provider 建单。
- Profile 仍可生成不含 HTML/bbox/token 的紧凑候选供模型参考,并继续执行零 Qty 删除等候选清洗,但未获得 accepted cell 前不能直接生成订单。 - Profile 仍可生成不含 HTML/bbox/token 的紧凑候选供模型参考,并继续执行零 Qty 删除等候选清洗,但未获得 accepted cell 前不能直接生成订单。
- 自动建单只能在质量门禁满足时由 Schema 策略开启;它不依赖 Dify 输入格式开关。 - 自动建单只能在质量门禁满足时由 Schema 策略开启;它不依赖 Dify 输入格式开关。
- L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、Runtime Binding、质量门禁与迁移共 `247 passed`;前端生产构建通过。该记录的历史基线 head 为 `a72f8091a2b8`;当前货代履约链部署必须以 `023a4b5c6d7e` 为唯一 Alembic head,`git diff --check` 通过。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。 - L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、Runtime Binding、质量门禁与迁移共 `247 passed`;前端生产构建通过。该记录的历史基线 head 为 `a72f8091a2b8`;当前货代履约链部署必须以 `023a4b5c6d7e` 为唯一 Alembic head,`git diff --check` 通过。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。
@@ -145,6 +145,8 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
3. 每日试点记录管理员 `GET /api/admin/shipping-notice/order-extraction-runs/health` 的队列、Provider、HXOPS 落库与总时延 P50/P95、失败率、重试与积压;库存 RPA 从配置测试运行记录读取耗时,上传 RPA 从 `ShippingUploadAttempt.started_at/finished_at` 统计。试点累计数据形成正式容量 SLA 前,不提高并发或放开自动建单。 3. 每日试点记录管理员 `GET /api/admin/shipping-notice/order-extraction-runs/health` 的队列、Provider、HXOPS 落库与总时延 P50/P95、失败率、重试与积压;库存 RPA 从配置测试运行记录读取耗时,上传 RPA 从 `ShippingUploadAttempt.started_at/finished_at` 统计。试点累计数据形成正式容量 SLA 前,不提高并发或放开自动建单。
4. 恢复演练在测试环境完成:人为中断 Worker 后重启,确认 stale Job 被恢复、已有 Provider 结果只续做 HXOPS 落库、相同文件重试不重复建单;再从经批准的数据库备份与 RPA 共享目录备份恢复到隔离环境,核对 Artifact、Attempt、Reservation 和审计记录。演练记录必须包含环境、备份时间、操作者、耗时、校验结果及遗留问题;失败时保持自动建单和自动上传关闭。 4. 恢复演练在测试环境完成:人为中断 Worker 后重启,确认 stale Job 被恢复、已有 Provider 结果只续做 HXOPS 落库、相同文件重试不重复建单;再从经批准的数据库备份与 RPA 共享目录备份恢复到隔离环境,核对 Artifact、Attempt、Reservation 和审计记录。演练记录必须包含环境、备份时间、操作者、耗时、校验结果及遗留问题;失败时保持自动建单和自动上传关闭。
**货代上传结果未知(工程 Review)**:RPA trigger 已成功投递而回调超时时,不得把它等同于“上传失败”或自动重传。HXOPS 将对应 `ShippingUploadAttempt` 标记为 `timed_out`、保留 Artifact 为 `uploading`、保留 Reservation 为 `artifact_reserved`,并将任务置于 `upload_result_unknown` 检查点;该检查点不提供 `retry_upload`。货代迟到成功回调可正常收口;普通网络错误仍保持未知。只有货代明确拒绝(`freight_rejected:`)并由授权操作者执行 Artifact 作废,才可释放预约单进入下一轮核验。该机制不要求修改 Dify 画布。
**阶段 7 Dify 手工配置补充**:上述容量、健康、恢复和备份均由 HXOPS/运维执行,Dify 不增加限流、重试、循环、恢复或自动建单节点。完成真实影子与试点验收后,仍需按本节既有唯一 Manifest 检查清单手工检查画布并留存截图/运行记录。 **阶段 7 Dify 手工配置补充**:上述容量、健康、恢复和备份均由 HXOPS/运维执行,Dify 不增加限流、重试、循环、恢复或自动建单节点。完成真实影子与试点验收后,仍需按本节既有唯一 Manifest 检查清单手工检查画布并留存截图/运行记录。
### 阶段 3 客户指纹绑定与冻结(2026-07-22) ### 阶段 3 客户指纹绑定与冻结(2026-07-22)
@@ -2179,6 +2181,7 @@ API 层
- PDF 工具栏采用左侧编辑操作、中间上一页/页码/下一页、右侧缩放操作的固定布局;页码输入支持大页数文档直接跳转,页面标记只按精确页码渲染。 - PDF 工具栏采用左侧编辑操作、中间上一页/页码/下一页、右侧缩放操作的固定布局;页码输入支持大页数文档直接跳转,页面标记只按精确页码渲染。
- 历史 `all_pages` 草稿缺少原始页码时按第 1 页恢复,重新保存后统一写入 `exact_page + page_no`,避免第 1 页标记泄漏到第 2 页。 - 历史 `all_pages` 草稿缺少原始页码时按第 1 页恢复,重新保存后统一写入 `exact_page + page_no`,避免第 1 页标记泄漏到第 2 页。
- 自动标记优先从 PDF 原生文字层补齐字符坐标与页面尺寸,仅在原生文字层为空时调用 OCR;补证结果仍属于待人工复核证据。 - 自动标记优先从 PDF 原生文字层补齐字符坐标与页面尺寸,仅在原生文字层为空时调用 OCR;补证结果仍属于待人工复核证据。
- 字段规则新增 `auto_annotation_enabled`:已启用且授权 PDF/OCR 坐标的 Header 字段才生成订单级标签/值框,Line 字段才按 `display_name + aliases` 的唯一精确表头命中生成表头字段框和对应明细字段框。默认仅业务必填、自动建单关键或具名业务用途字段参与;其余可选字段默认关闭,管理员可按需启用。关闭后保留字段的抽取语义和既有模板绑定,但不再参与新的自动标记。多个字段共享同一别名、同一重建列承载多个标签或无精确命中时一律保留未绑定候选并进入人工复核。
- 物理行和字段框描述可重复应用的行版式:横向边界用于字段取值;一个物理行包含多条视觉子行时,系统使用首条 `line_no` 锚定明细的真实字符坐标,将字段框校准到实际视觉 band(未标注的描述/备注行仍计入序号),再把同一纵向字段组按严格单调顺序对齐到后续明细。记录出现额外换行时,以 X 命中、注册解析器和有限字段形态辅助选择;最佳候选不唯一时字段留空并记录 `coordinate_profile_field_band_ambiguous`,禁止静默猜测。该机制避免父框留白、行距变化和可变换行造成错位,也防止料号尾数污染数量、单位或日期;覆盖父行全高的旧字段框和多 `row_offset` 模板继续按原兼容链路解析。 - 物理行和字段框描述可重复应用的行版式:横向边界用于字段取值;一个物理行包含多条视觉子行时,系统使用首条 `line_no` 锚定明细的真实字符坐标,将字段框校准到实际视觉 band(未标注的描述/备注行仍计入序号),再把同一纵向字段组按严格单调顺序对齐到后续明细。记录出现额外换行时,以 X 命中、注册解析器和有限字段形态辅助选择;最佳候选不唯一时字段留空并记录 `coordinate_profile_field_band_ambiguous`,禁止静默猜测。该机制避免父框留白、行距变化和可变换行造成错位,也防止料号尾数污染数量、单位或日期;覆盖父行全高的旧字段框和多 `row_offset` 模板继续按原兼容链路解析。
- 翻页时只选择当前页表格;当前页没有表格时清空表格与局部候选上下文,禁止复用上一页坐标证据。 - 翻页时只选择当前页表格;当前页没有表格时清空表格与局部候选上下文,禁止复用上一页坐标证据。
- 局部候选可返回多条逻辑明细;右侧按“候选 → 字段清单”展示,参与当前标注的字段统一按绑定 Schema 顺序排列,字段名表头不计入候选条数。 - 局部候选可返回多条逻辑明细;右侧按“候选 → 字段清单”展示,参与当前标注的字段统一按绑定 Schema 顺序排列,字段名表头不计入候选条数。
+7 -1
View File
@@ -34,6 +34,12 @@
# 智能HR请假管理功能清单 # 智能HR请假管理功能清单
## 订单级字段标注与确定性提取
- 已实现独立订单字段标注域(订单字段标签、值区、单行/多行模式、停止标签),与明细表头和物理行完全分离。
- 已实现页级 PDF/OCR 字符证据的锚点定位与相对区域读取;仅唯一原生坐标、格式校验通过的结果可标记 `confirmed`,其余进入 `needs_review` 或 `unavailable`。
- 已实现盲测订单字段真值、发布门禁与运行时合并;Dify 不得覆盖 `confirmed` 字段,配置说明见 `docs/features/shipping-notice/order-extraction-workflow-dify-guide.md`。
## 货代订单抽取异步 Run(阶段 0–5 已完成) ## 货代订单抽取异步 Run(阶段 0–5 已完成)
- 已实现 `ShippingOrderExtractionRun` 领域生命周期、不可变 Intake/Document/Schema 输入快照和服务端幂等键。 - 已实现 `ShippingOrderExtractionRun` 领域生命周期、不可变 Intake/Document/Schema 输入快照和服务端幂等键。
@@ -652,7 +658,7 @@
| 订单抽取紧凑结构化候选 | 已实现 / 质量验收延期 | 唯一 Manifest、Run 冻结、无 HTML/bbox/token 泄漏、accepted 字段锁与完整表零 Provider;人工真值及 95% 指标暂缓。 | | 订单抽取紧凑结构化候选 | 已实现 / 质量验收延期 | 唯一 Manifest、Run 冻结、无 HTML/bbox/token 泄漏、accepted 字段锁与完整表零 Provider;人工真值及 95% 指标暂缓。 |
| 订单抽取 L6 证据裁决与诊断 | 已实现 / 质量验收延期 | Observation 证据引用、纯文本无 cell 转复核、同 Document 强身份关联、冲突阻断、Candidate/UI 原因码和脱敏管理员追溯率诊断。 | | 订单抽取 L6 证据裁决与诊断 | 已实现 / 质量验收延期 | Observation 证据引用、纯文本无 cell 转复核、同 Document 强身份关联、冲突阻断、Candidate/UI 原因码和脱敏管理员追溯率诊断。 |
| 订单抽取 L7 启用准备 | 工程完成 / 阶段未验收 | 删除 Profile/纯文本零 Provider;自动建单要求当前 Schema 的已批准质量批次,并冻结到 Run、Worker 再核验。人工真值延期时无批准批次可选,自动建单保持关闭;影子 Run 和实际 Dify 验收尚缺。 | | 订单抽取 L7 启用准备 | 工程完成 / 阶段未验收 | 删除 Profile/纯文本零 Provider;自动建单要求当前 Schema 的已批准质量批次,并冻结到 Run、Worker 再核验。人工真值延期时无批准批次可选,自动建单保持关闭;影子 Run 和实际 Dify 验收尚缺。 |
| 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布前必须存在训练样本;盲测与 annotation/training 完全独立,常规模板至少 3 份、无表头至少 5 份,包含多明细及所需跨页续页样本;全通过、批准并原子提升到正式 checksum 后,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 | | 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布前必须存在训练样本;盲测与 annotation/training 完全独立,所有模板仅需 1 份样本,仍须包含多明细及所需跨页续页证据;通过、批准并原子提升到正式 checksum 后,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 |
| 订单客户指纹与 Snapshot 绑定 | 已实现 | Bill-to/Ship-to 原文与正式客户分层保存;Bill-to 人工确认须有理由并生成规则版本化指纹,冻结只采纳该确认结果并固化客户简码。 | | 订单客户指纹与 Snapshot 绑定 | 已实现 | Bill-to/Ship-to 原文与正式客户分层保存;Bill-to 人工确认须有理由并生成规则版本化指纹,冻结只采纳该确认结果并固化客户简码。 |
- 订单文档模板支持大页数 PDF 的上一页/页码跳转/下一页导航、顶部撤销/重做/复制/删除/保存/缩放工具栏、可折叠紧凑标注工具轨,以及按页隔离的区域标记;复制支持 `Ctrl/Cmd+D`,删除支持 `Delete/Backspace`,配置侧栏不再重复放置操作入口。 - 订单文档模板支持大页数 PDF 的上一页/页码跳转/下一页导航、顶部撤销/重做/复制/删除/保存/缩放工具栏、可折叠紧凑标注工具轨,以及按页隔离的区域标记;复制支持 `Ctrl/Cmd+D`,删除支持 `Delete/Backspace`,配置侧栏不再重复放置操作入口。
- 订单文档模板自动标记支持原生 PDF 坐标优先补证、扫描件 OCR 兜底、页面尺寸修复和可重复多物理行版式候选重算。 - 订单文档模板自动标记支持原生 PDF 坐标优先补证、扫描件 OCR 兜底、页面尺寸修复和可重复多物理行版式候选重算。
+2 -1
View File
@@ -19,6 +19,7 @@
- L3 将 parser revision 提升为 `v3`。扫描 PDF 直接适配 RapidOCR 多边形坐标,OCR cell 必须同时通过 OpenCV 网格和全部非空 cell 文本一致性;EML HTML 只保留清洗后的 table DOM,并用逻辑网格表达 rowspan/colspan。OCR/HTML 均固定 needs_review,原始 OCR 响应、页面图、主动 HTML 和临时表格片段不入库或 Dify。 - 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 不参与当前确定性执行。 - L4 新增 layout.v1→冻结 Schema 映射层,复用现有 HTML Grid 安全规则并保留真实 cell/token evidence。Run snapshot 升级为 v3并冻结内部 `layout_schema_candidates`;跨页只读显式 continuation。Manifest 强制剥离布局及映射候选,needs_review 不参与当前确定性执行。
- 订单坐标 Profile v2 的真相是 `document_match + table_regions[]`:每个表区保存相对区域、独立 `header_layouts[]`、连续的 `line_layouts[]`、字段区域到稳定 `field_id + field_code` 的绑定、受控解析器、排除/终止和跨页规则。表头只参与建议、校准和匹配,不能决定字段;所有区域为 `0..1` 相对坐标,越界、正面积重叠、重复明细字段和错序物理行由后端拒绝。 - 订单坐标 Profile v2 的真相是 `document_match + table_regions[]`:每个表区保存相对区域、独立 `header_layouts[]`、连续的 `line_layouts[]`、字段区域到稳定 `field_id + field_code` 的绑定、受控解析器、排除/终止和跨页规则。表头只参与建议、校准和匹配,不能决定字段;所有区域为 `0..1` 相对坐标,越界、正面积重叠、重复明细字段和错序物理行由后端拒绝。
- 订单级字段使用与表格层严格分离的 `order_field_layouts[]`:以稳定 `field_id/field_code` 绑定 Header Schema,按页域唯一定位标签锚点,再投影相对值区。页级 PDF 原生字符优先、扫描页 OCR 兜底;无证据、重复锚点、格式异常和固定坐标回退均不得 `confirmed`。确定性结果保存页号、锚点/值框和字符索引;盲测逐字段校验人工真值,Dify 只能补充未确认字段。
- 多行明细使用 `line_layouts[]` 表达任意连续 N 行版式:`row_offset=0` 固定为 main,后续为 continuation;每行独立保存区域和字段区域。字段只可绑定 Schema 显式允许的 `pdf_coordinate`/`ocr_coordinate` 来源,字段 ID 由后端重写,浏览器不能提交自由正则、脚本或 Prompt。 - 多行明细使用 `line_layouts[]` 表达任意连续 N 行版式:`row_offset=0` 固定为 main,后续为 continuation;每行独立保存区域和字段区域。字段只可绑定 Schema 显式允许的 `pdf_coordinate`/`ocr_coordinate` 来源,字段 ID 由后端重写,浏览器不能提交自由正则、脚本或 Prompt。
- 坐标版式建议先按自适应 y-band 分组物理行,再以左侧行号识别逻辑明细起点;相同 `row_offset` 的文本片段按相对 x 中心聚类,以相邻中心中点生成边界。接口只自动绑定确定性的 `line_no`,其他字段仍由管理员根据列示例确认,建议状态固定为 `needs_review`。 - 坐标版式建议先按自适应 y-band 分组物理行,再以左侧行号识别逻辑明细起点;相同 `row_offset` 的文本片段按相对 x 中心聚类,以相邻中心中点生成边界。接口只自动绑定确定性的 `line_no`,其他字段仍由管理员根据列示例确认,建议状态固定为 `needs_review`。
- `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、v2 定义校验值、完整定义、checksum 和乐观锁。同一模板只允许一个 published 版本;后续阶段的 Run 将冻结唯一匹配结果、Profile checksum、坐标证据和完整定义,发布/退役不会改变历史运行。 - `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、v2 定义校验值、完整定义、checksum 和乐观锁。同一模板只允许一个 published 版本;后续阶段的 Run 将冻结唯一匹配结果、Profile checksum、坐标证据和完整定义,发布/退役不会改变历史运行。
@@ -1264,7 +1265,7 @@ Dify
- L6 Observation 通过 `evidence_ref + evidence_metadata_json` 保存文本、邮件头或 layout cell 证据身份。旧纯文本表格解析器只做候选检测,不再进入 verified Observation;accepted layout 仅按同 Document 强身份关联。 - L6 Observation 通过 `evidence_ref + evidence_metadata_json` 保存文本、邮件头或 layout cell 证据身份。旧纯文本表格解析器只做候选检测,不再进入 verified Observation;accepted layout 仅按同 Document 强身份关联。
- L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。 - L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。
- L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。 - L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。
- **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_document_profile_test_suites/samples/runs` 保存草稿/发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。盲测集以 `profile_id + profile_checksum` 唯一绑定;模板保存改变草稿定义 hash 后,旧草稿集转为 `superseded`,新定义必须新建盲测集。发布事务校验至少 1 份训练样本、与 annotation/training 完全独立的 1 份盲测样本、至少 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 或凭据。 - **坐标 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。 - **受控坐标预览**:页面授权写入 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、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。 - **订单客户指纹与冻结门禁**:`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、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。
@@ -13,12 +13,17 @@ import type {
OrderProfileSampleDocument, OrderProfileSampleDocument,
CoordinateReconstructionPreview, CoordinateReconstructionPreview,
CoordinateReconstructionSuggestion, CoordinateReconstructionSuggestion,
OrderFieldLayoutSuggestionResponse,
OrderFieldValuePreviewResponse,
CoordinateReconstructionSettings, CoordinateReconstructionSettings,
OrderProfileSampleIntake, OrderProfileSampleIntake,
OrderProfileSamplePreview, OrderProfileSamplePreview,
OrderProfilePreviewPages, OrderProfilePreviewPages,
OrderProfileBoundSample, OrderProfileBoundSample,
OrderProfilePageTextCandidates, OrderProfilePageTextCandidates,
OrderProfileBlindTestInput,
OrderProfileBlindTestAvailableSample,
OrderProfileBlindTestCandidate,
OrderProfileTestSuite, OrderProfileTestSuite,
ShippingOrderDocumentProfile, ShippingOrderDocumentProfile,
} from '../types/shipping-order-document-profile.types'; } from '../types/shipping-order-document-profile.types';
@@ -73,16 +78,38 @@ export const previewOrderProfileCoordinateReconstruction = (
/** 从冻结字符坐标建议全部或指定物理行;rowOffset 省略时保持原有全量识别。 */ /** 从冻结字符坐标建议全部或指定物理行;rowOffset 省略时保持原有全量识别。 */
export const suggestOrderProfileCoordinateReconstruction = ( export const suggestOrderProfileCoordinateReconstruction = (
documentId: number, tableId: string, rowOffset?: number, documentId: number, tableId: string, rowOffset?: number, schemaVersionId?: number,
) => ) =>
requestJson<CoordinateReconstructionSuggestion>( requestJson<CoordinateReconstructionSuggestion>(
'/api/admin/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', { '/api/admin/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', {
method: 'POST', method: 'POST',
body: JSON.stringify({ document_id: documentId, table_id: tableId, row_offset: rowOffset }), body: JSON.stringify({ document_id: documentId, table_id: tableId, row_offset: rowOffset, schema_version_id: schemaVersionId }),
...jsonAuth(), ...jsonAuth(),
}, },
); );
/** 根据冻结 Header Schema 与整页字符坐标建议订单字段锚点和值区;结果始终需要人工确认。 */
export const suggestOrderProfileOrderFields = (
documentId: number, schemaVersionId: number, pageNo: number,
) => requestJson<OrderFieldLayoutSuggestionResponse>(
'/api/admin/shipping-notice/order-document-profile-samples/order-field-suggestions', {
method: 'POST',
body: JSON.stringify({ document_id: documentId, schema_version_id: schemaVersionId, page_no: pageNo }),
...jsonAuth(),
},
);
/** 按当前未保存的工作台定义重读订单单头字段值,供刷新后的复核面板恢复证据。 */
export const previewOrderProfileOrderFieldValues = (
documentId: number, schemaVersionId: number, pageNo: number, definition: ShippingOrderDocumentProfile['definition'],
) => requestJson<OrderFieldValuePreviewResponse>(
'/api/admin/shipping-notice/order-document-profile-samples/order-field-values-preview', {
method: 'POST',
body: JSON.stringify({ document_id: documentId, schema_version_id: schemaVersionId, page_no: pageNo, definition }),
...jsonAuth(),
},
);
/** 为扫描 PDF 生成 OCR 坐标证据;随后仍必须由管理员审核重建网格。 */ /** 为扫描 PDF 生成 OCR 坐标证据;随后仍必须由管理员审核重建网格。 */
export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, tableId: string) => export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, tableId: string) =>
requestJson<{ document_id: number; table_id: string; source: 'pdf' | 'ocr' }>( requestJson<{ document_id: number; table_id: string; source: 'pdf' | 'ocr' }>(
@@ -199,10 +226,29 @@ export const createOrderProfileTestSuite = (profileId: number) => requestJson<Or
); );
/** 将一份独立样本的人工真值写入当前盲测集。 */ /** 将一份独立样本的人工真值写入当前盲测集。 */
export const addOrderProfileTestSample = (suiteId: number, payload: { document_id: number; table_id: string; expected_rows: Array<Record<string, unknown>> }) => requestJson<OrderProfileTestSuite>( export const addOrderProfileTestSample = (suiteId: number, payload: OrderProfileBlindTestInput) => requestJson<OrderProfileTestSuite>(
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/samples`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/samples`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
); );
/** 从草稿盲测集中移除错误或不再适用的样本;批准后的测试集由服务端拒绝修改。 */
export const removeOrderProfileTestSample = (suiteId: number, sampleId: number) => requestJson<OrderProfileTestSuite>(
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/samples/${sampleId}`,
{ method: 'DELETE', ...jsonAuth() },
);
/** 列出未参与当前模板标注/训练且可用于盲测的受控订单样本。 */
export const listOrderProfileBlindTestAvailableSamples = (suiteId: number) => requestJson<{ samples: OrderProfileBlindTestAvailableSample[] }>(
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/available-samples`, auth(),
);
/** 自动运行独立样本,候选仅供管理员勾选复核,尚未写入真值。 */
export const previewOrderProfileBlindTestCandidate = (suiteId: number, payload: { document_id: number; table_id: string }) => requestJson<OrderProfileBlindTestCandidate>(
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/candidate-preview`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 将逐项勾选和必要更正值转为既有盲测真值。 */
export const confirmOrderProfileBlindTestReviews = (suiteId: number, payload: { document_id: number; table_id: string; row_reviews: unknown[]; order_field_reviews: Record<string, unknown> }) => requestJson<OrderProfileTestSuite>(
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/reviewed-samples`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 执行当前盲测集,任何字段或行数差异都保留为发布阻断。 */ /** 执行当前盲测集,任何字段或行数差异都保留为发布阻断。 */
export const executeOrderProfileTestSuite = (suiteId: number) => requestJson<OrderProfileTestSuite>( export const executeOrderProfileTestSuite = (suiteId: number) => requestJson<OrderProfileTestSuite>(
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/execute`, { method: 'POST', ...jsonAuth() }, `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/execute`, { method: 'POST', ...jsonAuth() },
@@ -188,7 +188,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
</header> </header>
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div> <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-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"> <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.drawOrderAnchor')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderAnchorTool') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawOrderField')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderField') }}</span></button><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.headerTool') }}</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.lineTool') }}</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.fieldTool') }}</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.exclusionTool') }}</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" /> <img :src="imageUrl" alt="Controlled document page preview" draggable="false" />
<div <div
v-for="region in regions" v-for="region in regions"
@@ -216,6 +216,8 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.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; } .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; } .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-header_field { z-index: 2; border: 1.5px solid #f59e0b; background: rgb(245 158 11 / .08); }.region-header_field .region-label,.region-header_field .resize-handle { background: #b45309; }
.region-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }.region-order_field .region-label,.region-order_field .resize-handle { background: #15803d; }
.region-order_anchor { z-index: 2; border: 1.5px solid #a855f7; background: rgb(168 85 247 / .08); }.region-order_anchor .region-label,.region-order_anchor .resize-handle { background: #7e22ce; }
.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; } .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; } .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-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; }
@@ -446,6 +446,10 @@ const contextSourceIsActive = (config: ShippingOrderFieldConfig): boolean => {
return optionId !== undefined && activeContextOptions.value.some((item) => item.id === optionId); return optionId !== undefined && activeContextOptions.value.some((item) => item.id === optionId);
}; };
/** 新增或历史字段缺少显式开关时,仅对业务必填或建单关键字段建议自动标记。 */
const defaultAutoAnnotationEnabled = (config: ShippingOrderFieldConfig): boolean =>
config.required === true || config.auto_create_key_field === true || (config.business_purpose || 'general') !== 'general';
/** 切换确定性来源时同步校正暴露策略,禁止页面提交后端未声明的组合。 */ /** 切换确定性来源时同步校正暴露策略,禁止页面提交后端未声明的组合。 */
const syncContextExposurePolicy = (config: ShippingOrderFieldConfig): void => { const syncContextExposurePolicy = (config: ShippingOrderFieldConfig): void => {
const option = activeContextOptions.value.find((item) => item.id === contextOptionId(config)); const option = activeContextOptions.value.find((item) => item.id === contextOptionId(config));
@@ -490,6 +494,11 @@ const syncDraftFields = (): void => {
}), }),
context_provider_option_id: contextOptionId(byId.get(field.id) || {} as ShippingOrderFieldConfig), context_provider_option_id: contextOptionId(byId.get(field.id) || {} as ShippingOrderFieldConfig),
enabled: byId.has(field.id) ? byId.get(field.id)?.enabled !== false : false, enabled: byId.has(field.id) ? byId.get(field.id)?.enabled !== false : false,
// Older snapshots did not store this switch. Do not flood a new workbench
// annotation with all optional fields; administrators can opt them in later.
auto_annotation_enabled: byId.has(field.id)
? byId.get(field.id)?.auto_annotation_enabled ?? defaultAutoAnnotationEnabled(byId.get(field.id)!)
: defaultAutoAnnotationEnabled(byId.get(field.id) || {} as ShippingOrderFieldConfig),
})) }))
.sort((left, right) => (globalSequence.get(left.field_id) || 0) - (globalSequence.get(right.field_id) || 0)) .sort((left, right) => (globalSequence.get(left.field_id) || 0) - (globalSequence.get(right.field_id) || 0))
.map((config, index) => ({ ...config, sequence: index + 1 })); .map((config, index) => ({ ...config, sequence: index + 1 }));
@@ -1007,8 +1016,8 @@ onMounted(async () => {
</template> </template>
</template> </template>
</div> </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> <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.auto_annotation_enabled" :disabled="isReadOnly || !selectedDraftField?.enabled" type="checkbox"><span><strong>{{ t('admin.shippingOrderSchema.autoAnnotationEnabled') }}</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 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> <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.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> </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> <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> </template>
@@ -10,8 +10,11 @@ export type OrderProfileEvidenceLevel = 'coordinate' | 'ocr_coordinate';
export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate'; export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate';
export interface OrderProfileRelativeRegion { x0: number; y0: number; x1: number; y1: number; } 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 OrderProfileAnchorRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
export interface OrderProfileAnchorRule { anchor_id: string; text: string; aliases?: 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 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 OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; } export interface 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 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 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 }>; }
@@ -33,6 +36,8 @@ export interface ShippingOrderDocumentProfile {
contract_version: 'order_coordinate_profile.v2'; contract_version: 'order_coordinate_profile.v2';
document_match: OrderProfileDocumentMatch; document_match: OrderProfileDocumentMatch;
table_regions: OrderProfileTableRegion[]; table_regions: OrderProfileTableRegion[];
order_field_layouts?: OrderProfileOrderFieldLayout[];
draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[];
/** 阶段 3 前允许旧页面只读显示历史 v1 版本;新写入不会产生这些字段。 */ /** 阶段 3 前允许旧页面只读显示历史 v1 版本;新写入不会产生这些字段。 */
row_structure?: 'preserved' | 'unsupported_row_structure'; row_structure?: 'preserved' | 'unsupported_row_structure';
drop_zero_qty?: boolean; drop_zero_qty?: boolean;
@@ -68,18 +73,47 @@ export interface OrderProfileTestSuite {
profile_checksum: string; profile_checksum: string;
status: 'draft' | 'approved' | 'superseded'; status: 'draft' | 'approved' | 'superseded';
sample_count: number; sample_count: number;
samples: Array<{
id: number;
document_id: number;
table_id: string;
filename: string;
page_no: number;
}>;
approved_at?: string | null; approved_at?: string | null;
latest_run?: { status: 'passed' | 'failed'; sample_count: number; passed_sample_count: number; failure_codes: string[] } | null; latest_run?: { status: 'passed' | 'failed'; sample_count: number; passed_sample_count: number; failure_codes: string[] } | null;
} }
export interface OrderProfileBlindTestInput {
document_id: number;
table_id: string;
expected_rows: Array<Record<string, unknown>>;
expected_order_fields?: Record<string, unknown>;
}
/** 盲测工作台的独立候选样本;已排除当前模板的标注和训练证据。 */
export interface OrderProfileBlindTestAvailableSample { document_id: number; table_id: string; page_no: number; filename: string; }
export interface OrderProfileBlindTestCandidate {
document_id: number; table_id: string; rows: Array<Record<string, unknown>>;
order_fields: Array<{ field_code: string; value: unknown; status: 'confirmed' | 'needs_review' | 'unavailable'; page_no: number | null; issues: string[] }>;
}
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */ /** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
export interface OrderProfileCanvasRegion { export interface OrderProfileCanvasRegion {
id: string; id: string;
kind: 'header' | 'header_field' | 'line' | 'field' | 'exclusion'; kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion';
label: string; label: string;
region: OrderProfileRelativeRegion; region: OrderProfileRelativeRegion;
fieldCode?: string | null; fieldCode?: string | null;
parentId?: string | null; parentId?: string | null;
/** 订单字段锚点与值框共享持久 layout_id,避免误归属明细物理行。 */
orderFieldId?: string | null;
/** 订单字段的读取形态;仅用于订单字段值框,保存时转为受控 value_mode。 */
valueMode?: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor';
/** 自动标记时从同一值框读取的待复核文本,仅用于工作台即时展示。 */
suggestedValue?: string | null;
/** 自动建议实际使用的坐标证据来源,保存时映射到最小证据等级。 */
evidenceSource?: 'pdf_coordinate' | 'ocr_coordinate';
stopAnchorText?: string | null;
/** 标记所属文档页;画布切页时仅渲染当前页的区域。 */ /** 标记所属文档页;画布切页时仅渲染当前页的区域。 */
pageNo: number; pageNo: number;
} }
@@ -186,7 +220,44 @@ export interface CoordinateSubrowSuggestion extends CoordinateSubrowLayout {
export interface CoordinateReconstructionSuggestion { export interface CoordinateReconstructionSuggestion {
table_id: string; table_id: string;
table_region?: OrderProfileRelativeRegion; table_region?: OrderProfileRelativeRegion;
header_regions?: Array<{ region: OrderProfileRelativeRegion; text: string; fields: Array<{ region: OrderProfileRelativeRegion; text: string }> }>; header_regions?: Array<{ region: OrderProfileRelativeRegion; text: string; fields: Array<{ region: OrderProfileRelativeRegion; text: string; field_code?: string | null; confidence?: 'exact_alias' | 'ambiguous' | 'unmapped' }> }>;
subrow_layouts: CoordinateSubrowSuggestion[]; subrow_layouts: CoordinateSubrowSuggestion[];
status: 'needs_review'; status: 'needs_review';
} }
/** 自动标记的订单级字段候选;仅供管理员复核,不是已绑定模板定义。 */
export interface OrderFieldLayoutSuggestion {
field_id: string;
field_code: string;
display_name: string;
source: 'pdf_coordinate' | 'ocr_coordinate';
status: 'suggested' | 'ambiguous' | 'unavailable';
binding_status?: 'bound' | 'unbound';
issue: string | null;
anchor_text?: string;
anchor_region?: OrderProfileRelativeRegion;
value_region?: OrderProfileRelativeRegion;
value_mode?: 'right_of_anchor' | 'below_anchor';
/** 与建议值框使用同一字符证据读取的待复核文本。 */
suggested_value?: string;
}
export interface OrderFieldLayoutSuggestionResponse {
page_no: number;
order_field_candidates: OrderFieldLayoutSuggestion[];
issues: string[];
status: 'needs_review';
}
export interface OrderFieldValuePreview {
field_id: string;
field_code: string;
value: string | null;
status: 'confirmed' | 'needs_review' | 'unavailable';
page_no: number | null;
}
export interface OrderFieldValuePreviewResponse {
page_no: number;
fields: OrderFieldValuePreview[];
}
@@ -31,6 +31,8 @@ export interface ShippingOrderFieldConfig {
minimum_confidence?: number | null; minimum_confidence?: number | null;
required: boolean; required: boolean;
aliases: string[]; aliases: string[];
/** 是否允许该字段按别名参与模板工作台的自动框选。 */
auto_annotation_enabled?: boolean;
normalizer_key: string; normalizer_key: string;
validator_keys: string[]; validator_keys: string[];
enum_options: string[]; enum_options: string[];
@@ -753,6 +753,22 @@ export const updateShippingNoticeCandidate = (
}, },
); );
export const promoteShippingNoticeCandidate = (candidateNo: string) =>
requestJson<import('../types/shipping.api.types').ShippingNoticeCandidateResponse>(
`/api/workspace/shipping-notice/candidates/${encodeURIComponent(candidateNo)}/promote`,
{ method: 'POST' },
);
export const rejectShippingNoticeCandidate = (candidateNo: string, reason?: string) =>
requestJson<import('../types/shipping.api.types').ShippingNoticeCandidateResponse>(
`/api/workspace/shipping-notice/candidates/${encodeURIComponent(candidateNo)}/reject`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason: reason || undefined }),
},
);
export const resolveShippingNoticeCandidateDuplicate = ( export const resolveShippingNoticeCandidateDuplicate = (
candidateNo: string, candidateNo: string,
action: string, action: string,
@@ -25,9 +25,10 @@ const props = defineProps<{
canForceCreate: boolean; canForceCreate: boolean;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
select: [candidateNo: string, selected: boolean];
update: [candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void]; update: [candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void];
resolveDuplicate: [candidateNo: string, action: ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void]; resolveDuplicate: [candidateNo: string, action: ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void];
promote: [candidateNo: string, done: (success: boolean) => void];
reject: [candidateNo: string, done: (success: boolean) => void];
}>(); }>();
const { t } = useI18n(); const { t } = useI18n();
@@ -186,6 +187,14 @@ function submitForceCreate(candidateNo: string): void {
}, },
); );
} }
/** 发起后端决定的人工采纳或驳回;UI 不自行推导履约资格。 */
function decideCandidate(candidateNo: string, action: 'promote' | 'reject'): void {
submittingCandidateNo.value = candidateNo;
const done = () => { submittingCandidateNo.value = ''; };
if (action === 'promote') emit('promote', candidateNo, done);
else emit('reject', candidateNo, done);
}
</script> </script>
<template> <template>
@@ -196,19 +205,13 @@ function submitForceCreate(candidateNo: string): void {
</div> </div>
<div v-for="candidate in candidates" :key="candidate.candidateNo" class="rounded-lg border border-default bg-surface-soft p-2 text-xs"> <div v-for="candidate in candidates" :key="candidate.candidateNo" class="rounded-lg border border-default bg-surface-soft p-2 text-xs">
<div class="flex flex-wrap items-center gap-2"> <div class="flex flex-wrap items-center gap-2">
<input
type="checkbox"
:checked="candidate.selected"
:disabled="!!candidate.consumedTaskId"
@change="emit('select', candidate.candidateNo, ($event.target as HTMLInputElement).checked)"
/>
<span class="font-mono text-primary">{{ candidate.candidateNo }}</span> <span class="font-mono text-primary">{{ candidate.candidateNo }}</span>
<span class="font-medium text-secondary">PO {{ candidate.poNumber || '-' }}</span> <span class="font-medium text-secondary">PO {{ candidate.poNumber || '-' }}</span>
<span v-if="candidate.documentFilename" class="max-w-40 truncate text-muted">{{ candidate.documentFilename }}</span> <span v-if="candidate.documentFilename" class="max-w-40 truncate text-muted">{{ candidate.documentFilename }}</span>
<span :class="candidate.validationStatus === 'ready' ? 'text-emerald-700' : 'text-amber-700'"> <span :class="candidate.candidateStatus === 'accepted' ? 'text-emerald-700' : 'text-amber-700'">
{{ candidate.validationStatus === 'ready' ? t('chat.shippingCandidateReady') : t('chat.shippingCandidateNeedsReview') }} {{ candidate.candidateStatus === 'accepted' ? (candidate.acceptanceMode === 'automatic' ? t('chat.shippingCandidateAutoAccepted') : t('chat.shippingCandidateAccepted')) : (candidate.candidateStatus === 'rejected' ? t('chat.shippingCandidateRejected') : t('chat.shippingCandidateNeedsReview')) }}
</span> </span>
<button type="button" class="ml-auto text-brand-700 hover:underline" @click="startEdit(candidate.candidateNo)"> <button v-if="candidate.actionButtons.includes('edit')" type="button" class="ml-auto text-brand-700 hover:underline" @click="startEdit(candidate.candidateNo)">
{{ t('chat.shippingCandidateEdit') }} {{ t('chat.shippingCandidateEdit') }}
</button> </button>
</div> </div>
@@ -308,6 +311,10 @@ function submitForceCreate(candidateNo: string): void {
<div v-else-if="candidate.duplicateResolution" class="mt-1 text-muted"> <div v-else-if="candidate.duplicateResolution" class="mt-1 text-muted">
{{ t('chat.shippingCandidateDuplicateResolved', { action: candidate.duplicateResolution.action }) }} {{ t('chat.shippingCandidateDuplicateResolved', { action: candidate.duplicateResolution.action }) }}
</div> </div>
<div v-if="candidate.actionButtons.includes('promote') || candidate.actionButtons.includes('reject')" class="mt-2 flex gap-2">
<button v-if="candidate.actionButtons.includes('promote')" type="button" class="rounded bg-brand-600 px-2 py-1 text-white disabled:opacity-50" :disabled="submittingCandidateNo === candidate.candidateNo" @click="decideCandidate(candidate.candidateNo, 'promote')">{{ t('chat.shippingCandidatePromote') }}</button>
<button v-if="candidate.actionButtons.includes('reject')" type="button" class="rounded border border-default px-2 py-1 text-secondary disabled:opacity-50" :disabled="submittingCandidateNo === candidate.candidateNo" @click="decideCandidate(candidate.candidateNo, 'reject')">{{ t('chat.shippingCandidateReject') }}</button>
</div>
<div v-if="editingCandidateNo === candidate.candidateNo" class="mt-2 space-y-2"> <div v-if="editingCandidateNo === candidate.candidateNo" class="mt-2 space-y-2">
<label class="block"> <label class="block">
<span class="text-muted">{{ t('chat.shippingCandidatePoNumber') }}</span> <span class="text-muted">{{ t('chat.shippingCandidatePoNumber') }}</span>
@@ -175,11 +175,6 @@ const shippingOrderExtractionReviewAttachments = computed<ShippingNoticePendingA
})); }));
}); });
/** 审核操作仍走统一 Candidate API,成功后由页面同步更新当前 Run 卡快照。 */
const selectOrderExtractionCandidate = async (candidateNo: string, selected: boolean) => {
await shippingHandlers.selectCandidate(candidateNo, selected);
};
const updateOrderExtractionCandidate = async ( const updateOrderExtractionCandidate = async (
candidateNo: string, candidateNo: string,
businessSummary: Record<string, unknown>, businessSummary: Record<string, unknown>,
@@ -188,6 +183,14 @@ const updateOrderExtractionCandidate = async (
await shippingHandlers.updateCandidate(candidateNo, businessSummary, done); await shippingHandlers.updateCandidate(candidateNo, businessSummary, done);
}; };
const promoteOrderExtractionCandidate = async (candidateNo: string, done: (success: boolean) => void) => {
await shippingHandlers.promoteCandidate(candidateNo, done);
};
const rejectOrderExtractionCandidate = async (candidateNo: string, done: (success: boolean) => void) => {
await shippingHandlers.rejectCandidate(candidateNo, done);
};
const resolveOrderExtractionCandidateDuplicate = async ( const resolveOrderExtractionCandidateDuplicate = async (
candidateNo: string, candidateNo: string,
action: import('../../types/shipping.types').ShippingDuplicateAction, action: import('../../types/shipping.types').ShippingDuplicateAction,
@@ -940,9 +943,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
:key="attachment.intakeNo" :key="attachment.intakeNo"
:attachment="attachment" :attachment="attachment"
:can-force-create="false" :can-force-create="false"
@select="selectOrderExtractionCandidate"
@update="updateOrderExtractionCandidate" @update="updateOrderExtractionCandidate"
@resolve-duplicate="resolveOrderExtractionCandidateDuplicate" @resolve-duplicate="resolveOrderExtractionCandidateDuplicate"
@promote="promoteOrderExtractionCandidate"
@reject="rejectOrderExtractionCandidate"
/> />
</div> </div>
<LeaveMessageBlock <LeaveMessageBlock
@@ -17,7 +17,8 @@ export interface ShippingMessageHandlers {
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>; removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
retryOrderExtractionRun: (runNo: string) => Promise<boolean>; retryOrderExtractionRun: (runNo: string) => Promise<boolean>;
reparseOrderExtractionRun: (runNo: string, reason: 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other') => Promise<boolean>; reparseOrderExtractionRun: (runNo: string, reason: 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other') => Promise<boolean>;
selectCandidate: (candidateNo: string, selected: boolean) => Promise<void>;
updateCandidate: (candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void) => Promise<void>; updateCandidate: (candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void) => Promise<void>;
resolveCandidateDuplicate: (candidateNo: string, action: import('../../types/shipping.types').ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void) => Promise<void>; resolveCandidateDuplicate: (candidateNo: string, action: import('../../types/shipping.types').ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void) => Promise<void>;
promoteCandidate: (candidateNo: string, done: (success: boolean) => void) => Promise<void>;
rejectCandidate: (candidateNo: string, done: (success: boolean) => void) => Promise<void>;
} }
@@ -1045,6 +1045,34 @@ export function useChatShipping(options: UseChatShippingOptions) {
} }
}; };
/** 人工采纳 Dify 兜底 Candidate,并刷新当前 Run 的审核快照。 */
const promoteShippingCandidate = async (candidateNo: string, done?: (success: boolean) => void) => {
try {
await shippingIntakes.promoteCandidate(candidateNo);
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
msg.success(t('chat.shippingCandidatePromoted'));
done?.(true);
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
done?.(false);
}
};
/** 人工驳回 Dify 兜底 Candidate,并刷新当前 Run 的审核快照。 */
const rejectShippingCandidate = async (candidateNo: string, done?: (success: boolean) => void) => {
try {
await shippingIntakes.rejectCandidate(candidateNo);
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
msg.success(t('chat.shippingCandidateRejected'));
done?.(true);
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
done?.(false);
}
};
const { const {
handleShippingAutoUploadFile, handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch, handleShippingAutoUploadNoticeBatch,
@@ -1484,6 +1512,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
setShippingCandidateSelected, setShippingCandidateSelected,
updateShippingCandidateSummary, updateShippingCandidateSummary,
resolveShippingCandidateDuplicate, resolveShippingCandidateDuplicate,
promoteShippingCandidate,
rejectShippingCandidate,
showShippingDuplicateDialog, showShippingDuplicateDialog,
showShippingCustomerDialog, showShippingCustomerDialog,
shippingCustomerOptions, shippingCustomerOptions,
@@ -37,9 +37,10 @@ type ShippingHandlerSource = Pick<
| 'removeShippingParseReviewLine' | 'removeShippingParseReviewLine'
| 'retryOrderExtractionRun' | 'retryOrderExtractionRun'
| 'reparseOrderExtractionRun' | 'reparseOrderExtractionRun'
| 'setShippingCandidateSelected'
| 'updateShippingCandidateSummary' | 'updateShippingCandidateSummary'
| 'resolveShippingCandidateDuplicate' | 'resolveShippingCandidateDuplicate'
| 'promoteShippingCandidate'
| 'rejectShippingCandidate'
>; >;
type TrainingHandlerSource = ReturnType<typeof useTrainingWorkspace>; type TrainingHandlerSource = ReturnType<typeof useTrainingWorkspace>;
@@ -75,9 +76,10 @@ export function createShippingMessageHandlers(shipping: ShippingHandlerSource):
removeLine: shipping.removeShippingParseReviewLine, removeLine: shipping.removeShippingParseReviewLine,
retryOrderExtractionRun: shipping.retryOrderExtractionRun, retryOrderExtractionRun: shipping.retryOrderExtractionRun,
reparseOrderExtractionRun: shipping.reparseOrderExtractionRun, reparseOrderExtractionRun: shipping.reparseOrderExtractionRun,
selectCandidate: shipping.setShippingCandidateSelected,
updateCandidate: shipping.updateShippingCandidateSummary, updateCandidate: shipping.updateShippingCandidateSummary,
resolveCandidateDuplicate: shipping.resolveShippingCandidateDuplicate, resolveCandidateDuplicate: shipping.resolveShippingCandidateDuplicate,
promoteCandidate: shipping.promoteShippingCandidate,
rejectCandidate: shipping.rejectShippingCandidate,
}; };
} }
@@ -24,6 +24,8 @@ import {
listActiveShippingNoticeIntakes, listActiveShippingNoticeIntakes,
resolveShippingNoticeDuplicate, resolveShippingNoticeDuplicate,
resolveShippingNoticeCandidateDuplicate, resolveShippingNoticeCandidateDuplicate,
promoteShippingNoticeCandidate,
rejectShippingNoticeCandidate,
retryShippingNoticeIntake, retryShippingNoticeIntake,
updateShippingNoticeCandidate, updateShippingNoticeCandidate,
} from '@/features/chat/api/shipping.api'; } from '@/features/chat/api/shipping.api';
@@ -171,6 +173,10 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
poNumber: remote.po_number || undefined, poNumber: remote.po_number || undefined,
documentFilename: remote.primary_document_filename || undefined, documentFilename: remote.primary_document_filename || undefined,
validationStatus: remote.validation_status, validationStatus: remote.validation_status,
candidateStatus: remote.candidate_status || 'provisional',
acceptanceMode: remote.acceptance_mode || undefined,
extractionSource: remote.extraction_source || undefined,
actionButtons: Array.isArray(remote.action_buttons) ? remote.action_buttons : [],
selected: Boolean(remote.selected), selected: Boolean(remote.selected),
conflicts: remote.conflicts || [], conflicts: remote.conflicts || [],
missingFields: Array.isArray(remote.missing_fields) ? remote.missing_fields.map((item) => String(item)) : [], missingFields: Array.isArray(remote.missing_fields) ? remote.missing_fields.map((item) => String(item)) : [],
@@ -539,6 +545,24 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
} }
}; };
/** 人工采纳已复核的 Dify Candidate;后端决定是否已满足履约门禁。 */
const promoteCandidate = async (candidateNo: string) => {
const remote = await promoteShippingNoticeCandidate(candidateNo);
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, { candidates: (attachment.candidates || []).map((item) => item.candidateNo === candidateNo ? mapServerCandidate(remote) : item) });
}
};
/** 人工驳回无需进入履约的 Dify Candidate。 */
const rejectCandidate = async (candidateNo: string, reason?: string) => {
const remote = await rejectShippingNoticeCandidate(candidateNo, reason);
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, { candidates: (attachment.candidates || []).map((item) => item.candidateNo === candidateNo ? mapServerCandidate(remote) : item) });
}
};
/** 保存单个 Candidate 的重复处理决策。 */ /** 保存单个 Candidate 的重复处理决策。 */
const resolveCandidateDuplicate = async ( const resolveCandidateDuplicate = async (
candidateNo: string, candidateNo: string,
@@ -594,6 +618,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
resolveCandidateDuplicate, resolveCandidateDuplicate,
setCandidateSelected, setCandidateSelected,
updateCandidateSummary, updateCandidateSummary,
promoteCandidate,
rejectCandidate,
getParsedIntakeNos, getParsedIntakeNos,
markOrderExtractionStarted, markOrderExtractionStarted,
rollbackOrderExtractionStarted, rollbackOrderExtractionStarted,
@@ -676,6 +676,10 @@ export interface ShippingNoticeCandidateResponse {
primary_document_filename?: string | null; primary_document_filename?: string | null;
po_number?: string | null; po_number?: string | null;
validation_status: string; validation_status: string;
candidate_status?: 'provisional' | 'accepted' | 'rejected' | 'expired';
acceptance_mode?: 'automatic' | 'manual' | 'legacy' | null;
extraction_source?: string | null;
action_buttons?: string[];
selected: boolean; selected: boolean;
conflicts?: Array<Record<string, unknown>>; conflicts?: Array<Record<string, unknown>>;
missing_fields?: string[]; missing_fields?: string[];
@@ -78,6 +78,10 @@ export interface ShippingNoticeCandidate {
poNumber?: string; poNumber?: string;
documentFilename?: string; documentFilename?: string;
validationStatus: string; validationStatus: string;
candidateStatus: 'provisional' | 'accepted' | 'rejected' | 'expired';
acceptanceMode?: 'automatic' | 'manual' | 'legacy';
extractionSource?: string;
actionButtons: string[];
selected: boolean; selected: boolean;
conflicts: Array<Record<string, unknown>>; conflicts: Array<Record<string, unknown>>;
missingFields?: string[]; missingFields?: string[];
+46 -6
View File
@@ -264,6 +264,7 @@
"autoCreationEnabled": "Enable automatic task creation", "autoCreationEnabled": "Enable automatic task creation",
"autoCreationSaved": "Automatic task creation setting saved", "autoCreationSaved": "Automatic task creation setting saved",
"autoCreateKeyField": "Task-creation key field", "autoCreateKeyField": "Task-creation key field",
"autoAnnotationEnabled": "Use for automatic annotation",
"minimumKeyFieldConfidence": "Minimum key-field confidence", "minimumKeyFieldConfidence": "Minimum key-field confidence",
"unnamedField": "Unnamed field", "unnamedField": "Unnamed field",
"pendingNameField": "Field awaiting name {number}", "pendingNameField": "Field awaiting name {number}",
@@ -2629,18 +2630,37 @@
"title": "Blind test", "title": "Blind test",
"samples": "Samples: {count} · {status}", "samples": "Samples: {count} · {status}",
"notRun": "not run", "notRun": "not run",
"approvedHint": "This blind test is approved; no further run or approval is needed.",
"selectIndependentSample": "Select independent sample",
"selectSamplePlaceholder": "Select an order not used to annotate this template",
"noIndependentSamples": "No independent sample is available. Upload and parse another matching order first.",
"reviewHint": "Mark every item correct or incorrect. Provide a correction for incorrect items; unreviewed items cannot be added.",
"row": "Line {index}",
"correct": "Correct",
"incorrect": "Incorrect",
"confirmReview": "Confirm review and add",
"correctionInvalid": "A line correction must be a JSON field object.",
"expectedRows": "Human truth (JSON array)", "expectedRows": "Human truth (JSON array)",
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]", "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.", "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.", "expectedRowsInvalid": "Truth must be a JSON array containing at least one non-empty line object.",
"trainingAdded": "Current training sample bound", "expectedOrderFields": "Order field truth (JSON object)",
"addTrainingSample": "Add training sample", "expectedOrderFieldsPlaceholder": "{\"customer_po\": \"PO-45001\"}",
"addCurrentSample": "Add current blind sample", "expectedOrderFieldsHint": "When order fields are configured, enter a human-confirmed value for every field.",
"expectedOrderFieldsInvalid": "Order field truth must be a JSON object.",
"trainingAdded": "Current training sample bound",
"addTrainingSample": "Add training sample",
"addedSamples": "Added blind-test samples",
"addedSamplesHint": "Draft samples can be removed; approved samples remain auditable.",
"removeSample": "Remove sample",
"sampleRemoved": "Blind-test sample removed",
"addCurrentSample": "Add current blind sample",
"run": "Run", "run": "Run",
"approve": "Approve" "approve": "Approve"
}, },
"workbench": { "workbench": {
"intro": "Drag evidence regions on a controlled document page; saved definitions contain no HTML or storage URL.", "boundHistoricalSchema": "bound historical version",
"intro": "Drag evidence regions on a controlled document page; saved definitions contain no HTML or storage URL.",
"openCanvas": "Create draft and open canvas", "openCanvas": "Create draft and open canvas",
"loadingPage": "Loading page...", "loadingPage": "Loading page...",
"canvasZoom": "Page zoom", "canvasZoom": "Page zoom",
@@ -2664,6 +2684,8 @@
"regionSuggestionReady": "Review the generated row and column marks, then confirm field bindings before saving.", "regionSuggestionReady": "Review the generated row and column marks, then confirm field bindings before saving.",
"unboundColumn": "Unbound column {count}", "unboundColumn": "Unbound column {count}",
"drawHeader": "Draw header", "drawHeader": "Draw header",
"drawOrderField": "Draw order field",
"drawOrderAnchor": "Draw order field label",
"drawLine": "Draw physical line", "drawLine": "Draw physical line",
"drawField": "Draw field", "drawField": "Draw field",
"drawExclusion": "Draw exclusion", "drawExclusion": "Draw exclusion",
@@ -2691,6 +2713,21 @@
"undo": "Undo", "undo": "Undo",
"redo": "Redo", "redo": "Redo",
"header": "Header", "header": "Header",
"orderField": "Order field",
"orderFieldCandidates": "Order header fields",
"unbound": "Unbound",
"noAnnotatedOrderFields": "No order header fields are annotated on this page.",
"suggestedValue": "Detected value",
"orderAnchor": "Order field label",
"orderAnchorTool": "Field label",
"headerTool": "Table header",
"lineTool": "Detail row",
"fieldTool": "Detail field",
"exclusionTool": "Exclusion area",
"orderFieldValueMode": "Read mode",
"orderFieldStopAnchor": "Stop label",
"orderFieldStopAnchorPlaceholder": "For example, SHIP TO",
"orderFieldModes": { "singleLine": "Single line", "rightOfAnchor": "Right of label", "belowAnchor": "Below label", "multiLine": "Multiple lines" },
"matchCurrentHeader": "Match current header", "matchCurrentHeader": "Match current header",
"matchAllHeaders": "Match all headers", "matchAllHeaders": "Match all headers",
"confirmHeaderBinding": "Confirm “{text}” as {field}", "confirmHeaderBinding": "Confirm “{text}” as {field}",
@@ -2722,6 +2759,8 @@
"regionLabels": { "regionLabels": {
"header": "Header {count}", "header": "Header {count}",
"header_field": "Header field {count}", "header_field": "Header field {count}",
"order_field": "Order field {count}",
"order_anchor": "Order field label {count}",
"line": "Physical line {count}", "line": "Physical line {count}",
"field": "Field {count}", "field": "Field {count}",
"exclusion": "Exclusion {count}" "exclusion": "Exclusion {count}"
@@ -2731,7 +2770,8 @@
"table": "Select a table on the current page.", "table": "Select a table on the current page.",
"line": "Add at least one main line layout.", "line": "Add at least one main line layout.",
"field": "Bind at least one line field.", "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." "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.",
"orderFieldStopAnchor": "A multi-line order field requires a stop label."
} }
} }
} }
+6
View File
@@ -110,6 +110,12 @@
"shippingCandidateCount": "{count} orders", "shippingCandidateCount": "{count} orders",
"shippingCandidateReady": "Ready", "shippingCandidateReady": "Ready",
"shippingCandidateNeedsReview": "Needs review", "shippingCandidateNeedsReview": "Needs review",
"shippingCandidateAutoAccepted": "Approved template accepted automatically",
"shippingCandidateAccepted": "Accepted after review",
"shippingCandidateRejected": "Rejected",
"shippingCandidatePromote": "Accept and continue",
"shippingCandidatePromoted": "Order candidate accepted",
"shippingCandidateReject": "Reject",
"shippingCandidateEdit": "Edit", "shippingCandidateEdit": "Edit",
"shippingCandidateSave": "Save changes", "shippingCandidateSave": "Save changes",
"shippingCandidateConflictCount": "{count} field conflicts must be corrected before task creation.", "shippingCandidateConflictCount": "{count} field conflicts must be corrected before task creation.",
+46 -6
View File
@@ -263,6 +263,7 @@
"autoCreationEnabled": "เปิดใช้การสร้างงานอัตโนมัติ", "autoCreationEnabled": "เปิดใช้การสร้างงานอัตโนมัติ",
"autoCreationSaved": "บันทึกการตั้งค่าการสร้างงานอัตโนมัติแล้ว", "autoCreationSaved": "บันทึกการตั้งค่าการสร้างงานอัตโนมัติแล้ว",
"autoCreateKeyField": "ฟิลด์สำคัญสำหรับการสร้างงาน", "autoCreateKeyField": "ฟิลด์สำคัญสำหรับการสร้างงาน",
"autoAnnotationEnabled": "ใช้สำหรับการทำเครื่องหมายอัตโนมัติ",
"minimumKeyFieldConfidence": "ความเชื่อมั่นขั้นต่ำของฟิลด์สำคัญ", "minimumKeyFieldConfidence": "ความเชื่อมั่นขั้นต่ำของฟิลด์สำคัญ",
"unnamedField": "ฟิลด์ไม่มีชื่อ", "unnamedField": "ฟิลด์ไม่มีชื่อ",
"pendingNameField": "ฟิลด์ที่รอตั้งชื่อ {number}", "pendingNameField": "ฟิลด์ที่รอตั้งชื่อ {number}",
@@ -2497,18 +2498,37 @@
"title": "การทดสอบแบบปิดบัง", "title": "การทดสอบแบบปิดบัง",
"samples": "ตัวอย่าง: {count} · {status}", "samples": "ตัวอย่าง: {count} · {status}",
"notRun": "ยังไม่ดำเนินการ", "notRun": "ยังไม่ดำเนินการ",
"approvedHint": "การทดสอบแบบปิดบังนี้ได้รับอนุมัติแล้ว ไม่ต้องดำเนินการหรืออนุมัติซ้ำ",
"selectIndependentSample": "เลือกตัวอย่างอิสระ",
"selectSamplePlaceholder": "เลือกคำสั่งซื้อที่ไม่ได้ใช้ทำเครื่องหมายเทมเพลตนี้",
"noIndependentSamples": "ไม่มีตัวอย่างอิสระ โปรดอัปโหลดและแยกข้อมูลคำสั่งซื้อประเภทเดียวกันอีกฉบับก่อน",
"reviewHint": "ทำเครื่องหมายแต่ละรายการว่าถูกต้องหรือผิดพลาด หากผิดพลาดต้องระบุค่าที่แก้ไข รายการที่ยังไม่ตรวจทานจะเพิ่มไม่ได้",
"row": "รายการ {index}",
"correct": "ถูกต้อง",
"incorrect": "ผิดพลาด",
"confirmReview": "ยืนยันการตรวจทานและเพิ่ม",
"correctionInvalid": "ค่าที่แก้ไขของรายการต้องเป็นออบเจ็กต์ฟิลด์ JSON",
"expectedRows": "ข้อมูลจริงที่ยืนยันโดยคน (อาร์เรย์ JSON)", "expectedRows": "ข้อมูลจริงที่ยืนยันโดยคน (อาร์เรย์ JSON)",
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]", "expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
"expectedRowsHint": "กรอกข้อมูลจริงของรายการที่มนุษย์ยืนยันอย่างน้อยหนึ่งรายการ ห้ามคัดลอกผลลัพธ์ตัวเลือก.", "expectedRowsHint": "กรอกข้อมูลจริงของรายการที่มนุษย์ยืนยันอย่างน้อยหนึ่งรายการ ห้ามคัดลอกผลลัพธ์ตัวเลือก.",
"expectedRowsInvalid": "ข้อมูลจริงต้องเป็นอาร์เรย์ JSON ที่มีอ็อบเจ็กต์รายการที่ไม่ว่างอย่างน้อยหนึ่งรายการ.", "expectedRowsInvalid": "ข้อมูลจริงต้องเป็นอาร์เรย์ JSON ที่มีอ็อบเจ็กต์รายการที่ไม่ว่างอย่างน้อยหนึ่งรายการ.",
"trainingAdded": "ผูกตัวอย่างการฝึกปัจจุบันแล้ว", "expectedOrderFields": "ข้อมูลจริงของฟิลด์คำสั่งซื้อ (ออบเจ็กต์ JSON)",
"addTrainingSample": "เพิ่มตัวอย่างการฝึก", "expectedOrderFieldsPlaceholder": "{\"customer_po\": \"PO-45001\"}",
"addCurrentSample": "เพิ่มตัวอย่างทดสอบปัจจุบัน", "expectedOrderFieldsHint": "เมื่อกำหนดฟิลด์คำสั่งซื้อ ต้องกรอกค่าที่ยืนยันโดยมนุษย์สำหรับทุกฟิลด์.",
"expectedOrderFieldsInvalid": "ข้อมูลจริงของฟิลด์คำสั่งซื้อต้องเป็นออบเจ็กต์ JSON.",
"trainingAdded": "ผูกตัวอย่างการฝึกปัจจุบันแล้ว",
"addTrainingSample": "เพิ่มตัวอย่างการฝึก",
"addedSamples": "ตัวอย่างการทดสอบที่เพิ่มแล้ว",
"addedSamplesHint": "ลบได้ในฉบับร่าง; หลังอนุมัติจะเก็บบันทึกการตรวจสอบไว้",
"removeSample": "ลบตัวอย่าง",
"sampleRemoved": "ลบตัวอย่างการทดสอบแล้ว",
"addCurrentSample": "เพิ่มตัวอย่างทดสอบปัจจุบัน",
"run": "ดำเนินการ", "run": "ดำเนินการ",
"approve": "อนุมัติ" "approve": "อนุมัติ"
}, },
"workbench": { "workbench": {
"intro": "ลากพื้นที่หลักฐานบนหน้าเอกสารที่ควบคุมไว้ คำนิยามที่บันทึกไม่มี HTML หรือ URL ที่เก็บข้อมูล", "boundHistoricalSchema": "เวอร์ชันประวัติที่ผูกไว้",
"intro": "ลากพื้นที่หลักฐานบนหน้าเอกสารที่ควบคุมไว้ คำนิยามที่บันทึกไม่มี HTML หรือ URL ที่เก็บข้อมูล",
"openCanvas": "สร้างฉบับร่างและเปิดผืนงาน", "openCanvas": "สร้างฉบับร่างและเปิดผืนงาน",
"loadingPage": "กำลังโหลดหน้า...", "loadingPage": "กำลังโหลดหน้า...",
"canvasZoom": "การซูมหน้า", "canvasZoom": "การซูมหน้า",
@@ -2532,6 +2552,8 @@
"regionSuggestionReady": "สร้างเครื่องหมายแถวและคอลัมน์เพื่อการตรวจทานแล้ว โปรดยืนยันการผูกฟิลด์ก่อนบันทึก", "regionSuggestionReady": "สร้างเครื่องหมายแถวและคอลัมน์เพื่อการตรวจทานแล้ว โปรดยืนยันการผูกฟิลด์ก่อนบันทึก",
"unboundColumn": "คอลัมน์ที่ยังไม่ผูก {count}", "unboundColumn": "คอลัมน์ที่ยังไม่ผูก {count}",
"drawHeader": "วาดหัวตาราง", "drawHeader": "วาดหัวตาราง",
"drawOrderField": "วาดฟิลด์คำสั่งซื้อ",
"drawOrderAnchor": "วาดป้ายกำกับฟิลด์คำสั่งซื้อ",
"drawLine": "วาดแถวจริง", "drawLine": "วาดแถวจริง",
"drawField": "วาดฟิลด์", "drawField": "วาดฟิลด์",
"drawExclusion": "วาดพื้นที่ยกเว้น", "drawExclusion": "วาดพื้นที่ยกเว้น",
@@ -2559,6 +2581,21 @@
"undo": "เลิกทำ", "undo": "เลิกทำ",
"redo": "ทำซ้ำ", "redo": "ทำซ้ำ",
"header": "หัวตาราง", "header": "หัวตาราง",
"orderField": "ฟิลด์คำสั่งซื้อ",
"orderFieldCandidates": "ฟิลด์ส่วนหัวคำสั่งซื้อ",
"unbound": "ยังไม่ผูก",
"noAnnotatedOrderFields": "ยังไม่มีการทำเครื่องหมายฟิลด์ส่วนหัวคำสั่งซื้อในหน้านี้",
"suggestedValue": "ค่าที่ตรวจพบ",
"orderAnchor": "ป้ายกำกับฟิลด์คำสั่งซื้อ",
"orderAnchorTool": "ป้ายฟิลด์",
"headerTool": "หัวตาราง",
"lineTool": "แถวรายการ",
"fieldTool": "ฟิลด์รายการ",
"exclusionTool": "พื้นที่ยกเว้น",
"orderFieldValueMode": "โหมดการอ่าน",
"orderFieldStopAnchor": "ป้ายกำกับสิ้นสุด",
"orderFieldStopAnchorPlaceholder": "ตัวอย่าง SHIP TO",
"orderFieldModes": { "singleLine": "บรรทัดเดียว", "rightOfAnchor": "ด้านขวาของป้ายกำกับ", "belowAnchor": "ด้านล่างป้ายกำกับ", "multiLine": "หลายบรรทัด" },
"matchCurrentHeader": "จับคู่หัวตารางปัจจุบัน", "matchCurrentHeader": "จับคู่หัวตารางปัจจุบัน",
"matchAllHeaders": "จับคู่หัวตารางทั้งหมด", "matchAllHeaders": "จับคู่หัวตารางทั้งหมด",
"confirmHeaderBinding": "ยืนยัน “{text}” เป็น {field}", "confirmHeaderBinding": "ยืนยัน “{text}” เป็น {field}",
@@ -2590,6 +2627,8 @@
"regionLabels": { "regionLabels": {
"header": "หัวตาราง {count}", "header": "หัวตาราง {count}",
"header_field": "ฟิลด์หัวตาราง {count}", "header_field": "ฟิลด์หัวตาราง {count}",
"order_field": "ฟิลด์คำสั่งซื้อ {count}",
"order_anchor": "ป้ายกำกับฟิลด์คำสั่งซื้อ {count}",
"line": "แถวจริง {count}", "line": "แถวจริง {count}",
"field": "ฟิลด์ {count}", "field": "ฟิลด์ {count}",
"exclusion": "พื้นที่ยกเว้น {count}" "exclusion": "พื้นที่ยกเว้น {count}"
@@ -2599,7 +2638,8 @@
"table": "เลือกตารางบนหน้าปัจจุบัน", "table": "เลือกตารางบนหน้าปัจจุบัน",
"line": "เพิ่มโครงร่างแถวหลักอย่างน้อยหนึ่งรายการ", "line": "เพิ่มโครงร่างแถวหลักอย่างน้อยหนึ่งรายการ",
"field": "ผูกฟิลด์รายละเอียดอย่างน้อยหนึ่งรายการ", "field": "ผูกฟิลด์รายละเอียดอย่างน้อยหนึ่งรายการ",
"coordinateField": "เวอร์ชันฟิลด์คำสั่งซื้อปัจจุบันไม่มีฟิลด์รายการที่เปิดใช้และได้รับอนุญาตให้ใช้หลักฐานพิกัด PDF โปรดอนุญาตในเทมเพลตฟิลด์คำสั่งซื้อก่อนสร้างโปรไฟล์" "coordinateField": "เวอร์ชันฟิลด์คำสั่งซื้อปัจจุบันไม่มีฟิลด์รายการที่เปิดใช้และได้รับอนุญาตให้ใช้หลักฐานพิกัด PDF โปรดอนุญาตในเทมเพลตฟิลด์คำสั่งซื้อก่อนสร้างโปรไฟล์",
"orderFieldStopAnchor": "ฟิลด์คำสั่งซื้อหลายบรรทัดต้องมีป้ายกำกับสิ้นสุด"
} }
} }
} }
+6
View File
@@ -110,6 +110,12 @@
"shippingCandidateCount": "คำสั่งซื้อ {count} รายการ", "shippingCandidateCount": "คำสั่งซื้อ {count} รายการ",
"shippingCandidateReady": "พร้อมสร้างงาน", "shippingCandidateReady": "พร้อมสร้างงาน",
"shippingCandidateNeedsReview": "ต้องตรวจสอบ", "shippingCandidateNeedsReview": "ต้องตรวจสอบ",
"shippingCandidateAutoAccepted": "ยืนยันอัตโนมัติจากเทมเพลตที่อนุมัติ",
"shippingCandidateAccepted": "ยอมรับหลังการตรวจสอบ",
"shippingCandidateRejected": "ปฏิเสธแล้ว",
"shippingCandidatePromote": "ยอมรับและดำเนินการต่อ",
"shippingCandidatePromoted": "ยอมรับคำสั่งซื้อแล้ว",
"shippingCandidateReject": "ปฏิเสธ",
"shippingCandidateEdit": "แก้ไข", "shippingCandidateEdit": "แก้ไข",
"shippingCandidateSave": "บันทึกการแก้ไข", "shippingCandidateSave": "บันทึกการแก้ไข",
"shippingCandidateConflictCount": "มีข้อมูลขัดแย้ง {count} จุด โปรดแก้ไขก่อนสร้างงาน", "shippingCandidateConflictCount": "มีข้อมูลขัดแย้ง {count} จุด โปรดแก้ไขก่อนสร้างงาน",
+46 -6
View File
@@ -293,6 +293,7 @@
"autoCreationEnabled": "启用自动建单", "autoCreationEnabled": "启用自动建单",
"autoCreationSaved": "自动建单设置已保存", "autoCreationSaved": "自动建单设置已保存",
"autoCreateKeyField": "建单关键字段", "autoCreateKeyField": "建单关键字段",
"autoAnnotationEnabled": "参与自动标记",
"minimumKeyFieldConfidence": "关键字段最低置信度", "minimumKeyFieldConfidence": "关键字段最低置信度",
"unnamedField": "未命名字段", "unnamedField": "未命名字段",
"pendingNameField": "待命名字段 {number}", "pendingNameField": "待命名字段 {number}",
@@ -2607,18 +2608,37 @@
"title": "盲测", "title": "盲测",
"samples": "样本:{count} · {status}", "samples": "样本:{count} · {status}",
"notRun": "未执行", "notRun": "未执行",
"approvedHint": "盲测已批准,无需重复执行或批准。",
"selectIndependentSample": "选择独立样本",
"selectSamplePlaceholder": "请选择未参与当前模板标注的订单",
"noIndependentSamples": "没有可用的独立样本;请先上传并完成解析另一份同类订单。",
"reviewHint": "请逐项勾选正确或错误;标为错误时填写更正值,未勾选不能加入盲测。",
"row": "明细 {index}",
"correct": "正确",
"incorrect": "错误",
"confirmReview": "确认复核并加入盲测",
"correctionInvalid": "明细更正值必须是 JSON 字段对象。",
"expectedRows": "人工真值(JSON 数组)", "expectedRows": "人工真值(JSON 数组)",
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]", "expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
"expectedRowsHint": "请输入至少一条人工确认的明细真值;不能复制候选结果。", "expectedRowsHint": "请输入至少一条人工确认的明细真值;不能复制候选结果。",
"expectedRowsInvalid": "真值必须是至少包含一条非空明细对象的 JSON 数组。", "expectedRowsInvalid": "真值必须是至少包含一条非空明细对象的 JSON 数组。",
"trainingAdded": "已绑定当前训练样本", "expectedOrderFields": "订单字段真值(JSON 对象)",
"addTrainingSample": "添加训练样本", "expectedOrderFieldsPlaceholder": "{\"customer_po\": \"PO-45001\"}",
"addCurrentSample": "添加当前盲测样本", "expectedOrderFieldsHint": "配置订单字段时,必须填写每个字段的人工确认值。",
"expectedOrderFieldsInvalid": "订单字段真值必须是 JSON 对象。",
"trainingAdded": "已绑定当前训练样本",
"addTrainingSample": "添加训练样本",
"addedSamples": "已加入的盲测样本",
"addedSamplesHint": "草稿可移除;批准后保留审计记录。",
"removeSample": "移除样本",
"sampleRemoved": "盲测样本已移除",
"addCurrentSample": "添加当前盲测样本",
"run": "执行", "run": "执行",
"approve": "批准" "approve": "批准"
}, },
"workbench": { "workbench": {
"intro": "在受控文档页面拖拽证据区域;保存定义不含 HTML 或存储地址。", "boundHistoricalSchema": "已绑定历史版本",
"intro": "在受控文档页面拖拽证据区域;保存定义不含 HTML 或存储地址。",
"openCanvas": "创建草稿并打开画布", "openCanvas": "创建草稿并打开画布",
"loadingPage": "正在加载页面…", "loadingPage": "正在加载页面…",
"canvasZoom": "页面缩放", "canvasZoom": "页面缩放",
@@ -2642,6 +2662,8 @@
"regionSuggestionReady": "已生成待复核的行和列标记,请确认字段绑定后保存。", "regionSuggestionReady": "已生成待复核的行和列标记,请确认字段绑定后保存。",
"unboundColumn": "待绑定列 {count}", "unboundColumn": "待绑定列 {count}",
"drawHeader": "绘制表头", "drawHeader": "绘制表头",
"drawOrderField": "绘制订单字段",
"drawOrderAnchor": "绘制订单字段标签",
"drawLine": "绘制物理行", "drawLine": "绘制物理行",
"drawField": "绘制字段", "drawField": "绘制字段",
"drawExclusion": "绘制排除区", "drawExclusion": "绘制排除区",
@@ -2669,6 +2691,21 @@
"undo": "撤销", "undo": "撤销",
"redo": "重做", "redo": "重做",
"header": "表头", "header": "表头",
"orderField": "订单字段",
"orderFieldCandidates": "订单单头字段",
"unbound": "待绑定",
"noAnnotatedOrderFields": "当前页面尚未标记订单单头字段。",
"suggestedValue": "识别值",
"orderAnchor": "订单字段标签",
"orderAnchorTool": "字段标签",
"headerTool": "明细表头",
"lineTool": "明细行项",
"fieldTool": "明细字段",
"exclusionTool": "排除区域",
"orderFieldValueMode": "读取方式",
"orderFieldStopAnchor": "结束标签",
"orderFieldStopAnchorPlaceholder": "例如 SHIP TO",
"orderFieldModes": { "singleLine": "单行", "rightOfAnchor": "标签右侧", "belowAnchor": "标签下方", "multiLine": "多行" },
"matchCurrentHeader": "匹配当前表头", "matchCurrentHeader": "匹配当前表头",
"matchAllHeaders": "匹配全部表头", "matchAllHeaders": "匹配全部表头",
"confirmHeaderBinding": "确认“{text}”绑定为 {field}", "confirmHeaderBinding": "确认“{text}”绑定为 {field}",
@@ -2700,6 +2737,8 @@
"regionLabels": { "regionLabels": {
"header": "表头 {count}", "header": "表头 {count}",
"header_field": "表头字段 {count}", "header_field": "表头字段 {count}",
"order_field": "订单字段 {count}",
"order_anchor": "订单字段标签 {count}",
"line": "物理行 {count}", "line": "物理行 {count}",
"field": "字段 {count}", "field": "字段 {count}",
"exclusion": "排除区 {count}" "exclusion": "排除区 {count}"
@@ -2709,7 +2748,8 @@
"table": "请选择当前页的表格。", "table": "请选择当前页的表格。",
"line": "请至少添加一个主行布局。", "line": "请至少添加一个主行布局。",
"field": "请至少绑定一个明细字段。", "field": "请至少绑定一个明细字段。",
"coordinateField": "当前订单字段版本没有授权 PDF 坐标来源的启用明细字段,请先在订单字段模板中授权后再创建。" "coordinateField": "当前订单字段版本没有授权 PDF 坐标来源的启用明细字段,请先在订单字段模板中授权后再创建。",
"orderFieldStopAnchor": "多行订单字段必须填写结束标签。"
} }
} }
} }
+6
View File
@@ -110,6 +110,12 @@
"shippingCandidateCount": "共 {count} 个订单", "shippingCandidateCount": "共 {count} 个订单",
"shippingCandidateReady": "可建单", "shippingCandidateReady": "可建单",
"shippingCandidateNeedsReview": "需要审核", "shippingCandidateNeedsReview": "需要审核",
"shippingCandidateAutoAccepted": "固定模板已自动确认",
"shippingCandidateAccepted": "已人工采纳",
"shippingCandidateRejected": "已驳回",
"shippingCandidatePromote": "采纳并继续",
"shippingCandidatePromoted": "订单候选已采纳",
"shippingCandidateReject": "驳回",
"shippingCandidateEdit": "修订", "shippingCandidateEdit": "修订",
"shippingCandidateSave": "保存修订", "shippingCandidateSave": "保存修订",
"shippingCandidateConflictCount": "存在 {count} 个字段冲突,请修订后再建单。", "shippingCandidateConflictCount": "存在 {count} 个字段冲突,请修订后再建单。",
+46 -6
View File
@@ -263,6 +263,7 @@
"autoCreationEnabled": "啟用自動建單", "autoCreationEnabled": "啟用自動建單",
"autoCreationSaved": "自動建單設定已儲存", "autoCreationSaved": "自動建單設定已儲存",
"autoCreateKeyField": "建單關鍵欄位", "autoCreateKeyField": "建單關鍵欄位",
"autoAnnotationEnabled": "參與自動標記",
"minimumKeyFieldConfidence": "關鍵欄位最低信心度", "minimumKeyFieldConfidence": "關鍵欄位最低信心度",
"unnamedField": "未命名欄位", "unnamedField": "未命名欄位",
"pendingNameField": "待命名欄位 {number}", "pendingNameField": "待命名欄位 {number}",
@@ -2497,18 +2498,37 @@
"title": "盲測", "title": "盲測",
"samples": "樣本:{count} · {status}", "samples": "樣本:{count} · {status}",
"notRun": "尚未執行", "notRun": "尚未執行",
"approvedHint": "盲測已批准,無須重複執行或批准。",
"selectIndependentSample": "選擇獨立樣本",
"selectSamplePlaceholder": "請選擇未參與目前範本標註的訂單",
"noIndependentSamples": "沒有可用的獨立樣本;請先上傳並完成解析另一份同類訂單。",
"reviewHint": "請逐項勾選正確或錯誤;標示錯誤時填寫更正值,未勾選不能加入盲測。",
"row": "明細 {index}",
"correct": "正確",
"incorrect": "錯誤",
"confirmReview": "確認複核並加入盲測",
"correctionInvalid": "明細更正值必須是 JSON 欄位物件。",
"expectedRows": "人工真值(JSON 陣列)", "expectedRows": "人工真值(JSON 陣列)",
"expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]", "expectedRowsPlaceholder": "[{\"line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
"expectedRowsHint": "請輸入至少一筆人工確認的明細真值;不可複製候選結果。", "expectedRowsHint": "請輸入至少一筆人工確認的明細真值;不可複製候選結果。",
"expectedRowsInvalid": "真值必須是至少包含一個非空明細物件的 JSON 陣列。", "expectedRowsInvalid": "真值必須是至少包含一個非空明細物件的 JSON 陣列。",
"trainingAdded": "已綁定目前訓練樣本", "expectedOrderFields": "訂單欄位真值(JSON 物件)",
"addTrainingSample": "新增訓練樣本", "expectedOrderFieldsPlaceholder": "{\"customer_po\": \"PO-45001\"}",
"addCurrentSample": "新增目前盲測樣本", "expectedOrderFieldsHint": "已設定訂單欄位時,必須填寫每個欄位的人工確認值。",
"expectedOrderFieldsInvalid": "訂單欄位真值必須是 JSON 物件。",
"trainingAdded": "已綁定目前訓練樣本",
"addTrainingSample": "新增訓練樣本",
"addedSamples": "已加入的盲測樣本",
"addedSamplesHint": "草稿可移除;批准後保留稽核記錄。",
"removeSample": "移除樣本",
"sampleRemoved": "盲測樣本已移除",
"addCurrentSample": "新增目前盲測樣本",
"run": "執行", "run": "執行",
"approve": "批准" "approve": "批准"
}, },
"workbench": { "workbench": {
"intro": "在受控文件頁面拖曳證據區域;儲存定義不含 HTML 或儲存位址。", "boundHistoricalSchema": "已綁定歷史版本",
"intro": "在受控文件頁面拖曳證據區域;儲存定義不含 HTML 或儲存位址。",
"openCanvas": "建立草稿並開啟畫布", "openCanvas": "建立草稿並開啟畫布",
"loadingPage": "正在載入頁面…", "loadingPage": "正在載入頁面…",
"canvasZoom": "頁面縮放", "canvasZoom": "頁面縮放",
@@ -2532,6 +2552,8 @@
"regionSuggestionReady": "已產生待複核的行和欄位標記,請確認欄位綁定後儲存。", "regionSuggestionReady": "已產生待複核的行和欄位標記,請確認欄位綁定後儲存。",
"unboundColumn": "待綁定欄 {count}", "unboundColumn": "待綁定欄 {count}",
"drawHeader": "繪製表頭", "drawHeader": "繪製表頭",
"drawOrderField": "繪製訂單欄位",
"drawOrderAnchor": "繪製訂單欄位標籤",
"drawLine": "繪製實體行", "drawLine": "繪製實體行",
"drawField": "繪製欄位", "drawField": "繪製欄位",
"drawExclusion": "繪製排除區", "drawExclusion": "繪製排除區",
@@ -2559,6 +2581,21 @@
"undo": "復原", "undo": "復原",
"redo": "重做", "redo": "重做",
"header": "表頭", "header": "表頭",
"orderField": "訂單欄位",
"orderFieldCandidates": "訂單單頭欄位",
"unbound": "待綁定",
"noAnnotatedOrderFields": "目前頁面尚未標記訂單單頭欄位。",
"suggestedValue": "識別值",
"orderAnchor": "訂單欄位標籤",
"orderAnchorTool": "欄位標籤",
"headerTool": "明細表頭",
"lineTool": "明細行項",
"fieldTool": "明細欄位",
"exclusionTool": "排除區域",
"orderFieldValueMode": "讀取方式",
"orderFieldStopAnchor": "結束標籤",
"orderFieldStopAnchorPlaceholder": "例如 SHIP TO",
"orderFieldModes": { "singleLine": "單行", "rightOfAnchor": "標籤右側", "belowAnchor": "標籤下方", "multiLine": "多行" },
"matchCurrentHeader": "比對目前表頭", "matchCurrentHeader": "比對目前表頭",
"matchAllHeaders": "比對全部表頭", "matchAllHeaders": "比對全部表頭",
"confirmHeaderBinding": "確認「{text}」綁定為 {field}", "confirmHeaderBinding": "確認「{text}」綁定為 {field}",
@@ -2590,6 +2627,8 @@
"regionLabels": { "regionLabels": {
"header": "表頭 {count}", "header": "表頭 {count}",
"header_field": "表頭欄位 {count}", "header_field": "表頭欄位 {count}",
"order_field": "訂單欄位 {count}",
"order_anchor": "訂單欄位標籤 {count}",
"line": "實體行 {count}", "line": "實體行 {count}",
"field": "欄位 {count}", "field": "欄位 {count}",
"exclusion": "排除區 {count}" "exclusion": "排除區 {count}"
@@ -2599,7 +2638,8 @@
"table": "請選擇目前頁面的表格。", "table": "請選擇目前頁面的表格。",
"line": "請至少新增一個主行布局。", "line": "請至少新增一個主行布局。",
"field": "請至少綁定一個明細欄位。", "field": "請至少綁定一個明細欄位。",
"coordinateField": "目前訂單欄位版本沒有授權 PDF 座標來源的啟用明細欄位,請先在訂單欄位範本中授權後再建立。" "coordinateField": "目前訂單欄位版本沒有授權 PDF 座標來源的啟用明細欄位,請先在訂單欄位範本中授權後再建立。",
"orderFieldStopAnchor": "多行訂單欄位必須填寫結束標籤。"
} }
} }
} }
+6
View File
@@ -110,6 +110,12 @@
"shippingCandidateCount": "共 {count} 個訂單", "shippingCandidateCount": "共 {count} 個訂單",
"shippingCandidateReady": "可建單", "shippingCandidateReady": "可建單",
"shippingCandidateNeedsReview": "需要審核", "shippingCandidateNeedsReview": "需要審核",
"shippingCandidateAutoAccepted": "固定範本已自動確認",
"shippingCandidateAccepted": "已人工採納",
"shippingCandidateRejected": "已駁回",
"shippingCandidatePromote": "採納並繼續",
"shippingCandidatePromoted": "訂單候選已採納",
"shippingCandidateReject": "駁回",
"shippingCandidateEdit": "修訂", "shippingCandidateEdit": "修訂",
"shippingCandidateSave": "儲存修訂", "shippingCandidateSave": "儲存修訂",
"shippingCandidateConflictCount": "存在 {count} 個欄位衝突,請修訂後再建單。", "shippingCandidateConflictCount": "存在 {count} 個欄位衝突,請修訂後再建單。",