Files
syops/backend/app/services/shipping_notice/export.py
T
hugo 11cef575b4 feat(shipping-notice): 优化货运订单履约流程与用户体验
- 优化聊天附件列表为横向可滚动布局并新增配套测试用例
- 移除自动填充默认用户消息逻辑,空备注时不再伪造默认正文
- 修复流程Gate动作展示逻辑,隐藏历史遗留操作与自动阶段无效按钮
- 完善库存匹配重试与订单快照冻结校验流程
- 优化进度展示优先级,优先显示人工待处理状态
- 移除Excel导出自动推导金额逻辑,强制使用Schema配置字段
- 新增货代通用报表RPA详细设计文档
- 更新相关测试用例与断言逻辑
2026-08-13 00:17:01 +08:00

549 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/export.py
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费;
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
"""
from __future__ import annotations
import hashlib
import json
import uuid
from datetime import date, datetime
from decimal import Decimal
from pathlib import Path
from typing import Any
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 (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderSnapshot,
ShippingOrderField,
ShippingNotice,
)
from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _storage_root() -> Path:
"""返回发货通知文件根目录。"""
configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip()
if configured:
return Path(resolve_backend_relative_path(configured))
return Path(current_app.instance_path) / 'shipping_notice'
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
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
if snapshot is None:
raise ValueError('任务没有可用于库存匹配的冻结订单快照')
fields = (snapshot.schema_version.definition_json or {}).get('fields') or []
header = dict(snapshot.header_values_json or {})
lines = [
dict(line.field_values_json or {})
for line in snapshot.lines
]
return header, lines
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。
Args:
task: 发货任务。
key: 系统事实键;仅允许白名单内键。
export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。
Returns:
对应系统事实值;未知键返回 None。
"""
values = {
'task_no': task.task_no,
'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': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_sequence': export_sequence,
}
return values.get(key)
def _format_value(value: Any, formatter: str) -> Any:
"""应用发布契约允许的确定性格式化器。"""
if value is None:
return ''
if formatter == 'upper':
return str(value).upper()
if formatter == 'lower':
return str(value).lower()
if formatter == 'date_mmddyyyy':
if isinstance(value, (date, datetime)):
return value.strftime('%m/%d/%Y')
text = str(value).strip()
for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d', '%m/%d/%Y'):
try:
return datetime.strptime(text[:10], pattern).strftime('%m/%d/%Y')
except ValueError:
continue
return text
if formatter == 'integer':
return int(Decimal(str(value)))
if formatter == 'decimal':
return float(Decimal(str(value)))
return str(value) if isinstance(value, (Decimal, date, datetime)) else value
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:
"""
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
Args:
mapping: 已发布模板映射项。
task: 发货任务。
order_values: 当前行或表头订单字段值。
inventory_values: 当前行库存字段值。
header_values: 明细行模式下可回退的表头字段。
export_sequence: 本次导出行序号(1..N)。
Returns:
经 formatter 处理后的单元格值。
"""
kind = mapping['source_kind']
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 is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
value = inventory_values.get(str(key))
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,
export_date=export_date,
)
if key == 'export_sequence' and value is None:
value = order_values.get('__export_sequence')
else:
value = key
return _format_value(value, mapping['formatter'])
def _match_text(value: Any) -> str:
"""规范化订单与库存匹配键;仅做确定性文本比较,不进行模糊推断。"""
if value is None:
return ''
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
return str(value).strip().casefold()
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
raw_ids = {
str(item['source_key']) for item in mappings
if item.get('row_mode') == row_mode and item.get('source_kind') == 'inventory_field'
}
ids = {int(item) for item in raw_ids if item.isdigit()}
if len(ids) != len(raw_ids):
raise ValueError('发货模板引用的库存字段无效')
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
).all() if ids else []
if len(rows) != len(ids):
raise ValueError('发货模板引用的库存字段已不存在')
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:
return {}
resolved = dict(rows[0])
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:
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
def _match_inventory_lines(
order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]],
match_keys: list[dict[str, str]], required_fields: set[str],
) -> list[dict[str, Any]]:
"""按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。"""
if not order_lines:
return []
if not match_keys:
raise ValueError('库存解析模板缺少订单与库存匹配键')
from app.models import ShippingInventoryField
ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
if not isinstance(item, dict):
raise ValueError('库存解析模板匹配键无效')
field_id = str(item.get('inventory_field_id') or '').strip()
inventory_field = catalog.get(field_id)
if not inventory_field:
raise ValueError('库存解析模板引用的库存字段已不可用')
normalized_keys.append({
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field': inventory_field,
})
result: list[dict[str, Any]] = []
for position, order_line in enumerate(order_lines, start=1):
expected = [
(_match_text(order_line.get(item['order_field_id'])), item['inventory_field'])
for item in normalized_keys
]
if any(not value for value, _field in expected):
raise ValueError(f'第 {position} 条订单行缺少库存匹配键值')
matched = [
row for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected)
]
if not matched:
raise ValueError(f'第 {position} 条订单行没有匹配的库存记录')
result.append(_collapse_inventory_matches(matched, required_fields))
return result
def _header_inventory_values(
matched_lines: list[dict[str, Any]], required_fields: set[str],
) -> dict[str, Any]:
"""Header 库存字段必须在所有订单行匹配结果中一致,否则不能生成单一 Header。"""
return _collapse_inventory_matches(matched_lines, required_fields)
def _safe_filename(name: str) -> str:
"""清理配置化文件名,防止路径穿越并强制 xlsx 扩展名。"""
cleaned = ''.join(ch for ch in name if ch.isalnum() or ch in {'-', '_', '.'}).strip('.')
cleaned = cleaned or 'shipment.xlsx'
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
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:
pattern = str(current_app.config.get('SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN') or '').strip()
if not pattern:
raise ValueError('发货 Excel 文件名规则未配置')
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
shipping_case = task.shipping_case
values = {
'task_no': 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],
'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '',
'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '',
'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '',
}
try:
return _safe_filename(pattern.format(**values))
except (KeyError, ValueError) as exc:
raise ValueError('发货 Excel 文件名规则无效') from exc
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': inventory_lines,
}
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExportArtifact]:
"""
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
Returns:
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。
"""
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.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.core.errors import AppError
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
# [T6 E2 硬门禁] 生成 Excel 前强制断言所有当前行匹配结果均为 matched;
# 即使单源任务有明确 inventory_source_code,行级短缺/冲突仍须先处理,避免导出不完整数据。
if task.id is not None:
pending_rows = db.session.query(
ShippingNoticeLineInventoryMatch.line_key,
ShippingNoticeLineInventoryMatch.match_result,
ShippingNoticeLineInventoryMatch.part_number,
ShippingNoticeLineInventoryMatch.reservation_id,
ShippingNoticeLineInventoryMatch.shortage_qty,
).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result != 'matched',
).limit(20).all()
pending_count = db.session.query(func.count(ShippingNoticeLineInventoryMatch.id)).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result != 'matched',
).scalar() or 0
if pending_count > 0:
details = [
{
'line_key': r[0],
'match_result': r[1],
'part_number': r[2],
'reservation_id': r[3],
'shortage_qty': r[4],
}
for r in pending_rows
]
raise AppError(
error_code='excel_not_ready',
status_code=409,
blocking_reason_code='inventory_match_incomplete',
message=f'存在 {pending_count} 行库存未完全匹配,禁止生成发货 Excel(请先处理短缺或冲突)。',
details={
'pending_count': int(pending_count),
'pending_rows_preview': details,
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
},
)
source_code = str(task.inventory_source_code 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
if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
# Fixed Sources receive this value from configuration; dynamic Sources receive it
# only after Reservation ID + Part Number resolves a unique inventory Warehouse.
if not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
template = source.excel_template
if template is None or template.status != 'published':
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
if source.parsing_profile is None or source.parsing_profile.status != 'published':
raise ValueError('库存源未绑定已发布的库存解析模板')
active_artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
).first()
if active_artifact is not None:
raise ValueError('当前任务存在待上传的发货 Excel,必须先完成或授权作废该 Artifact')
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
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,
)
verification, available_line_ids = current_available_snapshot_line_ids(task)
# [STEP 1] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
line_values = []
for line, values in zip(snapshot.lines, all_line_values, strict=True):
if line.id not in available_line_ids:
continue
row = dict(values)
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 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:
raise ValueError('发货 Excel 模板没有已发布的字段映射')
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
matched_inventory_lines = _match_inventory_lines(
line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields,
) 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, 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)
path = directory / f'{artifact_no}_{filename}'
template_bytes = file_asset_storage.get_bytes(template.storage_key)
if hashlib.sha256(template_bytes).hexdigest() != template.file_checksum:
raise ValueError('发货 Excel 模板文件缺失或校验失败')
try:
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'])
column = int(mapping['target_column'])
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 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)),
excel_business_no=excel_business_no,
export_date=export_date,
)
wb.save(path)
finally:
wb.close()
content = path.read_bytes()
# 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是
# 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。
artifact = ShippingExportArtifact(
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, inventory_lines,
),
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)
db.session.add(artifact)
db.session.flush()
reserve_available_for_artifact(task, artifact=artifact, verification=verification)
return str(path), filename, artifact
except Exception:
if path.is_file():
path.unlink()
raise