feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -116,6 +116,21 @@ def _system_fact(
|
||||
return values.get(key)
|
||||
|
||||
|
||||
def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bool:
|
||||
"""判断发布模板是否实际消费任务级 ``system_fact:warehouse_id``。
|
||||
|
||||
模板将库位作为 ``inventory_field`` 消费时,值来自库存快照或已审计的
|
||||
短缺放行补录字段;不得额外要求任务级 Warehouse ID。只有模板显式引用
|
||||
系统事实时才保留该 fail-closed 门禁。
|
||||
"""
|
||||
return any(
|
||||
isinstance(mapping, dict)
|
||||
and str(mapping.get('source_kind') or '').strip() == 'system_fact'
|
||||
and str(mapping.get('source_key') or '').strip() == 'warehouse_id'
|
||||
for mapping in mappings
|
||||
)
|
||||
|
||||
|
||||
def _format_value(value: Any, formatter: str) -> Any:
|
||||
"""应用发布契约允许的确定性格式化器。"""
|
||||
if value is None:
|
||||
@@ -227,26 +242,40 @@ def _inventory_field_user_label(field_id: str) -> str:
|
||||
return f'库存字段(编号 {normalized or "未知"})'
|
||||
|
||||
|
||||
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
|
||||
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
|
||||
def _collapse_inventory_matches(
|
||||
rows: list[dict[str, Any]],
|
||||
required_fields: set[str],
|
||||
*,
|
||||
release_overrides: dict[str, Any] | None = None,
|
||||
) -> 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))}
|
||||
override = str((release_overrides or {}).get(field) or '').strip()
|
||||
if len(values) > 1:
|
||||
if override:
|
||||
resolved[field] = override
|
||||
continue
|
||||
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)))
|
||||
elif override:
|
||||
resolved[field] = override
|
||||
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],
|
||||
*,
|
||||
release_overrides_by_line: dict[int, dict[str, Any]] | None = None,
|
||||
released_export_line_indexes: set[int] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。"""
|
||||
"""按发布匹配键解析库存投影;已审计短缺放行可在导出时使用订单与补录事实。"""
|
||||
if not order_lines:
|
||||
return []
|
||||
if not match_keys:
|
||||
@@ -287,11 +316,60 @@ def _match_inventory_lines(
|
||||
if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected)
|
||||
]
|
||||
if not matched:
|
||||
# 短缺放行不改写或伪造库存匹配事实。它只授权导出阶段在匹配键
|
||||
# (例如 Reservation ID)未命中时,以冻结订单字段及已审计补录值
|
||||
# 写模板;模板不消费库存字段时,空映射也是完整、可审计的输入。
|
||||
overrides = (release_overrides_by_line or {}).get(position - 1) or {}
|
||||
resolved_overrides = {
|
||||
field: value
|
||||
for field, value in overrides.items()
|
||||
if field in required_fields and _match_text(value)
|
||||
}
|
||||
is_released = (position - 1) in (released_export_line_indexes or set())
|
||||
if is_released and set(resolved_overrides) == required_fields:
|
||||
result.append(resolved_overrides)
|
||||
continue
|
||||
raise ValueError(f'第 {position} 条订单行没有匹配的库存记录')
|
||||
result.append(_collapse_inventory_matches(matched, required_fields))
|
||||
result.append(_collapse_inventory_matches(
|
||||
matched,
|
||||
required_fields,
|
||||
release_overrides=(release_overrides_by_line or {}).get(position - 1),
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _release_overrides_for_export_lines(
|
||||
*,
|
||||
line_values: list[dict[str, Any]],
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]],
|
||||
) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
将冻结订单原始行索引映射为本次 Excel 连续行索引。
|
||||
|
||||
核心逻辑:原始首行索引 ``0`` 是有效业务值,不能以 ``or`` 回退为缺失值;
|
||||
仅传递该行已审计的短缺放行字段,其他行不受影响。
|
||||
|
||||
Args:
|
||||
line_values: 已按本次可导出集合筛选的订单行,含 ``__order_line_index``。
|
||||
release_overrides_by_source_line: 原始冻结订单行索引 → 放行补录字段。
|
||||
|
||||
Returns:
|
||||
Excel 连续行索引 → 放行补录字段。
|
||||
"""
|
||||
overrides: dict[int, dict[str, Any]] = {}
|
||||
for export_index, row in enumerate(line_values):
|
||||
source_index = row.get('__order_line_index')
|
||||
if isinstance(source_index, bool):
|
||||
continue
|
||||
try:
|
||||
normalized_source_index = int(source_index)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if normalized_source_index in release_overrides_by_source_line:
|
||||
overrides[export_index] = release_overrides_by_source_line[normalized_source_index]
|
||||
return overrides
|
||||
|
||||
|
||||
def _header_inventory_values(
|
||||
matched_lines: list[dict[str, Any]], required_fields: set[str],
|
||||
) -> dict[str, Any]:
|
||||
@@ -373,8 +451,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
if not task_is_active(task):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
# [T6 E2 硬门禁] 生成 Excel 前强制断言所有当前行匹配结果均为 matched;
|
||||
# 即使单源任务有明确 inventory_source_code,行级短缺/冲突仍须先处理,避免导出不完整数据。
|
||||
# [T6 E2 硬门禁] 生成 Excel 前复用库存满足性判定:每行须库存充足,
|
||||
# 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。
|
||||
if task.id is not None:
|
||||
pending_rows = db.session.query(
|
||||
ShippingNoticeLineInventoryMatch.line_key,
|
||||
@@ -385,14 +463,13 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
).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:
|
||||
# 行级库存事实是当前正式放行 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],
|
||||
@@ -404,12 +481,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
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(请先处理短缺或冲突)。',
|
||||
code='SHIPPING.EXCEL_NOT_READY',
|
||||
message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。',
|
||||
http_status=409,
|
||||
details={
|
||||
'pending_count': int(pending_count),
|
||||
'blocking_reason_code': 'inventory_match_incomplete',
|
||||
'pending_count': len(pending_rows),
|
||||
'pending_rows_preview': details,
|
||||
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
|
||||
},
|
||||
@@ -429,15 +506,20 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
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('库存源未绑定已发布的库存解析模板')
|
||||
definition = template.definition_json or {}
|
||||
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')
|
||||
active_artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
|
||||
@@ -454,30 +536,76 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
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)。
|
||||
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')
|
||||
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
||||
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if task.id is not None:
|
||||
release_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for decision in release_rows:
|
||||
values = dict(decision.snapshot_json or {}).get('release_field_values')
|
||||
if isinstance(values, dict) and decision.line_index is not None:
|
||||
source_line_index = int(decision.line_index)
|
||||
released_source_line_indexes.add(source_line_index)
|
||||
release_overrides_by_source_line[source_line_index] = {
|
||||
str(key): value for key, value in values.items()
|
||||
}
|
||||
released_snapshot_line_ids = {
|
||||
int(line.id)
|
||||
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,
|
||||
)
|
||||
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
line_values = []
|
||||
for line, values in zip(snapshot.lines, all_line_values, strict=True):
|
||||
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
|
||||
if line.id not in available_line_ids:
|
||||
continue
|
||||
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 2] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
# [STEP 3] 活动库存 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')
|
||||
release_overrides_by_line = _release_overrides_for_export_lines(
|
||||
line_values=line_values,
|
||||
release_overrides_by_source_line=release_overrides_by_source_line,
|
||||
)
|
||||
released_export_line_indexes = {
|
||||
export_index
|
||||
for export_index, row in enumerate(line_values)
|
||||
if isinstance(row.get('__order_line_index'), int)
|
||||
and not isinstance(row.get('__order_line_index'), bool)
|
||||
and int(row['__order_line_index']) in released_source_line_indexes
|
||||
}
|
||||
matched_inventory_lines = _match_inventory_lines(
|
||||
line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields,
|
||||
line_values,
|
||||
inventory_lines,
|
||||
match_keys,
|
||||
line_inventory_fields | header_inventory_fields,
|
||||
release_overrides_by_line=release_overrides_by_line,
|
||||
released_export_line_indexes=released_export_line_indexes,
|
||||
) 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)
|
||||
|
||||
@@ -540,7 +668,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
reserve_available_for_artifact(task, artifact=artifact, verification=verification)
|
||||
reserve_available_for_artifact(
|
||||
task,
|
||||
artifact=artifact,
|
||||
verification=verification,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
)
|
||||
return str(path), filename, artifact
|
||||
except Exception:
|
||||
if path.is_file():
|
||||
|
||||
Reference in new issue
Block a user