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

@@ -481,6 +481,45 @@ def workspace_shipping_task_detail(task_no: str):
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-options', methods=['GET'])
def workspace_shipping_task_odm_options(task_no: str):
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
return _ok(notice_odm_options(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-choice', methods=['POST'])
def workspace_set_shipping_task_odm_choice(task_no: str):
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
snapshot_line_id = int(data.get('snapshot_line_id') or 0)
except (TypeError, ValueError):
snapshot_line_id = 0
result = set_notice_odm_choice(
task,
snapshot_line_id=snapshot_line_id,
odm_id=str(data.get('odm_id') or ''),
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
def workspace_list_shipping_task_audit_timeline(task_no: str):
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
+2
View File
@@ -45,6 +45,8 @@ class ShippingCustomer(Base):
index=True,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 客户可用的 ODM ID 清单;为空表示不限定。生成发货 Excel 时用于收敛库存命中行。
odm_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -126,6 +126,8 @@ class ShippingNoticeLineInventoryMatch(Base):
onupdate=datetime.utcnow,
nullable=False,
)
# 整单 ODM ID 用户选择;写在当前匹配事实行上,随重匹配轮次自然失效。
chosen_odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# T6: 行级实际源证据(决策 E1 硬约束)——用于幂等保护与跨源匹配审计。
matched_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
matched_row_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
@@ -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,
@@ -0,0 +1,54 @@
"""customer odm scope: add odm_ids to shipping_customers
Revision ID: aa11bb22cc33
Revises: fb26bc033d27
Create Date: 2026-09-16 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "aa11bb22cc33"
down_revision = "fb26bc033d27"
branch_labels = None
depends_on = None
def _add_column(insp, table: str, column: sa.Column) -> None:
if table not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns(table)}
if column.name not in columns:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.add_column(column)
def _drop_column(insp, table: str, name: str) -> None:
if table not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns(table)}
if name in columns:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.drop_column(name)
def upgrade():
insp = sa.inspect(op.get_bind())
_add_column(
insp,
"shipping_customers",
sa.Column("odm_ids", sa.JSON(), nullable=True),
)
_add_column(
insp,
"shipping_notice_line_inventory_matches",
sa.Column("chosen_odm_id", sa.String(length=64), nullable=True),
)
def downgrade():
insp = sa.inspect(op.get_bind())
_drop_column(insp, "shipping_notice_line_inventory_matches", "chosen_odm_id")
_drop_column(insp, "shipping_customers", "odm_ids")
@@ -29,6 +29,14 @@ RESERVATION_DEFINITION = {
],
}
LN_RESERVATION_DEFINITION = {
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
'fields': DEFINITION['fields'] + [
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line', 'required': True},
{'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line'},
],
}
def _row(po: str, part: str) -> dict:
return {'status': 'parsed', 'issues': [], 'fields': [
@@ -38,6 +46,12 @@ def _row(po: str, part: str) -> dict:
]}
def _ln_row(po: str, part: str, ln: str) -> dict:
row = _row(po, part)
row['fields'].append({'field_id': 'ln', 'value': ln, 'quote': ln})
return row
def _page_glyphs(*lines: str) -> list[dict]:
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
glyphs = []
@@ -152,6 +166,63 @@ def test_approved_pdf_marks_conflicting_reservation_region_for_review():
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
def test_approved_pdf_maps_reservation_by_printed_ln_when_ln_non_contiguous():
"""PO_6075309 回归:LN=1/2/4/5 非连续时 L#n 必须按 LN 值落行,整单不转复核。
关键断言:L#4/L#5 分别写入 LN=4/LN=5 行(旧位置序会把 L#4 错配到 LN=5 并把
L#5 误报 line_out_of_range);行级 reservation 已全部归属后 source_missing_fields
不得残留 line_index 0 的假缺失(``or -1`` falsy bug)。
"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=LN_RESERVATION_DEFINITION,
table={'rows': [
_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2'),
_ln_row('PO-1', 'P-4', '4'), _ln_row('PO-1', 'P-5', '5'),
]},
reservation_region_candidates=[
{'value': '1000159370', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation L#1: 1000159370'},
{'value': '1000159366', 'scope': 'line', 'line_no': 2, 'raw_text': 'Reservation L#2: 1000159366'},
{'value': '1000159379', 'scope': 'line', 'line_no': 4, 'raw_text': 'Reservation L#4: 1000159379'},
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
],
)
assert reason is None
order = (orders or [])[0]
assert order.get('reservation_region_status') != 'needs_review'
assert 'source_missing_fields' not in order
expected_by_ln = {'1': '1000159370', '2': '1000159366', '4': '1000159379', '5': '1000159236'}
for line in order['lines']:
ln = next(item['observations'][0]['value'] for item in line['fields'] if item['field_id'] == 'ln')
assert any(
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == expected_by_ln[ln]
for item in line['fields']
)
def test_approved_pdf_keeps_reservation_review_when_referenced_ln_row_is_missing():
"""被引用的印刷行号在解析行中不存在时必须转复核,不得按位置静默写入。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=LN_RESERVATION_DEFINITION,
table={'rows': [_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2')]},
reservation_region_candidates=[
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
],
)
assert reason is None
order = (orders or [])[0]
assert order['reservation_region_status'] == 'needs_review'
assert order['reservation_region_review_reasons'] == ['line_out_of_range']
# LN=1/LN=2 行无对应候选,reservation 保持缺失供人工补录。
assert all(
not any(item['field_id'] == 'line-reservation' for item in line['fields'])
for line in order['lines']
)
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
result = _reservation_region_candidates(
@@ -896,3 +896,260 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
with pytest.raises(RuntimeError, match='commit failed'):
_commit_generated_export(str(path))
assert not path.exists()
def _build_multi_odm_notice(
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
):
"""
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
Args:
odm_values: 单订单行场景下库存行命中的 ODM 值列表。
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
Returns:
(notice, customer)。
"""
from tests.conftest import confirm_test_customer_resolution
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
db.session.add(schema); db.session.flush()
part = _lookup_standard_fields('part_number')['part_number']
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version); db.session.flush()
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'ODMSCOPE', 'display_name': 'OdmScope',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
{'sheet': 'Detail', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
]},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
parsing = ShippingInventoryParsingProfile(
profile_code='ODMSCOPE', display_name='OdmScope', version=1, status='published', file_format='xlsx',
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
)
login = ShippingRpaProfile(
profile_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', login_url='https://invalid',
login_config_json={'auth_mode': 'password'},
)
db.session.add_all([parsing, login]); db.session.flush()
db.session.add(ShippingInventorySource(
source_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', rpa_profile_id=login.id,
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
))
customer = ShippingCustomer(
standard_name='ODM范围客户', short_code='ODMSC', status='active',
odm_ids=list(customer_odm_ids) if customer_odm_ids is not None else None,
)
db.session.add(customer); db.session.flush()
ot = ShippingOrderTask(task_no='OT-ODMSCOPE', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot); db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
)
db.session.add(extraction); db.session.flush()
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
snapshot_lines = []
for index, spec in enumerate(specs, start=1):
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
db.session.add(order_line); db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
decision_status='accepted', resolved_value_json=spec['part'],
)
db.session.add(decision); db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
value_text=spec['part'], decision_id=decision.id,
))
snapshot_lines.append((index, part.id, spec['part'], 1, f'100000000{index}'))
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
inventory_rows = []
for spec in specs:
for odm in spec['odm_values']:
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
storage_path=str(tmp_path / 'odm-scope.xlsx'),
inventory_lines_json=inventory_rows,
line_count=len(inventory_rows), share_mode='task_only', warehouse_id='DUB', source_code='ODMSCOPE',
snapshot_status='ready',
)
db.session.add(inventory_file); db.session.flush()
snapshot = _freeze_export_snapshot(
ot, extraction, version,
lines=snapshot_lines,
customer_id=customer.id, inventory_file_id=inventory_file.id,
)
notice = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
)
if choice_odm is not None:
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
match.chosen_odm_id = choice_odm
db.session.flush()
return notice, customer
def test_export_narrows_odm_by_customer_range(app, tmp_path):
"""客户 ODM ID 范围非空时,导出只取范围内库存行;范围命中唯一值写入表头。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['odm-2'],
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
"""客户范围把全部命中排除时,必须报指向客户数据的可行动错误而非「没有匹配」。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-9'],
)
with pytest.raises(ValueError, match='不在客户数据维护的 ODM ID 范围'):
generate_shipment_excel(task)
def test_export_applies_notice_odm_choice(app, tmp_path):
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], choice_odm='odm-2',
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_auto_narrows_unique_feasible_odm_without_manual_choice(app, tmp_path):
"""无范围、无选择时,整单唯一可行 ODM(各行命中交集恰一个)自动收敛。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
{'part': 'PN-B', 'odm_values': ['ODM-2']},
])
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
"""无范围、无选择且多值并存时维持折叠冲突阻断,等待用户整单选择。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'])
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
generate_shipment_excel(task)
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
from app.core.errors import AppError
from app.services.shipping_notice.notice_odm_choice_service import (
notice_odm_options,
set_notice_odm_choice,
)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-2', 'ODM-3'],
)
options = notice_odm_options(task)
# [断言] 逐行候选是客户范围过滤后的集合,且保留库存行原始大小写。
assert options['whitelist_applied'] is True
assert options['customer_odm_ids'] == ['ODM-2', 'ODM-3']
assert len(options['lines']) == 1
assert options['lines'][0]['odm_values'] == ['ODM-2']
assert options['lines'][0]['chosen_odm_id'] is None
snapshot_line_id = options['lines'][0]['snapshot_line_id']
result = set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-2')
assert result['odm_id'] == 'ODM-2'
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task.order_task_id), is_current=True,
).all()
assert matches and {m.chosen_odm_id for m in matches} == {'ODM-2'}
options = notice_odm_options(task)
assert options['lines'][0]['chosen_odm_id'] == 'ODM-2'
with pytest.raises(AppError) as exc:
set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-9')
assert getattr(exc.value, 'code', '') == 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
def test_notice_odm_choice_syncs_same_snapshot_file_lines(app, tmp_path):
"""同一快照文件的行:改任一行 ODM ID,其余行同步落库同一选择。"""
from app.services.shipping_notice.notice_odm_choice_service import (
notice_odm_options,
set_notice_odm_choice,
)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
{'part': 'PN-B', 'odm_values': ['ODM-2', 'ODM-3']},
])
options = notice_odm_options(task)
# [断言] 每行有自己的候选;同文件两行的可行集=交集。
by_sid = {str(item['snapshot_line_id']): item for item in options['lines']}
assert len(by_sid) == 2
assert options['lines'][0]['odm_values'] == ['ODM-1', 'ODM-2']
target_sid = options['lines'][0]['snapshot_line_id']
result = set_notice_odm_choice(
task, snapshot_line_id=target_sid, odm_id='ODM-2',
)
# [断言] 同步范围=同一快照文件:两行当前匹配行写同一选择。
assert result['synced_line_count'] == 2
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task.order_task_id), is_current=True,
).all()
assert len(matches) == 2
assert {m.chosen_odm_id for m in matches} == {'ODM-2'}
options = notice_odm_options(task)
assert all(item['chosen_odm_id'] == 'ODM-2' for item in options['lines'])
def test_notice_odm_options_empty_when_template_ignores_odm(app, tmp_path):
"""模板不消费 odm 字段时投影为空候选,不产生任何选择入口。"""
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1'])
options = notice_odm_options(task)
assert options['odm_field_id'] is not None
assert options['lines'] and options['lines'][0]['odm_values'] == ['ODM-1']
@@ -212,6 +212,35 @@ def test_reservation_region_requires_review_when_numbered_value_has_no_line_targ
assert applied.review_reasons == ('line_field_unavailable',)
def test_reservation_region_matches_line_by_printed_ln_number_not_position():
"""LN 非连续(部分行已拆单)时必须按 LN 值定位逻辑行,禁止位置错配或误报越界。"""
applied = apply_reservation_region_candidates(
candidates=extract_reservation_from_region_text(
"Reservation L#1: 1000159370\nReservation L#2: 1000159366\n"
"Reservation L#4: 1000159379\nReservation L#5: 1000159236"
),
header_field_id='header-reservation', line_field_id='line-reservation',
line_count=4, line_numbers=[1, 2, 4, 5],
)
assert applied.needs_review is False
# 键是逻辑行序号:L#4→第 3 行(LN=4)、L#5→第 4 行(LN=5)。
assert applied.line_values == {1: '1000159370', 2: '1000159366', 3: '1000159379', 4: '1000159236'}
def test_reservation_region_flags_review_when_referenced_ln_number_is_absent():
"""被引用的印刷行号在解析行中不存在时必须转复核,不得静默按位置写入。"""
applied = apply_reservation_region_candidates(
candidates=extract_reservation_from_region_text("Reservation L#5: 1000159236"),
header_field_id='header-reservation', line_field_id='line-reservation',
line_count=2, line_numbers=[1, 2],
)
assert applied.line_values == {}
assert applied.needs_review is True
assert applied.review_reasons == ('line_out_of_range',)
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
@@ -2962,3 +2962,254 @@ def test_run_lineage_root_walk_loads_parent_runs_without_frozen_snapshot_columns
for statement in point_loads:
assert 'input_snapshot_json' not in statement
assert 'result_json' not in statement
def test_review_queue_flags_blocked_gate_cases_as_needs_attention(app):
"""门禁 blocked_manual(如库存缺口)的已建任务单,队列必须下发 needs_attention=True。"""
from app.models import ShippingProcessExecution, ShippingProcessGate
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NEEDS-ATTN')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-NEEDS-ATTN',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-needs-attn',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-ATTN',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-NEEDS-ATTN',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-REVIEW-QUEUE-NEEDS-ATTN',
task_id=task.id,
review_case_id=case.id,
status='active',
current_gate_code='inventory_sufficiency',
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=execution.id,
gate_code='inventory_sufficiency',
sequence_no=16,
status='blocked_manual',
))
task.active_process_execution_id = execution.id
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
queue = serialize_review_queue([run])
# 关键断言:库存缺口类门禁阻塞必须在队列可见,不再只依赖当前单的完整详情。
assert queue['items'][0]['needs_attention'] is True
assert queue['items'][0]['lifecycle_stage'] == 'fulfillment_prep'
# 关键断言:needs_attention 抬升 summary needs_action 桶,不得被计成完成/在办。
assert queue['summary'] == {'total': 1, 'needs_action': 1, 'processing': 0, 'completed': 0}
def test_review_queue_waiting_external_gate_is_not_needs_attention(app):
"""RPA 外部等待(waiting_external)属于系统在办,不得标记 needs_attention。"""
from app.models import ShippingProcessExecution, ShippingProcessGate
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-WAIT-EXT')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-WAIT-EXT',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-wait-ext',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-WAIT',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-WAIT-EXT',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='freight_uploading',
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-REVIEW-QUEUE-WAIT-EXT',
task_id=task.id,
review_case_id=case.id,
status='waiting_external',
current_gate_code='freight_upload_rpa',
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=execution.id,
gate_code='freight_upload_rpa',
sequence_no=18,
status='waiting_external',
))
task.active_process_execution_id = execution.id
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
# 关键断言:外部等待是在办不是待办,图标应走进行中而非需人工。
assert item['needs_attention'] is False
def test_review_queue_without_execution_is_not_needs_attention(app):
"""已建任务但尚无 Execution(或缓存未命中)时,needs_attention 必须为 False。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NO-EXEC')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-NO-EXEC',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-no-exec',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-NOEXEC',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-NO-EXEC',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
# 关键断言:无门禁事实时不臆造需人工标志。
assert item['needs_attention'] is False
def test_review_queue_summary_counts_terminal_stage_as_completed(app):
"""OT.stage=completed(通知完成)的已建任务单计入 completed,不再计入 processing。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-DONE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-DONE',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-done',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMDONE',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-SUM-DONE',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='completed',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:summary 与五态图标同口径——confirmed+终态=completed 而非 processing。
assert summary['total'] == 1
assert summary['completed'] == 1
assert summary['processing'] == 0
assert summary['needs_action'] == 0
def test_review_queue_summary_counts_quality_issue_as_needs_action(app):
"""quality_issue(文件质量异常)从 completed 改归 needs_action,与黄⚠图标一致。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-QI')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-QI',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-qi',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMQI',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
case.status = 'quality_issue'
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:质量异常是待办不是完成。
assert summary['needs_action'] == 1
assert summary['completed'] == 0
assert summary['processing'] == 0
def test_review_queue_summary_counts_plain_confirmed_as_processing(app):
"""已建任务、无阻塞、非终态的 confirmed 单计入 processing(对应转圈图标)。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-PROC')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-PROC',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-proc',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMPROC',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-SUM-PROC',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:已创建任务是在办不是完成。
assert summary['processing'] == 1
assert summary['completed'] == 0
assert summary['needs_action'] == 0