feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口

完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
hugo committed 2026-08-11 14:04:39 +08:00
1 parent 8e0bbf7a81
commit c94d173f92
181 files changed
+12947 -1724

No files matched your search

+99 -14
View File
@@ -21,6 +21,7 @@ from zoneinfo import ZoneInfo
from flask import current_app
from openpyxl import load_workbook
from openpyxl.cell.cell import MergedCell
from sqlalchemy import func
from app import db
from app.models import (
@@ -29,6 +30,7 @@ from app.models import (
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderSnapshot,
ShippingOrderField,
ShippingNotice,
)
from app.path_utils import resolve_backend_relative_path
@@ -59,7 +61,39 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
return header, lines
def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None = None) -> Any:
def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None:
"""生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。"""
case = task.shipping_case
if case is None or not case.business_no:
return None
business_no = str(case.business_no).strip()
prefix = business_no[:-8] if len(business_no) > 8 else business_no
sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else ''
if not sequence and case.sequence_value:
sequence = f'{int(case.sequence_value):02d}'
if not sequence:
return None
export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date()
return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}'
def _clear_template_data_rows(ws: Any, start_row: int) -> None:
"""清除模板数据起始行之后的所有单元格值,保留模板表头与样式。"""
for row_index in range(start_row, ws.max_row + 1):
for column_index in range(1, ws.max_column + 1):
cell = ws.cell(row_index, column_index)
if not isinstance(cell, MergedCell):
cell.value = None
def _system_fact(
task: ShippingNotice,
key: str,
*,
export_sequence: int | None = None,
excel_business_no: str | None = None,
export_date: date | None = None,
) -> Any:
"""
读取受控任务事实,模板不能通过任意属性路径访问 ORM。
@@ -73,10 +107,10 @@ def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None
"""
values = {
'task_no': task.task_no,
'business_no': task.shipping_case.business_no if task.shipping_case else None,
'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None),
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_sequence': export_sequence,
}
return values.get(key)
@@ -110,6 +144,8 @@ 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,
excel_business_no: str | None = None,
export_date: date | None = None,
) -> Any:
"""
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
@@ -132,6 +168,16 @@ def _mapping_value(
key = mapping['source_key']
if kind == 'order_field':
value = order_values.get(key)
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' and export_sequence is not None:
value = export_sequence
if value in (None, '') and field_code == 'line_amount_with_tax':
value = order_values.get('__line_amount')
qty = order_values.get('__qty')
unit_price = order_values.get('__unit_price')
if value in (None, '') and qty not in (None, '') and unit_price not in (None, ''):
value = Decimal(str(qty)) * Decimal(str(unit_price))
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':
@@ -140,6 +186,8 @@ def _mapping_value(
value = _system_fact(
task, key,
export_sequence=export_sequence if key == 'export_sequence' else None,
excel_business_no=excel_business_no,
export_date=export_date,
)
if key == 'export_sequence' and value is None:
value = order_values.get('__export_sequence')
@@ -174,6 +222,17 @@ def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) ->
return {str(item.id) for item in rows}
def _inventory_field_user_label(field_id: str) -> str:
"""把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。"""
normalized = str(field_id or '').strip()
if normalized.isdigit():
row = ShippingInventoryField.query.filter_by(id=int(normalized)).first()
display_name = str(getattr(row, 'display_name', '') or '').strip() if row else ''
if display_name:
return display_name
return f'库存字段(编号 {normalized or "未知"})'
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
if not rows:
@@ -182,7 +241,8 @@ def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set
for field in required_fields:
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
if len(values) > 1:
raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致')
label = _inventory_field_user_label(field)
raise ValueError(f'订单行匹配到多个库存记录,库存字段“{label}”的值不一致,请检查库存映射或库存文件')
if values:
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
return resolved
@@ -252,7 +312,12 @@ def _safe_filename(name: str) -> str:
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
def _filename(
task: ShippingNotice,
template: ShippingExcelTemplate,
*,
excel_business_no: str | None = None,
) -> str:
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
if not pattern:
@@ -263,7 +328,7 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
shipping_case = task.shipping_case
values = {
'task_no': task.task_no,
'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no,
'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no),
'source_code': task.inventory_source_code or '',
'ts': now,
'date': now[:8],
@@ -280,14 +345,15 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
def _input_checksum(
task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate,
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
) -> str:
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
"""以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。"""
payload = {
'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,
'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [],
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
}
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
@@ -388,6 +454,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
excel_business_no = _excel_business_no(task, export_date=export_date)
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
reserve_available_for_artifact,
@@ -398,10 +466,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
for line, values in zip(snapshot.lines, all_line_values, strict=True):
if line.id not in available_line_ids:
continue
line_values.append(dict(values))
row = dict(values)
row['__qty'] = line.qty
row['__unit_price'] = line.unit_price
row['__line_amount'] = line.amount
line_values.append(row)
for index, row in enumerate(line_values, start=1):
row['__export_sequence'] = index
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 2] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
inventory_lines = resolve_inventory_lines_for_execution(task)
definition = template.definition_json or {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings:
@@ -415,7 +490,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
filename = _filename(task, template)
filename = _filename(task, template, excel_business_no=excel_business_no)
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
directory.mkdir(parents=True, exist_ok=True)
@@ -427,6 +502,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
path.write_bytes(template_bytes)
wb = load_workbook(path)
try:
data_start_rows = {
str(sheet): min(int(item['start_row']) for item in mappings if item['sheet'] == sheet)
for sheet in {str(item['sheet']) for item in mappings}
}
for sheet, start_row in data_start_rows.items():
_clear_template_data_rows(wb[sheet], start_row)
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
@@ -434,11 +515,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
if mapping['row_mode'] == 'header':
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,
)
continue
row_count = max(len(line_values), 1)
for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1):
ws.cell(row_index, column).value = None
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 {}
@@ -446,6 +527,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
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)),
excel_business_no=excel_business_no,
export_date=export_date,
)
wb.save(path)
finally:
@@ -458,7 +541,9 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
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,
input_checksum=_input_checksum(task, source, template, snapshot, header_values, line_values),
input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines,
),
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)