feat(shipping-notice): 添加货代履约策略管理功能,支持策略创建、发布及版本控制,增强订单冻结和预约管理逻辑
This commit is contained in:
1 parent
abd8fc1e16
commit
d62f5107b2
82 files changed
+4914
-514
No files matched your search
@@ -63,6 +63,14 @@ def get_order_document_profile_sample_status(intake_no: str):
|
||||
return _ok(service.get_sample_intake_status(intake_no, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/intakes/<string:intake_no>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_order_document_profile_sample(intake_no: str):
|
||||
"""删除未进入盲测且已结束解析的专用模板样本。"""
|
||||
service.delete_sample_intake(intake_no, actor_id=_actor_id())
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/<int:document_id>/tables', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_tables(document_id: int):
|
||||
@@ -70,6 +78,30 @@ def get_order_document_profile_sample_tables(document_id: int):
|
||||
return _ok(service.get_sample_tables(document_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_order_document_profile_coordinate_reconstruction():
|
||||
"""根据管理员确认的相对列边界返回只读坐标重建候选。"""
|
||||
return _ok(service.preview_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', methods=['POST'])
|
||||
@require_admin
|
||||
def suggest_order_document_profile_coordinate_reconstruction():
|
||||
"""根据冻结字符坐标自动建议动态物理行和列边界,结果仍需管理员确认。"""
|
||||
return _ok(service.suggest_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/ocr-coordinate-evidence', methods=['POST'])
|
||||
@require_admin
|
||||
def generate_order_document_profile_ocr_coordinate_evidence():
|
||||
"""为无文字层 PDF 的当前样本表格生成受控 OCR 坐标证据。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(service.generate_ocr_coordinate_evidence(
|
||||
document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/from-sample', methods=['POST'])
|
||||
@require_admin
|
||||
def create_order_document_profile_from_sample():
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice import fulfillment_policy_registry
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
@@ -42,6 +43,25 @@ def shipping_order_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'),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema', methods=['POST'])
|
||||
@require_admin
|
||||
def initialize_shipping_order_schema():
|
||||
|
||||
@@ -39,6 +39,7 @@ from app.models.shipping_fulfillment import (
|
||||
ShippingReservation,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.models.shipping_fulfillment_policy import ShippingFulfillmentPolicy
|
||||
from app.models.shipping_order_schema import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchemaAuditEvent,
|
||||
@@ -218,6 +219,7 @@ __all__ = [
|
||||
'ShippingInventoryVerificationLine',
|
||||
'ShippingExportArtifactLine',
|
||||
'ShippingUploadAttempt',
|
||||
'ShippingFulfillmentPolicy',
|
||||
'ShippingNoticeIntake',
|
||||
'ShippingNoticeDocument',
|
||||
'ShippingNoticeCandidate',
|
||||
|
||||
@@ -19,11 +19,11 @@ from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingReservation(Base):
|
||||
"""预约单当前履约注册表;同一预约号与内部料号在当前版本只能有一条事实。"""
|
||||
"""预约单当前履约注册表;Reservation ID 全局只能归属一个采购单。"""
|
||||
|
||||
__tablename__ = 'shipping_reservations'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('reservation_id', 'part_number', name='uq_shipping_reservations_reservation_part'),
|
||||
UniqueConstraint('reservation_id', name='uq_shipping_reservations_reservation_id'),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'available', 'artifact_reserved', 'uploaded', 'external_change_required')",
|
||||
name='ck_shipping_reservations_status',
|
||||
@@ -35,6 +35,7 @@ class ShippingReservation(Base):
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False)
|
||||
reservation_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
part_number: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
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)
|
||||
@@ -344,14 +344,14 @@ class ShippingInventoryExternalMapping(Base):
|
||||
__tablename__ = 'shipping_inventory_external_mappings'
|
||||
__table_args__ = (
|
||||
Index(
|
||||
'uq_shipping_inventory_external_mappings_source_default_enabled',
|
||||
'uq_shipping_inv_ext_map_src_default_enabled',
|
||||
'inventory_source_id',
|
||||
unique=True,
|
||||
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
|
||||
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_inventory_external_mappings_source_warehouse_enabled',
|
||||
'uq_shipping_inv_ext_map_src_wh_enabled',
|
||||
'inventory_source_id',
|
||||
'freight_warehouse_id',
|
||||
unique=True,
|
||||
|
||||
@@ -38,7 +38,7 @@ class ShippingOrderSnapshot(Base):
|
||||
# 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。
|
||||
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_po_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_code: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
bill_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -80,7 +80,6 @@ class ShippingOrderSnapshotLine(Base):
|
||||
line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
aws_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
uom: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
|
||||
+410
-17
@@ -17,8 +17,8 @@ from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
|
||||
|
||||
|
||||
_LINE_NUMBER_PATTERN = re.compile(r'^0{2,}\d+$')
|
||||
_DELETED_PATTERN = re.compile(r'^\*+\s*item\s+deleted\s*\*+$', re.IGNORECASE)
|
||||
_LINE_NUMBER_PATTERN = re.compile(r'^(?:0{2,}\d+|\d{1,6})$')
|
||||
_DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE)
|
||||
|
||||
|
||||
class CoordinateReconstructionModel(BaseModel):
|
||||
@@ -32,6 +32,7 @@ class CoordinateColumnAnchor(CoordinateReconstructionModel):
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
bbox: LayoutBBox
|
||||
field_code: str | None = None
|
||||
|
||||
|
||||
class ReconstructedCell(CoordinateReconstructionModel):
|
||||
@@ -44,10 +45,10 @@ class ReconstructedCell(CoordinateReconstructionModel):
|
||||
|
||||
|
||||
class ReconstructedRow(CoordinateReconstructionModel):
|
||||
"""一个 y-band 形成的视觉行;删除标记只能附着在前一强锚定行。"""
|
||||
"""一个 y-band 形成的视觉行;其角色供后续逻辑明细合并使用。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
role: Literal['data', 'continuation', 'deleted', 'needs_review']
|
||||
role: Literal['data', 'continuation', 'deleted', 'header', 'summary', 'needs_review']
|
||||
cells: list[ReconstructedCell] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
@@ -67,11 +68,128 @@ class CoordinateTableReconstruction(CoordinateReconstructionModel):
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
_HEADER_TERMS = frozenset({
|
||||
'item', 'material', 'description', 'date', 'price', 'quantity', 'amount',
|
||||
'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev',
|
||||
})
|
||||
_SUMMARY_PATTERN = re.compile(
|
||||
r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
class CoordinateSubrowLayout(CoordinateReconstructionModel):
|
||||
"""一条逻辑明细内某类物理子行的独立列边界与固定字段语义。"""
|
||||
|
||||
role: Literal['main', 'continuation']
|
||||
row_offset: int = Field(ge=0)
|
||||
column_boundaries: list[float] = Field(min_length=2)
|
||||
column_field_codes: list[str | None]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_layout(self) -> 'CoordinateSubrowLayout':
|
||||
"""确保子行边界覆盖整表,且每个区间恰好对应一个字段或忽略项。"""
|
||||
if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate subrow boundaries must start at 0 and end at 1')
|
||||
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
|
||||
raise ValueError('coordinate subrow boundaries must be strictly increasing')
|
||||
if len(self.column_field_codes) != len(self.column_boundaries) - 1:
|
||||
raise ValueError('coordinate subrow field codes must match column count')
|
||||
return self
|
||||
|
||||
|
||||
class ReconstructedLogicalRow(CoordinateReconstructionModel):
|
||||
"""多子行版式合并后的单条逻辑订单明细及来源物理行。"""
|
||||
|
||||
role: Literal['data', 'deleted']
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
source_row_indices: list[int] = Field(min_length=1)
|
||||
|
||||
|
||||
class CoordinateSubrowSuggestion(CoordinateReconstructionModel):
|
||||
"""从实际字符坐标生成的单种物理行版式建议,不包含绝对坐标。"""
|
||||
|
||||
role: Literal['main', 'continuation']
|
||||
row_offset: int = Field(ge=0)
|
||||
column_boundaries: list[float] = Field(min_length=2)
|
||||
column_samples: list[list[str]]
|
||||
suggested_field_codes: list[str | None]
|
||||
|
||||
|
||||
def suggest_multi_subrow_layouts(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
) -> list[CoordinateSubrowSuggestion]:
|
||||
"""
|
||||
从实际物理行和文本起始位置自动建议动态多行版式。
|
||||
|
||||
AI/调用方触发时机:管理员打开坐标重建且不清楚相对边界时调用。算法只负责把
|
||||
同一明细中的第 1..N 行分组并建议列区间;除可确定的 ``line_no`` 外不猜业务字段,
|
||||
建议结果仍须管理员结合示例文字确认。
|
||||
|
||||
Args:
|
||||
characters: 当前表格冻结的 PDF 原生或 OCR 字符坐标。
|
||||
table_bbox: 当前数据表范围。
|
||||
Returns:
|
||||
按 row_offset 排列的动态行建议;找不到可靠主行时返回空列表。
|
||||
"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
glyphs = _table_glyphs(characters, bbox)
|
||||
if not glyphs:
|
||||
return []
|
||||
bands = _group_visual_rows(glyphs)
|
||||
groups: list[list[list[tuple[int, PositionedCharacter]]]] = []
|
||||
current: list[list[tuple[int, PositionedCharacter]]] | None = None
|
||||
for band in bands:
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
compact = re.sub(r'\s+', '', text)
|
||||
if _SUMMARY_PATTERN.search(text):
|
||||
if current:
|
||||
groups.append(current)
|
||||
break
|
||||
if _DELETED_PATTERN.fullmatch(compact):
|
||||
if current:
|
||||
groups.append(current)
|
||||
current = None
|
||||
continue
|
||||
if _band_starts_item(band, bbox):
|
||||
if current:
|
||||
groups.append(current)
|
||||
current = [band]
|
||||
elif current is not None:
|
||||
current.append(band)
|
||||
if current:
|
||||
groups.append(current)
|
||||
if not groups:
|
||||
return []
|
||||
|
||||
max_rows = max(len(group) for group in groups)
|
||||
suggestions: list[CoordinateSubrowSuggestion] = []
|
||||
for row_offset in range(max_rows):
|
||||
samples = [group[row_offset] for group in groups if row_offset < len(group)]
|
||||
boundaries, column_samples, line_column = _suggest_band_boundaries(
|
||||
samples, bbox, detect_line_number=row_offset == 0,
|
||||
)
|
||||
suggestions.append(CoordinateSubrowSuggestion(
|
||||
role='main' if row_offset == 0 else 'continuation',
|
||||
row_offset=row_offset,
|
||||
column_boundaries=boundaries,
|
||||
column_samples=column_samples,
|
||||
suggested_field_codes=[
|
||||
'line_no' if row_offset == 0 and index == line_column else None
|
||||
for index in range(len(boundaries) - 1)
|
||||
],
|
||||
))
|
||||
return suggestions
|
||||
|
||||
|
||||
def reconstruct_table_from_positioned_text(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox,
|
||||
column_anchors: list[CoordinateColumnAnchor | dict[str, Any]],
|
||||
line_start_column_index: int = 0,
|
||||
) -> CoordinateTableReconstruction:
|
||||
"""
|
||||
以 x 列锚点、y 视觉行和内容/邻接辅助规则重建保守候选。
|
||||
@@ -83,7 +201,8 @@ def reconstruct_table_from_positioned_text(
|
||||
Args:
|
||||
characters: 表格范围内外的 PDF 原生字符及 source_index。
|
||||
table_bbox: 当前表格的真实页面范围。
|
||||
column_anchors: 从可信表头得到的列区间,至少两列且不可重叠。
|
||||
column_anchors: 管理员确认的列区间及可选固定字段编码,至少两列且不可重叠。
|
||||
line_start_column_index: 出现有效行号时代表新明细的列,默认第一列。
|
||||
Returns:
|
||||
带 glyph 索引的视觉行候选;status 始终为 needs_review。
|
||||
"""
|
||||
@@ -95,14 +214,19 @@ def reconstruct_table_from_positioned_text(
|
||||
issues: set[str] = set()
|
||||
rows: list[ReconstructedRow] = []
|
||||
previous_has_line_number = False
|
||||
data_region_started = False
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
cells: dict[int, list[tuple[int, PositionedCharacter]]] = {}
|
||||
for glyph_index, glyph in band:
|
||||
column = _assign_column(glyph.bbox, anchors)
|
||||
previous_column: int | None = None
|
||||
for text_run in _group_text_runs(band):
|
||||
run_bbox = _run_bbox(text_run)
|
||||
run_text = ''.join(glyph.text for _, glyph in text_run).strip()
|
||||
column = _assign_column(run_bbox, run_text, anchors, previous_column=previous_column)
|
||||
if column is None:
|
||||
issues.add('coordinate_reconstruction_column_ambiguous')
|
||||
continue
|
||||
cells.setdefault(column, []).append((glyph_index, glyph))
|
||||
cells.setdefault(column, []).extend(text_run)
|
||||
previous_column = column
|
||||
if not cells:
|
||||
continue
|
||||
rebuilt = [
|
||||
@@ -110,27 +234,225 @@ def reconstruct_table_from_positioned_text(
|
||||
for column, value in sorted(cells.items())
|
||||
]
|
||||
text = ' '.join(cell.text for cell in rebuilt)
|
||||
has_line_number = any(_LINE_NUMBER_PATTERN.fullmatch(cell.text.replace(' ', '')) for cell in rebuilt)
|
||||
if _DELETED_PATTERN.fullmatch(text.strip()):
|
||||
role: Literal['data', 'continuation', 'deleted', 'needs_review'] = (
|
||||
has_line_number = any(
|
||||
cell.column_index == line_start_column_index
|
||||
and _LINE_NUMBER_PATTERN.fullmatch(cell.text.replace(' ', ''))
|
||||
for cell in rebuilt
|
||||
)
|
||||
compact_text = re.sub(r'\s+', '', text)
|
||||
if _SUMMARY_PATTERN.search(text):
|
||||
role: Literal['data', 'continuation', 'deleted', 'header', 'summary', 'needs_review'] = 'summary'
|
||||
previous_has_line_number = False
|
||||
elif _DELETED_PATTERN.fullmatch(compact_text):
|
||||
role = (
|
||||
'deleted' if previous_has_line_number else 'needs_review'
|
||||
)
|
||||
if role == 'needs_review':
|
||||
issues.add('coordinate_reconstruction_deleted_row_unattached')
|
||||
elif has_line_number:
|
||||
role = 'data'
|
||||
data_region_started = True
|
||||
elif not data_region_started and _looks_like_header(text):
|
||||
role = 'header'
|
||||
else:
|
||||
role = 'continuation' if previous_has_line_number else 'needs_review'
|
||||
if role == 'needs_review':
|
||||
issues.add('coordinate_reconstruction_row_unanchored')
|
||||
rows.append(ReconstructedRow(row_index=row_index, role=role, cells=rebuilt))
|
||||
previous_has_line_number = has_line_number or (role == 'continuation' and previous_has_line_number)
|
||||
previous_has_line_number = has_line_number or (role in {'continuation', 'deleted'} and previous_has_line_number)
|
||||
|
||||
if not rows:
|
||||
issues.add('coordinate_reconstruction_rows_missing')
|
||||
return CoordinateTableReconstruction(rows=rows, issues=sorted(issues))
|
||||
|
||||
|
||||
def reconstruct_multi_subrow_table(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox,
|
||||
subrow_layouts: list[CoordinateSubrowLayout | dict[str, Any]],
|
||||
line_start_field_code: str = 'line_no',
|
||||
) -> list[ReconstructedLogicalRow]:
|
||||
"""
|
||||
使用每种子行的独立边界,将重叠版式的多条物理行合并为订单明细。
|
||||
|
||||
核心逻辑:每个视觉行先按主行布局寻找行号;命中后开始新明细。后续物理行按
|
||||
``row_offset`` 选择第 2..N 行布局,将值直接合并到固定字段,而不是沿用首行列号。
|
||||
|
||||
Args:
|
||||
characters: 表格范围内的原生或 OCR 字符坐标。
|
||||
table_bbox: 当前数据表页面范围。
|
||||
subrow_layouts: 主行、补充行和属性行的独立边界及字段映射。
|
||||
line_start_field_code: 标记新明细的固定字段,默认 ``line_no``。
|
||||
Returns:
|
||||
合并后的逻辑明细;纯表头、说明和合计区域不会返回。
|
||||
"""
|
||||
layouts = [
|
||||
item if isinstance(item, CoordinateSubrowLayout) else CoordinateSubrowLayout.model_validate(item)
|
||||
for item in subrow_layouts
|
||||
]
|
||||
by_offset = {item.row_offset: item for item in layouts}
|
||||
main = by_offset.get(0)
|
||||
if main is None or not any(code == line_start_field_code for code in main.column_field_codes):
|
||||
raise ValueError('multi-subrow reconstruction requires a main row line-start field')
|
||||
glyphs = _table_glyphs(characters, table_bbox)
|
||||
if not glyphs:
|
||||
return []
|
||||
anchors = {item.row_offset: _layout_anchors(item, table_bbox) for item in layouts}
|
||||
max_offset = max(by_offset)
|
||||
logical_rows: list[ReconstructedLogicalRow] = []
|
||||
current_fields: dict[str, str] | None = None
|
||||
current_sources: list[int] = []
|
||||
continuation_offset = 0
|
||||
current_deleted = False
|
||||
|
||||
def flush() -> None:
|
||||
"""将当前已聚合子行固化为一条逻辑明细。"""
|
||||
nonlocal current_fields, current_sources, current_deleted
|
||||
if current_fields is not None and current_sources:
|
||||
logical_rows.append(ReconstructedLogicalRow(
|
||||
role='deleted' if current_deleted else 'data',
|
||||
fields=current_fields,
|
||||
source_row_indices=current_sources,
|
||||
))
|
||||
current_fields = None
|
||||
current_sources = []
|
||||
current_deleted = False
|
||||
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
raw_text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
compact_text = re.sub(r'\s+', '', raw_text)
|
||||
if _SUMMARY_PATTERN.search(raw_text):
|
||||
flush()
|
||||
break
|
||||
if _DELETED_PATTERN.fullmatch(compact_text):
|
||||
if current_fields is not None:
|
||||
current_deleted = True
|
||||
current_sources.append(row_index)
|
||||
continue
|
||||
|
||||
main_values = _band_field_values(band, anchors[0])
|
||||
line_value = re.sub(r'\s+', '', main_values.get(line_start_field_code, ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_value):
|
||||
flush()
|
||||
current_fields = main_values
|
||||
current_sources = [row_index]
|
||||
continuation_offset = 0
|
||||
continue
|
||||
if current_fields is None:
|
||||
continue
|
||||
|
||||
continuation_offset += 1
|
||||
selected_offset = continuation_offset if continuation_offset in by_offset else max_offset
|
||||
values = _band_field_values(band, anchors[selected_offset])
|
||||
for field_code, value in values.items():
|
||||
previous = current_fields.get(field_code, '').strip()
|
||||
current_fields[field_code] = f'{previous} {value}'.strip()
|
||||
current_sources.append(row_index)
|
||||
|
||||
flush()
|
||||
return logical_rows
|
||||
|
||||
|
||||
def _layout_anchors(layout: CoordinateSubrowLayout, table_bbox: LayoutBBox) -> list[CoordinateColumnAnchor]:
|
||||
"""将子行相对边界转换为当前表格绝对列区间。"""
|
||||
width = table_bbox.x1 - table_bbox.x0
|
||||
return [CoordinateColumnAnchor(
|
||||
column_index=index,
|
||||
field_code=layout.column_field_codes[index],
|
||||
bbox=LayoutBBox(
|
||||
x0=table_bbox.x0 + width * layout.column_boundaries[index], y0=table_bbox.y0,
|
||||
x1=table_bbox.x0 + width * layout.column_boundaries[index + 1], y1=table_bbox.y1,
|
||||
),
|
||||
) for index in range(len(layout.column_field_codes))]
|
||||
|
||||
|
||||
def _band_field_values(
|
||||
band: list[tuple[int, PositionedCharacter]],
|
||||
anchors: list[CoordinateColumnAnchor],
|
||||
) -> dict[str, str]:
|
||||
"""先形成独立文本片段,再以片段中心落入子行区间,避免字段在边界处被拆字。"""
|
||||
values: dict[str, str] = {}
|
||||
for text_run in _group_text_runs(band):
|
||||
bbox = _run_bbox(text_run)
|
||||
center = (bbox.x0 + bbox.x1) / 2
|
||||
candidates = [
|
||||
anchor.column_index for anchor in anchors
|
||||
if anchor.bbox.x0 <= center <= anchor.bbox.x1
|
||||
]
|
||||
if len(candidates) != 1:
|
||||
continue
|
||||
column = candidates[0]
|
||||
field_code = anchors[column].field_code
|
||||
text = ''.join(glyph.text for _, glyph in text_run).strip()
|
||||
if not field_code or not text:
|
||||
continue
|
||||
previous = values.get(field_code, '').strip()
|
||||
values[field_code] = f'{previous} {text}'.strip()
|
||||
return values
|
||||
|
||||
|
||||
def _looks_like_header(text: str) -> bool:
|
||||
"""以有限英文表头词识别数据区之前的多层表头,避免把表头并入首条明细。"""
|
||||
words = set(re.findall(r'[a-z]+', text.lower()))
|
||||
return len(words & _HEADER_TERMS) >= 2
|
||||
|
||||
|
||||
def _band_starts_item(
|
||||
band: list[tuple[int, PositionedCharacter]], table_bbox: LayoutBBox,
|
||||
) -> bool:
|
||||
"""以左侧文本片段的行号形态识别新明细,不依赖已经配置的列边界。"""
|
||||
width = table_bbox.x1 - table_bbox.x0
|
||||
for run in _group_text_runs(band):
|
||||
bbox = _run_bbox(run)
|
||||
relative_center = ((bbox.x0 + bbox.x1) / 2 - table_bbox.x0) / width
|
||||
text = re.sub(r'\s+', '', ''.join(glyph.text for _, glyph in run))
|
||||
if relative_center <= 0.25 and _LINE_NUMBER_PATTERN.fullmatch(text):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _suggest_band_boundaries(
|
||||
bands: list[list[tuple[int, PositionedCharacter]]],
|
||||
table_bbox: LayoutBBox,
|
||||
*,
|
||||
detect_line_number: bool,
|
||||
) -> tuple[list[float], list[list[str]], int | None]:
|
||||
"""聚合相同 row_offset 的文本起始位置,以相邻列中心中点生成稳定相对边界。"""
|
||||
width = table_bbox.x1 - table_bbox.x0
|
||||
runs: list[tuple[float, str, bool]] = []
|
||||
for band in bands:
|
||||
for run in _group_text_runs(band):
|
||||
bbox = _run_bbox(run)
|
||||
center = max(0.0, min(1.0, ((bbox.x0 + bbox.x1) / 2 - table_bbox.x0) / width))
|
||||
text = ''.join(glyph.text for _, glyph in run).strip()
|
||||
if text:
|
||||
runs.append((center, text, bool(_LINE_NUMBER_PATTERN.fullmatch(re.sub(r'\s+', '', text)))))
|
||||
if not runs:
|
||||
return [0.0, 1.0], [[]], None
|
||||
|
||||
centers: list[float] = []
|
||||
clusters: list[list[tuple[float, str, bool]]] = []
|
||||
for item in sorted(runs, key=lambda value: value[0]):
|
||||
nearest = min(range(len(centers)), key=lambda index: abs(centers[index] - item[0])) if centers else None
|
||||
if nearest is not None and abs(centers[nearest] - item[0]) <= 0.045:
|
||||
clusters[nearest].append(item)
|
||||
centers[nearest] = median(value[0] for value in clusters[nearest])
|
||||
else:
|
||||
centers.append(item[0])
|
||||
clusters.append([item])
|
||||
ordered = sorted(zip(centers, clusters), key=lambda item: item[0])
|
||||
centers = [item[0] for item in ordered]
|
||||
clusters = [item[1] for item in ordered]
|
||||
boundaries = [0.0] + [round((left + right) / 2, 4) for left, right in zip(centers, centers[1:])] + [1.0]
|
||||
column_samples = [list(dict.fromkeys(value[1] for value in cluster))[:3] for cluster in clusters]
|
||||
line_column = next((
|
||||
index for index, cluster in enumerate(clusters)
|
||||
if detect_line_number and any(value[2] for value in cluster)
|
||||
), None)
|
||||
return boundaries, column_samples, line_column
|
||||
|
||||
|
||||
def _validated_anchors(raw: list[CoordinateColumnAnchor | dict[str, Any]]) -> list[CoordinateColumnAnchor]:
|
||||
"""校验列锚点数量、排序与不重叠,防止错误表头诱导列归属。"""
|
||||
anchors = sorted(
|
||||
@@ -175,16 +497,87 @@ def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[li
|
||||
return bands
|
||||
|
||||
|
||||
def _assign_column(bbox: LayoutBBox, anchors: list[CoordinateColumnAnchor]) -> int | None:
|
||||
"""优先最大 x-overlap,只有唯一最佳候选才允许归属;中心距离仅作无重叠时的后备。"""
|
||||
def _group_text_runs(
|
||||
band: list[tuple[int, PositionedCharacter]],
|
||||
) -> list[list[tuple[int, PositionedCharacter]]]:
|
||||
"""将同一视觉行的相邻字符组成文本片段,使字段格式评分可看到完整值。"""
|
||||
ordered = sorted(band, key=lambda item: (item[1].bbox.x0, item[0]))
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in ordered]
|
||||
gap_limit = max(2.0, median(widths) * 1.8)
|
||||
runs: list[list[tuple[int, PositionedCharacter]]] = []
|
||||
for item in ordered:
|
||||
if runs and item[1].bbox.x0 - runs[-1][-1][1].bbox.x1 <= gap_limit:
|
||||
runs[-1].append(item)
|
||||
else:
|
||||
runs.append([item])
|
||||
return runs
|
||||
|
||||
|
||||
def _run_bbox(run: list[tuple[int, PositionedCharacter]]) -> LayoutBBox:
|
||||
"""汇总文本片段 bbox,供列重叠与中心距离共同评分。"""
|
||||
boxes = [glyph.bbox for _, glyph in run]
|
||||
return LayoutBBox(
|
||||
x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes),
|
||||
x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes),
|
||||
)
|
||||
|
||||
|
||||
def _assign_column(
|
||||
bbox: LayoutBBox,
|
||||
text: str,
|
||||
anchors: list[CoordinateColumnAnchor],
|
||||
*,
|
||||
previous_column: int | None,
|
||||
) -> int | None:
|
||||
"""以 x-overlap 为主,字段格式和同行从左到右顺序只辅助边界歧义。"""
|
||||
overlaps = [max(0.0, min(bbox.x1, item.bbox.x1) - max(bbox.x0, item.bbox.x0)) for item in anchors]
|
||||
best_overlap = max(overlaps)
|
||||
if best_overlap > 0 and overlaps.count(best_overlap) == 1:
|
||||
return anchors[overlaps.index(best_overlap)].column_index
|
||||
if best_overlap > 0:
|
||||
candidates = [index for index, overlap in enumerate(overlaps) if overlap >= best_overlap * 0.8]
|
||||
if len(candidates) == 1:
|
||||
return anchors[candidates[0]].column_index
|
||||
scores = []
|
||||
for index in candidates:
|
||||
adjacency = 0.0
|
||||
if previous_column is not None:
|
||||
if anchors[index].column_index < previous_column:
|
||||
adjacency = -1.0
|
||||
elif anchors[index].column_index in {previous_column, previous_column + 1}:
|
||||
adjacency = 0.25
|
||||
scores.append(
|
||||
overlaps[index]
|
||||
+ _field_content_score(text, anchors[index].field_code) * max(bbox.x1 - bbox.x0, 1.0) * 0.25
|
||||
+ adjacency
|
||||
)
|
||||
best_score = max(scores)
|
||||
return anchors[candidates[scores.index(best_score)]].column_index if scores.count(best_score) == 1 else None
|
||||
center = (bbox.x0 + bbox.x1) / 2
|
||||
distances = [abs(center - (item.bbox.x0 + item.bbox.x1) / 2) for item in anchors]
|
||||
nearest = min(distances)
|
||||
return anchors[distances.index(nearest)].column_index if distances.count(nearest) == 1 else None
|
||||
candidates = [index for index, distance in enumerate(distances) if distance == nearest]
|
||||
if previous_column is not None:
|
||||
ordered_candidates = [index for index in candidates if anchors[index].column_index >= previous_column]
|
||||
candidates = ordered_candidates or candidates
|
||||
return anchors[candidates[0]].column_index if len(candidates) == 1 else None
|
||||
|
||||
|
||||
def _field_content_score(text: str, field_code: str | None) -> float:
|
||||
"""对固定订单字段执行有限格式评分;未知字段不影响几何归列。"""
|
||||
value = str(text or '').strip()
|
||||
if not value or not field_code:
|
||||
return 0.0
|
||||
compact = value.replace(',', '').replace(' ', '')
|
||||
if field_code == 'line_no':
|
||||
return 1.0 if _LINE_NUMBER_PATTERN.fullmatch(compact) else -1.0
|
||||
if field_code in {'qty', 'unit_price', 'amount'}:
|
||||
return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0
|
||||
if field_code == 'uom':
|
||||
return 1.0 if re.fullmatch(r'[A-Za-z]{1,6}', compact) else -0.5
|
||||
if field_code == 'required_date':
|
||||
return 1.0 if re.fullmatch(r'\d{1,4}[-/]\d{1,2}[-/]\d{1,4}', compact) else -0.5
|
||||
if field_code in {'part_number', 'customer_part_number', 'aws_part_number'}:
|
||||
return 0.75 if re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/-]{2,}', compact) else 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell:
|
||||
|
||||
@@ -3,12 +3,13 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
|
||||
用途:定义订单文档模板级解析 Profile 纯契约,覆盖全局 Schema 无法表达的模板列语义。
|
||||
依赖:Pydantic、HTML 网格、订单字段规则和既有 TEMP 复合料号规则。
|
||||
逻辑:Profile 只在精确结构指纹命中时按固定列执行注册解析器;行结构已丢失的模板显式阻断,不做相似匹配。
|
||||
逻辑:普通 Profile 按精确表头指纹匹配;坐标 Profile 先合并物理续行并生成稳定虚拟表头,再按固定列执行注册解析器。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
from decimal import Decimal
|
||||
@@ -17,6 +18,7 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
@@ -66,6 +68,45 @@ class OrderProfileColumnRule(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
class CoordinateReconstructionProfile(OrderProfileModel):
|
||||
"""冻结管理员确认的相对列边界;同版 PDF 表格据此重建并仍受 Profile 精确指纹门禁。"""
|
||||
|
||||
method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1'
|
||||
column_boundaries: list[float] = Field(default_factory=list)
|
||||
column_field_codes: list[str | None] = Field(default_factory=list)
|
||||
line_start_column_index: int = Field(default=0, ge=0)
|
||||
subrow_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_boundaries(self) -> 'CoordinateReconstructionProfile':
|
||||
"""边界须覆盖整表且严格递增,禁止由错误 HTML 反向猜列。"""
|
||||
if self.subrow_layouts:
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout
|
||||
|
||||
layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts]
|
||||
offsets = [item.row_offset for item in layouts]
|
||||
roles = [item.role for item in layouts]
|
||||
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or roles.count('main') != 1:
|
||||
raise ValueError('coordinate subrow layouts require contiguous offsets and one main row')
|
||||
if next(item for item in layouts if item.role == 'main').row_offset != 0:
|
||||
raise ValueError('coordinate main row must use offset zero')
|
||||
if any(item.row_offset > 0 and item.role != 'continuation' for item in layouts):
|
||||
raise ValueError('coordinate rows after the main row must be continuations')
|
||||
return self
|
||||
if len(self.column_boundaries) < 3:
|
||||
raise ValueError('coordinate reconstruction requires column boundaries')
|
||||
if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate reconstruction boundaries must start at 0 and end at 1')
|
||||
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
|
||||
raise ValueError('coordinate reconstruction boundaries must be strictly increasing')
|
||||
column_count = len(self.column_boundaries) - 1
|
||||
if self.column_field_codes and len(self.column_field_codes) != column_count:
|
||||
raise ValueError('coordinate reconstruction field codes must match column count')
|
||||
if self.line_start_column_index >= column_count:
|
||||
raise ValueError('coordinate reconstruction line start column is out of range')
|
||||
return self
|
||||
|
||||
|
||||
class OrderDocumentProfile(OrderProfileModel):
|
||||
"""保存不可变模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
|
||||
@@ -77,6 +118,7 @@ class OrderDocumentProfile(OrderProfileModel):
|
||||
data_start_row_index: int = Field(ge=1)
|
||||
row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved'
|
||||
column_rules: list[OrderProfileColumnRule] = Field(default_factory=list)
|
||||
coordinate_reconstruction: CoordinateReconstructionProfile | None = None
|
||||
drop_zero_qty: bool = True
|
||||
|
||||
@model_validator(mode='after')
|
||||
@@ -171,6 +213,104 @@ def order_profile_structure_fingerprint(
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def reconstruct_order_profile_html(
|
||||
*, characters: list[dict[str, Any]], table_bbox: dict[str, Any],
|
||||
reconstruction: CoordinateReconstructionProfile,
|
||||
) -> str:
|
||||
"""
|
||||
利用冻结坐标证据生成带稳定虚拟表头的逻辑明细 HTML。
|
||||
|
||||
核心逻辑:先按 x/y 重建物理行,再将 continuation 按列并入最近 data 行;deleted
|
||||
回写最近明细状态,summary 终止数据区。虚拟表头只表达列序,不依赖数据页表头是否完整。
|
||||
|
||||
Args:
|
||||
characters: 当前表格 bbox 内的原生或 OCR 字符坐标。
|
||||
table_bbox: 当前表格页面坐标。
|
||||
reconstruction: 管理员确认的相对列边界。
|
||||
Returns:
|
||||
可由既有 Profile 解析器消费的 HTML;行角色保存在 ``data-row-role`` 属性中。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
CoordinateColumnAnchor,
|
||||
reconstruct_multi_subrow_table,
|
||||
reconstruct_table_from_positioned_text,
|
||||
)
|
||||
|
||||
bbox = LayoutBBox.model_validate(table_bbox)
|
||||
if reconstruction.subrow_layouts:
|
||||
logical_rows = reconstruct_multi_subrow_table(
|
||||
characters=characters,
|
||||
table_bbox=bbox,
|
||||
subrow_layouts=reconstruction.subrow_layouts,
|
||||
)
|
||||
field_codes = []
|
||||
for layout in reconstruction.subrow_layouts:
|
||||
for code in layout.get('column_field_codes') or []:
|
||||
if code and code not in field_codes:
|
||||
field_codes.append(code)
|
||||
header = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>{html.escape(code)}</th>' for code in field_codes
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row.role, ','.join(str(index) for index in row.source_row_indices),
|
||||
''.join(f'<td>{html.escape(row.fields.get(code, ""))}</td>' for code in field_codes),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
boundaries = reconstruction.column_boundaries
|
||||
width = bbox.x1 - bbox.x0
|
||||
anchors = [CoordinateColumnAnchor(
|
||||
column_index=index,
|
||||
field_code=(reconstruction.column_field_codes[index] if reconstruction.column_field_codes else None),
|
||||
bbox=LayoutBBox(
|
||||
x0=bbox.x0 + width * boundaries[index], y0=bbox.y0,
|
||||
x1=bbox.x0 + width * boundaries[index + 1], y1=bbox.y1,
|
||||
),
|
||||
) for index in range(len(boundaries) - 1)]
|
||||
result = reconstruct_table_from_positioned_text(
|
||||
characters=characters, table_bbox=bbox, column_anchors=anchors,
|
||||
line_start_column_index=reconstruction.line_start_column_index,
|
||||
)
|
||||
if not result.rows:
|
||||
raise ValidationError(
|
||||
'No coordinate reconstruction rows were produced',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE',
|
||||
)
|
||||
logical_rows: list[dict[str, Any]] = []
|
||||
for row in result.rows:
|
||||
values = {cell.column_index: cell.text for cell in row.cells}
|
||||
if row.role == 'data':
|
||||
logical_rows.append({'role': 'data', 'values': values, 'source_rows': [row.row_index]})
|
||||
elif row.role == 'continuation' and logical_rows:
|
||||
current = logical_rows[-1]
|
||||
for column_index, value in values.items():
|
||||
previous = str(current['values'].get(column_index) or '').strip()
|
||||
current['values'][column_index] = f'{previous} {value}'.strip()
|
||||
current['source_rows'].append(row.row_index)
|
||||
elif row.role == 'deleted' and logical_rows:
|
||||
logical_rows[-1]['role'] = 'deleted'
|
||||
logical_rows[-1]['source_rows'].append(row.row_index)
|
||||
elif row.role == 'summary':
|
||||
break
|
||||
|
||||
header = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>coordinate_column_{index + 1}</th>' for index in range(len(anchors))
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row['role'], ','.join(str(index) for index in row['source_rows']),
|
||||
''.join(
|
||||
f'<td>{html.escape(str(row["values"].get(index, "")))}</td>'
|
||||
for index in range(len(anchors))
|
||||
),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
|
||||
|
||||
def parse_html_table_with_order_profile(
|
||||
html: str,
|
||||
*,
|
||||
@@ -210,15 +350,19 @@ def parse_html_table_with_order_profile(
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_column_out_of_range'],
|
||||
)
|
||||
row_roles = _profile_html_row_roles(html)
|
||||
rows = [
|
||||
_parse_profile_row(
|
||||
grid,
|
||||
row_index=index,
|
||||
profile=profile,
|
||||
contract=contract,
|
||||
source_role=row_roles[index] if index < len(row_roles) else 'data',
|
||||
)
|
||||
for index in range(profile.data_start_row_index, grid.row_count)
|
||||
]
|
||||
if not rows:
|
||||
return OrderProfileParseResult(matched=False)
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
@@ -233,8 +377,9 @@ def _parse_profile_row(
|
||||
row_index: int,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
source_role: str = 'data',
|
||||
) -> OrderProfileRowResult:
|
||||
"""执行一条 preserved 模板行;零 Qty 删除,非法字段保留机器问题码。"""
|
||||
"""执行一条逻辑模板行;坐标重建删除状态和零 Qty 均映射为 deleted。"""
|
||||
fields: dict[str, Any] = {}
|
||||
issues: list[str] = []
|
||||
explicit_qty: float | None = None
|
||||
@@ -258,7 +403,7 @@ def _parse_profile_row(
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
fields[code] = _profile_json_value(value)
|
||||
if profile.drop_zero_qty and explicit_qty == 0:
|
||||
if source_role == 'deleted' or (profile.drop_zero_qty and explicit_qty == 0):
|
||||
return OrderProfileRowResult(row_index=row_index, status='deleted')
|
||||
required_build = {'part_number', 'qty'}
|
||||
if not required_build.issubset(fields):
|
||||
@@ -271,6 +416,16 @@ def _parse_profile_row(
|
||||
)
|
||||
|
||||
|
||||
def _profile_html_row_roles(source_html: str) -> list[str]:
|
||||
"""读取坐标重建写入的受控行角色;普通 MinerU HTML 默认按 data 处理。"""
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
table = BeautifulSoup(source_html or '', 'html.parser').find('table')
|
||||
if table is None:
|
||||
return []
|
||||
return [str(row.get('data-row-role') or 'data') for row in table.find_all('tr')]
|
||||
|
||||
|
||||
def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
|
||||
"""执行代码注册的有限解析器;未知 key 不允许运行。"""
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
@@ -289,11 +444,16 @@ def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结 Schema 类型和 validator 规范化模板字段;非法值返回 None。"""
|
||||
"""按冻结 Schema 类型和 validator 规范化模板字段;模板日期兼容常见美式订单格式。"""
|
||||
if config is None:
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate = raw
|
||||
if value_type == 'date':
|
||||
text = str(raw or '').strip()
|
||||
matched = re.fullmatch(r'(\d{1,2})/(\d{1,2})/(\d{4})', text)
|
||||
if matched:
|
||||
candidate = f'{matched.group(3)}-{int(matched.group(1)):02d}-{int(matched.group(2)):02d}'
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
candidate = parse_number(raw)
|
||||
if candidate is None:
|
||||
|
||||
@@ -167,6 +167,7 @@ def build_mineru_table_snapshot(
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
extract_native_pdf_pages,
|
||||
)
|
||||
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
@@ -174,6 +175,10 @@ def build_mineru_table_snapshot(
|
||||
content=content, mineru=candidate,
|
||||
)
|
||||
snapshot['layout_candidate'] = layout.model_dump(mode='json')
|
||||
# 仅保存表格范围内的原生字符坐标,供管理员确认后的坐标模板在 Run 冻结快照中复现。
|
||||
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
|
||||
content=content, tables=tables,
|
||||
)
|
||||
except Exception:
|
||||
snapshot['issues'] = sorted(set(
|
||||
list(snapshot['issues']) + ['native_pdf_layout_candidate_invalid'],
|
||||
@@ -181,6 +186,34 @@ def build_mineru_table_snapshot(
|
||||
return snapshot
|
||||
|
||||
|
||||
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""按 MinerU 整表 bbox 截取 PDF 字符证据;非表格正文与页面图像绝不持久化。"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
|
||||
pages = {item.page_no: item for item in extract_native_pdf_pages(content)}
|
||||
evidence: dict[str, list[dict[str, Any]]] = {}
|
||||
for table in tables:
|
||||
table_id = str(table.get('table_id') or '')
|
||||
raw_bbox = table.get('bbox')
|
||||
page = pages.get(int(table.get('page_no') or 0))
|
||||
if not table_id or page is None or not isinstance(raw_bbox, dict):
|
||||
continue
|
||||
try:
|
||||
x0, y0 = float(raw_bbox['x0']), float(raw_bbox['y0'])
|
||||
x1, y1 = float(raw_bbox['x1']), float(raw_bbox['y1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
glyphs = []
|
||||
for item in page.characters:
|
||||
center_x = (item.bbox.x0 + item.bbox.x1) / 2
|
||||
center_y = (item.bbox.y0 + item.bbox.y1) / 2
|
||||
if x0 <= center_x <= x1 and y0 <= center_y <= y1:
|
||||
glyphs.append(item.model_dump(mode='json'))
|
||||
if glyphs:
|
||||
evidence[table_id] = glyphs
|
||||
return {'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence}
|
||||
|
||||
|
||||
def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None:
|
||||
"""就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。"""
|
||||
meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {}
|
||||
|
||||
@@ -22,7 +22,10 @@ from app.models import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.order_profile import parse_html_table_with_order_profile
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_service import _definition_contract
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
@@ -109,8 +112,25 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
failures: list[str] = []
|
||||
passed = 0
|
||||
for sample in suite.samples:
|
||||
html = _table_html(sample.document_id, sample.table_id)
|
||||
if parser.coordinate_reconstruction is not None:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
layout = current_layout_snapshot(document) if document is not None else None
|
||||
raw_table = next((
|
||||
item for item in (layout or {}).get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id
|
||||
), None)
|
||||
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
|
||||
characters = (evidence.get('tables') or {}).get(sample.table_id) if isinstance(evidence.get('tables'), dict) else None
|
||||
if not isinstance(raw_table, dict) or not isinstance(raw_table.get('bbox'), dict) or not isinstance(characters, list):
|
||||
failures.append(f'sample:{sample.id}:coordinate_evidence_missing')
|
||||
continue
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=[item for item in characters if isinstance(item, dict)],
|
||||
table_bbox=raw_table['bbox'], reconstruction=parser.coordinate_reconstruction,
|
||||
)
|
||||
parsed = parse_html_table_with_order_profile(
|
||||
_table_html(sample.document_id, sample.table_id), table_id=sample.table_id,
|
||||
html, table_id=sample.table_id,
|
||||
profile=parser, contract=contract,
|
||||
)
|
||||
actual = [dict(row.fields) for row in parsed.rows if row.status == 'parsed']
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
@@ -28,6 +29,7 @@ from app.services.shipping_notice.business_fingerprint import (
|
||||
build_business_fingerprint,
|
||||
build_content_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
# 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态)
|
||||
_ACTIVE_PROCESS_STATUSES = frozenset(
|
||||
@@ -82,6 +84,36 @@ def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[
|
||||
}
|
||||
|
||||
|
||||
def _reservation_differences(task: ShippingTask, summary: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。"""
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
if snapshot is None:
|
||||
return []
|
||||
proposed = {
|
||||
validated_reservation_id(str(line.get('reservation_id') or '')): line
|
||||
for line in summary.get('lines') or []
|
||||
if isinstance(line, dict) and validated_reservation_id(str(line.get('reservation_id') or ''))
|
||||
}
|
||||
differences: list[dict[str, Any]] = []
|
||||
for line in snapshot.lines:
|
||||
reservation_id = validated_reservation_id(line.reservation_id)
|
||||
candidate_line = proposed.get(reservation_id)
|
||||
if not reservation_id or candidate_line is None:
|
||||
continue
|
||||
previous = {'part_number': str(line.part_number or '').strip(), 'qty': str(line.qty)}
|
||||
proposed_value = {
|
||||
'part_number': str(candidate_line.get('part_number') or '').strip(),
|
||||
'qty': str(candidate_line.get('qty') or '').strip(),
|
||||
}
|
||||
if previous != proposed_value:
|
||||
differences.append({
|
||||
'reservation_id': reservation_id,
|
||||
'previous': previous,
|
||||
'proposed': proposed_value,
|
||||
})
|
||||
return differences
|
||||
|
||||
|
||||
def _allowed_actions_for(
|
||||
*,
|
||||
status: str,
|
||||
@@ -245,6 +277,10 @@ def detect_duplicates_for_intake(
|
||||
}
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
blocking = False
|
||||
for match in matches:
|
||||
task = db.session.query(ShippingTask).filter_by(task_no=match['task_no']).one_or_none()
|
||||
if task is not None:
|
||||
match['reservation_differences'] = _reservation_differences(task, summary)
|
||||
|
||||
return {
|
||||
'status': status,
|
||||
@@ -569,6 +605,10 @@ def detect_duplicates_for_candidate(
|
||||
}
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
blocking = False
|
||||
for match in matches:
|
||||
task = db.session.query(ShippingTask).filter_by(task_no=match['task_no']).one_or_none()
|
||||
if task is not None:
|
||||
match['reservation_differences'] = _reservation_differences(task, summary)
|
||||
|
||||
return {
|
||||
'status': status,
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
services/shipping_notice/fulfillment_policy_registry.py
|
||||
|
||||
用途:管理货代字段能力绑定与版本化滚动履约策略。
|
||||
依赖:订单 Schema、履约策略模型与统一 AppError。
|
||||
逻辑:策略使用稳定 field_id 绑定货代能力;冻结只消费当前 published 策略,历史 Snapshot 保存完整策略事实。
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
|
||||
SHIP_AVAILABLE_ROLLING_V1 = 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
_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',
|
||||
}
|
||||
|
||||
|
||||
def capability_catalog() -> list[dict[str, Any]]:
|
||||
"""返回货代专用能力目录;管理员不能配置自由代码、SQL 或脚本。"""
|
||||
return [{'capability_code': code, **spec} for code, spec in sorted(_CAPABILITIES.items())]
|
||||
|
||||
|
||||
def _schema() -> ShippingOrderSchema:
|
||||
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, *, schema_id: int) -> list[dict[str, Any]]:
|
||||
"""校验能力与稳定 field_id 的一对一绑定,拒绝 scope/type 漂移。"""
|
||||
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.schema_id != schema_id 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')
|
||||
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], *, schema_id: int) -> 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')
|
||||
return {
|
||||
'policy_code': policy_code,
|
||||
'fulfillment_mode': 'ship_available_rolling',
|
||||
'requires_confirmed_customer': True,
|
||||
'allows_partial_reservation': False,
|
||||
'field_bindings': _field_bindings(raw.get('field_bindings'), schema_id=schema_id),
|
||||
}
|
||||
|
||||
|
||||
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 get_state() -> dict[str, Any]:
|
||||
"""读取货代履约策略管理状态及当前发布版本。"""
|
||||
schema = _schema()
|
||||
policies = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).all()
|
||||
return {'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')
|
||||
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 not None:
|
||||
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:
|
||||
"""取得当前可执行策略;没有发布版本时 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')
|
||||
return selected
|
||||
@@ -19,17 +19,22 @@ from sqlalchemy import func
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentProfileTestSample,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import suggest_multi_subrow_layouts
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
CoordinateReconstructionProfile,
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
diagnose_order_profile_header,
|
||||
order_profile_structure_fingerprint,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
|
||||
|
||||
@@ -72,7 +77,15 @@ def _require_schema_version(raw_id: Any) -> ShippingOrderSchemaVersion:
|
||||
|
||||
|
||||
def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
"""校验纯 Profile 契约并把每个目标字段冻结为 field_id + field_code。"""
|
||||
"""
|
||||
校验 Profile 契约、冻结字段 ID,并确保坐标辅助规则与实际列映射一致。
|
||||
|
||||
Args:
|
||||
raw: 管理端提交的模板定义;禁止信任浏览器生成的字段辅助数组。
|
||||
schema_version: 当前模板绑定的不可变订单字段版本。
|
||||
Returns:
|
||||
可持久化的标准定义;坐标列字段和新行列均由列规则重新计算。
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError(
|
||||
'Order profile definition must be an object',
|
||||
@@ -104,6 +117,56 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
|
||||
for code in rule.target_field_codes
|
||||
],
|
||||
})
|
||||
raw_reconstruction = raw.get('coordinate_reconstruction')
|
||||
if isinstance(raw_reconstruction, dict):
|
||||
raw_subrows = raw_reconstruction.get('subrow_layouts')
|
||||
if isinstance(raw_subrows, list) and raw_subrows:
|
||||
normalized_subrows: list[dict[str, Any]] = []
|
||||
output_field_codes: list[str] = []
|
||||
for raw_subrow in raw_subrows:
|
||||
if not isinstance(raw_subrow, dict):
|
||||
raise ValidationError(
|
||||
'Coordinate subrow layout is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
codes = raw_subrow.get('column_field_codes')
|
||||
if not isinstance(codes, list) or any(
|
||||
code is not None and str(code).strip() not in fields for code in codes
|
||||
):
|
||||
raise ValidationError(
|
||||
'Coordinate subrow target field is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
)
|
||||
normalized_subrows.append({
|
||||
**raw_subrow,
|
||||
'column_field_codes': [str(code).strip() if code is not None else None for code in codes],
|
||||
})
|
||||
for code in codes:
|
||||
normalized = str(code).strip() if code is not None else ''
|
||||
if normalized and normalized not in output_field_codes:
|
||||
output_field_codes.append(normalized)
|
||||
normalized_rules = [{
|
||||
**OrderProfileColumnRule(
|
||||
column_index=index, extractor_key='direct', target_field_codes=[code],
|
||||
).model_dump(),
|
||||
'target_fields': [{'field_id': str(fields[code]['field_id']), 'field_code': code}],
|
||||
} for index, code in enumerate(output_field_codes)]
|
||||
raw_reconstruction = {**raw_reconstruction, 'subrow_layouts': normalized_subrows}
|
||||
else:
|
||||
column_count = len(raw_reconstruction.get('column_boundaries') or []) - 1
|
||||
field_codes: list[str | None] = [None] * max(column_count, 0)
|
||||
for rule in normalized_rules:
|
||||
column_index = int(rule['column_index'])
|
||||
if column_index < len(field_codes):
|
||||
field_codes[column_index] = str(rule['target_field_codes'][0])
|
||||
line_start_column_index = next(
|
||||
(index for index, code in enumerate(field_codes) if code == 'line_no'), 0,
|
||||
)
|
||||
raw_reconstruction = {
|
||||
**raw_reconstruction,
|
||||
'column_field_codes': field_codes,
|
||||
'line_start_column_index': line_start_column_index,
|
||||
}
|
||||
try:
|
||||
contract = OrderDocumentProfile(
|
||||
profile_code='VALIDATION_PROFILE',
|
||||
@@ -115,6 +178,7 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
|
||||
column_rules=[OrderProfileColumnRule(**{
|
||||
key: value for key, value in item.items() if key != 'target_fields'
|
||||
}) for item in normalized_rules],
|
||||
coordinate_reconstruction=raw_reconstruction,
|
||||
drop_zero_qty=raw.get('drop_zero_qty', True),
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
@@ -128,6 +192,10 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
|
||||
'data_start_row_index': contract.data_start_row_index,
|
||||
'row_structure': contract.row_structure,
|
||||
'column_rules': normalized_rules,
|
||||
'coordinate_reconstruction': (
|
||||
contract.coordinate_reconstruction.model_dump()
|
||||
if contract.coordinate_reconstruction else None
|
||||
),
|
||||
'drop_zero_qty': contract.drop_zero_qty,
|
||||
}
|
||||
|
||||
@@ -145,6 +213,7 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderDocument
|
||||
column_rules=[OrderProfileColumnRule(**{
|
||||
key: value for key, value in rule.items() if key != 'target_fields'
|
||||
}) for rule in definition.get('column_rules') or [] if isinstance(rule, dict)],
|
||||
coordinate_reconstruction=definition.get('coordinate_reconstruction'),
|
||||
drop_zero_qty=definition.get('drop_zero_qty', True),
|
||||
)
|
||||
|
||||
@@ -194,6 +263,102 @@ def _document_layout(document: ShippingNoticeDocument) -> dict[str, Any]:
|
||||
return layout
|
||||
|
||||
|
||||
def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[str, Any]]:
|
||||
"""读取当前布局冻结的整表原生字符;向浏览器只返回重建后的网格,不泄露坐标。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
characters = tables.get(table_id) if isinstance(tables.get(table_id), list) else []
|
||||
return [item for item in characters if isinstance(item, dict)]
|
||||
|
||||
|
||||
def generate_ocr_coordinate_evidence(*, document_id: int, table_id: str, actor_id: int | None) -> dict[str, Any]:
|
||||
"""为无文字层 PDF 的指定表格生成 OCR 坐标证据;仅管理员审核后的模板可使用。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
if document is None or not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
raise ValidationError('OCR coordinate reconstruction requires a PDF sample', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE')
|
||||
layout = _document_layout(document)
|
||||
raw_table = next((
|
||||
item for item in layout.get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id or '').strip()
|
||||
), None)
|
||||
if raw_table is None or not isinstance(raw_table.get('bbox'), dict):
|
||||
raise ValidationError('Selected sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
asset = db.session.get(FileAsset, document.asset_id)
|
||||
if asset is None:
|
||||
raise ValidationError('Sample file is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE')
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
|
||||
|
||||
try:
|
||||
page = next(
|
||||
item for item in extract_native_pdf_pages(read_asset_bytes(asset))
|
||||
if item.page_no == int(raw_table.get('page_no') or 0)
|
||||
)
|
||||
lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
characters = _ocr_lines_to_characters(lines=lines, table_bbox=raw_table['bbox'])
|
||||
except Exception as exc:
|
||||
raise ValidationError('OCR coordinate reconstruction is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
|
||||
if not characters:
|
||||
raise ValidationError('OCR found no usable table text', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE')
|
||||
next_snapshot = dict(layout)
|
||||
evidence = dict(next_snapshot.get('coordinate_evidence') or {})
|
||||
evidence_tables = dict(evidence.get('tables') or {})
|
||||
evidence_tables[str(raw_table['table_id'])] = characters
|
||||
next_snapshot['coordinate_evidence'] = {
|
||||
'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence_tables,
|
||||
'sources': {**dict(evidence.get('sources') or {}), str(raw_table['table_id']): 'ocr'},
|
||||
}
|
||||
next_snapshot['issues'] = sorted(set(list(next_snapshot.get('issues') or []) + ['coordinate_evidence_ocr_needs_review']))
|
||||
record_inline_layout_snapshot(
|
||||
document, next_snapshot,
|
||||
parser_key='mineru-pipeline+rapidocr:shipping_order_coordinate_evidence.v1',
|
||||
)
|
||||
db.session.commit()
|
||||
return {'document_id': document.id, 'table_id': str(raw_table['table_id']), 'source': 'ocr'}
|
||||
|
||||
|
||||
def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""把 OCR 行等宽拆为字符坐标并限制在整表范围;OCR 误差继续由人工审核兜底。"""
|
||||
bbox = table_bbox
|
||||
result: list[dict[str, Any]] = []
|
||||
source_index = 0
|
||||
for line in lines:
|
||||
text = str(line.text or '').strip()
|
||||
line_bbox = line.bbox
|
||||
if not text or not (bbox['x0'] <= (line_bbox.x0 + line_bbox.x1) / 2 <= bbox['x1'] and bbox['y0'] <= (line_bbox.y0 + line_bbox.y1) / 2 <= bbox['y1']):
|
||||
continue
|
||||
width = (line_bbox.x1 - line_bbox.x0) / len(text)
|
||||
for index, character in enumerate(text):
|
||||
if not character.strip():
|
||||
continue
|
||||
result.append({'text': character, 'source_index': source_index, 'bbox': {
|
||||
'x0': line_bbox.x0 + index * width, 'y0': line_bbox.y0,
|
||||
'x1': line_bbox.x0 + (index + 1) * width, 'y1': line_bbox.y1,
|
||||
}})
|
||||
source_index += 1
|
||||
return result
|
||||
|
||||
|
||||
def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, Any], raw_settings: Any) -> str:
|
||||
"""从持久化坐标证据和管理员确认的边界生成可审核重建表,缺任一条件均拒绝。"""
|
||||
try:
|
||||
settings = CoordinateReconstructionProfile.model_validate(raw_settings)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Coordinate reconstruction settings are invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') from exc
|
||||
table_id = str(raw_table.get('table_id') or '')
|
||||
characters = _coordinate_characters(layout, table_id)
|
||||
if not characters or not isinstance(raw_table.get('bbox'), dict):
|
||||
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE')
|
||||
try:
|
||||
return reconstruct_order_profile_html(
|
||||
characters=characters, table_bbox=raw_table['bbox'], reconstruction=settings,
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Coordinate reconstruction could not produce a table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') from exc
|
||||
|
||||
|
||||
def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
"""列出最近含 ready MinerU 表格的订单附件;不返回正文、HTML 或原始布局。"""
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
@@ -212,21 +377,93 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
if layout.get('status') != 'ready' or not tables:
|
||||
continue
|
||||
intake = db.session.get(ShippingNoticeIntake, document.intake_id)
|
||||
if intake is None:
|
||||
continue
|
||||
is_template_sample = intake.purpose == 'order_document_profile_sample'
|
||||
is_test_sample = ShippingDocumentProfileTestSample.query.filter_by(document_id=document.id).first() is not None
|
||||
result.append({
|
||||
'document_id': document.id,
|
||||
'intake_id': document.intake_id,
|
||||
'filename': document.filename,
|
||||
'intake_no': intake.intake_no,
|
||||
'filename': document.filename,
|
||||
'content_hash': document.content_hash,
|
||||
'provider': layout.get('provider'),
|
||||
'provider_version': layout.get('provider_version'),
|
||||
'table_count': len(tables),
|
||||
'created_at': document.created_at.isoformat() if document.created_at else None,
|
||||
'purpose': intake.purpose,
|
||||
'parse_status': intake.parse_status,
|
||||
'is_template_sample': is_template_sample,
|
||||
'can_delete': is_template_sample and not is_test_sample,
|
||||
'delete_block_reason': (
|
||||
'blind_test_referenced' if is_template_sample and is_test_sample else None
|
||||
),
|
||||
})
|
||||
if len(result) >= safe_limit:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None:
|
||||
"""删除管理员自己的专用模板样本;业务附件、解析中样本和盲测证据一律保留。"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
intake = ShippingNoticeIntake.query.filter_by(
|
||||
intake_no=str(intake_no or '').strip().upper(), user_id=int(actor_id),
|
||||
purpose='order_document_profile_sample',
|
||||
).first()
|
||||
if intake is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
if intake.parse_status != 'parsed':
|
||||
raise ConflictError(
|
||||
'Template sample is still being parsed',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED',
|
||||
)
|
||||
|
||||
documents = ShippingNoticeDocument.query.filter_by(intake_id=intake.id).all()
|
||||
document_ids = [document.id for document in documents]
|
||||
if document_ids and ShippingDocumentProfileTestSample.query.filter(
|
||||
ShippingDocumentProfileTestSample.document_id.in_(document_ids),
|
||||
).first() is not None:
|
||||
raise ConflictError(
|
||||
'Template sample is referenced by a blind test',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED',
|
||||
)
|
||||
|
||||
# Intake creation owns exactly one root-asset reference. Do not delete files shared by another flow.
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
asset_ids = {int(asset.id)} if asset is not None else set()
|
||||
asset_ids.update(int(document.asset_id) for document in documents if document.asset_id)
|
||||
assets = [db.session.get(FileAsset, asset_id) for asset_id in sorted(asset_ids)]
|
||||
if asset is None or int(asset.reference_count or 0) != 1 or any(
|
||||
item is None or (item.id != asset.id and int(item.reference_count or 0) != 1)
|
||||
for item in assets
|
||||
):
|
||||
raise ConflictError(
|
||||
'Template sample asset is referenced elsewhere',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED',
|
||||
)
|
||||
for document in documents:
|
||||
db.session.delete(document)
|
||||
db.session.flush()
|
||||
db.session.delete(intake)
|
||||
db.session.flush()
|
||||
for item in assets:
|
||||
if item is not None:
|
||||
item.reference_count = 0
|
||||
item.lifecycle_status = 'temporary'
|
||||
item.expires_at = None
|
||||
db.session.commit()
|
||||
|
||||
# Storage deletion is delegated to the established asset lifecycle service after FK rows are gone.
|
||||
from app.services.file_assets.service import delete_temporary_asset
|
||||
|
||||
for item in assets:
|
||||
if item is not None:
|
||||
delete_temporary_asset(asset_no=item.asset_no, user_id=int(actor_id))
|
||||
|
||||
|
||||
def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, Any]:
|
||||
"""从模板页已上传的私有 PDF/EML 创建隔离样本 Intake,不生成履约业务数据。"""
|
||||
if actor_id is None:
|
||||
@@ -290,6 +527,8 @@ def get_sample_tables(document_id: int) -> dict[str, Any]:
|
||||
],
|
||||
'issues': issues,
|
||||
'profile_creation_allowed': not issues,
|
||||
'coordinate_reconstruction_available': bool(_coordinate_characters(layout, table_id)) and isinstance(raw.get('bbox'), dict),
|
||||
'ocr_coordinate_reconstruction_available': not bool(_coordinate_characters(layout, table_id)) and bool(document.asset_id) and str(document.filename or '').lower().endswith('.pdf') and isinstance(raw.get('bbox'), dict),
|
||||
})
|
||||
return {
|
||||
'document': {
|
||||
@@ -302,6 +541,106 @@ def get_sample_tables(document_id: int) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def preview_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
生成不含坐标的逻辑明细候选,并返回行角色及来源物理行供管理员复核。
|
||||
|
||||
Args:
|
||||
data: document_id、table_id 和受控坐标重建参数。
|
||||
actor_id: 当前管理员 ID;样本文档仍由既有权限边界保护。
|
||||
Returns:
|
||||
稳定虚拟表头、合并后的逻辑明细、删除状态及来源物理行索引。
|
||||
"""
|
||||
try:
|
||||
document_id = int(data.get('document_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
|
||||
document = db.session.get(ShippingNoticeDocument, document_id)
|
||||
if document is None:
|
||||
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
layout = _document_layout(document)
|
||||
table_id = str(data.get('table_id') or '').strip()
|
||||
raw_table = next((item for item in layout.get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == table_id), None)
|
||||
if raw_table is None:
|
||||
raise ValidationError('Selected sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
rebuilt_html = _reconstructed_table_html(
|
||||
layout=layout, raw_table=raw_table, raw_settings=data.get('coordinate_reconstruction'),
|
||||
)
|
||||
grid = parse_html_grid(rebuilt_html, table_id=f'{table_id}:coordinate-review')
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
table = BeautifulSoup(rebuilt_html, 'html.parser').find('table')
|
||||
html_rows = table.find_all('tr') if table is not None else []
|
||||
return {
|
||||
'table_id': table_id,
|
||||
'row_count': grid.row_count,
|
||||
'column_count': grid.column_count,
|
||||
'rows': [[slot.text if slot is not None else '' for slot in row] for row in grid.rows],
|
||||
'row_roles': [str(row.get('data-row-role') or 'data') for row in html_rows],
|
||||
'source_row_indices': [
|
||||
[int(value) for value in str(row.get('data-source-rows') or '').split(',') if value.isdigit()]
|
||||
for row in html_rows
|
||||
],
|
||||
'status': 'needs_review',
|
||||
}
|
||||
|
||||
|
||||
def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
根据冻结字符坐标返回全部或指定物理行的相对列边界建议。
|
||||
|
||||
Args:
|
||||
data: document_id、table_id,以及可选的非负 row_offset。省略 row_offset 时建议全部行。
|
||||
actor_id: 当前管理员 ID;保留与预览接口一致的授权边界。
|
||||
Returns:
|
||||
仅含相对边界、少量列示例及确定性 line_no 建议的待审核配置;指定行时只返回该行。
|
||||
"""
|
||||
try:
|
||||
document_id = int(data.get('document_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
|
||||
document = db.session.get(ShippingNoticeDocument, document_id)
|
||||
if document is None:
|
||||
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
layout = _document_layout(document)
|
||||
table_id = str(data.get('table_id') or '').strip()
|
||||
raw_table = next((
|
||||
item for item in layout.get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == table_id
|
||||
), None)
|
||||
characters = _coordinate_characters(layout, table_id)
|
||||
if raw_table is None or not characters or not isinstance(raw_table.get('bbox'), dict):
|
||||
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE')
|
||||
suggestions = suggest_multi_subrow_layouts(
|
||||
characters=characters, table_bbox=raw_table['bbox'],
|
||||
)
|
||||
if not suggestions:
|
||||
raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID')
|
||||
raw_row_offset = data.get('row_offset')
|
||||
if raw_row_offset is not None:
|
||||
try:
|
||||
row_offset = int(raw_row_offset)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'row_offset is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID',
|
||||
) from exc
|
||||
if row_offset < 0:
|
||||
raise ValidationError(
|
||||
'row_offset is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID',
|
||||
)
|
||||
suggestions = [item for item in suggestions if item.row_offset == row_offset]
|
||||
if not suggestions:
|
||||
raise ValidationError(
|
||||
'Requested physical row could not be detected',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID',
|
||||
)
|
||||
return {
|
||||
'table_id': table_id,
|
||||
'subrow_layouts': [item.model_dump() for item in suggestions],
|
||||
'status': 'needs_review',
|
||||
}
|
||||
|
||||
|
||||
def create_draft_from_sample(
|
||||
data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -340,7 +679,13 @@ def create_draft_from_sample(
|
||||
raise ValidationError(
|
||||
'Sample row selection is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
) from exc
|
||||
grid = parse_html_grid(str(raw_table.get('html') or ''), table_id=table_id)
|
||||
coordinate_reconstruction = data.get('coordinate_reconstruction')
|
||||
source_html = str(raw_table.get('html') or '')
|
||||
if coordinate_reconstruction is not None:
|
||||
source_html = _reconstructed_table_html(
|
||||
layout=layout, raw_table=raw_table, raw_settings=coordinate_reconstruction,
|
||||
)
|
||||
grid = parse_html_grid(source_html, table_id=table_id)
|
||||
if (
|
||||
header_row_index < 0 or header_row_index >= grid.row_count
|
||||
or data_start_row_index <= header_row_index or data_start_row_index >= grid.row_count
|
||||
@@ -364,6 +709,7 @@ def create_draft_from_sample(
|
||||
'data_start_row_index': data_start_row_index,
|
||||
'row_structure': str(data.get('row_structure') or 'preserved'),
|
||||
'column_rules': data.get('column_rules'),
|
||||
'coordinate_reconstruction': coordinate_reconstruction,
|
||||
'drop_zero_qty': data.get('drop_zero_qty', True),
|
||||
}
|
||||
return save_draft({
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
@@ -245,6 +246,24 @@ def _profile_snapshot_targets_valid(raw: dict[str, Any], *, contract: Any) -> bo
|
||||
return True
|
||||
|
||||
|
||||
def _reconstructed_profile_html(*, layout: dict[str, Any], raw_table: dict[str, Any], profile: OrderDocumentProfile) -> str | None:
|
||||
"""从 Run 已冻结的坐标证据重建 HTML;证据缺失时绝不回读可变资产或降级猜测。"""
|
||||
if profile.coordinate_reconstruction is None:
|
||||
return str(raw_table.get('html') or '')
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
characters = tables.get(str(raw_table.get('table_id') or ''))
|
||||
if not isinstance(characters, list) or not isinstance(raw_table.get('bbox'), dict):
|
||||
return None
|
||||
try:
|
||||
return reconstruct_order_profile_html(
|
||||
characters=[item for item in characters if isinstance(item, dict)],
|
||||
table_bbox=raw_table['bbox'], reconstruction=profile.coordinate_reconstruction,
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _dify_profile_candidates(tables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""剥离内部 field_code,只向 Dify 暴露稳定 field_id、值和短逐字证据。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
@@ -301,10 +320,15 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
issues.append('order_profile_snapshot_field_mismatch')
|
||||
continue
|
||||
try:
|
||||
profile = _frozen_order_profile(raw_profile)
|
||||
source_html = _reconstructed_profile_html(layout=layout, raw_table=raw_table, profile=profile)
|
||||
if source_html is None:
|
||||
issues.append('order_profile_coordinate_reconstruction_unavailable')
|
||||
continue
|
||||
parsed = parse_html_table_with_order_profile(
|
||||
str(raw_table['html']),
|
||||
source_html,
|
||||
table_id=table_id,
|
||||
profile=_frozen_order_profile(raw_profile),
|
||||
profile=profile,
|
||||
contract=contract,
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
@@ -322,7 +346,12 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
if parsed.issues:
|
||||
issues.extend(parsed.issues)
|
||||
continue
|
||||
grid = parse_html_grid(str(raw_table['html']), table_id=table_id)
|
||||
profile = _frozen_order_profile(raw_profile)
|
||||
source_html = _reconstructed_profile_html(layout=layout, raw_table=raw_table, profile=profile)
|
||||
if source_html is None:
|
||||
issues.append('order_profile_coordinate_reconstruction_unavailable')
|
||||
continue
|
||||
grid = parse_html_grid(source_html, table_id=table_id)
|
||||
compact_rows: list[dict[str, Any]] = []
|
||||
for row in parsed.rows:
|
||||
if row.status == 'deleted':
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/order_field_purposes.py
|
||||
|
||||
用途:将冻结订单 Snapshot 按冻结 Schema 业务用途投影给履约链。
|
||||
依赖:order_schema.service、export.order_field_id_values、ShippingTask。
|
||||
逻辑:路由、门禁、匹配和展示只通过发布快照中的 business_purpose 定位稳定 field_id,禁止读取任务行固定业务列。
|
||||
用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。
|
||||
依赖:冻结履约策略、export.order_field_id_values、ShippingTask。
|
||||
逻辑:路由、门禁、匹配和展示只通过策略冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,19 +15,33 @@ from app.models import ShippingOrderSnapshot, ShippingTask
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
|
||||
|
||||
_PURPOSE_BY_CAPABILITY = {
|
||||
'fulfillment.reservation_identity': 'reservation_id',
|
||||
'fulfillment.part_number': 'part_number',
|
||||
'fulfillment.quantity': 'quantity',
|
||||
'routing.inventory_source_hint': 'inventory_source_hint',
|
||||
}
|
||||
|
||||
|
||||
def task_line_purpose_field_ids(task: ShippingTask, *, required: set[str] | None = None) -> dict[str, str]:
|
||||
"""读取冻结快照的行级用途与字段 ID,防止后续发布版本重解释履约任务。"""
|
||||
"""读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。"""
|
||||
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
|
||||
purposes = {
|
||||
str(config.get('business_purpose')): str(config.get('field_id'))
|
||||
for config in (snapshot.schema_version.definition_json or {}).get('fields') or []
|
||||
if config.get('scope') == 'line' and config.get('business_purpose') not in (None, '', 'general')
|
||||
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')
|
||||
}
|
||||
missing = sorted((required or set()) - set(purposes))
|
||||
if missing:
|
||||
raise ValueError(f'已发布订单 Schema 缺少业务用途:{", ".join(missing)}')
|
||||
raise ValueError(f'冻结履约策略缺少字段能力:{", ".join(missing)}')
|
||||
return purposes
|
||||
|
||||
|
||||
|
||||
@@ -26,20 +26,32 @@ from app.models import (
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import (
|
||||
published_policy,
|
||||
required_field_configs,
|
||||
)
|
||||
|
||||
|
||||
HEADER_FIELDS = (
|
||||
'po_number', 'customer_code', 'customer_name', 'bill_to_customer', 'bill_to_address',
|
||||
'ship_to_customer', 'ship_to_address', 'destination', 'currency', 'incoterm', 'required_date',
|
||||
'order_date', 'payment_term',
|
||||
)
|
||||
LINE_FIELDS = (
|
||||
'line_no', 'part_number', 'customer_part_number', 'aws_part_number', 'reservation_id', 'qty', 'uom',
|
||||
'unit_price', 'amount', 'warehouse', 'inventory_source_hint', 'remark',
|
||||
)
|
||||
CRITICAL_FIELDS = frozenset({'part_number', 'reservation_id', 'qty', 'po_number'})
|
||||
DECIMAL_FIELDS = frozenset({'qty', 'unit_price', 'amount'})
|
||||
DATE_FIELDS = frozenset({'required_date', 'order_date'})
|
||||
# 强类型列只是既有查询/导出投影;56 项标准字段的完整事实始终写在 field_id JSON。
|
||||
HEADER_FIELD_PROJECTIONS = {
|
||||
'customer_po_number': 'customer_po_number', 'customer_code': 'customer_code', 'customer_name': 'customer_name',
|
||||
'bill_to_customer': 'bill_to_customer', 'bill_to_address': 'bill_to_address',
|
||||
'ship_to_customer': 'ship_to_customer', 'ship_to_address': 'ship_to_address',
|
||||
'destination': 'destination', 'currency': 'currency', 'incoterm': 'incoterm',
|
||||
'order_date': 'order_date', 'payment_term': 'payment_term',
|
||||
}
|
||||
LINE_FIELD_PROJECTIONS = {
|
||||
'line_no': 'line_no', 'part_number': 'part_number', 'customer_part_number': 'customer_part_number',
|
||||
'reservation_id': 'reservation_id', 'qty': 'qty', 'uom': 'uom', 'unit_price': 'unit_price',
|
||||
'line_amount_with_tax': 'amount', 'requested_warehouse_code': 'warehouse',
|
||||
'inventory_source_hint': 'inventory_source_hint', 'line_remark': 'remark',
|
||||
}
|
||||
CRITICAL_FIELDS = frozenset({'part_number', 'reservation_id', 'qty', 'customer_po_number'})
|
||||
DECIMAL_FIELDS = frozenset({
|
||||
'qty', 'reference_qty', 'pricing_qty', 'unit_price', 'line_amount_before_tax',
|
||||
'line_tax_amount', 'line_amount_with_tax', 'tax_rate',
|
||||
})
|
||||
DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date'})
|
||||
|
||||
|
||||
def freeze_order_snapshot(
|
||||
@@ -79,7 +91,7 @@ def freeze_order_snapshot(
|
||||
details={'expected': expected_order_data_version, 'actual': actual_version},
|
||||
)
|
||||
extraction = _accepted_extraction(task)
|
||||
configs = _fixed_configs(extraction)
|
||||
policy, configs = _policy_configs(extraction)
|
||||
_assert_llm_review_gate(extraction, configs)
|
||||
header_values, line_values = _extraction_values(extraction, configs)
|
||||
customer_match = _confirmed_ordering_customer(extraction)
|
||||
@@ -94,6 +106,14 @@ 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 {}),
|
||||
'required_field_ids': {code: config['field_id'] for code, config in configs.items()},
|
||||
},
|
||||
'ordering_customer': {
|
||||
'match_id': customer_match.id,
|
||||
'identity_fingerprint': customer_match.identity_fingerprint,
|
||||
@@ -105,7 +125,7 @@ def freeze_order_snapshot(
|
||||
},
|
||||
frozen_by_id=actor_id,
|
||||
header_values_json=_field_id_values(header_values, configs),
|
||||
**{field: _coerce_value(header_values.get(field), field) for field in HEADER_FIELDS},
|
||||
**_project_values(header_values, HEADER_FIELD_PROJECTIONS),
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
@@ -114,7 +134,7 @@ def freeze_order_snapshot(
|
||||
snapshot_id=snapshot.id,
|
||||
position=position,
|
||||
field_values_json=_field_id_values(source, configs),
|
||||
**{field: _coerce_value(source.get(field), field) for field in LINE_FIELDS},
|
||||
**_project_values(source, LINE_FIELD_PROJECTIONS),
|
||||
))
|
||||
task.order_snapshot_id = snapshot.id
|
||||
ShippingOrderReviewEvent.query.filter_by(
|
||||
@@ -154,36 +174,17 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin
|
||||
return row
|
||||
|
||||
|
||||
def _fixed_configs(extraction: ShippingOrderExtraction) -> dict[str, dict[str, Any]]:
|
||||
"""验证预置核心字段存在且类型正确;扩展字段由已发布业务配置决定是否参与履约。"""
|
||||
configs = {
|
||||
str(item.get('field_code')): item
|
||||
for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[Any, dict[str, dict[str, Any]]]:
|
||||
"""按已发布货代策略验证冻结契约,Schema 只继续承担字段目录职责。"""
|
||||
definition = extraction.schema_version.definition_json or {}
|
||||
policy = published_policy()
|
||||
required = required_field_configs(definition, policy)
|
||||
all_configs = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in definition.get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
}
|
||||
expected = set(HEADER_FIELDS) | set(LINE_FIELDS)
|
||||
missing = expected - set(configs)
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'Frozen order schema is missing required core fields',
|
||||
code='SHIPPING.ORDER_CONTRACT_INVALID',
|
||||
details={'missing': sorted(missing)},
|
||||
)
|
||||
wrong_scope = [
|
||||
code for code, config in configs.items() if code in expected
|
||||
if str(config.get('scope')) != ('header' if code in HEADER_FIELDS else 'line')
|
||||
]
|
||||
if wrong_scope:
|
||||
raise ValidationError('Frozen order schema has invalid field scope', code='SHIPPING.ORDER_CONTRACT_INVALID', details={'fields': wrong_scope})
|
||||
wrong_type = [
|
||||
code for code, config in configs.items() if code in expected
|
||||
if str(config.get('value_type')) != (
|
||||
'date' if code in DATE_FIELDS else 'decimal' if code in DECIMAL_FIELDS else 'string'
|
||||
)
|
||||
]
|
||||
if wrong_type:
|
||||
raise ValidationError('Frozen order schema has invalid core field type', code='SHIPPING.ORDER_CONTRACT_INVALID', details={'fields': wrong_type})
|
||||
return configs
|
||||
return policy, all_configs | required
|
||||
|
||||
|
||||
def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[str, dict[str, Any]]) -> None:
|
||||
@@ -196,7 +197,7 @@ def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[s
|
||||
int(item.id): item
|
||||
for item in ShippingOrderFieldObservation.query.filter_by(extraction_id=extraction.id).all()
|
||||
}
|
||||
field_codes = {str(config['field_id']): code for code, config in configs.items()}
|
||||
field_codes = {str(config['field_id']): code for code, config in configs.items() if config.get('field_id')}
|
||||
blocked: list[dict[str, Any]] = []
|
||||
for decision in decisions.values():
|
||||
code = field_codes.get(str(decision.field_id))
|
||||
@@ -248,6 +249,14 @@ def _field_id_values(values: dict[str, Any], configs: dict[str, dict[str, Any]])
|
||||
}
|
||||
|
||||
|
||||
def _project_values(values: dict[str, Any], projections: dict[str, str]) -> dict[str, Any]:
|
||||
"""将标准字段的兼容投影写入旧强类型列,不把目录扩展为物理列。"""
|
||||
return {
|
||||
column: _coerce_value(values.get(field_code), field_code)
|
||||
for field_code, column in projections.items()
|
||||
}
|
||||
|
||||
|
||||
def _coerce_value(value: Any, field_code: str) -> Any:
|
||||
"""将动态 JSON 值安全写入强类型快照;数量为 Decimal,日期为 date,标识符为字符串。"""
|
||||
if value in (None, ''):
|
||||
|
||||
@@ -386,8 +386,7 @@ def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str,
|
||||
rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""仅用同 Document 的强身份字段关联 layout 行,禁止 Qty 等常见值导致跨文档串行。"""
|
||||
strong_codes = {
|
||||
'part_number', 'customer_part_number', 'aws_part_number',
|
||||
'reservation_id', 'line_no', 'po_number',
|
||||
'part_number', 'customer_part_number', 'reservation_id', 'line_no', 'customer_po_number',
|
||||
}
|
||||
signatures: list[tuple[str, Any, int]] = []
|
||||
for raw in raw_fields:
|
||||
@@ -604,9 +603,6 @@ def persist_dynamic_order(
|
||||
'required_key_field_codes': sorted({
|
||||
str(item['field_code'])
|
||||
for item in all_configs.values()
|
||||
if item.get('required') and (
|
||||
item.get('business_purpose') in {'part_number', 'quantity', 'reservation_id'}
|
||||
or item.get('field_code') == 'po_number'
|
||||
)
|
||||
if item.get('required') or item.get('field_code') == 'customer_po_number'
|
||||
}),
|
||||
}
|
||||
@@ -66,34 +66,67 @@ DIFY_EXPOSURE_POLICY_ORDER = ('never', 'redacted', 'confirmed_readonly')
|
||||
DIFY_EXPOSURE_POLICIES = frozenset(DIFY_EXPOSURE_POLICY_ORDER)
|
||||
SENSITIVITY_LEVELS = frozenset({'low', 'personal', 'confidential'})
|
||||
|
||||
# 阶段 1:这 26 个字段是预置强类型履约核心。扩展字段也可由已发布业务配置纳入履约,
|
||||
# 这 57 个字段是预置标准字段目录。扩展字段也可由已发布业务配置纳入履约,
|
||||
# 并在 Snapshot 中按稳定 field_id 冻结,避免字段重命名影响历史履约事实。
|
||||
FIXED_CORE_FIELD_SPECS: dict[str, tuple[str, str]] = {
|
||||
'po_number': ('header', 'string'),
|
||||
STANDARD_ORDER_FIELD_SPECS: dict[str, tuple[str, str]] = {
|
||||
# 客户订单事实:customer_po_number 是外部客户 PO;内部 ERP 单号属于系统事实。
|
||||
'customer_po_number': ('header', 'string'),
|
||||
'order_date': ('header', 'date'),
|
||||
'source_order_number': ('header', 'string'),
|
||||
'contract_number': ('header', 'string'),
|
||||
'order_type': ('header', 'string'),
|
||||
'sales_channel': ('header', 'string'),
|
||||
'customer_code': ('header', 'string'),
|
||||
'customer_name': ('header', 'string'),
|
||||
'bill_to_customer': ('header', 'string'),
|
||||
'bill_to_address': ('header', 'string'),
|
||||
'ship_to_customer': ('header', 'string'),
|
||||
'ship_to_address': ('header', 'string'),
|
||||
'end_customer': ('header', 'string'),
|
||||
'customer_contact': ('header', 'string'),
|
||||
'ship_from_organization': ('header', 'string'),
|
||||
'destination': ('header', 'string'),
|
||||
'currency': ('header', 'string'),
|
||||
'incoterm': ('header', 'string'),
|
||||
'required_date': ('header', 'date'),
|
||||
'order_date': ('header', 'date'),
|
||||
'payment_term': ('header', 'string'),
|
||||
'mark_number': ('header', 'string'),
|
||||
'direct_ship_required': ('header', 'boolean'),
|
||||
'urgent_order': ('header', 'boolean'),
|
||||
'order_remark': ('header', 'string'),
|
||||
'line_no': ('line', 'string'),
|
||||
'part_number': ('line', 'string'),
|
||||
'customer_part_number': ('line', 'string'),
|
||||
'aws_part_number': ('line', 'string'),
|
||||
'reservation_id': ('line', 'string'),
|
||||
'part_number': ('line', 'string'),
|
||||
'product_revision': ('line', 'string'),
|
||||
'customer_part_number': ('line', 'string'),
|
||||
'customer_po_line_no': ('line', 'string'),
|
||||
'product_feature': ('line', 'string'),
|
||||
'qty': ('line', 'decimal'),
|
||||
'uom': ('line', 'string'),
|
||||
'reference_qty': ('line', 'decimal'),
|
||||
'reference_uom': ('line', 'string'),
|
||||
'pricing_qty': ('line', 'decimal'),
|
||||
'pricing_uom': ('line', 'string'),
|
||||
'required_date': ('line', 'date'),
|
||||
'requested_receipt_date': ('line', 'date'),
|
||||
'unit_price': ('line', 'decimal'),
|
||||
'amount': ('line', 'decimal'),
|
||||
'warehouse': ('line', 'string'),
|
||||
'line_amount_before_tax': ('line', 'decimal'),
|
||||
'line_tax_amount': ('line', 'decimal'),
|
||||
'line_amount_with_tax': ('line', 'decimal'),
|
||||
'tax_category': ('line', 'string'),
|
||||
'tax_rate': ('line', 'decimal'),
|
||||
'ship_from_site': ('line', 'string'),
|
||||
'line_ship_to_address': ('line', 'string'),
|
||||
'requested_warehouse_code': ('line', 'string'),
|
||||
'storage_location_code': ('line', 'string'),
|
||||
'lot_number': ('line', 'string'),
|
||||
'inventory_source_hint': ('line', 'string'),
|
||||
'remark': ('line', 'string'),
|
||||
'partial_delivery_allowed': ('line', 'boolean'),
|
||||
'bonded_flag': ('line', 'boolean'),
|
||||
'package_type': ('line', 'string'),
|
||||
'project_code': ('line', 'string'),
|
||||
'wbs_code': ('line', 'string'),
|
||||
'activity_code': ('line', 'string'),
|
||||
'line_remark': ('line', 'string'),
|
||||
}
|
||||
|
||||
|
||||
@@ -650,7 +683,7 @@ def get_extraction_audit(extraction_id: int) -> dict[str, Any]:
|
||||
|
||||
|
||||
def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""初始化全局唯一订单 Schema 并预置 26 个履约核心字段;仍允许新增扩展字段。"""
|
||||
"""初始化全局唯一订单 Schema 并预置 57 个标准字段;仍允许新增扩展字段。"""
|
||||
if ShippingOrderSchema.query.count():
|
||||
raise ConflictError('Only one shipping order schema is allowed', code='SHIPPING.ORDER_SCHEMA_EXISTS')
|
||||
display_name = str(data.get('display_name') or '').strip()
|
||||
@@ -665,7 +698,7 @@ def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str
|
||||
)
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
for sequence, (field_code, (scope, value_type)) in enumerate(FIXED_CORE_FIELD_SPECS.items(), start=1):
|
||||
for sequence, (field_code, (scope, value_type)) in enumerate(STANDARD_ORDER_FIELD_SPECS.items(), start=1):
|
||||
db.session.add(ShippingOrderField(
|
||||
schema_id=schema.id,
|
||||
field_code=field_code,
|
||||
@@ -676,6 +709,20 @@ def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str
|
||||
display_sequence=sequence,
|
||||
created_by_id=actor_id,
|
||||
))
|
||||
db.session.flush()
|
||||
# 初始化仅预置策略草稿;管理员发布 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(schema_id=schema.id).all()}
|
||||
draft = 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()
|
||||
|
||||
@@ -684,7 +731,7 @@ def save_field(
|
||||
data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建或更新字段;核心 26 字段身份不可变,扩展字段仍可按既有治理规则维护。"""
|
||||
"""创建或更新字段;标准字段身份不可变,扩展字段仍可按既有治理规则维护。"""
|
||||
schema = _require_schema()
|
||||
field = db.session.get(ShippingOrderField, field_id) if field_id else None
|
||||
if field_id and (field is None or field.schema_id != schema.id):
|
||||
@@ -696,7 +743,7 @@ def save_field(
|
||||
collection_mode = str(data.get('collection_mode') or 'llm_extraction').strip()
|
||||
if not FIELD_CODE_RE.fullmatch(code):
|
||||
raise ValidationError('field_code must use lower snake_case', code='SHIPPING.ORDER_FIELD_INVALID')
|
||||
fixed_shape = FIXED_CORE_FIELD_SPECS.get(code)
|
||||
fixed_shape = STANDARD_ORDER_FIELD_SPECS.get(code)
|
||||
# 预置核心字段在 Schema 初始化时已存在。历史调用方重复声明相同契约时
|
||||
# 只返回既有字段,绝不能再插入一条同名记录;形状不一致仍是硬错误。
|
||||
if field is None and fixed_shape is not None:
|
||||
@@ -705,7 +752,7 @@ def save_field(
|
||||
if (scope, value_type) != fixed_shape:
|
||||
raise ConflictError('Core order field identity is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
|
||||
return _field_payload(existing_core)
|
||||
if field is not None and field.field_code in FIXED_CORE_FIELD_SPECS:
|
||||
if field is not None and field.field_code in STANDARD_ORDER_FIELD_SPECS:
|
||||
if field.field_code != code or (scope, value_type) != fixed_shape:
|
||||
raise ConflictError('Core order field identity is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
|
||||
if scope not in FIELD_SCOPES or value_type not in FIELD_TYPES:
|
||||
@@ -873,7 +920,7 @@ def _field_runtime_references(field_id: str) -> list[str]:
|
||||
"""返回字段仍被哪些可运行下游配置引用,供退役与 Schema 发布共用。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingOrderDocumentProfile,
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingFulfillmentPolicy,
|
||||
)
|
||||
references: list[str] = []
|
||||
if db.session.query(ShippingInventoryRoutingRuleCondition).join(ShippingInventoryRoutingRule).filter(
|
||||
@@ -912,6 +959,15 @@ def _field_runtime_references(field_id: str) -> list[str]:
|
||||
)
|
||||
if template_reference:
|
||||
references.append('excel_template')
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
policy_reference = any(
|
||||
any(str(item.get('field_id') or '') == field_id for item in (policy.definition_json or {}).get('field_bindings', []))
|
||||
for policy in ShippingFulfillmentPolicy.query.filter_by(
|
||||
schema_id=field.schema_id if field is not None else None, status='published',
|
||||
).all()
|
||||
)
|
||||
if policy_reference:
|
||||
references.append('fulfillment_policy')
|
||||
# 识别定义同样消费稳定订单字段;字段退役或发布移除前必须先完成规则替换/退役。
|
||||
from app.services.shipping_notice.identity_rules.service import active_definition_field_references
|
||||
references.extend(active_definition_field_references(field_id))
|
||||
|
||||
@@ -17,9 +17,13 @@ from app.core.errors import ValidationError
|
||||
|
||||
|
||||
TABLE_FIELD_CODES = frozenset({
|
||||
'line_no', 'part_number', 'qty', 'unit_price', 'amount', 'currency',
|
||||
'reservation_id', 'required_date', 'customer_part_number',
|
||||
'aws_part_number', 'uom', 'remark', 'po_number', 'inventory_source_hint',
|
||||
'line_no', 'reservation_id', 'part_number', 'product_revision', 'customer_part_number',
|
||||
'customer_po_line_no', 'product_feature', 'qty', 'uom', 'reference_qty', 'reference_uom',
|
||||
'pricing_qty', 'pricing_uom', 'required_date', 'requested_receipt_date', 'unit_price',
|
||||
'line_amount_before_tax', 'line_tax_amount', 'line_amount_with_tax', 'tax_category', 'tax_rate',
|
||||
'ship_from_site', 'line_ship_to_address', 'requested_warehouse_code', 'storage_location_code',
|
||||
'lot_number', 'inventory_source_hint', 'partial_delivery_allowed', 'bonded_flag', 'package_type',
|
||||
'project_code', 'wbs_code', 'activity_code', 'line_remark',
|
||||
})
|
||||
|
||||
# 这些技术/业务标识与 Reservation ID 语义不同,管理员配置不得覆盖安全边界。
|
||||
|
||||
@@ -22,6 +22,9 @@ from app.models import (
|
||||
ShippingReservation,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
|
||||
def _decimal(value: Any) -> Decimal:
|
||||
@@ -36,40 +39,105 @@ def _decimal(value: Any) -> Decimal:
|
||||
|
||||
|
||||
def ensure_task_reservations(task: ShippingTask) -> list[ShippingReservation]:
|
||||
"""由冻结 Snapshot 注册预约单;历史上传或占用记录不允许被新快照静默覆盖。"""
|
||||
"""由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。"""
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValidationError('Frozen order snapshot is required', code='SHIPPING.ORDER_SNAPSHOT_REQUIRED')
|
||||
po_number = normalize_po_number(snapshot.customer_po_number).upper()
|
||||
registered: list[ShippingReservation] = []
|
||||
seen: set[str] = set()
|
||||
for line in snapshot.lines:
|
||||
reservation_id = str(line.reservation_id or '').strip()
|
||||
reservation_id = validated_reservation_id(line.reservation_id)
|
||||
part_number = str(line.part_number or '').strip()
|
||||
if not reservation_id or not part_number or line.qty is None:
|
||||
raise ValidationError('Reservation id, part number and quantity are required', code='SHIPPING.RESERVATION_INVALID')
|
||||
row = ShippingReservation.query.filter_by(reservation_id=reservation_id, part_number=part_number).one_or_none()
|
||||
if reservation_id in seen:
|
||||
raise ConflictError('Reservation is duplicated in the frozen order', code='SHIPPING.RESERVATION_DUPLICATED_IN_ORDER')
|
||||
seen.add(reservation_id)
|
||||
row = ShippingReservation.query.filter_by(reservation_id=reservation_id).one_or_none()
|
||||
if row is None:
|
||||
row = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=line.id, reservation_id=reservation_id,
|
||||
part_number=part_number, required_qty=_decimal(line.qty), status='pending',
|
||||
po_number_normalized=po_number, part_number=part_number, required_qty=_decimal(line.qty), status='pending',
|
||||
)
|
||||
db.session.add(row)
|
||||
elif row.task_id != task.id or row.snapshot_line_id != line.id:
|
||||
raise ConflictError(
|
||||
'Reservation is already registered by another order version',
|
||||
code='SHIPPING.RESERVATION_ALREADY_REGISTERED',
|
||||
elif not po_number:
|
||||
raise ValidationError(
|
||||
'Purchase order is required when a reservation is already registered',
|
||||
code='SHIPPING.RESERVATION_PO_REQUIRED',
|
||||
)
|
||||
elif row.po_number_normalized != po_number:
|
||||
raise ConflictError(
|
||||
'Reservation is already registered by a different purchase order',
|
||||
code='SHIPPING.RESERVATION_PO_CONFLICT',
|
||||
details={'reservation_id': reservation_id, 'registered_po_number': row.po_number_normalized},
|
||||
)
|
||||
elif row.task_id != task.id or row.snapshot_line_id != line.id:
|
||||
if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}:
|
||||
raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED')
|
||||
if row.part_number != part_number or row.required_qty != _decimal(line.qty):
|
||||
if task.supersedes_task_id == row.task_id:
|
||||
_transfer_confirmed_revision(row, task=task, line=line, part_number=part_number)
|
||||
registered.append(row)
|
||||
continue
|
||||
raise ConflictError(
|
||||
'Reservation revision requires human confirmation',
|
||||
code='SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED',
|
||||
details={
|
||||
'reservation_id': reservation_id,
|
||||
'registered_task_id': row.task_id,
|
||||
'previous': {'part_number': row.part_number, 'qty': str(row.required_qty)},
|
||||
'proposed': {'part_number': part_number, 'qty': str(_decimal(line.qty))},
|
||||
},
|
||||
)
|
||||
raise ConflictError('Reservation is already registered by another order version', code='SHIPPING.RESERVATION_ALREADY_REGISTERED')
|
||||
registered.append(row)
|
||||
db.session.flush()
|
||||
return registered
|
||||
|
||||
|
||||
def _transfer_confirmed_revision(
|
||||
reservation: ShippingReservation,
|
||||
*, task: ShippingTask,
|
||||
line: Any,
|
||||
part_number: str,
|
||||
) -> None:
|
||||
"""仅允许已确认的直接修订后继接替未履约 Reservation,并追加双向审计。"""
|
||||
previous = {
|
||||
'task_id': reservation.task_id,
|
||||
'snapshot_line_id': reservation.snapshot_line_id,
|
||||
'part_number': reservation.part_number,
|
||||
'qty': str(reservation.required_qty),
|
||||
}
|
||||
reservation.task_id = task.id
|
||||
reservation.snapshot_line_id = line.id
|
||||
reservation.part_number = part_number
|
||||
reservation.required_qty = _decimal(line.qty)
|
||||
reservation.status = 'pending'
|
||||
reservation.current_artifact_id = None
|
||||
details = {
|
||||
'reservation_id': reservation.reservation_id,
|
||||
'previous': previous,
|
||||
'proposed': {
|
||||
'task_id': task.id,
|
||||
'snapshot_line_id': line.id,
|
||||
'part_number': part_number,
|
||||
'qty': str(reservation.required_qty),
|
||||
},
|
||||
}
|
||||
log_task_event(task, 'reservation_revision_confirmed', details)
|
||||
parent = db.session.get(ShippingTask, task.supersedes_task_id)
|
||||
if parent is not None:
|
||||
log_task_event(parent, 'reservation_revision_superseded', details)
|
||||
|
||||
|
||||
def record_inventory_verification(
|
||||
task: ShippingTask, *, inventory_snapshot_id: int | None, source_config_version: str | None,
|
||||
line_results: list[dict[str, Any]],
|
||||
) -> ShippingInventoryVerification:
|
||||
"""把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。"""
|
||||
reservations = ensure_task_reservations(task)
|
||||
by_key = {(row.reservation_id, row.part_number): row for row in reservations}
|
||||
by_key = {row.reservation_id: row for row in reservations}
|
||||
verification = ShippingInventoryVerification(
|
||||
task_id=task.id, inventory_snapshot_id=inventory_snapshot_id,
|
||||
source_config_version=source_config_version, status='completed', result_json={'line_count': len(line_results)},
|
||||
@@ -78,10 +146,10 @@ def record_inventory_verification(
|
||||
db.session.flush()
|
||||
available_count = 0
|
||||
for item in line_results:
|
||||
reservation_id = str(item.get('reservation_id') or '').strip()
|
||||
reservation_id = validated_reservation_id(item.get('reservation_id'))
|
||||
part_number = str(item.get('part_number') or '').strip()
|
||||
reservation = by_key.get((reservation_id, part_number))
|
||||
if reservation is None:
|
||||
reservation = by_key.get(reservation_id)
|
||||
if reservation is None or reservation.part_number != part_number:
|
||||
raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
|
||||
required = _decimal(item.get('required_qty'))
|
||||
available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0')
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""make shipping reservation globally unique
|
||||
|
||||
Revision ID: 025b6c7d8e9f
|
||||
Revises: 024a5b6c7d8e
|
||||
Create Date: 2026-07-23 00:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '025b6c7d8e9f'
|
||||
down_revision = '024a5b6c7d8e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""将预约号改为单列全局唯一,并保存首次注册时的标准 PO。"""
|
||||
with op.batch_alter_table('shipping_reservations') as batch:
|
||||
batch.add_column(sa.Column('po_number_normalized', sa.String(length=255), nullable=True))
|
||||
batch.drop_constraint('uq_shipping_reservations_reservation_part', type_='unique')
|
||||
batch.create_unique_constraint('uq_shipping_reservations_reservation_id', ['reservation_id'])
|
||||
op.execute("UPDATE shipping_reservations SET po_number_normalized = '' WHERE po_number_normalized IS NULL")
|
||||
with op.batch_alter_table('shipping_reservations') as batch:
|
||||
batch.alter_column('po_number_normalized', existing_type=sa.String(length=255), nullable=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复旧的 Reservation 与料号联合唯一约束。"""
|
||||
with op.batch_alter_table('shipping_reservations') as batch:
|
||||
batch.drop_constraint('uq_shipping_reservations_reservation_id', type_='unique')
|
||||
batch.create_unique_constraint('uq_shipping_reservations_reservation_part', ['reservation_id', 'part_number'])
|
||||
batch.drop_column('po_number_normalized')
|
||||
@@ -0,0 +1,48 @@
|
||||
"""add shipping fulfillment policies
|
||||
|
||||
Revision ID: 026c7d8e9f0a
|
||||
Revises: 025b6c7d8e9f
|
||||
Create Date: 2026-07-23 00:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '026c7d8e9f0a'
|
||||
down_revision = '025b6c7d8e9f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""建立货代专用策略版本表;不影响已冻结的历史 Snapshot。"""
|
||||
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.ForeignKey('shipping_fulfillment_policies.id')),
|
||||
sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id')),
|
||||
sa.Column('published_by_id', sa.Integer(), sa.ForeignKey('users.id')),
|
||||
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),
|
||||
sa.UniqueConstraint('schema_id', 'policy_code', 'version', name='uq_shipping_fulfillment_policies_version'),
|
||||
sa.CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_fulfillment_policies_status'),
|
||||
)
|
||||
op.create_index(
|
||||
'uq_shipping_fulfillment_policy_one_published', 'shipping_fulfillment_policies', ['schema_id'], unique=True,
|
||||
postgresql_where=sa.text("status = 'published'"), sqlite_where=sa.text("status = 'published'"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除尚未被 Snapshot 外键引用的策略表。"""
|
||||
op.drop_index('uq_shipping_fulfillment_policy_one_published', table_name='shipping_fulfillment_policies')
|
||||
op.drop_table('shipping_fulfillment_policies')
|
||||
@@ -0,0 +1,172 @@
|
||||
"""expand shipping standard field catalog
|
||||
|
||||
Revision ID: 027d8e9f0a1b
|
||||
Revises: 026c7d8e9f0a
|
||||
Create Date: 2026-07-23 00:00:00.000000
|
||||
|
||||
用途:以 57 项标准字段目录重建 shipping_order_fields,并清理依赖旧 field_id 的未投产数据。
|
||||
依赖:shipping_order_schemas / shipping_order_fields 及相关履约、库存配置表。
|
||||
逻辑:先按外键安全顺序清空受影响事实表,再重插标准字段;含解析绑定审计表须先于 parsing_profiles 删除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '027d8e9f0a1b'
|
||||
down_revision = '026c7d8e9f0a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
STANDARD_FIELDS = (
|
||||
('customer_po_number', 'header', 'string'), ('order_date', 'header', 'date'),
|
||||
('source_order_number', 'header', 'string'), ('contract_number', 'header', 'string'),
|
||||
('order_type', 'header', 'string'), ('sales_channel', 'header', 'string'),
|
||||
('customer_code', 'header', 'string'), ('customer_name', 'header', 'string'),
|
||||
('bill_to_customer', 'header', 'string'), ('bill_to_address', 'header', 'string'),
|
||||
('ship_to_customer', 'header', 'string'), ('ship_to_address', 'header', 'string'),
|
||||
('end_customer', 'header', 'string'), ('customer_contact', 'header', 'string'),
|
||||
('ship_from_organization', 'header', 'string'), ('destination', 'header', 'string'),
|
||||
('currency', 'header', 'string'), ('incoterm', 'header', 'string'),
|
||||
('payment_term', 'header', 'string'), ('mark_number', 'header', 'string'),
|
||||
('direct_ship_required', 'header', 'boolean'), ('urgent_order', 'header', 'boolean'),
|
||||
('order_remark', 'header', 'string'), ('line_no', 'line', 'string'),
|
||||
('reservation_id', 'line', 'string'), ('part_number', 'line', 'string'),
|
||||
('product_revision', 'line', 'string'), ('customer_part_number', 'line', 'string'),
|
||||
('customer_po_line_no', 'line', 'string'), ('product_feature', 'line', 'string'),
|
||||
('qty', 'line', 'decimal'), ('uom', 'line', 'string'), ('reference_qty', 'line', 'decimal'),
|
||||
('reference_uom', 'line', 'string'), ('pricing_qty', 'line', 'decimal'),
|
||||
('pricing_uom', 'line', 'string'), ('required_date', 'line', 'date'),
|
||||
('requested_receipt_date', 'line', 'date'), ('unit_price', 'line', 'decimal'),
|
||||
('line_amount_before_tax', 'line', 'decimal'), ('line_tax_amount', 'line', 'decimal'),
|
||||
('line_amount_with_tax', 'line', 'decimal'), ('tax_category', 'line', 'string'),
|
||||
('tax_rate', 'line', 'decimal'), ('ship_from_site', 'line', 'string'),
|
||||
('line_ship_to_address', 'line', 'string'), ('requested_warehouse_code', 'line', 'string'),
|
||||
('storage_location_code', 'line', 'string'), ('lot_number', 'line', 'string'),
|
||||
('inventory_source_hint', 'line', 'string'), ('partial_delivery_allowed', 'line', 'boolean'),
|
||||
('bonded_flag', 'line', 'boolean'), ('package_type', 'line', 'string'),
|
||||
('project_code', 'line', 'string'), ('wbs_code', 'line', 'string'),
|
||||
('activity_code', 'line', 'string'), ('line_remark', 'line', 'string'),
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""清理未投产旧配置/订单事实后,以 57 项目录重新建立字段身份。"""
|
||||
bind = op.get_bind()
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
_reset_affected_shipping_order_data(bind, tables)
|
||||
if 'shipping_order_snapshots' in tables:
|
||||
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshots')}
|
||||
with op.batch_alter_table('shipping_order_snapshots') as batch:
|
||||
if 'po_number' in columns:
|
||||
batch.alter_column('po_number', new_column_name='customer_po_number')
|
||||
if 'shipping_order_snapshot_lines' in tables:
|
||||
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshot_lines')}
|
||||
if 'aws_part_number' in columns:
|
||||
with op.batch_alter_table('shipping_order_snapshot_lines') as batch:
|
||||
batch.drop_column('aws_part_number')
|
||||
|
||||
if not {'shipping_order_schemas', 'shipping_order_fields'} <= tables:
|
||||
return
|
||||
schema = bind.execute(sa.text("SELECT id FROM shipping_order_schemas WHERE schema_code = 'SHIPPING_ORDER'")).mappings().first()
|
||||
if not schema:
|
||||
return
|
||||
schema_id = schema['id']
|
||||
# 业务未投产,旧 field_id 不可安全重解释为新语义,因此一律重新建立。
|
||||
bind.execute(sa.text("DELETE FROM shipping_order_fields WHERE schema_id = :schema_id"), {'schema_id': schema_id})
|
||||
for sequence, (field_code, scope, value_type) in enumerate(STANDARD_FIELDS, start=1):
|
||||
bind.execute(sa.text("""
|
||||
INSERT INTO shipping_order_fields
|
||||
(id, schema_id, field_code, scope, value_type, field_category, collection_mode,
|
||||
display_sequence, status, published_once, created_at, updated_at)
|
||||
VALUES
|
||||
(:id, :schema_id, :field_code, :scope, :value_type, :field_category,
|
||||
'llm_extraction', :sequence, 'active', false, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
"""), {
|
||||
'id': str(uuid.uuid4()), 'schema_id': schema_id, 'field_code': field_code,
|
||||
'scope': scope, 'value_type': value_type,
|
||||
'field_category': 'order_header' if scope == 'header' else 'order_line',
|
||||
'sequence': sequence,
|
||||
})
|
||||
|
||||
|
||||
def _reset_affected_shipping_order_data(bind: sa.Connection, tables: set[str]) -> None:
|
||||
"""删除依赖旧字段身份的未投产配置和履约数据,并解除任务引用。
|
||||
|
||||
核心逻辑:先解绑任务/库存源外键,再按依赖末端→前端顺序 DELETE;
|
||||
parsing_binding_audits 必须早于 parsing_profiles,避免 FK 阻断。
|
||||
"""
|
||||
if 'shipping_tasks' in tables:
|
||||
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_tasks')}
|
||||
resets = []
|
||||
if 'current_order_extraction_id' in columns:
|
||||
resets.append('current_order_extraction_id = NULL')
|
||||
if 'order_snapshot_id' in columns:
|
||||
resets.append('order_snapshot_id = NULL')
|
||||
if 'source_candidate_id' in columns:
|
||||
resets.append('source_candidate_id = NULL')
|
||||
if resets:
|
||||
bind.execute(sa.text(f"UPDATE shipping_tasks SET {', '.join(resets)}"))
|
||||
if 'agent_runtime_bindings' in tables:
|
||||
columns = {item['name'] for item in sa.inspect(bind).get_columns('agent_runtime_bindings')}
|
||||
if 'quality_batch_id' in columns:
|
||||
bind.execute(sa.text('UPDATE agent_runtime_bindings SET quality_batch_id = NULL'))
|
||||
if 'shipping_inventory_sources' in tables:
|
||||
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_inventory_sources')}
|
||||
resets = [name for name in ('parsing_profile_id', 'previous_parsing_profile_id', 'excel_template_id') if name in columns]
|
||||
if resets:
|
||||
assignments = [f'{name} = NULL' for name in resets]
|
||||
if 'enabled' in columns:
|
||||
assignments.append('enabled = false')
|
||||
bind.execute(sa.text(f"UPDATE shipping_inventory_sources SET {', '.join(assignments)}"))
|
||||
# 由最末端向 Schema/Field 反向清理,确保不同部署阶段缺表时也可安全升级。
|
||||
affected_tables = (
|
||||
'shipping_notice_candidates', 'shipping_excel_templates',
|
||||
'shipping_upload_attempts', 'shipping_export_artifact_lines',
|
||||
'shipping_inventory_verification_lines', 'shipping_reservations',
|
||||
'shipping_inventory_verifications', 'shipping_export_artifacts',
|
||||
'shipping_order_review_events', 'shipping_order_snapshot_lines', 'shipping_order_snapshots',
|
||||
'shipping_order_customer_matches', 'shipping_order_field_values',
|
||||
'shipping_order_field_decisions', 'shipping_order_field_observations',
|
||||
'shipping_order_lines', 'shipping_order_extractions',
|
||||
'shipping_order_extraction_quality_labels', 'shipping_order_extraction_progress_events',
|
||||
'shipping_order_extraction_diagnostic_audits', 'shipping_order_extraction_units',
|
||||
'shipping_order_extraction_plans', 'shipping_order_extraction_run_intakes',
|
||||
'shipping_order_extraction_runs', 'shipping_order_extraction_quality_batches',
|
||||
'shipping_customer_shadow_matches', 'shipping_customer_shadow_resolutions',
|
||||
'shipping_document_profile_test_runs', 'shipping_document_profile_test_samples',
|
||||
'shipping_document_profile_test_suites', 'shipping_order_document_profiles',
|
||||
'shipping_inventory_routing_rule_versions', 'shipping_inventory_routing_rule_conditions',
|
||||
'shipping_inventory_routing_rules',
|
||||
# [STEP] 先清绑定审计,再删 parsing_profiles,避免 previous/current 外键挡住删除。
|
||||
'shipping_inventory_source_parsing_binding_audits',
|
||||
'shipping_inventory_parsing_profiles',
|
||||
'shipping_identity_evidences', 'shipping_identity_rule_audit_events',
|
||||
'shipping_identity_rule_sets', 'shipping_identity_definitions',
|
||||
'shipping_fulfillment_policies', 'shipping_order_schema_audit_events',
|
||||
'shipping_order_schema_versions',
|
||||
)
|
||||
for table in affected_tables:
|
||||
if table in tables:
|
||||
bind.execute(sa.text(f'DELETE FROM {table}'))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅恢复已重命名/移除的物理兼容列;字段目录按发布记录仍不可无损回退。"""
|
||||
bind = op.get_bind()
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_order_snapshot_lines' in tables:
|
||||
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshot_lines')}
|
||||
if 'aws_part_number' not in columns:
|
||||
with op.batch_alter_table('shipping_order_snapshot_lines') as batch:
|
||||
batch.add_column(sa.Column('aws_part_number', sa.String(length=255), nullable=True))
|
||||
if 'shipping_order_snapshots' in tables:
|
||||
columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshots')}
|
||||
if 'customer_po_number' in columns:
|
||||
with op.batch_alter_table('shipping_order_snapshots') as batch:
|
||||
batch.alter_column('customer_po_number', new_column_name='po_number')
|
||||
@@ -135,7 +135,7 @@ def upgrade() -> None:
|
||||
)
|
||||
op.create_index('ix_shipping_inventory_external_mappings_inventory_source_id', 'shipping_inventory_external_mappings', ['inventory_source_id'])
|
||||
op.create_index(
|
||||
'uq_shipping_inventory_external_mappings_source_default_enabled',
|
||||
'uq_shipping_inv_ext_map_src_default_enabled',
|
||||
'shipping_inventory_external_mappings',
|
||||
['inventory_source_id'],
|
||||
unique=True,
|
||||
@@ -143,7 +143,7 @@ def upgrade() -> None:
|
||||
sqlite_where=sa.text('freight_warehouse_id IS NULL AND enabled = 1'),
|
||||
)
|
||||
op.create_index(
|
||||
'uq_shipping_inventory_external_mappings_source_warehouse_enabled',
|
||||
'uq_shipping_inv_ext_map_src_wh_enabled',
|
||||
'shipping_inventory_external_mappings',
|
||||
['inventory_source_id', 'freight_warehouse_id'],
|
||||
unique=True,
|
||||
|
||||
@@ -51,7 +51,6 @@ def _published_purposes(bind) -> dict[str, str]:
|
||||
def upgrade() -> None:
|
||||
"""仅迁移草稿规则;已发布规则若仍使用固定事实则阻断,禁止混合运行路径。"""
|
||||
bind = op.get_bind()
|
||||
purposes = _published_purposes(bind)
|
||||
rules = sa.table(
|
||||
'shipping_inventory_routing_rules',
|
||||
sa.column('id', sa.Integer()), sa.column('status', sa.String()),
|
||||
@@ -66,9 +65,13 @@ def upgrade() -> None:
|
||||
.join(rules, rules.c.id == conditions.c.rule_id)
|
||||
.where(conditions.c.system_fact_key.in_(tuple(_FACT_TO_PURPOSE)))
|
||||
).mappings().all()
|
||||
# 新库不存在旧固定事实条件,无需强制要求尚未配置的 published Schema。
|
||||
if not legacy:
|
||||
return
|
||||
published = [row for row in legacy if row['status'] == 'published']
|
||||
if published:
|
||||
raise RuntimeError('Published routing rules still use fixed system facts; retire and replace them before migration')
|
||||
purposes = _published_purposes(bind)
|
||||
for row in legacy:
|
||||
if row['status'] != 'draft':
|
||||
continue
|
||||
|
||||
+34
-34
@@ -91,12 +91,18 @@ def _backfill_legacy_inventory_source() -> None:
|
||||
bind = op.get_bind()
|
||||
legacy_config_version = "legacy-unverified"
|
||||
|
||||
rows = bind.execute(
|
||||
sa.text(
|
||||
"SELECT id, step_payload_json, pending_human_reason FROM shipping_tasks "
|
||||
"WHERE step_payload_json IS NOT NULL"
|
||||
)
|
||||
).fetchall()
|
||||
# `step_payload_json` was introduced by a sibling historical migration, not
|
||||
# this revision's ancestor chain. Fresh databases therefore have no legacy
|
||||
# JSON to backfill, while upgraded legacy databases can still preserve it.
|
||||
task_columns = {item["name"] for item in sa.inspect(bind).get_columns("shipping_tasks")}
|
||||
rows = []
|
||||
if "step_payload_json" in task_columns:
|
||||
rows = bind.execute(
|
||||
sa.text(
|
||||
"SELECT id, step_payload_json, pending_human_reason FROM shipping_tasks "
|
||||
"WHERE step_payload_json IS NOT NULL"
|
||||
)
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
payload = row.step_payload_json
|
||||
if not isinstance(payload, dict):
|
||||
@@ -175,36 +181,15 @@ def _backfill_legacy_inventory_source() -> None:
|
||||
},
|
||||
)
|
||||
if needs_review or status in {"ambiguous", "unresolved"}:
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_tasks SET "
|
||||
"pending_human_reason = 'inventory_source_unresolved', "
|
||||
"current_step = 'step2_parse_confirm', "
|
||||
"process_status = 'pending_review' "
|
||||
"WHERE id = :task_id"
|
||||
),
|
||||
{"task_id": row.id},
|
||||
)
|
||||
_mark_unresolved(bind, task_columns, "id = :task_id", {"task_id": row.id})
|
||||
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_tasks SET "
|
||||
"pending_human_reason = 'inventory_source_unresolved', "
|
||||
"current_step = 'step2_parse_confirm', "
|
||||
"process_status = 'pending_review' "
|
||||
"WHERE inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') "
|
||||
"AND (pending_human_reason IS NULL OR pending_human_reason = '')"
|
||||
)
|
||||
)
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_tasks SET "
|
||||
"pending_human_reason = 'inventory_source_unresolved', "
|
||||
"current_step = 'step2_parse_confirm', "
|
||||
"process_status = 'pending_review' "
|
||||
"WHERE inventory_source_config_version = 'legacy-unverified'"
|
||||
)
|
||||
_mark_unresolved(
|
||||
bind,
|
||||
task_columns,
|
||||
"inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') "
|
||||
"AND (pending_human_reason IS NULL OR pending_human_reason = '')",
|
||||
)
|
||||
_mark_unresolved(bind, task_columns, "inventory_source_config_version = 'legacy-unverified'")
|
||||
|
||||
file_rows = bind.execute(
|
||||
sa.text("SELECT id, source_code, warehouse_id FROM shipping_inventory_files WHERE source_code IS NOT NULL")
|
||||
@@ -218,6 +203,21 @@ def _backfill_legacy_inventory_source() -> None:
|
||||
)
|
||||
|
||||
|
||||
def _mark_unresolved(
|
||||
bind: sa.Connection,
|
||||
task_columns: set[str],
|
||||
where_clause: str,
|
||||
params: dict[str, object] | None = None,
|
||||
) -> None:
|
||||
"""回填旧状态时只写当前历史分支实际拥有的任务列。"""
|
||||
assignments = ["pending_human_reason = 'inventory_source_unresolved'"]
|
||||
if "current_step" in task_columns:
|
||||
assignments.append("current_step = 'step2_parse_confirm'")
|
||||
if "process_status" in task_columns:
|
||||
assignments.append("process_status = 'pending_review'")
|
||||
bind.execute(sa.text(f"UPDATE shipping_tasks SET {', '.join(assignments)} WHERE {where_clause}"), params or {})
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Remove inventory source gate columns."""
|
||||
with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
|
||||
|
||||
+12
-4
@@ -12,6 +12,7 @@ Create Date: 2026-07-17 10:28:00.000000
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
@@ -23,6 +24,10 @@ depends_on = None
|
||||
|
||||
def upgrade() -> None:
|
||||
"""将 shipping_inventory_erp_mappings 重命名为 shipping_inventory_external_mappings。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
# 空库链已由 2b3c 直接创建 external 表;只有历史库保留 erp 表时才需要重命名。
|
||||
if 'shipping_inventory_erp_mappings' not in tables:
|
||||
return
|
||||
# [STEP 1] 表名
|
||||
op.rename_table('shipping_inventory_erp_mappings', 'shipping_inventory_external_mappings')
|
||||
|
||||
@@ -60,11 +65,11 @@ def upgrade() -> None:
|
||||
)
|
||||
op.execute(
|
||||
'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_default_enabled '
|
||||
'RENAME TO uq_shipping_inventory_external_mappings_source_default_enabled'
|
||||
'RENAME TO uq_shipping_inv_ext_map_src_default_enabled'
|
||||
)
|
||||
op.execute(
|
||||
'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_warehouse_enabled '
|
||||
'RENAME TO uq_shipping_inventory_external_mappings_source_warehouse_enabled'
|
||||
'RENAME TO uq_shipping_inv_ext_map_src_wh_enabled'
|
||||
)
|
||||
op.execute(
|
||||
'ALTER INDEX IF EXISTS shipping_inventory_erp_mappings_pkey '
|
||||
@@ -74,16 +79,19 @@ def upgrade() -> None:
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚为 erp_* 表与列名。"""
|
||||
tables = set(sa.inspect(op.get_bind()).get_table_names())
|
||||
if 'shipping_inventory_external_mappings' not in tables:
|
||||
return
|
||||
op.execute(
|
||||
'ALTER INDEX IF EXISTS shipping_inventory_external_mappings_pkey '
|
||||
'RENAME TO shipping_inventory_erp_mappings_pkey'
|
||||
)
|
||||
op.execute(
|
||||
'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_warehouse_enabled '
|
||||
'ALTER INDEX IF EXISTS uq_shipping_inv_ext_map_src_wh_enabled '
|
||||
'RENAME TO uq_shipping_inventory_erp_mappings_source_warehouse_enabled'
|
||||
)
|
||||
op.execute(
|
||||
'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_default_enabled '
|
||||
'ALTER INDEX IF EXISTS uq_shipping_inv_ext_map_src_default_enabled '
|
||||
'RENAME TO uq_shipping_inventory_erp_mappings_source_default_enabled'
|
||||
)
|
||||
op.execute(
|
||||
|
||||
@@ -38,6 +38,9 @@ def _json_consumed_run_no_expr(dialect_name: str) -> str:
|
||||
|
||||
def _backfill_consumed_run_no(bind) -> None:
|
||||
"""将历史 step_payload_json 中的消费轮次回填到独立列。"""
|
||||
task_columns = {item["name"] for item in sa.inspect(bind).get_columns("shipping_tasks")}
|
||||
if "step_payload_json" not in task_columns:
|
||||
return
|
||||
expr = _json_consumed_run_no_expr(bind.dialect.name)
|
||||
bind.execute(
|
||||
sa.text(
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
@@ -30,28 +31,28 @@ from app.models import (
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_freeze_service import (
|
||||
HEADER_FIELDS,
|
||||
LINE_FIELDS,
|
||||
HEADER_FIELD_PROJECTIONS,
|
||||
LINE_FIELD_PROJECTIONS,
|
||||
assert_task_order_is_editable,
|
||||
freeze_order_snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False):
|
||||
def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False, suffix: str = '001'):
|
||||
"""创建一份含预置核心字段的已接受解析;可加入扩展字段验证配置化履约。"""
|
||||
user = User(username='snapshot-user', email='snapshot-user@example.test', password_hash='x')
|
||||
task = ShippingTask(task_no='SN-SNAPSHOT-001', source_type='test', order_data_version=7)
|
||||
user = User(username=f'snapshot-user-{suffix}', email=f'snapshot-user-{suffix}@example.test', password_hash='x')
|
||||
task = ShippingTask(task_no=f'SN-SNAPSHOT-{suffix}', source_type='test', order_data_version=7)
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order')
|
||||
db.session.add_all([user, task, schema])
|
||||
db.session.flush()
|
||||
definitions = []
|
||||
fields: dict[str, ShippingOrderField] = {}
|
||||
field_codes = [*HEADER_FIELDS, *LINE_FIELDS]
|
||||
field_codes = [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS]
|
||||
if with_extension:
|
||||
field_codes.append('packing_reference')
|
||||
for position, code in enumerate(field_codes, start=1):
|
||||
scope = 'header' if code in HEADER_FIELDS else 'line'
|
||||
value_type = 'decimal' if code in {'qty', 'unit_price', 'amount'} else ('date' if code in {'required_date', 'order_date'} else 'string')
|
||||
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
|
||||
value_type = 'decimal' if code in {'qty', 'unit_price', 'line_amount_with_tax'} else ('date' if code in {'required_date', 'order_date'} else 'string')
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code=code, scope=scope, value_type=value_type,
|
||||
field_category='order_header' if scope == 'header' else 'order_line',
|
||||
@@ -64,6 +65,27 @@ 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',
|
||||
)
|
||||
@@ -73,15 +95,15 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
values = {
|
||||
'po_number': 'PO-0001', 'customer_code': 'C-001', 'customer_name': 'Customer',
|
||||
'customer_po_number': 'PO-0001', 'customer_code': 'C-001', 'customer_name': 'Customer',
|
||||
'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'),
|
||||
'unit_price': Decimal('2.30'), 'amount': Decimal('28.75'), 'uom': 'PCS',
|
||||
'unit_price': Decimal('2.30'), 'line_amount_with_tax': Decimal('28.75'), 'uom': 'PCS',
|
||||
'packing_reference': 'PK-0007',
|
||||
}
|
||||
for code, field in fields.items():
|
||||
value = values.get(code)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None if code in HEADER_FIELDS else line.id,
|
||||
extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id,
|
||||
field_id=field.id, decision_status='accepted', resolved_value_json=str(value) if isinstance(value, Decimal) else value,
|
||||
supporting_observation_ids_json=[],
|
||||
)
|
||||
@@ -89,7 +111,7 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
|
||||
db.session.flush()
|
||||
if value is not None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None if code in HEADER_FIELDS else line.id,
|
||||
extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id,
|
||||
field_id=field.id, decision_id=decision.id, value_json=str(value) if isinstance(value, Decimal) else value,
|
||||
value_text=str(value) if isinstance(value, str) else None,
|
||||
value_decimal=value if isinstance(value, Decimal) else None,
|
||||
@@ -187,6 +209,38 @@ def test_freeze_rejects_core_field_type_drift(app):
|
||||
assert error.value.code == 'SHIPPING.ORDER_CONTRACT_INVALID'
|
||||
|
||||
|
||||
def test_freeze_allows_schema_without_optional_standard_fields(app):
|
||||
"""关键断言:当前滚动发货策略只要求预约号、料号和正数数量,不要求全部标准字段。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order()
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
required = {'reservation_id', 'part_number', 'qty'}
|
||||
extraction.schema_version.definition_json['fields'] = [
|
||||
item for item in extraction.schema_version.definition_json['fields']
|
||||
if item['field_code'] in required
|
||||
]
|
||||
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app):
|
||||
"""冻结只能采纳已确认订购客户,调用者传 customer_id 不能绕过该链路。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -10,7 +10,18 @@ from __future__ import annotations
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
reconstruct_table_from_positioned_text,
|
||||
suggest_multi_subrow_layouts,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
CoordinateReconstructionProfile,
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
order_profile_structure_fingerprint,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _glyphs(*rows: list[tuple[str, float]]) -> list[dict]:
|
||||
@@ -62,3 +73,229 @@ def test_coordinate_reconstruction_only_attaches_deleted_marker_to_prior_line():
|
||||
assert attached.rows[1].role == 'deleted'
|
||||
assert unattached.rows[0].role == 'needs_review'
|
||||
assert unattached.issues == ['coordinate_reconstruction_deleted_row_unattached']
|
||||
|
||||
|
||||
def test_reconstructed_profile_html_uses_confirmed_relative_column_boundaries():
|
||||
"""坐标模板用稳定虚拟表头并合并续行,不能回退到错误 HTML 的行列关系。"""
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('ITEM NO', 12), ('MATERIAL', 62)],
|
||||
[('00010', 12), ('PART-A', 62)],
|
||||
[('PART-A-DETAIL', 62)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 120, 'y1': 70},
|
||||
reconstruction=CoordinateReconstructionProfile(column_boundaries=[0, 0.4, 1]),
|
||||
)
|
||||
assert 'coordinate_column_1' in html
|
||||
assert 'ITEM NO' not in html
|
||||
assert 'PART-A PART-A-DETAIL' in html
|
||||
assert html.count('<tr ') == 2
|
||||
|
||||
|
||||
def test_reconstructed_profile_html_marks_deleted_and_stops_at_summary():
|
||||
"""删除标记回写最近明细;TOTAL AMOUNT 之后的文本不得进入逻辑明细。"""
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00010', 12), ('PART-A', 62)],
|
||||
[('** Item deleted **', 62)],
|
||||
[('TOTAL AMOUNT', 62), ('100.00', 150)],
|
||||
[('00020', 12), ('PART-B', 62)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
reconstruction=CoordinateReconstructionProfile(column_boundaries=[0, 0.3, 0.7, 1]),
|
||||
)
|
||||
assert 'data-row-role="deleted"' in html
|
||||
assert 'PART-B' not in html
|
||||
|
||||
|
||||
def test_coordinate_reconstruction_uses_fixed_field_content_for_boundary_tie():
|
||||
"""字符恰好跨数量与单位边界时,固定字段类型只能作为几何并列的辅助证据。"""
|
||||
result = reconstruct_table_from_positioned_text(
|
||||
characters=[
|
||||
{'text': 'E', 'bbox': {'x0': 96, 'y0': 20, 'x1': 100, 'y1': 30}},
|
||||
{'text': 'A', 'bbox': {'x0': 100, 'y0': 20, 'x1': 104, 'y1': 30}},
|
||||
],
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100),
|
||||
column_anchors=[
|
||||
{'column_index': 0, 'field_code': 'qty', 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 100}},
|
||||
{'column_index': 1, 'field_code': 'uom', 'bbox': {'x0': 100, 'y0': 0, 'x1': 200, 'y1': 100}},
|
||||
],
|
||||
)
|
||||
assert result.rows[0].cells[0].column_index == 1
|
||||
assert result.rows[0].cells[0].text == 'EA'
|
||||
|
||||
|
||||
def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
"""端到端验证:一条数据行加两条续行只能产出一条可审核订单明细。"""
|
||||
settings = CoordinateReconstructionProfile(
|
||||
column_boundaries=[0, 0.2, 0.7, 1],
|
||||
column_field_codes=['line_no', 'part_number', 'qty'],
|
||||
)
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00020', 12), ('6Y70B2501901', 52), ('30', 160)],
|
||||
[('D4-A08AR1200002', 52)],
|
||||
[('RoHS2', 52)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
reconstruction=settings,
|
||||
)
|
||||
grid = parse_html_grid(html, table_id='inventec')
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='INVENTEC_PO', version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0, data_start_row_index=1,
|
||||
column_rules=[
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['qty']),
|
||||
],
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'display_name': 'Line', 'enabled': True},
|
||||
{'field_code': 'part_number', 'display_name': 'Part', 'enabled': True},
|
||||
{'field_code': 'qty', 'display_name': 'Qty', 'value_type': 'decimal', 'enabled': True},
|
||||
]})
|
||||
|
||||
parsed = parse_html_table_with_order_profile(html, table_id='inventec', profile=profile, contract=contract)
|
||||
|
||||
assert parsed.matched is True
|
||||
assert len(parsed.rows) == 1
|
||||
assert parsed.rows[0].fields == {
|
||||
'line_no': '00020', 'part_number': '6Y70B2501901 D4-A08AR1200002 RoHS2', 'qty': 30,
|
||||
}
|
||||
|
||||
|
||||
def test_multi_subrow_profile_uses_independent_overlapping_boundaries():
|
||||
"""主行和补充行可在相同横坐标表达不同字段,并合并为一条逻辑明细。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{
|
||||
'role': 'main', 'row_offset': 0,
|
||||
'column_boundaries': [0, 0.12, 0.32, 0.5, 0.68, 0.84, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'remark', 'unit_price', 'qty', 'uom'],
|
||||
},
|
||||
{
|
||||
'role': 'continuation', 'row_offset': 1,
|
||||
'column_boundaries': [0, 0.18, 0.48, 0.7, 1],
|
||||
'column_field_codes': [None, 'customer_part_number', 'required_date', 'remark'],
|
||||
},
|
||||
{
|
||||
'role': 'continuation', 'row_offset': 2,
|
||||
'column_boundaries': [0, 0.25, 0.55, 1],
|
||||
'column_field_codes': [None, 'inventory_source_hint', 'remark'],
|
||||
},
|
||||
])
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00020', 12), ('6Y70B2501901', 46), ('SET,RACK', 102), ('941.76', 154), ('30', 208), ('EA', 260)],
|
||||
[('D4-A08AR1200002', 58), ('06/29/2026', 150), ('Ship by land', 220)],
|
||||
[('RoHS2', 82), ('EXW AWS HUB', 180)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100},
|
||||
reconstruction=settings,
|
||||
)
|
||||
|
||||
assert html.count('data-row-role="data"') == 1
|
||||
assert '6Y70B2501901' in html
|
||||
assert 'D4-A08AR1200002' in html
|
||||
assert '06/29/2026' in html
|
||||
assert 'EXW AWS HUB' in html
|
||||
assert 'data-source-rows="0,1,2"' in html
|
||||
|
||||
|
||||
def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser():
|
||||
"""多子行输出必须继续由既有固定列 Profile 解析器消费,避免另造运行链路。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.2, 0.65, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.4, 0.7, 1],
|
||||
'column_field_codes': [None, 'required_date', 'remark']},
|
||||
])
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00020', 12), ('PART-20', 70), ('30', 240)],
|
||||
[('06/29/2026', 135), ('Ship by land', 235)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70},
|
||||
reconstruction=settings,
|
||||
)
|
||||
grid = parse_html_grid(html, table_id='multi-subrow')
|
||||
headers = ['line_no', 'part_number', 'qty', 'required_date', 'remark']
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='MULTI_SUBROW', version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0, data_start_row_index=1,
|
||||
column_rules=[
|
||||
OrderProfileColumnRule(column_index=index, extractor_key='direct', target_field_codes=[code])
|
||||
for index, code in enumerate(headers)
|
||||
],
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'enabled': True},
|
||||
{'field_code': 'part_number', 'enabled': True},
|
||||
{'field_code': 'qty', 'value_type': 'decimal', 'enabled': True},
|
||||
{'field_code': 'required_date', 'value_type': 'date', 'enabled': True},
|
||||
{'field_code': 'remark', 'enabled': True},
|
||||
]})
|
||||
|
||||
parsed = parse_html_table_with_order_profile(html, table_id='multi-subrow', profile=profile, contract=contract)
|
||||
|
||||
assert parsed.matched is True
|
||||
assert len(parsed.rows) == 1
|
||||
assert parsed.rows[0].fields['part_number'] == 'PART-20'
|
||||
assert parsed.rows[0].fields['qty'] == 30
|
||||
assert parsed.rows[0].fields['required_date'] == '2026-06-29'
|
||||
assert parsed.rows[0].fields['remark'] == 'Ship by land'
|
||||
|
||||
|
||||
def test_multi_subrow_profile_supports_four_or_more_physical_rows():
|
||||
"""逻辑明细行数由模板动态定义,四行版式不得被固定三行实现截断。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'customer_part_number']},
|
||||
{'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'required_date']},
|
||||
{'role': 'continuation', 'row_offset': 3, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'remark']},
|
||||
])
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('10', 12), ('PART-10', 100), ('3', 270)],
|
||||
[('VENDOR-10', 180)],
|
||||
[('05/05/2026', 180)],
|
||||
[('R2_SA;HF_SA', 180)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100},
|
||||
reconstruction=settings,
|
||||
)
|
||||
|
||||
assert html.count('data-row-role="data"') == 1
|
||||
assert 'data-source-rows="0,1,2,3"' in html
|
||||
assert 'VENDOR-10' in html
|
||||
assert '05/05/2026' in html
|
||||
assert 'R2_SA;HF_SA' in html
|
||||
|
||||
|
||||
def test_layout_suggestion_uses_real_rows_and_dynamic_column_counts():
|
||||
"""自动建议应从真实横坐标生成动态行数,并忽略表头和合计区域。"""
|
||||
suggestions = suggest_multi_subrow_layouts(
|
||||
characters=_glyphs(
|
||||
[('ITEM NO', 12), ('MATERIAL NO', 70), ('ORDER QUANTITY', 240)],
|
||||
[('00020', 12), ('6Y70B2501401', 70), ('36', 250)],
|
||||
[('B3-AR1000270A1', 105), ('06/29/2026', 180), ('Ship by land', 240)],
|
||||
[('RoHS2', 20), ('A', 105), ('EXW AWS HUB', 145)],
|
||||
[('TOTAL AMOUNT', 220), ('1815.48', 280)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 130},
|
||||
)
|
||||
|
||||
assert len(suggestions) == 3
|
||||
assert suggestions[0].suggested_field_codes[0] == 'line_no'
|
||||
assert suggestions[0].column_samples[0] == ['00020']
|
||||
assert 'B3-AR1000270A1' in suggestions[1].column_samples[0]
|
||||
assert suggestions[2].column_boundaries[0] == 0
|
||||
assert suggestions[2].column_boundaries[-1] == 1
|
||||
@@ -39,10 +39,19 @@ def _freeze_export_snapshot(
|
||||
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
|
||||
) -> None:
|
||||
"""为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
|
||||
field_codes = {
|
||||
str(item.get('field_id')): str(item.get('field_code') or '')
|
||||
for item in (version.definition_json or {}).get('fields') or []
|
||||
}
|
||||
po_number = next(
|
||||
(str(value) for field_id, value in (header or {}).items() if field_codes.get(str(field_id)) == 'po_number'),
|
||||
'TEST-PO-001',
|
||||
)
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1, rule_versions_json={},
|
||||
header_values_json={str(key): value for key, value in (header or {}).items()},
|
||||
customer_po_number=po_number,
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
@@ -225,7 +234,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
_freeze_export_snapshot(
|
||||
task, extraction, version,
|
||||
header={customer.id: 'acme', po_number.id: '16754796'},
|
||||
lines=[(1, part.id, 'PN-1', 1, 'RES-EXPORT-1')],
|
||||
lines=[(1, part.id, 'PN-1', 1, '1000000001')],
|
||||
)
|
||||
|
||||
path, filename, artifact = generate_shipment_excel(task)
|
||||
@@ -409,8 +418,8 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
_freeze_export_snapshot(
|
||||
task, extraction, version,
|
||||
lines=[
|
||||
(1, part.id, 'PN-A', 1, 'RES-KEYED-A'),
|
||||
(2, part.id, 'PN-B', 1, 'RES-KEYED-B'),
|
||||
(1, part.id, 'PN-A', 1, '1000000002'),
|
||||
(2, part.id, 'PN-B', 1, '1000000003'),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -579,7 +588,7 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
|
||||
db.session.add(task); db.session.flush()
|
||||
_freeze_export_snapshot(
|
||||
task, extraction, version,
|
||||
lines=[(1, part.id, 'PN-A', 1, 'RES-AMBIGUOUS-A')],
|
||||
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='值不一致'):
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
tests/test_shipping_fulfillment_policy.py
|
||||
|
||||
用途:验证货代字段能力绑定与版本化履约策略。
|
||||
依赖:订单 Schema 服务、履约策略注册表与测试数据库。
|
||||
逻辑:策略只允许受控能力绑定稳定 field_id;发布后冻结保存版本快照,错误类型或范围必须阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import 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 test_policy_initialization_and_publish_versions_are_isolated(app):
|
||||
"""初始化只创建待确认草稿;发布后新版本退役旧版且保留稳定字段绑定。"""
|
||||
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',
|
||||
}
|
||||
|
||||
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_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_allows_a_custom_field_to_bind_a_compatible_capability(app):
|
||||
"""自定义字段只要 scope/type 匹配,即可经策略承担履约能力而不依赖字段编码。"""
|
||||
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',
|
||||
}, actor_id=None)
|
||||
bindings = _bindings()
|
||||
bindings[0]['field_id'] = custom['id']
|
||||
|
||||
draft = create_draft({'field_bindings': bindings, 'change_note': '客户预约单字段'}, actor_id=None)
|
||||
|
||||
reservation = next(item for item in draft['definition']['field_bindings']
|
||||
if item['capability_code'] == 'fulfillment.reservation_identity')
|
||||
assert reservation['field_id'] == custom['id']
|
||||
assert reservation['field_code'] == 'customer_reservation_reference'
|
||||
|
||||
|
||||
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)
|
||||
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'])
|
||||
custom = schema_service.save_field({
|
||||
'field_code': 'unpublished_reservation_reference', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
bindings = _bindings()
|
||||
bindings[0]['field_id'] = custom['id']
|
||||
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) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED'
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
tests/test_shipping_inventory_routing_engine.py
|
||||
|
||||
用途:验证库存源路由只消费已发布订单 Schema 的已裁决字段值。
|
||||
用途:验证库存源路由只消费冻结订单 Snapshot 中的已裁决字段值。
|
||||
依赖:订单 Schema service、库存路由模型、inventory_routing_engine。
|
||||
逻辑:测试以稳定 field_id 创建 FieldValue,确认库存源线索优先于预定单号兜底且不会读取固定任务行字段。
|
||||
逻辑:测试以稳定 field_id 创建冻结行事实,确认库存源线索优先于预定单号兜底且不会读取可变解析投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,48 +11,66 @@ from __future__ import annotations
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _field_config(field_id: str, *, name: str) -> dict:
|
||||
def _field_config(field_id: str, *, name: str, value_type: str = 'string') -> dict:
|
||||
"""构造最小可发布行字段配置;路由只依赖其稳定 field_id。"""
|
||||
return {
|
||||
'field_id': field_id, 'display_name': name, 'required': False, 'aliases': [],
|
||||
'normalizer_key': 'uppercase_trim', 'validator_keys': [], 'enum_options': [],
|
||||
'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim',
|
||||
'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text',
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None, 'comparator_key': 'normalized_text',
|
||||
'relation_role': None,
|
||||
}
|
||||
|
||||
|
||||
def _published_line_fields() -> dict[str, str]:
|
||||
"""创建当前测试所需的预定单号和库存源线索字段,并发布其稳定契约。"""
|
||||
"""创建冻结履约所需字段及可选库存源线索,并发布其稳定契约。"""
|
||||
order_schema_service.initialize_schema({'display_name': '路由字段'}, actor_id=None)
|
||||
reservation = order_schema_service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
part_number = order_schema_service.save_field(
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
qty = order_schema_service.save_field(
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None,
|
||||
)
|
||||
source_hint = order_schema_service.save_field(
|
||||
{'field_code': 'inventory_source_hint', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
reservation_config = _field_config(reservation['id'], name='预定单号')
|
||||
reservation_config['business_purpose'] = 'reservation_id'
|
||||
part_number_config = _field_config(part_number['id'], name='料号')
|
||||
part_number_config['business_purpose'] = 'part_number'
|
||||
qty_config = _field_config(qty['id'], name='数量', value_type='decimal')
|
||||
qty_config['business_purpose'] = 'quantity'
|
||||
source_hint_config = _field_config(source_hint['id'], name='库存源线索')
|
||||
source_hint_config['business_purpose'] = 'inventory_source_hint'
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [reservation_config, source_hint_config], 'expected_lock_version': draft['lock_version'],
|
||||
'fields': [reservation_config, part_number_config, qty_config, source_hint_config],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
return {'reservation_id': reservation['id'], 'inventory_source_hint': source_hint['id']}
|
||||
return {
|
||||
'reservation_id': reservation['id'], 'part_number': part_number['id'], 'qty': qty['id'],
|
||||
'inventory_source_hint': source_hint['id'],
|
||||
}
|
||||
|
||||
|
||||
def _task_with_line_values(values: dict[str, tuple[str, str]]) -> tuple[ShippingTask, dict[str, int]]:
|
||||
"""保存当前解析的 FieldValue;测试断言路由只通过该审计投影读取值。"""
|
||||
def _task_with_line_values(
|
||||
fields: dict[str, str], values: dict[str, tuple[str, str]],
|
||||
) -> tuple[ShippingTask, dict[str, int]]:
|
||||
"""创建冻结快照;路由测试只允许从该不可变事实读取字段。"""
|
||||
task = ShippingTask(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -77,6 +95,23 @@ def _task_with_line_values(values: dict[str, tuple[str, str]]) -> tuple[Shipping
|
||||
value_text=value, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
snapshot_values = {field_id: value for field_id, (value, _purpose) in values.items()}
|
||||
snapshot_values.setdefault(fields['part_number'], 'PN-ROUTE')
|
||||
snapshot_values.setdefault(fields['qty'], '1')
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id,
|
||||
schema_version_id=extraction.schema_version_id, order_data_version=1,
|
||||
rule_versions_json={}, header_values_json={}, customer_po_number='ROUTE-PO-001',
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0,
|
||||
reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''),
|
||||
part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']],
|
||||
field_values_json=snapshot_values,
|
||||
))
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
return task, {'_position': 0}
|
||||
|
||||
@@ -100,7 +135,7 @@ def test_reservation_prefix_rule_returns_ambiguous_source_candidates(app):
|
||||
"""十位预定单号兜底只产生 DUB/RTM 候选,不在路由阶段擅自选择 Source。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
@@ -115,7 +150,7 @@ def test_inventory_source_hint_wins_over_reservation_fallback(app):
|
||||
"""高优先级库存源线索必须覆盖预定单号兜底,体现明确订单事实优先。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({
|
||||
task, line = _task_with_line_values(fields, {
|
||||
fields['reservation_id']: ('1000123456', 'reservation_id'),
|
||||
fields['inventory_source_hint']: ('VMI-FRA01', 'inventory_source_hint'),
|
||||
})
|
||||
@@ -139,7 +174,7 @@ def test_crane_inventory_source_hint_wins_over_reservation_fallback(app):
|
||||
"""Crane 邮件线索必须按高优先级规则命中,不依赖五位预定单号兜底。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({
|
||||
task, line = _task_with_line_values(fields, {
|
||||
fields['reservation_id']: ('1000123456', 'reservation_id'),
|
||||
fields['inventory_source_hint']: ('LUK', 'inventory_source_hint'),
|
||||
})
|
||||
@@ -166,7 +201,7 @@ def test_five_digit_reservation_rule_can_route_to_crane(app):
|
||||
"""五位纯数字预定单号通过订单 FieldValue 路由 Crane,Warehouse 仍留给库存行匹配。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({fields['reservation_id']: ('12345', 'reservation_id')})
|
||||
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('12345', 'reservation_id')})
|
||||
db.session.add(_rule(
|
||||
code='RSV_LENGTH_5', priority=200, sources=['CRANE'],
|
||||
conditions=[(fields['reservation_id'], 'numeric_length', 5)],
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""验证库存源独立字段迁移可在不存在旧 JSON 列的空库链上执行。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_inventory_source_gate_backfill_skips_absent_legacy_json_column(monkeypatch):
|
||||
"""关键断言:空库没有 sibling 迁移的 JSON 列时,回填不得查询不存在的列。"""
|
||||
migration = importlib.import_module('migrations.versions.b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields')
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_tasks', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('pending_human_reason', sa.String(64)),
|
||||
sa.Column('inventory_source_status', sa.String(32)),
|
||||
sa.Column('inventory_source_config_version', sa.String(32)),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_inventory_files', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('source_code', sa.String(64)),
|
||||
sa.Column('warehouse_id', sa.String(64)),
|
||||
sa.Column('identity_status', sa.String(32)),
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
metadata.create_all(connection)
|
||||
monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection)))
|
||||
migration._backfill_legacy_inventory_source()
|
||||
|
||||
|
||||
def test_rpa_consumed_run_backfill_skips_absent_legacy_json_column(monkeypatch):
|
||||
"""关键断言:后续幂等迁移在空库链中也不得读取 sibling JSON 列。"""
|
||||
migration = importlib.import_module('migrations.versions.d6e7f8a9b0c1_add_rpa_callback_idempotency_fields')
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_tasks', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('inventory_rpa_consumed_run_no', sa.String(128)),
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
metadata.create_all(connection)
|
||||
monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection)))
|
||||
migration._backfill_consumed_run_no(connection)
|
||||
|
||||
|
||||
def test_external_mapping_rename_skips_empty_database_chain(monkeypatch):
|
||||
"""关键断言:新库已无 ERP 表时,兼容重命名迁移必须成为安全空操作。"""
|
||||
migration = importlib.import_module('migrations.versions.d38f4a5b6c7d_rename_erp_mappings_to_external_mappings')
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
with engine.begin() as connection:
|
||||
monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection)))
|
||||
migration.upgrade()
|
||||
|
||||
|
||||
def test_routing_rule_migration_skips_empty_configuration(monkeypatch):
|
||||
"""关键断言:没有旧路由条件的空库不得要求业务管理员预先发布 Schema。"""
|
||||
migration = importlib.import_module('migrations.versions.ad2e3f4a5b6c_migrate_routing_rules_to_order_fields')
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('shipping_order_schema_versions', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('status', sa.String()), sa.Column('definition_json', sa.JSON()))
|
||||
sa.Table('shipping_inventory_routing_rules', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('status', sa.String()))
|
||||
sa.Table(
|
||||
'shipping_inventory_routing_rule_conditions', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True), sa.Column('rule_id', sa.Integer()),
|
||||
sa.Column('source_kind', sa.String()), sa.Column('order_field_id', sa.String()), sa.Column('system_fact_key', sa.String()),
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
metadata.create_all(connection)
|
||||
monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection)))
|
||||
migration.upgrade()
|
||||
@@ -82,7 +82,16 @@ def _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_i
|
||||
# 建立最小履约真相,避免旧测试绕过阶段 1 门禁。
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'],
|
||||
order_data_version=task.order_data_version or 1, rule_versions_json={}, header_values_json={},
|
||||
order_data_version=task.order_data_version or 1,
|
||||
rule_versions_json={'fulfillment_policy': {
|
||||
'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1,
|
||||
'definition': {'field_bindings': [
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'},
|
||||
]},
|
||||
}},
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
|
||||
@@ -17,6 +17,8 @@ from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingDocumentProfileTestSample,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
FileAsset,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
@@ -412,3 +414,269 @@ def test_profile_sample_intake_is_isolated_from_shipping_business_flow(app):
|
||||
with pytest.raises(Exception) as caught:
|
||||
create_order_document_profile_sample_intake(user_id=user.id, asset_no=invalid.asset_no)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID'
|
||||
|
||||
|
||||
def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, monkeypatch):
|
||||
"""专用样本可回收;历史业务样本与盲测证据必须由删除门禁保留。"""
|
||||
with app.app_context():
|
||||
user = User(username='sample-delete-admin', email='sample-delete@example.com', role='admin', status='active')
|
||||
asset = FileAsset(
|
||||
asset_no='FA-PROFILE-DELETE', owner_user_id=1, original_filename='delete.pdf',
|
||||
storage_provider='minio', storage_bucket='test', storage_key='delete.pdf',
|
||||
content_hash='1' * 64, file_size=100, mime_type='application/pdf',
|
||||
upload_status='ready', lifecycle_status='referenced', reference_count=1,
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset.owner_user_id = user.id
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-PROFILE-DELETE', asset_id=asset.id, user_id=user.id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
|
||||
attachment_key='delete.pdf', filename='delete.pdf', content_hash='1' * 64,
|
||||
classification='supporting', parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
|
||||
deleted_assets: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.delete_temporary_asset',
|
||||
lambda *, asset_no, user_id: deleted_assets.append(asset_no),
|
||||
)
|
||||
service.delete_sample_intake(intake.intake_no, actor_id=user.id)
|
||||
assert ShippingNoticeIntake.query.filter_by(intake_no=intake.intake_no).first() is None
|
||||
assert deleted_assets == ['FA-PROFILE-DELETE']
|
||||
|
||||
asset.reference_count = 1
|
||||
asset.lifecycle_status = 'referenced'
|
||||
|
||||
protected_intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-PROFILE-BLIND', asset_id=asset.id, user_id=user.id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v7',
|
||||
)
|
||||
db.session.add(protected_intake)
|
||||
db.session.flush()
|
||||
protected_document = ShippingNoticeDocument(
|
||||
intake_id=protected_intake.id, asset_id=asset.id, document_type='attachment',
|
||||
attachment_key='blind.pdf', filename='blind.pdf', content_hash='2' * 64,
|
||||
classification='supporting', parse_status='parsed',
|
||||
)
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='DELETE_TEST', display_name='Delete test', version=1,
|
||||
status='published', schema_version_id=_schema_version().id,
|
||||
structure_fingerprint='2' * 64, definition_json={}, checksum='2' * 64,
|
||||
published_at=datetime.utcnow(), lock_version=1,
|
||||
)
|
||||
db.session.add_all([protected_document, profile])
|
||||
db.session.flush()
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=profile.checksum, created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingDocumentProfileTestSample(
|
||||
suite_id=suite.id, document_id=protected_document.id, table_id='table-1',
|
||||
expected_rows_json=[], created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.delete_sample_intake(protected_intake.intake_no, actor_id=user.id)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED'
|
||||
|
||||
|
||||
def test_profile_normalizes_coordinate_fields_from_column_rules(app):
|
||||
"""服务端必须覆盖浏览器伪造的坐标字段辅助数组和新行列。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'COORDINATE_SAFE', 'display_name': 'Coordinate safe',
|
||||
'schema_version_id': schema.id,
|
||||
'definition': {
|
||||
'structure_fingerprint': 'a' * 64,
|
||||
'header_row_index': 0, 'data_start_row_index': 1,
|
||||
'row_structure': 'preserved',
|
||||
'column_rules': [
|
||||
{'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number']},
|
||||
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['part_number']},
|
||||
{'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['qty']},
|
||||
],
|
||||
'coordinate_reconstruction': {
|
||||
'column_boundaries': [0, 0.2, 0.8, 1],
|
||||
'column_field_codes': ['qty', 'qty', 'qty'],
|
||||
'line_start_column_index': 2,
|
||||
},
|
||||
},
|
||||
}, actor_id=None)
|
||||
|
||||
reconstruction = saved['definition']['coordinate_reconstruction']
|
||||
assert reconstruction['column_field_codes'] == ['customer_part_number', 'part_number', 'qty']
|
||||
assert reconstruction['line_start_column_index'] == 0
|
||||
|
||||
|
||||
def test_profile_accepts_schema_bound_multi_subrow_layouts(app):
|
||||
"""多子行允许重叠字段语义,但每个字段都必须来自绑定 Schema。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'MULTI_SUBROW', 'display_name': 'Multi subrow',
|
||||
'schema_version_id': schema.id,
|
||||
'definition': {
|
||||
'structure_fingerprint': 'c' * 64,
|
||||
'header_row_index': 0, 'data_start_row_index': 1,
|
||||
'row_structure': 'preserved',
|
||||
'column_rules': [
|
||||
{'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number']},
|
||||
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['part_number']},
|
||||
{'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['qty']},
|
||||
],
|
||||
'coordinate_reconstruction': {'subrow_layouts': [
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.3, 0.7, 1],
|
||||
'column_field_codes': ['customer_part_number', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'customer_part_number']},
|
||||
]},
|
||||
},
|
||||
}, actor_id=None)
|
||||
|
||||
subrows = saved['definition']['coordinate_reconstruction']['subrow_layouts']
|
||||
assert subrows[0]['column_field_codes'] == ['customer_part_number', 'part_number', 'qty']
|
||||
assert subrows[1]['column_field_codes'] == [None, 'customer_part_number']
|
||||
|
||||
|
||||
def test_coordinate_preview_reports_four_source_rows(app, monkeypatch):
|
||||
"""四行物理版式在管理端预览中必须合并为一条逻辑明细并保留全部来源行。"""
|
||||
def characters(*rows: list[tuple[str, float]]) -> list[dict]:
|
||||
"""构造四条相互分离的坐标文本行,模拟持久化原生 PDF 字符证据。"""
|
||||
result: list[dict] = []
|
||||
source_index = 0
|
||||
for row_index, row in enumerate(rows):
|
||||
for text, x0 in row:
|
||||
for character_index, character in enumerate(text):
|
||||
result.append({
|
||||
'text': character,
|
||||
'source_index': source_index,
|
||||
'bbox': {
|
||||
'x0': x0 + character_index * 5,
|
||||
'y0': 10 + row_index * 20,
|
||||
'x1': x0 + (character_index + 1) * 5,
|
||||
'y1': 20 + row_index * 20,
|
||||
},
|
||||
})
|
||||
source_index += 1
|
||||
return result
|
||||
|
||||
layout = {
|
||||
'tables': [{
|
||||
'table_id': 'four-row', 'page_no': 1,
|
||||
'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100},
|
||||
'html': '<table><tr><td>broken</td></tr></table>',
|
||||
}],
|
||||
'coordinate_evidence': {'tables': {'four-row': characters(
|
||||
[('10', 12), ('PART-10', 100), ('3', 270)],
|
||||
[('VENDOR-10', 180)],
|
||||
[('05/05/2026', 180)],
|
||||
[('R2_SA;HF_SA', 180)],
|
||||
)}},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
|
||||
|
||||
with app.app_context():
|
||||
preview = service.preview_coordinate_reconstruction({
|
||||
'document_id': 101,
|
||||
'table_id': 'four-row',
|
||||
'coordinate_reconstruction': {'subrow_layouts': [
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'customer_part_number']},
|
||||
{'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'required_date']},
|
||||
{'role': 'continuation', 'row_offset': 3, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'part_number']},
|
||||
]},
|
||||
}, actor_id=None)
|
||||
|
||||
assert preview['row_count'] == 2
|
||||
assert preview['row_roles'] == ['header', 'data']
|
||||
assert preview['source_row_indices'] == [[], [0, 1, 2, 3]]
|
||||
|
||||
|
||||
def test_coordinate_suggestion_returns_reviewable_dynamic_rows(app, monkeypatch):
|
||||
"""建议接口只返回相对边界和示例,并自动标出首行 line_no。"""
|
||||
characters = []
|
||||
source_index = 0
|
||||
for row_index, row in enumerate([
|
||||
[('00020', 12), ('PART-20', 100), ('36', 270)],
|
||||
[('VENDOR-20', 150)],
|
||||
]):
|
||||
for text, x0 in row:
|
||||
for character_index, character in enumerate(text):
|
||||
characters.append({
|
||||
'text': character, 'source_index': source_index,
|
||||
'bbox': {
|
||||
'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20,
|
||||
'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20,
|
||||
},
|
||||
})
|
||||
source_index += 1
|
||||
layout = {
|
||||
'tables': [{'table_id': 'suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70},
|
||||
'html': '<table><tr><td>broken</td></tr></table>'}],
|
||||
'coordinate_evidence': {'tables': {'suggest': characters}},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 102 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_coordinate_reconstruction(
|
||||
{'document_id': 102, 'table_id': 'suggest'}, actor_id=None,
|
||||
)
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert len(result['subrow_layouts']) == 2
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'][0] == 'line_no'
|
||||
assert result['subrow_layouts'][1]['column_boundaries'] == [0.0, 1.0]
|
||||
|
||||
|
||||
def test_coordinate_suggestion_can_return_only_requested_physical_row(app, monkeypatch):
|
||||
"""指定 row_offset 时只返回当前物理行,避免覆盖管理员已确认的其他行。"""
|
||||
characters = []
|
||||
source_index = 0
|
||||
for row_index, row in enumerate([
|
||||
[('00020', 12), ('PART-20', 100), ('36', 270)],
|
||||
[('VENDOR-20', 150)],
|
||||
]):
|
||||
for value, x0 in row:
|
||||
for character_index, character in enumerate(value):
|
||||
characters.append({
|
||||
'text': character, 'source_index': source_index,
|
||||
'bbox': {
|
||||
'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20,
|
||||
'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20,
|
||||
},
|
||||
})
|
||||
source_index += 1
|
||||
layout = {
|
||||
'tables': [{'table_id': 'suggest-one', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70},
|
||||
'html': '<table><tr><td>broken</td></tr></table>'}],
|
||||
'coordinate_evidence': {'tables': {'suggest-one': characters}},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 103 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_coordinate_reconstruction(
|
||||
{'document_id': 103, 'table_id': 'suggest-one', 'row_offset': 1}, actor_id=None,
|
||||
)
|
||||
|
||||
# 当前行识别只返回 row_offset=1,首行建议不会混入响应。
|
||||
assert [item['row_offset'] for item in result['subrow_layouts']] == [1]
|
||||
assert result['subrow_layouts'][0]['column_samples'] == [['VENDOR-20']]
|
||||
@@ -1,16 +1,17 @@
|
||||
"""
|
||||
tests/test_shipping_order_field_purposes.py
|
||||
|
||||
用途:验证履约门禁从任务锁定的订单 Schema 快照和 FieldValue 读取业务字段。
|
||||
依赖:订单 Schema service/runtime 模型、reservation_gate。
|
||||
逻辑:当前任务不读取固定任务行投影;缺少用途或 Extraction 时必须明确阻断。
|
||||
用途:验证履约门禁只从冻结订单快照及其冻结策略读取预约单号。
|
||||
依赖:订单 Schema service、冻结快照模型、reservation_gate。
|
||||
逻辑:当前任务不得读取可变 FieldValue 或旧任务行投影;策略缺少能力时必须明确阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask,
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
@@ -30,8 +31,8 @@ def _config(field_id: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _task_with_reservation(value: str) -> ShippingTask:
|
||||
"""发布 Schema 并持久化当前 Extraction 的行级 FieldValue。"""
|
||||
def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingTask:
|
||||
"""创建冻结快照,策略绑定决定履约阶段如何定位预约单号。"""
|
||||
service.initialize_schema({'display_name': '用途测试'}, actor_id=None)
|
||||
field = service.save_field({'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
@@ -61,25 +62,47 @@ def _task_with_reservation(value: str) -> ShippingTask:
|
||||
value_text=value, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
bindings = []
|
||||
if include_reservation_capability:
|
||||
bindings.append({
|
||||
'capability_code': 'fulfillment.reservation_identity',
|
||||
'field_id': field['id'],
|
||||
'scope': 'line',
|
||||
})
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], order_data_version=1,
|
||||
customer_po_number='PURPOSE-PO-001', header_values_json={},
|
||||
rule_versions_json={'fulfillment_policy': {
|
||||
'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1,
|
||||
'definition': {'field_bindings': bindings},
|
||||
}},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0, reservation_id=value,
|
||||
field_values_json={field['id']: value},
|
||||
))
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def test_task_reservation_gate_uses_current_field_value_not_task_line_projection(app):
|
||||
"""门禁以 FieldValue 的合法号码为准,即使旧任务行投影保存错误值也不得阻断。"""
|
||||
def test_task_reservation_gate_uses_frozen_value_not_mutable_projection_or_field_value(app):
|
||||
"""门禁以冻结预约单为准,旧任务投影或后续 FieldValue 变化均不得重解释履约。"""
|
||||
with app.app_context():
|
||||
task = _task_with_reservation('3000000001')
|
||||
task.lines_json = [{'reservation_id': 'INVALID'}]
|
||||
value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one()
|
||||
value.value_text = 'INVALID'
|
||||
value.value_json = 'INVALID'
|
||||
db.session.commit()
|
||||
assert task_reservation_gate_issues(task) == []
|
||||
|
||||
|
||||
def test_task_reservation_gate_blocks_extraction_without_purpose(app):
|
||||
"""历史 Schema 未声明业务用途时不得猜测 field_code,必须阻断履约。"""
|
||||
def test_task_reservation_gate_blocks_snapshot_without_reservation_capability(app):
|
||||
"""冻结策略缺少预约单能力时不得猜测 field_code,必须阻断履约。"""
|
||||
with app.app_context():
|
||||
task = _task_with_reservation('3000000001')
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
definition = dict(extraction.schema_version.definition_json)
|
||||
definition['fields'] = [dict(item, business_purpose='general') for item in definition['fields']]
|
||||
extraction.schema_version.definition_json = definition
|
||||
db.session.commit()
|
||||
task = _task_with_reservation('3000000001', include_reservation_capability=False)
|
||||
issues = task_reservation_gate_issues(task)
|
||||
assert issues[0]['reason'] == 'order_schema_unavailable'
|
||||
@@ -16,6 +16,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
@@ -83,17 +84,19 @@ def _publish_draft(version_id: int) -> dict:
|
||||
return service.publish(version_id, actor_id=None, expected_lock_version=version.lock_version)
|
||||
|
||||
|
||||
def test_order_schema_initializes_fixed_core_and_allows_extension_fields(app):
|
||||
"""关键断言:25 个预置业务核心不可变;扩展字段仍允许按业务治理新增。"""
|
||||
def test_order_schema_initializes_standard_fields_and_allows_extension_fields(app):
|
||||
"""关键断言:57 个预置标准字段身份不可变;扩展字段仍允许按业务治理新增。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
|
||||
core_codes = set(service.FIXED_CORE_FIELD_SPECS)
|
||||
core_codes = set(service.STANDARD_ORDER_FIELD_SPECS)
|
||||
fields = ShippingOrderField.query.order_by(ShippingOrderField.display_sequence).all()
|
||||
assert len(core_codes) == 25
|
||||
assert len(core_codes) == 57
|
||||
assert {field.field_code for field in fields} == core_codes
|
||||
assert service.FIXED_CORE_FIELD_SPECS['bill_to_address'] == ('header', 'string')
|
||||
assert 'bill_to_customer_code' not in core_codes
|
||||
assert service.STANDARD_ORDER_FIELD_SPECS['bill_to_address'] == ('header', 'string')
|
||||
assert service.STANDARD_ORDER_FIELD_SPECS['product_revision'] == ('line', 'string')
|
||||
assert 'po_number' not in core_codes
|
||||
assert 'aws_part_number' not in core_codes
|
||||
|
||||
bill_to_address = next(field for field in fields if field.field_code == 'bill_to_address')
|
||||
with pytest.raises(Exception) as error:
|
||||
@@ -281,6 +284,48 @@ 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():
|
||||
@@ -354,7 +399,7 @@ def test_delete_unused_order_field_removes_draft_config_and_catalog_row(app):
|
||||
|
||||
assert result == {'field_id': field['id'], 'action': 'deleted'}
|
||||
assert db.session.get(ShippingOrderField, field['id']) is None
|
||||
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.FIXED_CORE_FIELD_SPECS)
|
||||
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.STANDARD_ORDER_FIELD_SPECS)
|
||||
assert service.get_state()['versions'][0]['field_count'] == 0
|
||||
|
||||
|
||||
@@ -376,7 +421,7 @@ def test_delete_historical_order_field_archives_and_hides_current_catalog(app):
|
||||
|
||||
assert result == {'field_id': field['id'], 'action': 'archived'}
|
||||
assert db.session.get(ShippingOrderField, field['id']).status == 'retired'
|
||||
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.FIXED_CORE_FIELD_SPECS)
|
||||
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.STANDARD_ORDER_FIELD_SPECS)
|
||||
assert service.get_state()['versions'][0]['id'] == next_draft['id']
|
||||
assert service.get_state()['versions'][0]['field_count'] == 0
|
||||
|
||||
@@ -436,7 +481,18 @@ def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
|
||||
first = service.create_draft({}, actor_id=None)
|
||||
referenced_config = _field_config(referenced['id'])
|
||||
referenced_config.update({'normalizer_key': 'trim', 'comparator_key': 'normalized_text', 'validator_keys': []})
|
||||
_save_draft(first['id'], [referenced_config])
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
policy_configs = []
|
||||
for code in ('reservation_id', 'part_number', 'qty', 'inventory_source_hint'):
|
||||
config = _field_config(fields[code].id, name=code)
|
||||
config.update({
|
||||
'aliases': [], 'extraction_instruction': '',
|
||||
'normalizer_key': 'decimal' if code == 'qty' else 'uppercase_trim',
|
||||
'validator_keys': ['positive_decimal'] if code == 'qty' else ['reservation_id'] if code == 'reservation_id' else [],
|
||||
'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
})
|
||||
policy_configs.append(config)
|
||||
_save_draft(first['id'], policy_configs)
|
||||
_publish_draft(first['id'])
|
||||
db.session.add(ShippingInventoryParsingProfile(
|
||||
profile_code='schema-gate', display_name='Schema Gate', status='published',
|
||||
@@ -453,7 +509,9 @@ def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
_publish_draft(second['id'])
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED'
|
||||
assert service.get_published_contract()['fields'][0]['field_id'] == referenced['id']
|
||||
assert referenced['id'] in {
|
||||
field['field_id'] for field in service.get_published_contract()['fields']
|
||||
}
|
||||
|
||||
|
||||
def test_order_schema_rejects_type_incompatible_rules_and_can_delete_draft(app):
|
||||
@@ -539,7 +597,7 @@ def test_order_field_global_order_persists_without_schema_draft(app):
|
||||
refreshed = service.get_state()
|
||||
|
||||
assert [item['id'] for item in refreshed['fields']][-2:] == [second['id'], first['id']]
|
||||
assert [item['display_sequence'] for item in refreshed['fields']][-2:] == [26, 27]
|
||||
assert [item['display_sequence'] for item in refreshed['fields']][-2:] == [58, 59]
|
||||
assert not any(item['status'] == 'draft' for item in refreshed['versions'])
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
backend/tests/test_shipping_reservation_global_unique_migration.py
|
||||
|
||||
用途:验证 Reservation 改为单列全局唯一后的数据库结构。
|
||||
依赖:Alembic Operations 与 SQLite 最小前置表。
|
||||
逻辑:先执行滚动履约初始迁移,再验证后继迁移替换唯一约束并增加 PO 快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_global_reservation_migration_replaces_composite_unique_constraint(monkeypatch):
|
||||
"""关键断言:Reservation 单列唯一且 PO 快照为必填,回滚可恢复旧约束。"""
|
||||
initial = importlib.import_module('migrations.versions.022a3b4c5d6e_add_shipping_rolling_fulfillment')
|
||||
migration = importlib.import_module('migrations.versions.025b6c7d8e9f_make_shipping_reservation_globally_unique')
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
for table in ('shipping_tasks', 'shipping_order_snapshot_lines', 'shipping_export_artifacts', 'shipping_inventory_files'):
|
||||
sa.Table(table, metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
monkeypatch.setattr(initial, 'op', operations)
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
initial.upgrade()
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
columns = {item['name']: item for item in inspector.get_columns('shipping_reservations')}
|
||||
constraints = inspector.get_unique_constraints('shipping_reservations')
|
||||
assert columns['po_number_normalized']['nullable'] is False
|
||||
assert any(item['name'] == 'uq_shipping_reservations_reservation_id' and item['column_names'] == ['reservation_id'] for item in constraints)
|
||||
migration.downgrade()
|
||||
constraints = sa.inspect(connection).get_unique_constraints('shipping_reservations')
|
||||
assert any(item['name'] == 'uq_shipping_reservations_reservation_part' for item in constraints)
|
||||
@@ -10,10 +10,14 @@ from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshotLine, ShippingReservation
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingOrderExtraction, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingReservation, ShippingTask
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
ensure_task_reservations,
|
||||
record_inventory_verification,
|
||||
)
|
||||
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
|
||||
@@ -79,3 +83,124 @@ def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app):
|
||||
_verification, second_available = current_available_snapshot_line_ids(task)
|
||||
assert second.id > first.id
|
||||
assert second_available == {third_line.id} # C 后续补货,只能进入第二轮。
|
||||
|
||||
|
||||
def test_reservation_rejects_different_purchase_order_and_requires_review_for_same_po_change(app):
|
||||
"""关键断言:Reservation 全局归属首个 PO;同 PO 的料号或数量变化只能走人工修订。"""
|
||||
with app.app_context():
|
||||
first_task, first_user = _build_accepted_order(suffix='101')
|
||||
first_snapshot = freeze_order_snapshot(first_task, actor_id=first_user.id, expected_order_data_version=7)
|
||||
ensure_task_reservations(first_task)
|
||||
db.session.commit()
|
||||
|
||||
second_task = ShippingTask(task_no='SN-SNAPSHOT-102', source_type='test')
|
||||
db.session.add(second_task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=second_task.id, schema_version_id=first_snapshot.schema_version_id,
|
||||
input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
second_snapshot = ShippingOrderSnapshot(
|
||||
task_id=second_task.id, extraction_id=extraction.id, schema_version_id=first_snapshot.schema_version_id,
|
||||
order_data_version=1, rule_versions_json={}, header_values_json={}, customer_po_number='PO-OTHER',
|
||||
)
|
||||
db.session.add(second_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=second_snapshot.id, position=0, reservation_id='0012345678',
|
||||
part_number='000123', qty=Decimal('12.5'), field_values_json={},
|
||||
))
|
||||
second_task.order_snapshot_id = second_snapshot.id
|
||||
db.session.flush()
|
||||
with pytest.raises(ConflictError) as different_po:
|
||||
ensure_task_reservations(second_task)
|
||||
assert different_po.value.code == 'SHIPPING.RESERVATION_PO_CONFLICT'
|
||||
db.session.rollback()
|
||||
|
||||
# The first registration remains immutable after the rejected different-PO attempt.
|
||||
assert first_snapshot.lines[0].reservation_id == '0012345678'
|
||||
|
||||
|
||||
def test_confirmed_task_revision_transfers_unfulfilled_reservation_with_audit(app):
|
||||
"""已确认的直接后继可接替同 PO 的未履约 Reservation,且保留父子审计。"""
|
||||
with app.app_context():
|
||||
first_task, first_user = _build_accepted_order(suffix='201')
|
||||
first_snapshot = freeze_order_snapshot(first_task, actor_id=first_user.id, expected_order_data_version=7)
|
||||
ensure_task_reservations(first_task)
|
||||
db.session.flush()
|
||||
original = ShippingReservation.query.filter_by(reservation_id=first_snapshot.lines[0].reservation_id).one()
|
||||
|
||||
revision_task = ShippingTask(
|
||||
task_no='SN-SNAPSHOT-202', source_type='test', supersedes_task_id=first_task.id,
|
||||
)
|
||||
db.session.add(revision_task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=revision_task.id, schema_version_id=first_snapshot.schema_version_id,
|
||||
input_snapshot_hash='c' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
revision_snapshot = ShippingOrderSnapshot(
|
||||
task_id=revision_task.id, extraction_id=extraction.id,
|
||||
schema_version_id=first_snapshot.schema_version_id, order_data_version=2,
|
||||
rule_versions_json={}, header_values_json={}, customer_po_number=first_snapshot.customer_po_number,
|
||||
)
|
||||
db.session.add(revision_snapshot)
|
||||
db.session.flush()
|
||||
revision_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=revision_snapshot.id, position=0,
|
||||
reservation_id=first_snapshot.lines[0].reservation_id,
|
||||
part_number='000123-REV', qty=Decimal('13.5'), field_values_json={},
|
||||
)
|
||||
db.session.add(revision_line)
|
||||
revision_task.order_snapshot_id = revision_snapshot.id
|
||||
db.session.flush()
|
||||
|
||||
registered = ensure_task_reservations(revision_task)
|
||||
|
||||
assert registered == [original]
|
||||
assert original.task_id == revision_task.id
|
||||
assert original.snapshot_line_id == revision_line.id
|
||||
assert original.part_number == '000123-REV'
|
||||
assert original.required_qty == Decimal('13.5')
|
||||
assert {event.event_type for event in revision_task.events} == {'reservation_revision_confirmed'}
|
||||
assert {event.event_type for event in first_task.events} == {'reservation_revision_superseded'}
|
||||
|
||||
|
||||
def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it(app):
|
||||
"""PO 不属于首次最小履约集;已有 Reservation 时缺 PO 必须阻断歧义修订。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='301')
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
snapshot.customer_po_number = None
|
||||
ensure_task_reservations(task)
|
||||
db.session.flush()
|
||||
|
||||
repeat_task = ShippingTask(task_no='SN-SNAPSHOT-302', source_type='test')
|
||||
db.session.add(repeat_task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=repeat_task.id, schema_version_id=snapshot.schema_version_id,
|
||||
input_snapshot_hash='d' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
repeat_snapshot = ShippingOrderSnapshot(
|
||||
task_id=repeat_task.id, extraction_id=extraction.id, schema_version_id=snapshot.schema_version_id,
|
||||
order_data_version=1, rule_versions_json={}, header_values_json={}, customer_po_number=None,
|
||||
)
|
||||
db.session.add(repeat_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=repeat_snapshot.id, position=0, reservation_id=snapshot.lines[0].reservation_id,
|
||||
part_number=snapshot.lines[0].part_number, qty=snapshot.lines[0].qty, field_values_json={},
|
||||
))
|
||||
repeat_task.order_snapshot_id = repeat_snapshot.id
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ensure_task_reservations(repeat_task)
|
||||
assert exc_info.value.code == 'SHIPPING.RESERVATION_PO_REQUIRED'
|
||||
@@ -0,0 +1,48 @@
|
||||
"""验证货代标准字段目录扩展迁移。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_standard_field_catalog_migration_resets_old_schema_data(monkeypatch):
|
||||
"""关键断言:未投产旧字段身份被清空,客户 PO 与新目录重新建立。"""
|
||||
migration = importlib.import_module('migrations.versions.027d8e9f0a1b_expand_shipping_standard_field_catalog')
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
schemas = sa.Table('shipping_order_schemas', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('schema_code', sa.String(64)))
|
||||
fields = sa.Table(
|
||||
'shipping_order_fields', metadata, sa.Column('id', sa.String(36), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer()), sa.Column('field_code', sa.String(64)),
|
||||
sa.Column('scope', sa.String(16)), sa.Column('value_type', sa.String(16)),
|
||||
sa.Column('field_category', sa.String(32)), sa.Column('collection_mode', sa.String(32)),
|
||||
sa.Column('display_sequence', sa.Integer()), sa.Column('status', sa.String(16)),
|
||||
sa.Column('published_once', sa.Boolean()), sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()),
|
||||
)
|
||||
snapshots = sa.Table('shipping_order_snapshots', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('po_number', sa.String(255)))
|
||||
lines = sa.Table('shipping_order_snapshot_lines', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('aws_part_number', sa.String(255)))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(schemas.insert(), {'id': 1, 'schema_code': 'SHIPPING_ORDER'})
|
||||
connection.execute(fields.insert(), [
|
||||
{'id': 'po-id', 'schema_id': 1, 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
|
||||
'field_category': 'order_header', 'collection_mode': 'llm_extraction', 'display_sequence': 1,
|
||||
'status': 'active', 'published_once': False},
|
||||
{'id': 'aws-id', 'schema_id': 1, 'field_code': 'aws_part_number', 'scope': 'line', 'value_type': 'string',
|
||||
'field_category': 'order_line', 'collection_mode': 'llm_extraction', 'display_sequence': 2,
|
||||
'status': 'active', 'published_once': False},
|
||||
])
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
migration.upgrade()
|
||||
field_rows = connection.execute(sa.text('SELECT id, field_code, status FROM shipping_order_fields')).mappings().all()
|
||||
by_code = {row['field_code']: row for row in field_rows}
|
||||
assert by_code['customer_po_number']['id'] != 'po-id'
|
||||
assert 'aws_part_number' not in by_code
|
||||
assert len([row for row in field_rows if row['status'] == 'active']) == 57
|
||||
assert 'customer_po_number' in {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_snapshots')}
|
||||
assert 'aws_part_number' not in {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_snapshot_lines')}
|
||||
@@ -165,6 +165,7 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app):
|
||||
)
|
||||
reservation = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=1, reservation_id='RES-TIMELINE-001', part_number='PN-TIMELINE',
|
||||
po_number_normalized='PO-TIMELINE-001',
|
||||
required_qty=2, status='artifact_reserved', current_artifact_id=None,
|
||||
)
|
||||
db.session.add_all([artifact, reservation])
|
||||
|
||||
@@ -42,6 +42,7 @@ def _ready_artifact() -> tuple[ShippingTask, ShippingExportArtifact, ShippingRes
|
||||
db.session.add(artifact); db.session.flush()
|
||||
reservation = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=1, reservation_id='RES-UPLOAD-1', part_number='PN-1',
|
||||
po_number_normalized='PO-UPLOAD-1',
|
||||
required_qty=Decimal('1'), status='artifact_reserved', current_artifact_id=artifact.id,
|
||||
)
|
||||
db.session.add(reservation); db.session.flush()
|
||||
|
||||
Reference in new issue
Block a user