feat(shipping_notice): 支持客户 ODM 白名单与整单 ODM 选择收敛导出

- 客户主数据新增 odm_ids 白名单字段(含 Alembic 迁移),表单与管理端支持维护
- 导出库存命中行按客户白名单与整单 ODM 裁决收敛,新增 notice_odm_choice_service
- 工作台新增 odm-options / odm-choice 接口,投影行级候选并持久化用户选择
- 修复复核工作台跨 Run 切换时接收解析上下文残留
- 同步四语言 i18n、测试用例、funclist 与 shipping-notice 技术文档
This commit is contained in:
hugo committed 2026-09-16 19:50:12 +08:00
1 parent a032354cb9
commit d396371020
51 files changed
+2717 -109

No files matched your search

@@ -37,6 +37,47 @@ from app.services.shipping_notice.customer_normalization import (
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
_ODM_ID_MAX_ITEMS = 100
_ODM_ID_MAX_LENGTH = 64
def _normalize_odm_ids(value: Any) -> list[str] | None:
"""
规范化客户 ODM ID 清单:逐项 trim、去空、去重(保持原顺序)。
Args:
value: 前端提交的清单(字符串列表);None 表示未提交,空列表表示清空。
Returns:
规范化后的清单;None 仅当输入为 None。
Raises:
ValidationError: 条目超长或清单超量。
"""
if value is None:
return None
if not isinstance(value, list):
raise ValidationError(
'ODM ID list must be an array of strings',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
normalized: list[str] = []
for item in value:
text = str(item or '').strip()
if not text:
continue
if len(text) > _ODM_ID_MAX_LENGTH:
raise ValidationError(
'ODM ID is too long',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
details={'odm_id': text},
)
if text not in normalized:
normalized.append(text)
if len(normalized) > _ODM_ID_MAX_ITEMS:
raise ValidationError(
'Too many ODM IDs',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
return normalized
def _record_lifecycle_event(
@@ -142,6 +183,7 @@ def serialize_customer(
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
'created_by_id': record.created_by_id,
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
@@ -318,6 +360,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
odm_ids=_normalize_odm_ids(data.get('odm_ids')) if 'odm_ids' in data else None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
@@ -385,11 +428,13 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
next_odm_ids = before['odm_ids']
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
@@ -404,11 +449,14 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
if 'odm_ids' in data:
next_odm_ids = _normalize_odm_ids(data.get('odm_ids'))
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
'odm_ids': next_odm_ids,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
@@ -418,6 +466,7 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.odm_ids = next_odm_ids
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
@@ -56,6 +56,7 @@ from app.services.shipping_notice.order_schema.field_rules import normalize_orde
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
reservation_region_candidates_from_layout,
resolve_candidate_line_numbers,
)
@@ -551,6 +552,10 @@ def _candidate_for_sample(
header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None,
line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None,
line_count=len(rows),
# 盲测与正式解析共用 LN 值定位,防止预览与正式路由行归属不一致。
line_numbers=resolve_candidate_line_numbers([
row.get('customer_po_line_no') if isinstance(row, dict) else None for row in rows
]),
)
if applied.header_value and reservation_fields.get('header'):
header = reservation_fields['header']
+277 -54
View File
@@ -5,6 +5,8 @@ services/shipping_notice/export.py
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
整单 ODM 裁决依次应用:客户 odm_ids 范围 → 用户选择(OT.chosen_odm_id)→
唯一可行交集自动收敛;模板消费 odm 字段时生效;
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
@@ -45,8 +47,12 @@ from app.services.file_assets.storage import file_asset_storage
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
task_id = getattr(task, 'order_task_id', None)
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
"""
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
task_id = int(task_id)
@@ -63,6 +69,23 @@ def _notice_source_code(task: ShippingNotice) -> str | None:
return codes[0] if len(codes) == 1 else None
def _notice_chosen_odm(task: ShippingNotice) -> str | None:
"""读取当前行级匹配事实上的整单 ODM 用户选择(notice_odm_choice_service 落库)。"""
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
values = [
str(row[0]).strip()
for row in db.session.query(ShippingNoticeLineInventoryMatch.chosen_odm_id).filter(
ShippingNoticeLineInventoryMatch.task_id == int(task_id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.chosen_odm_id.isnot(None),
).distinct().all()
if row[0]
]
return values[0] if values else None
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
task_id = getattr(task, 'order_task_id', None)
@@ -426,29 +449,7 @@ def _match_inventory_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,
})
normalized_keys = _normalize_match_keys(match_keys)
result: list[dict[str, Any]] = []
for position, order_line in enumerate(order_lines, start=1):
expected = [
@@ -586,34 +587,176 @@ def _input_checksum(
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 禁止传模板或字段映射。
def _resolve_odm_inventory_field_id() -> int | None:
"""返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。"""
field = ShippingInventoryField.query.filter_by(field_code='odm_id', status='active').first()
return int(field.id) if field is not None else None
Returns:
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, str]]:
"""
校验并规范化库存解析模板匹配键为 {order_field_id, inventory_field} 列表。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
ValueError: 匹配键缺失、无效或引用的库存字段已不可用。
"""
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
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,
})
return normalized_keys
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
def _per_line_odm_sets(
order_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
normalized_keys: list[dict[str, str]],
odm_key: str,
) -> list[set[str]]:
"""逐导出行收集命中库存行的 odm 值集合;缺匹配键行与未命中行返回空集。"""
sets: list[set[str]] = []
for order_line in order_lines:
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):
sets.append(set())
continue
matched = {
_match_text(row.get(odm_key))
for row in inventory_lines
if all(_match_text(row.get(field)) == value for value, field in expected)
}
matched.discard('')
sets.append(matched)
return sets
def _intersect_odm_sets(sets: list[set[str]]) -> set[str]:
"""各行命中 odm 集合的交集;未命中行(空集)不参与约束,全部为空返回空集。"""
active = [item for item in sets if item]
if not active:
return set()
return set.intersection(*active)
def _adjudicate_notice_odm(
*,
line_values: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
match_keys: list[dict[str, Any]],
odm_field_id: int | None,
snapshot: ShippingOrderSnapshot,
chosen_odm_raw: str | None,
) -> dict[str, Any]:
"""
整单(Notice)级 ODM 收敛裁决;模板不消费 odm 字段时直接跳过。
逻辑:客户 ODM ID 范围非空先过滤;用户选择(OT.chosen_odm_id)次之;
无范围且无选择时,各导出行命中 odm 交集唯一则自动收敛(唯一可行解,无需人工)。
多值并存时不过滤,由逐行折叠按现有契约阻断,并由工作台下发候选供用户选择。
Returns:
{'inventory_lines': 收敛后的库存行, 'feasible_odm_ids': 排序候选,
'whitelist_applied': 是否应用了客户范围, 'chosen_odm_id': 用户选择(展示值)}
Raises:
ValueError: 范围排除全部命中,或用户选择在当前库存中已不存在。
"""
result = {
'inventory_lines': inventory_lines,
'feasible_odm_ids': [],
'per_line_odm_ids': [],
'whitelist_applied': False,
'chosen_odm_id': None,
}
if odm_field_id is None:
return result
odm_key = str(odm_field_id)
# 归一化值 → 原始展示值:候选/已选回显保留库存行原样大小写。
odm_display: dict[str, str] = {}
for row in inventory_lines:
raw = str(row.get(odm_key) or '').strip()
if raw:
odm_display.setdefault(_match_text(raw), raw)
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
customer_odm_ids = [
_match_text(value) for value in (customer.odm_ids or []) if _match_text(value)
] if customer is not None else []
chosen_odm = _match_text(chosen_odm_raw) if str(chosen_odm_raw or '').strip() else None
result['chosen_odm_id'] = odm_display.get(chosen_odm, str(chosen_odm_raw).strip()) if chosen_odm else None
normalized_keys = _normalize_match_keys(match_keys)
pre_odm_sets = _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
if customer_odm_ids:
result['whitelist_applied'] = True
scope = set(customer_odm_ids)
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in scope]
# 范围把原本有命中的行全部排除时,必须给出指向客户数据的可行动错误,
# 避免回落成误导性的「没有匹配的库存记录」。
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内,请检查客户数据或库存文件')
# 逐行候选取「客户范围过滤后、选择收敛前」的集合:用户在任何一行改选,候选都来自同一口径。
scoped_sets = (
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
if customer_odm_ids else pre_odm_sets
)
if chosen_odm:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) == chosen_odm]
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('发货通知已选择的 ODM ID 在当前库存中不存在,请重新选择')
elif not customer_odm_ids:
# 无范围、无选择:交集唯一即唯一可行解,自动收敛;多值留给折叠阻断 + 人工选择。
feasible = _intersect_odm_sets(pre_odm_sets)
if len(feasible) == 1:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in feasible]
result['inventory_lines'] = inventory_lines
result['per_line_odm_ids'] = [
sorted(odm_display.get(value, value) for value in line_set)
for line_set in scoped_sets
]
result['feasible_odm_ids'] = sorted(
odm_display.get(value, value)
for value in _intersect_odm_sets(
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key),
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
)
return result
def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
"""
汇集发货 Excel 导出匹配所需的只读输入;不物化、不写库。
【AI 触发时机】:generate_shipment_excel 的行匹配准备,以及工作台整单 ODM
候选投影(notice_odm_choice_service)复用,保证两者消费同一份匹配事实。
Returns:
source/template/snapshot/header_values/line_values/inventory_lines/
match_keys/line_inventory_fields/header_inventory_fields/verification/
selected_snapshot_line_ids/release_overrides_by_line/released_export_line_indexes。
"""
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(_notice_source_code(task) or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
@@ -637,11 +780,6 @@ def generate_shipment_excel(
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
reserve_available_for_artifact,
)
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')
@@ -696,6 +834,7 @@ def generate_shipment_excel(
continue
row = dict(values)
row['__order_line_index'] = source_index
row['__snapshot_line_id'] = int(line.id)
line_values.append(row)
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
@@ -703,8 +842,6 @@ def generate_shipment_excel(
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
from app.models import ShippingInventoryField
match_field_ids = {
int(item.get('inventory_field_id'))
for item in match_keys
@@ -742,6 +879,90 @@ def generate_shipment_excel(
and not isinstance(row.get('__order_line_index'), bool)
and int(row['__order_line_index']) in released_source_line_indexes
}
return {
'source': source,
'template': template,
'snapshot': snapshot,
'mappings': mappings,
'source_notice': source_notice,
'header_values': header_values,
'line_values': line_values,
'inventory_lines': inventory_lines,
'match_keys': match_keys,
'line_inventory_fields': line_inventory_fields,
'header_inventory_fields': header_inventory_fields,
'verification': verification,
'released_snapshot_line_ids': released_snapshot_line_ids,
'selected_snapshot_line_ids': selected_snapshot_line_ids,
'release_overrides_by_line': release_overrides_by_line,
'released_export_line_indexes': released_export_line_indexes,
}
def generate_shipment_excel(
task: ShippingNotice,
) -> tuple[str, str, ShippingExportArtifact]:
"""
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
Args:
chosen_odm_id: 整单 ODM ID 用户选择(本次生成的请求参数,不落库);
多 ODM 冲突时由工作台下发候选后随 Gate 动作传入,仅当其在当前库存命中时生效。
Returns:
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
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
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
inputs = prepare_export_match_inputs(task)
source = inputs['source']
template = inputs['template']
snapshot = inputs['snapshot']
mappings = inputs['mappings']
source_notice = inputs['source_notice']
header_values = inputs['header_values']
line_values = inputs['line_values']
match_keys = inputs['match_keys']
line_inventory_fields = inputs['line_inventory_fields']
header_inventory_fields = inputs['header_inventory_fields']
inventory_lines = inputs['inventory_lines']
verification = inputs['verification']
released_snapshot_line_ids = inputs['released_snapshot_line_ids']
selected_snapshot_line_ids = inputs['selected_snapshot_line_ids']
release_overrides_by_line = inputs['release_overrides_by_line']
released_export_line_indexes = inputs['released_export_line_indexes']
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
# [STEP 3.5] 整单 ODM 裁决:客户 ODM ID 范围 → 用户选择 → 唯一可行交集自动收敛。
odm_field_id = (
_resolve_odm_inventory_field_id()
if (line_inventory_fields or header_inventory_fields) else None
)
adjudication = _adjudicate_notice_odm(
line_values=line_values,
inventory_lines=inventory_lines,
match_keys=match_keys,
odm_field_id=odm_field_id,
snapshot=snapshot,
chosen_odm_raw=_notice_chosen_odm(task),
)
inventory_lines = adjudication['inventory_lines']
matched_inventory_lines = _match_inventory_lines(
line_values,
inventory_lines,
@@ -854,6 +1075,8 @@ def generate_shipment_excel(
)
db.session.add(artifact)
db.session.flush()
from app.services.shipping_notice.reservation_service import reserve_available_for_artifact
reserve_available_for_artifact(
source_notice,
artifact=artifact,
@@ -0,0 +1,177 @@
"""
services/shipping_notice/notice_odm_choice_service.py
用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。
逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一
事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行
(shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」
圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值);
重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import AppError
from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch
_ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
def _adjudication_task_id(task) -> int | None:
"""返回裁决挂接的 OT 主键:Notice 取 order_task_id,OT 取自身 id。"""
return getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
def notice_odm_options(task) -> dict[str, Any]:
"""
投影整单 ODM 逐行候选与当前用户选择;只读,不物化 Notice、不写库。
【AI 触发时机】:工作台通知准备面板需要展示「一个预约单号多个 ODM ID」的
行级候选与已选值时调用;禁止用它替代导出收敛——实际过滤由导出裁决执行。
Returns:
{odm_field_id, lines: [{snapshot_line_id, odm_values, chosen_odm_id}],
customer_odm_ids, whitelist_applied};模板不消费 odm 字段时 lines 为空列表。
"""
from app.services.shipping_notice.export import (
_adjudicate_notice_odm,
_notice_chosen_odm,
_resolve_odm_inventory_field_id,
prepare_export_match_inputs,
)
empty: dict[str, Any] = {
'odm_field_id': None,
'lines': [],
'customer_odm_ids': [],
'whitelist_applied': False,
}
# OT / Notice 都可直接投影(导出取数兼容两者);导出时再按正式链路裁决。
try:
inputs = prepare_export_match_inputs(task)
except (ValueError, AppError):
return empty
odm_field_id = (
_resolve_odm_inventory_field_id()
if (inputs['line_inventory_fields'] or inputs['header_inventory_fields']) else None
)
if odm_field_id is None:
return empty
snapshot = inputs['snapshot']
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
customer_odm_ids = (
[str(value or '').strip() for value in (customer.odm_ids or []) if str(value or '').strip()]
if customer is not None else []
)
try:
adjudication = _adjudicate_notice_odm(
line_values=inputs['line_values'],
inventory_lines=inputs['inventory_lines'],
match_keys=inputs['match_keys'],
odm_field_id=odm_field_id,
snapshot=snapshot,
chosen_odm_raw=_notice_chosen_odm(task),
)
except ValueError:
# 范围排除全部命中 / 选择已失效:候选投影为空,用户需先修客户数据或重选。
return {
'odm_field_id': odm_field_id,
'lines': [],
'customer_odm_ids': customer_odm_ids,
'whitelist_applied': True,
}
lines_payload = []
for row, odm_values in zip(inputs['line_values'], adjudication['per_line_odm_ids'], strict=True):
lines_payload.append({
'snapshot_line_id': row.get('__snapshot_line_id'),
'odm_values': list(odm_values),
'chosen_odm_id': adjudication['chosen_odm_id'],
})
return {
'odm_field_id': odm_field_id,
'lines': lines_payload,
'customer_odm_ids': customer_odm_ids,
'whitelist_applied': adjudication['whitelist_applied'],
}
def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[str, Any]:
"""
保存整单 ODM ID 用户选择:更新目标行的当前匹配事实,并同步同一快照文件的行。
同步范围 = 与目标行 `inventory_snapshot_id` 相同的全部 is_current 匹配行
(Header 契约是整单一个值,同文件行必须一致);校验取同步范围内各行候选的交集,
保证选择不会把其他行变成无匹配。
Args:
task: 正式 Notice 或其 OT。
snapshot_line_id: 用户编辑的冻结订单行 ID(工作台行主键)。
odm_id: 用户选定的 ODM ID。
Returns:
{task_id, odm_id, synced_line_count, odm_values}。
Raises:
AppError: 无当前匹配事实、行不存在,或所选值不在同步范围可行候选内
(SHIPPING.NOTICE_ODM_CHOICE_INVALID)。
"""
normalized = str(odm_id or '').strip()
options = notice_odm_options(task)
task_id = _adjudication_task_id(task)
if not task_id:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='Shipping task is required before recording ODM choice',
http_status=409,
)
target_row = (
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task_id),
snapshot_line_id=int(snapshot_line_id or 0),
is_current=True,
)
.first()
)
if target_row is None:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='No current inventory match fact for the given line',
http_status=409,
details={'snapshot_line_id': snapshot_line_id},
)
# 同步范围:与目标行关联同一快照文件的全部当前匹配行。
scope_rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id)
.all()
) if target_row.inventory_snapshot_id is not None else [target_row]
lines_by_sid = {
str(item.get('snapshot_line_id')): item for item in options.get('lines') or []
}
scope_candidates: list[set[str]] = []
for row in scope_rows:
entry = lines_by_sid.get(str(row.snapshot_line_id))
if entry is not None:
scope_candidates.append({str(v).strip().casefold() for v in entry.get('odm_values') or []})
feasible: set[str] = set.intersection(*scope_candidates) if scope_candidates else set()
if not normalized or normalized.strip().casefold() not in feasible:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='Selected ODM ID is not among the feasible values',
http_status=409,
details={'odm_id': normalized, 'odm_values': sorted(feasible)},
)
# 同步落库:同一快照文件的全部当前匹配行写同一选择(前后端同步语义的落库侧)。
for row in scope_rows:
row.chosen_odm_id = normalized
db.session.flush()
return {
'task_id': int(task_id),
'odm_id': normalized,
'synced_line_count': len(scope_rows),
'odm_values': sorted(feasible),
}
@@ -64,6 +64,7 @@ from app.services.shipping_notice.order_profile_value_adapter import get_value_a
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
resolve_candidate_line_numbers,
)
@@ -2090,14 +2091,18 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
)
decision['parsed_table_count'] = 1
decision['route_type'] = 'profile_deterministic'
# 模板确定性取值已成功,复核只针对业务归属(Reservation 专区/行校验)。
# 必须以 deterministic 携带原因码交 STP 裁 needs_review,让已解析订单
# 继续落 provisional Candidate 供复核台编辑;review_required 会被
# Worker 当作"无可信取值"丢弃,复核草稿将退化为空白手工单。
if any(order.get('reservation_region_status') == 'needs_review' for order in orders):
decision['fallback_reason_codes'] = ['reservation_region_needs_review']
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
decision, execution_mode='deterministic', orders=orders,
)
if decision.get('fallback_reason_codes'):
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
decision, execution_mode='deterministic', orders=orders,
)
decision['fallback_reason_codes'] = []
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
@@ -2357,11 +2362,31 @@ def _build_approved_profile_order_result(
if candidates:
header_target = reservation_scope.get('header')
line_target = reservation_scope.get('line')
# Reservation 注释的 L#n 引用单据印刷行号(LN 列),必须按 customer_po_line_no
# 值定位逻辑行;LN 非连续(部分行已拆单)时按位置写入会错配并误报越界。
line_numbers: list[int | None] | None = None
if line_target:
ln_field_id = next(
(str(item.get('field_id') or '') for item in fields
if str(item.get('field_code') or '') == 'customer_po_line_no'),
None,
)
if ln_field_id:
line_numbers = resolve_candidate_line_numbers([
next(
(observation.get('value') for field in group.get('fields') or []
if str(field.get('field_id') or '') == ln_field_id
for observation in field.get('observations') or []),
None,
)
for group in line_groups
])
applied = apply_reservation_region_candidates(
candidates=candidates,
header_field_id=str(header_target.get('field_id') or '') if header_target else None,
line_field_id=str(line_target.get('field_id') or '') if line_target else None,
line_count=len(line_groups),
line_numbers=line_numbers,
)
if applied.header_value and header_target:
header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {})
@@ -2379,9 +2404,10 @@ def _build_approved_profile_order_result(
]
if line_target:
for line_no, value in applied.line_values.items():
# line_no 已是逻辑行序号;候选里携带的是印刷行号,证据只按值回查。
line_evidence = next((
item for item in candidates
if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value
if item.get('scope') == 'line' and item.get('value') == value
), {})
line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{
'value': value, 'document_id': int(unit.document_id),
@@ -2390,7 +2416,8 @@ def _build_approved_profile_order_result(
line_id = str(line_target.get('field_id') or '')
line_code = str(line_target.get('field_code') or '')
for missing in source_missing_fields['lines']:
if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1:
# 不能用 `or -1` 兜底:line_index 0 是合法值,会被 falsy 判断跳过。
if isinstance(missing, dict) and missing.get('line_index') == line_no - 1:
missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id]
missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code]
source_missing_fields['lines'] = [
@@ -1065,6 +1065,54 @@ def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] |
return None
# 队列当前 Gate 活跃口径:在 _queue_current_gate_hint 活跃集合上补 queued/failed_terminal,
# 供 needs_attention 兜底取 Gate,避免终态失败的单被漏判。
_QUEUE_CURRENT_GATE_STATUSES = frozenset({
'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal',
})
# 需要人工介入的 Gate 状态;waiting_external/running/pending/queued 属系统在办,不算需人工。
_QUEUE_ATTENTION_GATE_STATUSES = frozenset({'blocked_manual', 'blocked_retryable', 'failed_terminal'})
def _queue_gate_needs_attention(case: ShippingOrderReviewCase) -> bool:
"""
判定 Case 当前正式门禁是否需要人工介入;供队列摘要下发 needs_attention。
只读会话级批量缓存(_load_review_case_summary_batch 已预取 Execution/Gate),
零额外 SQL;当前 Gate 取 execution.current_gate_code 对应 Gate,缺失时按
sequence_no 取第一个活跃 Gate。调用方禁止据此之外再自行推断阻塞。
Args:
case: 当前复核 Case。
Returns:
当前 Gate 状态 ∈ {blocked_manual, blocked_retryable, failed_terminal} 时 True;
无 Execution / 无活跃 Gate 时 False。
"""
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if not isinstance(cache, dict) or getattr(case, 'id', None) is None:
return False
execution = (cache.get('execution_by_case_id') or {}).get(int(case.id))
if execution is None:
return False
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or []
current = None
if gate_code:
for gate in gates:
if str(getattr(gate, 'gate_code', '') or '').strip().lower() == gate_code:
current = gate
break
if current is None:
for gate in gates:
if str(getattr(gate, 'status', '') or '').strip().lower() in _QUEUE_CURRENT_GATE_STATUSES:
current = gate
break
if current is None:
return False
return str(getattr(current, 'status', '') or '').strip().lower() in _QUEUE_ATTENTION_GATE_STATUSES
def _serialize_review_case_summary(
case: ShippingOrderReviewCase,
*,
@@ -1157,6 +1205,7 @@ def _serialize_review_case_summary(
'status': case.status,
'draft_version': int(draft.draft_version) if draft is not None else None,
'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0,
'needs_attention': _queue_gate_needs_attention(case),
# Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。
# 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。
'available_actions': (
@@ -1377,6 +1426,28 @@ def _load_review_case_summary_batch(
}
def _queue_summary_bucket(item: dict[str, Any]) -> str:
"""
队列计数桶归类;优先级与前端队列图标一致:需人工 > 终态完成 > 进行中。
桶是"处置去向"粗归类,与五态图标非一一映射(non_order 计入 completed,
图标为中性别灰○);needs_attention(门禁阻塞)恒优先于 completed,
避免阻塞单被计数成"完成"。
Args:
item: 队列 item 投影(含 status / needs_attention / lifecycle_stage)。
Returns:
'needs_action' | 'completed' | 'processing'。
"""
status = str(item.get('status') or '')
if status in ('unreviewed', 'draft', 'ready', 'quality_issue') or item.get('needs_attention'):
return 'needs_action'
if status in ('non_order', 'closed', 'completed') or str(item.get('lifecycle_stage') or '') == 'upload_complete':
return 'completed'
return 'processing'
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
if not runs:
@@ -1444,10 +1515,11 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
db.session.info.pop('shipping_conversation_projection_read_cache', None)
else:
db.session.info['shipping_conversation_projection_read_cache'] = previous_cache
buckets = [_queue_summary_bucket(item) for item in items]
counts = {
'total': len(items),
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
'processing': sum(1 for item in items if item['status'] in ('confirming', 'reparse_pending')),
'completed': sum(1 for item in items if item['status'] in ('confirmed', 'non_order', 'quality_issue')),
'needs_action': buckets.count('needs_action'),
'processing': buckets.count('processing'),
'completed': buckets.count('completed'),
}
return {'conversation_id': conversation_id, 'summary': counts, 'items': items}
@@ -210,6 +210,17 @@ def project_reservation_onto_validation_evidence(
header_field_id=str((reservation_scope.get('header') or {}).get('field_id') or '') or None,
line_field_id=str((reservation_scope.get('line') or {}).get('field_id') or '') or None,
line_count=len(projected['lines']),
line_numbers=resolve_candidate_line_numbers([
next(
(
field.get('normalized_value') or field.get('raw_value')
for field in line.get('fields') or []
if isinstance(field, dict) and str(field.get('field_code') or '') == 'customer_po_line_no'
),
None,
)
for line in projected['lines']
]),
)
header_target = reservation_scope.get('header')
if applied.header_value and header_target:
@@ -247,20 +258,51 @@ def project_reservation_onto_validation_evidence(
return projected
def resolve_candidate_line_numbers(values: list[object]) -> list[int | None] | None:
"""把按逻辑行顺序给出的 Customer PO 行号(LN 列)取值整理为候选定位表。
核心逻辑:Reservation 注释里的 ``L#n`` 引用的是单据上印刷的行号,必须按 LN 值
定位逻辑行;LN 非连续(如部分行已拆单)时按位置写入会错配并误报越界。
任一行解析出有效行号才返回定位表;完全没有行号取值时返回 None,
由调用方保持历史位置序行为以兼容无 LN 字段的旧 Schema。
"""
numbers: list[int | None] = []
has_number = False
for value in values:
try:
number = int(str(value).strip())
except (TypeError, ValueError):
number = None
else:
has_number = True
numbers.append(number)
return numbers if has_number else None
def apply_reservation_region_candidates(
*, candidates: list[dict[str, object]], header_field_id: str | None,
line_field_id: str | None, line_count: int,
line_numbers: list[int | None] | None = None,
) -> ReservationRegionApplication:
"""按固定契约将专用区域候选归属到订单头和逻辑明细行。
无行号 Reservation 是整单事实,最多接受一个不同值;带行号的值仅在
Schema 启用明细 Reservation 字段时写入对应逻辑行。冲突、越界行号或
多个不同整单值必须转人工复核,不能静默猜测。
``line_numbers`` 为各逻辑行的 Customer PO 行号(LN 列,1 起始);提供时候选
``line_no`` 按 LN 值定位逻辑行,被引用行号不存在则记 ``line_out_of_range``。
未提供时保持历史位置序写入,仅兼容无 LN 字段的旧 Schema。
"""
_ = header_field_id
header_values: list[str] = []
line_values_by_no: dict[int, list[str]] = {}
reasons: list[str] = []
line_target_by_number: dict[int, int] = {}
if line_numbers is not None:
for index, number in enumerate(line_numbers):
if isinstance(number, int) and number > 0:
line_target_by_number.setdefault(number, index + 1)
for item in candidates:
if not isinstance(item, dict):
continue
@@ -277,6 +319,8 @@ def apply_reservation_region_candidates(
except (TypeError, ValueError):
reasons.append('line_out_of_range')
continue
if line_numbers is not None:
line_no = line_target_by_number.get(line_no, 0)
if line_no < 1 or line_no > line_count:
reasons.append('line_out_of_range')
continue
@@ -1001,6 +1001,30 @@ def _build_stage_context(
if str(item.get('source_code') or '').strip()
]
# [STEP] 整单 ODM 裁决投影:一个预约单号多个 ODM ID 时,逐行下发候选与已选
# (同一快照文件的行同步使用同一值);投影失败不阻断工作台渲染,仅退化为无 ODM 入口。
try:
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
odm_projection = notice_odm_options(task)
except Exception:
odm_projection = {}
odm_lines_by_sid = {
str(item.get('snapshot_line_id')): item for item in odm_projection.get('lines') or []
}
for prep_line in preparation_lines:
entry = odm_lines_by_sid.get(str(prep_line.get('snapshot_line_id')))
if entry is None:
continue
prep_line['odm_values'] = list(entry.get('odm_values') or [])
prep_line['chosen_odm_id'] = entry.get('chosen_odm_id')
prep_line['odm_conflict'] = len(entry.get('odm_values') or []) > 1
odm_options_payload = {
'conflict': any(bool(item.get('odm_conflict')) for item in preparation_lines),
'customer_odm_ids': list(odm_projection.get('customer_odm_ids') or []),
'whitelist_applied': bool(odm_projection.get('whitelist_applied')),
}
artifact = None
attempts = []
if getattr(task, 'id', None):
@@ -1052,6 +1076,8 @@ def _build_stage_context(
],
'resolved_source_codes': list(facts.get('resolved_ok_source_codes') or []),
'source_options': source_options,
# 整单 ODM 裁决:conflict=True 时前端展示候选下拉,选择后可重试生成 Excel。
'odm_options': odm_options_payload,
'inventory_file': {
'available': downloadable_inventory is not None,
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,