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,