Merge branch 'hugo-shipping-notice' into dev

# Conflicts:
#	frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
hugo committed 2026-09-17 16:29:10 +08:00
commit 80d78130f8
121 files changed
+9621 -1263

No files matched your search

@@ -199,6 +199,7 @@ def workspace_shipping_my_todos():
todo_category=str(request.args.get('todo_category') or '').strip() or None,
customer=str(request.args.get('customer') or '').strip() or None,
task_no=str(request.args.get('task_no') or '').strip() or None,
terminal_kind=str(request.args.get('terminal_kind') or '').strip() or None,
))
@@ -212,6 +213,67 @@ def workspace_shipping_my_todos_count():
return _ok(count_my_todos(user.id, is_admin=is_admin))
def _done_lines_report_params() -> dict[str, Any]:
"""解析明细报表共用筛选参数(客户/料号/发货通知日期范围),供查询与导出复用。"""
return {
'customer': str(request.args.get('customer') or '').strip() or None,
'part_number': str(request.args.get('part_number') or '').strip() or None,
'notice_date_from': str(request.args.get('notice_date_from') or '').strip() or None,
'notice_date_to': str(request.args.get('notice_date_to') or '').strip() or None,
}
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines', methods=['GET'])
def workspace_shipping_done_lines():
"""
分页列出已完成(已核验上传成功)通知的平铺明细行,供「通知完成」子视图报表。
核心逻辑:明细行跨 Notice 混排、不按 OT 聚合;支持 客户 / 料号 /
发货通知日期范围 筛选;行结构为标准 12 字段 + 溯源编号(task_no/business_no)。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import list_done_notice_lines
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
try:
page = int(request.args.get('page') or 1)
page_size = int(request.args.get('page_size') or 20)
except (TypeError, ValueError) as exc:
raise ValidationError('page and page_size must be integers') from exc
return _ok(list_done_notice_lines(
user.id,
is_admin=is_admin,
page=page,
page_size=page_size,
**_done_lines_report_params(),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines/export', methods=['GET'])
def workspace_shipping_done_lines_export():
"""
导出当前筛选下的已完成通知明细 Excel。
核心逻辑:固定 12 列标准格式(客户/客户编号/订单日期/订单项次/料号/数量/
约定出货日期/客户PO/已用数量/open qty/订单单号/单价),OT 编号不落列;
已用数量 / open qty 无数据源留空。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
stream, filename = build_done_lines_xlsx(
user.id,
is_admin=is_admin,
**_done_lines_report_params(),
)
response = send_file(
stream, as_attachment=True, download_name=filename, mimetype=EXPORT_MIME_TYPE,
)
response.call_on_close(stream.close)
return response
def _batch_task_nos(data: dict) -> list[str]:
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
raw_task_nos = data.get('task_nos')
@@ -481,6 +543,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,
@@ -0,0 +1,59 @@
"""
backend/app/services/shipping_notice/conversation_title.py
用途:为订单抽取**新建**会话推导业务化标题,替代写死的「订单抽取」。
依赖:仅标准库(datetime/pathlib/re);禁止引入 Flask/DB 依赖,保持可单测。
逻辑:取首个非空附件文件名去扩展名 → 循环剥离邮件前缀 → 截断 24 字符 →
多文件追加「等 N 个文件」→ 追加 MM-DD 日期消歧 → 全空回退「订单抽取」。
仅新建会话时调用;存量会话标题一律不改(设计决策见 2026-09-17 spec)。
"""
from __future__ import annotations
import re
from datetime import datetime
from pathlib import PureWindowsPath
_FALLBACK_TITLE = '订单抽取'
_NAME_MAX_CHARS = 24
_TITLE_MAX_CHARS = 60
# re:/fw:/fwd: 为半角冒号且大小写不敏感;回复/转发为全角冒号。循环剥离以支持多层嵌套。
_MAIL_PREFIX_PATTERN = re.compile(r'^\s*(?:re|fw|fwd)\s*:|^\s*(?:回复|转发):', re.IGNORECASE)
def _strip_mail_prefixes(name: str) -> str:
"""循环剥离单个文件名开头的邮件前缀(Re:/Fw:/Fwd:/回复:/转发:)。"""
current = name.strip()
while True:
stripped = _MAIL_PREFIX_PATTERN.sub('', current, count=1).lstrip()
if stripped == current:
return current
current = stripped
def derive_order_extraction_title(filenames: list[str], created_at: datetime) -> str:
"""
按首个附件文件名推导订单抽取会话标题。
Args:
filenames: 本次冻结 Intake 对应的资产原始文件名,按 Intake 顺序;
允许包含空串占位(保持计数口径)。
created_at: 会话创建时间(服务器 UTC,不做时区换算),提供 MM-DD 消歧后缀。
Returns:
形如「PO#6075309 等 11 个文件 09-15」的标题;文件名全空时回退「订单抽取」;
末尾做 60 字符防御性钳制(24 字主名约束下正常不可达)。
"""
ordered = [str(name or '').strip() for name in filenames]
usable = [name for name in ordered if name]
if not usable:
return _FALLBACK_TITLE
# PureWindowsPath 同时把 '/' 与 '\' 视为目录分隔符,兼容两类上传来源的路径写法。
stem = PureWindowsPath(usable[0]).stem
base = _strip_mail_prefixes(stem)[:_NAME_MAX_CHARS].strip()
if not base:
return _FALLBACK_TITLE
parts = [base]
if len(ordered) > 1:
parts.append(f'等 {len(ordered)} 个文件')
parts.append(f'{created_at.month:02d}-{created_at.day:02d}')
return ' '.join(parts)[:_TITLE_MAX_CHARS]
@@ -4,6 +4,9 @@ services/shipping_notice/customer_auto_resolution.py
用途:基于管理员审核的强证据受控自动确认 OT 客户。
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。
命中分级与复核侧共用:canonical 等值(unique_strong_match)与完整包含
(unique_containment_match,指纹整体出现在提取值中且证据授权)可自动确认;
截断包含(containment_weak)只供人工建议,永不进入本裁决。
"""
from __future__ import annotations
@@ -29,14 +32,18 @@ from app.services.shipping_notice.customer_identity_gate import (
customer_confirmation_facts,
)
from app.services.shipping_notice.customer_normalization import (
IDENTITY_MATCH_CONTAINMENT_STRONG,
IDENTITY_MATCH_EQUALITY,
canonical_identity_key,
classify_identity_containment,
is_public_email_domain,
normalize_customer_name,
normalize_domain,
normalize_email,
normalize_identity_evidence_value,
)
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
AUTO_RESOLUTION_VERSION = "customer-auto-v3"
# 允许自动确认的裁决状态;质量门禁分母与审计均以该集合为准。
AUTO_CONFIRM_ELIGIBLE_STATUSES = frozenset({'unique_strong_match', 'unique_containment_match'})
CUSTOMER_AUDIT_EVENT_TYPES = (
"customer_auto_resolution_evaluated",
"customer_auto_confirmed",
@@ -65,8 +72,8 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
eligible_samples = 0
correct_samples = 0
for shadow in labeled:
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
if decision['status'] != 'unique_strong_match':
decision = resolve_auto_customer_decision(shadow)
if decision['status'] not in AUTO_CONFIRM_ELIGIBLE_STATUSES:
continue
eligible_samples += 1
if int(decision['customer_id']) == int(shadow.manual_customer_id):
@@ -229,23 +236,55 @@ def _verified_shadow_value(
config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
context_source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
try:
if context_source.get('option_key') == 'from_email':
return normalize_email(value)
if context_source.get('option_key') == 'from_domain':
return normalize_domain(value)
if config.get('normalizer_key') == 'name':
return normalize_customer_name(value) or None
return str(value or '').strip().upper() or None
# 与影子识别/证据导入共用同一归一化,保证复核键与存储键同源(含换行折叠)。
return normalize_identity_evidence_value(
value,
option_key=context_source.get('option_key'),
normalizer_key=config.get('normalizer_key'),
)
except Exception:
return None
def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
def _classify_auto_evidence_match(
*, runtime_normalized: str, evidence_normalized: str, option_key: str,
) -> str | None:
"""
对单个授权证据做自动确认视角的命中分级。
核心逻辑:邮箱/域名只做大小写无关精确等值;文本类先比 canonical 等值
(吸收标点/空白差异),再判「指纹完整出现在提取值中」的强包含;
截断包含(containment_weak)返回给展示层但在此一律判不命中——剩余部分
未经验证,无法排除「另一个更短名的完整客户」,禁止自动确认。
"""
if option_key in {'from_email', 'from_domain'}:
if runtime_normalized.casefold() == evidence_normalized.casefold():
return IDENTITY_MATCH_EQUALITY
return None
if canonical_identity_key(runtime_normalized) == canonical_identity_key(evidence_normalized):
return IDENTITY_MATCH_EQUALITY
match_kind = classify_identity_containment(
runtime_normalized, evidence_normalized, option_key=option_key,
)
return match_kind if match_kind == IDENTITY_MATCH_CONTAINMENT_STRONG else None
def resolve_auto_customer_decision(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
"""
按影子记录的冻结定义和当前已审核授权证据求唯一自动确认客户。
业务定义、站点证据、公共邮箱域名及快照外字段都不是自动确认依据;多个客户命中时
一律返回歧义,即使其中一个客户累积的证据更多。
一律返回歧义,即使其中一个客户累积的证据更多。等值命中存在时包含命中不参与裁决;
仅「指纹完整出现在提取值中」(unique_containment_match)这一种包含形态在唯一且
授权时可自动确认,截断形态永不。
Args:
shadow: 已持久化的客户影子识别记录(须含规则快照与证据 JSON)。
Returns:
裁决字典:status(unique_strong_match / unique_containment_match /
ambiguous / unmatched / rule_snapshot_missing 等)、customer_id、
evidence(含 match_kind 溯源)与候选客户列表。
"""
snapshot = _rule_snapshot(shadow)
if snapshot is None:
@@ -256,6 +295,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
if isinstance(item, dict) and str(item.get('id') or '')
}
matched: dict[int, list[dict[str, Any]]] = {}
match_tiers: dict[int, str] = {}
for evidence in shadow.evidence_json or []:
if not isinstance(evidence, dict):
continue
@@ -298,8 +338,12 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
auto_match_allowed=True,
).all()
for record in records:
# 主数据中历史录入值也可能保留不同大小写;按指纹语义比较而非原始字符串比较。
if str(record.normalized_value or '').strip().casefold() != normalized.casefold():
match_kind = _classify_auto_evidence_match(
runtime_normalized=verified_normalized,
evidence_normalized=str(record.normalized_value or ''),
option_key=option_key,
)
if match_kind is None:
continue
if record.customer_id is None:
continue
@@ -311,16 +355,34 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
'definition_id': definition_id,
'definition_code': definition.get('definition_code'),
'normalized_value': normalized,
'match_kind': match_kind,
'source': field_value_source,
'context_source': context_source,
})
if (
customer.id not in match_tiers
or match_kind == IDENTITY_MATCH_EQUALITY
):
match_tiers[customer.id] = match_kind
# [STEP] 等值优先:存在等值命中的客户时,包含命中客户不参与裁决;
# 截断包含已在分级阶段被排除,绝不出现在自动确认候选中。
equality_customer_ids = {cid for cid, kind in match_tiers.items() if kind == IDENTITY_MATCH_EQUALITY}
decision_customer_ids = equality_customer_ids or set(match_tiers)
matched = {cid: matched[cid] for cid in decision_customer_ids}
if len(matched) != 1:
result = _decision_base(shadow, status='ambiguous' if matched else 'unmatched')
result['evidence'] = [item for rows in matched.values() for item in rows]
result['candidate_customer_ids'] = sorted(matched)
return result
customer_id = next(iter(matched))
result = _decision_base(shadow, status='unique_strong_match')
result = _decision_base(
shadow,
status=(
'unique_strong_match'
if match_tiers[customer_id] == IDENTITY_MATCH_EQUALITY
else 'unique_containment_match'
),
)
result['customer_id'] = customer_id
result['evidence'] = matched[customer_id]
return result
@@ -362,7 +424,7 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask)
if shadow is None:
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
decision = resolve_auto_customer_decision(shadow)
quality_gate = _auto_confirmation_quality_gate()
if not quality_gate['is_eligible']:
return {
@@ -1,9 +1,12 @@
"""
services/shipping_notice/customer_normalization.py
用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验。
用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验,
并提供识别证据的 canonical 比较键与包含关系分级。
依赖:re、unicodedata 标准库。
逻辑:管理后台导入与运行期客户裁决共用,避免同一证据在不同入口产生不同匹配键。
逻辑:管理后台导入、运行期影子识别与自动确认复核共用同一证据归一化
(normalize_identity_evidence_value),避免同一证据在不同入口产生不同匹配键;
canonical 键用于标点/空白无关的等值比较,包含分级支撑客户识别的三层匹配。
"""
from __future__ import annotations
@@ -130,3 +133,97 @@ def normalize_identifier(identifier_type: Any, value: Any) -> str:
details={'field': 'identifier_value'},
)
return normalized
# 邮箱/域名上下文键:指纹语义为精确标识,禁止参与包含分级。
_IDENTITY_EMAIL_DOMAIN_OPTION_KEYS = frozenset({'from_email', 'from_domain'})
# 包含命中的最短 canonical 字符数:更短片段(如 'c/o'→'CO')不足以声明同主体,
# 且短指纹一律由 canonical 等值路径承担,不享受包含兜底。
IDENTITY_CONTAINMENT_MIN_CHARS = 8
# 包含关系等值性强弱标记:strong=指纹完整出现在提取值中;weak=提取值疑似指纹截断。
IDENTITY_MATCH_EQUALITY = 'approved_identity_evidence'
IDENTITY_MATCH_CONTAINMENT_STRONG = 'containment_strong'
IDENTITY_MATCH_CONTAINMENT_WEAK = 'containment_weak'
# 等值 > 完整包含 > 截断包含;数值越小身份信号越强。
IDENTITY_MATCH_TIER_RANK = {
IDENTITY_MATCH_EQUALITY: 0,
IDENTITY_MATCH_CONTAINMENT_STRONG: 1,
IDENTITY_MATCH_CONTAINMENT_WEAK: 2,
}
_CANONICAL_STRIP_RE = re.compile(r'[\W_]+', re.UNICODE)
def normalize_identity_evidence_value(
value: Any, *, option_key: Any = None, normalizer_key: Any = None,
) -> str | None:
"""
按识别定义冻结的字段配置生成证据匹配键;导入、影子识别与自动确认复核共用。
核心逻辑:与 identity_rules._normalize_for_snapshot、resolver._normalize、
customer_auto_resolution._verified_shadow_value 的历史分支一一对应;兜底分支统一
走 clean_text(折叠内部空白/换行),修复运行侧保留换行导致多行提取值永远无法
等值命中单行注册证据的不对称缺陷。
Args:
value: 已裁决 Header 字段值或管理员录入的原始证据值。
option_key: 字段上下文来源(from_email/from_domain 时按邮箱/域名校验归一)。
normalizer_key: 冻结 Schema 字段配置的 normalizer('name' 走客户名称词管线)。
Returns:
归一化匹配键;空值返回 None(调用方按各自契约决定跳过或报错)。
Raises:
ValidationError: 邮箱/域名值不合法(由下游 normalize_* 抛出,调用方自行容错)。
"""
kind = clean_text(option_key).lower() if option_key else ''
if kind == 'from_email':
return normalize_email(value)
if kind == 'from_domain':
return normalize_domain(value)
if clean_text(normalizer_key or '').lower() == 'name':
return normalize_customer_name(value) or None
return clean_text(value).upper() or None
def canonical_identity_key(value: Any) -> str:
"""
生成识别证据的 canonical 比较键:NFKC + casefold + 剔除全部非字母数字。
核心逻辑:中文等 Unicode 词字符保留(支持中文客户名),标点、空白、下划线
全部剔除,使 'QCH, INC.' 与 'QCH INC.' 这类打印差异在等值比较中不再分裂。
邮箱/域名指纹禁止使用本键比较('@'、'.' 属于语义字符),调用方须先分流。
"""
return _CANONICAL_STRIP_RE.sub('', unicodedata.normalize('NFKC', str(value or '')).casefold())
def classify_identity_containment(
runtime_normalized: Any, evidence_normalized: Any, *, option_key: Any = None,
) -> str | None:
"""
对文本类识别证据做双向包含分级,供客户识别的弱命中层使用。
Args:
runtime_normalized: 运行时提取值(已经 normalize_identity_evidence_value 归一)。
evidence_normalized: 库内已注册证据值(同上归一)。
option_key: 字段上下文来源;from_email/from_domain 直接返回 None。
Returns:
IDENTITY_MATCH_CONTAINMENT_STRONG:注册指纹完整出现在提取值中(提取多带
折行尾巴),身份信号可参与受控自动确认;
IDENTITY_MATCH_CONTAINMENT_WEAK:提取值疑似指纹截断片段(剩余部分未经验
证,无法区分「截断」与「另一个更短名的完整客户」),只允许作为人工确认建议;
None:无包含关系,或包含侧短于 IDENTITY_CONTAINMENT_MIN_CHARS。
"""
kind = clean_text(option_key).lower() if option_key else ''
if kind in _IDENTITY_EMAIL_DOMAIN_OPTION_KEYS:
return None
runtime_key = canonical_identity_key(runtime_normalized)
evidence_key = canonical_identity_key(evidence_normalized)
if not runtime_key or not evidence_key:
return None
if len(evidence_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and evidence_key in runtime_key:
return IDENTITY_MATCH_CONTAINMENT_STRONG
if len(runtime_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and runtime_key in evidence_key:
return IDENTITY_MATCH_CONTAINMENT_WEAK
return None
@@ -36,9 +36,10 @@ def refresh_candidate_shadow_resolution(candidate: ShippingOrderCandidate) -> Sh
resolution = resolve_candidate_identity(candidate, intake)
evidence = list(resolution['evidence'])
matches = list(resolution['customer_matches'])
# 状态一律以 resolver 的层级裁决为准(等值 > 完整包含 > 截断包含),
# 本地不再按分数重复判定,避免两处排序/歧义语义分叉;top_score 取排序首位的累计权重。
status = str(resolution['status'])
top_score = float(matches[0]['score']) if matches else None
tied = [item for item in matches if float(item['score']) == top_score] if top_score is not None else []
status = 'unmatched' if not matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous'
row = db.session.query(ShippingCustomerShadowResolution).filter_by(candidate_id=int(candidate.id)).first()
if row is None:
row = ShippingCustomerShadowResolution(candidate_id=int(candidate.id), intake_id=int(candidate.intake_id))
@@ -11,6 +11,11 @@ services/shipping_notice/document_layout/order_profile_matcher.py
禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
表头可经 Schema 别名表(header_to_field)把命中短语归一为 field:: 字段语义原子
(schema_canonical_header_atoms),实现跨措辞的身份对齐,未配置时退化为词级原子;
canonical 序列(schema_canonical_header_tokens)供 signature_conflict 硬门禁的
二次机会评估复用同一表头打分逻辑(effective = max(原始, canonical),仅无必选
锚点且契约可用时生效,七维上报分数维持原始值);
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
"""
@@ -126,6 +131,7 @@ def match_frozen_coordinate_profiles(
profiles: list[dict[str, Any]],
layout: dict[str, Any],
customer_hint_id: int | None = None,
header_to_field: dict[str, str] | None = None,
) -> ProfileMatchResult:
"""
对同一文档的冻结 Profile 做签名硬门禁、分项评分与唯一匹配。
@@ -134,6 +140,10 @@ def match_frozen_coordinate_profiles(
profiles: 已发布模板快照列表;须含 matching_signature 与 definition。
layout: 冻结 layout 快照,含 tables 与 coordinate_evidence。
customer_hint_id: 可选运行期客户 ID,仅用于 trusted_business_context 维度。
header_to_field: 可选 Schema 表头别名契约(TableHeaderContract.header_to_field,
key 为归一化表头文案、value 为 field_code);传入时无必选锚点路径的表头
原子互斥先经 schema_canonical_header_atoms 归一为字段语义原子再比对,
实现跨别名身份对齐;None/空时退化为词级原子(既有行为)。
Returns:
ProfileMatchResult:含 Top1/Top2/Margin、evidence_coverage 与候选分项得分。
@@ -233,6 +243,7 @@ def match_frozen_coordinate_profiles(
optional_hits=optional_hits,
customer_ids=raw.get('customer_ids') if isinstance(raw.get('customer_ids'), list) else None,
customer_hint_id=customer_hint_id,
header_to_field=header_to_field,
)
reason_codes.extend(hard_conflict_codes)
if _profile_requires_unavailable_structure_evidence(
@@ -894,8 +905,17 @@ def _compute_dimension_results(
optional_hits: list[bool],
customer_ids: list[int] | None,
customer_hint_id: int | None,
header_to_field: dict[str, str] | None = None,
) -> tuple[dict[str, MatchDimensionResult], list[str]]:
"""基于签名与冻结证据计算统一七维三态结果。"""
"""
基于签名与冻结证据计算统一七维三态结果。
Args:
header_to_field: 可选 Schema 表头别名契约;非 None/非空时表头原子互斥
(仅无必选锚点路径)先按别名归一为字段语义原子,None 时走词级原子;
同时启用 signature_conflict 门禁的二次机会评估(见 [STEP 1.1]),
七维上报分数不受其影响,维持原始值。
"""
hard_conflicts: list[str] = []
results: dict[str, MatchDimensionResult] = {}
@@ -906,20 +926,36 @@ def _compute_dimension_results(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=enforce_header_atoms,
)
# 七维上报维持原始得分;canonical 二次评估得分只参与下方 signature_conflict 门禁。
results['header_semantic_position'] = header_result
if (
enforce_header_atoms
and header_result.state == 'mismatched'
and _header_discriminator_atoms_conflict(signature=signature, observed=observed)
and _header_discriminator_atoms_conflict(
signature=signature, observed=observed, header_to_field=header_to_field,
)
):
hard_conflicts.append('profile_header_discriminator_conflict')
elif (
header_result.state == 'mismatched'
and signature
and signature.get('table_patterns')
and header_result.score < 0.35
):
hard_conflicts.append('profile_header_signature_conflict')
elif header_result.state == 'mismatched' and signature and signature.get('table_patterns'):
# [STEP 1.1] 二次机会门禁:原始软分被词级原子互斥压到 0.35 以下的候选,
# 在「无必选锚点 + 别名契约可用」前提下用 canonical token 复用同一打分
# 逻辑重估一次(effective = max(原始, canonical)),使跨别名措辞不再被
# 第二道表头硬门禁误杀;不满足前提时 effective 即原始分,行为零变化。
effective_score = header_result.score
if header_result.score < 0.35 and enforce_header_atoms and header_to_field:
canonical_result = _score_header_semantic_position(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=False,
expected_tokens_override=schema_canonical_header_tokens(
_signature_identity_header_tokens(signature), header_to_field,
),
observed_tokens_override=schema_canonical_header_tokens(
[str(item) for item in observed.get('header_tokens') or []], header_to_field,
),
)
effective_score = max(effective_score, canonical_result.score)
if effective_score < 0.35:
hard_conflicts.append('profile_header_signature_conflict')
# [STEP 2] column_topology
column_result = _score_column_topology(signature=signature, observed=observed, profile=profile)
@@ -969,16 +1005,32 @@ def _score_header_semantic_position(
observed: dict[str, Any],
required_hits: list[bool],
enforce_atom_discriminator: bool = True,
expected_tokens_override: list[str] | None = None,
observed_tokens_override: list[str] | None = None,
) -> MatchDimensionResult:
"""比对真实表头 token、横向顺序和位置。
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
期望侧先截断单逻辑表头的折行副标签污染。
Args:
expected_tokens_override: 期望侧 token 覆盖(如 Schema 别名归一后的
canonical 序列);None 时按 `_signature_identity_header_tokens`
既有口径取值,行为不变。提供时软评分(含词命中率与顺序比)整体
切换到该序列上进行,供二次机会门禁复用同一套打分逻辑。
observed_tokens_override: 观测侧 token 覆盖(口径同上);None 时按
`observed['header_tokens']` 既有口径取值,行为不变。
"""
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
if expected_tokens_override is None:
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
else:
expected_tokens = [str(item).casefold() for item in expected_tokens_override]
if observed_tokens_override is None:
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
else:
observed_tokens = [str(item).casefold() for item in observed_tokens_override]
required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0
if not expected_tokens:
if not required_hits:
@@ -997,8 +1049,16 @@ def _score_header_semantic_position(
return MatchDimensionResult(state='mismatched', score=0.0)
matched = sum(1 for token in expected_tokens if token in observed_tokens)
token_ratio = matched / len(expected_tokens)
expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)]
observed_order = observed.get('header_tokens') or []
expected_order = (
expected_tokens
if expected_tokens_override is not None
else [str(item).casefold() for item in _signature_identity_header_order(signature)]
)
observed_order = (
observed_tokens
if observed_tokens_override is not None
else observed.get('header_tokens') or []
)
shared = [item for item in expected_order if item in observed_order]
order_ratio = 1.0
if len(shared) > 1:
@@ -1018,6 +1078,21 @@ def _score_header_semantic_position(
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
# 字段语义原子前缀:词级原子只含 [a-z0-9],不可能出现冒号,与前缀无碰撞空间。
_HEADER_FIELD_MARKER = 'field::'
def _header_normalized_words(text: str) -> list[str]:
"""
表头统一词管线:剥括号注记 → casefold → 去撇号 → 按非字母数字切分。
核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径
产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空,
调用方按各自的跳过策略处理)。
"""
normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold())
normalized = re.sub(r"['’]", '', normalized)
return [part for part in re.split(r'[^a-z0-9]+', normalized) if part]
def _sanitize_signature_table_identity(
@@ -1081,32 +1156,209 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时
仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。
核心逻辑:先拼接 token(让跨 token 空格切开的括号注记仍可整体剥除),再走
_header_normalized_words 统一词管线切词;过滤过短词与虚词。签名侧与运行时共用。
"""
joined = ' '.join(str(token) for token in tokens)
normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold())
normalized = re.sub(r"['’]", '', normalized)
atoms: set[str] = set()
for part in re.split(r'[^a-z0-9]+', normalized):
for part in _header_normalized_words(joined):
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
return frozenset(atoms)
def schema_canonical_header_atoms(
tokens: list[str],
header_to_field: dict[str, str] | None,
) -> frozenset[str]:
"""
将表头 token 按 Schema 别名归一为字段语义原子,供订单模板身份匹配跨别名对齐。
用途:同一业务字段在不同供应商模板中的表头措辞不同(如 Ship Date / Requested
Ship Date / 出货日期),词级原子只能字面碰撞;本函数借助 Schema 别名表把命中
别名的表头文本升级为 field::<field_code> 标记原子,使身份比较基于字段语义而非
具体措辞。未配置别名时零行为变化,完全退化为词级原子。
核心逻辑:
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险);
- 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold →
去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个
field_code 时整体弃用该短语——身份归属不允许歧义;
- 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出
field::<field_code> 原子(短语内单词不再残留);未命中的剩余单词沿用词级
原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS);
- 中文别名经词管线切词后为空词元组 → 自然跳过(有意行为):词级原子本就只
保留 [a-z0-9],中文措辞无法构成词级身份,语义升级依赖别名表配置英文别名。
Args:
tokens: 表头 token 列表(可为合并格长文案,如 "Requested Ship Date Unit
Price");空串/空白 token 会被跳过(吸收 MinerU 空格占位)。
header_to_field: TableHeaderContract.header_to_field(普通 dict[str, str],
key 为 Schema 别名的归一化表头文案,value 为 field_code);鸭子类型
消费,不引入 order_schema → matcher 反向依赖;None/空表示未配置。
Returns:
frozenset[str]:field::<field_code> 标记原子与词级原子的并集。
"""
if not header_to_field:
return _header_token_atoms(tokens)
# [STEP 1] 构建短语字典:别名 key → 词元组 → field_code;casefold 跨字段
# 碰撞的短语整体弃用(身份归属不允许歧义,宁缺勿错)。
grouped: dict[tuple[str, ...], dict[str, str]] = {}
for alias, field_code in header_to_field.items():
words = tuple(_header_normalized_words(alias))
if not words:
# 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。
continue
grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code))
phrase_to_field: dict[tuple[str, ...], str] = {
words: next(iter(codes.values()))
for words, codes in grouped.items()
if len(codes) == 1
}
# [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。
atoms: set[str] = set()
for token in tokens:
if not str(token).strip():
# 空串/纯空白 token(MinerU 空格占位)直接跳过。
continue
words = _header_normalized_words(token)
index = 0
while index < len(words):
match_end = 0
match_code = ''
# 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。
for end in range(len(words), index, -1):
code = phrase_to_field.get(tuple(words[index:end]))
if code is not None:
match_end = end
match_code = code
break
if match_end:
atoms.add(_HEADER_FIELD_MARKER + match_code)
index = match_end
continue
word = words[index]
if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS:
atoms.add(word)
index += 1
return frozenset(atoms)
def schema_canonical_header_tokens(
tokens: list[str],
header_to_field: dict[str, str] | None,
) -> list[str]:
"""
将表头 token 按 Schema 别名归一为序列语义的 canonical token 列表。
用途:供 `profile_header_signature_conflict` 二次机会门禁复用
`_score_header_semantic_position` 的既有软评分——词级互斥把跨别名措辞的
原始分压成 0 后,用本函数归一出的 canonical 序列重估一次,命中别名的片段
以统一的 field::<field_code> 标记项参与序列比较,实现跨措辞的软分 rescue。
与 `schema_canonical_header_atoms` 的关系:二者共用同一词管线
(`_header_normalized_words`)与同一贪心最长短语匹配口径、同一未命中词过滤,
但语义不同——atoms 是集合语义(去重、无序,供硬互斥集合全等比较),本函数
是序列语义(保序、允许重复,供软评分按序列比较)。二者各自独立实现,
不得互相调用/推导;同一输入下本函数结果去重即 atoms 结果(同源语义)。
核心逻辑:
- header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化);
- 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组,
同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义);
- 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个**
`field::<field_code>` 列表项(短语内单词不残留);未命中词按 atoms 同一
过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留;
- 空串/纯空白 token(MinerU 空格占位)跳过,与 atoms 口径一致。
Args:
tokens: 表头 token 列表(期望侧传 `_signature_identity_header_tokens`
的结果、观测侧传 `observed['header_tokens']`);可为合并格长文案。
header_to_field: TableHeaderContract.header_to_field(dict[str, str],
key 为 Schema 别名归一化表头文案、value 为 field_code);
None/空表示未配置。
Returns:
list[str]:canonical token 序列(保序、允许重复)。
"""
if not header_to_field:
return tokens
# [STEP 1] 短语字典:与 schema_canonical_header_atoms 完全同源的构建口径。
grouped: dict[tuple[str, ...], dict[str, str]] = {}
for alias, field_code in header_to_field.items():
words = tuple(_header_normalized_words(alias))
if not words:
# 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。
continue
grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code))
phrase_to_field: dict[tuple[str, ...], str] = {
words: next(iter(codes.values()))
for words, codes in grouped.items()
if len(codes) == 1
}
# [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项,
# 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。
canonical: list[str] = []
for token in tokens:
if not str(token).strip():
# 空串/纯空白 token(MinerU 空格占位)直接跳过。
continue
words = _header_normalized_words(token)
index = 0
while index < len(words):
match_end = 0
match_code = ''
# 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。
for end in range(len(words), index, -1):
code = phrase_to_field.get(tuple(words[index:end]))
if code is not None:
match_end = end
match_code = code
break
if match_end:
canonical.append(_HEADER_FIELD_MARKER + match_code)
index = match_end
continue
word = words[index]
if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS:
canonical.append(word)
index += 1
return canonical
def _header_discriminator_atoms_conflict(
*,
signature: dict[str, Any] | None,
observed: dict[str, Any],
header_to_field: dict[str, str] | None = None,
) -> bool:
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
"""
签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。
Args:
header_to_field: 可选 Schema 表头别名契约;非 None/非空时签名侧与观测侧
token 均先经 schema_canonical_header_atoms 归一为字段语义原子再比较
全等,使跨别名措辞(同字段不同表头文案)不再误判互斥;None/空时
两侧均走词级原子(既有行为,零变化)。
"""
if signature is None or not signature.get('table_patterns'):
return False
expected_tokens = _signature_identity_header_tokens(signature)
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if not expected_tokens or not observed_tokens:
return False
return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
if header_to_field:
expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field)
observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field)
else:
expected_atoms = _header_token_atoms(expected_tokens)
observed_atoms = _header_token_atoms(observed_tokens)
return expected_atoms != observed_atoms
def _score_column_topology(
@@ -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']
@@ -0,0 +1,290 @@
"""
backend/app/services/shipping_notice/done_line_report.py
用途:「我的待办」已完成(已核验上传成功)发货通知的平铺明细行报表读模型与专用导出。
依赖:query_service 的可见性与上传成功口径(_visible_tasks_query_for_todos /
_verified_upload_success_sql_expr);shipping_order_snapshot 冻结快照。
逻辑:Notice(uploaded) → OT → Snapshot → SnapshotLine 展开为标准 12 字段行;页面另附
OT/business 编号列便于溯源,导出严格 12 列不落编号。已用数量 / open_qty 当前无
数据源,契约占位为 None(前端与 Excel 均留空)。约定出货日期取行级 required_date
(field_values_json),缺失时回退快照表头 typed 列;订单单号取表头
source_order_number(field_id 键)。支持 客户 / 料号 / 发货通知日期(Notice
创建日期)筛选,按明细行分页;导出复用同一查询,行数受 DONE_LINE_EXPORT_LIMIT 防护。
"""
from __future__ import annotations
from datetime import date, datetime, time
from io import BytesIO
from typing import Any
from zoneinfo import ZoneInfo
from openpyxl import Workbook
from sqlalchemy import asc, desc
from app import db
from app.core.errors import ValidationError
from app.models import (
ShippingNotice,
ShippingOrderField,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
)
from app.services.shipping_notice.query_service import (
_verified_upload_success_sql_expr,
_visible_tasks_query_for_todos,
)
# 导出防护上限:超出即截断(明细行报表场景远低于该量级)。
DONE_LINE_EXPORT_LIMIT = 10000
# 导出固定 12 列中文表头;顺序即业务标准格式,OT 编号不落列。
DONE_REPORT_HEADERS: tuple[str, ...] = (
"客户", "客户编号", "订单日期", "订单项次", "料号", "数量",
"约定出货日期", "客户PO", "已用数量", "open qty", "订单单号", "单价",
)
def _parse_notice_date(value: Any, *, label: str) -> date:
"""解析 YYYY-MM-DD 日期参数;非法输入抛 ValidationError,禁止静默吞掉。"""
text = str(value or '').strip()
if not text:
raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID')
try:
return datetime.strptime(text[:10], '%Y-%m-%d').date()
except ValueError as exc:
raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID') from exc
def _done_lines_query(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
):
"""
构造已完成通知明细行的联表查询(Notice → OT → Snapshot → SnapshotLine)。
核心逻辑:仅取已核验上传成功的正式 Notice;可见性复用待办口径(非管理员仅创建者);
客户按快照 客户名称/客户编号 模糊、料号按 行料号/客户料号 模糊、发货通知日期按
Notice created_at 自然日闭区间过滤。
Raises:
ValidationError: 日期参数非法。
"""
q = (
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(_verified_upload_success_sql_expr())
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderSnapshot, ShippingOrderSnapshot.task_id == ShippingOrderTask.id)
.join(ShippingOrderSnapshotLine, ShippingOrderSnapshotLine.snapshot_id == ShippingOrderSnapshot.id)
)
customer_needle = str(customer or '').strip()
if customer_needle:
like = f"%{customer_needle}%"
q = q.filter(
db.or_(
ShippingOrderSnapshot.customer_name.ilike(like),
ShippingOrderSnapshot.customer_code.ilike(like),
)
)
part_needle = str(part_number or '').strip()
if part_needle:
like = f"%{part_needle}%"
q = q.filter(
db.or_(
ShippingOrderSnapshotLine.part_number.ilike(like),
ShippingOrderSnapshotLine.customer_part_number.ilike(like),
)
)
if notice_date_from:
from_day = notice_date_from if isinstance(notice_date_from, date) else _parse_notice_date(notice_date_from, label='notice_date_from')
q = q.filter(ShippingNotice.created_at >= datetime.combine(from_day, time.min))
if notice_date_to:
to_day = notice_date_to if isinstance(notice_date_to, date) else _parse_notice_date(notice_date_to, label='notice_date_to')
q = q.filter(ShippingNotice.created_at <= datetime.combine(to_day, time.max))
return q
def _report_field_ids() -> dict[tuple[str, str], str]:
"""读取报表所需的标准字段资产 id(field_code+scope 唯一),供 JSON 值回源。"""
rows = ShippingOrderField.query.filter(
ShippingOrderField.field_code.in_(('required_date', 'source_order_number')),
ShippingOrderField.status == 'active',
).all()
return {(row.field_code, row.scope): str(row.id) for row in rows}
def _date_text(value: Any) -> str | None:
"""日期值统一为 YYYY-MM-DD 文本;date 对象取日期部分,字符串截前十位。"""
if value in (None, ''):
return None
if hasattr(value, 'isoformat'):
return str(value.isoformat())[:10]
text = str(value).strip()
return text[:10] or None
def _num_text(value: Any) -> float | None:
"""数量/单价序列化为 JSON number;缺失返回 None(禁止 0 冒充)。"""
if value in (None, ''):
return None
return float(value)
def _serialize_done_line(
notice: ShippingNotice,
snapshot: ShippingOrderSnapshot,
line: ShippingOrderSnapshotLine,
field_ids: dict[tuple[str, str], str],
) -> dict[str, Any]:
"""按标准 12 字段 + 溯源编号序列化一行明细;无数据源字段契约留空。"""
required_date_field_id = field_ids.get(('required_date', 'line'))
required_date = (
(line.field_values_json or {}).get(required_date_field_id)
if required_date_field_id else None
)
if required_date in (None, ''):
required_date = snapshot.required_date
source_order_field_id = field_ids.get(('source_order_number', 'header'))
source_order_number = (
(snapshot.header_values_json or {}).get(source_order_field_id)
if source_order_field_id else None
)
return {
# 溯源编号:仅页面展示,导出不落列。
'task_no': notice.task_no,
'business_no': notice.business_no,
# 标准 12 字段。
'customer_name': snapshot.customer_name,
'customer_code': snapshot.customer_code,
'order_date': _date_text(snapshot.order_date),
'line_no': line.line_no,
'part_number': line.part_number,
'qty': _num_text(line.qty),
'required_date': _date_text(required_date),
'customer_po_number': snapshot.customer_po_number,
'used_qty': None,
'open_qty': None,
'source_order_number': source_order_number,
'unit_price': _num_text(line.unit_price),
}
def list_done_notice_lines(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
"""
分页列出已完成通知的平铺明细行(跨 Notice 混排,不按 OT 聚合)。
Returns:
{items, page, page_size, total};item 结构见 _serialize_done_line。
"""
normalized_page = max(1, int(page))
normalized_page_size = max(1, min(int(page_size), 100))
q = _done_lines_query(
user_id,
is_admin=is_admin,
customer=customer,
part_number=part_number,
notice_date_from=notice_date_from,
notice_date_to=notice_date_to,
)
total = int(q.count())
field_ids = _report_field_ids()
items: list[dict[str, Any]] = []
if total:
offset = (normalized_page - 1) * normalized_page_size
rows = (
q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine)
.order_by(
desc(ShippingNotice.created_at), desc(ShippingNotice.id),
asc(ShippingOrderSnapshotLine.position),
)
.offset(offset)
.limit(normalized_page_size)
.all()
)
items = [
_serialize_done_line(notice, snapshot, line, field_ids)
for notice, snapshot, line in rows
]
return {
'items': items,
'page': normalized_page,
'page_size': normalized_page_size,
'total': total,
}
def build_done_lines_xlsx(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
) -> tuple[BytesIO, str]:
"""
按当前筛选生成标准 12 列明细 Excel(不落 OT 编号列),返回流与下载文件名。
核心逻辑:与列表同源查询、不分页;超过 DONE_LINE_EXPORT_LIMIT 截断并在文件名
带时间戳,避免同日下载互相覆盖。单元格空值写 None(留空),禁止以 0 伪装。
"""
q = _done_lines_query(
user_id,
is_admin=is_admin,
customer=customer,
part_number=part_number,
notice_date_from=notice_date_from,
notice_date_to=notice_date_to,
)
rows = (
q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine)
.order_by(
desc(ShippingNotice.created_at), desc(ShippingNotice.id),
asc(ShippingOrderSnapshotLine.position),
)
.limit(DONE_LINE_EXPORT_LIMIT)
.all()
)
field_ids = _report_field_ids()
workbook = Workbook()
sheet = workbook.active
sheet.title = '通知明细'
sheet.append(list(DONE_REPORT_HEADERS))
for notice, snapshot, line in rows:
item = _serialize_done_line(notice, snapshot, line, field_ids)
sheet.append([
item['customer_name'],
item['customer_code'],
item['order_date'],
item['line_no'],
item['part_number'],
item['qty'],
item['required_date'],
item['customer_po_number'],
item['used_qty'],
item['open_qty'],
item['source_order_number'],
item['unit_price'],
])
buffer = BytesIO()
workbook.save(buffer)
buffer.seek(0)
stamp = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d_%H%M%S')
filename = f'done-lines-{stamp}.xlsx'
return buffer, filename
+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,
@@ -569,7 +569,7 @@ def _trigger_freight_upload_rpa(
timeout = _rpa_upload_timeout_seconds()
set_task_step_progress(
task,
step_key='step7_upload_freight',
stage="freight_uploading",
step_title='上传货代',
status='running',
message=t('workflow.fulfillment.upload_triggered_wait', lang=lang),
@@ -1249,7 +1249,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
line_result_status = str(match_payload.get('match_status') or 'unfulfillable')
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1639,7 +1639,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1731,7 +1731,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
**_match_step_progress_fields(
match_status=match_status,
@@ -1810,7 +1810,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1867,7 +1867,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
**_match_step_progress_fields(
match_status=match_status,
@@ -2066,7 +2066,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step6_generate_file",
stage="excel_generating",
step_title="生成发货文件",
status="running",
message=t("workflow.fulfillment.generate_running", lang=lang),
@@ -2120,7 +2120,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
_clear_notice_invalidated_from_stage(task)
set_task_step_progress(
task,
step_key="step6_generate_file",
stage="excel_generating",
step_title="生成发货文件",
status="completed",
message=t("workflow.fulfillment.generate_completed", lang=lang),
@@ -2451,7 +2451,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
_close_uploaded_task(task, actor_type='rpa', actor_id=None)
set_task_step_progress(
task,
step_key="step7_upload_freight",
stage="freight_uploading",
step_title="上传货代",
status="completed",
message=t("workflow.fulfillment.rpa_uploaded", lang=lang),
@@ -2507,7 +2507,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
set_task_step_progress(
task,
step_key="step7_upload_freight",
stage="freight_uploading",
step_title="上传货代",
status="needs_human",
message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang),
@@ -2527,7 +2527,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
set_task_step_progress(
task,
step_key="step7_upload_freight",
stage="freight_uploading",
step_title="上传货代",
status="needs_human",
message=t("workflow.fulfillment.upload_failed_wait_manual", lang=lang),
@@ -2,6 +2,8 @@
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据。
逻辑:只读取 Candidate 所属 Extraction 的 accepted/corroborated Header FieldValue;站点候选不反向确认客户主体。
客户命中分三层:canonical 等值 > 完整包含(指纹整体出现在提取值中)> 截断包含(仅人工建议);
邮箱/域名指纹只做精确等值,禁止包含比较。
"""
from __future__ import annotations
@@ -23,12 +25,14 @@ from app.models import (
ShippingOrderSchemaVersion,
)
from app.services.shipping_notice.customer_normalization import (
normalize_customer_name,
normalize_domain,
normalize_email,
IDENTITY_MATCH_EQUALITY,
IDENTITY_MATCH_TIER_RANK,
canonical_identity_key,
classify_identity_containment,
normalize_identity_evidence_value,
)
RESOLUTION_VERSION = 'shadow-v2'
RESOLUTION_VERSION = 'shadow-v3'
ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
@@ -37,14 +41,11 @@ def _normalize(definition: dict[str, Any], value: object) -> str | None:
try:
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
if source.get('option_key') == 'from_email':
return normalize_email(value)
if source.get('option_key') == 'from_domain':
return normalize_domain(value)
if field_config.get('normalizer_key') == 'name':
return normalize_customer_name(value) or None
normalized = str(value or '').strip().upper()
return normalized or None
return normalize_identity_evidence_value(
value,
option_key=source.get('option_key'),
normalizer_key=field_config.get('normalizer_key'),
)
except Exception:
return None
@@ -154,6 +155,8 @@ def _source_evidence(
normalized = _normalize(definition, value)
if not normalized:
continue
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
evidence.append({
'definition_id': definition_id,
'definition_code': code,
@@ -161,6 +164,8 @@ def _source_evidence(
'target_type': definition.get('target_type'),
'raw_value': value,
'normalized_value': normalized,
# 供命中分级使用:邮箱/域名指纹只做精确等值,不参与包含比较。
'option_key': str(context_source.get('option_key') or ''),
'weight': int(definition.get('default_weight') or 0),
'source': source,
})
@@ -178,27 +183,68 @@ def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons
}
def _classify_evidence_match(
*, runtime_value: str, evidence_value: str, option_key: str,
) -> str | None:
"""
对单个已审核证据做命中分级:等值 > 完整包含 > 截断包含。
核心逻辑:邮箱/域名指纹语义字符(@、.)参与构成身份,只做归一化后精确等值;
文本类指纹先比 canonical 等值(吸收标点/空白/大小写差异),再判双向包含。
"""
if option_key in {'from_email', 'from_domain'}:
return IDENTITY_MATCH_EQUALITY if runtime_value == evidence_value else None
if canonical_identity_key(runtime_value) == canonical_identity_key(evidence_value):
return IDENTITY_MATCH_EQUALITY
return classify_identity_containment(runtime_value, evidence_value, option_key=option_key)
def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。"""
"""
按同定义已审核证据聚合客户候选,附命中层级;禁止排序取首条抹平歧义。
核心逻辑:每个(运行时证据, 注册证据)对先分级;同一客户取其最强命中层级,
排序先按层级升序(等值候选始终排在包含候选前),再按累计权重降序。
顶层(最强层级)候选唯一时调用方才判 unique_candidate,多家并列即 ambiguous。
"""
scores: dict[int, float] = defaultdict(float)
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
tiers: dict[int, str] = {}
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
for item in evidence:
if item['target_type'] != 'customer':
continue
records = ShippingIdentityEvidence.query.filter_by(
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
definition_id=item['definition_id'], status='approved',
).all()
for record in records:
customer = customers.get(record.customer_id) if record.customer_id is not None else None
if customer is None:
continue
match_kind = _classify_evidence_match(
runtime_value=str(item['normalized_value'] or ''),
evidence_value=str(record.normalized_value or ''),
option_key=str(item.get('option_key') or ''),
)
if match_kind is None:
continue
scores[customer.id] += item['weight']
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
return sorted(
[_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) for customer_id, score in scores.items()],
key=lambda item: (-float(item['score']), int(item['customer_id'])),
)
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': match_kind})
if customer.id not in tiers or IDENTITY_MATCH_TIER_RANK[match_kind] < IDENTITY_MATCH_TIER_RANK[tiers[customer.id]]:
tiers[customer.id] = match_kind
ranked = [
_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id])
for customer_id, score in scores.items()
]
# 客户最强层级在聚合后补写,再按(层级, 权重, 客户 ID)排序。
for item in ranked:
item['match_kind'] = tiers[int(item['customer_id'])]
ranked.sort(key=lambda item: (
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])],
-float(item['score']),
int(item['customer_id']),
))
return ranked
def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -252,11 +298,20 @@ def resolve_candidate_identity(candidate: ShippingOrderCandidate, intake: Shippi
evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake)
customer_matches = _rank_customer_matches(evidence)
site_matches = _rank_site_matches(evidence)
top_score = float(customer_matches[0]['score']) if customer_matches else None
tied = [item for item in customer_matches if float(item['score']) == top_score] if top_score is not None else []
# [STEP] 顶层 = 候选中的最强命中层级;仅顶层唯一才 unique_candidate,
# 强层级唯一时弱层级候选仅作展示,不参与歧义计算。
top_tier_candidates: list[dict[str, Any]] = []
if customer_matches:
top_tier_rank = min(
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] for item in customer_matches
)
top_tier_candidates = [
item for item in customer_matches
if IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] == top_tier_rank
]
return {
'resolution_version': RESOLUTION_VERSION,
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous',
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(top_tier_candidates) == 1 else 'ambiguous',
'evidence': evidence,
'customer_matches': customer_matches,
'site_matches': site_matches,
@@ -695,7 +695,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message="本批库存快照已确认,等待匹配库存",
@@ -101,7 +101,7 @@ def inventory_loaded_response(
)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="completed",
message=f"已载入库存 {len(inventory_lines)} 行",
@@ -1212,7 +1212,7 @@ def ensure_inventory_via_rpa(
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='running',
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
@@ -1240,7 +1240,7 @@ def ensure_inventory_via_rpa(
poll_read_only = not allow_auto_retry
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='needs_human',
message='库存 RPA 未能为全部库存源生成结果。',
@@ -1353,7 +1353,7 @@ def ensure_inventory_via_rpa(
)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message=progress_message,
@@ -1403,7 +1403,7 @@ def ensure_inventory_via_rpa(
_set_workflow_error(task, human_message[:500])
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=human_message,
@@ -1553,7 +1553,7 @@ def _handle_rpa_inventory_skipped(
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message="货代系统当前无可用库存",
@@ -1600,7 +1600,7 @@ def _handle_rpa_inventory_failed(
})
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='needs_human',
message=_workflow_error(task),
@@ -1950,7 +1950,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
}
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message="RPA 库存文件已返回,正在读取库存快照",
@@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block(
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='needs_human',
message=t('workflow.inventory.unavailable', lang=lang),
@@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
try:
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message=t("workflow.inventory.uploading", lang=lang),
@@ -461,7 +461,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task.error_message = None
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message="已触发库存获取,等待各库存源回调。",
@@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message="库存 RPA 未能为全部库存源生成结果。",
@@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -5,7 +5,7 @@ services/shipping_notice/lifecycle_projection.py
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
[B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
兜底;无正式事实时保持未分类。兼容 OT.stage 上残留的 step_key 别名。
兜底;无正式事实时保持未分类。
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
"""
@@ -75,11 +75,6 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
'freight_uploading': 'freight_upload',
'manual_upload_handoff': 'freight_upload',
'completed': 'upload_complete',
# 历史 step_key 曾被误写入 OT.stage;投影只读别名,避免工作台掉回接收解析空白页。
'step5_match_inventory': 'fulfillment_prep',
'step6_generate_file': 'fulfillment_prep',
'step3_inventory_prepare': 'fulfillment_prep',
'step7_upload_freight': 'freight_upload',
}
def lifecycle_entries(
@@ -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),
}
@@ -30,6 +30,7 @@ from app.services.shipping_notice import order_document_profile_lease_service as
from app.services.shipping_notice import order_document_profile_service as profile_service
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.document_layout.order_profile_signature import (
LAYOUT_SIGNATURE_ID,
MATCHER_POLICY_ID,
@@ -1235,6 +1236,15 @@ def _build_coordinate_overlap_evidence(
definition = dict(profile.definition_json or {})
thresholds = _match_thresholds(definition)
schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {}
try:
header_to_field = compile_table_header_contract(
schema_definition if isinstance(schema_definition, dict) else {},
).header_to_field
except ValidationError:
# 冻结 Schema definition 非法(别名碰撞等)时容忍降级:None 使 overlap
# 证据的表头原子互斥退化为词级原子,不阻断模板验证;空 definition 编译
# 出空映射,matcher 侧与 None 同口径。
header_to_field = None
published = published_rival_snapshots_for_overlap(profile)
candidates = [draft_snapshot, *published]
sample_role_pollution = _detect_sample_role_pollution(profile)
@@ -1243,7 +1253,9 @@ def _build_coordinate_overlap_evidence(
outcomes: list[dict[str, Any]] = []
for sample in samples:
layout = _load_sample_layout(sample)
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
match = match_frozen_coordinate_profiles(
profiles=candidates, layout=layout, header_to_field=header_to_field,
)
parse_result = None
if match.profile_code == profile.profile_code and int(match.version or 0) == int(profile.version):
if parse_result_resolver is not None:
@@ -1296,7 +1308,9 @@ def _build_coordinate_overlap_evidence(
'reason_code': 'representative_layout_unavailable',
})
continue
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
match = match_frozen_coordinate_profiles(
profiles=candidates, layout=layout, header_to_field=header_to_field,
)
source_unique = (
match.status in {'unique_match', 'selected_by_score'}
and match.profile_code == published_snapshot.get('profile_code')
@@ -56,6 +56,7 @@ from app.models import (
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
from app.services.shipping_notice.order_extraction_route_contract import (
PARSER_ENGINE_VERSION,
PARSER_POLICY_VERSION,
@@ -697,6 +698,16 @@ def _load_intakes(
return rows
def _intake_filenames(intakes: list[ShippingOrderIntake]) -> list[str]:
"""按 Intake 顺序取资产原始文件名;无资产或资产缺失以空串占位,保持计数口径。"""
asset_ids = [int(intake.asset_id) for intake in intakes if intake.asset_id]
if not asset_ids:
return []
rows = db.session.query(FileAsset.id, FileAsset.original_filename).filter(FileAsset.id.in_(asset_ids)).all()
filename_by_id = {row[0]: str(row[1] or '') for row in rows}
return [filename_by_id.get(int(intake.asset_id), '') for intake in intakes if intake.asset_id]
def _resolve_conversation(
*,
user_id: int,
@@ -713,6 +724,7 @@ def _resolve_conversation(
intakes: 已按用户锁定且通过业务资格校验的 Intake。
Returns:
已存在或本事务新建的 ChatSession;调用方负责最终提交。
新建会话的 title 由 conversation_title 按首个 Intake 文件名派生;已存在会话不改动标题。
Raises:
ConflictError: 所选 Intake 已分属不同会话,或与显式会话不一致。
"""
@@ -737,7 +749,7 @@ def _resolve_conversation(
session_id=uuid.uuid4().hex,
user_id=user_id,
agent_id=agent_id,
title='订单抽取',
title=derive_order_extraction_title(_intake_filenames(intakes), datetime.utcnow()),
status='running',
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
@@ -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,
)
@@ -1071,7 +1072,12 @@ def _profile_table_candidates(
'issues': ['order_profile_selected_identity_invalid'], 'match': profile_match,
}
else:
match = match_frozen_coordinate_profiles(profiles=coordinate_profiles, layout=layout)
# 主路由匹配与下游表格解析共用同一冻结 Schema 表头契约:matcher 侧
# 表头原子互斥按别名归一为字段语义原子,跨措辞近亲模板不误杀。
match = match_frozen_coordinate_profiles(
profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field,
)
affinity_applied = False
if not match_only:
match = _apply_parse_validation_gate(
@@ -1542,9 +1548,8 @@ def _apply_reparse_profile_affinity(
), None)
if candidate is None:
return match, False
verified = match_frozen_coordinate_profiles(profiles=[frozen], layout=layout)
if verified.status != 'unique_match':
return match, False
# 契约编译须先于复验:复验与解析验证消费同一份冻结 Schema definition,
# 表头原子互斥才能与正式取值走同一别名口径。
schema_snapshot = (
run.input_snapshot_json.get('schema')
if isinstance(getattr(run, 'input_snapshot_json', None), dict)
@@ -1555,6 +1560,18 @@ def _apply_reparse_profile_affinity(
if isinstance(schema_snapshot, dict) and isinstance(schema_snapshot.get('definition'), dict)
else {}
)
try:
header_to_field = compile_table_header_contract(schema_definition).header_to_field
except ValidationError:
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
# 词级原子,不阻断重识别亲和性;definition 为空时编译结果为空映射,
# matcher 侧与 None 同口径。
header_to_field = None
verified = match_frozen_coordinate_profiles(
profiles=[frozen], layout=layout, header_to_field=header_to_field,
)
if verified.status != 'unique_match':
return match, False
parse_result = validate_profile_parse_candidate(
profile_snapshot=frozen,
layout=layout,
@@ -2090,14 +2107,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 +2378,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 +2420,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 +2432,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'] = [
@@ -2540,7 +2583,15 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
layout = ensure_on_demand_coordinate_evidence(
document=document_model, layout=layout, page_nos=required_pages,
)
match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
try:
header_to_field = compile_table_header_contract(definition).header_to_field
except ValidationError:
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
# 词级原子,confirmed 字段锁集返回空,不抛错。
header_to_field = None
match = match_frozen_coordinate_profiles(
profiles=profiles, layout=layout, header_to_field=header_to_field,
)
match, _affinity_applied = _apply_reparse_profile_affinity(
run=run, unit=unit, profiles=profiles, match=match, layout=layout,
)
@@ -258,19 +258,26 @@ def retry_review_case_customer_resolution(
case = _load_writable_case(user_id=user_id, case_no=case_no)
matches: list[dict[str, Any]] = []
if case.candidate_id:
from app.services.shipping_notice.customer_auto_resolution import (
AUTO_CONFIRM_ELIGIBLE_STATUSES,
resolve_auto_customer_decision,
)
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if candidate is not None:
shadow = refresh_candidate_shadow_resolution(candidate)
# [STEP 2] 重新识别后若客户指纹唯一命中,直接写入确认结果;投影函数保持纯读。
# [STEP 2] 重新识别后与任务期协调器共用同一分级裁决:canonical 等值唯一或
# 「指纹完整出现」包含唯一且证据授权才自动确认;截断建议(containment_weak)
# 只进候选展示,绝不在此确认。投影函数保持纯读。
decision = resolve_auto_customer_decision(shadow)
if (
shadow.status == 'unique_candidate'
and shadow.top_customer_id
str(decision.get('status') or '') in AUTO_CONFIRM_ELIGIBLE_STATUSES
and decision.get('customer_id') is not None
and not resolve_review_case_customer_resolved(case=case, candidate=candidate)
):
confirm_customer_resolution(
candidate,
customer_id=int(shadow.top_customer_id),
customer_id=int(decision['customer_id']),
actor_id=None,
method='auto_rule',
reason='客户识别指纹唯一命中自动确认',
@@ -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}
@@ -260,25 +260,27 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
return ('completed', 'completed')
if ps in {'waiting_upload', 'upload_failed', 'uploading'} or projected_upload == 'uploading':
return ('automating', 'freight_uploading')
if 'upload' in step or step.startswith('step7'):
# [契约唯一] current_step 只存 15 阶契约码(CheckPoint stepN_* 遗留键已清除),
# 阶段信号按契约码精确匹配,不再做子串/前缀启发式。
if step == 'freight_uploading':
return ('automating', 'freight_uploading')
if ps in {'export', 'excel', 'generating_excel'} or 'generate' in step or step.startswith('step6'):
if ps in {'export', 'excel', 'generating_excel'} or step == 'excel_generating':
return ('automating', 'excel_generating')
if ps == 'matched' and export_path:
return ('automating', 'excel_generating')
if ps in {'matching', 'inventory_ready', 'matched'} or 'match' in step:
if ps in {'matching', 'inventory_ready', 'matched'} or step == 'inventory_matching':
return ('automating', 'inventory_matching')
# 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。
if ps in {'waiting_inventory', 'parsed'} or 'fetch' in step or step.startswith('step4'):
if ps in {'waiting_inventory', 'parsed'} or step == 'inventory_fetching':
return ('automating', 'inventory_fetching')
if ps == 'pending_review':
return ('waiting_review', 'waiting_review')
if ps in {'creating', 'order_creating', 'confirming'} or 'create' in step or step.startswith('step3'):
if ps in {'creating', 'order_creating', 'confirming'} or step == 'order_creating':
return ('automating', 'order_creating')
if ps in {'fetching_inventory', 'inventory_fetching'}:
return ('automating', 'inventory_fetching')
@@ -687,13 +689,8 @@ _USER_STAGE_TO_CODE: dict[str, str] = {
'waiting_review': 'waiting_human_review',
'inventory_fetching': 'inventory_fetch',
'inventory_matching': 'inventory_match',
# step_key 误写入 OT.stage 时的只读别名(与 lifecycle_projection 同源)。
'step5_match_inventory': 'inventory_match',
'step3_inventory_prepare': 'inventory_fetch',
'step6_generate_file': 'excel_generate',
'excel_generating': 'excel_generate',
'freight_uploading': 'freight_upload',
'step7_upload_freight': 'freight_upload',
'completed': 'completed',
'failed': 'failed_terminal',
'cancelled': 'cancelled',
@@ -88,6 +88,13 @@ from app.services.shipping_notice.constants import (
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGE_BY_GATE,
LIFECYCLE_STAGE_BY_PROCESSING_STAGE,
)
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_REASON_OWNING_GATE,
)
from app.services.shipping_notice.state_machine import (
UserMode,
resolve_task_ui_state,
@@ -132,6 +139,17 @@ _TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
"done": frozenset({"done"}),
}
# 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」属 done 桶终态,不做筛选维度。
_ACTIONABLE_TODO_STAGES: tuple[str, ...] = (
"intake_parse", "order_review", "fulfillment_prep", "freight_upload",
)
# 无 processing_stage 且人工原因不可映射时的 todo_category 粗兜底(与 Gate 映射语义对齐)。
_TODO_STAGE_BY_CATEGORY_FALLBACK: dict[str, str] = {
"review": "order_review",
"exception": "fulfillment_prep",
"manual_upload": "freight_upload",
}
# 尚未挂 OT、仍需用户/系统关注的 Intake 解析状态(进入我的待办)。
_ORPHAN_INTAKE_TODO_PARSE_STATUSES = frozenset({
"created",
@@ -2762,12 +2780,14 @@ def _todo_tasks_base_query(
customer_needle: str,
customer_like: str,
task_no: str | None,
terminal_kind: str | None = None,
):
"""
构造带精确 category CASE 过滤的 Task 待办查询。
核心逻辑:可见性 / 客户过滤后,用 _task_todo_category_sql_expr().in_(allowed);
done 桶另加终态粗筛。pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
done 桶另加终态粗筛;terminal_kind 进一步拆分 done 子视图(通知完成 / 驳回作废)。
pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
"""
q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
@@ -2817,6 +2837,17 @@ def _todo_tasks_base_query(
),
)
)
# [STEP] 终态子视图过滤:前端「通知完成 / 复核驳回·已作废」子 tab 各取所需;
# 口径与分类 CASE 的 done 分支保持一致(上传成功优先,二者互斥)。
if terminal_kind == "upload_complete":
q = q.filter(upload_success)
elif terminal_kind == "reject_void":
q = q.filter(
db.or_(
workflow_review_status == RS_REJECTED,
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
)
)
return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed))))
@@ -2825,6 +2856,108 @@ def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
def _classify_todo_lifecycle_stage(
category: str,
*,
pending_human_reason: Any = None,
processing_stage: Any = None,
) -> str | None:
"""
按统一生命周期口径归类待办条目的阶段 tab(仅供计数,不替代 ui_state)。
核心逻辑:与 ``project_lifecycle`` 同优先级——processing_stage 权威 → 人工原因
归属 Gate 兜底 → todo_category 粗兜底;结果若不是四个可动作阶段(如 completed
映射出的 upload_complete)则返回 None,由调用方跳过,避免污染阶段 tab 计数。
Args:
category: 待办分类 CASE 结果(review/exception/manual_upload/in_progress)。
pending_human_reason: OT ``pending_human_reason`` 人工原因码(可空)。
processing_stage: OT ``stage`` 已持久化处理阶段(可空)。
Returns:
四个可动作阶段码之一;不可归入时 None。
"""
stage_key = str(processing_stage or '').strip().lower()
if stage_key in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[stage_key]
else:
gate = PROCESS_GATE_REASON_OWNING_GATE.get(str(pending_human_reason or '').strip())
if gate in LIFECYCLE_STAGE_BY_GATE:
stage = LIFECYCLE_STAGE_BY_GATE[gate]
else:
stage = _TODO_STAGE_BY_CATEGORY_FALLBACK.get(str(category or ''), 'fulfillment_prep')
return stage if stage in _ACTIONABLE_TODO_STAGES else None
def _my_todo_stage_counts(user_id: int, *, is_admin: bool) -> dict[str, int]:
"""
统计待处理桶在四个可动作阶段的分布,供前端阶段筛选 tab 展示全量计数。
核心逻辑:Review Case 走统一生命周期投影(候选有效性裁决 接收解析 vs 订单复核);
孤儿 Intake 恒为接收解析;Notice / OT 分支一次取回「分类 CASE + OT stage +
人工原因」后在 Python 侧归类,避免为计数复制一份 SQL 阶段状态机。
Returns:
{intake_parse, order_review, fulfillment_prep, freight_upload}(含 0 值键)。
"""
counts: dict[str, int] = {code: 0 for code in _ACTIONABLE_TODO_STAGES}
def _bump(stage: str | None) -> None:
if stage in counts:
counts[str(stage)] += 1
# [STEP 1] 开放 Review Case:复用统一投影,禁止另写候选有效性判断。
for case_row in _visible_open_review_cases_query(user_id, is_admin=is_admin).all():
projection = _review_case_lifecycle_projection(case_row)
_bump(str(projection.get('lifecycle_stage') or '').strip() or None)
# [STEP 2] 孤儿 Intake(未建 OT 的解析待办)恒为接收解析。
counts["intake_parse"] += int(
_visible_orphan_intakes_query(user_id, is_admin=is_admin).count()
)
# [STEP 3] Notice 分支:分类 CASE 直接作为列取回,连同 OT stage / 人工原因归类。
category_expr = _task_todo_category_sql_expr()
ot_stage_subquery = select(ShippingOrderTask.stage).where(
ShippingOrderTask.id == ShippingNotice.order_task_id,
).scalar_subquery()
ot_reason_subquery = select(ShippingOrderTask.pending_human_reason).where(
ShippingOrderTask.id == ShippingNotice.order_task_id,
).scalar_subquery()
notice_rows = (
_active_todo_tasks_scope(user_id, is_admin=is_admin)
.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
.with_entities(
category_expr.label("category"),
ot_stage_subquery.label("ot_stage"),
ot_reason_subquery.label("ot_reason"),
)
.all()
)
for category, ot_stage, ot_reason in notice_rows:
_bump(_classify_todo_lifecycle_stage(
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
))
# [STEP 4] OT 分支(库存准备尚未建正式 Notice)同理。
ot_category_expr = _order_task_todo_category_sql_expr()
ot_rows = (
_visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(ot_category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
.with_entities(
ot_category_expr.label("category"),
ShippingOrderTask.stage.label("ot_stage"),
ShippingOrderTask.pending_human_reason.label("ot_reason"),
)
.all()
)
for category, ot_stage, ot_reason in ot_rows:
_bump(_classify_todo_lifecycle_stage(
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
))
return counts
def list_my_todos(
user_id: int,
*,
@@ -2835,6 +2968,7 @@ def list_my_todos(
todo_category: str | None = None,
customer: str | None = None,
task_no: str | None = None,
terminal_kind: str | None = None,
) -> dict[str, Any]:
"""
分页列出「我的待办」:建单前 Review Case + 未建 OT Intake + 建单后 Task。
@@ -2851,6 +2985,7 @@ def list_my_todos(
todo_category: 可选细分类覆盖 bucket。
customer: 客户名/代码/来源文件名/Case 号/PO/Intake 号模糊过滤。
task_no: 精确任务号过滤(仅 Task 项;复核/Intake 项忽略)。
terminal_kind: done 桶终态子视图过滤(upload_complete | reject_void);其余 bucket 忽略。
Returns:
{items, page, page_size, total}
@@ -2869,6 +3004,7 @@ def list_my_todos(
customer_like = f"%{customer_needle}%" if customer_needle else ""
include_review_cases = "review" in allowed and not task_no
include_orphan_intakes = "intake_parse" in allowed and not task_no
normalized_terminal_kind = str(terminal_kind or "").strip().lower() or None
# [STEP 1] 多端投影为统一列:kind / entity_id / sort_at / sort_ref。
branches = []
@@ -2915,6 +3051,7 @@ def list_my_todos(
customer_needle=customer_needle,
customer_like=customer_like,
task_no=task_no,
terminal_kind=normalized_terminal_kind,
)
branches.append(
tasks_q.with_entities(
@@ -3053,14 +3190,17 @@ def list_my_todos(
}
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]:
"""
统计「我的待办」各 bucket 数量,供导航徽标使用。
统计「我的待办」各 bucket 数量,供导航徽标与阶段筛选 tab 使用。
核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT。
核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT;
阶段 tab 计数与 done 终态拆分见 _my_todo_stage_counts / done_counts 组装。
Returns:
{pending, processing, done, total_pending_badge}
{pending, processing, done, total_pending_badge,
stage_counts: {intake_parse, order_review, fulfillment_prep, freight_upload},
done_counts: {upload_complete, reject_void}}
"""
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
@@ -3077,7 +3217,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))).count()
processing = active.filter(category_expr == "in_progress").count()
processing += ot_active.filter(ot_category == "in_progress").count()
done = (
done_base = (
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(
db.or_(
@@ -3091,11 +3231,19 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
)
)
.filter(category_expr == "done")
.count()
)
done = done_base.count()
# done 拆分:已核验上传成功 vs 复核驳回/作废归档;分类 CASE 中上传成功优先,
# 故二者互斥,reject_void 用差值即无重叠计数。
done_upload = done_base.filter(upload_success).count()
return {
"pending": pending,
"processing": processing,
"done": done,
"total_pending_badge": pending,
"stage_counts": _my_todo_stage_counts(user_id, is_admin=is_admin),
"done_counts": {
"upload_complete": done_upload,
"reject_void": max(0, done - done_upload),
},
}
@@ -44,6 +44,9 @@ from app.models import (
ShippingOrderReviewCase,
User,
)
from app.services.shipping_notice.error_explainability_contract import (
UNKNOWN_BUSINESS_FAILURE_REASON_CODE,
)
# ============================================================
@@ -60,6 +63,11 @@ class BlockingReason(TypedDict, total=False):
code: str | None
i18n_key: str | None
details: dict[str, Any] | None
# 建单前资格快照回退透传字段(来自冻结 explainability 契约,
# 见 error_explainability_contract.build_explainability_reason;
# message 为中文兜底文案,前端优先按 i18n 命名空间解析)。
message: str | None
next_action: str | None
class CurrentGate(TypedDict, total=False):
@@ -723,11 +731,67 @@ def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingR
return BlockingReason(code=None, i18n_key=None, details=details)
i18n_key = _REASON_TO_I18N_KEY.get(raw_code)
if i18n_key is None:
# fail-closed:给一个通用兜底 key
i18n_key = 'shipping.review.blocked_generic'
# fail-closed:兜底键必须指向前端真实存在的键;此前指向不存在的
# shipping.review.blocked_generic,任何未映射码都会在前端双重落空成
# 「当前步骤需要人工处理」。
i18n_key = 'chat.shippingProcessing.reasonCode.unknown'
return BlockingReason(code=raw_code, i18n_key=i18n_key, details=details)
def _blocking_reason_is_generic(reason: BlockingReason) -> bool:
"""
判断 blocking_reason 是否未携带具体原因(无码或仅落通用兜底键)。
仅此情形才允许回退到资格快照,避免覆盖 automation 侧更精确的裁决。
"""
if not isinstance(reason, dict):
return True
code = str(reason.get('code') or '').strip()
if not code:
return True
return str(reason.get('i18n_key') or '').strip() == 'chat.shippingProcessing.reasonCode.unknown'
def _primary_validation_blocking_reason(validation: dict[str, Any] | None) -> BlockingReason | None:
"""
【AI 触发时机】:automation 无具体原因码,需要从草稿校验快照取首要阻断原因时。
核心逻辑:只认 severity=blocking 且 explainability 未降级(非
unknown_business_failure)的 issue;透传冻结契约的 message / next_action,
本模块不新造文案或映射。无可用 issue 返回 None,由调用方保持既有兜底。
"""
if not isinstance(validation, dict):
return None
issues = validation.get('issues')
if not isinstance(issues, list):
return None
for issue in issues:
if not isinstance(issue, dict):
continue
if str(issue.get('severity') or '').strip().lower() != 'blocking':
continue
explainability = issue.get('explainability') if isinstance(issue.get('explainability'), dict) else {}
code = str(
explainability.get('reason_code')
or issue.get('reason_code')
or issue.get('code')
or ''
).strip()
if not code or code == UNKNOWN_BUSINESS_FAILURE_REASON_CODE:
continue
details = {
key: value for key, value in issue.items()
if key in {'field_code', 'field_id', 'line_index', 'owning_gate_code'}
and value is not None
}
return BlockingReason(
code=code,
i18n_key=_REASON_TO_I18N_KEY.get(code),
details=details or None,
message=str(explainability.get('message') or issue.get('message') or '').strip() or None,
next_action=str(explainability.get('next_action') or '').strip() or None,
)
return None
# ============================================================
# [5] user_status(F2 六值;默认人工等待 = waiting_human,禁止 idle)
# ============================================================
@@ -1218,6 +1282,13 @@ def project_review_case_projection_bundle(
current_gate = project_case_current_gate(case, automation, available_actions)
# [STEP 4] blocking_reason
blocking_reason = project_case_blocking_reason(automation)
# [STEP 4.1] automation 未携带具体原因时,回退到草稿校验快照的首要 blocking
# issue:资格评估落库时已按冻结 explainability 契约附带原因文案与下一步动作,
# 此处仅透传,让批次中心/工作台展示「客户尚未确认」等具体原因而非通用兜底。
if _blocking_reason_is_generic(blocking_reason):
fallback_reason = _primary_validation_blocking_reason(validation)
if fallback_reason is not None:
blocking_reason = fallback_reason
# [STEP 5] user_status
user_status = project_case_user_status(case, automation)
# [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case
@@ -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
@@ -4003,6 +4003,33 @@ def _conversation_processing_from_work_items(
}
def _review_case_blocking_reason(
case: ShippingOrderReviewCase | None,
drafts_by_id: dict[int, Any],
) -> dict[str, Any] | None:
"""
建单前 Case 摘要叶子的具体阻断原因:回退到草稿校验快照的首要 blocking issue。
核心逻辑:资格评估落库时已按冻结 explainability 契约附带 code/message/next_action
(见 reconciliation_projector._primary_validation_blocking_reason);摘要路径的
drafts_by_id 已批量加载,透传零额外查询。无 Draft / 无可用 issue 返回 None,
调用方保持 review_case_{status} 状态码兜底。
"""
if case is None:
return None
draft_id = getattr(case, 'current_draft_id', None)
if draft_id is None:
return None
draft = drafts_by_id.get(int(draft_id))
validation = getattr(draft, 'validation_result_json', None)
if not isinstance(validation, dict):
return None
from app.services.shipping_notice.reconciliation_projector import (
_primary_validation_blocking_reason,
)
return _primary_validation_blocking_reason(validation)
def project_conversation_processing_summary(
*,
user_id: int,
@@ -4585,7 +4612,13 @@ def project_conversation_processing_summary(
'po_number': candidate_po or None,
},
'current_gate': current_gate,
'blocking_reason': {'code': reason} if reason else None,
# v4:建单前 Case 的 review_case_{status} 状态码先回退到资格快照的
# 首要阻断 issue(客户尚未确认等具体原因),无可用 issue 才落状态码。
'blocking_reason': (
_review_case_blocking_reason(case, drafts_by_id)
if str(reason or '').startswith('review_case_')
else ({'code': reason} if reason else None)
),
'primary_action': primary_action,
'available_actions': available_actions,
'intake_parse_authorized': intake_parse_authorized,
@@ -703,7 +703,7 @@ def replace_task_notice(
intake.parse_warnings_json = cleaned_warnings
set_task_step_progress(
task,
step_key="step2_parse_confirm",
stage="waiting_review",
step_title="确认解析",
status="needs_human",
message="发货通知文本抽取失败",
@@ -732,7 +732,7 @@ def replace_task_notice(
_reset_notice_edit_downstream(task)
set_task_step_progress(
task,
step_key="step1_notice_submit",
stage="order_creating",
step_title="提交通知",
status="completed",
message="已重新上传发货通知并覆盖当前任务",
@@ -2,7 +2,7 @@
services/shipping_notice/tool_common.py
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract、progress_audit_contract。
逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用;
log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/
freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent;
@@ -20,6 +20,10 @@ from flask import current_app
from app import db
from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
from app.services.shipping_notice.progress_audit_contract import (
SHIPPING_PROCESSING_STAGES,
shipping_processing_stage_index,
)
def cfg_bool(key: str, default: bool = False) -> bool:
@@ -211,7 +215,7 @@ def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
def set_task_step_progress(
task: ShippingNotice,
*,
step_key: str,
stage: str,
step_title: str,
status: str,
message: str,
@@ -221,13 +225,38 @@ def set_task_step_progress(
detail: str | None = None,
extra: dict[str, Any] | None = None,
) -> None:
"""写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。"""
"""写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。
【AI 触发时机】履约工作流(库存准备/匹配/Excel/上传/通知重解析)报告阶段内
细粒度进度或失败等待人工时调用。
核心逻辑:``stage`` 必须是冻结 15 阶契约码(SHIPPING_PROCESSING_STAGES 成员),
写入 ``current_step`` 与 ``step_payload_json.current_step_progress`` 供投影展示;
``OT.stage`` 仅按 15 阶序列【只进不退】推进——空缺时直接写入,已有值仅当新
stage 序号不小于旧值才覆盖,保证进度上报永远不会把订单拉回早期阶段。
Args:
stage: 15 阶契约码(如 inventory_fetching / inventory_matching /
excel_generating / freight_uploading);禁止传入 CheckPoint 时代
stepN_* 遗留键(已全部清除)。
step_title: 展示用步骤名。
status: 步骤执行态(running/completed/needs_human/failed 等调用方语义)。
message: 用户可读进度说明。
Raises:
ValueError: ``stage`` 不是 15 阶契约成员时立即失败(写错阶段码属于代码缺陷)。
"""
code = str(stage or '').strip()
if code not in SHIPPING_PROCESSING_STAGES:
raise ValueError(
f'set_task_step_progress: stage must be a SHIPPING_PROCESSING_STAGES member, got {stage!r}'
)
owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
payload = dict(getattr(owner, 'step_payload_json', None) or {})
progress: dict[str, Any] = {
"step_key": step_key,
"stage": code,
"step_title": step_title,
"status": status,
"message": str(message or "").strip(),
@@ -244,9 +273,19 @@ def set_task_step_progress(
progress["extra"] = extra
payload["current_step_progress"] = progress
if hasattr(owner, 'current_step'):
owner.current_step = step_key
owner.current_step = code
if hasattr(owner, 'stage'):
owner.stage = step_key
current_stage = str(getattr(owner, 'stage', None) or '').strip().lower()
current_idx = shipping_processing_stage_index(current_stage)
target_idx = shipping_processing_stage_index(code)
# 只进不退:进度上报只允许推进或停留在既有序列位置,禁止回退
# (历史缺陷:进度上报曾把 order_creating 踩回早期码,工作台掉回接收解析)。
if (
not current_stage
or current_idx is None
or (target_idx is not None and target_idx >= current_idx)
):
owner.stage = code
if hasattr(owner, 'step_payload_json'):
owner.step_payload_json = payload
@@ -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")
@@ -0,0 +1,25 @@
"""merge migration heads
用途:合并平行迁移分支,恢复 Alembic 单 head 链。
依赖:无表结构操作,仅声明多父级(aa11bb22cc33 客户 ODM 字段 × vc6a7b8c9d0e 凭证检核通知配置)。
逻辑:hugo-shipping-notice 与 dev 两侧各自新增迁移产生分叉;本 Revision 只做图合并,
upgrade/downgrade 均为空操作,实际 DDL 由两个父迁移各自负责。
Revision ID: dd22ee33ff44
Revises: aa11bb22cc33, vc6a7b8c9d0e
Create Date: 2026-09-17 00:00:00.000000
"""
revision = "dd22ee33ff44"
down_revision = ("aa11bb22cc33", "vc6a7b8c9d0e")
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,384 @@
"""
backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py
用途:验证客户识别三级命中(canonical 等值 > 完整包含 > 截断包含)与受控自动确认边界。
依赖:内存数据库、customer_normalization、identity_resolution.resolver、
customer_auto_resolution、customer_shadow_resolution。
逻辑:以 QCH/Quanta 真实差异形态(标点变体、c/o 截断、折行块整段提取、家族前缀、
跨行 vs 单行证据)构造分支,断言影子候选层级、状态语义,以及自动确认只放行
「等值唯一」与「完整包含唯一且证据授权」,截断建议永不自动确认。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import (
ShippingCustomer,
ShippingIdentityDefinition,
ShippingIdentityEvidence,
ShippingIdentityRuleSet,
ShippingOrderCandidate,
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderIntake,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice.customer_auto_resolution import resolve_auto_customer_decision
from app.services.shipping_notice.customer_normalization import (
IDENTITY_MATCH_CONTAINMENT_STRONG,
IDENTITY_MATCH_CONTAINMENT_WEAK,
IDENTITY_MATCH_EQUALITY,
canonical_identity_key,
classify_identity_containment,
normalize_identity_evidence_value,
)
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
FIELD_ID = 'fid-ship-to-customer'
RULE_SET_DEF_ID = 'def-ship-to-customer'
@pytest.mark.pure_unit
class TestCanonicalIdentityKey:
"""canonical 键:标点/空白/大小写不敏感,中文保留。"""
def test_punctuation_whitespace_case_insensitive(self):
# 关键断言:QCH 注册值与 PDF 打印值的标点/空格差异不再分裂等值命中。
assert canonical_identity_key('QCH, INC., A NEVADA CORPORATION') == canonical_identity_key(
'qch inc a nevada corporation',
)
def test_keeps_cjk_word_chars(self):
# 关键断言:中文客户名不被剔除,仍可参与等值比较。
assert canonical_identity_key('英業達股份有限公司桃科廠') == '英業達股份有限公司桃科廠'
assert canonical_identity_key('Inventec 英業達') == 'inventec英業達'
@pytest.mark.pure_unit
class TestNormalizeIdentityEvidenceValue:
"""识别证据统一归一化:三处调用点同源,兜底分支折叠内部空白。"""
def test_fallback_collapses_newlines(self):
# 关键断言:多行提取值折叠换行后可与单行注册证据等值(修复换行不对称缺陷)。
assert normalize_identity_evidence_value('QUANTA MFG,\n1 WALDENBOOKS DR.') == 'QUANTA MFG, 1 WALDENBOOKS DR.'
def test_name_normalizer_strips_punctuation(self):
assert normalize_identity_evidence_value('Hyve, Solutions', normalizer_key='name') == 'HYVESOLUTIONS'
def test_email_branch_keeps_semantic_chars(self):
assert normalize_identity_evidence_value('A@B.COM', option_key='from_email') == 'a@b.com'
def test_blank_returns_none(self):
assert normalize_identity_evidence_value(' ') is None
@pytest.mark.pure_unit
class TestClassifyIdentityContainment:
"""双向包含分级:强=指纹完整出现;弱=提取值疑似截断;邮箱/域名不参与。"""
EVIDENCE = 'QCH INC., A NEVADA CORPORATION C/O QUANTA'
def test_strong_when_fingerprint_fully_inside_runtime(self):
# 关键断言:折行块整段进入字段值时,完整指纹命中判强包含(可受控自动确认)。
assert classify_identity_containment(
'QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', self.EVIDENCE,
) == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_weak_when_runtime_is_truncation(self):
# 关键断言:截断方向只判弱命中——剩余部分未经验证,禁止自动确认。
assert classify_identity_containment(
'QCH, INC., A NEVADA CORPORATION c/o', self.EVIDENCE,
) == IDENTITY_MATCH_CONTAINMENT_WEAK
def test_fragment_below_minimum_chars_rejected(self):
# 关键断言:'c/o'→'CO' 这类短碎片不得产生包含噪声。
assert classify_identity_containment('c/o', self.EVIDENCE) is None
def test_email_domain_never_contained(self):
assert classify_identity_containment('ops@corp.com', 'ops@corp', option_key='from_email') is None
def test_unrelated_values_rejected(self):
assert classify_identity_containment('HYVE SOLUTIONS CORPORATION', self.EVIDENCE) is None
def _build_identity_world(*, runtime_value: str, evidences: list[dict]):
"""
构建最小识别世界:发布规则集 + 单 Header 字段抽取链 + 客户/证据主数据。
Args:
runtime_value: 已裁决 Header 字段值(模拟 PDF 提取结果)。
evidences: 注册证据列表,每项含 customer_name/short_code/normalized_value,
可选 auto(默认 True,对应 auto_match_allowed)。
Returns:
(candidate, intake) 供 resolve_candidate_identity / 影子刷新使用。
"""
user = User(username='tier-user', email='tier@example.com', role='user')
db.session.add(user)
db.session.flush()
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
if schema is None:
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', lock_version=1, checksum='1' * 64,
definition_json={'fields': [{
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'display_name': 'Ship To Customer',
'scope': 'header', 'value_type': 'string', 'enabled': True,
'available_for_customer_identity': True, 'normalizer_key': 'trim',
}]},
)
db.session.add(version)
db.session.flush()
definition_json = {
'order_schema': {'id': version.id, 'version': version.version, 'checksum': version.checksum},
'definitions': [{
'id': RULE_SET_DEF_ID, 'definition_code': 'ship_to_customer_rule',
'display_name': 'Ship To Customer', 'evidence_label': 'Ship To',
'target_type': 'customer', 'context_field_id': FIELD_ID,
'default_weight': 100, 'max_automation': 'conditional', 'status': 'active',
'field_config': {
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'scope': 'header',
'value_type': 'string', 'normalizer_key': 'trim',
'context_source': {'provider': 'order_field', 'option_key': None},
'available_for_customer_identity': True,
},
}],
}
db.session.add(ShippingIdentityRuleSet(version=1, status='published', definition_json=definition_json, checksum='c' * 64))
db.session.add(ShippingIdentityDefinition(
id=RULE_SET_DEF_ID, definition_code='ship_to_customer_rule', target_type='customer',
context_field_id=FIELD_ID, default_weight=100, max_automation='conditional', status='active',
))
intake = ShippingOrderIntake(intake_no='INT-TIER', asset_id=1, user_id=user.id, parser_version='test')
db.session.add(intake)
db.session.flush()
extraction = ShippingOrderExtraction(
intake_id=intake.id, schema_version_id=version.id, input_snapshot_hash='h' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, field_id=FIELD_ID, decision_status='accepted', decided_at=datetime.utcnow(),
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, field_id=FIELD_ID, decision_id=decision.id, value_text=runtime_value,
))
candidate = ShippingOrderCandidate(
candidate_no='CAND-TIER', intake_id=intake.id, primary_document_id=1,
candidate_key='tier-test', candidate_status='accepted', order_extraction_id=extraction.id,
)
db.session.add(candidate)
for index, spec in enumerate(evidences, start=1):
customer = ShippingCustomer(
standard_name=spec['customer_name'], short_code=spec['short_code'], status='active',
)
db.session.add(customer)
db.session.flush()
db.session.add(ShippingIdentityEvidence(
definition_id=RULE_SET_DEF_ID, customer_id=customer.id,
raw_value=spec['normalized_value'], normalized_value=spec['normalized_value'],
status='approved', auto_match_allowed=spec.get('auto', True),
))
db.session.commit()
return candidate, intake
class TestResolverTierMatching:
"""影子识别三级命中与状态语义(resolve_candidate_identity)。"""
def test_punctuation_variant_hits_equality_tier(self, app):
with app.app_context():
# 关键断言:'QCH,' vs 'QCH' 标点差异经 canonical 等值命中,不再是 unmatched。
candidate, intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
def test_truncated_runtime_becomes_weak_suggestion(self, app):
with app.app_context():
# 关键断言:c/o 截断形态产出唯一弱命中候选(unique_candidate 仅表示展示层唯一),
# match_kind=containment_weak,交由人工确认。
candidate, intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_WEAK
def test_wrapped_block_hits_strong_containment(self, app):
with app.app_context():
# 关键断言:折行块整段提取时完整指纹出现,判强包含。
candidate, intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_family_prefix_stays_ambiguous(self, app):
with app.app_context():
# 关键断言:家族共享前缀同时包含命中 QCG/TW 两个站点客户 → ambiguous,不取首条。
candidate, intake = _build_identity_world(
runtime_value='Quanta Computer Inc.',
evidences=[
{
'customer_name': 'QUANTA QCG', 'short_code': 'QCG',
'normalized_value': 'QUANTA COMPUTER INC. DE 2470.58.340',
},
{
'customer_name': 'QUANTA TW', 'short_code': 'TWQ',
'normalized_value': 'QUANTA COMPUTER INC. HQ PLANT',
},
],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'ambiguous'
assert {item['match_kind'] for item in result['customer_matches']} == {IDENTITY_MATCH_CONTAINMENT_WEAK}
def test_equality_beats_containment_in_order(self, app):
with app.app_context():
# 关键断言:等值候选排在包含候选之前,且顶层唯一时状态为 unique_candidate。
candidate, intake = _build_identity_world(
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
evidences=[
{
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
'normalized_value': 'WISTRON CORPORATION',
},
{
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
},
],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
names = {item['standard_name']: item for item in result['customer_matches']}
# 关键断言:等值候选排第一,强包含候选次之;强层级唯一 → unique_candidate。
assert result['customer_matches'][0]['standard_name'] == 'WIWYNN CZ BRNO'
assert names['WIWYNN CZ BRNO']['match_kind'] == IDENTITY_MATCH_EQUALITY
assert names['WIWYNN CZ']['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_multiline_runtime_matches_single_line_evidence(self, app):
with app.app_context():
# 关键断言:运行侧换行折叠修复后,跨行提取值可与单行注册证据等值命中。
candidate, intake = _build_identity_world(
runtime_value='Quanta Manufacturing Nashville, LLC,\n1 Waldenbooks Dr.',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QUANTA MANUFACTURING NASHVILLE, LLC, 1 WALDENBOOKS DR.',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
class TestAutoConfirmDecision:
"""自动确认分级裁决(resolve_auto_customer_decision)。"""
def _shadow(self, candidate):
return refresh_candidate_shadow_resolution(candidate)
def test_equality_unique_confirms_strong(self, app):
with app.app_context():
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unique_strong_match'
assert decision['customer_id'] is not None
def test_containment_strong_unique_confirms_with_match_kind(self, app):
with app.app_context():
# 关键断言:指纹完整出现的唯一包含命中且证据授权 → unique_containment_match,
# 审计证据带 match_kind=containment_strong 溯源。
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unique_containment_match'
assert decision['customer_id'] is not None
assert decision['evidence'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_truncation_only_never_confirms(self, app):
with app.app_context():
# 关键断言:截断形态(本单 7911678818.PDF)永不自动确认,保持 unmatched 交人工。
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unmatched'
assert decision['customer_id'] is None
def test_unauthorized_evidence_never_confirms(self, app):
with app.app_context():
# 关键断言:auto_match_allowed=False 的证据即使等值唯一也不自动确认。
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION', 'auto': False,
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unmatched'
assert decision['customer_id'] is None
def test_equality_precedes_containment(self, app):
with app.app_context():
# 关键断言:等值命中存在时包含命中不参与裁决,等值客户唯一即确认。
candidate, _intake = _build_identity_world(
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
evidences=[
{
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
'normalized_value': 'WISTRON CORPORATION',
},
{
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
},
],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unique_strong_match'
customers = {c.id: c.standard_name for c in ShippingCustomer.query.all()}
assert customers[decision['customer_id']] == 'WIWYNN CZ BRNO'
@@ -235,6 +235,180 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
assert bundle['user_status'] == 'waiting_human'
# ============================================================
# [BR] blocking_reason 资格快照回退:
# automation 无具体原因码时,回退到草稿校验快照(validation_result_json)
# 中首要 blocking issue 的冻结 explainability 透传(code/message/next_action),
# 让批次中心与工作台展示具体原因,而非「当前步骤需要人工处理」兜底。
# ============================================================
def _validation_snapshot_with_issues(issues: list[dict]) -> dict:
"""构造与 order_build_eligibility 持久化结构一致的 validation 快照。"""
return {'can_build': False, 'can_auto_create': False, 'issues': issues}
@pytest.mark.pure_unit
def test_bundle_falls_back_to_primary_validation_issue_when_automation_lacks_reason():
"""[BR-1] automation 无具体原因码时,blocking_reason 必须回退到首要 blocking issue。"""
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
case = _fake_case(status='draft', candidate_id=None)
bundle = project_review_case_projection_bundle(
case,
validation=_validation_snapshot_with_issues([
{
'code': 'customer_unresolved',
'severity': 'blocking',
'owning_gate_code': 'customer_resolution',
'message': '客户尚未确认',
'explainability': {
'reason_code': 'customer_unresolved',
'message': '客户尚未确认',
'next_action': 'confirm_customer',
},
},
]),
post_confirm=None,
is_admin=False,
)
reason = bundle['blocking_reason']
# 断言意图:透传冻结契约的事实三元组,前端据此展示「客户尚未确认 / 确认客户」
assert reason['code'] == 'customer_unresolved'
assert reason['message'] == '客户尚未确认'
assert reason['next_action'] == 'confirm_customer'
@pytest.mark.pure_unit
def test_validation_fallback_skips_degraded_and_non_blocking_issues():
"""[BR-2] 降级码(unknown_business_failure)与非 blocking issue 不进入回退。"""
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
case = _fake_case(status='draft', candidate_id=None)
bundle = project_review_case_projection_bundle(
case,
validation=_validation_snapshot_with_issues([
# 仅阻断自动建单,不属用户阻断
{
'code': 'candidate_qualification_blocked',
'severity': 'auto_create_blocking',
'explainability': {
'reason_code': 'llm_path_cannot_auto_freeze',
'message': '智能识别结果尚未通过自动建单资格检查',
'next_action': 'open_order_review',
},
},
# 契约降级码:不透传给用户
{
'code': 'weird_new_issue',
'severity': 'blocking',
'explainability': {
'reason_code': 'unknown_business_failure',
'message': '业务处理失败,请凭请求编号联系管理员',
'next_action': '',
},
},
# 首个可用 blocking issue
{
'code': 'required_field_missing',
'severity': 'blocking',
'field_code': 'reservation_id',
'explainability': {
'reason_code': 'required_field_missing',
'message': '缺少创建订单所需字段',
'next_action': 'open_order_review',
},
},
]),
post_confirm=None,
is_admin=False,
)
reason = bundle['blocking_reason']
assert reason['code'] == 'required_field_missing'
assert reason['next_action'] == 'open_order_review'
assert reason['details'].get('field_code') == 'reservation_id'
@pytest.mark.pure_unit
def test_bundle_keeps_mapped_automation_reason_over_validation_fallback(monkeypatch):
"""[BR-3] automation 已有映射的具体原因码时不回退,避免覆盖更精确的裁决。"""
from app.services.shipping_notice import reconciliation_projector
case = _fake_case(status='draft', candidate_id=None)
monkeypatch.setattr(
reconciliation_projector,
'project_case_automation_status',
lambda case, *, validation, post_confirm: {
'status': 'manual_fallback',
'retryable': False,
'reason_code': 'duplicate_decision_required',
},
)
bundle = reconciliation_projector.project_review_case_projection_bundle(
case,
validation=_validation_snapshot_with_issues([
{
'code': 'customer_unresolved',
'severity': 'blocking',
'explainability': {
'reason_code': 'customer_unresolved',
'message': '客户尚未确认',
'next_action': 'confirm_customer',
},
},
]),
post_confirm=None,
is_admin=False,
)
reason = bundle['blocking_reason']
assert reason['code'] == 'duplicate_decision_required'
assert reason.get('message') is None
@pytest.mark.pure_unit
def test_bundle_without_usable_issues_keeps_legacy_blocking_reason():
"""[BR-4] 快照无可用 issue 时保持既有兜底行为(不得抛错、不得造原因)。"""
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
case = _fake_case(status='draft', candidate_id=None)
bundle = project_review_case_projection_bundle(
case,
validation={'can_build': True, 'can_auto_create': True, 'issues': []},
post_confirm=None,
is_admin=False,
)
reason = bundle['blocking_reason']
assert isinstance(reason, dict)
assert reason.get('message') is None
assert reason.get('next_action') is None
@pytest.mark.pure_unit
def test_unmapped_automation_reason_uses_existing_generic_i18n_key():
"""[BR-5] 未映射原因码的 fail-closed 兜底必须指向前端真实存在的键。"""
from app.services.shipping_notice.reconciliation_projector import (
project_case_blocking_reason,
)
reason = project_case_blocking_reason({
'status': 'manual_fallback',
'reason_code': 'totally_new_unmapped_code',
})
assert reason['code'] == 'totally_new_unmapped_code'
# 此前指向不存在的 shipping.review.blocked_generic,任何未映射码都会双重落空
assert reason['i18n_key'] == 'chat.shippingProcessing.reasonCode.unknown'
@pytest.mark.pure_unit
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
+2 -2
View File
@@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app):
user_id=user.id,
conversation_id=session.session_id,
status='waiting_review',
stage='step5_match_inventory',
stage='inventory_matching',
progress_version=1,
)
ot_b = ShippingOrderTask(
@@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
user_id=user.id,
conversation_id=session.session_id,
status='waiting_review',
stage='step5_match_inventory',
stage='inventory_matching',
progress_version=1,
)
db.session.add(ot)
@@ -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(
@@ -0,0 +1,298 @@
"""
tests/test_order_profile_header_identity.py
用途:锁定 schema_canonical_header_atoms / schema_canonical_header_tokens 的表头
别名语义归一行为,及其在表头原子硬互斥(_header_discriminator_atoms_conflict)
与 signature_conflict 二次机会门禁中的防回归契约;含真实故障单 PO_6075316
(日期换词 + 相邻列并格 + 空串 token)的形状回归。
依赖:order_profile_matcher.schema_canonical_header_atoms /
schema_canonical_header_tokens / _header_token_atoms /
_header_discriminator_atoms_conflict。
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
别名的契约下跨措辞对齐,异义词不归并。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_header_discriminator_atoms_conflict,
_header_token_atoms,
schema_canonical_header_atoms,
schema_canonical_header_tokens,
)
pytestmark = pytest.mark.pure_unit
def test_none_or_empty_mapping_degrades_to_word_atoms():
"""未配置别名表时必须与既有词级原子化完全一致(零行为变化)。"""
tokens = ['Requested Ship Date (ETD)', 'Qty', 'Unit Price']
# 关键断言:None 与空 dict 均退化为 _header_token_atoms,结果与直接调用逐项相等
assert schema_canonical_header_atoms(tokens, None) == _header_token_atoms(tokens)
assert schema_canonical_header_atoms(tokens, {}) == _header_token_atoms(tokens)
# 关键断言:退化路径下不得混入任何 field:: 标记原子
assert not any(
atom.startswith('field::')
for atom in schema_canonical_header_atoms(tokens, None)
)
def test_exact_phrase_hit_emits_field_marker():
"""别名精确命中时短语整体替换为 field::<field_code>,不残留短语内单词。"""
atoms = schema_canonical_header_atoms(
['Requested Ship Date'],
{'requested ship date': 'requested_receipt_date'},
)
# 关键断言:命中段落被消费,仅剩语义标记原子,词级原子 requested/ship/date 不再出现
assert atoms == frozenset({'field::requested_receipt_date'})
def test_merged_cell_greedy_decomposition():
"""合并格长文案按贪心最长短语分解为多个 field 标记原子。"""
atoms = schema_canonical_header_atoms(
['Requested Ship Date Unit Price'],
{
'requested ship date': 'requested_receipt_date',
'unit price': 'unit_price',
},
)
# 关键断言:两个别名短语各自命中并消费整段,互不残留单词原子
assert atoms == frozenset({'field::requested_receipt_date', 'field::unit_price'})
def test_greedy_prefers_longest_phrase():
"""同一位置长短短语重叠时必须取最长短语(贪心最长匹配)。"""
atoms = schema_canonical_header_atoms(
['Requested Ship Date'],
{
'ship date': 'ship_date',
'requested ship date': 'requested_receipt_date',
},
)
# 关键断言:最长短语胜出且整段消费,短短语不产生任何残留 field/词级原子
assert atoms == frozenset({'field::requested_receipt_date'})
def test_case_insensitive_matching():
"""表头与别名 key 大小写不同仍命中(casefold 同源词管线)。"""
atoms = schema_canonical_header_atoms(
['UNIT PRICE'],
{'Unit Price': 'unit_price'},
)
# 关键断言:大小写差异不阻断短语命中,field_code 保留别名表原样
assert atoms == frozenset({'field::unit_price'})
def test_unmatched_words_kept_and_short_words_filtered():
"""未命中别名的词沿用既有过滤:长度 >=3 且非虚词才保留为词级原子。"""
atoms = schema_canonical_header_atoms(
['Total Amount ok the ab'],
{'unit price': 'unit_price'},
)
# 关键断言:total/amount 保留;'ok'/'ab' 过短被滤;'the' 为虚词被滤
assert atoms == frozenset({'total', 'amount'})
mixed = schema_canonical_header_atoms(
['Unit Price Remarks ok'],
{'unit price': 'unit_price'},
)
# 关键断言:同一 token 内 field 标记原子与词级原子可共存
assert mixed == frozenset({'field::unit_price', 'remarks'})
def test_empty_tokens_skipped():
"""空串/纯空白 token(MinerU 空格占位)直接跳过且不影响其余 token。"""
atoms = schema_canonical_header_atoms(
['', ' ', 'Unit Price'],
{'unit price': 'unit_price'},
)
# 关键断言:空白 token 不产生原子也不中断匹配,后续 token 照常命中
assert atoms == frozenset({'field::unit_price'})
def test_chinese_alias_yields_no_field_atom():
"""中文别名切词为空 → 自然跳过(有意行为:词级原子只保留 [a-z0-9])。"""
atoms = schema_canonical_header_atoms(
['数量', 'Qty'],
{'数量': 'quantity'},
)
# 关键断言:中文别名不产生 field:: 原子;词级原子口径不变(qty 长度 >=3 保留)
assert atoms == frozenset({'qty'})
def test_casefold_collision_phrase_discarded():
"""同一短语 casefold 后映射到多个 field_code → 整体弃用,回退词级原子。"""
atoms = schema_canonical_header_atoms(
['Ship Date'],
{
'Ship Date': 'ship_date',
'ship date': 'requested_ship_date',
},
)
# 关键断言:歧义短语不得产出任何 field:: 原子;未命中单词走既有过滤保留
assert atoms == frozenset({'ship', 'date'})
def test_casefold_equal_duplicate_alias_kept():
"""同短语重复别名但 field_code 仅大小写不同 → 不视为歧义,短语保留。"""
atoms = schema_canonical_header_atoms(
['Ship Date'],
{'Ship Date': 'ship_date', 'SHIP DATE': 'SHIP_DATE'},
)
# 关键断言:casefold 视角同码不构成身份歧义,短语照常产出标记原子
assert atoms == frozenset({'field::ship_date'})
# --- PO_6075316 真实故障形状回归:别名契约 vs 表头原子硬互斥 ---
_SIGNATURE_TRAINING_TOKENS = [
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
'Requested Arrival Date', 'Unit Price', 'Extension',
]
_PO6075316_OBSERVED_TOKENS = [
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
'Requested Ship Date Unit Price', '', 'Extension',
]
_SCHEMA_V4_HEADER_TO_FIELD = {
'Requested Receipt Date': 'requested_receipt_date',
'Requested Arrival Date': 'requested_receipt_date',
'Requested Ship Date': 'requested_receipt_date',
'Unit Price': 'unit_price',
'Extension': 'line_amount_with_tax',
'Part Number': 'customer_part_number',
'Vendor Item': 'part_number',
'Quantity': 'qty',
'LN': 'customer_po_line_no',
}
def _po6075316_signature() -> dict:
"""训练签名(命中模板 HYVE)的明细表 header_tokens 形状。"""
return {'table_patterns': [{'header_tokens': list(_SIGNATURE_TRAINING_TOKENS)}]}
def test_po6075316_fault_shape_passes_with_ship_date_alias_contract():
"""PO_6075316 形状(日期换词+并格+空串)在含 Ship Date 别名契约下不再互斥。"""
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
# 关键断言:两侧经 Schema 别名归一后字段语义原子全等,硬互斥判定为不冲突
assert _header_discriminator_atoms_conflict(
signature=_po6075316_signature(),
observed=observed,
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
) is False
# 佐证:'Requested Ship Date' 与 'Requested Arrival Date' 归一为同一标记原子;
# 并格长文案贪心分解出日期+单价两个标记原子;空串 token(MinerU 占位)零原子。
assert schema_canonical_header_atoms(
observed['header_tokens'], _SCHEMA_V4_HEADER_TO_FIELD,
) == schema_canonical_header_atoms(
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
)
def test_po6075316_fault_shape_still_conflicts_without_alias_contract():
"""同形状不传契约(或契约缺 Ship Date 别名)时互斥仍在——豁免效果来自别名。"""
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
# 关键断言:不传 header_to_field 时两侧退化词级原子,arrival≠ship,既有互斥零变化
assert _header_discriminator_atoms_conflict(
signature=_po6075316_signature(), observed=observed,
) is True
contract_without_ship_alias = {
key: value
for key, value in _SCHEMA_V4_HEADER_TO_FIELD.items()
if key != 'Requested Ship Date'
}
# 关键断言:契约缺 Ship Date 别名时观测侧 ship 退回词级原子,互斥依旧成立
assert _header_discriminator_atoms_conflict(
signature=_po6075316_signature(),
observed=observed,
header_to_field=contract_without_ship_alias,
) is True
def test_po6075316_foreign_date_word_not_merged_by_alias():
"""日期列换成未配别名的真正异义词(Customer PO Date)时不得归并,互斥仍触发。"""
observed = {'header_tokens': [
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
'Customer PO Date Unit Price', '', 'Extension',
]}
# 关键断言:别名契约只归并已治理措辞,不同语义字段(客户 PO 日期)保持互斥
assert _header_discriminator_atoms_conflict(
signature=_po6075316_signature(),
observed=observed,
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
) is True
# --- schema_canonical_header_tokens:序列语义 canonical 归一(二次机会门禁供料) ---
def test_tokens_none_or_empty_mapping_returns_input_list_unchanged():
"""None/空 dict 时原样返回输入列表(零归一,与 atoms 的退化口径一致)。"""
tokens = ['Requested Ship Date (ETD)', 'Qty', '']
# 关键断言:None 与空 dict 均不做任何归一,列表内容原样返回
assert schema_canonical_header_tokens(tokens, None) == tokens
assert schema_canonical_header_tokens(tokens, {}) == tokens
# 关键断言:退化路径下不得混入任何 field:: 标记项
assert not any(item.startswith('field::') for item in schema_canonical_header_tokens(tokens, None))
def test_tokens_hit_phrase_collapses_to_single_item_and_keeps_order():
"""命中片段坍缩为单个 field 标记列表项,且保持在原 token 的序列位置。"""
canonical = schema_canonical_header_tokens(
['Requested Ship Date', 'Remarks', 'Unit Price'],
{
'requested ship date': 'requested_receipt_date',
'unit price': 'unit_price',
},
)
# 关键断言:命中短语各坍缩为单列表项并按原顺序交错排列,短语内单词不残留
assert canonical == [
'field::requested_receipt_date', 'remarks', 'field::unit_price',
]
def test_tokens_sequence_semantics_keeps_duplicates_and_unmatched_words():
"""序列语义:允许重复、未命中词原样保留——与 atoms 的集合语义形成对照。"""
canonical = schema_canonical_header_tokens(
['Unit Price', 'Total Amount ok the ab', 'Unit Price'],
{'unit price': 'unit_price'},
)
# 关键断言:重复 token 各自产出标记项(不去重);total/amount 原词保序保留;
# 'ok'/'ab' 过短、'the' 为虚词被滤(与 atoms 同一过滤口径)
assert canonical == [
'field::unit_price', 'total', 'amount', 'field::unit_price',
]
def test_tokens_dedup_equals_atoms_same_source_semantics():
"""同源语义:同一输入下 tokens 版去重即 atoms 版结果(同管线同短语匹配)。"""
tokens = ['', ' ', 'Requested Ship Date Unit Price', 'Vendor Item#', 'ok the ab']
mapping = {
'requested ship date': 'requested_receipt_date',
'unit price': 'unit_price',
'vendor item': 'part_number',
}
canonical = schema_canonical_header_tokens(tokens, mapping)
atoms = schema_canonical_header_atoms(tokens, mapping)
# 关键断言:序列版去重后与集合版逐项相等——两条路径完全同源,不得漂移
assert set(canonical) == set(atoms)
# 关键断言:空白 token 不产出列表项(与 atoms 跳过口径一致)
assert len(canonical) == len([item for item in canonical if item])
def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
"""PO_6075316 形状在含 Ship Date 别名下两侧 canonical 序列逐项相等(保序)。"""
canonical_expected = schema_canonical_header_tokens(
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
)
canonical_observed = schema_canonical_header_tokens(
_PO6075316_OBSERVED_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
)
# 关键断言:并格长文案贪心分解出的标记原子序列与训练侧完全一致(含顺序),
# 供二次机会门禁按序列比较得出满配额软分
assert canonical_expected == canonical_observed
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
assert canonical_expected[0] == 'field::customer_po_line_no'
@@ -0,0 +1,37 @@
"""
backend/tests/test_shipping_conversation_title.py
用途:验证订单抽取会话标题纯函数的派生规则(前缀剥离/截断/计数后缀/日期/回退)。
依赖:纯函数,无 Flask/DB 夹具。
逻辑:命名是内容派生的确定性函数,用逐条断言锁定规则,防止后续误改口径。
"""
from __future__ import annotations
from datetime import datetime
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
def test_strips_leading_mail_prefixes_and_appends_date():
"""首个文件名循环剥离 Re/Fw/Fwd/回复/转发 前缀,末尾追加 MM-DD。"""
title = derive_order_extraction_title(['回复:转发:FWD: PO#6075309.eml'], datetime(2026, 9, 15))
assert title == 'PO#6075309 09-15'
def test_multi_files_appends_count_suffix():
"""文件总数大于 1 时追加「等 N 个文件」,N 按传入文件名总数计。"""
title = derive_order_extraction_title(['PO#6075309.eml', 'invoice.pdf', 'list.pdf'], datetime(2026, 9, 15))
assert title == 'PO#6075309 等 3 个文件 09-15'
def test_truncates_long_name_to_24_chars():
"""主名超过 24 字符截断,且不吞掉日期后缀。"""
title = derive_order_extraction_title(['A' * 30 + '.pdf'], datetime(2026, 12, 31))
assert title == 'A' * 24 + ' 12-31'
def test_blank_filenames_fall_back_to_default():
"""文件名全空(含空列表与纯空白项)回退写死标题「订单抽取」。"""
assert derive_order_extraction_title([], datetime(2026, 9, 15)) == '订单抽取'
assert derive_order_extraction_title(['', ' '], datetime(2026, 9, 15)) == '订单抽取'
@@ -0,0 +1,227 @@
"""
backend/tests/test_shipping_done_line_report.py
用途:已完成通知明细行报表(done-lines)查询与专用导出的单测。
依赖:pytest、openpyxl、ShippingNotice/OT/Snapshot/Artifact 夹具、done_line_report。
逻辑:覆盖 12 字段映射(typed 列 + field_values_json 回源与回退)、可见性(非本人不可见、
未上传成功不进报表)、客户/料号/发货通知日期筛选、分页、导出表头与留空行为。
"""
from datetime import date, datetime, timedelta
import pytest
from openpyxl import load_workbook
from app.models import (
ShippingNotice,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
ShippingExportArtifact,
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
)
from app.services.shipping_notice.done_line_report import (
DONE_REPORT_HEADERS,
build_done_lines_xlsx,
list_done_notice_lines,
)
def _seed_report_fixture(db, *, owner: int):
"""最小报表夹具:一张已完成双行通知 + 一张仅 ready 未上传的通知(应被排除)。"""
order = ShippingOrderTask(task_no="OT-DONE-LINE", source_type="direct_pdf", user_id=owner)
pending_order = ShippingOrderTask(task_no="OT-DONE-LINE-PENDING", source_type="direct_pdf", user_id=owner)
notice = ShippingNotice(task_no="SN-DONE-LINE", source_type="manual", user_id=owner)
pending_notice = ShippingNotice(task_no="SN-DONE-LINE-PENDING", source_type="manual", user_id=owner)
db.session.add_all([order, pending_order, notice, pending_notice])
template = ShippingExcelTemplate(
template_code='DONELINE', display_name='DoneLine', version=1, status='published',
storage_bucket='test', storage_key='done.xlsx', original_filename='done.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='DONELINE', display_name='DoneLine', version=1, status='published',
file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='DONELINE', display_name='DoneLine')
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={'fields': []},
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
# 标准字段资产:约定出货日期(行级)与来源单号(表头级),值为 field_id 键 JSON。
db.session.add(ShippingOrderField(
id='f-req-date', field_code='required_date', scope='line', value_type='date',
field_category='order_line', collection_mode='deterministic_context',
asset_kind='system_standard', storage_mode='typed_column', storage_column='required_date',
))
db.session.add(ShippingOrderField(
id='f-source-order', field_code='source_order_number', scope='header', value_type='string',
field_category='order_header', collection_mode='deterministic_context',
asset_kind='system_standard', storage_mode='json_only',
))
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
order_data_version=1,
customer_name='HYVE CS', customer_code='HC001', customer_po_number='306085',
order_date=date(2026, 6, 1), required_date=date(2026, 6, 15),
header_values_json={'f-source-order': '8301-2606010052'},
)
db.session.add(snapshot)
db.session.flush()
db.session.add_all([
ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, line_no=1,
part_number='B3-A08AR10000017-A6', qty=80, unit_price=1525.08,
field_values_json={'f-req-date': '2026-06-15'},
),
ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=2, line_no=2,
part_number='D4-A08AR12000001', qty=1000, unit_price=898.72,
field_values_json={},
),
])
order.order_snapshot_id = snapshot.id
notice.order_task_id = order.id
extraction_two = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='e' * 64, status='accepted',
)
db.session.add(extraction_two)
db.session.flush()
pending_snapshot = ShippingOrderSnapshot(
task_id=pending_order.id, extraction_id=extraction_two.id, schema_version_id=version.id,
order_data_version=1,
customer_name='PENDING CS', customer_code='PC001',
)
db.session.add(pending_snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=pending_snapshot.id, position=1, line_no=1, part_number='X-1', qty=1,
))
pending_order.order_snapshot_id = pending_snapshot.id
pending_notice.order_task_id = pending_order.id
def add_artifact(target, *, artifact_no: str, status: str) -> None:
"""为 Notice 建立报表口径所需的最小 Artifact。"""
db.session.add(ShippingExportArtifact(
artifact_no=artifact_no, task_id=target.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
file_checksum='d' * 64, file_size=1, status=status,
))
add_artifact(notice, artifact_no='ART-DONE-LINE', status='uploaded')
add_artifact(pending_notice, artifact_no='ART-DONE-LINE-PENDING', status='ready')
db.session.commit()
return notice
def test_list_done_notice_lines_maps_standard_fields(app):
"""明细行平铺不按 OT 聚合;12 字段含 JSON 回源与表头回退,无数据源字段留空。"""
with app.app_context():
from app import db
owner = 88
_seed_report_fixture(db, owner=owner)
result = list_done_notice_lines(owner, page=1, page_size=20)
# 断言:仅 uploaded 通知进入报表;两行明细平铺,OT 不聚合。
assert result["total"] == 2
assert {item["line_no"] for item in result["items"]} == {1, 2}
first = next(item for item in result["items"] if item["line_no"] == 1)
# 断言:溯源编号 + 标准 12 字段映射。
assert first["task_no"] == "SN-DONE-LINE"
assert first["customer_name"] == "HYVE CS"
assert first["customer_code"] == "HC001"
assert first["order_date"] == "2026-06-01"
assert first["part_number"] == "B3-A08AR10000017-A6"
assert first["qty"] == 80.0
# 行级 field_values_json 有值时优先于快照表头 typed 列。
assert first["required_date"] == "2026-06-15"
assert first["customer_po_number"] == "306085"
assert first["source_order_number"] == "8301-2606010052"
assert first["unit_price"] == 1525.08
# 已用数量 / open qty 当前无数据源,契约留空。
assert first["used_qty"] is None
assert first["open_qty"] is None
second = next(item for item in result["items"] if item["line_no"] == 2)
# 断言:行级无 required_date 时回退快照表头 typed 列。
assert second["required_date"] == "2026-06-15"
assert second["source_order_number"] == "8301-2606010052"
# 断言:其他用户不可见(非管理员仅创建者)。
assert list_done_notice_lines(999)["total"] == 0
def test_list_done_notice_lines_filters_and_pagination(app):
"""客户/料号/发货通知日期筛选与按明细行分页生效。"""
with app.app_context():
from app import db
owner = 89
_seed_report_fixture(db, owner=owner)
# 客户模糊(大小写不敏感)。
assert list_done_notice_lines(owner, customer="hyve")["total"] == 2
assert list_done_notice_lines(owner, customer="不存在")["total"] == 0
# 料号模糊(命中单行)。
part_page = list_done_notice_lines(owner, part_number="B3-")
assert part_page["total"] == 1
assert part_page["items"][0]["part_number"] == "B3-A08AR10000017-A6"
# 发货通知日期范围:今天闭区间命中;未来区间为空。
today = datetime.utcnow().date()
assert list_done_notice_lines(
owner, notice_date_from=today.isoformat(), notice_date_to=today.isoformat(),
)["total"] == 2
tomorrow = (today + timedelta(days=1)).isoformat()
assert list_done_notice_lines(owner, notice_date_from=tomorrow)["total"] == 0
# 按明细行分页。
page_one = list_done_notice_lines(owner, page=1, page_size=1)
page_two = list_done_notice_lines(owner, page=2, page_size=1)
assert page_one["total"] == 2
assert {page_one["items"][0]["line_no"], page_two["items"][0]["line_no"]} == {1, 2}
def test_build_done_lines_xlsx_writes_fixed_twelve_columns(app):
"""导出严格 12 列标准格式:OT 编号不落列,无数据源列留空。"""
with app.app_context():
from app import db
owner = 90
_seed_report_fixture(db, owner=owner)
stream, filename = build_done_lines_xlsx(owner)
assert filename.startswith("done-lines-") and filename.endswith(".xlsx")
workbook = load_workbook(stream)
sheet = workbook.active
rows = list(sheet.iter_rows(values_only=True))
# 断言:表头为固定 12 列中文标准格式。
assert tuple(rows[0]) == DONE_REPORT_HEADERS
# 断言:两行明细,且不含 OT 编号列;数量/单价写数值,无数据源列留空。
assert len(rows) == 3
first_data = rows[1]
assert first_data[0] == "HYVE CS"
assert first_data[3] == 1
assert first_data[4] == "B3-A08AR10000017-A6"
assert first_data[5] == 80.0
assert first_data[8] is None
assert first_data[9] is None
assert first_data[10] == "8301-2606010052"
assert first_data[11] == 1525.08
@@ -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']
@@ -0,0 +1,125 @@
"""
backend/tests/test_shipping_my_todo_stage_counts.py
用途:「我的待办」count 聚合扩展单测(阶段 tab 计数 + 已完成子终态拆分)。
依赖:pytest、ShippingNotice / ShippingOrderTask / Artifact 夹具、query_service.count_my_todos。
逻辑:覆盖 processing_stage 权威 / 人工原因归属 Gate / todo_category 兜底三路阶段归类;
done 桶拆分为已核验上传成功与 复核驳回/作废 两类终态计数。
"""
import pytest
from app.models import (
ShippingNotice,
ShippingOrderTask,
ShippingExportArtifact,
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderExtraction,
)
from app.services.shipping_notice.constants import RS_REJECTED
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
def test_count_my_todos_reports_stage_counts_and_done_breakdown(app):
"""阶段 tab 计数按权威口径归类;done 拆分为上传成功与驳回作废两类。"""
with app.app_context():
from app import db
owner = 77
# [STEP] 四个待处理条目分别覆盖三路归类路径:
# OT.stage 权威(waiting_review→订单复核)、原因映射(upload_rpa_failed→货代上传、
# inventory_source_unresolved→通知准备)、类别兜底(artifact ready 人工上传→货代上传)。
review_task = ShippingOrderTask(
task_no="OT-STAGE-REVIEW", stage="waiting_review",
source_type="direct_pdf", user_id=owner,
)
upload_rpa_task = ShippingOrderTask(
task_no="OT-STAGE-UPLOAD-RPA", pending_human_reason="upload_rpa_failed",
source_type="direct_pdf", user_id=owner,
)
inventory_task = ShippingOrderTask(
task_no="OT-STAGE-INVENTORY", pending_human_reason="inventory_source_unresolved",
source_type="direct_pdf", user_id=owner,
)
rejected_task = ShippingOrderTask(
task_no="OT-STAGE-REJECTED", review_status=RS_REJECTED,
source_type="direct_pdf", user_id=owner,
)
manual_task = ShippingOrderTask(
task_no="OT-STAGE-MANUAL", source_type="direct_pdf", user_id=owner,
)
manual_notice = ShippingNotice(task_no="SN-STAGE-MANUAL", source_type="manual", user_id=owner)
done_notice = ShippingNotice(task_no="SN-STAGE-DONE", source_type="manual", user_id=owner)
rejected_notice = ShippingNotice(task_no="SN-STAGE-REJECTED", source_type="manual", user_id=owner)
db.session.add_all([
review_task, upload_rpa_task, inventory_task, rejected_task, manual_task,
manual_notice, done_notice, rejected_notice,
])
template = ShippingExcelTemplate(
template_code='STAGE', display_name='Stage', version=1, status='published',
storage_bucket='test', storage_key='stage.xlsx', original_filename='stage.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='STAGE', display_name='Stage', version=1, status='published',
file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='STAGE', display_name='Stage')
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={},
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
manual_notice.order_task_id = manual_task.id
rejected_notice.order_task_id = rejected_task.id
def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact:
"""为 Notice 建立待办分类所需的最小正式 Excel Artifact。"""
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
file_checksum='d' * 64, file_size=1, status=status,
)
db.session.add(artifact)
return artifact
# 人工上传待登记(ready→manual_upload);已完成(uploaded→done/upload_complete);
# 驳回终态(ready 但 OT 复核驳回→done/reject_void)。
add_artifact(manual_notice, artifact_no='ART-STAGE-MANUAL', status='ready')
add_artifact(done_notice, artifact_no='ART-STAGE-DONE-UP', status='uploaded')
add_artifact(rejected_notice, artifact_no='ART-STAGE-REJ', status='ready')
db.session.commit()
counts = count_my_todos(owner)
# 断言:四个待处理条目按权威口径落入正确阶段 tab。
assert counts["pending"] == 4
assert counts["stage_counts"] == {
"intake_parse": 0,
"order_review": 1,
"fulfillment_prep": 1,
"freight_upload": 2,
}
# 断言:done 拆分——uploaded Artifact 计上传成功,OT 复核驳回计驳回作废。
assert counts["done"] == 2
assert counts["done_counts"] == {"upload_complete": 1, "reject_void": 1}
# 断言:terminal_kind 子视图过滤——两个终态子 tab 各自只取对应集合,互不重叠。
upload_page = list_my_todos(owner, bucket="done", terminal_kind="upload_complete")
assert {item["task_no"] for item in upload_page["items"]} == {"SN-STAGE-DONE"}
reject_page = list_my_todos(owner, bucket="done", terminal_kind="reject_void")
assert {item["task_no"] for item in reject_page["items"]} == {"SN-STAGE-REJECTED"}
# 无过滤参数时保持既有行为:done 全量。
assert list_my_todos(owner, bucket="done")["total"] == 2
@@ -538,7 +538,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
db.session.refresh(task)
assert result['status'] == 'ok', result
assert result['data']['stage'] == 'step5_match_inventory'
assert result['data']['stage'] == 'inventory_matching'
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id)
assert snapshot is not None
@@ -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
@@ -0,0 +1,87 @@
"""
backend/tests/test_shipping_order_extraction_conversation_title.py
用途:验证订单抽取新建会话按 Intake 资产文件名派生标题,且已存在会话标题一律不动。
依赖:全局 Flask/SQLite 测试夹具(app)、Run service 的会话解析内部函数。
逻辑:新建分支走 conversation_title 派生;追加归属等存量路径保持原标题(含「订单抽取」)。
"""
from __future__ import annotations
from app import db
from app.models import Agent, ChatSession, FileAsset, ShippingOrderIntake, User
from app.services.shipping_notice.order_extraction_run_service import _resolve_conversation
def _seed_user_agent(suffix: str) -> tuple[User, Agent]:
"""构造用户与货代 Agent;suffix 保证同文件内多用例数据隔离。"""
user = User(username=f'title-user-{suffix}', email=f'title-{suffix}@example.com', password_hash='x')
agent = Agent(
name=f'Title Agent {suffix}',
agent_code='shipping_notice',
runtime_provider='hybrid',
dify_app_id=f'title-agent-{suffix}',
dify_api_key='test-key',
is_active=True,
)
user.agents.append(agent)
db.session.add_all([user, agent])
db.session.flush()
return user, agent
def _seed_intake(suffix: str, user: User, filename: str, conversation_id: str | None = None) -> ShippingOrderIntake:
"""构造带资产文件名的已解析 Intake。"""
asset = FileAsset(
asset_no=f'FA-TITLE-{suffix}',
owner_user_id=user.id,
original_filename=filename,
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/{filename}',
content_hash=(suffix.lower() * 64)[:64],
file_size=10,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=f'SNI-TITLE-{suffix}',
asset_id=asset.id,
user_id=user.id,
conversation_id=conversation_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='test',
)
db.session.add(intake)
db.session.flush()
return intake
def test_new_session_title_derives_from_intake_filenames(app):
"""新建会话:标题 = 首个文件名(剥离邮件前缀)+ 等 N 个文件 + 日期后缀。"""
user, agent = _seed_user_agent('NEW')
first = _seed_intake('NEW1', user, 'RE: PO#6075309 for HOXIN.eml')
second = _seed_intake('NEW2', user, 'invoice.pdf')
session = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[first, second])
# 日期后缀来自 utcnow,断言前缀避免对当天日期产生脆弱依赖。
assert session.title.startswith('PO#6075309 for HOXIN 等 2 个文件 ')
def test_existing_session_title_stays_untouched(app):
"""已存在会话:即便标题仍是写死的「订单抽取」,Intake 归属也不改标题。"""
user, agent = _seed_user_agent('KEEP')
session = ChatSession(session_id='title-session-keep', user_id=user.id, agent_id=agent.id, title='订单抽取')
db.session.add(session)
db.session.flush()
intake = _seed_intake('KEEP1', user, 'RE: PO#6075309.eml', conversation_id=session.session_id)
resolved = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[intake])
assert resolved.session_id == session.session_id
assert resolved.title == '订单抽取'
@@ -5,6 +5,7 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
_extract_matching_signature,
_observe_layout_features,
_resolve_coordinate_transform,
_signature_identity_header_tokens,
match_frozen_coordinate_profiles,
)
from app.services.shipping_notice.document_layout.order_profile_signature import (
@@ -1386,3 +1387,125 @@ def test_observe_layout_features_applies_business_row_clip():
assert bbox is not None
assert bbox[3] < 0.62
assert bbox[3] > 0.50
# --- PO_6075316 路由级合成回归:别名契约经二次机会门禁清空两道表头硬门禁 ---
# 训练签名(命中模板 HYVE)的明细表 header_tokens 形状。
_PO6075316_TRAINING_TOKENS = [
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
'Requested Arrival Date', 'Unit Price', 'Extension',
]
# 故障 PDF(PO_6075316)观测形状:日期词变更 + 相邻列并格 + 一个 MinerU 空串占位。
_PO6075316_FAULT_TOKENS = [
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
'Requested Ship Date Unit Price', '', 'Extension',
]
# Schema v4 相关别名(归一化 key → field_code),含治理后的 Requested Ship Date。
_PO6075316_HEADER_TO_FIELD = {
'Requested Receipt Date': 'requested_receipt_date',
'Requested Arrival Date': 'requested_receipt_date',
'Requested Ship Date': 'requested_receipt_date',
'Unit Price': 'unit_price',
'Extension': 'line_amount_with_tax',
'Part Number': 'customer_part_number',
'Vendor Item': 'part_number',
'Quantity': 'qty',
'LN': 'customer_po_line_no',
}
def _column_header_glyphs(tokens: list[str], *, x_start: float = 40.0, y0: float = 76.0, y1: float = 88.0, column_gap: float = 12.0) -> list[dict]:
"""按列生成表头字符证据。
列内空格不额外步进(合并格文案保持为单一 span,空格由 boundary 恢复);
列间留大间隔强制 positioned_token_spans 切分;空串列不产出字符。
"""
glyphs: list[dict] = []
cursor = x_start
for token in tokens:
first_of_column = True
for index, char in enumerate(token):
if char == ' ':
continue
glyphs.append({
'text': char,
'bbox': {'x0': cursor, 'y0': y0, 'x1': cursor + 3, 'y1': y1},
'boundary_before': 'none' if first_of_column else ('space' if index and token[index - 1] == ' ' else 'none'),
})
first_of_column = False
cursor += 4.0
cursor += column_gap
return glyphs
def _layout_with_column_header(tokens: list[str], *, page_width: float = 640) -> dict:
"""以指定列 token 形状构造坐标 layout(沿用 _layout 骨架,整体替换表头字符)。"""
layout = _layout()
layout['coordinate_evidence']['pages']['1']['width'] = page_width
header = _column_header_glyphs(tokens)
layout['coordinate_evidence']['tables']['table-1'] = header
layout['coordinate_evidence']['page_glyphs']['1'] = [
*layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
*header,
]
return layout
def test_header_alias_contract_clears_all_po6075316_header_hard_gates():
"""路由重放 PO_6075316:含 Ship Date 别名的契约清空 discriminator 与
signature_conflict 两道表头硬门禁(二次机会:canonical 序列复评达标)。"""
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
# 构造守卫:冻结签名 token 必须与训练形状逐字一致,防止证据管线漂移使断言空转。
signature_body, _ = _extract_matching_signature(profile)
assert _signature_identity_header_tokens(signature_body) == _PO6075316_TRAINING_TOKENS
with_contract = match_frozen_coordinate_profiles(
profiles=[profile], layout=fault,
header_to_field=_PO6075316_HEADER_TO_FIELD,
)
without_contract = match_frozen_coordinate_profiles(profiles=[profile], layout=fault)
contract_candidate = with_contract.candidates[0]
plain_candidate = without_contract.candidates[0]
# 关键断言:别名契约下第一道 discriminator 互斥被 canonical 原子全等豁免。
assert 'profile_header_discriminator_conflict' not in contract_candidate.reason_codes
# 关键断言:第二道 signature_conflict 门禁被二次机会清空——原始分被词级互斥
# 压成 0 后,canonical 序列复用同一打分逻辑重估,effective >= 0.35 不再硬拒。
assert 'profile_header_signature_conflict' not in contract_candidate.reason_codes
# 关键断言:两道表头硬门禁全清后候选成为硬匹配(表头类原因码不为拦路面)。
assert contract_candidate.hard_match is True
# 关键断言:不传契约时同形状仍被词级原子互斥拒绝——互斥机制本身未被别名破坏。
assert 'profile_header_discriminator_conflict' in plain_candidate.reason_codes
def test_header_alias_contract_without_ship_date_alias_keeps_hard_rejection():
"""反向用例:契约缺 Ship Date 别名时二次机会不生效,候选仍被表头硬门禁拒绝。
证明二次机会来自别名本身而非门禁放水。缺 Ship Date 别名时两侧 canonical
原子不再全等,先触发 discriminator 分支——if/elif 结构下 signature_conflict
分支被前置分支吸收(不得并列上报同根因),故拦路码为 discriminator;
断言落点是「仍被硬拒」:hard_match False 且综合分归零。
"""
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
contract_without_ship_alias = {
key: value
for key, value in _PO6075316_HEADER_TO_FIELD.items()
if key != 'Requested Ship Date'
}
partial = match_frozen_coordinate_profiles(
profiles=[profile], layout=fault,
header_to_field=contract_without_ship_alias,
)
candidate = partial.candidates[0]
# 关键断言:缺 Ship Date 别名 → 跨措辞(ship vs arrival)无法归一 → 硬互斥仍在。
assert 'profile_header_discriminator_conflict' in candidate.reason_codes
# 关键断言:候选仍被硬拒(综合分归零、非硬匹配)——别名缺失绝不放行。
assert candidate.hard_match is False
assert candidate.score == 0.0
@@ -372,7 +372,7 @@ def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(ap
conversation_id=session.session_id,
extraction_run_id=run.id,
status='waiting_review',
stage='step5_match_inventory',
stage='inventory_matching',
)
db.session.add(task)
db.session.flush()
@@ -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
@@ -230,18 +230,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
# 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。
uploaded = SimpleNamespace(
id=None,
current_step='step7_upload', upload_status='uploaded', export_file_path=None,
current_step='freight_uploading', upload_status='uploaded', export_file_path=None,
)
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
waiting = SimpleNamespace(
current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx',
current_step='freight_uploading', upload_status='pending', export_file_path='/x.xlsx',
)
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
matching = SimpleNamespace(
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
current_step='inventory_matching', upload_status='', match_status='matching', export_file_path=None,
)
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
@@ -540,7 +540,7 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None
owner_agent_id=int(agent.id),
candidate_id=None,
status='waiting_review',
stage='step5_match_inventory',
stage='inventory_matching',
progress_version=3,
)
db.session.add(task)
@@ -1660,7 +1660,7 @@ def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app)
intake_id=intake.id,
candidate_id=candidate.id,
status='waiting_review',
stage='step3_inventory_prepare',
stage='inventory_fetching',
)
db.session.add(order_task)
db.session.flush()
@@ -1876,6 +1876,73 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No
assert summary_leaf['intake_parse_authorized'] is False
def test_summary_leaf_surfaces_primary_validation_issue_for_open_case(app) -> None:
"""摘要叶子对建单前 Case 必须透传首要资格 issue,而非 review_case_{status} 状态码。
回归:批次进度中心对"客户尚未确认"等具体阻断只显示「订单草稿待处理」状态文案,
原因是叶子摘要用 Case 状态拼 blocking_reason.code;资格评估已把冻结
explainability(code/message/next_action)持久化进 draft.validation_result_json,
摘要路径应透传该裁决(drafts_by_id 已批量加载,零额外查询)。
"""
with app.app_context():
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-LEAF-ISSUE-REASON',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-SUMMARY-ISSUE-REASON', intake_id=intake.id,
primary_document_id=document.id, candidate_key='summary-issue-reason',
order_extraction_run_id=run.id, is_current_version=True,
candidate_status='accepted', po_number='PO-SUMMARY-ISSUE-REASON',
)
db.session.add(candidate)
db.session.flush()
review_case = ensure_run_review_cases(run=run)[0]
review_case.status = 'draft'
draft = review_case.current_draft
assert draft is not None
# 模拟资格评估落库的首要阻断 issue(与 order_build_eligibility 持久化结构一致)
draft.validation_result_json = {
'can_build': False,
'can_auto_create': False,
'issues': [{
'code': 'customer_unresolved',
'severity': 'blocking',
'owning_gate_code': 'customer_resolution',
'message': '客户尚未确认',
'explainability': {
'reason_code': 'customer_unresolved',
'message': '客户尚未确认',
'next_action': 'confirm_customer',
},
}],
}
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
summary_leaf = next(
child
for rows in payload['conversation_processing']['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
if child['source_summary']['document_id'] == document.id
)
reason = summary_leaf['ui_state']['blocking_reason']
# 关键断言:透传契约三元组;不得再是 review_case_draft 状态码
assert reason['code'] == 'customer_unresolved'
assert reason['message'] == '客户尚未确认'
assert reason['next_action'] == 'confirm_customer'
def test_summary_leaf_open_case_with_queued_stp_is_running_not_waiting_human(app) -> None:
"""开放 Case 若已有 queued STP Job,摘要必须进系统处理中,不得误报待人工。
@@ -2860,7 +2927,7 @@ def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(a
conversation_id=session.session_id,
intake_id=int(intake.id),
extraction_run_id=int(run.id),
current_step='step7_upload_freight',
current_step='freight_uploading',
status='automating',
stage='freight_uploading',
progress_version=1,
@@ -3139,7 +3206,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=int(run.id),
current_step='step7_upload_freight',
current_step='freight_uploading',
status='processing',
stage='candidate_creating',
progress_version=1,
@@ -36,21 +36,39 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage():
)
def test_legacy_step_key_stage_maps_to_fulfillment_prep():
"""OT.stage 若残留 step5_match_inventory,生命周期必须进通知准备而非接收解析。"""
def test_stage_mapping_rejects_checkpoint_legacy_keys():
"""CheckPoint stepN_* 遗留键已全部清除:阶段映射只认 15 阶契约码。
历史缺陷:step_key 被写进 OT.stage,靠投影别名兜底;现写路径只产出契约码
(set_task_step_progress 校验 + 存量迁移清洗),别名不得再存在。
"""
legacy_keys = [
'step1_notice_submit',
'step2_parse_confirm',
'step3_inventory_prepare',
'step5_match_inventory',
'step6_generate_file',
'step7_upload_freight',
]
for key in legacy_keys:
assert key not in LIFECYCLE_STAGE_BY_PROCESSING_STAGE, (
f"CheckPoint 遗留键 {key!r} 不得再进入阶段映射"
)
for stage_code in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
assert not str(stage_code).startswith('step'), (
f"阶段映射出现非契约键 {stage_code!r}"
)
# 契约码本身仍能正常映射:库存匹配属通知准备,processing_stage 权威生效。
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
result = project_lifecycle(
current_gate={'gate_code': 'task_creation', 'status': 'invalidated'},
blocking_reason={'code': 'gate_invalidated'},
has_candidate_context=True,
processing_stage='step5_match_inventory',
processing_stage='inventory_matching',
)
# processing_stage 权威高于错误的 task_creation 门禁。
assert result['lifecycle_stage'] == 'fulfillment_prep'
assert result['lifecycle_authority'] == 'processing_stage'
current = next(e for e in result['lifecycle_entries'] if e['state'] == 'current')
assert current['code'] == 'fulfillment_prep'
def test_fifteen_stages_inventory_source_before_review():
@@ -283,7 +283,7 @@ def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(m
id=1,
order_task_id=9,
upload_status='uploaded',
current_step='step6_generate_file',
current_step='excel_generating',
stage_nodes_json=None,
step_payload_json=None,
)
@@ -76,7 +76,7 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
extraction_run_id=int(run.id),
owner_agent_id=int(agent.id),
status='waiting_review',
stage='step5_match_inventory',
stage='inventory_matching',
progress_version=3,
)
db.session.add(order_task)
@@ -91,7 +91,7 @@ def test_service_chain_customer_confirm_projection(app, workbench_chain_ids):
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.review_status = 'pending_confirm'
notice.current_step = 'step4_match_inventory'
notice.current_step = 'inventory_matching'
notice.customer_id = 1
db.session.commit()
@@ -112,7 +112,7 @@ def test_service_chain_inventory_match_projection(app, workbench_chain_ids):
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.match_status = 'matched'
notice.current_step = 'step4_match_inventory'
notice.current_step = 'inventory_matching'
db.session.commit()
before, projection = _project_after_sync(notice, order_task, run)
@@ -130,7 +130,7 @@ def test_service_chain_excel_generate_projection(app, workbench_chain_ids):
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.upload_status = 'pending'
notice.current_step = 'step7_upload_freight'
notice.current_step = 'freight_uploading'
notice.export_file_path = '/tmp/fake-shipping.xlsx'
db.session.commit()
@@ -148,7 +148,7 @@ def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids)
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.current_step = 'step7_upload_freight'
notice.current_step = 'freight_uploading'
notice.upload_status = 'failed'
notice.export_file_path = '/tmp/fake-shipping.xlsx'
db.session.commit()