refactor(shipping-line): 统一订单与通知明细项次并移除旧键
This commit is contained in:
1 parent
938f3dd0e8
commit
b5d894a923
11 files changed
+331
-302
No files matched your search
@@ -28,19 +28,27 @@ class ShippingNoticeLine(Base):
|
||||
__tablename__ = 'shipping_notice_lines'
|
||||
__table_args__ = (
|
||||
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_snapshot_line_id', 'snapshot_line_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
|
||||
snapshot_line_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_snapshot_lines.id', ondelete='SET NULL'), nullable=True,
|
||||
snapshot_line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), 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)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), 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)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_task_line.py
|
||||
|
||||
用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。
|
||||
依赖:models.base.Base、shipping_notices、users。
|
||||
依赖:models.base.Base、shipping_order_tasks、users。
|
||||
逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。
|
||||
"""
|
||||
|
||||
@@ -60,7 +60,7 @@ class ShippingTaskFieldConflict(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
|
||||
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
@@ -91,4 +91,4 @@ class ShippingTaskFieldConflict(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
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_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'}
|
||||
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',
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ services/shipping_notice/export.py
|
||||
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
|
||||
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
|
||||
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
|
||||
在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费;
|
||||
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
|
||||
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
|
||||
"""
|
||||
|
||||
@@ -29,16 +29,55 @@ from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderField,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingCustomer,
|
||||
)
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
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:
|
||||
"""
|
||||
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
|
||||
@@ -73,16 +112,7 @@ def _storage_root() -> Path:
|
||||
|
||||
|
||||
def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
|
||||
"""后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。"""
|
||||
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
|
||||
"""返回当前 Notice;订单事实统一由其关联 OT/Snapshot 提供。"""
|
||||
return notice
|
||||
|
||||
|
||||
@@ -90,7 +120,9 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
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:
|
||||
raise ValueError('任务没有可用于库存匹配的冻结订单快照')
|
||||
fields = (snapshot.schema_version.definition_json or {}).get('fields') or []
|
||||
@@ -122,9 +154,10 @@ def _system_fact(
|
||||
task: ShippingNotice,
|
||||
key: str,
|
||||
*,
|
||||
export_sequence: int | None = None,
|
||||
excel_business_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,
|
||||
) -> Any:
|
||||
"""
|
||||
@@ -133,18 +166,16 @@ def _system_fact(
|
||||
Args:
|
||||
task: 发货任务。
|
||||
key: 系统事实键;仅允许白名单内键。
|
||||
export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。
|
||||
|
||||
Returns:
|
||||
对应系统事实值;未知键返回 None。
|
||||
"""
|
||||
values = {
|
||||
'task_no': notice_no or task.task_no,
|
||||
'business_no': notice_no or excel_business_no or task.business_no,
|
||||
'warehouse_id': task.inventory_warehouse_id,
|
||||
'inventory_source_code': task.inventory_source_code,
|
||||
'warehouse_id': notice_line_warehouse_id,
|
||||
'inventory_source_code': _notice_source_code(task),
|
||||
'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)
|
||||
|
||||
@@ -191,9 +222,11 @@ def _format_value(value: Any, formatter: str) -> Any:
|
||||
|
||||
def _mapping_value(
|
||||
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,
|
||||
notice_no: str | None = None,
|
||||
notice_line_no: str | None = None,
|
||||
notice_line_warehouse_id: str | None = None,
|
||||
export_date: date | None = None,
|
||||
field_id_by_code: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
@@ -201,9 +234,7 @@ def _mapping_value(
|
||||
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
|
||||
|
||||
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
|
||||
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
|
||||
项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 →
|
||||
导出行序号),与 UI 展示同一口径,禁止此处另造回退链。
|
||||
通知项次只读取 ``ShippingNoticeLine.line_no``;订单字段映射不再使用导出序号兜底。
|
||||
|
||||
Args:
|
||||
mapping: 已发布模板映射项。
|
||||
@@ -211,7 +242,6 @@ def _mapping_value(
|
||||
order_values: 当前行或表头订单字段值(field_id 为键)。
|
||||
inventory_values: 当前行库存字段值。
|
||||
header_values: 明细行模式下可回退的表头字段。
|
||||
export_sequence: 本次导出行序号(1..N)。
|
||||
field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。
|
||||
|
||||
Returns:
|
||||
@@ -224,13 +254,7 @@ def _mapping_value(
|
||||
field = db.session.get(ShippingOrderField, key) if key else None
|
||||
field_code = str(field.field_code or '') if field else ''
|
||||
if value in (None, '') and field_code == 'line_no':
|
||||
from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no
|
||||
|
||||
value = resolve_order_line_no(
|
||||
field_values=order_values,
|
||||
field_id_by_code=field_id_by_code,
|
||||
fallback_sequence=export_sequence,
|
||||
)['value']
|
||||
value = notice_line_no
|
||||
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
|
||||
value = header_values.get(key)
|
||||
elif kind == 'inventory_field':
|
||||
@@ -238,13 +262,12 @@ def _mapping_value(
|
||||
elif kind == 'system_fact':
|
||||
value = _system_fact(
|
||||
task, key,
|
||||
export_sequence=export_sequence if key == 'export_sequence' else None,
|
||||
excel_business_no=excel_business_no,
|
||||
notice_no=notice_no,
|
||||
notice_line_no=notice_line_no,
|
||||
notice_line_warehouse_id=notice_line_warehouse_id,
|
||||
export_date=export_date,
|
||||
)
|
||||
if key == 'export_sequence' and value is None:
|
||||
value = order_values.get('__export_sequence')
|
||||
else:
|
||||
value = key
|
||||
# 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串;
|
||||
@@ -447,13 +470,20 @@ def _filename(
|
||||
if not pattern:
|
||||
raise ValueError('发货 Excel 文件名规则未配置')
|
||||
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 = {
|
||||
'task_no': notice_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,
|
||||
'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 '',
|
||||
'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,
|
||||
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
|
||||
'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,
|
||||
'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_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):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
assert_notice_has_no_export_artifact(task)
|
||||
# [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()
|
||||
if source is None:
|
||||
# [T6 多候选兼容] 单源 resolved 走上方 inventory_source_code;多候选 candidates_frozen 时可能 source_code==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
|
||||
source = None
|
||||
if source is None:
|
||||
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
|
||||
template = source.excel_template
|
||||
@@ -528,13 +556,10 @@ def generate_shipment_excel(
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
if not mappings:
|
||||
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)
|
||||
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:
|
||||
raise ValueError('任务没有可用于导出的冻结订单快照')
|
||||
header_values, all_line_values = order_field_id_values(task)
|
||||
@@ -590,7 +615,7 @@ def generate_shipment_excel(
|
||||
)
|
||||
except ConflictError:
|
||||
raise
|
||||
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
# [STEP 2] 先筛出最终可导出行;通知项次来自已持久化的 ShippingNoticeLine.line_no。
|
||||
line_values = []
|
||||
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
|
||||
if line.id not in available_line_ids:
|
||||
@@ -598,8 +623,6 @@ def generate_shipment_excel(
|
||||
row = dict(values)
|
||||
row['__order_line_index'] = source_index
|
||||
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
|
||||
|
||||
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
@@ -661,21 +684,37 @@ def generate_shipment_excel(
|
||||
start_row = int(mapping['start_row'])
|
||||
column = int(mapping['target_column'])
|
||||
if mapping['row_mode'] == 'header':
|
||||
if _template_requires_system_warehouse_id([mapping]):
|
||||
raise ValueError('Warehouse ID 仅可作为发货通知行字段导出,模板不得将其映射为表头')
|
||||
ws.cell(start_row, column).value = _mapping_value(
|
||||
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
|
||||
excel_business_no=excel_business_no,
|
||||
export_date=export_date,
|
||||
notice_line_no=None,
|
||||
notice_line_warehouse_id=None,
|
||||
field_id_by_code=field_id_by_code,
|
||||
)
|
||||
continue
|
||||
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):
|
||||
order_line = line_values[index] if index < len(line_values) else {}
|
||||
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
|
||||
ws.cell(start_row + index, column).value = _mapping_value(
|
||||
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
|
||||
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,
|
||||
export_date=export_date,
|
||||
field_id_by_code=field_id_by_code,
|
||||
@@ -691,7 +730,7 @@ def generate_shipment_excel(
|
||||
artifact_no=artifact_no, task_id=task.id,
|
||||
template_id=template.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(
|
||||
task, source, template, snapshot, header_values, line_values, inventory_lines,
|
||||
notice_id=int(task.id),
|
||||
|
||||
@@ -9,36 +9,26 @@ services/shipping_notice/notice_line_constants.py
|
||||
from __future__ import annotations
|
||||
|
||||
NOTICE_LINE_FIELDS = (
|
||||
"line_no",
|
||||
"part_number",
|
||||
"qty",
|
||||
"unit_price",
|
||||
"amount",
|
||||
"currency",
|
||||
"line_amount_with_tax",
|
||||
"reservation_id",
|
||||
"required_date",
|
||||
"customer_part_number",
|
||||
"aws_part_number",
|
||||
"uom",
|
||||
"line_remark",
|
||||
"po_number",
|
||||
"allocation_id",
|
||||
"inventory_source_hint",
|
||||
)
|
||||
|
||||
NOTICE_FIELD_LABELS = {
|
||||
"line_no": "项次 / Item / Line No",
|
||||
"part_number": "内部料号 / Part Number",
|
||||
"qty": "需求数量",
|
||||
"unit_price": "单价",
|
||||
"amount": "金额",
|
||||
"currency": "币种",
|
||||
"line_amount_with_tax": "含税金额 / Amount",
|
||||
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
|
||||
"required_date": "要求交期 / 交货日期",
|
||||
"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",
|
||||
"line_remark": "行备注",
|
||||
}
|
||||
@@ -9,6 +9,7 @@ backend/app/services/shipping_notice/notice_line_service.py
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLine, ShippingOrderSnapshot
|
||||
@@ -19,6 +20,7 @@ def replace_notice_lines_from_snapshot(
|
||||
notice_id: int,
|
||||
snapshot: ShippingOrderSnapshot,
|
||||
snapshot_line_ids: set[int] | None = None,
|
||||
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
|
||||
@@ -35,18 +37,26 @@ def replace_notice_lines_from_snapshot(
|
||||
now = datetime.utcnow()
|
||||
rows: list[ShippingNoticeLine] = []
|
||||
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 []):
|
||||
if selected_ids and int(line.id) not in selected_ids:
|
||||
continue
|
||||
notice_position += 1
|
||||
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
|
||||
rows.append(
|
||||
ShippingNoticeLine(
|
||||
notice_id=int(notice_id),
|
||||
snapshot_line_id=int(line.id) if getattr(line, 'id', None) else None,
|
||||
position=int(line.position),
|
||||
line_key=str(getattr(line, 'line_no', None) or '').strip() or None,
|
||||
position=notice_position - 1,
|
||||
# 发货通知项次按当前通知单重新从 1 编排。
|
||||
line_no=notice_position,
|
||||
part_number=getattr(line, 'part_number', None),
|
||||
reservation_id=getattr(line, 'reservation_id', 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 {}),
|
||||
created_at=now,
|
||||
)
|
||||
|
||||
@@ -86,14 +86,6 @@ def parse_notice_row(
|
||||
if idx_qty is not None:
|
||||
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")
|
||||
reservation_id = ""
|
||||
if idx_res is not None:
|
||||
@@ -119,18 +111,22 @@ def parse_notice_row(
|
||||
if value is not None:
|
||||
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
|
||||
if idx_amount is not None:
|
||||
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)
|
||||
if value is not None:
|
||||
parsed["amount"] = float(value)
|
||||
|
||||
for field in (
|
||||
'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)
|
||||
if idx is None:
|
||||
@@ -145,7 +141,7 @@ def parse_notice_row(
|
||||
if 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:
|
||||
computed = round(parsed["unit_price"] * float(qty), 4)
|
||||
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
|
||||
if "reservation_id" in mapped:
|
||||
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
|
||||
return score
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ from app.services.shipping_notice.notice_line_values import (
|
||||
map_notice_header,
|
||||
norm_header,
|
||||
normalize_currency,
|
||||
normalize_line_no,
|
||||
normalize_required_date,
|
||||
parse_number,
|
||||
)
|
||||
@@ -201,10 +200,6 @@ def normalize_notice_line(
|
||||
if raw_uom and field_enabled("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"))
|
||||
if reservation_id and field_enabled("reservation_id"):
|
||||
line["reservation_id"] = reservation_id
|
||||
@@ -217,9 +212,10 @@ def normalize_notice_line(
|
||||
line["unit_price"] = unit_price
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
currency = normalize_currency(raw.get("currency"))
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_line_no_resolver.py
|
||||
|
||||
用途:内部项次(line_no)展示/导出值的唯一解析器——冻结字段真实值 → 客户 PO 行号 →
|
||||
行展示序号,并输出来源标注(field / customer_po_line_no / sequence / None)。
|
||||
用途:读取已经持久化的订单项次(line_no)。
|
||||
依赖:app.models(ShippingNotice/Snapshot/Extraction)、order_schema.field_rules(格式门禁)。
|
||||
逻辑:Excel 导出(export._mapping_value)与 UI 投影(query_service / ui_state)统一调用
|
||||
本模块,禁止各调用方自行兜底,避免同一数据出现两套口径;缺失事实必须显式标注来源,
|
||||
不得把内部行号伪装成业务项次。
|
||||
逻辑:line_no 由冻结/正式通知写路径按单据内顺序生成;本模块不执行派生、回退或来源推断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,11 +12,6 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
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(
|
||||
@@ -67,87 +59,67 @@ def notice_line_field_id_map(task: ShippingNotice) -> dict[str, str]:
|
||||
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_id_by_code: dict[str, str] | None,
|
||||
code: str,
|
||||
) -> str | None:
|
||||
"""按 field_id 优先、field_code 兼容的稳定顺序读取行字段值。
|
||||
|
||||
核心逻辑:冻结 JSON 以 field_id(UUID)为键;历史/测试数据可能仍按 field_code 存储。
|
||||
任一键命中且非空即返回规范化字符串,避免把 0/False 等合法值误判为空。
|
||||
"""
|
||||
"""按 Schema field_id 读取普通业务字段;不参与系统项次解析。"""
|
||||
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 ''
|
||||
if field_id and field_id in values:
|
||||
raw = values[field_id]
|
||||
if raw not in (None, ''):
|
||||
text = str(raw).strip()
|
||||
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
|
||||
field_id = str((field_id_by_code or {}).get(code) or '').strip()
|
||||
raw = values.get(field_id) if field_id else None
|
||||
if raw in (None, ''):
|
||||
return None
|
||||
text = str(raw).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def resolve_order_line_no(
|
||||
*,
|
||||
field_values: dict[str, Any] | None,
|
||||
field_id_by_code: dict[str, str] | None,
|
||||
fallback_sequence: int | None = None,
|
||||
field_id_by_code: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""解析一行内部项次展示值(唯一权威入口)。
|
||||
|
||||
【AI 触发时机】需要展示或导出某订单行的项次时统一调用;禁止在展示层自行回退。
|
||||
|
||||
核心逻辑:
|
||||
[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 位数字)一律跳过,不得以序号冒充业务值。
|
||||
核心逻辑:只读取 field_values 中已经持久化的 line_no;customer_po_line_no 和
|
||||
展示序号都不能作为内部项次的替代来源。
|
||||
|
||||
Args:
|
||||
field_values: 行字段值 JSON(field_id 或 field_code 键均可)。
|
||||
field_id_by_code: field_code → field_id 映射;为空时仅按 field_code 键兼容读取。
|
||||
fallback_sequence: 1 基展示序号;None 表示无序号兜底。
|
||||
field_id_by_code: 已废弃参数,仅为调用方签名稳定保留;不会参与读取。
|
||||
|
||||
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')
|
||||
if line_no is not None and is_valid_line_no_value(line_no):
|
||||
return {'value': line_no, 'source': LINE_NO_SOURCE_FIELD}
|
||||
|
||||
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}
|
||||
del field_id_by_code
|
||||
line_no = _read_persisted_line_no(field_values)
|
||||
return {'value': line_no, 'source': 'persisted' if line_no is not None else None}
|
||||
|
||||
|
||||
def resolve_order_line_no_projection(
|
||||
*,
|
||||
field_values: dict[str, Any] | None,
|
||||
field_id_by_code: dict[str, str] | None,
|
||||
fallback_sequence: int | None = None,
|
||||
field_id_by_code: dict[str, str] | None = None,
|
||||
) -> 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(
|
||||
field_values=field_values,
|
||||
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']}
|
||||
Reference in new issue
Block a user