feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
1 parent
7cfd5d167e
commit
1e5aedb9ed
235 files changed
+11394
-9613
No files matched your search
@@ -24,9 +24,11 @@ from openpyxl import load_workbook
|
||||
from openpyxl.cell.cell import MergedCell
|
||||
from sqlalchemy import func
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingNoticeLine,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderSnapshot,
|
||||
@@ -37,6 +39,31 @@ from app.path_utils import resolve_backend_relative_path
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None:
|
||||
"""
|
||||
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
|
||||
|
||||
Args:
|
||||
task: 当前发货通知单。
|
||||
|
||||
Raises:
|
||||
ConflictError: 已存在任意导出 Artifact;后续库存必须创建新的发货通知单。
|
||||
"""
|
||||
if task.id is None:
|
||||
return
|
||||
existing = ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first()
|
||||
if existing is not None:
|
||||
raise ConflictError(
|
||||
'A shipping notice can generate only one Excel artifact',
|
||||
code='SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED',
|
||||
details={
|
||||
'task_no': task.task_no,
|
||||
'business_no': task.business_no,
|
||||
'artifact_no': existing.artifact_no,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _storage_root() -> Path:
|
||||
"""返回发货通知文件根目录。"""
|
||||
configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip()
|
||||
@@ -45,8 +72,22 @@ def _storage_root() -> Path:
|
||||
return Path(current_app.instance_path) / 'shipping_notice'
|
||||
|
||||
|
||||
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
|
||||
return notice
|
||||
|
||||
|
||||
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
|
||||
"""从 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
|
||||
@@ -62,19 +103,10 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
|
||||
|
||||
|
||||
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}'
|
||||
"""返回当前发货通知单编号;履约路径不回退到其他聚合标识。"""
|
||||
if task.business_no:
|
||||
return str(task.business_no).strip()
|
||||
return None
|
||||
|
||||
|
||||
def _clear_template_data_rows(ws: Any, start_row: int) -> None:
|
||||
@@ -92,6 +124,7 @@ def _system_fact(
|
||||
*,
|
||||
export_sequence: int | None = None,
|
||||
excel_business_no: str | None = None,
|
||||
notice_no: str | None = None,
|
||||
export_date: date | None = None,
|
||||
) -> Any:
|
||||
"""
|
||||
@@ -106,8 +139,8 @@ def _system_fact(
|
||||
对应系统事实值;未知键返回 None。
|
||||
"""
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None),
|
||||
'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,
|
||||
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
|
||||
@@ -160,6 +193,7 @@ 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,
|
||||
notice_no: str | None = None,
|
||||
export_date: date | None = None,
|
||||
) -> Any:
|
||||
"""
|
||||
@@ -196,6 +230,7 @@ def _mapping_value(
|
||||
task, key,
|
||||
export_sequence=export_sequence if key == 'export_sequence' else None,
|
||||
excel_business_no=excel_business_no,
|
||||
notice_no=notice_no,
|
||||
export_date=export_date,
|
||||
)
|
||||
if key == 'export_sequence' and value is None:
|
||||
@@ -393,6 +428,7 @@ def _filename(
|
||||
template: ShippingExcelTemplate,
|
||||
*,
|
||||
excel_business_no: str | None = None,
|
||||
notice_no: str | None = None,
|
||||
) -> str:
|
||||
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
|
||||
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
|
||||
@@ -401,16 +437,15 @@ def _filename(
|
||||
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),
|
||||
'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 '',
|
||||
'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 '',
|
||||
'customer_short_code': task.customer_short_code_snapshot or '',
|
||||
'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 '',
|
||||
}
|
||||
try:
|
||||
return _safe_filename(pattern.format(**values))
|
||||
@@ -422,6 +457,7 @@ 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]],
|
||||
notice_id: int | None = None,
|
||||
) -> str:
|
||||
"""以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。"""
|
||||
payload = {
|
||||
@@ -430,12 +466,15 @@ def _input_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,
|
||||
'notice_id': notice_id,
|
||||
}
|
||||
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]:
|
||||
def generate_shipment_excel(
|
||||
task: ShippingNotice,
|
||||
) -> tuple[str, str, ShippingExportArtifact]:
|
||||
"""
|
||||
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
|
||||
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
|
||||
@@ -445,56 +484,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
|
||||
Raises:
|
||||
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
|
||||
AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。
|
||||
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
|
||||
"""
|
||||
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 前复用库存满足性判定:每行须库存充足,
|
||||
# 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。
|
||||
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),
|
||||
).limit(20).all()
|
||||
# 行级库存事实是当前正式放行 Gate 的真相。历史导出任务可能只有
|
||||
# Reservation 核验轮次;这类任务继续由下方 Reservation 选择保护,不能因
|
||||
# 缺少新表事实被误判为“未匹配”。
|
||||
has_line_match_facts = bool(pending_rows)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
if has_line_match_facts and not match_completed(task):
|
||||
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(
|
||||
code='SHIPPING.EXCEL_NOT_READY',
|
||||
message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。',
|
||||
http_status=409,
|
||||
details={
|
||||
'blocking_reason_code': 'inventory_match_incomplete',
|
||||
'pending_count': len(pending_rows),
|
||||
'pending_rows_preview': details,
|
||||
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
|
||||
},
|
||||
)
|
||||
assert_notice_has_no_export_artifact(task)
|
||||
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
|
||||
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:
|
||||
@@ -524,18 +523,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
# 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')
|
||||
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
|
||||
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
|
||||
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,
|
||||
@@ -550,12 +543,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if task.id is not None:
|
||||
if source_notice.id is not None:
|
||||
release_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
@@ -574,10 +567,19 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
for source_index, line in enumerate(snapshot.lines)
|
||||
if source_index in release_overrides_by_source_line
|
||||
}
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
task,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
)
|
||||
selected_snapshot_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
|
||||
if row.snapshot_line_id is not None
|
||||
}
|
||||
try:
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
source_notice,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
|
||||
)
|
||||
except ConflictError:
|
||||
raise
|
||||
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
line_values = []
|
||||
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
|
||||
@@ -591,7 +593,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
|
||||
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
inventory_lines = resolve_inventory_lines_for_execution(task)
|
||||
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
|
||||
release_overrides_by_line = _release_overrides_for_export_lines(
|
||||
line_values=line_values,
|
||||
release_overrides_by_source_line=release_overrides_by_source_line,
|
||||
@@ -613,9 +615,17 @@ 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)
|
||||
|
||||
# [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、
|
||||
# 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。
|
||||
if not task.business_no:
|
||||
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
|
||||
|
||||
assign_notice_business_number(task)
|
||||
excel_business_no = _excel_business_no(task, export_date=export_date)
|
||||
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_key = task.task_no
|
||||
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / directory_key
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f'{artifact_no}_{filename}'
|
||||
template_bytes = file_asset_storage.get_bytes(template.storage_key)
|
||||
@@ -658,14 +668,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
wb.close()
|
||||
|
||||
content = path.read_bytes()
|
||||
# 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是
|
||||
# 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。
|
||||
# 当前 Notice 的唯一 Excel;后续分批履约必须先创建新的 Notice,
|
||||
# 因而不得在此处替换或追加当前 Notice 的 Artifact。
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=task.id, template_id=template.id,
|
||||
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,
|
||||
notice_id=int(task.id),
|
||||
),
|
||||
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
|
||||
file_size=len(content), status='ready',
|
||||
@@ -673,10 +685,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
reserve_available_for_artifact(
|
||||
task,
|
||||
source_notice,
|
||||
artifact=artifact,
|
||||
verification=verification,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
|
||||
)
|
||||
return str(path), filename, artifact
|
||||
except Exception:
|
||||
|
||||
Reference in new issue
Block a user