refactor(shipping-line): 统一订单与通知明细项次并移除旧键

This commit is contained in:
hugo committed 2026-09-04 20:46:37 +08:00
1 parent 938f3dd0e8
commit b5d894a923
11 files changed
+331 -302

No files matched your search

+11 -3
View File
@@ -28,19 +28,27 @@ class ShippingNoticeLine(Base):
__tablename__ = 'shipping_notice_lines' __tablename__ = 'shipping_notice_lines'
__table_args__ = ( __table_args__ = (
UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'), UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'),
UniqueConstraint('notice_id', 'line_no', name='uq_shipping_notice_lines_line_no'),
Index('ix_shipping_notice_lines_notice_id', 'notice_id'), Index('ix_shipping_notice_lines_notice_id', 'notice_id'),
Index('ix_shipping_notice_lines_snapshot_line_id', 'snapshot_line_id'), Index('ix_shipping_notice_lines_snapshot_line_id', 'snapshot_line_id'),
) )
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False) notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
snapshot_line_id: Mapped[Optional[int]] = mapped_column( snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='SET NULL'), nullable=True, ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), nullable=False,
) )
position: Mapped[int] = mapped_column(Integer, nullable=False) position: Mapped[int] = mapped_column(Integer, nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) # 发货通知项次:每个 Notice 从 1 开始连续编号,禁止使用导出序号或客户 PO 行号。
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True) required_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True,
)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+3 -3
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_task_line.py backend/app/models/shipping_task_line.py
用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。 用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。
依赖:models.base.Base、shipping_notices、users。 依赖:models.base.Base、shipping_order_tasks、users。
逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。 逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。
""" """
@@ -60,7 +60,7 @@ class ShippingTaskFieldConflict(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column( task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'), ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False, nullable=False,
index=True, index=True,
) )
@@ -91,4 +91,4 @@ class ShippingTaskFieldConflict(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='field_conflicts') task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', back_populates='field_conflicts')
@@ -36,7 +36,7 @@ ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'consta
ALLOWED_ROW_MODES = {'header', 'line'} ALLOWED_ROW_MODES = {'header', 'line'}
ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'} ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'}
ALLOWED_SYSTEM_FACTS = { ALLOWED_SYSTEM_FACTS = {
'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'export_sequence', 'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'notice_line_no',
} }
+97 -58
View File
@@ -4,7 +4,7 @@ services/shipping_notice/export.py
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。 用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。 依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板; 逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费; 在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。 订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
""" """
@@ -29,16 +29,55 @@ from app.models import (
ShippingExcelTemplate, ShippingExcelTemplate,
ShippingExportArtifact, ShippingExportArtifact,
ShippingNoticeLine, ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryField, ShippingInventoryField,
ShippingInventorySource, ShippingInventorySource,
ShippingOrderSnapshot, ShippingOrderSnapshot,
ShippingOrderField, ShippingOrderField,
ShippingNotice, ShippingNotice,
ShippingOrderTask,
ShippingCustomer,
) )
from app.path_utils import resolve_backend_relative_path from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage from app.services.file_assets.storage import file_asset_storage
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
codes = [
str(row[0]).strip().upper()
for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
).distinct().all()
if row[0]
]
return codes[0] if len(codes) == 1 else None
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
ids = [
int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
).distinct().all()
]
return ids[0] if len(ids) == 1 else None
def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None: def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None:
""" """
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。 确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
@@ -73,16 +112,7 @@ def _storage_root() -> Path:
def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice: def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
"""后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。""" """返回当前 Notice;订单事实统一由其关联 OT/Snapshot 提供。"""
if notice.order_snapshot_id:
return notice
if notice.order_task_id:
source = ShippingNotice.query.filter(
ShippingNotice.order_task_id == int(notice.order_task_id),
ShippingNotice.order_snapshot_id.isnot(None),
).order_by(ShippingNotice.id.asc()).first()
if source is not None:
return source
return notice return notice
@@ -90,7 +120,9 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。""" """从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
assert_task_not_supersession_blocked(task) assert_task_not_supersession_blocked(task)
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None: if snapshot is None:
raise ValueError('任务没有可用于库存匹配的冻结订单快照') raise ValueError('任务没有可用于库存匹配的冻结订单快照')
fields = (snapshot.schema_version.definition_json or {}).get('fields') or [] fields = (snapshot.schema_version.definition_json or {}).get('fields') or []
@@ -122,9 +154,10 @@ def _system_fact(
task: ShippingNotice, task: ShippingNotice,
key: str, key: str,
*, *,
export_sequence: int | None = None,
excel_business_no: str | None = None, excel_business_no: str | None = None,
notice_no: str | None = None, notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None, export_date: date | None = None,
) -> Any: ) -> Any:
""" """
@@ -133,18 +166,16 @@ def _system_fact(
Args: Args:
task: 发货任务。 task: 发货任务。
key: 系统事实键;仅允许白名单内键。 key: 系统事实键;仅允许白名单内键。
export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。
Returns: Returns:
对应系统事实值;未知键返回 None。 对应系统事实值;未知键返回 None。
""" """
values = { values = {
'task_no': notice_no or task.task_no, 'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no, 'business_no': notice_no or excel_business_no or task.business_no,
'warehouse_id': task.inventory_warehouse_id, 'warehouse_id': notice_line_warehouse_id,
'inventory_source_code': task.inventory_source_code, 'inventory_source_code': _notice_source_code(task),
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(), 'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_sequence': export_sequence, 'notice_line_no': notice_line_no,
} }
return values.get(key) return values.get(key)
@@ -191,9 +222,11 @@ def _format_value(value: Any, formatter: str) -> Any:
def _mapping_value( def _mapping_value(
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any], mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None, export_sequence: int | None = None, header_values: dict[str, Any] | None = None,
excel_business_no: str | None = None, excel_business_no: str | None = None,
notice_no: str | None = None, notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None, export_date: date | None = None,
field_id_by_code: dict[str, str] | None = None, field_id_by_code: dict[str, str] | None = None,
) -> Any: ) -> Any:
@@ -201,9 +234,7 @@ def _mapping_value(
按映射来源类型读取值;未知来源已在模板发布时被拒绝。 按映射来源类型读取值;未知来源已在模板发布时被拒绝。
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实; 核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。 通知项次只读取 ``ShippingNoticeLine.line_no``;订单字段映射不再使用导出序号兜底。
项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 →
导出行序号),与 UI 展示同一口径,禁止此处另造回退链。
Args: Args:
mapping: 已发布模板映射项。 mapping: 已发布模板映射项。
@@ -211,7 +242,6 @@ def _mapping_value(
order_values: 当前行或表头订单字段值(field_id 为键)。 order_values: 当前行或表头订单字段值(field_id 为键)。
inventory_values: 当前行库存字段值。 inventory_values: 当前行库存字段值。
header_values: 明细行模式下可回退的表头字段。 header_values: 明细行模式下可回退的表头字段。
export_sequence: 本次导出行序号(1..N)。
field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。 field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。
Returns: Returns:
@@ -224,13 +254,7 @@ def _mapping_value(
field = db.session.get(ShippingOrderField, key) if key else None field = db.session.get(ShippingOrderField, key) if key else None
field_code = str(field.field_code or '') if field else '' field_code = str(field.field_code or '') if field else ''
if value in (None, '') and field_code == 'line_no': if value in (None, '') and field_code == 'line_no':
from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no value = notice_line_no
value = resolve_order_line_no(
field_values=order_values,
field_id_by_code=field_id_by_code,
fallback_sequence=export_sequence,
)['value']
if value is None and mapping.get('row_mode') == 'line' and header_values is not None: if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key) value = header_values.get(key)
elif kind == 'inventory_field': elif kind == 'inventory_field':
@@ -238,13 +262,12 @@ def _mapping_value(
elif kind == 'system_fact': elif kind == 'system_fact':
value = _system_fact( value = _system_fact(
task, key, task, key,
export_sequence=export_sequence if key == 'export_sequence' else None,
excel_business_no=excel_business_no, excel_business_no=excel_business_no,
notice_no=notice_no, notice_no=notice_no,
notice_line_no=notice_line_no,
notice_line_warehouse_id=notice_line_warehouse_id,
export_date=export_date, export_date=export_date,
) )
if key == 'export_sequence' and value is None:
value = order_values.get('__export_sequence')
else: else:
value = key value = key
# 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串; # 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串;
@@ -447,13 +470,20 @@ def _filename(
if not pattern: if not pattern:
raise ValueError('发货 Excel 文件名规则未配置') raise ValueError('发货 Excel 文件名规则未配置')
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S') now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
customer_short_code = ''
if isinstance(owner, ShippingOrderTask):
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
facts = customer_resolution_facts(owner)
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
customer_short_code = str(getattr(customer, 'short_code', None) or '')
values = { values = {
'task_no': notice_no or task.task_no, 'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no or task.task_no, 'business_no': notice_no or excel_business_no or task.business_no or task.task_no,
'source_code': task.inventory_source_code or '', 'source_code': _notice_source_code(task) or '',
'ts': now, 'ts': now,
'date': now[:8], 'date': now[:8],
'customer_short_code': task.customer_short_code_snapshot or '', 'customer_short_code': customer_short_code,
'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '', 'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '',
'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '', 'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '',
} }
@@ -474,7 +504,7 @@ def _input_checksum(
'task_id': task.id, 'source_id': source.id, 'template_id': template.id, 'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum, 'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id, 'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id, 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task),
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
'notice_id': notice_id, 'notice_id': notice_id,
} }
@@ -499,24 +529,22 @@ def generate_shipment_excel(
from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task): if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel') raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task) assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task) assert_notice_has_no_export_artifact(task)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。 # [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(task.inventory_source_code or '').strip().upper() source_code = str(_notice_source_code(task) or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None: if source is None:
# [T6 多候选兼容] 单源 resolved 走上方 inventory_source_code;多候选 candidates_frozen 时可能 source_code==None, source = None
# 在严格全行 matched 前提下可退回到第一条 line_match 的 inventory_source_code(保证不绕过断言)。
first_match = db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
).limit(1).first()
source_code_candidate = str(first_match[0]).strip().upper() if first_match and first_match[0] else ''
source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None
if source is None: if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel') raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
template = source.excel_template template = source.excel_template
@@ -528,13 +556,10 @@ def generate_shipment_excel(
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings: if not mappings:
raise ValueError('发货 Excel 模板没有已发布的字段映射') raise ValueError('发货 Excel 模板没有已发布的字段映射')
# Fixed Sources receive task Warehouse ID from configuration; dynamic Sources
# resolve it only after Reservation ID + Part Number matches. This requirement
# applies only when the published template actually consumes that system fact.
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
source_notice = _source_notice_for_order_facts(task) source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None: if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照') raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task) header_values, all_line_values = order_field_id_values(task)
@@ -590,7 +615,7 @@ def generate_shipment_excel(
) )
except ConflictError: except ConflictError:
raise raise
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。 # [STEP 2] 先筛出最终可导出行;通知项次来自已持久化的 ShippingNoticeLine.line_no。
line_values = [] line_values = []
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)): for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
if line.id not in available_line_ids: if line.id not in available_line_ids:
@@ -598,8 +623,6 @@ def generate_shipment_excel(
row = dict(values) row = dict(values)
row['__order_line_index'] = source_index row['__order_line_index'] = source_index
line_values.append(row) line_values.append(row)
for index, row in enumerate(line_values, start=1):
row['__export_sequence'] = index
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。 # [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
@@ -661,21 +684,37 @@ def generate_shipment_excel(
start_row = int(mapping['start_row']) start_row = int(mapping['start_row'])
column = int(mapping['target_column']) column = int(mapping['target_column'])
if mapping['row_mode'] == 'header': if mapping['row_mode'] == 'header':
if _template_requires_system_warehouse_id([mapping]):
raise ValueError('Warehouse ID 仅可作为发货通知行字段导出,模板不得将其映射为表头')
ws.cell(start_row, column).value = _mapping_value( ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory, mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no, excel_business_no=excel_business_no,
export_date=export_date, export_date=export_date,
notice_line_no=None,
notice_line_warehouse_id=None,
field_id_by_code=field_id_by_code, field_id_by_code=field_id_by_code,
) )
continue continue
row_count = max(len(line_values), 1) row_count = max(len(line_values), 1)
notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
for index in range(row_count): for index in range(row_count):
order_line = line_values[index] if index < len(line_values) else {} order_line = line_values[index] if index < len(line_values) else {}
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {} inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
ws.cell(start_row + index, column).value = _mapping_value( ws.cell(start_row + index, column).value = _mapping_value(
mapping, task=task, order_values=order_line, inventory_values=inventory_line, mapping, task=task, order_values=order_line, inventory_values=inventory_line,
header_values=header_values, header_values=header_values,
export_sequence=int(order_line.get('__export_sequence') or (index + 1)), notice_line_no=(
int(notice_lines[index].line_no)
if index < len(notice_lines) and notice_lines[index].line_no is not None
else None
),
notice_line_warehouse_id=(
notice_lines[index].inventory_warehouse_id
if index < len(notice_lines)
else None
),
excel_business_no=excel_business_no, excel_business_no=excel_business_no,
export_date=export_date, export_date=export_date,
field_id_by_code=field_id_by_code, field_id_by_code=field_id_by_code,
@@ -691,7 +730,7 @@ def generate_shipment_excel(
artifact_no=artifact_no, task_id=task.id, artifact_no=artifact_no, task_id=task.id,
template_id=template.id, template_id=template.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id, inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task),
input_checksum=_input_checksum( input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines, task, source, template, snapshot, header_values, line_values, inventory_lines,
notice_id=int(task.id), notice_id=int(task.id),
@@ -9,36 +9,26 @@ services/shipping_notice/notice_line_constants.py
from __future__ import annotations from __future__ import annotations
NOTICE_LINE_FIELDS = ( NOTICE_LINE_FIELDS = (
"line_no",
"part_number", "part_number",
"qty", "qty",
"unit_price", "unit_price",
"amount", "line_amount_with_tax",
"currency",
"reservation_id", "reservation_id",
"required_date", "required_date",
"customer_part_number", "customer_part_number",
"aws_part_number",
"uom", "uom",
"line_remark", "line_remark",
"po_number",
"allocation_id",
"inventory_source_hint", "inventory_source_hint",
) )
NOTICE_FIELD_LABELS = { NOTICE_FIELD_LABELS = {
"line_no": "项次 / Item / Line No",
"part_number": "内部料号 / Part Number", "part_number": "内部料号 / Part Number",
"qty": "需求数量", "qty": "需求数量",
"unit_price": "单价", "unit_price": "单价",
"amount": "金额", "line_amount_with_tax": "含税金额 / Amount",
"currency": "币种",
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)", "reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
"required_date": "要求交期 / 交货日期", "required_date": "要求交期 / 交货日期",
"customer_part_number": "客户料号 / Customer Part Number", "customer_part_number": "客户料号 / Customer Part Number",
"aws_part_number": "AWS 料号 / AWS Part Number",
"po_number": "PO Number",
"allocation_id": "Allocation ID",
"inventory_source_hint": "库存来源提示 / Hub Code", "inventory_source_hint": "库存来源提示 / Hub Code",
"line_remark": "行备注", "line_remark": "行备注",
} }
@@ -9,6 +9,7 @@ backend/app/services/shipping_notice/notice_line_service.py
from __future__ import annotations from __future__ import annotations
from datetime import datetime from datetime import datetime
from typing import Any
from app import db from app import db
from app.models import ShippingNoticeLine, ShippingOrderSnapshot from app.models import ShippingNoticeLine, ShippingOrderSnapshot
@@ -19,6 +20,7 @@ def replace_notice_lines_from_snapshot(
notice_id: int, notice_id: int,
snapshot: ShippingOrderSnapshot, snapshot: ShippingOrderSnapshot,
snapshot_line_ids: set[int] | None = None, snapshot_line_ids: set[int] | None = None,
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
) -> int: ) -> int:
""" """
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。 用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
@@ -35,18 +37,26 @@ def replace_notice_lines_from_snapshot(
now = datetime.utcnow() now = datetime.utcnow()
rows: list[ShippingNoticeLine] = [] rows: list[ShippingNoticeLine] = []
selected_ids = {int(item) for item in (snapshot_line_ids or set())} selected_ids = {int(item) for item in (snapshot_line_ids or set())}
inventory_facts_by_snapshot_line_id = inventory_facts_by_snapshot_line_id or {}
notice_position = 0
for line in list(snapshot.lines or []): for line in list(snapshot.lines or []):
if selected_ids and int(line.id) not in selected_ids: if selected_ids and int(line.id) not in selected_ids:
continue continue
notice_position += 1
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
rows.append( rows.append(
ShippingNoticeLine( ShippingNoticeLine(
notice_id=int(notice_id), notice_id=int(notice_id),
snapshot_line_id=int(line.id) if getattr(line, 'id', None) else None, snapshot_line_id=int(line.id) if getattr(line, 'id', None) else None,
position=int(line.position), position=notice_position - 1,
line_key=str(getattr(line, 'line_no', None) or '').strip() or None, # 发货通知项次按当前通知单重新从 1 编排。
line_no=notice_position,
part_number=getattr(line, 'part_number', None), part_number=getattr(line, 'part_number', None),
reservation_id=getattr(line, 'reservation_id', None), reservation_id=getattr(line, 'reservation_id', None),
required_qty=getattr(line, 'qty', None), required_qty=getattr(line, 'qty', None),
inventory_source_code=inventory_facts.get('inventory_source_code'),
inventory_file_id=inventory_facts.get('inventory_file_id'),
inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
field_values_json=dict(getattr(line, 'field_values_json', None) or {}), field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
created_at=now, created_at=now,
) )
@@ -86,14 +86,6 @@ def parse_notice_row(
if idx_qty is not None: if idx_qty is not None:
skip_indices.add(idx_qty) skip_indices.add(idx_qty)
idx_line_no = columns.get("line_no")
if idx_line_no is not None:
config = contract.fields_by_code.get('line_no')
line_no = _normalized_cell(row, idx_line_no, config)
skip_indices.add(idx_line_no)
if line_no is not None:
parsed["line_no"] = str(line_no)
idx_res = columns.get("reservation_id") idx_res = columns.get("reservation_id")
reservation_id = "" reservation_id = ""
if idx_res is not None: if idx_res is not None:
@@ -119,18 +111,22 @@ def parse_notice_row(
if value is not None: if value is not None:
parsed["unit_price"] = float(value) parsed["unit_price"] = float(value)
idx_amount = columns.get("amount") # 冻结契约的表头字段码已从旧版 `amount` 迁移为 `line_amount_with_tax`(见
# table_contract.TABLE_FIELD_CODES / order_freeze_service.LINE_FIELD_PROJECTIONS)。
# 表格列以 `line_amount_with_tax` 识别,但订单行输出沿用通知层的 `amount` 表示键,
# 供 normalize_notice_line / validate_notice_lines 等下游统一消费。
idx_amount = columns.get("line_amount_with_tax")
amount_cell = None amount_cell = None
if idx_amount is not None: if idx_amount is not None:
amount_cell = cell(row, idx_amount) amount_cell = cell(row, idx_amount)
config = contract.fields_by_code.get('amount') config = contract.fields_by_code.get('line_amount_with_tax')
value = _normalized_cell(row, idx_amount, config, numeric=True) value = _normalized_cell(row, idx_amount, config, numeric=True)
if value is not None: if value is not None:
parsed["amount"] = float(value) parsed["amount"] = float(value)
for field in ( for field in (
'currency', 'uom', 'required_date', 'po_number', 'inventory_source_hint', 'currency', 'uom', 'required_date', 'po_number', 'inventory_source_hint',
'customer_part_number', 'aws_part_number', 'line_remark', 'customer_part_number', 'line_remark',
): ):
idx = columns.get(field) idx = columns.get(field)
if idx is None: if idx is None:
@@ -145,7 +141,7 @@ def parse_notice_row(
if currency: if currency:
parsed['currency'] = currency parsed['currency'] = currency
amount_config = contract.fields_by_code.get('amount') amount_config = contract.fields_by_code.get('line_amount_with_tax')
if amount_config is not None and "amount" not in parsed and "unit_price" in parsed: if amount_config is not None and "amount" not in parsed and "unit_price" in parsed:
computed = round(parsed["unit_price"] * float(qty), 4) computed = round(parsed["unit_price"] * float(qty), 4)
normalized = _normalized_cell([computed], 0, amount_config, numeric=True) normalized = _normalized_cell([computed], 0, amount_config, numeric=True)
@@ -170,7 +166,7 @@ def score_notice_header_row(cells: list[Any], contract: TableHeaderContract | No
score += 30 score += 30
if "reservation_id" in mapped: if "reservation_id" in mapped:
score += 10 score += 10
if "unit_price" in mapped or "amount" in mapped: if "unit_price" in mapped or "line_amount_with_tax" in mapped or "amount" in mapped:
score += 5 score += 5
return score return score
@@ -20,7 +20,6 @@ from app.services.shipping_notice.notice_line_values import (
map_notice_header, map_notice_header,
norm_header, norm_header,
normalize_currency, normalize_currency,
normalize_line_no,
normalize_required_date, normalize_required_date,
parse_number, parse_number,
) )
@@ -201,10 +200,6 @@ def normalize_notice_line(
if raw_uom and field_enabled("uom"): if raw_uom and field_enabled("uom"):
line["uom"] = raw_uom line["uom"] = raw_uom
line_no = normalize_line_no(raw.get("line_no"))
if line_no and field_enabled("line_no"):
line["line_no"] = line_no
reservation_id = extract_reservation_id(raw.get("reservation_id")) reservation_id = extract_reservation_id(raw.get("reservation_id"))
if reservation_id and field_enabled("reservation_id"): if reservation_id and field_enabled("reservation_id"):
line["reservation_id"] = reservation_id line["reservation_id"] = reservation_id
@@ -217,9 +212,10 @@ def normalize_notice_line(
line["unit_price"] = unit_price line["unit_price"] = unit_price
amount = parse_number(raw.get("amount")) amount = parse_number(raw.get("amount"))
if amount is not None and field_enabled("amount"): # Schema 使用 canonical line_amount_with_tax;内部通知行仍保留 amount 键供下游消费。
if amount is not None and field_enabled("line_amount_with_tax"):
line["amount"] = amount line["amount"] = amount
elif unit_price is not None and field_enabled("amount"): elif unit_price is not None and field_enabled("line_amount_with_tax"):
line["amount"] = round(unit_price * qty, 4) line["amount"] = round(unit_price * qty, 4)
currency = normalize_currency(raw.get("currency")) currency = normalize_currency(raw.get("currency"))
@@ -1,12 +1,9 @@
""" """
backend/app/services/shipping_notice/order_line_no_resolver.py backend/app/services/shipping_notice/order_line_no_resolver.py
用途:内部项次(line_no)展示/导出值的唯一解析器——冻结字段真实值 → 客户 PO 行号 → 用途:读取已经持久化的订单项次(line_no)。
行展示序号,并输出来源标注(field / customer_po_line_no / sequence / None)。
依赖:app.models(ShippingNotice/Snapshot/Extraction)、order_schema.field_rules(格式门禁)。 依赖:app.models(ShippingNotice/Snapshot/Extraction)、order_schema.field_rules(格式门禁)。
逻辑:Excel 导出(export._mapping_value)与 UI 投影(query_service / ui_state)统一调用 逻辑:line_no 由冻结/正式通知写路径按单据内顺序生成;本模块不执行派生、回退或来源推断。
本模块,禁止各调用方自行兜底,避免同一数据出现两套口径;缺失事实必须显式标注来源,
不得把内部行号伪装成业务项次。
""" """
from __future__ import annotations from __future__ import annotations
@@ -15,11 +12,6 @@ from typing import Any
from app import db from app import db
from app.models import ShippingNotice, ShippingOrderExtraction, ShippingOrderSnapshot from app.models import ShippingNotice, ShippingOrderExtraction, ShippingOrderSnapshot
from app.services.shipping_notice.order_schema.field_rules import is_valid_line_no_value
LINE_NO_SOURCE_FIELD = 'field'
LINE_NO_SOURCE_CUSTOMER_PO_LINE = 'customer_po_line_no'
LINE_NO_SOURCE_SEQUENCE = 'sequence'
def field_id_by_code_from_definition( def field_id_by_code_from_definition(
@@ -67,87 +59,67 @@ def notice_line_field_id_map(task: ShippingNotice) -> dict[str, str]:
return {} return {}
def _read_field( def _read_persisted_line_no(field_values: dict[str, Any] | None) -> str | None:
"""读取冻结行中按 ``line_no`` 规范持久化的项次值。
核心逻辑:项次不是 Schema 字段值,也不是外部单据行号;写路径生成后直接
持久化到行事实中,读取层不得按 field_code、客户行号或展示位置猜测。
"""
values = field_values if isinstance(field_values, dict) else {}
raw = values.get('line_no')
if raw in (None, ''):
return None
text = str(raw).strip()
return text or None
def read_field_by_id(
field_values: dict[str, Any] | None, field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None, field_id_by_code: dict[str, str] | None,
code: str, code: str,
) -> str | None: ) -> str | None:
"""按 field_id 优先、field_code 兼容的稳定顺序读取行字段值。 """按 Schema field_id 读取普通业务字段;不参与系统项次解析。"""
核心逻辑:冻结 JSON 以 field_id(UUID)为键;历史/测试数据可能仍按 field_code 存储。
任一键命中且非空即返回规范化字符串,避免把 0/False 等合法值误判为空。
"""
values = field_values if isinstance(field_values, dict) else {} values = field_values if isinstance(field_values, dict) else {}
field_id = str(field_id_by_code.get(code) or '') if field_id_by_code else '' field_id = str((field_id_by_code or {}).get(code) or '').strip()
if field_id and field_id in values: raw = values.get(field_id) if field_id else None
raw = values[field_id] if raw in (None, ''):
if raw not in (None, ''): return None
text = str(raw).strip() text = str(raw).strip()
return text or None return text or None
if code in values:
raw = values[code]
if raw not in (None, ''):
text = str(raw).strip()
return text or None
return None
def resolve_order_line_no( def resolve_order_line_no(
*, *,
field_values: dict[str, Any] | None, field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None, field_id_by_code: dict[str, str] | None = None,
fallback_sequence: int | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""解析一行内部项次展示值(唯一权威入口)。 """解析一行内部项次展示值(唯一权威入口)。
【AI 触发时机】需要展示或导出某订单行的项次时统一调用;禁止在展示层自行回退。 【AI 触发时机】需要展示或导出某订单行的项次时统一调用;禁止在展示层自行回退。
核心逻辑: 核心逻辑:只读取 field_values 中已经持久化的 line_no;customer_po_line_no 和
[STEP 1] line_no 字段真实值(须通过 is_valid_line_no_value 格式门禁)→ source=field; 展示序号都不能作为内部项次的替代来源。
[STEP 2] customer_po_line_no 字段真实值(同格式门禁)→ source=customer_po_line_no;
[STEP 3] 调用方提供的 1..N 行序号 → source=sequence(明确标注为展示序号);
[STEP 4] 全部缺失 → {'value': None, 'source': None}。
与派生规则同门禁:非法项次格式(非 1–6 位数字)一律跳过,不得以序号冒充业务值。
Args: Args:
field_values: 行字段值 JSON(field_id 或 field_code 键均可)。 field_values: 行字段值 JSON(field_id 或 field_code 键均可)。
field_id_by_code: field_code → field_id 映射;为空时仅按 field_code 键兼容读取。 field_id_by_code: 已废弃参数,仅为调用方签名稳定保留;不会参与读取。
fallback_sequence: 1 基展示序号;None 表示无序号兜底。
Returns: Returns:
{'value': 规范化字符串或 None, 'source': 'field'|'customer_po_line_no'|'sequence'|None}。 {'value': 规范化字符串或 None, 'source': 'persisted'|None}。
""" """
line_no = _read_field(field_values, field_id_by_code, 'line_no') del field_id_by_code
if line_no is not None and is_valid_line_no_value(line_no): line_no = _read_persisted_line_no(field_values)
return {'value': line_no, 'source': LINE_NO_SOURCE_FIELD} return {'value': line_no, 'source': 'persisted' if line_no is not None else None}
customer_line_no = _read_field(field_values, field_id_by_code, 'customer_po_line_no')
if customer_line_no is not None and is_valid_line_no_value(customer_line_no):
return {'value': customer_line_no, 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
if fallback_sequence is not None and int(fallback_sequence) >= 1:
return {'value': str(int(fallback_sequence)), 'source': LINE_NO_SOURCE_SEQUENCE}
return {'value': None, 'source': None}
def resolve_order_line_no_projection( def resolve_order_line_no_projection(
*, *,
field_values: dict[str, Any] | None, field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None, field_id_by_code: dict[str, str] | None = None,
fallback_sequence: int | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""与 resolve_order_line_no 同源的 UI/导出投影形(line_no / line_no_source 键)。 """读取不可变订单项次投影。"""
核心逻辑:仅供展示层消费;把语义结果映射为前端契约键,避免各处手写
{'line_no': result['value'], 'line_no_source': result['source']} 产生分叉。
Returns:
{'line_no': str|None, 'line_no_source': 'field'|'customer_po_line_no'|'sequence'|None}。
"""
resolved = resolve_order_line_no( resolved = resolve_order_line_no(
field_values=field_values, field_values=field_values,
field_id_by_code=field_id_by_code, field_id_by_code=field_id_by_code,
fallback_sequence=fallback_sequence,
) )
return {'line_no': resolved['value'], 'line_no_source': resolved['source']} return {'line_no': resolved['value']}
+137 -54
View File
@@ -20,7 +20,8 @@ from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction, ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ShippingOrderTask,
ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink,
) )
from app.services.shipping_notice import excel_template from app.services.shipping_notice import excel_template
from app.services.shipping_notice.export import ( from app.services.shipping_notice.export import (
@@ -32,6 +33,7 @@ from app.services.shipping_notice.export import (
generate_shipment_excel, generate_shipment_excel,
) )
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
from app.services.shipping_notice.inventory_file_store import ( from app.services.shipping_notice.inventory_file_store import (
active_inventory_lines_for_task, active_inventory_lines_for_task,
replace_task_inventory_link, replace_task_inventory_link,
@@ -77,10 +79,11 @@ def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fac
def _freeze_export_snapshot( def _freeze_export_snapshot(
task: ShippingNotice, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion, task: ShippingOrderTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None, *, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
) -> None: customer_id: int | None = None, inventory_file_id: int | None = None,
"""为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。""" ) -> ShippingOrderSnapshot:
"""为导出测试在 OT 上建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
field_codes = { field_codes = {
str(item.get('field_id')): str(item.get('field_code') or '') str(item.get('field_id')): str(item.get('field_code') or '')
for item in (version.definition_json or {}).get('fields') or [] for item in (version.definition_json or {}).get('fields') or []
@@ -91,6 +94,7 @@ def _freeze_export_snapshot(
) )
snapshot = ShippingOrderSnapshot( snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id, task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
customer_id=customer_id,
order_data_version=1, rule_versions_json={}, order_data_version=1, rule_versions_json={},
header_values_json={str(key): value for key, value in (header or {}).items()}, header_values_json={str(key): value for key, value in (header or {}).items()},
customer_po_number=po_number, customer_po_number=po_number,
@@ -99,20 +103,59 @@ def _freeze_export_snapshot(
db.session.flush() db.session.flush()
for position, field_id, part_number, qty, reservation_id in lines or []: for position, field_id, part_number, qty, reservation_id in lines or []:
db.session.add(ShippingOrderSnapshotLine( db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=position, part_number=part_number, snapshot_id=snapshot.id, position=position, line_no=position,
reservation_id=reservation_id, qty=Decimal(str(qty)), part_number=part_number, reservation_id=reservation_id, qty=Decimal(str(qty)),
field_values_json={str(field_id): part_number}, field_values_json={str(field_id): part_number},
)) ))
db.session.flush() db.session.flush()
task.order_snapshot_id = snapshot.id task.order_snapshot_id = snapshot.id
record_inventory_verification( record_inventory_verification(
task, inventory_snapshot_id=task.inventory_snapshot_id, source_config_version='test-v1', task, inventory_snapshot_id=inventory_file_id, source_config_version='test-v1',
line_results=[{ line_results=[{
'reservation_id': line.reservation_id, 'part_number': line.part_number, 'reservation_id': line.reservation_id, 'part_number': line.part_number,
'required_qty': line.qty, 'available_qty': line.qty, 'line_status': 'ok', 'required_qty': line.qty, 'available_qty': line.qty, 'line_status': 'ok',
} for line in snapshot.lines], } for line in snapshot.lines],
) )
db.session.flush() db.session.flush()
return snapshot
def _materialize_export_notice(
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: ShippingInventoryFile,
source_code: str, notice_no: str,
) -> ShippingNotice:
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
导出链路只接受已物化的正式 Notice;OT 承载订单/库存事实,Notice 通过
order_task_id 指向 OT。行级匹配事实按 OT id 落库,库存 Link 绑定 Notice 本身。
"""
notice = ShippingNotice(
task_no=notice_no, source_type='manual', order_task_id=ot.id, user_id=ot.user_id,
)
db.session.add(notice)
db.session.flush()
replace_notice_lines_from_snapshot(
notice_id=notice.id, snapshot=snapshot,
inventory_facts_by_snapshot_line_id={
int(line.id): {
'inventory_source_code': source_code,
'inventory_file_id': int(inventory_file.id),
'inventory_warehouse_id': inventory_file.warehouse_id,
}
for line in snapshot.lines
},
)
for line in snapshot.lines:
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
match_result='matched', inventory_status='ready',
inventory_snapshot_id=inventory_file.id, inventory_source_code=source_code,
is_current=True, detail_json={},
))
db.session.flush()
replace_task_inventory_link(notice, inventory_file, role='owner')
db.session.flush()
return notice
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@@ -153,23 +196,21 @@ def _workbook_upload() -> FileStorage:
def test_filename_pattern_supports_business_number_and_split_business_variables(): def test_filename_pattern_supports_business_number_and_split_business_variables():
"""业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。""" """业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。"""
task = ShippingNotice( task = ShippingNotice(
task_no='TASK-FILENAME', inventory_source_code='DBS', business_no='WYC26060201', task_no='TASK-FILENAME', business_no='WYC26060201',
customer_short_code_snapshot='WYC', business_date=date(2026, 6, 2), business_sequence_value=1, business_date=date(2026, 6, 2), business_sequence_value=1,
) )
template = ShippingExcelTemplate( template = ShippingExcelTemplate(
template_code='FILENAME', display_name='Filename', template_code='FILENAME', display_name='Filename',
definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'}, definition_json={'filename_pattern': '{business_no}_{business_date}_{sequence}.xlsx'},
) )
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx' assert _filename(task, template) == 'WYC26060201_260602_01.xlsx'
def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path): def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path):
"""业务执行必须使用活动库存 Link,忽略请求库存和旧任务缓存。""" """业务执行必须使用活动库存 Link,忽略请求库存。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(task_no='OT-INVENTORY-SOURCE', user_id=1)
task_no='TASK-INVENTORY-SOURCE', inventory_lines_json=[{'part_number': 'STALE'}],
)
inventory_file = ShippingInventoryFile( inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'), inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1, inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1,
@@ -185,22 +226,20 @@ def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cac
) )
assert resolved == [{'part_number': 'ACTIVE'}] assert resolved == [{'part_number': 'ACTIVE'}]
assert task.inventory_lines_json == [{'part_number': 'STALE'}]
def test_inventory_execution_keeps_legacy_fallback_without_active_link(app): def test_inventory_execution_keeps_legacy_fallback_without_active_link(app):
"""无活动 Link 的历史任务仍可读取请求库存或旧缓存,避免升级后无法恢复。""" """无活动 Link 的历史任务仍可读取请求库存,避免升级后无法恢复。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(task_no='OT-INVENTORY-LEGACY', user_id=1)
task_no='TASK-INVENTORY-LEGACY', inventory_lines_json=[{'part_number': 'CACHE'}],
)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
assert resolve_inventory_lines_for_execution( assert resolve_inventory_lines_for_execution(
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}], task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
) == [{'part_number': 'PAYLOAD'}] ) == [{'part_number': 'PAYLOAD'}]
assert resolve_inventory_lines_for_execution(task) == [{'part_number': 'CACHE'}] # 既无活动 Link 也无旧缓存时返回空,不伪造或回退到其它任务库存。
assert resolve_inventory_lines_for_execution(task) == []
def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch): def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch):
@@ -208,7 +247,7 @@ def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp
with app.app_context(): with app.app_context():
storage_path = tmp_path / 'stale.xlsx' storage_path = tmp_path / 'stale.xlsx'
storage_path.write_bytes(b'stale-source') storage_path.write_bytes(b'stale-source')
task = ShippingNotice(task_no='TASK-INVENTORY-NO-REPARSE') task = ShippingOrderTask(task_no='OT-INVENTORY-NO-REPARSE', user_id=1)
inventory_file = ShippingInventoryFile( inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path), inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}], inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}],
@@ -269,6 +308,8 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
"""发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。""" """发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context(): with app.app_context():
from tests.conftest import confirm_test_customer_resolution
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order') schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
db.session.add(schema) db.session.add(schema)
db.session.flush() db.session.flush()
@@ -315,10 +356,15 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
) )
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') ot = ShippingOrderTask(task_no='OT-EXPORT-1', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
)
db.session.add_all([source, extraction]) db.session.add_all([source, extraction])
db.session.flush() db.session.flush()
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_no=2)
db.session.add(order_line) db.session.add(order_line)
db.session.flush() db.session.flush()
header_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=customer.id, decision_status='accepted', resolved_value_json='acme') header_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=customer.id, decision_status='accepted', resolved_value_json='acme')
@@ -336,21 +382,26 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
) )
db.session.add(confirmed_customer) db.session.add(confirmed_customer)
db.session.flush() db.session.flush()
task = ShippingNotice( confirm_test_customer_resolution(ot, customer=confirmed_customer, extraction=extraction)
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB', inventory_file = ShippingInventoryFile(
customer_id=confirmed_customer.id, inventory_file_no='SIF-EXPORT-1', user_id=None,
customer_resolution_status='confirmed', source_file_name='inventory.xlsx', storage_path=str(tmp_path / 'inventory.xlsx'),
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。 inventory_lines_json=[{
inventory_warehouse_id=None, inventory_lines_json=[{
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9', _inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
}], inventory_snapshot_id=None, }],
line_count=1, share_mode='task_only', warehouse_id='DUB', source_code='DUB', snapshot_status='ready',
) )
db.session.add(task) db.session.add(inventory_file)
db.session.flush() db.session.flush()
_freeze_export_snapshot( snapshot = _freeze_export_snapshot(
task, extraction, version, ot, extraction, version,
header={customer.id: 'acme', po_number.id: '16754796'}, header={customer.id: 'acme', po_number.id: '16754796'},
lines=[(1, part.id, 'PN-1', 1, '1000000001')], lines=[(1, part.id, 'PN-1', 1, '1000000001')],
customer_id=confirmed_customer.id, inventory_file_id=inventory_file.id,
)
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。
task = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='DUB', notice_no='TASK-EXPORT-1',
) )
assert task.business_no is None assert task.business_no is None
@@ -427,7 +478,7 @@ def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app):
assert _mapping_value( assert _mapping_value(
{'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'}, {'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'},
task=task, order_values={}, inventory_values={}, export_sequence=1, task=task, order_values={}, inventory_values={}, notice_line_no=1,
) == 1 ) == 1
assert _mapping_value( assert _mapping_value(
{'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'}, {'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'},
@@ -523,6 +574,8 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
"""库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。""" """库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context(): with app.app_context():
from tests.conftest import confirm_test_customer_resolution
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order') schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
db.session.add(schema); db.session.flush() db.session.add(schema); db.session.flush()
part = _lookup_standard_fields('part_number')['part_number'] part = _lookup_standard_fields('part_number')['part_number']
@@ -552,10 +605,16 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
)) ))
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') customer = ShippingCustomer(standard_name='键控匹配客户', short_code='KEY', status='active')
db.session.add(customer); db.session.flush()
ot = ShippingOrderTask(task_no='OT-KEYED', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot); db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
)
db.session.add(extraction); db.session.flush() db.session.add(extraction); db.session.flush()
for position, value in enumerate(('PN-A', 'PN-B'), start=1): for position, value in enumerate(('PN-A', 'PN-B'), start=1):
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_key=str(position)) line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
db.session.add(line); db.session.flush() db.session.add(line); db.session.flush()
decision = ShippingOrderFieldDecision( decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=part.id, extraction_id=extraction.id, line_id=line.id, field_id=part.id,
@@ -566,20 +625,27 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
extraction_id=extraction.id, line_id=line.id, field_id=part.id, extraction_id=extraction.id, line_id=line.id, field_id=part.id,
value_text=value, decision_id=decision.id, value_text=value, decision_id=decision.id,
)) ))
task = ShippingNotice( confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
task_no='TASK-KEYED', current_order_extraction_id=extraction.id, inventory_source_code='KEYED', inventory_file = ShippingInventoryFile(
inventory_warehouse_id='DUB', inventory_lines_json=[ inventory_file_no='SIF-KEYED', user_id=None, source_file_name='keyed.xlsx',
storage_path=str(tmp_path / 'keyed.xlsx'),
inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'}, {_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'},
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'}, {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'},
], ],
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='KEYED', snapshot_status='ready',
) )
db.session.add(task); db.session.flush() db.session.add(inventory_file); db.session.flush()
_freeze_export_snapshot( snapshot = _freeze_export_snapshot(
task, extraction, version, ot, extraction, version,
lines=[ lines=[
(1, part.id, 'PN-A', 1, '1000000002'), (1, part.id, 'PN-A', 1, '1000000002'),
(2, part.id, 'PN-B', 1, '1000000003'), (2, part.id, 'PN-B', 1, '1000000003'),
], ],
customer_id=customer.id, inventory_file_id=inventory_file.id,
)
task = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='KEYED', notice_no='TASK-KEYED',
) )
path, _filename, _artifact = generate_shipment_excel(task) path, _filename, _artifact = generate_shipment_excel(task)
@@ -700,6 +766,8 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
"""导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。""" """导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context(): with app.app_context():
from tests.conftest import confirm_test_customer_resolution
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order') schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
db.session.add(schema); db.session.flush() db.session.add(schema); db.session.flush()
part = _lookup_standard_fields('part_number')['part_number'] part = _lookup_standard_fields('part_number')['part_number']
@@ -726,9 +794,15 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
)) ))
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') customer = ShippingCustomer(standard_name='模糊匹配客户', short_code='AMB', status='active')
db.session.add(customer); db.session.flush()
ot = ShippingOrderTask(task_no='OT-AMBIGUOUS', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot); db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
)
db.session.add(extraction); db.session.flush() db.session.add(extraction); db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_no=2)
db.session.add(line); db.session.flush() db.session.add(line); db.session.flush()
decision = ShippingOrderFieldDecision( decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=part.id, extraction_id=extraction.id, line_id=line.id, field_id=part.id,
@@ -739,17 +813,25 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
extraction_id=extraction.id, line_id=line.id, field_id=part.id, extraction_id=extraction.id, line_id=line.id, field_id=part.id,
value_text='PN-A', decision_id=decision.id, value_text='PN-A', decision_id=decision.id,
)) ))
task = ShippingNotice( confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
task_no='TASK-AMBIGUOUS', current_order_extraction_id=extraction.id, ambiguous_file = ShippingInventoryFile(
inventory_source_code='AMBIGUOUS', inventory_warehouse_id='DUB', inventory_lines_json=[ inventory_file_no='SIF-AMBIGUOUS', user_id=None, source_file_name='ambiguous.xlsx',
storage_path=str(tmp_path / 'ambiguous.xlsx'),
inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'}, {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'},
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'}, {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'},
], ],
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS',
snapshot_status='ready',
) )
db.session.add(task); db.session.flush() db.session.add(ambiguous_file); db.session.flush()
_freeze_export_snapshot( snapshot = _freeze_export_snapshot(
task, extraction, version, ot, extraction, version,
lines=[(1, part.id, 'PN-A', 1, '1000000004')], lines=[(1, part.id, 'PN-A', 1, '1000000004')],
customer_id=customer.id, inventory_file_id=ambiguous_file.id,
)
task = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=ambiguous_file, source_code='AMBIGUOUS', notice_no='TASK-AMBIGUOUS',
) )
with pytest.raises(ValueError, match='库存字段“ODM 编号”'): with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
@@ -770,7 +852,9 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
db.session.add(inventory_file) db.session.add(inventory_file)
db.session.flush() db.session.flush()
replace_task_inventory_link(task, inventory_file, role='owner') replace_task_inventory_link(task, inventory_file, role='owner')
task.inventory_snapshot_id = inventory_file.id # 切换活动库存后,行级匹配事实须指向新快照;导出只读取活动 Link。
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=ot.id, is_current=True).all():
match.inventory_snapshot_id = inventory_file.id
db.session.flush() db.session.flush()
path, _filename_value, artifact = generate_shipment_excel(task) path, _filename_value, artifact = generate_shipment_excel(task)
@@ -781,7 +865,6 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
finally: finally:
workbook.close() workbook.close()
assert artifact.inventory_snapshot_id == inventory_file.id assert artifact.inventory_snapshot_id == inventory_file.id
assert task.inventory_lines_json[0][_inventory_field_id('odm_id')] == 'ODM-1'
def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch): def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch):
@@ -1,113 +1,48 @@
""" """
backend/tests/test_shipping_order_line_no_resolver.py backend/tests/test_shipping_order_line_no_resolver.py
用途:order_line_no_resolver 单一解析器契约测试(项次展示/导出同源)。 用途:验证订单项次解析器只读取系统持久化的 line_no。
依赖:pytest、resolver、field_rules 格式门禁。 依赖:order_line_no_resolver。
逻辑:覆盖 field 真实值 / customer_po_line_no 回退 / sequence 展示序号 / 全空缺失四级分支, 逻辑:line_no 缺失时显式返回空值;客户 PO 行号、field_id 映射和展示序号均不得成为回退来源。
并验证 field_id 键与历史 field_code 键两种入参格式;mark 为 pure_unit 跳过 Flask 创建。
""" """
import pytest import pytest
from app.services.shipping_notice.order_line_no_resolver import ( from app.services.shipping_notice.order_line_no_resolver import (
LINE_NO_SOURCE_CUSTOMER_PO_LINE,
LINE_NO_SOURCE_FIELD,
LINE_NO_SOURCE_SEQUENCE,
field_id_by_code_from_definition, field_id_by_code_from_definition,
resolve_order_line_no, resolve_order_line_no,
) )
LINE_NO_ID = 'line-no-id'
CUSTOMER_PO_LINE_ID = 'customer-po-line-id' @pytest.mark.pure_unit
FIELD_ID_BY_CODE = { def test_resolver_reads_persisted_line_no_only():
'line_no': LINE_NO_ID, """系统已持久化项次时原样返回,不进行派生或格式重排。"""
'customer_po_line_no': CUSTOMER_PO_LINE_ID, assert resolve_order_line_no(
} field_values={'line_no': '00010', 'customer_po_line_no': '00020'},
field_id_by_code={'line_no': 'line-no-id'},
) == {'value': '00010', 'source': 'persisted'}
@pytest.mark.pure_unit @pytest.mark.pure_unit
def test_resolver_prefers_real_line_no_field_value(): def test_resolver_does_not_use_field_id_or_customer_po_line_no():
"""line_no 字段真实值必须优先于客户 PO 行号与序号。""" """项次不是 Schema 字段值,也不能从客户 PO 行号推断。"""
assert resolve_order_line_no( assert resolve_order_line_no(
field_values={LINE_NO_ID: '00010', CUSTOMER_PO_LINE_ID: '00020'}, field_values={'line-no-id': '10', 'customer_po_line_no': '20'},
field_id_by_code=FIELD_ID_BY_CODE, field_id_by_code={'line_no': 'line-no-id'},
fallback_sequence=1,
) == {'value': '00010', 'source': LINE_NO_SOURCE_FIELD}
@pytest.mark.pure_unit
def test_resolver_prefers_real_line_no_over_sequence_and_customer():
"""line_no 缺失时按顺序回退 customer_po_line_no,不直接落序号。"""
assert resolve_order_line_no(
field_values={CUSTOMER_PO_LINE_ID: '10'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=1,
) == {'value': '10', 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
@pytest.mark.pure_unit
def test_resolver_rejects_invalid_customer_line_no_format():
"""客户 PO 行号格式非法(非 1–6 位数字)时不得当业务项次,回退展示序号。"""
assert resolve_order_line_no(
field_values={'line_no': None, CUSTOMER_PO_LINE_ID: 'ABC'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=2,
) == {'value': '2', 'source': LINE_NO_SOURCE_SEQUENCE}
@pytest.mark.pure_unit
def test_resolver_uses_sequence_when_business_fields_missing():
"""line_no 与 customer_po_line_no 均缺失时仅能使用显式标注的展示序号。"""
assert resolve_order_line_no(
field_values={'line_no': None},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=3,
) == {'value': '3', 'source': LINE_NO_SOURCE_SEQUENCE}
@pytest.mark.pure_unit
def test_resolver_missing_everything_returns_none_source():
"""全部事实缺失且无序号时返回 None/None,禁止伪造空字符串或 0。"""
assert resolve_order_line_no(
field_values={},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=None,
) == {'value': None, 'source': None} ) == {'value': None, 'source': None}
@pytest.mark.pure_unit @pytest.mark.pure_unit
def test_resolver_supports_legacy_field_code_keys(): def test_resolver_does_not_fallback_to_display_sequence():
"""历史/测试数据按 field_code 键存储时,解析器仍能正确读取。""" """缺少持久化项次时显式返回空值,展示层不能伪造业务项次。"""
assert resolve_order_line_no( assert resolve_order_line_no(
field_values={'line_no': '00020', 'customer_po_line_no': '00030'}, field_values={},
field_id_by_code=None, ) == {'value': None, 'source': None}
fallback_sequence=5,
) == {'value': '00020', 'source': LINE_NO_SOURCE_FIELD}
@pytest.mark.pure_unit @pytest.mark.pure_unit
def test_resolver_fallbacks_to_code_key_when_field_id_missing(): def test_field_id_by_code_from_definition_is_metadata_only():
"""field_id 键缺失时回退读取 field_code 键,避免跨格式读取失败。""" """Schema 映射仍可独立解析,但不会参与 line_no 读取。"""
assert resolve_order_line_no(
field_values={CUSTOMER_PO_LINE_ID: '10', 'customer_po_line_no': '20'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=1,
) == {'value': '10', 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
@pytest.mark.pure_unit
def test_resolver_keeps_leading_zeros():
"""项次原样输出,保留前导零(如 00010),禁止转 int 丢零。"""
assert resolve_order_line_no(
field_values={'line_no': '00010'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=1,
) == {'value': '00010', 'source': LINE_NO_SOURCE_FIELD}
@pytest.mark.pure_unit
def test_field_id_by_code_from_definition_extracts_only_pair():
"""Schema 定义中仅提取同时具备 field_code/field_id 的字段。"""
definition = {'fields': [ definition = {'fields': [
{'field_code': 'line_no', 'field_id': 'a', 'scope': 'line'}, {'field_code': 'line_no', 'field_id': 'a', 'scope': 'line'},
{'field_code': 'customer_po_line_no', 'field_id': 'b'}, {'field_code': 'customer_po_line_no', 'field_id': 'b'},