refactor(shipping-line): 统一订单与通知明细项次并移除旧键
This commit is contained in:
1 parent
938f3dd0e8
commit
b5d894a923
11 files changed
+331
-302
No files matched your search
@@ -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),
|
||||
|
||||
Reference in new issue
Block a user