refactor(shipping-notice): 移除废弃的履约策略模型与相关逻辑
- 删除 `ShippingFulfillmentPolicy` 模型及其依赖,简化字段治理逻辑 - 更新相关服务与 API,确保自动建单策略通过 Schema 草稿管理 - 调整文档与代码注释,反映新的固定履约契约逻辑 - 增强事件审计功能,记录任务状态变化与操作人信息
This commit is contained in:
1 parent
aa8fb2616c
commit
c85997884b
81 files changed
+2625
-1965
No files matched your search
@@ -2,7 +2,7 @@
|
||||
backend/app/api/admin/shipping_order_schema.py
|
||||
|
||||
用途:提供唯一发货订单 Schema、字段目录和版本发布的管理 API。
|
||||
依赖:admin blueprint、require_admin、order_schema.service、fulfillment_policy_registry。
|
||||
依赖:admin blueprint、require_admin、order_schema.service、field_asset_service。
|
||||
逻辑:路由读取管理员身份;字段校验、不可变性与事务由领域服务完成。
|
||||
固定操作默认 Schema STANDARD_SHIPPING_NOTICE;不接受 family_code,不下线表结构。
|
||||
"""
|
||||
@@ -16,7 +16,6 @@ from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.models.shipping_order_schema import ShippingOrderField
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice import fulfillment_policy_registry
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_V1_ADOPTION_CODES
|
||||
|
||||
@@ -38,39 +37,16 @@ def get_shipping_order_schema():
|
||||
return _ok(service.get_state())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/auto-creation-policy', methods=['GET', 'PUT'])
|
||||
@admin_bp.route('/shipping-order-schema/auto-creation-policy', methods=['GET'])
|
||||
@require_admin
|
||||
def shipping_order_auto_creation_policy():
|
||||
"""
|
||||
GET:读取已发布生效的自动建单策略。
|
||||
PUT:已废弃;须写入 Schema 草稿并随版本发布生效。
|
||||
读取已发布生效的自动建单策略。
|
||||
|
||||
说明:写操作已移除。修改须通过 Schema 草稿保存并发布
|
||||
(PUT /shipping-order-schema/versions/:id 携带 auto_creation_policy)。
|
||||
"""
|
||||
if request.method == 'GET':
|
||||
return _ok(service.get_auto_creation_policy())
|
||||
return _ok(service.save_auto_creation_policy(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-fulfillment-policies', methods=['GET', 'POST'])
|
||||
@require_admin
|
||||
def shipping_fulfillment_policies():
|
||||
"""读取履约策略能力目录或创建新的货代履约策略草稿。"""
|
||||
if request.method == 'GET':
|
||||
return _ok(fulfillment_policy_registry.get_state())
|
||||
return _ok(fulfillment_policy_registry.create_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-fulfillment-policies/<int:policy_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_fulfillment_policy(policy_id: int):
|
||||
"""发布指定货代履约策略版本并退役当前版本。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(fulfillment_policy_registry.publish(
|
||||
policy_id, actor_id=_actor_id(), expected_lock_version=payload.get('expected_lock_version'),
|
||||
))
|
||||
return _ok(service.get_auto_creation_policy())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema', methods=['POST'])
|
||||
|
||||
@@ -38,7 +38,6 @@ from app.models.shipping_fulfillment import (
|
||||
ShippingReservation,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.models.shipping_fulfillment_policy import ShippingFulfillmentPolicy
|
||||
from app.models.shipping_order_schema import (
|
||||
ShippingFieldAsset,
|
||||
ShippingOrderExtraction,
|
||||
@@ -250,7 +249,6 @@ __all__ = [
|
||||
'ShippingInventoryVerificationLine',
|
||||
'ShippingExportArtifactLine',
|
||||
'ShippingUploadAttempt',
|
||||
'ShippingFulfillmentPolicy',
|
||||
'ShippingNoticeIntake',
|
||||
'ShippingNoticeDocument',
|
||||
'ShippingNoticeCandidate',
|
||||
|
||||
@@ -271,6 +271,9 @@ class ShippingTaskEvent(Base):
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
after_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
"""
|
||||
models/shipping_fulfillment_policy.py
|
||||
|
||||
用途:保存货代字段能力绑定和不可变履约策略版本。
|
||||
依赖:订单 Schema、users 与 SQLAlchemy Base。
|
||||
逻辑:Schema 负责字段目录;本模型以稳定 field_id 将字段绑定到货代履约能力,并只允许一个 published 策略。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingFulfillmentPolicy(Base):
|
||||
"""货代履约策略版本;published 版本不可修改且由冻结 Snapshot 引用。"""
|
||||
|
||||
__tablename__ = 'shipping_fulfillment_policies'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schema_id', 'policy_code', 'version', name='uq_shipping_fulfillment_policies_version'),
|
||||
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_fulfillment_policies_status'),
|
||||
Index(
|
||||
'uq_shipping_fulfillment_policy_one_published', 'schema_id', unique=True,
|
||||
postgresql_where=text("status = 'published'"), sqlite_where=text("status = 'published'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
|
||||
policy_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
source_policy_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_fulfillment_policies.id'), nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
+18
-12
@@ -156,6 +156,7 @@ class CoordinateProfileLogicalRow(CoordinateReconstructionModel):
|
||||
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
source_row_indices: list[int] = Field(min_length=1)
|
||||
role: Literal['data', 'deleted'] = 'data'
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@@ -228,13 +229,15 @@ def reconstruct_coordinate_profile_rows(
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
initial_fields: dict[str, str] | None = None,
|
||||
initial_next_offset: int = 0,
|
||||
include_deleted: bool = False,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
|
||||
主行必须在其已绑定 ``line_no`` 区域中出现有效行号才启动明细;未满足此条件的
|
||||
视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,避免描述
|
||||
换行、合计或相邻无关表区静默混入当前订单行。
|
||||
换行、合计或相邻无关表区静默混入当前订单行。``include_deleted`` 仅供标注预览
|
||||
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。
|
||||
"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
|
||||
@@ -287,6 +290,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
ordered_layouts=ordered_layouts,
|
||||
termination_rules=termination_rules or [],
|
||||
initial_fields=initial_fields,
|
||||
include_deleted=include_deleted,
|
||||
)
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
@@ -323,10 +327,12 @@ def reconstruct_coordinate_profile_rows(
|
||||
next_offset = initial_next_offset if current is not None else 0
|
||||
current_issues: list[str] = []
|
||||
|
||||
def flush() -> None:
|
||||
def flush(*, role: Literal['data', 'deleted'] = 'data') -> None:
|
||||
nonlocal current, sources, next_offset, current_issues
|
||||
if current is not None and (sources or initial_fields):
|
||||
results.append(CoordinateProfileLogicalRow(fields=current, source_row_indices=sources, issues=current_issues))
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=current, source_row_indices=sources, role=role, issues=current_issues,
|
||||
))
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
@@ -335,10 +341,9 @@ def reconstruct_coordinate_profile_rows(
|
||||
flush()
|
||||
break
|
||||
if _DELETED_PATTERN.fullmatch(re.sub(r'\s+', '', text)):
|
||||
# Deletion markers apply only to the immediately preceding started record.
|
||||
# Do not emit it as a partial row and do not guess an association when no
|
||||
# main row is active.
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
# Preserve deleted evidence for the annotator; downstream consumers use
|
||||
# the role to exclude it rather than silently losing the document row.
|
||||
flush(role='deleted')
|
||||
continue
|
||||
main_values, main_issues = values_for(band, ordered_layouts[0])
|
||||
line_no = re.sub(r'\s+', '', main_values.get('line_no', ''))
|
||||
@@ -370,7 +375,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
current_issues.extend(continuation_issues)
|
||||
next_offset += 1
|
||||
flush()
|
||||
return results
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _reconstruct_relative_y_profile_rows(
|
||||
@@ -380,6 +385,7 @@ def _reconstruct_relative_y_profile_rows(
|
||||
ordered_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]],
|
||||
initial_fields: dict[str, str] | None,
|
||||
include_deleted: bool,
|
||||
) -> list[CoordinateProfileLogicalRow] | None:
|
||||
"""
|
||||
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
|
||||
@@ -429,10 +435,9 @@ def _reconstruct_relative_y_profile_rows(
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
|
||||
record = usable_bands[start:end]
|
||||
if any(_DELETED_PATTERN.fullmatch(re.sub(
|
||||
deleted = any(_DELETED_PATTERN.fullmatch(re.sub(
|
||||
r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)),
|
||||
)) for _, band in record):
|
||||
continue
|
||||
)) for _, band in record)
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
matched_bands, alignment_issues = _match_field_band_groups(
|
||||
@@ -467,9 +472,10 @@ def _reconstruct_relative_y_profile_rows(
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
role='deleted' if deleted else 'data',
|
||||
issues=issues,
|
||||
))
|
||||
return results
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _matches_termination_rule(
|
||||
|
||||
@@ -126,7 +126,7 @@ def _extract_layout(
|
||||
# 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),
|
||||
region=_absolute_value_region(layout=layout, anchor=reference_anchor, width=width, height=height),
|
||||
anchor_bbox=reference_anchor, fallback=False,
|
||||
review_issue='order_field_anchor_text_mismatch',
|
||||
))
|
||||
@@ -142,7 +142,7 @@ def _extract_layout(
|
||||
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,
|
||||
region=_absolute_value_region(layout=layout, anchor=anchor_bbox, width=width, height=height), anchor_bbox=anchor_bbox, fallback=False,
|
||||
))
|
||||
usable = [item for item in results if item.status != 'unavailable']
|
||||
if len(usable) == 1:
|
||||
@@ -165,16 +165,12 @@ def _read_value_region(
|
||||
source: str, region: LayoutBBox, anchor_bbox: LayoutBBox | None, fallback: bool,
|
||||
review_issue: str | None = None,
|
||||
) -> OrderFieldExtraction:
|
||||
"""按视觉行合并值区文字,多行模式先以停止标签截断,再执行 Schema 规范化与校验。
|
||||
"""按管理员值框读取文字,多行模式先以停止标签截断,再执行 Schema 规范化与校验。
|
||||
|
||||
``right_of_anchor`` 使用锚点右侧的同一连续文本段,而不是严格依赖值框的
|
||||
左边界;这能避免标签后的冒号进入值,也能容忍框选末尾少量字符。
|
||||
值框是字段边界的主证据。即使 ``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)]
|
||||
)
|
||||
selected = [(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,
|
||||
@@ -449,6 +445,13 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB
|
||||
)
|
||||
|
||||
|
||||
def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox:
|
||||
"""优先使用管理员画布绝对值框;旧模板才按锚点偏移投影。"""
|
||||
if layout.absolute_value_region is not None:
|
||||
return _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
|
||||
|
||||
def _glyph_bbox(glyph: dict[str, Any]) -> LayoutBBox:
|
||||
"""严格解析一枚冻结 glyph 的 bbox;坏坐标不会被修正后参与提取。"""
|
||||
return LayoutBBox.model_validate(glyph.get('bbox'))
|
||||
|
||||
@@ -110,9 +110,11 @@ class OrderFieldLayout(OrderProfileModel):
|
||||
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.
|
||||
# ``absolute_value_region`` is the authoritative administrator-drawn page box.
|
||||
# ``value_region`` remains only for legacy profiles whose values were stored as
|
||||
# offsets relative to the anchor bbox.
|
||||
value_region: AnchorRelativeRegion | None = None
|
||||
absolute_value_region: RelativeRegion | 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)
|
||||
@@ -132,8 +134,11 @@ class OrderFieldLayout(OrderProfileModel):
|
||||
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')
|
||||
elif (
|
||||
(self.value_region is None) == (self.absolute_value_region is None)
|
||||
or self.fallback_value_region is not None
|
||||
):
|
||||
raise ValueError('anchored order field requires one value region')
|
||||
if self.value_mode == 'multi_line' and not self.stop_anchors:
|
||||
raise ValueError('multi-line order field requires stop anchors')
|
||||
return self
|
||||
@@ -226,6 +231,7 @@ class DraftUnboundOrderFieldLayout(OrderProfileModel):
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor: AnchorRule | None = None
|
||||
value_region: AnchorRelativeRegion | None = None
|
||||
absolute_value_region: RelativeRegion | 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)
|
||||
@@ -237,7 +243,8 @@ class DraftUnboundOrderFieldLayout(OrderProfileModel):
|
||||
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_region=self.value_region, absolute_value_region=self.absolute_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,
|
||||
)
|
||||
|
||||
@@ -274,17 +274,15 @@ def _json_value(value: Any) -> Any:
|
||||
|
||||
|
||||
def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""列出可用于当前盲测的同类专用订单,严格排除建模和已加入盲测的文档。"""
|
||||
"""列出可用于当前盲测的同类专用订单,严格排除建模和已加入盲测的文档。
|
||||
|
||||
列表阶段只读取已存布局摘要,不能为每个候选触发 OCR/坐标证据补齐;用户选中
|
||||
某份样本后,再由候选预览执行完整的坐标和订单字段校验。
|
||||
"""
|
||||
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}
|
||||
@@ -298,18 +296,12 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
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 '',
|
||||
|
||||
@@ -15,7 +15,6 @@ from typing import Any
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
@@ -176,28 +175,7 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]:
|
||||
extra={'template_code': template.template_code},
|
||||
))
|
||||
|
||||
# [STEP 5] 履约策略 field_bindings
|
||||
for policy in ShippingFulfillmentPolicy.query.filter(
|
||||
ShippingFulfillmentPolicy.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
hit_paths: list[str] = []
|
||||
for index, item in enumerate((policy.definition_json or {}).get('field_bindings', []) or []):
|
||||
if isinstance(item, dict) and str(item.get('field_id') or '') == field_id:
|
||||
role = item.get('role') or item.get('purpose') or index
|
||||
hit_paths.append(f'definition.field_bindings[{index}]({role})')
|
||||
if not hit_paths:
|
||||
continue
|
||||
references.append(_ref(
|
||||
kind='fulfillment_policy',
|
||||
object_id=policy.id,
|
||||
display_name=getattr(policy, 'display_name', None) or f'Policy #{policy.id}',
|
||||
status=policy.status,
|
||||
version=getattr(policy, 'version', None),
|
||||
reference_path='; '.join(hit_paths),
|
||||
admin_path='/admin/shipping-inventory?section=fulfillment',
|
||||
))
|
||||
|
||||
# [STEP 6] 客户识别定义 / 规则集
|
||||
# [STEP 5] 客户识别定义 / 规则集
|
||||
for definition in ShippingIdentityDefinition.query.filter_by(
|
||||
context_field_id=field_id, status='active',
|
||||
).all():
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
冻结前履约就绪门禁。
|
||||
|
||||
用途:集中检查订单解析、字段裁决、客户、冲突与库存源状态,阻止不完整订单进入不可编辑快照。
|
||||
依赖:订单 Extraction、字段裁决、冲突门禁、库存源门禁及已发布履约策略。
|
||||
依赖:订单 Extraction、字段裁决、冲突门禁、库存源门禁及固定履约契约。
|
||||
逻辑:order_freeze_service 在创建 Snapshot 前调用;失败统一返回结构化 blocking issues。
|
||||
阶段 5 自动冻结入口接入后,同一服务继续负责把 Run 级自动冻结门禁摘要折叠为冻结阻断原因。
|
||||
"""
|
||||
@@ -22,7 +22,6 @@ def assert_freeze_readiness(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
extraction: ShippingOrderExtraction,
|
||||
policy: Any,
|
||||
configs: dict[str, dict[str, Any]],
|
||||
freeze_mode: str = 'manual',
|
||||
auto_freeze_policy: dict[str, Any] | None = None,
|
||||
@@ -34,7 +33,7 @@ def assert_freeze_readiness(
|
||||
issues.extend(open_field_conflict_issues(task))
|
||||
issues.extend(_auto_freeze_blocking_issues(freeze_mode=freeze_mode, auto_freeze_policy=auto_freeze_policy))
|
||||
|
||||
required = required_field_configs(extraction.schema_version.definition_json or {}, policy)
|
||||
required = required_field_configs(extraction.schema_version.definition_json or {})
|
||||
required_codes = {'reservation_id', 'part_number', 'qty'}
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all()
|
||||
decisions = ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).all()
|
||||
|
||||
@@ -1,268 +1,64 @@
|
||||
"""
|
||||
services/shipping_notice/fulfillment_policy_registry.py
|
||||
|
||||
用途:管理货代字段能力绑定与版本化滚动履约策略。
|
||||
依赖:唯一发货订单 Schema、字段资产、履约策略模型与统一 AppError。
|
||||
逻辑:策略使用稳定 field_id 绑定货代能力;核心能力仅允许系统标准行字段;
|
||||
发布策略前必须存在已发布 Schema,且绑定字段已被采用;
|
||||
冻结只消费当前 published 策略,历史 Snapshot 保存完整策略事实。
|
||||
用途:声明唯一且不可配置的货代滚动履约契约。
|
||||
依赖:订单 Schema 版本定义与统一 ValidationError。
|
||||
逻辑:冻结服务取得核心字段配置并把规则快照写入订单;库存、制单和上传只读取该冻结事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingFulfillmentPolicy, ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
FULFILLMENT_CORE_FIELD_CODES,
|
||||
)
|
||||
|
||||
|
||||
SHIP_AVAILABLE_ROLLING_V1 = 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
_CORE_CAPABILITIES = frozenset({
|
||||
'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity',
|
||||
})
|
||||
_CAPABILITIES = {
|
||||
'fulfillment.reservation_identity': {'scope': 'line', 'value_type': 'string', 'required': True},
|
||||
'fulfillment.part_number': {'scope': 'line', 'value_type': 'string', 'required': True},
|
||||
'fulfillment.quantity': {'scope': 'line', 'value_type': 'decimal', 'required': True},
|
||||
'routing.inventory_source_hint': {'scope': 'line', 'value_type': 'string', 'required': False},
|
||||
}
|
||||
_REQUIRED_CAPABILITIES = frozenset({
|
||||
'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity',
|
||||
})
|
||||
_CANONICAL_FIELD_CODES = {
|
||||
'fulfillment.reservation_identity': 'reservation_id',
|
||||
'fulfillment.part_number': 'part_number',
|
||||
'fulfillment.quantity': 'qty',
|
||||
'routing.inventory_source_hint': 'inventory_source_hint',
|
||||
from app.core.errors import ValidationError
|
||||
FIXED_FULFILLMENT_RULE_CODE = 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
_REQUIRED_FIELDS = {
|
||||
'reservation_id': {'scope': 'line', 'value_type': 'string'},
|
||||
'part_number': {'scope': 'line', 'value_type': 'string'},
|
||||
'qty': {'scope': 'line', 'value_type': 'decimal'},
|
||||
}
|
||||
|
||||
|
||||
def capability_catalog() -> list[dict[str, Any]]:
|
||||
"""返回货代专用能力目录;管理员不能配置自由代码、SQL 或脚本。"""
|
||||
return [{'capability_code': code, **spec} for code, spec in sorted(_CAPABILITIES.items())]
|
||||
|
||||
|
||||
def _schema() -> ShippingOrderSchema:
|
||||
"""
|
||||
读取唯一发货订单 Schema(STANDARD_SHIPPING_NOTICE),兼容历史 SHIPPING_ORDER。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Schema 尚未初始化。
|
||||
"""
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code=DEFAULT_SCHEMA_FAMILY_CODE).one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
raise NotFoundError('Shipping order schema is not initialized', code='SHIPPING.ORDER_SCHEMA_NOT_FOUND')
|
||||
return schema
|
||||
|
||||
|
||||
def _checksum(definition: dict[str, Any]) -> str:
|
||||
"""为策略定义计算稳定摘要,供冻结与审计比对。"""
|
||||
return hashlib.sha256(json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
|
||||
|
||||
def _field_bindings(raw: Any, **_ignored: Any) -> list[dict[str, Any]]:
|
||||
"""校验能力与稳定 field_id 的一对一绑定;核心能力仅允许系统标准行字段。"""
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('field_bindings must be a list', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
seen_capabilities: set[str] = set()
|
||||
seen_fields: set[str] = set()
|
||||
bindings: list[dict[str, Any]] = []
|
||||
for item in raw:
|
||||
if not isinstance(item, dict):
|
||||
raise ValidationError('field binding is invalid', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
capability = str(item.get('capability_code') or '').strip()
|
||||
field_id = str(item.get('field_id') or '').strip()
|
||||
spec = _CAPABILITIES.get(capability)
|
||||
field = db.session.get(ShippingOrderField, field_id) if field_id else None
|
||||
if (
|
||||
spec is None or field is None or field.status != 'active'
|
||||
or field.scope != spec['scope'] or field.value_type != spec['value_type']
|
||||
or capability in seen_capabilities or field_id in seen_fields
|
||||
):
|
||||
raise ValidationError('field capability binding is invalid', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
expected_code = _CANONICAL_FIELD_CODES.get(capability)
|
||||
if capability in _CORE_CAPABILITIES:
|
||||
if field.asset_kind != 'system_standard' or field.field_code not in FULFILLMENT_CORE_FIELD_CODES:
|
||||
raise ValidationError(
|
||||
'Core fulfillment capabilities require system standard line fields',
|
||||
code='SHIPPING.FULFILLMENT_FIELD_INVALID',
|
||||
details={'capability_code': capability, 'field_code': field.field_code},
|
||||
)
|
||||
if expected_code and field.field_code != expected_code:
|
||||
raise ValidationError(
|
||||
'Core fulfillment capability must bind the canonical standard field',
|
||||
code='SHIPPING.FULFILLMENT_FIELD_INVALID',
|
||||
details={'capability_code': capability, 'expected': expected_code},
|
||||
)
|
||||
seen_capabilities.add(capability)
|
||||
seen_fields.add(field_id)
|
||||
bindings.append({
|
||||
'capability_code': capability,
|
||||
'field_id': field.id,
|
||||
'field_code': field.field_code,
|
||||
'scope': field.scope,
|
||||
'value_type': field.value_type,
|
||||
})
|
||||
if _REQUIRED_CAPABILITIES - seen_capabilities:
|
||||
raise ValidationError(
|
||||
'required fulfillment capability bindings are missing',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_INVALID',
|
||||
details={'capabilities': sorted(_REQUIRED_CAPABILITIES - seen_capabilities)},
|
||||
)
|
||||
return sorted(bindings, key=lambda item: item['capability_code'])
|
||||
|
||||
|
||||
def _definition(raw: dict[str, Any], **_ignored: Any) -> dict[str, Any]:
|
||||
"""生成可发布的受控策略定义,策略仅支持滚动发货语义。"""
|
||||
policy_code = str(raw.get('policy_code') or SHIP_AVAILABLE_ROLLING_V1).strip()
|
||||
if policy_code != SHIP_AVAILABLE_ROLLING_V1:
|
||||
raise ValidationError('unsupported fulfillment policy', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
def fixed_rule_definition() -> dict[str, Any]:
|
||||
"""返回代码内置履约规则;管理员和 API 均不能修改此定义。"""
|
||||
return {
|
||||
'policy_code': policy_code,
|
||||
'rule_code': FIXED_FULFILLMENT_RULE_CODE,
|
||||
'fulfillment_mode': 'ship_available_rolling',
|
||||
'requires_confirmed_customer': True,
|
||||
'allows_partial_reservation': False,
|
||||
'field_bindings': _field_bindings(raw.get('field_bindings')),
|
||||
'requires_full_reservation_availability': True,
|
||||
'includes_all_available_reservations': True,
|
||||
}
|
||||
|
||||
|
||||
def list_field_references(field_id: str) -> list[dict[str, Any]]:
|
||||
"""列出仍绑定该字段的履约策略版本,供影响分析使用。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for policy in ShippingFulfillmentPolicy.query.filter(
|
||||
ShippingFulfillmentPolicy.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
bindings = (policy.definition_json or {}).get('field_bindings') or []
|
||||
if any(str(item.get('field_id') or '') == field_id for item in bindings if isinstance(item, dict)):
|
||||
items.append({
|
||||
'kind': 'fulfillment_policy',
|
||||
'policy_id': policy.id,
|
||||
'version': policy.version,
|
||||
'status': policy.status,
|
||||
})
|
||||
return items
|
||||
def fixed_rule_checksum() -> str:
|
||||
"""计算固定规则摘要,便于冻结快照与审计记录稳定比对。"""
|
||||
encoded = json.dumps(fixed_rule_definition(), ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def _payload(policy: ShippingFulfillmentPolicy) -> dict[str, Any]:
|
||||
"""序列化策略版本,前端只能拿到已验证定义与版本状态。"""
|
||||
return {
|
||||
'id': policy.id, 'policy_code': policy.policy_code, 'version': policy.version, 'status': policy.status,
|
||||
'definition': dict(policy.definition_json or {}), 'checksum': policy.checksum,
|
||||
'lock_version': policy.lock_version, 'change_note': policy.change_note,
|
||||
'published_at': policy.published_at.isoformat() if policy.published_at else None,
|
||||
def required_field_configs(definition: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"""从当前 Schema 定义定位固定履约所需的三个标准表身字段并校验类型。"""
|
||||
by_code = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in definition.get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
}
|
||||
|
||||
|
||||
def get_state() -> dict[str, Any]:
|
||||
"""读取唯一发货订单 Schema 的货代履约策略管理状态及当前发布版本。"""
|
||||
schema = _schema()
|
||||
policies = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).all()
|
||||
return {
|
||||
'schema_code': schema.schema_code,
|
||||
'capabilities': capability_catalog(),
|
||||
'policies': [_payload(item) for item in policies],
|
||||
}
|
||||
|
||||
|
||||
def create_draft(
|
||||
raw: dict[str, Any], *, actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建下一策略草稿;未发布策略不得参与冻结。"""
|
||||
schema = _schema()
|
||||
latest = db.session.query(ShippingFulfillmentPolicy.version).filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).first()
|
||||
definition = _definition(raw, schema_id=schema.id)
|
||||
policy = ShippingFulfillmentPolicy(
|
||||
schema_id=schema.id, policy_code=definition['policy_code'], version=(int(latest[0]) + 1 if latest else 1),
|
||||
definition_json=definition, change_note=str(raw.get('change_note') or '').strip() or None, created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(policy)
|
||||
db.session.commit()
|
||||
return _payload(policy)
|
||||
|
||||
|
||||
def publish(
|
||||
policy_id: int, *, actor_id: int | None, expected_lock_version: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""发布策略并退役旧版本;策略字段必须存在于当前已发布 Schema。"""
|
||||
policy = db.session.get(ShippingFulfillmentPolicy, policy_id)
|
||||
if policy is None:
|
||||
raise NotFoundError('Fulfillment policy not found', code='SHIPPING.FULFILLMENT_POLICY_NOT_FOUND')
|
||||
schema = _schema()
|
||||
if policy.schema_id != schema.id:
|
||||
raise NotFoundError('Fulfillment policy not found', code='SHIPPING.FULFILLMENT_POLICY_NOT_FOUND')
|
||||
if policy.status != 'draft' or expected_lock_version != policy.lock_version:
|
||||
raise ConflictError('Fulfillment policy has changed', code='SHIPPING.FULFILLMENT_POLICY_CONFLICT')
|
||||
definition = _definition(dict(policy.definition_json or {}), schema_id=policy.schema_id)
|
||||
published_schema = ShippingOrderSchemaVersion.query.filter_by(
|
||||
schema_id=policy.schema_id, status='published',
|
||||
).one_or_none()
|
||||
if published_schema is None:
|
||||
raise ConflictError(
|
||||
'Fulfillment policy requires a published schema version',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_SCHEMA_REQUIRED',
|
||||
details={'schema_id': policy.schema_id},
|
||||
)
|
||||
enabled_field_ids = {
|
||||
str(config.get('field_id'))
|
||||
for config in (published_schema.definition_json or {}).get('fields') or []
|
||||
if config.get('enabled', True)
|
||||
}
|
||||
missing_field_ids = sorted(
|
||||
str(binding['field_id'])
|
||||
for binding in definition['field_bindings']
|
||||
if str(binding['field_id']) not in enabled_field_ids
|
||||
)
|
||||
if missing_field_ids:
|
||||
raise ValidationError(
|
||||
'Fulfillment policy fields must be included in the published schema',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_INVALID',
|
||||
details={'field_ids': missing_field_ids},
|
||||
)
|
||||
current = ShippingFulfillmentPolicy.query.filter_by(schema_id=policy.schema_id, status='published').one_or_none()
|
||||
now = datetime.utcnow()
|
||||
if current is not None:
|
||||
current.status, current.retired_at = 'retired', now
|
||||
policy.definition_json = definition
|
||||
policy.checksum = _checksum(definition)
|
||||
policy.status, policy.published_by_id, policy.published_at = 'published', actor_id, now
|
||||
db.session.commit()
|
||||
return _payload(policy)
|
||||
|
||||
|
||||
def published_policy() -> ShippingFulfillmentPolicy:
|
||||
"""取得唯一 Schema 当前可执行策略;没有发布版本时 fail closed。"""
|
||||
schema = _schema()
|
||||
policy = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id, status='published').one_or_none()
|
||||
if policy is None:
|
||||
raise ConflictError('No published fulfillment policy', code='SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED')
|
||||
return policy
|
||||
|
||||
|
||||
def required_field_configs(definition: dict[str, Any], policy: ShippingFulfillmentPolicy) -> dict[str, dict[str, Any]]:
|
||||
"""把已发布策略的能力绑定解析为冻结字段配置,并拒绝 Schema 版本漂移。"""
|
||||
by_id = {str(item.get('field_id')): item for item in definition.get('fields') or [] if item.get('enabled', True)}
|
||||
selected: dict[str, dict[str, Any]] = {}
|
||||
bound_capabilities: set[str] = set()
|
||||
for binding in (policy.definition_json or {}).get('field_bindings') or []:
|
||||
capability = str(binding.get('capability_code') or '')
|
||||
config = by_id.get(str(binding.get('field_id') or ''))
|
||||
spec = _CAPABILITIES.get(capability)
|
||||
if config is None and spec is not None and not spec['required']:
|
||||
continue
|
||||
if config is None or spec is None or config.get('scope') != spec['scope'] or config.get('value_type') != spec['value_type']:
|
||||
raise ValidationError('Frozen order schema does not satisfy the fulfillment policy', code='SHIPPING.ORDER_CONTRACT_INVALID')
|
||||
selected[_CANONICAL_FIELD_CODES[capability]] = config
|
||||
bound_capabilities.add(capability)
|
||||
if _REQUIRED_CAPABILITIES - bound_capabilities:
|
||||
raise ValidationError('Fulfillment policy bindings are incomplete', code='SHIPPING.ORDER_CONTRACT_INVALID')
|
||||
for field_code, expected in _REQUIRED_FIELDS.items():
|
||||
config = by_code.get(field_code)
|
||||
if (
|
||||
config is None
|
||||
or config.get('scope') != expected['scope']
|
||||
or config.get('value_type') != expected['value_type']
|
||||
or config.get('asset_kind') not in (None, 'system_standard')
|
||||
):
|
||||
raise ValidationError(
|
||||
'Frozen order schema does not satisfy the fixed fulfillment rule',
|
||||
code='SHIPPING.ORDER_CONTRACT_INVALID',
|
||||
details={'field_code': field_code},
|
||||
)
|
||||
selected[field_code] = config
|
||||
return selected
|
||||
@@ -20,7 +20,7 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.models import ShippingTask
|
||||
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.inventory_file_store import active_inventory_lines_for_task
|
||||
@@ -53,7 +53,7 @@ from app.services.shipping_notice.rpa_attempts import (
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_common import log_task_event, prepend_tool_message, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
|
||||
|
||||
@@ -164,18 +164,13 @@ def _rpa_upload_timeout_seconds() -> int:
|
||||
return _cfg_int("SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS", 30, min_value=5)
|
||||
|
||||
|
||||
def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None:
|
||||
"""写入 ShippingTaskEvent 审计记录。"""
|
||||
if task.id is None:
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type=event_type,
|
||||
detail_json=detail or {},
|
||||
)
|
||||
)
|
||||
|
||||
def _event_actor_id(payload: dict[str, Any]) -> int | None:
|
||||
"""解析工作台传入的操作人;缺失时明确按系统自动动作记录。"""
|
||||
try:
|
||||
value = payload.get('operator_id') or payload.get('actor_id')
|
||||
return int(value) if value is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def match_completed(task: ShippingTask) -> bool:
|
||||
@@ -314,6 +309,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
dict[str, Any]: Tool 标准响应;status 可为 ok / needs_human / failed。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
actor_id = _event_actor_id(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
@@ -464,7 +460,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
if match_status in {"fulfillable", "partial"} and match_completed(task):
|
||||
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
|
||||
log_task_event(task, "matched_rolling_available", {"match_status": match_status, "verification_id": verification.id})
|
||||
log_task_event(task, "matched_rolling_available", {"match_status": match_status, "verification_id": verification.id}, actor_id=actor_id, source='workspace_api' if actor_id else 'system')
|
||||
db.session.commit()
|
||||
match_result = tool_response(
|
||||
status="ok",
|
||||
@@ -475,7 +471,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return try_auto_chain_after_match(task, match_result, payload=payload)
|
||||
|
||||
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
|
||||
log_task_event(task, "match_needs_review", {"match_status": match_status, "shortage": shortage})
|
||||
log_task_event(task, "match_needs_review", {"match_status": match_status, "shortage": shortage}, actor_id=actor_id, source='workspace_api' if actor_id else 'system')
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -513,6 +509,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
dict[str, Any]: 含 download_hint 的 Tool 响应;门禁失败时 forbidden_next_tools 含 upload_to_freight。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
actor_id = _event_actor_id(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
@@ -617,7 +614,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
progress_percent=100,
|
||||
detail=filename,
|
||||
)
|
||||
log_task_event(task, "export_generated", {"file_name": filename, "artifact_no": artifact.artifact_no})
|
||||
log_task_event(task, "export_generated", {"file_name": filename, "artifact_no": artifact.artifact_no}, actor_id=actor_id, source='workspace_api' if actor_id else 'system')
|
||||
_commit_generated_export(path)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -708,7 +705,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
log_task_event(task, 'upload_manual_confirmed', {'artifact_id': attempt.artifact_id, 'attempt_id': attempt.id})
|
||||
log_task_event(task, 'upload_manual_confirmed', {'artifact_id': attempt.artifact_id, 'attempt_id': attempt.id}, actor_id=attempt.operator_id, source='workspace_api')
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/order_document_profile_creation_service.py
|
||||
|
||||
用途:完成订单模板三步创建向导的最终原子提交。
|
||||
依赖:Profile 保存、样本布局、Revision、EditLease 与 Profile 审计模型。
|
||||
逻辑:前两步只在浏览器保存临时状态;本服务在最后一步一次创建草稿、样本绑定、Revision 审计和编辑租约,任一失败整体回滚。
|
||||
逻辑:前两步只在浏览器保存临时状态;本服务在最后一步一次创建草稿、首份建模/训练样本绑定、Revision 审计和编辑租约,任一失败整体回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -112,15 +112,22 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
change_source='wizard_created', commit=False,
|
||||
)
|
||||
profile_id = int(saved['id'])
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile_id, document_id=document.id, table_id=table_id,
|
||||
sample_role='annotation', created_by_id=actor_id,
|
||||
))
|
||||
# 首份样本既承载画布标注,也作为训练证据;盲测仍必须另选独立文档。
|
||||
for sample_role in ('annotation', 'training'):
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile_id, document_id=document.id, table_id=table_id,
|
||||
sample_role=sample_role, created_by_id=actor_id,
|
||||
))
|
||||
db.session.flush()
|
||||
profile_service._refresh_training_sample_count(db.session.get(ShippingOrderDocumentProfile, profile_id))
|
||||
revision_no = int(saved['draft_revision']['revision_no'])
|
||||
profile_service._audit(
|
||||
profile_id=profile_id, document_id=document.id, event_type='wizard_created', actor_id=actor_id,
|
||||
operation_id=operation_id, browser_session_id=session_id, revision_no=revision_no,
|
||||
detail={'main_table_id': table_id, 'schema_version_id': schema_version_id, 'profile_code': profile_code},
|
||||
detail={
|
||||
'main_table_id': table_id, 'schema_version_id': schema_version_id, 'profile_code': profile_code,
|
||||
'sample_roles': ['annotation', 'training'],
|
||||
},
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
token = secrets.token_urlsafe(32)
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
|
||||
run_id = data.get('validation_run_id')
|
||||
validation = db.session.get(ShippingOrderDocumentProfileValidationRun, int(run_id)) if str(run_id or '').isdigit() else None
|
||||
blocking: list[dict[str, Any]] = []
|
||||
if validation is None or validation.profile_id != profile.id or validation.status != 'passed' or validation.definition_checksum != revision.definition_checksum:
|
||||
if validation is None or validation.profile_id != profile.id or validation.run_type != 'current_sample' or validation.status != 'passed' or validation.definition_checksum != revision.definition_checksum:
|
||||
blocking.append({'key': 'current_validation_required', 'message': 'A passing validation run for the current draft is required.'})
|
||||
try:
|
||||
from app.services.shipping_notice.document_profile_quality_service import assert_profile_publishable
|
||||
|
||||
@@ -386,8 +386,14 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
|
||||
draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'],
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
# Pydantic locations only describe the submitted contract, so exposing the
|
||||
# first one lets the workbench identify a bad region without leaking data.
|
||||
validation_errors = getattr(exc, 'errors', lambda: [])()
|
||||
location = validation_errors[0].get('loc', ()) if validation_errors else ()
|
||||
raise ValidationError(
|
||||
'Order profile definition is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'Order profile definition is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'field_path': '.'.join(str(item) for item in location) or '$'},
|
||||
) from exc
|
||||
return {
|
||||
'contract_version': contract.contract_version,
|
||||
@@ -662,6 +668,8 @@ def preview_profile_region(
|
||||
table_region=table_region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in table_region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
|
||||
# 预览保留删除证据,供管理员核对;正式订单运行仍使用默认排除规则。
|
||||
include_deleted=True,
|
||||
))
|
||||
# 复合解析器可能生成未显式列在 target_fields 的附加字段,仍需纳入本次候选。
|
||||
for row in rows:
|
||||
@@ -676,7 +684,7 @@ def preview_profile_region(
|
||||
result = {
|
||||
'table_id': table_id, 'row_count': len(rows) + (1 if field_codes else 0),
|
||||
'column_count': len(field_codes), 'rows': ([field_codes] if field_codes else []) + [[row.fields.get(code, '') for code in field_codes] for row in rows],
|
||||
'row_roles': (['header'] if field_codes else []) + ['data'] * len(rows),
|
||||
'row_roles': (['header'] if field_codes else []) + [row.role for row in rows],
|
||||
'source_row_indices': ([[]] if field_codes else []) + [row.source_row_indices for row in rows],
|
||||
'status': 'needs_review',
|
||||
}
|
||||
|
||||
@@ -122,6 +122,20 @@ def _instant_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _current_sample_summary(*, line_field_count: int, line_value_count: int, header_field_count: int, header_value_count: int, sample_role: str) -> tuple[str, dict[str, Any], dict[str, Any]]:
|
||||
"""将样本试读的字段和值完整性转为发布可消费的明确结果。"""
|
||||
field_count = line_field_count + header_field_count
|
||||
value_count = line_value_count + header_value_count
|
||||
summary = {
|
||||
'sample_role': sample_role, 'field_count': field_count, 'value_count': value_count,
|
||||
'line_field_count': line_field_count, 'header_field_count': header_field_count,
|
||||
}
|
||||
if field_count <= 0 or value_count <= 0:
|
||||
summary['failure_code'] = 'order_profile_current_sample_no_readable_values'
|
||||
return 'failed', summary, {}
|
||||
return 'passed', summary, {'field_count': field_count, 'value_count': value_count}
|
||||
|
||||
|
||||
def run_instant_check(profile_id: int, *, data: dict[str, Any], actor_id: int | None, browser_session_id: str | None, lease_token: str | None, operation_id: str) -> dict[str, Any]:
|
||||
"""创建即时结构检查运行;必须持有草稿租约且失败结果同样持久化可查询。"""
|
||||
profile = _profile(profile_id)
|
||||
@@ -152,9 +166,18 @@ def run_current_sample(profile_id: int, *, data: dict[str, Any], actor_id: int |
|
||||
}, actor_id=actor_id)
|
||||
rows = preview.get('rows') if isinstance(preview, dict) else []
|
||||
fields = preview.get('field_codes') if isinstance(preview, dict) else []
|
||||
row.status, row.summary_json, row.result_snapshot_json = 'passed', {
|
||||
'sample_role': sample.sample_role, 'row_count': len(rows or []), 'field_count': len(fields or []),
|
||||
}, {'row_count': len(rows or []), 'field_count': len(fields or [])}
|
||||
definition = dict(profile.definition_json or {})
|
||||
header_fields = profile_service.preview_order_field_values({
|
||||
'document_id': sample.document_id, 'schema_version_id': profile.schema_version_id,
|
||||
'page_no': 1, 'definition': definition,
|
||||
}, actor_id=actor_id).get('fields') or []
|
||||
line_value_count = sum(1 for source_row in rows[1:] if isinstance(source_row, list) for value in source_row if str(value or '').strip())
|
||||
header_value_count = sum(1 for field in header_fields if isinstance(field, dict) and str(field.get('value') or '').strip())
|
||||
row.status, row.summary_json, row.result_snapshot_json = _current_sample_summary(
|
||||
line_field_count=len(fields or []), line_value_count=line_value_count,
|
||||
header_field_count=len(header_fields), header_value_count=header_value_count,
|
||||
sample_role=sample.sample_role,
|
||||
)
|
||||
except Exception as exc:
|
||||
row.status, row.summary_json, row.result_snapshot_json = 'failed', {
|
||||
'sample_role': sample.sample_role, 'failure_code': getattr(exc, 'code', 'SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/order_field_purposes.py
|
||||
|
||||
用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。
|
||||
依赖:冻结履约策略、export.order_field_id_values、ShippingTask。
|
||||
逻辑:路由、门禁、匹配和展示只通过策略冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
|
||||
逻辑:路由、门禁、匹配和展示只通过固定规则冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,17 +28,14 @@ def task_line_purpose_field_ids(task: ShippingTask, *, required: set[str] | None
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于履约的冻结订单快照')
|
||||
policy = (snapshot.rule_versions_json or {}).get('fulfillment_policy')
|
||||
definition = policy.get('definition') if isinstance(policy, dict) else None
|
||||
bindings = definition.get('field_bindings') if isinstance(definition, dict) else None
|
||||
rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule')
|
||||
required_ids = rule.get('required_field_ids') if isinstance(rule, dict) else None
|
||||
purposes = {
|
||||
purpose: str(binding.get('field_id'))
|
||||
for binding in bindings or []
|
||||
if isinstance(binding, dict)
|
||||
and binding.get('scope') == 'line'
|
||||
and (purpose := _PURPOSE_BY_CAPABILITY.get(str(binding.get('capability_code') or '')))
|
||||
and binding.get('field_id')
|
||||
}
|
||||
'reservation_id': str(required_ids.get('reservation_id') or ''),
|
||||
'part_number': str(required_ids.get('part_number') or ''),
|
||||
'quantity': str(required_ids.get('qty') or ''),
|
||||
} if isinstance(required_ids, dict) else {}
|
||||
purposes = {purpose: field_id for purpose, field_id in purposes.items() if field_id}
|
||||
missing = sorted((required or set()) - set(purposes))
|
||||
if missing:
|
||||
raise ValueError(f'冻结履约策略缺少字段能力:{", ".join(missing)}')
|
||||
|
||||
@@ -31,7 +31,7 @@ from app.models import (
|
||||
)
|
||||
|
||||
# 强类型列只是既有查询/导出投影;56 项标准字段的完整事实始终写在 field_id JSON。
|
||||
# 注意:本常量须保持在 fulfillment_policy / standard_field_registry 导入之前定义,
|
||||
# 注意:本常量须保持在固定履约契约 / standard_field_registry 导入之前定义,
|
||||
# 供 standard_field_registry 引用,避免三方循环导入。
|
||||
HEADER_FIELD_PROJECTIONS = {
|
||||
'customer_po_number': 'customer_po_number', 'customer_code': 'customer_code', 'customer_name': 'customer_name',
|
||||
@@ -107,7 +107,6 @@ def freeze_order_snapshot(
|
||||
assert_freeze_readiness(
|
||||
task=task,
|
||||
extraction=extraction,
|
||||
policy=policy,
|
||||
configs=configs,
|
||||
freeze_mode=freeze_mode,
|
||||
auto_freeze_policy=auto_freeze_policy,
|
||||
@@ -125,12 +124,10 @@ def freeze_order_snapshot(
|
||||
order_data_version=actual_version,
|
||||
rule_versions_json={
|
||||
**dict(rule_versions or {}),
|
||||
'fulfillment_policy': {
|
||||
'id': policy.id,
|
||||
'code': policy.policy_code,
|
||||
'version': policy.version,
|
||||
'checksum': policy.checksum,
|
||||
'definition': dict(policy.definition_json or {}),
|
||||
'fulfillment_rule': {
|
||||
'code': policy['rule_code'],
|
||||
'checksum': _fixed_rule_checksum(),
|
||||
'definition': dict(policy),
|
||||
'required_field_ids': {code: config['field_id'] for code, config in configs.items()},
|
||||
},
|
||||
'ordering_customer': {
|
||||
@@ -215,7 +212,7 @@ def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dic
|
||||
for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
],
|
||||
'fulfillment_policy': {'id': policy.id, 'version': policy.version, 'checksum': policy.checksum},
|
||||
'fulfillment_rule': {'code': policy['rule_code'], 'checksum': _fixed_rule_checksum()},
|
||||
'fields': fields,
|
||||
'manual_reviews': reviews,
|
||||
}
|
||||
@@ -249,23 +246,27 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin
|
||||
return row
|
||||
|
||||
|
||||
def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[Any, dict[str, dict[str, Any]]]:
|
||||
"""按已发布货代策略验证冻结契约,Schema 只继续承担字段目录职责。"""
|
||||
# 懒加载:避免 standard_field_registry ↔ order_freeze ↔ fulfillment_policy 循环导入。
|
||||
def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
|
||||
"""按固定履约契约验证冻结字段,Schema 仅承担字段目录职责。"""
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import (
|
||||
published_policy,
|
||||
fixed_rule_definition,
|
||||
required_field_configs,
|
||||
)
|
||||
|
||||
definition = extraction.schema_version.definition_json or {}
|
||||
policy = published_policy()
|
||||
required = required_field_configs(definition, policy)
|
||||
required = required_field_configs(definition)
|
||||
all_configs = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in definition.get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
}
|
||||
return policy, all_configs | required
|
||||
return fixed_rule_definition(), all_configs | required
|
||||
|
||||
|
||||
def _fixed_rule_checksum() -> str:
|
||||
"""延迟读取固定规则摘要,避免标准字段目录初始化时形成循环导入。"""
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import fixed_rule_checksum
|
||||
return fixed_rule_checksum()
|
||||
|
||||
def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[str, dict[str, Any]]) -> None:
|
||||
"""关键字段若由未经证据确认的 LLM fallback 参与裁决,则强制人工复核。"""
|
||||
|
||||
@@ -246,21 +246,19 @@ def get_auto_creation_policy() -> dict[str, Any]:
|
||||
|
||||
def save_auto_creation_policy(raw: Any, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
拒绝立即改写自动建单策略;须写入 Schema 草稿并随发布生效。
|
||||
兼容旧调用的拒绝入口;自动建单策略不得经独立写接口立即生效。
|
||||
|
||||
Args:
|
||||
raw: 忽略;保留签名兼容旧 PUT。
|
||||
raw: 忽略。
|
||||
actor_id: 忽略。
|
||||
|
||||
Returns:
|
||||
永不返回。
|
||||
|
||||
Raises:
|
||||
ConflictError: 引导客户端走草稿保存/发布路径。
|
||||
ConflictError: 引导改走草稿保存并发布(``SHIPPING.ORDER_SCHEMA_AUTO_CREATION_VIA_DRAFT``)。
|
||||
"""
|
||||
del raw, actor_id
|
||||
raise ConflictError(
|
||||
'Auto-creation policy must be saved on the Schema draft and takes effect on publish',
|
||||
'Auto-creation policy must be saved on the Schema draft and takes effect on publish; '
|
||||
'PUT /shipping-order-schema/auto-creation-policy has been removed',
|
||||
code='SHIPPING.ORDER_SCHEMA_AUTO_CREATION_VIA_DRAFT',
|
||||
)
|
||||
|
||||
@@ -871,19 +869,6 @@ def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str
|
||||
after={'schema_code': SCHEMA_CODE, 'display_name': display_name},
|
||||
change_summary={'action': 'family_created'},
|
||||
)
|
||||
# 初始化仅预置策略草稿;须有 published Schema 后才能有效绑定字段。
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import create_draft
|
||||
|
||||
fields_by_code = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
create_draft({
|
||||
'field_bindings': [
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields_by_code['reservation_id'].id},
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': fields_by_code['part_number'].id},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': fields_by_code['qty'].id},
|
||||
{'capability_code': 'routing.inventory_source_hint', 'field_id': fields_by_code['inventory_source_hint'].id},
|
||||
],
|
||||
'change_note': '初始化货代滚动履约策略',
|
||||
}, actor_id=actor_id)
|
||||
db.session.commit()
|
||||
return get_state()
|
||||
|
||||
|
||||
@@ -139,9 +139,15 @@ def _fulfillment_timeline(task: ShippingTask) -> dict[str, list[dict[str, Any]]]
|
||||
artifact_lines = ShippingExportArtifactLine.query.filter(
|
||||
ShippingExportArtifactLine.artifact_id.in_(artifact_ids),
|
||||
).all() if artifact_ids else []
|
||||
reservations_by_artifact: dict[int, list[int]] = {}
|
||||
reservation_ids = {
|
||||
item.id: item.reservation_id
|
||||
for item in ShippingReservation.query.filter(ShippingReservation.task_id == task.id).all()
|
||||
}
|
||||
reservations_by_artifact: dict[int, list[str]] = {}
|
||||
for line in artifact_lines:
|
||||
reservations_by_artifact.setdefault(int(line.artifact_id), []).append(int(line.reservation_id))
|
||||
reservations_by_artifact.setdefault(int(line.artifact_id), []).append(
|
||||
reservation_ids.get(int(line.reservation_id), str(line.reservation_id))
|
||||
)
|
||||
attempts = ShippingUploadAttempt.query.filter(
|
||||
ShippingUploadAttempt.artifact_id.in_(artifact_ids),
|
||||
).order_by(ShippingUploadAttempt.created_at, ShippingUploadAttempt.id).all() if artifact_ids else []
|
||||
@@ -150,7 +156,7 @@ def _fulfillment_timeline(task: ShippingTask) -> dict[str, list[dict[str, Any]]]
|
||||
'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.inventory_snapshot_id,
|
||||
'source_config_version': item.source_config_version, 'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
'lines': [{
|
||||
'reservation_id': line.reservation_id, 'required_qty': str(line.required_qty),
|
||||
'reservation_id': reservation_ids.get(int(line.reservation_id), str(line.reservation_id)), 'required_qty': str(line.required_qty),
|
||||
'available_qty': str(line.available_qty), 'status': line.status,
|
||||
} for line in item.lines],
|
||||
} for item in verifications],
|
||||
@@ -732,6 +738,11 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
{
|
||||
"event_type": e.event_type,
|
||||
"detail_json": e.detail_json,
|
||||
"actor_id": e.actor_id,
|
||||
"request_id": e.request_id,
|
||||
"source": e.source,
|
||||
"before_json": e.before_json,
|
||||
"after_json": e.after_json,
|
||||
"created_at": e.created_at.isoformat() if e.created_at else None,
|
||||
}
|
||||
for e in sorted(task.events or [], key=lambda x: x.created_at or "")
|
||||
@@ -1788,4 +1799,4 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
"processing": processing,
|
||||
"done": done,
|
||||
"total_pending_badge": pending,
|
||||
}
|
||||
}
|
||||
@@ -259,6 +259,10 @@ def log_task_event(
|
||||
detail: dict[str, Any] | None = None,
|
||||
*,
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
source: str | None = None,
|
||||
before: dict[str, Any] | None = None,
|
||||
after: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。
|
||||
@@ -269,8 +273,12 @@ def log_task_event(
|
||||
Args:
|
||||
task: 目标任务。
|
||||
event_type: 事件类型码。
|
||||
detail: 结构化明细;可含 source。
|
||||
detail: 结构化明细;包含动作对象与原因。
|
||||
actor_id: 操作者用户 ID;系统事件传 None。
|
||||
request_id: 请求追踪标识。
|
||||
source: 操作来源,如 workspace_api 或 system。
|
||||
before: 操作前业务快照。
|
||||
after: 操作后业务快照。
|
||||
"""
|
||||
if task.id is None:
|
||||
db.session.flush()
|
||||
@@ -279,6 +287,10 @@ def log_task_event(
|
||||
event_type=event_type,
|
||||
detail_json=detail or {},
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
source=source,
|
||||
before_json=before,
|
||||
after_json=after,
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""replace configurable fulfillment policy with fixed rule and enrich task audit
|
||||
|
||||
Revision ID: 1a3b5c7d9e0f
|
||||
Revises: 1a2b3c4d5e60
|
||||
Create Date: 2026-07-29 00:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '1a3b5c7d9e0f'
|
||||
down_revision = '1a2b3c4d5e60'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""删除无需配置的策略表,并为任务审计补齐前后快照和来源。"""
|
||||
op.add_column('shipping_task_events', sa.Column('before_json', sa.JSON(), nullable=True))
|
||||
op.add_column('shipping_task_events', sa.Column('after_json', sa.JSON(), nullable=True))
|
||||
op.add_column('shipping_task_events', sa.Column('source', sa.String(length=32), nullable=True))
|
||||
op.create_index('ix_shipping_task_events_source', 'shipping_task_events', ['source'])
|
||||
op.drop_index('uq_shipping_fulfillment_policy_one_published', table_name='shipping_fulfillment_policies')
|
||||
op.drop_table('shipping_fulfillment_policies')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复策略表结构;不恢复已被明确废弃的历史策略数据。"""
|
||||
op.create_table(
|
||||
'shipping_fulfillment_policies',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False),
|
||||
sa.Column('policy_code', sa.String(length=64), nullable=False),
|
||||
sa.Column('version', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'),
|
||||
sa.Column('definition_json', sa.JSON(), nullable=False),
|
||||
sa.Column('checksum', sa.String(length=64)), sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('change_note', sa.Text()), sa.Column('source_policy_id', sa.Integer()),
|
||||
sa.Column('created_by_id', sa.Integer()), sa.Column('published_by_id', sa.Integer()),
|
||||
sa.Column('published_at', sa.DateTime()), sa.Column('retired_at', sa.DateTime()),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
)
|
||||
op.create_index('uq_shipping_fulfillment_policy_one_published', 'shipping_fulfillment_policies', ['schema_id'], unique=True)
|
||||
op.drop_index('ix_shipping_task_events_source', table_name='shipping_task_events')
|
||||
op.drop_column('shipping_task_events', 'source')
|
||||
op.drop_column('shipping_task_events', 'after_json')
|
||||
op.drop_column('shipping_task_events', 'before_json')
|
||||
@@ -22,7 +22,6 @@ from app.models import (
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingTaskFieldConflict,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
@@ -32,7 +31,7 @@ from app.models import (
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import published_policy, required_field_configs
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import required_field_configs
|
||||
from app.services.shipping_notice.order_freeze_service import (
|
||||
HEADER_FIELD_PROJECTIONS,
|
||||
LINE_FIELD_PROJECTIONS,
|
||||
@@ -75,27 +74,6 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='snapshot-test')
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
bindings = [
|
||||
('fulfillment.reservation_identity', 'reservation_id'),
|
||||
('fulfillment.part_number', 'part_number'),
|
||||
('fulfillment.quantity', 'qty'),
|
||||
('routing.inventory_source_hint', 'inventory_source_hint'),
|
||||
]
|
||||
db.session.add(ShippingFulfillmentPolicy(
|
||||
schema_id=schema.id, policy_code='SHIP_AVAILABLE_ROLLING_V1', version=1, status='published',
|
||||
checksum='policy-test', definition_json={
|
||||
'policy_code': 'SHIP_AVAILABLE_ROLLING_V1', 'fulfillment_mode': 'ship_available_rolling',
|
||||
'requires_confirmed_customer': True, 'allows_partial_reservation': False,
|
||||
'field_bindings': [
|
||||
{
|
||||
'capability_code': capability, 'field_id': fields[field_code].id,
|
||||
'field_code': field_code, 'scope': 'line',
|
||||
'value_type': 'decimal' if field_code == 'qty' else 'string',
|
||||
}
|
||||
for capability, field_code in bindings
|
||||
],
|
||||
},
|
||||
))
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
@@ -237,21 +215,7 @@ def test_freeze_allows_schema_without_optional_standard_fields(app):
|
||||
|
||||
assert snapshot.lines[0].reservation_id == '0012345678'
|
||||
assert snapshot.currency is None
|
||||
assert snapshot.rule_versions_json['fulfillment_policy']['code'] == 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
|
||||
|
||||
def test_freeze_rejects_when_no_fulfillment_policy_is_published(app):
|
||||
"""关键断言:Schema 已发布不等于可履约,未发布策略时必须在冻结入口阻断。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order()
|
||||
ShippingFulfillmentPolicy.query.delete()
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as error:
|
||||
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
|
||||
assert error.value.code == 'SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED'
|
||||
assert task.order_snapshot_id is None
|
||||
assert snapshot.rule_versions_json['fulfillment_rule']['code'] == 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
|
||||
|
||||
def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app):
|
||||
@@ -295,20 +259,18 @@ def test_auto_freeze_readiness_fails_closed_with_run_policy_blockers(app):
|
||||
task, _user = _build_accepted_order(suffix='auto-freeze-readiness')
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
assert extraction is not None
|
||||
policy = published_policy()
|
||||
definition = extraction.schema_version.definition_json or {}
|
||||
configs = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
}
|
||||
configs.update(required_field_configs(definition, policy))
|
||||
configs.update(required_field_configs(definition))
|
||||
|
||||
with pytest.raises(ValidationError) as blocked_error:
|
||||
assert_freeze_readiness(
|
||||
task=task,
|
||||
extraction=extraction,
|
||||
policy=policy,
|
||||
configs=configs,
|
||||
freeze_mode='auto',
|
||||
auto_freeze_policy={
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
"""
|
||||
backend/tests/test_fulfillment_core_rejects_extension.py
|
||||
|
||||
用途:验证履约核心能力拒绝绑定扩展字段资产(阶段 5 收口)。
|
||||
依赖:fulfillment_policy_registry、field_asset_service、Flask 测试 app。
|
||||
逻辑:初始化 Schema 族后,用扩展字段绑 fulfillment.part_number 须抛 FULFILLMENT_FIELD_INVALID。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.shipping_order_schema import ShippingOrderField
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
from app.services.shipping_notice import fulfillment_policy_registry
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def test_core_fulfillment_binding_rejects_extension_field(app):
|
||||
"""关键断言:扩展资产不可绑定履约核心 capability。"""
|
||||
with app.app_context():
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
order_schema_service.initialize_schema({'display_name': 'Fulfillment Gate'}, actor_id=None)
|
||||
extension = field_asset_service.create_extension({
|
||||
'field_code': 'custom_part_alias',
|
||||
'scope': 'line',
|
||||
'value_type': 'string',
|
||||
'display_name': '自定义料号',
|
||||
}, actor_id=None)
|
||||
reservation = ShippingOrderField.query.filter_by(field_code='reservation_id').one()
|
||||
qty = ShippingOrderField.query.filter_by(field_code='qty').one()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
fulfillment_policy_registry.create_draft({
|
||||
'field_bindings': [
|
||||
{
|
||||
'capability_code': 'fulfillment.reservation_identity',
|
||||
'field_id': reservation.id,
|
||||
},
|
||||
{
|
||||
'capability_code': 'fulfillment.part_number',
|
||||
'field_id': extension['id'],
|
||||
},
|
||||
{
|
||||
'capability_code': 'fulfillment.quantity',
|
||||
'field_id': qty.id,
|
||||
},
|
||||
],
|
||||
'change_note': 'must fail',
|
||||
}, actor_id=None)
|
||||
assert exc.value.code == 'SHIPPING.FULFILLMENT_FIELD_INVALID'
|
||||
@@ -34,7 +34,7 @@ def _wizard_payload(schema_id: int, document_id: int, *, table_id: str = 'sample
|
||||
|
||||
|
||||
def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomically(app):
|
||||
"""关键断言:最后一步一次提交全部治理对象,并绑定用户已确认的主表格。"""
|
||||
"""关键断言:最后一步一次提交全部治理对象,并将主表格作为标注和训练证据。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
# 只借用已解析文档夹具;其 Profile 绑定与向导目标无关。
|
||||
@@ -55,12 +55,15 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
|
||||
assert created['draft_revision']['revision_no'] == 1
|
||||
assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1
|
||||
assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1
|
||||
audit = ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
profile_id=profile_id, event_type='wizard_created', operation_id='wizard-create-op',
|
||||
).one()
|
||||
assert audit.detail_json['profile_code'] == created['profile_code']
|
||||
assert audit.detail_json['sample_roles'] == ['annotation', 'training']
|
||||
|
||||
|
||||
def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
|
||||
|
||||
@@ -27,7 +27,7 @@ def _passing_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun:
|
||||
row = ShippingOrderDocumentProfileValidationRun(
|
||||
profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'],
|
||||
definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'],
|
||||
run_type='instant_check', status='passed', summary_json={}, result_snapshot_json={}, operation_id='passing-validation',
|
||||
run_type='current_sample', status='passed', summary_json={}, result_snapshot_json={}, operation_id='passing-validation',
|
||||
)
|
||||
db.session.add(row); db.session.commit()
|
||||
return row
|
||||
|
||||
@@ -82,3 +82,16 @@ def test_failed_current_sample_run_remains_queryable(app):
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
assert validation_service.list_runs(draft['id'])[0]['id'] == result['id']
|
||||
|
||||
|
||||
def test_current_sample_summary_rejects_empty_fields_or_values():
|
||||
"""关键断言:没有字段或读取值的样本不能伪装成可发布的通过运行。"""
|
||||
assert validation_service._current_sample_summary(
|
||||
line_field_count=0, line_value_count=2, header_field_count=0, header_value_count=0, sample_role='annotation',
|
||||
)[0] == 'failed'
|
||||
assert validation_service._current_sample_summary(
|
||||
line_field_count=2, line_value_count=0, header_field_count=1, header_value_count=0, sample_role='annotation',
|
||||
)[0] == 'failed'
|
||||
assert validation_service._current_sample_summary(
|
||||
line_field_count=2, line_value_count=1, header_field_count=1, header_value_count=0, sample_role='annotation',
|
||||
)[0] == 'passed'
|
||||
@@ -12,6 +12,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentProfileTestRun,
|
||||
ShippingDocumentProfileTestSample,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
@@ -271,6 +272,51 @@ def test_profile_detail_returns_safe_summaries_without_blind_truth(app):
|
||||
assert 'blind-secret.pdf' not in encoded
|
||||
|
||||
|
||||
def test_profile_detail_separates_bound_and_suite_blind_test_counts(app):
|
||||
"""盲测套件样本不等同于模板直接绑定的 blind_test 样本,详情 DTO 必须分别统计。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
user = User(username='suite-only-admin', email='suite-only@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
profile = _profile(schema.id, profile_code='TSUITE', version=1, status='published')
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id,
|
||||
profile_checksum=profile.checksum or '1' * 64,
|
||||
status='approved',
|
||||
approved_by_id=user.id,
|
||||
approved_at=datetime.utcnow(),
|
||||
created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
db.session.flush()
|
||||
document = _document(user, filename='suite-only.pdf', content_hash='f' * 64)
|
||||
db.session.add(ShippingDocumentProfileTestSample(
|
||||
suite_id=suite.id,
|
||||
document_id=document.id,
|
||||
table_id='suite-only-table',
|
||||
expected_rows_json=[],
|
||||
expected_order_fields_json={},
|
||||
created_by_id=user.id,
|
||||
))
|
||||
db.session.add(ShippingDocumentProfileTestRun(
|
||||
suite_id=suite.id,
|
||||
profile_checksum=profile.checksum or '1' * 64,
|
||||
status='passed',
|
||||
sample_count=1,
|
||||
passed_sample_count=1,
|
||||
failure_codes_json=[],
|
||||
executed_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
detail = version_service.get_profile_detail(profile.id)
|
||||
# 绑定样本为零不否定独立盲测套件已完成。
|
||||
assert detail['sample_summary']['blind_test_count'] == 0
|
||||
assert detail['test_summary']['sample_count'] == 1
|
||||
assert detail['test_summary']['status'] == 'approved'
|
||||
|
||||
|
||||
def test_version_center_routes_return_family_summary_and_explicit_404(app, admin_jwt_headers):
|
||||
"""新版本中心路由必须能按族返回摘要,并在版本不存在时返回明确 404。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -313,8 +313,8 @@ def test_coordinate_profile_rows_restore_pdf_visual_spaces():
|
||||
assert rows[0].fields['shipway'] == 'By Truck'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_discard_the_prior_record_for_explicit_deleted_marker():
|
||||
"""`** Item deleted **` 只能废弃前一条已启动明细,不能作为下一条或独立明细。"""
|
||||
def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them_for_preview():
|
||||
"""正式解析排除删除行,标注预览可显式返回同一行的删除证据。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-DELETED', 65)],
|
||||
@@ -329,6 +329,20 @@ def test_coordinate_profile_rows_discard_the_prior_record_for_explicit_deleted_m
|
||||
)
|
||||
assert [row.fields for row in rows] == [{'line_no': '00020', 'part_number': 'PART-KEEP'}]
|
||||
|
||||
preview_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-DELETED', 65)],
|
||||
[('** Item deleted **', 65)],
|
||||
[('00020', 10), ('PART-KEEP', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}], include_deleted=True,
|
||||
)
|
||||
# 关键断言:预览保留被删除的原始明细,但角色明确标识为不可纳入结果。
|
||||
assert [(row.fields['line_no'], row.role) for row in preview_rows] == [('00010', 'deleted'), ('00020', 'data')]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schema_fields():
|
||||
"""脱敏回放 F9A1:四条物理行只合并为一条,并只读取已绑定的标准字段。"""
|
||||
@@ -434,6 +448,7 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
assert deleted == []
|
||||
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_replay_sample_visual_band_offsets_despite_parent_whitespace():
|
||||
"""父物理行含底部留白时应复用样例视觉子行偏移,不能按高度缩放把字段投到行间。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
|
||||
@@ -249,6 +249,32 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
|
||||
|
||||
def test_coordinate_blind_candidate_list_does_not_prepare_missing_evidence(app, monkeypatch):
|
||||
"""关键断言:打开盲测候选列表只能读取现有摘要,不能为历史文档触发 OCR 证据补齐。"""
|
||||
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': [], 'order_field_layouts': [],
|
||||
}
|
||||
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)
|
||||
monkeypatch.setattr(
|
||||
quality, '_ensure_order_field_evidence',
|
||||
lambda **_kwargs: pytest.fail('candidate listing must not prepare coordinate evidence'),
|
||||
)
|
||||
|
||||
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}
|
||||
|
||||
|
||||
def test_coordinate_blind_preview_skips_header_only_regions(app):
|
||||
"""关键断言:仅含订单字段的页不重建物理行,候选预览不会因空布局报 500。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_fulfillment_policy.py
|
||||
|
||||
用途:验证货代字段能力绑定与版本化履约策略。
|
||||
依赖:订单 Schema 服务、履约策略注册表与测试数据库。
|
||||
逻辑:策略只允许受控能力绑定稳定 field_id;发布后冻结保存版本快照,错误类型或范围必须阻断;
|
||||
无已发布 Schema 时不得发布策略。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingFulfillmentPolicy, ShippingOrderField
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import create_draft, get_state, publish
|
||||
from app.services.shipping_notice.order_schema import service as schema_service
|
||||
|
||||
|
||||
def _bindings() -> list[dict[str, str]]:
|
||||
"""以当前标准字段的稳定 ID 构造首个滚动履约策略绑定。"""
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
return [
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id'].id},
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number'].id},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': fields['qty'].id},
|
||||
{'capability_code': 'routing.inventory_source_hint', 'field_id': fields['inventory_source_hint'].id},
|
||||
]
|
||||
|
||||
|
||||
def _field_config(field_id: str, *, display_name: str, value_type: str = 'string') -> dict:
|
||||
"""构造可发布的最小字段配置,验证策略只能绑定当前已发布字段。"""
|
||||
return {
|
||||
'field_id': field_id, 'display_name': display_name, 'business_purpose': 'general',
|
||||
'required': False, 'aliases': [], 'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim',
|
||||
'validator_keys': [], 'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text',
|
||||
}
|
||||
|
||||
|
||||
def _publish_minimal_schema() -> None:
|
||||
"""发布含履约绑定字段的最小 Schema,供策略发布门禁使用。"""
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
draft = schema_service.create_draft({}, actor_id=None)
|
||||
configs = [
|
||||
_field_config(fields['reservation_id'].id, display_name='预定单号'),
|
||||
_field_config(fields['part_number'].id, display_name='料号'),
|
||||
_field_config(fields['qty'].id, display_name='数量', value_type='decimal'),
|
||||
_field_config(fields['inventory_source_hint'].id, display_name='库存源线索'),
|
||||
]
|
||||
saved = schema_service.save_draft(draft['id'], {
|
||||
'fields': configs, 'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
|
||||
|
||||
def test_policy_initialization_and_publish_versions_are_isolated(app):
|
||||
"""初始化只创建待确认草稿;有已发布 Schema 后,发布策略会退役旧版且保留稳定字段绑定。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
initial = ShippingFulfillmentPolicy.query.filter_by(status='draft').one()
|
||||
assert initial.policy_code == 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
assert {item['capability_code'] for item in initial.definition_json['field_bindings']} >= {
|
||||
'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity',
|
||||
}
|
||||
|
||||
_publish_minimal_schema()
|
||||
initial = publish(initial.id, actor_id=None, expected_lock_version=initial.lock_version)
|
||||
assert initial['status'] == 'published'
|
||||
|
||||
draft = create_draft({'field_bindings': _bindings(), 'change_note': '复核策略'}, actor_id=None)
|
||||
released = publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
|
||||
assert released['status'] == 'published'
|
||||
assert ShippingFulfillmentPolicy.query.filter_by(status='retired').one().id == initial['id']
|
||||
assert len(get_state()['capabilities']) == 4
|
||||
|
||||
|
||||
def test_policy_publish_requires_published_schema(app):
|
||||
"""断言:同族尚无已发布 Schema 时,不得发布履约策略。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
initial = ShippingFulfillmentPolicy.query.filter_by(status='draft').one()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
publish(initial.id, actor_id=None, expected_lock_version=initial.lock_version)
|
||||
assert exc_info.value.code == 'SHIPPING.FULFILLMENT_POLICY_SCHEMA_REQUIRED'
|
||||
|
||||
|
||||
def test_policy_rejects_scope_or_type_drift(app):
|
||||
"""能力绑定只能选择匹配 scope/value_type 的字段,不能借字段目录绕过履约契约。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
bindings = _bindings()
|
||||
wrong = next(item for item in ShippingOrderField.query.filter_by(field_code='customer_po_number').all())
|
||||
bindings[0]['field_id'] = wrong.id
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_draft({'field_bindings': bindings}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.FULFILLMENT_POLICY_INVALID'
|
||||
|
||||
|
||||
def test_policy_rejects_extension_on_core_capability(app):
|
||||
"""核心履约能力不得绑定扩展字段;须使用系统标准表身字段。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
custom = schema_service.save_field({
|
||||
'field_code': 'customer_reservation_reference', 'scope': 'line', 'value_type': 'string',
|
||||
'display_name': '客户预约单号',
|
||||
}, actor_id=None)
|
||||
bindings = _bindings()
|
||||
bindings[0]['field_id'] = custom['id']
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_draft({'field_bindings': bindings, 'change_note': '客户预约单字段'}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.FULFILLMENT_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_policy_publish_rejects_an_active_field_omitted_from_published_schema(app):
|
||||
"""已有正式 Schema 后,API 不得发布绑定了目录中但未纳入版本的字段的策略。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
draft = schema_service.create_draft({}, actor_id=None)
|
||||
# 故意不纳入 inventory_source_hint,策略绑定仍包含该字段时应被拒绝。
|
||||
configs = [
|
||||
_field_config(fields['reservation_id'].id, display_name='预定单号'),
|
||||
_field_config(fields['part_number'].id, display_name='料号'),
|
||||
_field_config(fields['qty'].id, display_name='数量', value_type='decimal'),
|
||||
]
|
||||
saved = schema_service.save_draft(draft['id'], {
|
||||
'fields': configs, 'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
policy_draft = create_draft({'field_bindings': _bindings()}, actor_id=None)
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
publish(policy_draft['id'], actor_id=None, expected_lock_version=policy_draft['lock_version'])
|
||||
assert exc_info.value.code == 'SHIPPING.FULFILLMENT_POLICY_INVALID'
|
||||
|
||||
|
||||
def test_schema_publish_cannot_omit_a_field_bound_by_published_policy(app):
|
||||
"""发布 Schema 时须反查当前策略,避免移除绑定字段后冻结阶段才失败。"""
|
||||
with app.app_context():
|
||||
schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None)
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
first = schema_service.create_draft({}, actor_id=None)
|
||||
first_fields = [
|
||||
_field_config(fields['reservation_id'].id, display_name='预定单号'),
|
||||
_field_config(fields['part_number'].id, display_name='料号'),
|
||||
_field_config(fields['qty'].id, display_name='数量', value_type='decimal'),
|
||||
_field_config(fields['inventory_source_hint'].id, display_name='库存源线索'),
|
||||
]
|
||||
saved = schema_service.save_draft(first['id'], {
|
||||
'fields': first_fields, 'expected_lock_version': first['lock_version'],
|
||||
}, actor_id=None)
|
||||
schema_service.publish(first['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
initial_policy = ShippingFulfillmentPolicy.query.filter_by(status='draft').one()
|
||||
publish(initial_policy.id, actor_id=None, expected_lock_version=initial_policy.lock_version)
|
||||
second = schema_service.create_draft({}, actor_id=None)
|
||||
only_required = first_fields[:3]
|
||||
saved = schema_service.save_draft(second['id'], {
|
||||
'fields': only_required, 'expected_lock_version': second['lock_version'],
|
||||
}, actor_id=None)
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
schema_service.publish(second['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
assert getattr(exc_info.value, 'code', None) in {
|
||||
'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED',
|
||||
'SHIPPING.FIELD_IMPACT_BLOCKED',
|
||||
}
|
||||
@@ -522,11 +522,16 @@ def test_profile_samples_are_governed_and_audited(app, monkeypatch):
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
annotation_samples = service.add_profile_sample(
|
||||
draft['id'], document_id=document.id, table_id='sample-table', sample_role='annotation', actor_id=None,
|
||||
)
|
||||
samples = service.add_profile_sample(
|
||||
draft['id'], document_id=document.id, table_id='sample-table', sample_role='training', actor_id=None,
|
||||
)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
assert len(samples) == 1
|
||||
# 标注与训练是不同的证据角色,同一文档页可同时承担两者。
|
||||
assert len(annotation_samples) == 1
|
||||
assert {item['sample_role'] for item in samples} == {'annotation', 'training'}
|
||||
assert profile.training_sample_count == 1
|
||||
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileAudit.id.desc(),
|
||||
@@ -534,9 +539,10 @@ def test_profile_samples_are_governed_and_audited(app, monkeypatch):
|
||||
assert audit.event_type == 'profile_sample_added'
|
||||
assert audit.detail_json == {'sample_role': 'training', 'has_table_binding': True}
|
||||
|
||||
service.remove_profile_sample(profile.id, samples[0]['id'], actor_id=None)
|
||||
training_sample = next(item for item in samples if item['sample_role'] == 'training')
|
||||
service.remove_profile_sample(profile.id, training_sample['id'], actor_id=None)
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile.id).training_sample_count == 0
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).count() == 0
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).count() == 1
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.publish(profile.id, actor_id=None, expected_lock_version=profile.lock_version)
|
||||
@@ -929,6 +935,20 @@ def test_profile_rejects_unknown_field_and_stale_lock(app):
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_profile_definition_validation_exposes_first_invalid_field_path(app):
|
||||
"""关键断言:无效坐标必须给出安全字段路径,供工作台定位而不回传样本文本。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
invalid = _data(schema.id)
|
||||
invalid['definition']['table_regions'][0]['line_layouts'][0]['region']['x1'] = 0
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft(invalid, actor_id=None)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
assert getattr(caught.value, 'details', {}).get('field_path') == 'table_regions.0.line_layouts.0.region'
|
||||
|
||||
|
||||
def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
"""普通用户不能维护 Profile;管理员错误使用统一业务 envelope。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
@@ -966,6 +986,24 @@ def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
assert lease.status_code == 201
|
||||
lease_payload = parse_api_data(lease.get_json())
|
||||
|
||||
invalid_definition = _data(schema_id)
|
||||
invalid_definition['definition']['table_regions'][0]['line_layouts'][0]['region']['x1'] = 0
|
||||
invalid = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={
|
||||
**invalid_definition,
|
||||
'expected_lock_version': payload['lock_version'],
|
||||
'browser_session_id': 'profile-admin-tab',
|
||||
'lease_token': lease_payload['lease_token'],
|
||||
'operation_id': 'profile-admin-invalid-definition',
|
||||
},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
invalid_error = parse_api_error(invalid.get_json())
|
||||
assert invalid_error['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
assert invalid_error['details']['field_path'] == 'table_regions.0.line_layouts.0.region'
|
||||
|
||||
conflict = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={
|
||||
|
||||
@@ -805,7 +805,6 @@ def test_run_submission_auto_freezes_qualified_tasks(app):
|
||||
"""Run 命中已授权模板后,应自动消费 accepted Candidate 并冻结为履约 Snapshot。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingCustomer, ShippingDocumentProfileAutoFreezeQualification, ShippingOrderCustomerMatch
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import create_draft, publish
|
||||
from tests.test_shipping_order_auto_freeze_policy import _published_profile
|
||||
|
||||
fields = _ensure_order_schema()
|
||||
@@ -838,15 +837,6 @@ def test_run_submission_auto_freezes_qualified_tasks(app):
|
||||
unit = run.extraction_plan.units[0]
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='e' * 64)
|
||||
policy_draft = create_draft({
|
||||
'field_bindings': [
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']},
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']},
|
||||
{'capability_code': 'routing.inventory_source_hint', 'field_id': fields['inventory_source_hint']},
|
||||
],
|
||||
}, actor_id=None)
|
||||
publish(policy_draft['id'], actor_id=None, expected_lock_version=policy_draft['lock_version'])
|
||||
customer = ShippingCustomer(standard_name='Freeze Customer', short_code='FRZ')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
|
||||
@@ -8,6 +8,8 @@ tests/test_shipping_order_field_extraction.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import ValidationError as PydanticValidationError
|
||||
|
||||
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
|
||||
@@ -248,24 +250,24 @@ def test_common_purchase_order_slash_date_is_normalized():
|
||||
assert result.value.isoformat() == '2026-06-20'
|
||||
|
||||
|
||||
def test_date_recovers_one_glyph_just_outside_value_frame():
|
||||
"""关键断言:日期值框少一个字符宽时仅补紧邻末尾数字,避免候选无故消失。"""
|
||||
def test_date_does_not_extend_beyond_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},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 3.55, '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'
|
||||
# 关键断言:框外末尾字符不能被静默吞入,管理员需扩大值框后再读取。
|
||||
assert result.status == 'needs_review'
|
||||
assert result.value is None
|
||||
|
||||
|
||||
def test_right_of_anchor_recovers_a_customer_name_cut_off_by_value_frame():
|
||||
"""客户值框截在单词中间时,应跳过冒号并补全同一连续公司名称。"""
|
||||
def test_right_of_anchor_does_not_extend_customer_name_beyond_value_frame():
|
||||
"""右侧锚点模式同样严格服从值框,避免相邻字段字符污染。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
# Right edge cuts ``Corporation`` before its last three characters.
|
||||
@@ -277,9 +279,9 @@ def test_right_of_anchor_recovers_a_customer_name_cut_off_by_value_frame():
|
||||
'BILL TO: Inventec Corporation BILL ADDRESS: 66 Street', 20, 20,
|
||||
))}))[0]
|
||||
|
||||
# 关键断言:不能回传 ``: Inventec Corporati``,也不能吞入右侧地址字段。
|
||||
# 关键断言:不跨框补足公司名称,也不吞入右侧地址字段。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == 'Inventec Corporation'
|
||||
assert result.value == 'Inventec Corpor'
|
||||
|
||||
|
||||
def test_right_of_anchor_never_extends_from_customer_value_box_into_address():
|
||||
@@ -300,6 +302,57 @@ def test_right_of_anchor_never_extends_from_customer_value_box_into_address():
|
||||
assert result.value == 'Inventec Corporation'
|
||||
|
||||
|
||||
def test_absolute_value_region_uses_canvas_boundary_instead_of_anchor_projection():
|
||||
"""锚点只定位字段,画布绝对值框必须排除其左侧的相邻字符。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
'absolute_value_region': {'x0': .30, 'y0': .20, 'x1': .95, 'y1': .30},
|
||||
'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(
|
||||
field_code='bill_to_address',
|
||||
), coordinate_evidence=_evidence(pages={'1': _glyphs(
|
||||
('BILL TO', 20, 20), ('n 66 Hou-Kang Street', 56, 44),
|
||||
)}))[0]
|
||||
|
||||
# 关键断言:框左侧的 n 不属于值框,实际标签 bbox 的尺寸不得改变该判断。
|
||||
assert result.value == '66 Hou-Kang Street'
|
||||
|
||||
|
||||
def test_anchored_order_field_rejects_ambiguous_legacy_and_absolute_value_regions():
|
||||
"""新旧值框不能并存,避免后续编辑绕过唯一画布读取边界。"""
|
||||
try:
|
||||
_profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
'absolute_value_region': {'x0': .30, 'y0': .20, 'x1': .95, 'y1': .30},
|
||||
})
|
||||
except PydanticValidationError as error:
|
||||
# 新旧坐标体系只能二选一,确保绝对画布框始终是新定义的唯一读取边界。
|
||||
assert 'anchored order field requires one value region' in str(error)
|
||||
else:
|
||||
raise AssertionError('anchored order field accepted two value regions')
|
||||
|
||||
|
||||
def test_absolute_multiline_value_region_keeps_all_rows_before_stop_anchor():
|
||||
"""多行字段严格按画布高度读取,不能因锚点投影高度而丢失末行。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'destination', 'text': 'DESTINATION'},
|
||||
'absolute_value_region': {'x0': .30, 'y0': .20, 'x1': 1, 'y1': .46},
|
||||
'value_mode': 'multi_line',
|
||||
'stop_anchors': [{'anchor_id': 'tel', 'text': 'TEL'}],
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(
|
||||
field_code='destination',
|
||||
), coordinate_evidence=_evidence(pages={'1': _glyphs(
|
||||
('DESTINATION', 20, 20), ('Blvd Madrid 8560', 64, 44),
|
||||
('32695', 64, 56), ('Juarez, Chihuahua, Mexico', 64, 68), ('TEL 52-656', 20, 84),
|
||||
)}))[0]
|
||||
|
||||
# 关键断言:三个值行全部保留,停止标签之后的电话号码不进入结果。
|
||||
assert result.value == 'Blvd Madrid 8560\n32695\nJuarez, Chihuahua, Mexico'
|
||||
|
||||
|
||||
def test_multiline_stop_anchor_ignores_same_label_above_current_anchor():
|
||||
"""页眉或其他区块中位于当前锚点上方的停止标签,不能截断账款地址。"""
|
||||
address = _profile(layout={
|
||||
|
||||
@@ -16,7 +16,6 @@ from sqlalchemy.exc import IntegrityError
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
@@ -285,48 +284,6 @@ def test_order_schema_admin_api_permissions_and_validation(app, client):
|
||||
assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.ORDER_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_fulfillment_policy_admin_api_requires_published_schema_and_admin(app, client):
|
||||
"""关键断言:策略仅由管理员发布,且绑定字段必须存在于当前 published Schema。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_seed_users()
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
configs = []
|
||||
for code, name, value_type in (
|
||||
('reservation_id', '预约单号', 'string'),
|
||||
('part_number', '料号', 'string'),
|
||||
('qty', '数量', 'decimal'),
|
||||
('inventory_source_hint', '库存源线索', 'string'),
|
||||
):
|
||||
config = _field_config(fields[code].id, name=name)
|
||||
config.update({
|
||||
'aliases': [],
|
||||
'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim',
|
||||
'validator_keys': ['positive_decimal'] if value_type == 'decimal' else ['reservation_id'] if code == 'reservation_id' else [],
|
||||
'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text',
|
||||
})
|
||||
configs.append(config)
|
||||
_save_draft(draft['id'], configs)
|
||||
_publish_draft(draft['id'])
|
||||
policy = ShippingFulfillmentPolicy.query.filter_by(status='draft').one()
|
||||
|
||||
forbidden = client.post(
|
||||
f'/api/admin/shipping-fulfillment-policies/{policy.id}/publish',
|
||||
headers=_headers('schema-user', 'user'), json={'expected_lock_version': policy.lock_version},
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN'
|
||||
|
||||
published = client.post(
|
||||
f'/api/admin/shipping-fulfillment-policies/{policy.id}/publish',
|
||||
headers=_headers('schema-admin', 'admin'), json={'expected_lock_version': policy.lock_version},
|
||||
)
|
||||
assert published.status_code == 200
|
||||
assert parse_api_data(published.get_json())['status'] == 'published'
|
||||
|
||||
|
||||
def test_dynamic_header_field_value_is_unique(app):
|
||||
"""Header 动态字段值必须按 extraction+field 唯一,避免 NULL 绕过唯一约束。"""
|
||||
with app.app_context():
|
||||
|
||||
Reference in new issue
Block a user