370 lines
17 KiB
Python
370 lines
17 KiB
Python
"""
|
|
services/shipping_notice/export.py
|
|
|
|
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
|
|
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
|
|
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板。
|
|
"""
|
|
|
|
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 app import db
|
|
from app.models import (
|
|
ShippingExcelTemplate,
|
|
ShippingExportArtifact,
|
|
ShippingInventoryField,
|
|
ShippingInventorySource,
|
|
ShippingOrderSnapshot,
|
|
ShippingTask,
|
|
)
|
|
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: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
|
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
|
|
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 _system_fact(task: ShippingTask, key: str) -> Any:
|
|
"""读取受控任务事实,模板不能通过任意属性路径访问 ORM。"""
|
|
values = {
|
|
'task_no': task.task_no,
|
|
'business_no': 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(),
|
|
}
|
|
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: ShippingTask, order_values: dict[str, Any], inventory_values: dict[str, Any],
|
|
header_values: dict[str, Any] | None = None,
|
|
) -> Any:
|
|
"""按映射来源类型读取值;未知来源已在模板发布时被拒绝。"""
|
|
kind = mapping['source_kind']
|
|
key = mapping['source_key']
|
|
if kind == 'order_field':
|
|
value = order_values.get(key)
|
|
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)
|
|
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 _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:
|
|
raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致')
|
|
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: ShippingTask, template: ShippingExcelTemplate) -> 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': 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: ShippingTask, source: ShippingInventorySource, template: ShippingExcelTemplate,
|
|
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
|
|
) -> str:
|
|
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
|
|
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 [],
|
|
}
|
|
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: ShippingTask) -> tuple[str, str, ShippingExportArtifact]:
|
|
"""
|
|
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
|
|
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
|
|
|
|
Returns:
|
|
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
|
|
|
|
Raises:
|
|
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
|
|
"""
|
|
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:
|
|
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)
|
|
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)
|
|
line_values = [
|
|
values for line, values in zip(snapshot.lines, all_line_values, strict=True)
|
|
if line.id in available_line_ids
|
|
]
|
|
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
|
|
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)
|
|
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:
|
|
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,
|
|
)
|
|
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 {}
|
|
ws.cell(start_row + index, column).value = _mapping_value(
|
|
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
|
|
header_values=header_values,
|
|
)
|
|
wb.save(path)
|
|
finally:
|
|
wb.close()
|
|
|
|
content = path.read_bytes()
|
|
# 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是
|
|
# 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。
|
|
artifact = ShippingExportArtifact(
|
|
artifact_no=artifact_no, task_id=task.id, batch_id=task.batch_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),
|
|
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
|