refactor(shipping-notice): 移除废弃的履约策略模型与相关逻辑

- 删除 `ShippingFulfillmentPolicy` 模型及其依赖,简化字段治理逻辑
- 更新相关服务与 API,确保自动建单策略通过 Schema 草稿管理
- 调整文档与代码注释,反映新的固定履约契约逻辑
- 增强事件审计功能,记录任务状态变化与操作人信息
This commit is contained in:
hugo committed 2026-07-29 23:23:27 +08:00
1 parent aa8fb2616c
commit c85997884b
81 files changed
+2625 -1965

No files matched your search

@@ -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)
@@ -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,
))