Merge branch 'hugo-shipping-notice' into dev
# Conflicts: # frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
commit
80d78130f8
121 files changed
+9621
-1263
No files matched your search
@@ -63,6 +63,7 @@ frontend/package-lock.json
|
||||
*.swp
|
||||
*.swo
|
||||
.cursorrules
|
||||
.zcode
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
|
||||
@@ -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,无敏感快照)。"""
|
||||
|
||||
@@ -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
|
||||
@@ -5,6 +5,8 @@ services/shipping_notice/export.py
|
||||
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
|
||||
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
|
||||
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
|
||||
整单 ODM 裁决依次应用:客户 odm_ids 范围 → 用户选择(OT.chosen_odm_id)→
|
||||
唯一可行交集自动收敛;模板消费 odm 字段时生效;
|
||||
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
|
||||
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
|
||||
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
|
||||
@@ -45,8 +47,12 @@ from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
def _notice_source_code(task: ShippingNotice) -> str | None:
|
||||
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
|
||||
task_id = getattr(task, 'order_task_id', None)
|
||||
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
|
||||
|
||||
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
|
||||
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
|
||||
"""
|
||||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
task_id = int(task_id)
|
||||
@@ -63,6 +69,23 @@ def _notice_source_code(task: ShippingNotice) -> str | None:
|
||||
return codes[0] if len(codes) == 1 else None
|
||||
|
||||
|
||||
def _notice_chosen_odm(task: ShippingNotice) -> str | None:
|
||||
"""读取当前行级匹配事实上的整单 ODM 用户选择(notice_odm_choice_service 落库)。"""
|
||||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
values = [
|
||||
str(row[0]).strip()
|
||||
for row in db.session.query(ShippingNoticeLineInventoryMatch.chosen_odm_id).filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task_id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.chosen_odm_id.isnot(None),
|
||||
).distinct().all()
|
||||
if row[0]
|
||||
]
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
|
||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
|
||||
task_id = getattr(task, 'order_task_id', None)
|
||||
@@ -426,29 +449,7 @@ def _match_inventory_lines(
|
||||
return []
|
||||
if not match_keys:
|
||||
raise ValueError('库存解析模板缺少订单与库存匹配键')
|
||||
from app.models import ShippingInventoryField
|
||||
|
||||
ids = {
|
||||
int(item.get('inventory_field_id'))
|
||||
for item in match_keys
|
||||
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
|
||||
}
|
||||
catalog = {
|
||||
str(item.id): str(item.id)
|
||||
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
|
||||
}
|
||||
normalized_keys: list[dict[str, str]] = []
|
||||
for item in match_keys:
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError('库存解析模板匹配键无效')
|
||||
field_id = str(item.get('inventory_field_id') or '').strip()
|
||||
inventory_field = catalog.get(field_id)
|
||||
if not inventory_field:
|
||||
raise ValueError('库存解析模板引用的库存字段已不可用')
|
||||
normalized_keys.append({
|
||||
'order_field_id': str(item.get('order_field_id') or ''),
|
||||
'inventory_field': inventory_field,
|
||||
})
|
||||
normalized_keys = _normalize_match_keys(match_keys)
|
||||
result: list[dict[str, Any]] = []
|
||||
for position, order_line in enumerate(order_lines, start=1):
|
||||
expected = [
|
||||
@@ -586,34 +587,176 @@ def _input_checksum(
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def generate_shipment_excel(
|
||||
task: ShippingNotice,
|
||||
) -> tuple[str, str, ShippingExportArtifact]:
|
||||
"""
|
||||
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
|
||||
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
|
||||
def _resolve_odm_inventory_field_id() -> int | None:
|
||||
"""返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。"""
|
||||
field = ShippingInventoryField.query.filter_by(field_code='odm_id', status='active').first()
|
||||
return int(field.id) if field is not None else None
|
||||
|
||||
Returns:
|
||||
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
|
||||
|
||||
def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, str]]:
|
||||
"""
|
||||
校验并规范化库存解析模板匹配键为 {order_field_id, inventory_field} 列表。
|
||||
|
||||
Raises:
|
||||
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
|
||||
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
|
||||
ValueError: 匹配键缺失、无效或引用的库存字段已不可用。
|
||||
"""
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
ids = {
|
||||
int(item.get('inventory_field_id'))
|
||||
for item in match_keys
|
||||
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
|
||||
}
|
||||
catalog = {
|
||||
str(item.id): str(item.id)
|
||||
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
|
||||
}
|
||||
normalized_keys: list[dict[str, str]] = []
|
||||
for item in match_keys:
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError('库存解析模板匹配键无效')
|
||||
field_id = str(item.get('inventory_field_id') or '').strip()
|
||||
inventory_field = catalog.get(field_id)
|
||||
if not inventory_field:
|
||||
raise ValueError('库存解析模板引用的库存字段已不可用')
|
||||
normalized_keys.append({
|
||||
'order_field_id': str(item.get('order_field_id') or ''),
|
||||
'inventory_field': inventory_field,
|
||||
})
|
||||
return normalized_keys
|
||||
|
||||
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
|
||||
from app.models import ShippingOrderTask
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
from app.services.shipping_notice.shipping_notice_creation_service import (
|
||||
create_shipping_notice_after_inventory_gate,
|
||||
|
||||
def _per_line_odm_sets(
|
||||
order_lines: list[dict[str, Any]],
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
normalized_keys: list[dict[str, str]],
|
||||
odm_key: str,
|
||||
) -> list[set[str]]:
|
||||
"""逐导出行收集命中库存行的 odm 值集合;缺匹配键行与未命中行返回空集。"""
|
||||
sets: list[set[str]] = []
|
||||
for order_line in order_lines:
|
||||
expected = [
|
||||
(_match_text(order_line.get(item['order_field_id'])), item['inventory_field'])
|
||||
for item in normalized_keys
|
||||
]
|
||||
if any(not value for value, _field in expected):
|
||||
sets.append(set())
|
||||
continue
|
||||
matched = {
|
||||
_match_text(row.get(odm_key))
|
||||
for row in inventory_lines
|
||||
if all(_match_text(row.get(field)) == value for value, field in expected)
|
||||
}
|
||||
matched.discard('')
|
||||
sets.append(matched)
|
||||
return sets
|
||||
|
||||
|
||||
def _intersect_odm_sets(sets: list[set[str]]) -> set[str]:
|
||||
"""各行命中 odm 集合的交集;未命中行(空集)不参与约束,全部为空返回空集。"""
|
||||
active = [item for item in sets if item]
|
||||
if not active:
|
||||
return set()
|
||||
return set.intersection(*active)
|
||||
|
||||
|
||||
def _adjudicate_notice_odm(
|
||||
*,
|
||||
line_values: list[dict[str, Any]],
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
match_keys: list[dict[str, Any]],
|
||||
odm_field_id: int | None,
|
||||
snapshot: ShippingOrderSnapshot,
|
||||
chosen_odm_raw: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
整单(Notice)级 ODM 收敛裁决;模板不消费 odm 字段时直接跳过。
|
||||
|
||||
逻辑:客户 ODM ID 范围非空先过滤;用户选择(OT.chosen_odm_id)次之;
|
||||
无范围且无选择时,各导出行命中 odm 交集唯一则自动收敛(唯一可行解,无需人工)。
|
||||
多值并存时不过滤,由逐行折叠按现有契约阻断,并由工作台下发候选供用户选择。
|
||||
|
||||
Returns:
|
||||
{'inventory_lines': 收敛后的库存行, 'feasible_odm_ids': 排序候选,
|
||||
'whitelist_applied': 是否应用了客户范围, 'chosen_odm_id': 用户选择(展示值)}
|
||||
Raises:
|
||||
ValueError: 范围排除全部命中,或用户选择在当前库存中已不存在。
|
||||
"""
|
||||
result = {
|
||||
'inventory_lines': inventory_lines,
|
||||
'feasible_odm_ids': [],
|
||||
'per_line_odm_ids': [],
|
||||
'whitelist_applied': False,
|
||||
'chosen_odm_id': None,
|
||||
}
|
||||
if odm_field_id is None:
|
||||
return result
|
||||
|
||||
odm_key = str(odm_field_id)
|
||||
# 归一化值 → 原始展示值:候选/已选回显保留库存行原样大小写。
|
||||
odm_display: dict[str, str] = {}
|
||||
for row in inventory_lines:
|
||||
raw = str(row.get(odm_key) or '').strip()
|
||||
if raw:
|
||||
odm_display.setdefault(_match_text(raw), raw)
|
||||
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
|
||||
customer_odm_ids = [
|
||||
_match_text(value) for value in (customer.odm_ids or []) if _match_text(value)
|
||||
] if customer is not None else []
|
||||
chosen_odm = _match_text(chosen_odm_raw) if str(chosen_odm_raw or '').strip() else None
|
||||
result['chosen_odm_id'] = odm_display.get(chosen_odm, str(chosen_odm_raw).strip()) if chosen_odm else None
|
||||
normalized_keys = _normalize_match_keys(match_keys)
|
||||
pre_odm_sets = _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
|
||||
|
||||
if customer_odm_ids:
|
||||
result['whitelist_applied'] = True
|
||||
scope = set(customer_odm_ids)
|
||||
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in scope]
|
||||
# 范围把原本有命中的行全部排除时,必须给出指向客户数据的可行动错误,
|
||||
# 避免回落成误导性的「没有匹配的库存记录」。
|
||||
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
|
||||
raise ValueError('订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内,请检查客户数据或库存文件')
|
||||
# 逐行候选取「客户范围过滤后、选择收敛前」的集合:用户在任何一行改选,候选都来自同一口径。
|
||||
scoped_sets = (
|
||||
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
|
||||
if customer_odm_ids else pre_odm_sets
|
||||
)
|
||||
if chosen_odm:
|
||||
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) == chosen_odm]
|
||||
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
|
||||
raise ValueError('发货通知已选择的 ODM ID 在当前库存中不存在,请重新选择')
|
||||
elif not customer_odm_ids:
|
||||
# 无范围、无选择:交集唯一即唯一可行解,自动收敛;多值留给折叠阻断 + 人工选择。
|
||||
feasible = _intersect_odm_sets(pre_odm_sets)
|
||||
if len(feasible) == 1:
|
||||
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in feasible]
|
||||
result['inventory_lines'] = inventory_lines
|
||||
result['per_line_odm_ids'] = [
|
||||
sorted(odm_display.get(value, value) for value in line_set)
|
||||
for line_set in scoped_sets
|
||||
]
|
||||
result['feasible_odm_ids'] = sorted(
|
||||
odm_display.get(value, value)
|
||||
for value in _intersect_odm_sets(
|
||||
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key),
|
||||
)
|
||||
task = create_shipping_notice_after_inventory_gate(task)
|
||||
if not task_is_active(task):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
assert_notice_has_no_export_artifact(task)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""
|
||||
汇集发货 Excel 导出匹配所需的只读输入;不物化、不写库。
|
||||
|
||||
【AI 触发时机】:generate_shipment_excel 的行匹配准备,以及工作台整单 ODM
|
||||
候选投影(notice_odm_choice_service)复用,保证两者消费同一份匹配事实。
|
||||
|
||||
Returns:
|
||||
source/template/snapshot/header_values/line_values/inventory_lines/
|
||||
match_keys/line_inventory_fields/header_inventory_fields/verification/
|
||||
selected_snapshot_line_ids/release_overrides_by_line/released_export_line_indexes。
|
||||
"""
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
)
|
||||
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
|
||||
source_code = str(_notice_source_code(task) or '').strip().upper()
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
@@ -637,11 +780,6 @@ def generate_shipment_excel(
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于导出的冻结订单快照')
|
||||
header_values, all_line_values = order_field_id_values(task)
|
||||
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
reserve_available_for_artifact,
|
||||
)
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
@@ -696,6 +834,7 @@ def generate_shipment_excel(
|
||||
continue
|
||||
row = dict(values)
|
||||
row['__order_line_index'] = source_index
|
||||
row['__snapshot_line_id'] = int(line.id)
|
||||
line_values.append(row)
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
|
||||
@@ -703,8 +842,6 @@ def generate_shipment_excel(
|
||||
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
|
||||
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
|
||||
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
|
||||
from app.models import ShippingInventoryField
|
||||
|
||||
match_field_ids = {
|
||||
int(item.get('inventory_field_id'))
|
||||
for item in match_keys
|
||||
@@ -742,6 +879,90 @@ def generate_shipment_excel(
|
||||
and not isinstance(row.get('__order_line_index'), bool)
|
||||
and int(row['__order_line_index']) in released_source_line_indexes
|
||||
}
|
||||
return {
|
||||
'source': source,
|
||||
'template': template,
|
||||
'snapshot': snapshot,
|
||||
'mappings': mappings,
|
||||
'source_notice': source_notice,
|
||||
'header_values': header_values,
|
||||
'line_values': line_values,
|
||||
'inventory_lines': inventory_lines,
|
||||
'match_keys': match_keys,
|
||||
'line_inventory_fields': line_inventory_fields,
|
||||
'header_inventory_fields': header_inventory_fields,
|
||||
'verification': verification,
|
||||
'released_snapshot_line_ids': released_snapshot_line_ids,
|
||||
'selected_snapshot_line_ids': selected_snapshot_line_ids,
|
||||
'release_overrides_by_line': release_overrides_by_line,
|
||||
'released_export_line_indexes': released_export_line_indexes,
|
||||
}
|
||||
|
||||
|
||||
def generate_shipment_excel(
|
||||
task: ShippingNotice,
|
||||
) -> tuple[str, str, ShippingExportArtifact]:
|
||||
"""
|
||||
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
|
||||
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
|
||||
|
||||
Args:
|
||||
chosen_odm_id: 整单 ODM ID 用户选择(本次生成的请求参数,不落库);
|
||||
多 ODM 冲突时由工作台下发候选后随 Gate 动作传入,仅当其在当前库存命中时生效。
|
||||
|
||||
Returns:
|
||||
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
|
||||
|
||||
Raises:
|
||||
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
|
||||
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
|
||||
"""
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
|
||||
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
|
||||
from app.models import ShippingOrderTask
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
from app.services.shipping_notice.shipping_notice_creation_service import (
|
||||
create_shipping_notice_after_inventory_gate,
|
||||
)
|
||||
task = create_shipping_notice_after_inventory_gate(task)
|
||||
if not task_is_active(task):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
assert_notice_has_no_export_artifact(task)
|
||||
inputs = prepare_export_match_inputs(task)
|
||||
source = inputs['source']
|
||||
template = inputs['template']
|
||||
snapshot = inputs['snapshot']
|
||||
mappings = inputs['mappings']
|
||||
source_notice = inputs['source_notice']
|
||||
header_values = inputs['header_values']
|
||||
line_values = inputs['line_values']
|
||||
match_keys = inputs['match_keys']
|
||||
line_inventory_fields = inputs['line_inventory_fields']
|
||||
header_inventory_fields = inputs['header_inventory_fields']
|
||||
inventory_lines = inputs['inventory_lines']
|
||||
verification = inputs['verification']
|
||||
released_snapshot_line_ids = inputs['released_snapshot_line_ids']
|
||||
selected_snapshot_line_ids = inputs['selected_snapshot_line_ids']
|
||||
release_overrides_by_line = inputs['release_overrides_by_line']
|
||||
released_export_line_indexes = inputs['released_export_line_indexes']
|
||||
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
|
||||
# [STEP 3.5] 整单 ODM 裁决:客户 ODM ID 范围 → 用户选择 → 唯一可行交集自动收敛。
|
||||
odm_field_id = (
|
||||
_resolve_odm_inventory_field_id()
|
||||
if (line_inventory_fields or header_inventory_fields) else None
|
||||
)
|
||||
adjudication = _adjudicate_notice_odm(
|
||||
line_values=line_values,
|
||||
inventory_lines=inventory_lines,
|
||||
match_keys=match_keys,
|
||||
odm_field_id=odm_field_id,
|
||||
snapshot=snapshot,
|
||||
chosen_odm_raw=_notice_chosen_odm(task),
|
||||
)
|
||||
inventory_lines = adjudication['inventory_lines']
|
||||
matched_inventory_lines = _match_inventory_lines(
|
||||
line_values,
|
||||
inventory_lines,
|
||||
@@ -854,6 +1075,8 @@ def generate_shipment_excel(
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.reservation_service import reserve_available_for_artifact
|
||||
|
||||
reserve_available_for_artifact(
|
||||
source_notice,
|
||||
artifact=artifact,
|
||||
|
||||
@@ -569,7 +569,7 @@ def _trigger_freight_upload_rpa(
|
||||
timeout = _rpa_upload_timeout_seconds()
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step7_upload_freight',
|
||||
stage="freight_uploading",
|
||||
step_title='上传货代',
|
||||
status='running',
|
||||
message=t('workflow.fulfillment.upload_triggered_wait', lang=lang),
|
||||
@@ -1249,7 +1249,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
|
||||
line_result_status = str(match_payload.get('match_status') or 'unfulfillable')
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
@@ -1639,7 +1639,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
@@ -1731,7 +1731,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
**_match_step_progress_fields(
|
||||
match_status=match_status,
|
||||
@@ -1810,7 +1810,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
@@ -1867,7 +1867,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
**_match_step_progress_fields(
|
||||
match_status=match_status,
|
||||
@@ -2066,7 +2066,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step6_generate_file",
|
||||
stage="excel_generating",
|
||||
step_title="生成发货文件",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.generate_running", lang=lang),
|
||||
@@ -2120,7 +2120,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_clear_notice_invalidated_from_stage(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step6_generate_file",
|
||||
stage="excel_generating",
|
||||
step_title="生成发货文件",
|
||||
status="completed",
|
||||
message=t("workflow.fulfillment.generate_completed", lang=lang),
|
||||
@@ -2451,7 +2451,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_close_uploaded_task(task, actor_type='rpa', actor_id=None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="completed",
|
||||
message=t("workflow.fulfillment.rpa_uploaded", lang=lang),
|
||||
@@ -2507,7 +2507,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang),
|
||||
@@ -2527,7 +2527,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message=t("workflow.fulfillment.upload_failed_wait_manual", lang=lang),
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
|
||||
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据。
|
||||
逻辑:只读取 Candidate 所属 Extraction 的 accepted/corroborated Header FieldValue;站点候选不反向确认客户主体。
|
||||
客户命中分三层:canonical 等值 > 完整包含(指纹整体出现在提取值中)> 截断包含(仅人工建议);
|
||||
邮箱/域名指纹只做精确等值,禁止包含比较。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,12 +25,14 @@ from app.models import (
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
IDENTITY_MATCH_EQUALITY,
|
||||
IDENTITY_MATCH_TIER_RANK,
|
||||
canonical_identity_key,
|
||||
classify_identity_containment,
|
||||
normalize_identity_evidence_value,
|
||||
)
|
||||
|
||||
RESOLUTION_VERSION = 'shadow-v2'
|
||||
RESOLUTION_VERSION = 'shadow-v3'
|
||||
ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
|
||||
|
||||
|
||||
@@ -37,14 +41,11 @@ def _normalize(definition: dict[str, Any], value: object) -> str | None:
|
||||
try:
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
if source.get('option_key') == 'from_email':
|
||||
return normalize_email(value)
|
||||
if source.get('option_key') == 'from_domain':
|
||||
return normalize_domain(value)
|
||||
if field_config.get('normalizer_key') == 'name':
|
||||
return normalize_customer_name(value) or None
|
||||
normalized = str(value or '').strip().upper()
|
||||
return normalized or None
|
||||
return normalize_identity_evidence_value(
|
||||
value,
|
||||
option_key=source.get('option_key'),
|
||||
normalizer_key=field_config.get('normalizer_key'),
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -154,6 +155,8 @@ def _source_evidence(
|
||||
normalized = _normalize(definition, value)
|
||||
if not normalized:
|
||||
continue
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
evidence.append({
|
||||
'definition_id': definition_id,
|
||||
'definition_code': code,
|
||||
@@ -161,6 +164,8 @@ def _source_evidence(
|
||||
'target_type': definition.get('target_type'),
|
||||
'raw_value': value,
|
||||
'normalized_value': normalized,
|
||||
# 供命中分级使用:邮箱/域名指纹只做精确等值,不参与包含比较。
|
||||
'option_key': str(context_source.get('option_key') or ''),
|
||||
'weight': int(definition.get('default_weight') or 0),
|
||||
'source': source,
|
||||
})
|
||||
@@ -178,27 +183,68 @@ def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons
|
||||
}
|
||||
|
||||
|
||||
def _classify_evidence_match(
|
||||
*, runtime_value: str, evidence_value: str, option_key: str,
|
||||
) -> str | None:
|
||||
"""
|
||||
对单个已审核证据做命中分级:等值 > 完整包含 > 截断包含。
|
||||
|
||||
核心逻辑:邮箱/域名指纹语义字符(@、.)参与构成身份,只做归一化后精确等值;
|
||||
文本类指纹先比 canonical 等值(吸收标点/空白/大小写差异),再判双向包含。
|
||||
"""
|
||||
if option_key in {'from_email', 'from_domain'}:
|
||||
return IDENTITY_MATCH_EQUALITY if runtime_value == evidence_value else None
|
||||
if canonical_identity_key(runtime_value) == canonical_identity_key(evidence_value):
|
||||
return IDENTITY_MATCH_EQUALITY
|
||||
return classify_identity_containment(runtime_value, evidence_value, option_key=option_key)
|
||||
|
||||
|
||||
def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。"""
|
||||
"""
|
||||
按同定义已审核证据聚合客户候选,附命中层级;禁止排序取首条抹平歧义。
|
||||
|
||||
核心逻辑:每个(运行时证据, 注册证据)对先分级;同一客户取其最强命中层级,
|
||||
排序先按层级升序(等值候选始终排在包含候选前),再按累计权重降序。
|
||||
顶层(最强层级)候选唯一时调用方才判 unique_candidate,多家并列即 ambiguous。
|
||||
"""
|
||||
scores: dict[int, float] = defaultdict(float)
|
||||
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
tiers: dict[int, str] = {}
|
||||
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
|
||||
for item in evidence:
|
||||
if item['target_type'] != 'customer':
|
||||
continue
|
||||
records = ShippingIdentityEvidence.query.filter_by(
|
||||
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
|
||||
definition_id=item['definition_id'], status='approved',
|
||||
).all()
|
||||
for record in records:
|
||||
customer = customers.get(record.customer_id) if record.customer_id is not None else None
|
||||
if customer is None:
|
||||
continue
|
||||
match_kind = _classify_evidence_match(
|
||||
runtime_value=str(item['normalized_value'] or ''),
|
||||
evidence_value=str(record.normalized_value or ''),
|
||||
option_key=str(item.get('option_key') or ''),
|
||||
)
|
||||
if match_kind is None:
|
||||
continue
|
||||
scores[customer.id] += item['weight']
|
||||
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
|
||||
return sorted(
|
||||
[_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) for customer_id, score in scores.items()],
|
||||
key=lambda item: (-float(item['score']), int(item['customer_id'])),
|
||||
)
|
||||
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': match_kind})
|
||||
if customer.id not in tiers or IDENTITY_MATCH_TIER_RANK[match_kind] < IDENTITY_MATCH_TIER_RANK[tiers[customer.id]]:
|
||||
tiers[customer.id] = match_kind
|
||||
ranked = [
|
||||
_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id])
|
||||
for customer_id, score in scores.items()
|
||||
]
|
||||
# 客户最强层级在聚合后补写,再按(层级, 权重, 客户 ID)排序。
|
||||
for item in ranked:
|
||||
item['match_kind'] = tiers[int(item['customer_id'])]
|
||||
ranked.sort(key=lambda item: (
|
||||
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])],
|
||||
-float(item['score']),
|
||||
int(item['customer_id']),
|
||||
))
|
||||
return ranked
|
||||
|
||||
|
||||
def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
@@ -252,11 +298,20 @@ def resolve_candidate_identity(candidate: ShippingOrderCandidate, intake: Shippi
|
||||
evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake)
|
||||
customer_matches = _rank_customer_matches(evidence)
|
||||
site_matches = _rank_site_matches(evidence)
|
||||
top_score = float(customer_matches[0]['score']) if customer_matches else None
|
||||
tied = [item for item in customer_matches if float(item['score']) == top_score] if top_score is not None else []
|
||||
# [STEP] 顶层 = 候选中的最强命中层级;仅顶层唯一才 unique_candidate,
|
||||
# 强层级唯一时弱层级候选仅作展示,不参与歧义计算。
|
||||
top_tier_candidates: list[dict[str, Any]] = []
|
||||
if customer_matches:
|
||||
top_tier_rank = min(
|
||||
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] for item in customer_matches
|
||||
)
|
||||
top_tier_candidates = [
|
||||
item for item in customer_matches
|
||||
if IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] == top_tier_rank
|
||||
]
|
||||
return {
|
||||
'resolution_version': RESOLUTION_VERSION,
|
||||
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous',
|
||||
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(top_tier_candidates) == 1 else 'ambiguous',
|
||||
'evidence': evidence,
|
||||
'customer_matches': customer_matches,
|
||||
'site_matches': site_matches,
|
||||
|
||||
@@ -695,7 +695,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
|
||||
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message="本批库存快照已确认,等待匹配库存",
|
||||
|
||||
@@ -101,7 +101,7 @@ def inventory_loaded_response(
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="completed",
|
||||
message=f"已载入库存 {len(inventory_lines)} 行",
|
||||
|
||||
@@ -1212,7 +1212,7 @@ def ensure_inventory_via_rpa(
|
||||
_set_workflow_error(task, None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='running',
|
||||
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
|
||||
@@ -1240,7 +1240,7 @@ def ensure_inventory_via_rpa(
|
||||
poll_read_only = not allow_auto_retry
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
@@ -1353,7 +1353,7 @@ def ensure_inventory_via_rpa(
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message=progress_message,
|
||||
@@ -1403,7 +1403,7 @@ def ensure_inventory_via_rpa(
|
||||
_set_workflow_error(task, human_message[:500])
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=human_message,
|
||||
@@ -1553,7 +1553,7 @@ def _handle_rpa_inventory_skipped(
|
||||
_set_workflow_error(task, None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="货代系统当前无可用库存",
|
||||
@@ -1600,7 +1600,7 @@ def _handle_rpa_inventory_failed(
|
||||
})
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=_workflow_error(task),
|
||||
@@ -1950,7 +1950,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="RPA 库存文件已返回,正在读取库存快照",
|
||||
|
||||
@@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block(
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=t('workflow.inventory.unavailable', lang=lang),
|
||||
@@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
try:
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message=t("workflow.inventory.uploading", lang=lang),
|
||||
@@ -461,7 +461,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
@@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.error_message = None
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="已触发库存获取,等待各库存源回调。",
|
||||
@@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="库存 RPA 未能为全部库存源生成结果。",
|
||||
@@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
@@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
|
||||
@@ -5,7 +5,7 @@ services/shipping_notice/lifecycle_projection.py
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
|
||||
逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
|
||||
[B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
|
||||
兜底;无正式事实时保持未分类。兼容 OT.stage 上残留的 step_key 别名。
|
||||
兜底;无正式事实时保持未分类。
|
||||
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
|
||||
"""
|
||||
|
||||
@@ -75,11 +75,6 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
|
||||
'freight_uploading': 'freight_upload',
|
||||
'manual_upload_handoff': 'freight_upload',
|
||||
'completed': 'upload_complete',
|
||||
# 历史 step_key 曾被误写入 OT.stage;投影只读别名,避免工作台掉回接收解析空白页。
|
||||
'step5_match_inventory': 'fulfillment_prep',
|
||||
'step6_generate_file': 'fulfillment_prep',
|
||||
'step3_inventory_prepare': 'fulfillment_prep',
|
||||
'step7_upload_freight': 'freight_upload',
|
||||
}
|
||||
|
||||
def lifecycle_entries(
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
services/shipping_notice/notice_odm_choice_service.py
|
||||
|
||||
用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。
|
||||
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。
|
||||
逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一
|
||||
事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行
|
||||
(shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」
|
||||
圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值);
|
||||
重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch
|
||||
|
||||
_ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
|
||||
|
||||
|
||||
def _adjudication_task_id(task) -> int | None:
|
||||
"""返回裁决挂接的 OT 主键:Notice 取 order_task_id,OT 取自身 id。"""
|
||||
return getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
|
||||
|
||||
def notice_odm_options(task) -> dict[str, Any]:
|
||||
"""
|
||||
投影整单 ODM 逐行候选与当前用户选择;只读,不物化 Notice、不写库。
|
||||
|
||||
【AI 触发时机】:工作台通知准备面板需要展示「一个预约单号多个 ODM ID」的
|
||||
行级候选与已选值时调用;禁止用它替代导出收敛——实际过滤由导出裁决执行。
|
||||
|
||||
Returns:
|
||||
{odm_field_id, lines: [{snapshot_line_id, odm_values, chosen_odm_id}],
|
||||
customer_odm_ids, whitelist_applied};模板不消费 odm 字段时 lines 为空列表。
|
||||
"""
|
||||
from app.services.shipping_notice.export import (
|
||||
_adjudicate_notice_odm,
|
||||
_notice_chosen_odm,
|
||||
_resolve_odm_inventory_field_id,
|
||||
prepare_export_match_inputs,
|
||||
)
|
||||
|
||||
empty: dict[str, Any] = {
|
||||
'odm_field_id': None,
|
||||
'lines': [],
|
||||
'customer_odm_ids': [],
|
||||
'whitelist_applied': False,
|
||||
}
|
||||
# OT / Notice 都可直接投影(导出取数兼容两者);导出时再按正式链路裁决。
|
||||
try:
|
||||
inputs = prepare_export_match_inputs(task)
|
||||
except (ValueError, AppError):
|
||||
return empty
|
||||
odm_field_id = (
|
||||
_resolve_odm_inventory_field_id()
|
||||
if (inputs['line_inventory_fields'] or inputs['header_inventory_fields']) else None
|
||||
)
|
||||
if odm_field_id is None:
|
||||
return empty
|
||||
snapshot = inputs['snapshot']
|
||||
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
|
||||
customer_odm_ids = (
|
||||
[str(value or '').strip() for value in (customer.odm_ids or []) if str(value or '').strip()]
|
||||
if customer is not None else []
|
||||
)
|
||||
try:
|
||||
adjudication = _adjudicate_notice_odm(
|
||||
line_values=inputs['line_values'],
|
||||
inventory_lines=inputs['inventory_lines'],
|
||||
match_keys=inputs['match_keys'],
|
||||
odm_field_id=odm_field_id,
|
||||
snapshot=snapshot,
|
||||
chosen_odm_raw=_notice_chosen_odm(task),
|
||||
)
|
||||
except ValueError:
|
||||
# 范围排除全部命中 / 选择已失效:候选投影为空,用户需先修客户数据或重选。
|
||||
return {
|
||||
'odm_field_id': odm_field_id,
|
||||
'lines': [],
|
||||
'customer_odm_ids': customer_odm_ids,
|
||||
'whitelist_applied': True,
|
||||
}
|
||||
lines_payload = []
|
||||
for row, odm_values in zip(inputs['line_values'], adjudication['per_line_odm_ids'], strict=True):
|
||||
lines_payload.append({
|
||||
'snapshot_line_id': row.get('__snapshot_line_id'),
|
||||
'odm_values': list(odm_values),
|
||||
'chosen_odm_id': adjudication['chosen_odm_id'],
|
||||
})
|
||||
return {
|
||||
'odm_field_id': odm_field_id,
|
||||
'lines': lines_payload,
|
||||
'customer_odm_ids': customer_odm_ids,
|
||||
'whitelist_applied': adjudication['whitelist_applied'],
|
||||
}
|
||||
|
||||
|
||||
def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
保存整单 ODM ID 用户选择:更新目标行的当前匹配事实,并同步同一快照文件的行。
|
||||
|
||||
同步范围 = 与目标行 `inventory_snapshot_id` 相同的全部 is_current 匹配行
|
||||
(Header 契约是整单一个值,同文件行必须一致);校验取同步范围内各行候选的交集,
|
||||
保证选择不会把其他行变成无匹配。
|
||||
|
||||
Args:
|
||||
task: 正式 Notice 或其 OT。
|
||||
snapshot_line_id: 用户编辑的冻结订单行 ID(工作台行主键)。
|
||||
odm_id: 用户选定的 ODM ID。
|
||||
Returns:
|
||||
{task_id, odm_id, synced_line_count, odm_values}。
|
||||
Raises:
|
||||
AppError: 无当前匹配事实、行不存在,或所选值不在同步范围可行候选内
|
||||
(SHIPPING.NOTICE_ODM_CHOICE_INVALID)。
|
||||
"""
|
||||
normalized = str(odm_id or '').strip()
|
||||
options = notice_odm_options(task)
|
||||
task_id = _adjudication_task_id(task)
|
||||
if not task_id:
|
||||
raise AppError(
|
||||
code=_ODM_CHOICE_INVALID_CODE,
|
||||
message='Shipping task is required before recording ODM choice',
|
||||
http_status=409,
|
||||
)
|
||||
target_row = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(
|
||||
task_id=int(task_id),
|
||||
snapshot_line_id=int(snapshot_line_id or 0),
|
||||
is_current=True,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if target_row is None:
|
||||
raise AppError(
|
||||
code=_ODM_CHOICE_INVALID_CODE,
|
||||
message='No current inventory match fact for the given line',
|
||||
http_status=409,
|
||||
details={'snapshot_line_id': snapshot_line_id},
|
||||
)
|
||||
# 同步范围:与目标行关联同一快照文件的全部当前匹配行。
|
||||
scope_rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task_id), is_current=True)
|
||||
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id)
|
||||
.all()
|
||||
) if target_row.inventory_snapshot_id is not None else [target_row]
|
||||
lines_by_sid = {
|
||||
str(item.get('snapshot_line_id')): item for item in options.get('lines') or []
|
||||
}
|
||||
scope_candidates: list[set[str]] = []
|
||||
for row in scope_rows:
|
||||
entry = lines_by_sid.get(str(row.snapshot_line_id))
|
||||
if entry is not None:
|
||||
scope_candidates.append({str(v).strip().casefold() for v in entry.get('odm_values') or []})
|
||||
feasible: set[str] = set.intersection(*scope_candidates) if scope_candidates else set()
|
||||
if not normalized or normalized.strip().casefold() not in feasible:
|
||||
raise AppError(
|
||||
code=_ODM_CHOICE_INVALID_CODE,
|
||||
message='Selected ODM ID is not among the feasible values',
|
||||
http_status=409,
|
||||
details={'odm_id': normalized, 'odm_values': sorted(feasible)},
|
||||
)
|
||||
# 同步落库:同一快照文件的全部当前匹配行写同一选择(前后端同步语义的落库侧)。
|
||||
for row in scope_rows:
|
||||
row.chosen_odm_id = normalized
|
||||
db.session.flush()
|
||||
return {
|
||||
'task_id': int(task_id),
|
||||
'odm_id': normalized,
|
||||
'synced_line_count': len(scope_rows),
|
||||
'odm_values': sorted(feasible),
|
||||
}
|
||||
@@ -30,6 +30,7 @@ from app.services.shipping_notice import order_document_profile_lease_service as
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import (
|
||||
LAYOUT_SIGNATURE_ID,
|
||||
MATCHER_POLICY_ID,
|
||||
@@ -1235,6 +1236,15 @@ def _build_coordinate_overlap_evidence(
|
||||
definition = dict(profile.definition_json or {})
|
||||
thresholds = _match_thresholds(definition)
|
||||
schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {}
|
||||
try:
|
||||
header_to_field = compile_table_header_contract(
|
||||
schema_definition if isinstance(schema_definition, dict) else {},
|
||||
).header_to_field
|
||||
except ValidationError:
|
||||
# 冻结 Schema definition 非法(别名碰撞等)时容忍降级:None 使 overlap
|
||||
# 证据的表头原子互斥退化为词级原子,不阻断模板验证;空 definition 编译
|
||||
# 出空映射,matcher 侧与 None 同口径。
|
||||
header_to_field = None
|
||||
published = published_rival_snapshots_for_overlap(profile)
|
||||
candidates = [draft_snapshot, *published]
|
||||
sample_role_pollution = _detect_sample_role_pollution(profile)
|
||||
@@ -1243,7 +1253,9 @@ def _build_coordinate_overlap_evidence(
|
||||
outcomes: list[dict[str, Any]] = []
|
||||
for sample in samples:
|
||||
layout = _load_sample_layout(sample)
|
||||
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=candidates, layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
parse_result = None
|
||||
if match.profile_code == profile.profile_code and int(match.version or 0) == int(profile.version):
|
||||
if parse_result_resolver is not None:
|
||||
@@ -1296,7 +1308,9 @@ def _build_coordinate_overlap_evidence(
|
||||
'reason_code': 'representative_layout_unavailable',
|
||||
})
|
||||
continue
|
||||
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=candidates, layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
source_unique = (
|
||||
match.status in {'unique_match', 'selected_by_score'}
|
||||
and match.profile_code == published_snapshot.get('profile_code')
|
||||
|
||||
@@ -56,6 +56,7 @@ from app.models import (
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
|
||||
from app.services.shipping_notice.order_extraction_route_contract import (
|
||||
PARSER_ENGINE_VERSION,
|
||||
PARSER_POLICY_VERSION,
|
||||
@@ -697,6 +698,16 @@ def _load_intakes(
|
||||
return rows
|
||||
|
||||
|
||||
def _intake_filenames(intakes: list[ShippingOrderIntake]) -> list[str]:
|
||||
"""按 Intake 顺序取资产原始文件名;无资产或资产缺失以空串占位,保持计数口径。"""
|
||||
asset_ids = [int(intake.asset_id) for intake in intakes if intake.asset_id]
|
||||
if not asset_ids:
|
||||
return []
|
||||
rows = db.session.query(FileAsset.id, FileAsset.original_filename).filter(FileAsset.id.in_(asset_ids)).all()
|
||||
filename_by_id = {row[0]: str(row[1] or '') for row in rows}
|
||||
return [filename_by_id.get(int(intake.asset_id), '') for intake in intakes if intake.asset_id]
|
||||
|
||||
|
||||
def _resolve_conversation(
|
||||
*,
|
||||
user_id: int,
|
||||
@@ -713,6 +724,7 @@ def _resolve_conversation(
|
||||
intakes: 已按用户锁定且通过业务资格校验的 Intake。
|
||||
Returns:
|
||||
已存在或本事务新建的 ChatSession;调用方负责最终提交。
|
||||
新建会话的 title 由 conversation_title 按首个 Intake 文件名派生;已存在会话不改动标题。
|
||||
Raises:
|
||||
ConflictError: 所选 Intake 已分属不同会话,或与显式会话不一致。
|
||||
"""
|
||||
@@ -737,7 +749,7 @@ def _resolve_conversation(
|
||||
session_id=uuid.uuid4().hex,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title='订单抽取',
|
||||
title=derive_order_extraction_title(_intake_filenames(intakes), datetime.utcnow()),
|
||||
status='running',
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
|
||||
@@ -64,6 +64,7 @@ from app.services.shipping_notice.order_profile_value_adapter import get_value_a
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
resolve_candidate_line_numbers,
|
||||
)
|
||||
|
||||
|
||||
@@ -1071,7 +1072,12 @@ def _profile_table_candidates(
|
||||
'issues': ['order_profile_selected_identity_invalid'], 'match': profile_match,
|
||||
}
|
||||
else:
|
||||
match = match_frozen_coordinate_profiles(profiles=coordinate_profiles, layout=layout)
|
||||
# 主路由匹配与下游表格解析共用同一冻结 Schema 表头契约:matcher 侧
|
||||
# 表头原子互斥按别名归一为字段语义原子,跨措辞近亲模板不误杀。
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=coordinate_profiles, layout=layout,
|
||||
header_to_field=contract.header_to_field,
|
||||
)
|
||||
affinity_applied = False
|
||||
if not match_only:
|
||||
match = _apply_parse_validation_gate(
|
||||
@@ -1542,9 +1548,8 @@ def _apply_reparse_profile_affinity(
|
||||
), None)
|
||||
if candidate is None:
|
||||
return match, False
|
||||
verified = match_frozen_coordinate_profiles(profiles=[frozen], layout=layout)
|
||||
if verified.status != 'unique_match':
|
||||
return match, False
|
||||
# 契约编译须先于复验:复验与解析验证消费同一份冻结 Schema definition,
|
||||
# 表头原子互斥才能与正式取值走同一别名口径。
|
||||
schema_snapshot = (
|
||||
run.input_snapshot_json.get('schema')
|
||||
if isinstance(getattr(run, 'input_snapshot_json', None), dict)
|
||||
@@ -1555,6 +1560,18 @@ def _apply_reparse_profile_affinity(
|
||||
if isinstance(schema_snapshot, dict) and isinstance(schema_snapshot.get('definition'), dict)
|
||||
else {}
|
||||
)
|
||||
try:
|
||||
header_to_field = compile_table_header_contract(schema_definition).header_to_field
|
||||
except ValidationError:
|
||||
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
|
||||
# 词级原子,不阻断重识别亲和性;definition 为空时编译结果为空映射,
|
||||
# matcher 侧与 None 同口径。
|
||||
header_to_field = None
|
||||
verified = match_frozen_coordinate_profiles(
|
||||
profiles=[frozen], layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
if verified.status != 'unique_match':
|
||||
return match, False
|
||||
parse_result = validate_profile_parse_candidate(
|
||||
profile_snapshot=frozen,
|
||||
layout=layout,
|
||||
@@ -2090,14 +2107,18 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
)
|
||||
decision['parsed_table_count'] = 1
|
||||
decision['route_type'] = 'profile_deterministic'
|
||||
# 模板确定性取值已成功,复核只针对业务归属(Reservation 专区/行校验)。
|
||||
# 必须以 deterministic 携带原因码交 STP 裁 needs_review,让已解析订单
|
||||
# 继续落 provisional Candidate 供复核台编辑;review_required 会被
|
||||
# Worker 当作"无可信取值"丢弃,复核草稿将退化为空白手工单。
|
||||
if any(order.get('reservation_region_status') == 'needs_review' for order in orders):
|
||||
decision['fallback_reason_codes'] = ['reservation_region_needs_review']
|
||||
return _apply_stp_route_adjudication(
|
||||
decision, execution_mode='review_required', orders=orders,
|
||||
decision, execution_mode='deterministic', orders=orders,
|
||||
)
|
||||
if decision.get('fallback_reason_codes'):
|
||||
return _apply_stp_route_adjudication(
|
||||
decision, execution_mode='review_required', orders=orders,
|
||||
decision, execution_mode='deterministic', orders=orders,
|
||||
)
|
||||
decision['fallback_reason_codes'] = []
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
@@ -2357,11 +2378,31 @@ def _build_approved_profile_order_result(
|
||||
if candidates:
|
||||
header_target = reservation_scope.get('header')
|
||||
line_target = reservation_scope.get('line')
|
||||
# Reservation 注释的 L#n 引用单据印刷行号(LN 列),必须按 customer_po_line_no
|
||||
# 值定位逻辑行;LN 非连续(部分行已拆单)时按位置写入会错配并误报越界。
|
||||
line_numbers: list[int | None] | None = None
|
||||
if line_target:
|
||||
ln_field_id = next(
|
||||
(str(item.get('field_id') or '') for item in fields
|
||||
if str(item.get('field_code') or '') == 'customer_po_line_no'),
|
||||
None,
|
||||
)
|
||||
if ln_field_id:
|
||||
line_numbers = resolve_candidate_line_numbers([
|
||||
next(
|
||||
(observation.get('value') for field in group.get('fields') or []
|
||||
if str(field.get('field_id') or '') == ln_field_id
|
||||
for observation in field.get('observations') or []),
|
||||
None,
|
||||
)
|
||||
for group in line_groups
|
||||
])
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=candidates,
|
||||
header_field_id=str(header_target.get('field_id') or '') if header_target else None,
|
||||
line_field_id=str(line_target.get('field_id') or '') if line_target else None,
|
||||
line_count=len(line_groups),
|
||||
line_numbers=line_numbers,
|
||||
)
|
||||
if applied.header_value and header_target:
|
||||
header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {})
|
||||
@@ -2379,9 +2420,10 @@ def _build_approved_profile_order_result(
|
||||
]
|
||||
if line_target:
|
||||
for line_no, value in applied.line_values.items():
|
||||
# line_no 已是逻辑行序号;候选里携带的是印刷行号,证据只按值回查。
|
||||
line_evidence = next((
|
||||
item for item in candidates
|
||||
if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value
|
||||
if item.get('scope') == 'line' and item.get('value') == value
|
||||
), {})
|
||||
line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{
|
||||
'value': value, 'document_id': int(unit.document_id),
|
||||
@@ -2390,7 +2432,8 @@ def _build_approved_profile_order_result(
|
||||
line_id = str(line_target.get('field_id') or '')
|
||||
line_code = str(line_target.get('field_code') or '')
|
||||
for missing in source_missing_fields['lines']:
|
||||
if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1:
|
||||
# 不能用 `or -1` 兜底:line_index 0 是合法值,会被 falsy 判断跳过。
|
||||
if isinstance(missing, dict) and missing.get('line_index') == line_no - 1:
|
||||
missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id]
|
||||
missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code]
|
||||
source_missing_fields['lines'] = [
|
||||
@@ -2540,7 +2583,15 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document_model, layout=layout, page_nos=required_pages,
|
||||
)
|
||||
match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
|
||||
try:
|
||||
header_to_field = compile_table_header_contract(definition).header_to_field
|
||||
except ValidationError:
|
||||
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
|
||||
# 词级原子,confirmed 字段锁集返回空,不抛错。
|
||||
header_to_field = None
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=profiles, layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
match, _affinity_applied = _apply_reparse_profile_affinity(
|
||||
run=run, unit=unit, profiles=profiles, match=match, layout=layout,
|
||||
)
|
||||
|
||||
@@ -258,19 +258,26 @@ def retry_review_case_customer_resolution(
|
||||
case = _load_writable_case(user_id=user_id, case_no=case_no)
|
||||
matches: list[dict[str, Any]] = []
|
||||
if case.candidate_id:
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
AUTO_CONFIRM_ELIGIBLE_STATUSES,
|
||||
resolve_auto_customer_decision,
|
||||
)
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||||
if candidate is not None:
|
||||
shadow = refresh_candidate_shadow_resolution(candidate)
|
||||
# [STEP 2] 重新识别后若客户指纹唯一命中,直接写入确认结果;投影函数保持纯读。
|
||||
# [STEP 2] 重新识别后与任务期协调器共用同一分级裁决:canonical 等值唯一或
|
||||
# 「指纹完整出现」包含唯一且证据授权才自动确认;截断建议(containment_weak)
|
||||
# 只进候选展示,绝不在此确认。投影函数保持纯读。
|
||||
decision = resolve_auto_customer_decision(shadow)
|
||||
if (
|
||||
shadow.status == 'unique_candidate'
|
||||
and shadow.top_customer_id
|
||||
str(decision.get('status') or '') in AUTO_CONFIRM_ELIGIBLE_STATUSES
|
||||
and decision.get('customer_id') is not None
|
||||
and not resolve_review_case_customer_resolved(case=case, candidate=candidate)
|
||||
):
|
||||
confirm_customer_resolution(
|
||||
candidate,
|
||||
customer_id=int(shadow.top_customer_id),
|
||||
customer_id=int(decision['customer_id']),
|
||||
actor_id=None,
|
||||
method='auto_rule',
|
||||
reason='客户识别指纹唯一命中自动确认',
|
||||
|
||||
@@ -1065,6 +1065,54 @@ def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] |
|
||||
return None
|
||||
|
||||
|
||||
# 队列当前 Gate 活跃口径:在 _queue_current_gate_hint 活跃集合上补 queued/failed_terminal,
|
||||
# 供 needs_attention 兜底取 Gate,避免终态失败的单被漏判。
|
||||
_QUEUE_CURRENT_GATE_STATUSES = frozenset({
|
||||
'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal',
|
||||
})
|
||||
# 需要人工介入的 Gate 状态;waiting_external/running/pending/queued 属系统在办,不算需人工。
|
||||
_QUEUE_ATTENTION_GATE_STATUSES = frozenset({'blocked_manual', 'blocked_retryable', 'failed_terminal'})
|
||||
|
||||
|
||||
def _queue_gate_needs_attention(case: ShippingOrderReviewCase) -> bool:
|
||||
"""
|
||||
判定 Case 当前正式门禁是否需要人工介入;供队列摘要下发 needs_attention。
|
||||
|
||||
只读会话级批量缓存(_load_review_case_summary_batch 已预取 Execution/Gate),
|
||||
零额外 SQL;当前 Gate 取 execution.current_gate_code 对应 Gate,缺失时按
|
||||
sequence_no 取第一个活跃 Gate。调用方禁止据此之外再自行推断阻塞。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case。
|
||||
|
||||
Returns:
|
||||
当前 Gate 状态 ∈ {blocked_manual, blocked_retryable, failed_terminal} 时 True;
|
||||
无 Execution / 无活跃 Gate 时 False。
|
||||
"""
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
if not isinstance(cache, dict) or getattr(case, 'id', None) is None:
|
||||
return False
|
||||
execution = (cache.get('execution_by_case_id') or {}).get(int(case.id))
|
||||
if execution is None:
|
||||
return False
|
||||
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
|
||||
gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or []
|
||||
current = None
|
||||
if gate_code:
|
||||
for gate in gates:
|
||||
if str(getattr(gate, 'gate_code', '') or '').strip().lower() == gate_code:
|
||||
current = gate
|
||||
break
|
||||
if current is None:
|
||||
for gate in gates:
|
||||
if str(getattr(gate, 'status', '') or '').strip().lower() in _QUEUE_CURRENT_GATE_STATUSES:
|
||||
current = gate
|
||||
break
|
||||
if current is None:
|
||||
return False
|
||||
return str(getattr(current, 'status', '') or '').strip().lower() in _QUEUE_ATTENTION_GATE_STATUSES
|
||||
|
||||
|
||||
def _serialize_review_case_summary(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
@@ -1157,6 +1205,7 @@ def _serialize_review_case_summary(
|
||||
'status': case.status,
|
||||
'draft_version': int(draft.draft_version) if draft is not None else None,
|
||||
'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0,
|
||||
'needs_attention': _queue_gate_needs_attention(case),
|
||||
# Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。
|
||||
# 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。
|
||||
'available_actions': (
|
||||
@@ -1377,6 +1426,28 @@ def _load_review_case_summary_batch(
|
||||
}
|
||||
|
||||
|
||||
def _queue_summary_bucket(item: dict[str, Any]) -> str:
|
||||
"""
|
||||
队列计数桶归类;优先级与前端队列图标一致:需人工 > 终态完成 > 进行中。
|
||||
|
||||
桶是"处置去向"粗归类,与五态图标非一一映射(non_order 计入 completed,
|
||||
图标为中性别灰○);needs_attention(门禁阻塞)恒优先于 completed,
|
||||
避免阻塞单被计数成"完成"。
|
||||
|
||||
Args:
|
||||
item: 队列 item 投影(含 status / needs_attention / lifecycle_stage)。
|
||||
|
||||
Returns:
|
||||
'needs_action' | 'completed' | 'processing'。
|
||||
"""
|
||||
status = str(item.get('status') or '')
|
||||
if status in ('unreviewed', 'draft', 'ready', 'quality_issue') or item.get('needs_attention'):
|
||||
return 'needs_action'
|
||||
if status in ('non_order', 'closed', 'completed') or str(item.get('lifecycle_stage') or '') == 'upload_complete':
|
||||
return 'completed'
|
||||
return 'processing'
|
||||
|
||||
|
||||
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
|
||||
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
|
||||
if not runs:
|
||||
@@ -1444,10 +1515,11 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
|
||||
db.session.info.pop('shipping_conversation_projection_read_cache', None)
|
||||
else:
|
||||
db.session.info['shipping_conversation_projection_read_cache'] = previous_cache
|
||||
buckets = [_queue_summary_bucket(item) for item in items]
|
||||
counts = {
|
||||
'total': len(items),
|
||||
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
|
||||
'processing': sum(1 for item in items if item['status'] in ('confirming', 'reparse_pending')),
|
||||
'completed': sum(1 for item in items if item['status'] in ('confirmed', 'non_order', 'quality_issue')),
|
||||
'needs_action': buckets.count('needs_action'),
|
||||
'processing': buckets.count('processing'),
|
||||
'completed': buckets.count('completed'),
|
||||
}
|
||||
return {'conversation_id': conversation_id, 'summary': counts, 'items': items}
|
||||
@@ -260,25 +260,27 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
return ('completed', 'completed')
|
||||
if ps in {'waiting_upload', 'upload_failed', 'uploading'} or projected_upload == 'uploading':
|
||||
return ('automating', 'freight_uploading')
|
||||
if 'upload' in step or step.startswith('step7'):
|
||||
# [契约唯一] current_step 只存 15 阶契约码(CheckPoint stepN_* 遗留键已清除),
|
||||
# 阶段信号按契约码精确匹配,不再做子串/前缀启发式。
|
||||
if step == 'freight_uploading':
|
||||
return ('automating', 'freight_uploading')
|
||||
|
||||
if ps in {'export', 'excel', 'generating_excel'} or 'generate' in step or step.startswith('step6'):
|
||||
if ps in {'export', 'excel', 'generating_excel'} or step == 'excel_generating':
|
||||
return ('automating', 'excel_generating')
|
||||
if ps == 'matched' and export_path:
|
||||
return ('automating', 'excel_generating')
|
||||
|
||||
if ps in {'matching', 'inventory_ready', 'matched'} or 'match' in step:
|
||||
if ps in {'matching', 'inventory_ready', 'matched'} or step == 'inventory_matching':
|
||||
return ('automating', 'inventory_matching')
|
||||
|
||||
# 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。
|
||||
if ps in {'waiting_inventory', 'parsed'} or 'fetch' in step or step.startswith('step4'):
|
||||
if ps in {'waiting_inventory', 'parsed'} or step == 'inventory_fetching':
|
||||
return ('automating', 'inventory_fetching')
|
||||
|
||||
if ps == 'pending_review':
|
||||
return ('waiting_review', 'waiting_review')
|
||||
|
||||
if ps in {'creating', 'order_creating', 'confirming'} or 'create' in step or step.startswith('step3'):
|
||||
if ps in {'creating', 'order_creating', 'confirming'} or step == 'order_creating':
|
||||
return ('automating', 'order_creating')
|
||||
if ps in {'fetching_inventory', 'inventory_fetching'}:
|
||||
return ('automating', 'inventory_fetching')
|
||||
@@ -687,13 +689,8 @@ _USER_STAGE_TO_CODE: dict[str, str] = {
|
||||
'waiting_review': 'waiting_human_review',
|
||||
'inventory_fetching': 'inventory_fetch',
|
||||
'inventory_matching': 'inventory_match',
|
||||
# step_key 误写入 OT.stage 时的只读别名(与 lifecycle_projection 同源)。
|
||||
'step5_match_inventory': 'inventory_match',
|
||||
'step3_inventory_prepare': 'inventory_fetch',
|
||||
'step6_generate_file': 'excel_generate',
|
||||
'excel_generating': 'excel_generate',
|
||||
'freight_uploading': 'freight_upload',
|
||||
'step7_upload_freight': 'freight_upload',
|
||||
'completed': 'completed',
|
||||
'failed': 'failed_terminal',
|
||||
'cancelled': 'cancelled',
|
||||
|
||||
@@ -88,6 +88,13 @@ from app.services.shipping_notice.constants import (
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGE_BY_GATE,
|
||||
LIFECYCLE_STAGE_BY_PROCESSING_STAGE,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_REASON_OWNING_GATE,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
UserMode,
|
||||
resolve_task_ui_state,
|
||||
@@ -132,6 +139,17 @@ _TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
|
||||
"done": frozenset({"done"}),
|
||||
}
|
||||
|
||||
# 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」属 done 桶终态,不做筛选维度。
|
||||
_ACTIONABLE_TODO_STAGES: tuple[str, ...] = (
|
||||
"intake_parse", "order_review", "fulfillment_prep", "freight_upload",
|
||||
)
|
||||
# 无 processing_stage 且人工原因不可映射时的 todo_category 粗兜底(与 Gate 映射语义对齐)。
|
||||
_TODO_STAGE_BY_CATEGORY_FALLBACK: dict[str, str] = {
|
||||
"review": "order_review",
|
||||
"exception": "fulfillment_prep",
|
||||
"manual_upload": "freight_upload",
|
||||
}
|
||||
|
||||
# 尚未挂 OT、仍需用户/系统关注的 Intake 解析状态(进入我的待办)。
|
||||
_ORPHAN_INTAKE_TODO_PARSE_STATUSES = frozenset({
|
||||
"created",
|
||||
@@ -2762,12 +2780,14 @@ def _todo_tasks_base_query(
|
||||
customer_needle: str,
|
||||
customer_like: str,
|
||||
task_no: str | None,
|
||||
terminal_kind: str | None = None,
|
||||
):
|
||||
"""
|
||||
构造带精确 category CASE 过滤的 Task 待办查询。
|
||||
|
||||
核心逻辑:可见性 / 客户过滤后,用 _task_todo_category_sql_expr().in_(allowed);
|
||||
done 桶另加终态粗筛。pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
|
||||
done 桶另加终态粗筛;terminal_kind 进一步拆分 done 子视图(通知完成 / 驳回作废)。
|
||||
pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
|
||||
"""
|
||||
q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||||
@@ -2817,6 +2837,17 @@ def _todo_tasks_base_query(
|
||||
),
|
||||
)
|
||||
)
|
||||
# [STEP] 终态子视图过滤:前端「通知完成 / 复核驳回·已作废」子 tab 各取所需;
|
||||
# 口径与分类 CASE 的 done 分支保持一致(上传成功优先,二者互斥)。
|
||||
if terminal_kind == "upload_complete":
|
||||
q = q.filter(upload_success)
|
||||
elif terminal_kind == "reject_void":
|
||||
q = q.filter(
|
||||
db.or_(
|
||||
workflow_review_status == RS_REJECTED,
|
||||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||||
)
|
||||
)
|
||||
return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed))))
|
||||
|
||||
|
||||
@@ -2825,6 +2856,108 @@ def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
|
||||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
|
||||
|
||||
def _classify_todo_lifecycle_stage(
|
||||
category: str,
|
||||
*,
|
||||
pending_human_reason: Any = None,
|
||||
processing_stage: Any = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
按统一生命周期口径归类待办条目的阶段 tab(仅供计数,不替代 ui_state)。
|
||||
|
||||
核心逻辑:与 ``project_lifecycle`` 同优先级——processing_stage 权威 → 人工原因
|
||||
归属 Gate 兜底 → todo_category 粗兜底;结果若不是四个可动作阶段(如 completed
|
||||
映射出的 upload_complete)则返回 None,由调用方跳过,避免污染阶段 tab 计数。
|
||||
|
||||
Args:
|
||||
category: 待办分类 CASE 结果(review/exception/manual_upload/in_progress)。
|
||||
pending_human_reason: OT ``pending_human_reason`` 人工原因码(可空)。
|
||||
processing_stage: OT ``stage`` 已持久化处理阶段(可空)。
|
||||
|
||||
Returns:
|
||||
四个可动作阶段码之一;不可归入时 None。
|
||||
"""
|
||||
stage_key = str(processing_stage or '').strip().lower()
|
||||
if stage_key in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||||
stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[stage_key]
|
||||
else:
|
||||
gate = PROCESS_GATE_REASON_OWNING_GATE.get(str(pending_human_reason or '').strip())
|
||||
if gate in LIFECYCLE_STAGE_BY_GATE:
|
||||
stage = LIFECYCLE_STAGE_BY_GATE[gate]
|
||||
else:
|
||||
stage = _TODO_STAGE_BY_CATEGORY_FALLBACK.get(str(category or ''), 'fulfillment_prep')
|
||||
return stage if stage in _ACTIONABLE_TODO_STAGES else None
|
||||
|
||||
|
||||
def _my_todo_stage_counts(user_id: int, *, is_admin: bool) -> dict[str, int]:
|
||||
"""
|
||||
统计待处理桶在四个可动作阶段的分布,供前端阶段筛选 tab 展示全量计数。
|
||||
|
||||
核心逻辑:Review Case 走统一生命周期投影(候选有效性裁决 接收解析 vs 订单复核);
|
||||
孤儿 Intake 恒为接收解析;Notice / OT 分支一次取回「分类 CASE + OT stage +
|
||||
人工原因」后在 Python 侧归类,避免为计数复制一份 SQL 阶段状态机。
|
||||
|
||||
Returns:
|
||||
{intake_parse, order_review, fulfillment_prep, freight_upload}(含 0 值键)。
|
||||
"""
|
||||
counts: dict[str, int] = {code: 0 for code in _ACTIONABLE_TODO_STAGES}
|
||||
|
||||
def _bump(stage: str | None) -> None:
|
||||
if stage in counts:
|
||||
counts[str(stage)] += 1
|
||||
|
||||
# [STEP 1] 开放 Review Case:复用统一投影,禁止另写候选有效性判断。
|
||||
for case_row in _visible_open_review_cases_query(user_id, is_admin=is_admin).all():
|
||||
projection = _review_case_lifecycle_projection(case_row)
|
||||
_bump(str(projection.get('lifecycle_stage') or '').strip() or None)
|
||||
|
||||
# [STEP 2] 孤儿 Intake(未建 OT 的解析待办)恒为接收解析。
|
||||
counts["intake_parse"] += int(
|
||||
_visible_orphan_intakes_query(user_id, is_admin=is_admin).count()
|
||||
)
|
||||
|
||||
# [STEP 3] Notice 分支:分类 CASE 直接作为列取回,连同 OT stage / 人工原因归类。
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
ot_stage_subquery = select(ShippingOrderTask.stage).where(
|
||||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||||
).scalar_subquery()
|
||||
ot_reason_subquery = select(ShippingOrderTask.pending_human_reason).where(
|
||||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||||
).scalar_subquery()
|
||||
notice_rows = (
|
||||
_active_todo_tasks_scope(user_id, is_admin=is_admin)
|
||||
.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
|
||||
.with_entities(
|
||||
category_expr.label("category"),
|
||||
ot_stage_subquery.label("ot_stage"),
|
||||
ot_reason_subquery.label("ot_reason"),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for category, ot_stage, ot_reason in notice_rows:
|
||||
_bump(_classify_todo_lifecycle_stage(
|
||||
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
|
||||
))
|
||||
|
||||
# [STEP 4] OT 分支(库存准备尚未建正式 Notice)同理。
|
||||
ot_category_expr = _order_task_todo_category_sql_expr()
|
||||
ot_rows = (
|
||||
_visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
.filter(ot_category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
|
||||
.with_entities(
|
||||
ot_category_expr.label("category"),
|
||||
ShippingOrderTask.stage.label("ot_stage"),
|
||||
ShippingOrderTask.pending_human_reason.label("ot_reason"),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for category, ot_stage, ot_reason in ot_rows:
|
||||
_bump(_classify_todo_lifecycle_stage(
|
||||
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
|
||||
))
|
||||
return counts
|
||||
|
||||
|
||||
def list_my_todos(
|
||||
user_id: int,
|
||||
*,
|
||||
@@ -2835,6 +2968,7 @@ def list_my_todos(
|
||||
todo_category: str | None = None,
|
||||
customer: str | None = None,
|
||||
task_no: str | None = None,
|
||||
terminal_kind: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出「我的待办」:建单前 Review Case + 未建 OT Intake + 建单后 Task。
|
||||
@@ -2851,6 +2985,7 @@ def list_my_todos(
|
||||
todo_category: 可选细分类覆盖 bucket。
|
||||
customer: 客户名/代码/来源文件名/Case 号/PO/Intake 号模糊过滤。
|
||||
task_no: 精确任务号过滤(仅 Task 项;复核/Intake 项忽略)。
|
||||
terminal_kind: done 桶终态子视图过滤(upload_complete | reject_void);其余 bucket 忽略。
|
||||
|
||||
Returns:
|
||||
{items, page, page_size, total}
|
||||
@@ -2869,6 +3004,7 @@ def list_my_todos(
|
||||
customer_like = f"%{customer_needle}%" if customer_needle else ""
|
||||
include_review_cases = "review" in allowed and not task_no
|
||||
include_orphan_intakes = "intake_parse" in allowed and not task_no
|
||||
normalized_terminal_kind = str(terminal_kind or "").strip().lower() or None
|
||||
|
||||
# [STEP 1] 多端投影为统一列:kind / entity_id / sort_at / sort_ref。
|
||||
branches = []
|
||||
@@ -2915,6 +3051,7 @@ def list_my_todos(
|
||||
customer_needle=customer_needle,
|
||||
customer_like=customer_like,
|
||||
task_no=task_no,
|
||||
terminal_kind=normalized_terminal_kind,
|
||||
)
|
||||
branches.append(
|
||||
tasks_q.with_entities(
|
||||
@@ -3053,14 +3190,17 @@ def list_my_todos(
|
||||
}
|
||||
|
||||
|
||||
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]:
|
||||
"""
|
||||
统计「我的待办」各 bucket 数量,供导航徽标使用。
|
||||
统计「我的待办」各 bucket 数量,供导航徽标与阶段筛选 tab 使用。
|
||||
|
||||
核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT。
|
||||
核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT;
|
||||
阶段 tab 计数与 done 终态拆分见 _my_todo_stage_counts / done_counts 组装。
|
||||
|
||||
Returns:
|
||||
{pending, processing, done, total_pending_badge}
|
||||
{pending, processing, done, total_pending_badge,
|
||||
stage_counts: {intake_parse, order_review, fulfillment_prep, freight_upload},
|
||||
done_counts: {upload_complete, reject_void}}
|
||||
"""
|
||||
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
|
||||
@@ -3077,7 +3217,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))).count()
|
||||
processing = active.filter(category_expr == "in_progress").count()
|
||||
processing += ot_active.filter(ot_category == "in_progress").count()
|
||||
done = (
|
||||
done_base = (
|
||||
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
.filter(
|
||||
db.or_(
|
||||
@@ -3091,11 +3231,19 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
)
|
||||
)
|
||||
.filter(category_expr == "done")
|
||||
.count()
|
||||
)
|
||||
done = done_base.count()
|
||||
# done 拆分:已核验上传成功 vs 复核驳回/作废归档;分类 CASE 中上传成功优先,
|
||||
# 故二者互斥,reject_void 用差值即无重叠计数。
|
||||
done_upload = done_base.filter(upload_success).count()
|
||||
return {
|
||||
"pending": pending,
|
||||
"processing": processing,
|
||||
"done": done,
|
||||
"total_pending_badge": pending,
|
||||
"stage_counts": _my_todo_stage_counts(user_id, is_admin=is_admin),
|
||||
"done_counts": {
|
||||
"upload_complete": done_upload,
|
||||
"reject_void": max(0, done - done_upload),
|
||||
},
|
||||
}
|
||||
@@ -44,6 +44,9 @@ from app.models import (
|
||||
ShippingOrderReviewCase,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.error_explainability_contract import (
|
||||
UNKNOWN_BUSINESS_FAILURE_REASON_CODE,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -60,6 +63,11 @@ class BlockingReason(TypedDict, total=False):
|
||||
code: str | None
|
||||
i18n_key: str | None
|
||||
details: dict[str, Any] | None
|
||||
# 建单前资格快照回退透传字段(来自冻结 explainability 契约,
|
||||
# 见 error_explainability_contract.build_explainability_reason;
|
||||
# message 为中文兜底文案,前端优先按 i18n 命名空间解析)。
|
||||
message: str | None
|
||||
next_action: str | None
|
||||
|
||||
|
||||
class CurrentGate(TypedDict, total=False):
|
||||
@@ -723,11 +731,67 @@ def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingR
|
||||
return BlockingReason(code=None, i18n_key=None, details=details)
|
||||
i18n_key = _REASON_TO_I18N_KEY.get(raw_code)
|
||||
if i18n_key is None:
|
||||
# fail-closed:给一个通用兜底 key
|
||||
i18n_key = 'shipping.review.blocked_generic'
|
||||
# fail-closed:兜底键必须指向前端真实存在的键;此前指向不存在的
|
||||
# shipping.review.blocked_generic,任何未映射码都会在前端双重落空成
|
||||
# 「当前步骤需要人工处理」。
|
||||
i18n_key = 'chat.shippingProcessing.reasonCode.unknown'
|
||||
return BlockingReason(code=raw_code, i18n_key=i18n_key, details=details)
|
||||
|
||||
|
||||
def _blocking_reason_is_generic(reason: BlockingReason) -> bool:
|
||||
"""
|
||||
判断 blocking_reason 是否未携带具体原因(无码或仅落通用兜底键)。
|
||||
仅此情形才允许回退到资格快照,避免覆盖 automation 侧更精确的裁决。
|
||||
"""
|
||||
if not isinstance(reason, dict):
|
||||
return True
|
||||
code = str(reason.get('code') or '').strip()
|
||||
if not code:
|
||||
return True
|
||||
return str(reason.get('i18n_key') or '').strip() == 'chat.shippingProcessing.reasonCode.unknown'
|
||||
|
||||
|
||||
def _primary_validation_blocking_reason(validation: dict[str, Any] | None) -> BlockingReason | None:
|
||||
"""
|
||||
【AI 触发时机】:automation 无具体原因码,需要从草稿校验快照取首要阻断原因时。
|
||||
核心逻辑:只认 severity=blocking 且 explainability 未降级(非
|
||||
unknown_business_failure)的 issue;透传冻结契约的 message / next_action,
|
||||
本模块不新造文案或映射。无可用 issue 返回 None,由调用方保持既有兜底。
|
||||
"""
|
||||
if not isinstance(validation, dict):
|
||||
return None
|
||||
issues = validation.get('issues')
|
||||
if not isinstance(issues, list):
|
||||
return None
|
||||
for issue in issues:
|
||||
if not isinstance(issue, dict):
|
||||
continue
|
||||
if str(issue.get('severity') or '').strip().lower() != 'blocking':
|
||||
continue
|
||||
explainability = issue.get('explainability') if isinstance(issue.get('explainability'), dict) else {}
|
||||
code = str(
|
||||
explainability.get('reason_code')
|
||||
or issue.get('reason_code')
|
||||
or issue.get('code')
|
||||
or ''
|
||||
).strip()
|
||||
if not code or code == UNKNOWN_BUSINESS_FAILURE_REASON_CODE:
|
||||
continue
|
||||
details = {
|
||||
key: value for key, value in issue.items()
|
||||
if key in {'field_code', 'field_id', 'line_index', 'owning_gate_code'}
|
||||
and value is not None
|
||||
}
|
||||
return BlockingReason(
|
||||
code=code,
|
||||
i18n_key=_REASON_TO_I18N_KEY.get(code),
|
||||
details=details or None,
|
||||
message=str(explainability.get('message') or issue.get('message') or '').strip() or None,
|
||||
next_action=str(explainability.get('next_action') or '').strip() or None,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [5] user_status(F2 六值;默认人工等待 = waiting_human,禁止 idle)
|
||||
# ============================================================
|
||||
@@ -1218,6 +1282,13 @@ def project_review_case_projection_bundle(
|
||||
current_gate = project_case_current_gate(case, automation, available_actions)
|
||||
# [STEP 4] blocking_reason
|
||||
blocking_reason = project_case_blocking_reason(automation)
|
||||
# [STEP 4.1] automation 未携带具体原因时,回退到草稿校验快照的首要 blocking
|
||||
# issue:资格评估落库时已按冻结 explainability 契约附带原因文案与下一步动作,
|
||||
# 此处仅透传,让批次中心/工作台展示「客户尚未确认」等具体原因而非通用兜底。
|
||||
if _blocking_reason_is_generic(blocking_reason):
|
||||
fallback_reason = _primary_validation_blocking_reason(validation)
|
||||
if fallback_reason is not None:
|
||||
blocking_reason = fallback_reason
|
||||
# [STEP 5] user_status
|
||||
user_status = project_case_user_status(case, automation)
|
||||
# [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case
|
||||
|
||||
@@ -210,6 +210,17 @@ def project_reservation_onto_validation_evidence(
|
||||
header_field_id=str((reservation_scope.get('header') or {}).get('field_id') or '') or None,
|
||||
line_field_id=str((reservation_scope.get('line') or {}).get('field_id') or '') or None,
|
||||
line_count=len(projected['lines']),
|
||||
line_numbers=resolve_candidate_line_numbers([
|
||||
next(
|
||||
(
|
||||
field.get('normalized_value') or field.get('raw_value')
|
||||
for field in line.get('fields') or []
|
||||
if isinstance(field, dict) and str(field.get('field_code') or '') == 'customer_po_line_no'
|
||||
),
|
||||
None,
|
||||
)
|
||||
for line in projected['lines']
|
||||
]),
|
||||
)
|
||||
header_target = reservation_scope.get('header')
|
||||
if applied.header_value and header_target:
|
||||
@@ -247,20 +258,51 @@ def project_reservation_onto_validation_evidence(
|
||||
return projected
|
||||
|
||||
|
||||
def resolve_candidate_line_numbers(values: list[object]) -> list[int | None] | None:
|
||||
"""把按逻辑行顺序给出的 Customer PO 行号(LN 列)取值整理为候选定位表。
|
||||
|
||||
核心逻辑:Reservation 注释里的 ``L#n`` 引用的是单据上印刷的行号,必须按 LN 值
|
||||
定位逻辑行;LN 非连续(如部分行已拆单)时按位置写入会错配并误报越界。
|
||||
任一行解析出有效行号才返回定位表;完全没有行号取值时返回 None,
|
||||
由调用方保持历史位置序行为以兼容无 LN 字段的旧 Schema。
|
||||
"""
|
||||
numbers: list[int | None] = []
|
||||
has_number = False
|
||||
for value in values:
|
||||
try:
|
||||
number = int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
number = None
|
||||
else:
|
||||
has_number = True
|
||||
numbers.append(number)
|
||||
return numbers if has_number else None
|
||||
|
||||
|
||||
def apply_reservation_region_candidates(
|
||||
*, candidates: list[dict[str, object]], header_field_id: str | None,
|
||||
line_field_id: str | None, line_count: int,
|
||||
line_numbers: list[int | None] | None = None,
|
||||
) -> ReservationRegionApplication:
|
||||
"""按固定契约将专用区域候选归属到订单头和逻辑明细行。
|
||||
|
||||
无行号 Reservation 是整单事实,最多接受一个不同值;带行号的值仅在
|
||||
Schema 启用明细 Reservation 字段时写入对应逻辑行。冲突、越界行号或
|
||||
多个不同整单值必须转人工复核,不能静默猜测。
|
||||
|
||||
``line_numbers`` 为各逻辑行的 Customer PO 行号(LN 列,1 起始);提供时候选
|
||||
``line_no`` 按 LN 值定位逻辑行,被引用行号不存在则记 ``line_out_of_range``。
|
||||
未提供时保持历史位置序写入,仅兼容无 LN 字段的旧 Schema。
|
||||
"""
|
||||
_ = header_field_id
|
||||
header_values: list[str] = []
|
||||
line_values_by_no: dict[int, list[str]] = {}
|
||||
reasons: list[str] = []
|
||||
line_target_by_number: dict[int, int] = {}
|
||||
if line_numbers is not None:
|
||||
for index, number in enumerate(line_numbers):
|
||||
if isinstance(number, int) and number > 0:
|
||||
line_target_by_number.setdefault(number, index + 1)
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
@@ -277,6 +319,8 @@ def apply_reservation_region_candidates(
|
||||
except (TypeError, ValueError):
|
||||
reasons.append('line_out_of_range')
|
||||
continue
|
||||
if line_numbers is not None:
|
||||
line_no = line_target_by_number.get(line_no, 0)
|
||||
if line_no < 1 or line_no > line_count:
|
||||
reasons.append('line_out_of_range')
|
||||
continue
|
||||
|
||||
@@ -4003,6 +4003,33 @@ def _conversation_processing_from_work_items(
|
||||
}
|
||||
|
||||
|
||||
def _review_case_blocking_reason(
|
||||
case: ShippingOrderReviewCase | None,
|
||||
drafts_by_id: dict[int, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
建单前 Case 摘要叶子的具体阻断原因:回退到草稿校验快照的首要 blocking issue。
|
||||
|
||||
核心逻辑:资格评估落库时已按冻结 explainability 契约附带 code/message/next_action
|
||||
(见 reconciliation_projector._primary_validation_blocking_reason);摘要路径的
|
||||
drafts_by_id 已批量加载,透传零额外查询。无 Draft / 无可用 issue 返回 None,
|
||||
调用方保持 review_case_{status} 状态码兜底。
|
||||
"""
|
||||
if case is None:
|
||||
return None
|
||||
draft_id = getattr(case, 'current_draft_id', None)
|
||||
if draft_id is None:
|
||||
return None
|
||||
draft = drafts_by_id.get(int(draft_id))
|
||||
validation = getattr(draft, 'validation_result_json', None)
|
||||
if not isinstance(validation, dict):
|
||||
return None
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
_primary_validation_blocking_reason,
|
||||
)
|
||||
return _primary_validation_blocking_reason(validation)
|
||||
|
||||
|
||||
def project_conversation_processing_summary(
|
||||
*,
|
||||
user_id: int,
|
||||
@@ -4585,7 +4612,13 @@ def project_conversation_processing_summary(
|
||||
'po_number': candidate_po or None,
|
||||
},
|
||||
'current_gate': current_gate,
|
||||
'blocking_reason': {'code': reason} if reason else None,
|
||||
# v4:建单前 Case 的 review_case_{status} 状态码先回退到资格快照的
|
||||
# 首要阻断 issue(客户尚未确认等具体原因),无可用 issue 才落状态码。
|
||||
'blocking_reason': (
|
||||
_review_case_blocking_reason(case, drafts_by_id)
|
||||
if str(reason or '').startswith('review_case_')
|
||||
else ({'code': reason} if reason else None)
|
||||
),
|
||||
'primary_action': primary_action,
|
||||
'available_actions': available_actions,
|
||||
'intake_parse_authorized': intake_parse_authorized,
|
||||
|
||||
@@ -703,7 +703,7 @@ def replace_task_notice(
|
||||
intake.parse_warnings_json = cleaned_warnings
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
stage="waiting_review",
|
||||
step_title="确认解析",
|
||||
status="needs_human",
|
||||
message="发货通知文本抽取失败",
|
||||
@@ -732,7 +732,7 @@ def replace_task_notice(
|
||||
_reset_notice_edit_downstream(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step1_notice_submit",
|
||||
stage="order_creating",
|
||||
step_title="提交通知",
|
||||
status="completed",
|
||||
message="已重新上传发货通知并覆盖当前任务",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/tool_common.py
|
||||
|
||||
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract、progress_audit_contract。
|
||||
逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用;
|
||||
log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/
|
||||
freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent;
|
||||
@@ -20,6 +20,10 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
SHIPPING_PROCESSING_STAGES,
|
||||
shipping_processing_stage_index,
|
||||
)
|
||||
|
||||
|
||||
def cfg_bool(key: str, default: bool = False) -> bool:
|
||||
@@ -211,7 +215,7 @@ def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
|
||||
def set_task_step_progress(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
step_key: str,
|
||||
stage: str,
|
||||
step_title: str,
|
||||
status: str,
|
||||
message: str,
|
||||
@@ -221,13 +225,38 @@ def set_task_step_progress(
|
||||
detail: str | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。"""
|
||||
"""写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。
|
||||
|
||||
【AI 触发时机】履约工作流(库存准备/匹配/Excel/上传/通知重解析)报告阶段内
|
||||
细粒度进度或失败等待人工时调用。
|
||||
|
||||
核心逻辑:``stage`` 必须是冻结 15 阶契约码(SHIPPING_PROCESSING_STAGES 成员),
|
||||
写入 ``current_step`` 与 ``step_payload_json.current_step_progress`` 供投影展示;
|
||||
``OT.stage`` 仅按 15 阶序列【只进不退】推进——空缺时直接写入,已有值仅当新
|
||||
stage 序号不小于旧值才覆盖,保证进度上报永远不会把订单拉回早期阶段。
|
||||
|
||||
Args:
|
||||
stage: 15 阶契约码(如 inventory_fetching / inventory_matching /
|
||||
excel_generating / freight_uploading);禁止传入 CheckPoint 时代
|
||||
stepN_* 遗留键(已全部清除)。
|
||||
step_title: 展示用步骤名。
|
||||
status: 步骤执行态(running/completed/needs_human/failed 等调用方语义)。
|
||||
message: 用户可读进度说明。
|
||||
|
||||
Raises:
|
||||
ValueError: ``stage`` 不是 15 阶契约成员时立即失败(写错阶段码属于代码缺陷)。
|
||||
"""
|
||||
code = str(stage or '').strip()
|
||||
if code not in SHIPPING_PROCESSING_STAGES:
|
||||
raise ValueError(
|
||||
f'set_task_step_progress: stage must be a SHIPPING_PROCESSING_STAGES member, got {stage!r}'
|
||||
)
|
||||
owner = task
|
||||
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
|
||||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
|
||||
payload = dict(getattr(owner, 'step_payload_json', None) or {})
|
||||
progress: dict[str, Any] = {
|
||||
"step_key": step_key,
|
||||
"stage": code,
|
||||
"step_title": step_title,
|
||||
"status": status,
|
||||
"message": str(message or "").strip(),
|
||||
@@ -244,9 +273,19 @@ def set_task_step_progress(
|
||||
progress["extra"] = extra
|
||||
payload["current_step_progress"] = progress
|
||||
if hasattr(owner, 'current_step'):
|
||||
owner.current_step = step_key
|
||||
owner.current_step = code
|
||||
if hasattr(owner, 'stage'):
|
||||
owner.stage = step_key
|
||||
current_stage = str(getattr(owner, 'stage', None) or '').strip().lower()
|
||||
current_idx = shipping_processing_stage_index(current_stage)
|
||||
target_idx = shipping_processing_stage_index(code)
|
||||
# 只进不退:进度上报只允许推进或停留在既有序列位置,禁止回退
|
||||
# (历史缺陷:进度上报曾把 order_creating 踩回早期码,工作台掉回接收解析)。
|
||||
if (
|
||||
not current_stage
|
||||
or current_idx is None
|
||||
or (target_idx is not None and target_idx >= current_idx)
|
||||
):
|
||||
owner.stage = code
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
owner.step_payload_json = payload
|
||||
|
||||
|
||||
@@ -1001,6 +1001,30 @@ def _build_stage_context(
|
||||
if str(item.get('source_code') or '').strip()
|
||||
]
|
||||
|
||||
# [STEP] 整单 ODM 裁决投影:一个预约单号多个 ODM ID 时,逐行下发候选与已选
|
||||
# (同一快照文件的行同步使用同一值);投影失败不阻断工作台渲染,仅退化为无 ODM 入口。
|
||||
try:
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
|
||||
odm_projection = notice_odm_options(task)
|
||||
except Exception:
|
||||
odm_projection = {}
|
||||
odm_lines_by_sid = {
|
||||
str(item.get('snapshot_line_id')): item for item in odm_projection.get('lines') or []
|
||||
}
|
||||
for prep_line in preparation_lines:
|
||||
entry = odm_lines_by_sid.get(str(prep_line.get('snapshot_line_id')))
|
||||
if entry is None:
|
||||
continue
|
||||
prep_line['odm_values'] = list(entry.get('odm_values') or [])
|
||||
prep_line['chosen_odm_id'] = entry.get('chosen_odm_id')
|
||||
prep_line['odm_conflict'] = len(entry.get('odm_values') or []) > 1
|
||||
odm_options_payload = {
|
||||
'conflict': any(bool(item.get('odm_conflict')) for item in preparation_lines),
|
||||
'customer_odm_ids': list(odm_projection.get('customer_odm_ids') or []),
|
||||
'whitelist_applied': bool(odm_projection.get('whitelist_applied')),
|
||||
}
|
||||
|
||||
artifact = None
|
||||
attempts = []
|
||||
if getattr(task, 'id', None):
|
||||
@@ -1052,6 +1076,8 @@ def _build_stage_context(
|
||||
],
|
||||
'resolved_source_codes': list(facts.get('resolved_ok_source_codes') or []),
|
||||
'source_options': source_options,
|
||||
# 整单 ODM 裁决:conflict=True 时前端展示候选下拉,选择后可重试生成 Excel。
|
||||
'odm_options': odm_options_payload,
|
||||
'inventory_file': {
|
||||
'available': downloadable_inventory is not None,
|
||||
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""customer odm scope: add odm_ids to shipping_customers
|
||||
|
||||
Revision ID: aa11bb22cc33
|
||||
Revises: fb26bc033d27
|
||||
Create Date: 2026-09-16 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "aa11bb22cc33"
|
||||
down_revision = "fb26bc033d27"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _add_column(insp, table: str, column: sa.Column) -> None:
|
||||
if table not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns(table)}
|
||||
if column.name not in columns:
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
batch_op.add_column(column)
|
||||
|
||||
|
||||
def _drop_column(insp, table: str, name: str) -> None:
|
||||
if table not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns(table)}
|
||||
if name in columns:
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
batch_op.drop_column(name)
|
||||
|
||||
|
||||
def upgrade():
|
||||
insp = sa.inspect(op.get_bind())
|
||||
_add_column(
|
||||
insp,
|
||||
"shipping_customers",
|
||||
sa.Column("odm_ids", sa.JSON(), nullable=True),
|
||||
)
|
||||
_add_column(
|
||||
insp,
|
||||
"shipping_notice_line_inventory_matches",
|
||||
sa.Column("chosen_odm_id", sa.String(length=64), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
insp = sa.inspect(op.get_bind())
|
||||
_drop_column(insp, "shipping_notice_line_inventory_matches", "chosen_odm_id")
|
||||
_drop_column(insp, "shipping_customers", "odm_ids")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""merge migration heads
|
||||
|
||||
用途:合并平行迁移分支,恢复 Alembic 单 head 链。
|
||||
依赖:无表结构操作,仅声明多父级(aa11bb22cc33 客户 ODM 字段 × vc6a7b8c9d0e 凭证检核通知配置)。
|
||||
逻辑:hugo-shipping-notice 与 dev 两侧各自新增迁移产生分叉;本 Revision 只做图合并,
|
||||
upgrade/downgrade 均为空操作,实际 DDL 由两个父迁移各自负责。
|
||||
|
||||
Revision ID: dd22ee33ff44
|
||||
Revises: aa11bb22cc33, vc6a7b8c9d0e
|
||||
Create Date: 2026-09-17 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
revision = "dd22ee33ff44"
|
||||
down_revision = ("aa11bb22cc33", "vc6a7b8c9d0e")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py
|
||||
|
||||
用途:验证客户识别三级命中(canonical 等值 > 完整包含 > 截断包含)与受控自动确认边界。
|
||||
依赖:内存数据库、customer_normalization、identity_resolution.resolver、
|
||||
customer_auto_resolution、customer_shadow_resolution。
|
||||
逻辑:以 QCH/Quanta 真实差异形态(标点变体、c/o 截断、折行块整段提取、家族前缀、
|
||||
跨行 vs 单行证据)构造分支,断言影子候选层级、状态语义,以及自动确认只放行
|
||||
「等值唯一」与「完整包含唯一且证据授权」,截断建议永不自动确认。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import resolve_auto_customer_decision
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG,
|
||||
IDENTITY_MATCH_CONTAINMENT_WEAK,
|
||||
IDENTITY_MATCH_EQUALITY,
|
||||
canonical_identity_key,
|
||||
classify_identity_containment,
|
||||
normalize_identity_evidence_value,
|
||||
)
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
|
||||
|
||||
FIELD_ID = 'fid-ship-to-customer'
|
||||
RULE_SET_DEF_ID = 'def-ship-to-customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestCanonicalIdentityKey:
|
||||
"""canonical 键:标点/空白/大小写不敏感,中文保留。"""
|
||||
|
||||
def test_punctuation_whitespace_case_insensitive(self):
|
||||
# 关键断言:QCH 注册值与 PDF 打印值的标点/空格差异不再分裂等值命中。
|
||||
assert canonical_identity_key('QCH, INC., A NEVADA CORPORATION') == canonical_identity_key(
|
||||
'qch inc a nevada corporation',
|
||||
)
|
||||
|
||||
def test_keeps_cjk_word_chars(self):
|
||||
# 关键断言:中文客户名不被剔除,仍可参与等值比较。
|
||||
assert canonical_identity_key('英業達股份有限公司桃科廠') == '英業達股份有限公司桃科廠'
|
||||
assert canonical_identity_key('Inventec 英業達') == 'inventec英業達'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestNormalizeIdentityEvidenceValue:
|
||||
"""识别证据统一归一化:三处调用点同源,兜底分支折叠内部空白。"""
|
||||
|
||||
def test_fallback_collapses_newlines(self):
|
||||
# 关键断言:多行提取值折叠换行后可与单行注册证据等值(修复换行不对称缺陷)。
|
||||
assert normalize_identity_evidence_value('QUANTA MFG,\n1 WALDENBOOKS DR.') == 'QUANTA MFG, 1 WALDENBOOKS DR.'
|
||||
|
||||
def test_name_normalizer_strips_punctuation(self):
|
||||
assert normalize_identity_evidence_value('Hyve, Solutions', normalizer_key='name') == 'HYVESOLUTIONS'
|
||||
|
||||
def test_email_branch_keeps_semantic_chars(self):
|
||||
assert normalize_identity_evidence_value('A@B.COM', option_key='from_email') == 'a@b.com'
|
||||
|
||||
def test_blank_returns_none(self):
|
||||
assert normalize_identity_evidence_value(' ') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestClassifyIdentityContainment:
|
||||
"""双向包含分级:强=指纹完整出现;弱=提取值疑似截断;邮箱/域名不参与。"""
|
||||
|
||||
EVIDENCE = 'QCH INC., A NEVADA CORPORATION C/O QUANTA'
|
||||
|
||||
def test_strong_when_fingerprint_fully_inside_runtime(self):
|
||||
# 关键断言:折行块整段进入字段值时,完整指纹命中判强包含(可受控自动确认)。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_weak_when_runtime_is_truncation(self):
|
||||
# 关键断言:截断方向只判弱命中——剩余部分未经验证,禁止自动确认。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_fragment_below_minimum_chars_rejected(self):
|
||||
# 关键断言:'c/o'→'CO' 这类短碎片不得产生包含噪声。
|
||||
assert classify_identity_containment('c/o', self.EVIDENCE) is None
|
||||
|
||||
def test_email_domain_never_contained(self):
|
||||
assert classify_identity_containment('ops@corp.com', 'ops@corp', option_key='from_email') is None
|
||||
|
||||
def test_unrelated_values_rejected(self):
|
||||
assert classify_identity_containment('HYVE SOLUTIONS CORPORATION', self.EVIDENCE) is None
|
||||
|
||||
|
||||
def _build_identity_world(*, runtime_value: str, evidences: list[dict]):
|
||||
"""
|
||||
构建最小识别世界:发布规则集 + 单 Header 字段抽取链 + 客户/证据主数据。
|
||||
|
||||
Args:
|
||||
runtime_value: 已裁决 Header 字段值(模拟 PDF 提取结果)。
|
||||
evidences: 注册证据列表,每项含 customer_name/short_code/normalized_value,
|
||||
可选 auto(默认 True,对应 auto_match_allowed)。
|
||||
Returns:
|
||||
(candidate, intake) 供 resolve_candidate_identity / 影子刷新使用。
|
||||
"""
|
||||
user = User(username='tier-user', email='tier@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', lock_version=1, checksum='1' * 64,
|
||||
definition_json={'fields': [{
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'display_name': 'Ship To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'trim',
|
||||
}]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
definition_json = {
|
||||
'order_schema': {'id': version.id, 'version': version.version, 'checksum': version.checksum},
|
||||
'definitions': [{
|
||||
'id': RULE_SET_DEF_ID, 'definition_code': 'ship_to_customer_rule',
|
||||
'display_name': 'Ship To Customer', 'evidence_label': 'Ship To',
|
||||
'target_type': 'customer', 'context_field_id': FIELD_ID,
|
||||
'default_weight': 100, 'max_automation': 'conditional', 'status': 'active',
|
||||
'field_config': {
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'scope': 'header',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
'context_source': {'provider': 'order_field', 'option_key': None},
|
||||
'available_for_customer_identity': True,
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.add(ShippingIdentityRuleSet(version=1, status='published', definition_json=definition_json, checksum='c' * 64))
|
||||
db.session.add(ShippingIdentityDefinition(
|
||||
id=RULE_SET_DEF_ID, definition_code='ship_to_customer_rule', target_type='customer',
|
||||
context_field_id=FIELD_ID, default_weight=100, max_automation='conditional', status='active',
|
||||
))
|
||||
intake = ShippingOrderIntake(intake_no='INT-TIER', asset_id=1, user_id=user.id, parser_version='test')
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake.id, schema_version_id=version.id, input_snapshot_hash='h' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_status='accepted', decided_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_id=decision.id, value_text=runtime_value,
|
||||
))
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-TIER', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key='tier-test', candidate_status='accepted', order_extraction_id=extraction.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
for index, spec in enumerate(evidences, start=1):
|
||||
customer = ShippingCustomer(
|
||||
standard_name=spec['customer_name'], short_code=spec['short_code'], status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingIdentityEvidence(
|
||||
definition_id=RULE_SET_DEF_ID, customer_id=customer.id,
|
||||
raw_value=spec['normalized_value'], normalized_value=spec['normalized_value'],
|
||||
status='approved', auto_match_allowed=spec.get('auto', True),
|
||||
))
|
||||
db.session.commit()
|
||||
return candidate, intake
|
||||
|
||||
|
||||
class TestResolverTierMatching:
|
||||
"""影子识别三级命中与状态语义(resolve_candidate_identity)。"""
|
||||
|
||||
def test_punctuation_variant_hits_equality_tier(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:'QCH,' vs 'QCH' 标点差异经 canonical 等值命中,不再是 unmatched。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
def test_truncated_runtime_becomes_weak_suggestion(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:c/o 截断形态产出唯一弱命中候选(unique_candidate 仅表示展示层唯一),
|
||||
# match_kind=containment_weak,交由人工确认。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_wrapped_block_hits_strong_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:折行块整段提取时完整指纹出现,判强包含。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_family_prefix_stays_ambiguous(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:家族共享前缀同时包含命中 QCG/TW 两个站点客户 → ambiguous,不取首条。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Computer Inc.',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'QUANTA QCG', 'short_code': 'QCG',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. DE 2470.58.340',
|
||||
},
|
||||
{
|
||||
'customer_name': 'QUANTA TW', 'short_code': 'TWQ',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. HQ PLANT',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'ambiguous'
|
||||
assert {item['match_kind'] for item in result['customer_matches']} == {IDENTITY_MATCH_CONTAINMENT_WEAK}
|
||||
|
||||
def test_equality_beats_containment_in_order(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值候选排在包含候选之前,且顶层唯一时状态为 unique_candidate。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
names = {item['standard_name']: item for item in result['customer_matches']}
|
||||
# 关键断言:等值候选排第一,强包含候选次之;强层级唯一 → unique_candidate。
|
||||
assert result['customer_matches'][0]['standard_name'] == 'WIWYNN CZ BRNO'
|
||||
assert names['WIWYNN CZ BRNO']['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
assert names['WIWYNN CZ']['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_multiline_runtime_matches_single_line_evidence(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:运行侧换行折叠修复后,跨行提取值可与单行注册证据等值命中。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Manufacturing Nashville, LLC,\n1 Waldenbooks Dr.',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QUANTA MANUFACTURING NASHVILLE, LLC, 1 WALDENBOOKS DR.',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
|
||||
class TestAutoConfirmDecision:
|
||||
"""自动确认分级裁决(resolve_auto_customer_decision)。"""
|
||||
|
||||
def _shadow(self, candidate):
|
||||
return refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
def test_equality_unique_confirms_strong(self, app):
|
||||
with app.app_context():
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
assert decision['customer_id'] is not None
|
||||
|
||||
def test_containment_strong_unique_confirms_with_match_kind(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:指纹完整出现的唯一包含命中且证据授权 → unique_containment_match,
|
||||
# 审计证据带 match_kind=containment_strong 溯源。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_containment_match'
|
||||
assert decision['customer_id'] is not None
|
||||
assert decision['evidence'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_truncation_only_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:截断形态(本单 7911678818.PDF)永不自动确认,保持 unmatched 交人工。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_unauthorized_evidence_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:auto_match_allowed=False 的证据即使等值唯一也不自动确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION', 'auto': False,
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_equality_precedes_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值命中存在时包含命中不参与裁决,等值客户唯一即确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
customers = {c.id: c.standard_name for c in ShippingCustomer.query.all()}
|
||||
assert customers[decision['customer_id']] == 'WIWYNN CZ BRNO'
|
||||
@@ -235,6 +235,180 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [BR] blocking_reason 资格快照回退:
|
||||
# automation 无具体原因码时,回退到草稿校验快照(validation_result_json)
|
||||
# 中首要 blocking issue 的冻结 explainability 透传(code/message/next_action),
|
||||
# 让批次中心与工作台展示具体原因,而非「当前步骤需要人工处理」兜底。
|
||||
# ============================================================
|
||||
|
||||
def _validation_snapshot_with_issues(issues: list[dict]) -> dict:
|
||||
"""构造与 order_build_eligibility 持久化结构一致的 validation 快照。"""
|
||||
return {'can_build': False, 'can_auto_create': False, 'issues': issues}
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_falls_back_to_primary_validation_issue_when_automation_lacks_reason():
|
||||
"""[BR-1] automation 无具体原因码时,blocking_reason 必须回退到首要 blocking issue。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
# 断言意图:透传冻结契约的事实三元组,前端据此展示「客户尚未确认 / 确认客户」
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_validation_fallback_skips_degraded_and_non_blocking_issues():
|
||||
"""[BR-2] 降级码(unknown_business_failure)与非 blocking issue 不进入回退。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
# 仅阻断自动建单,不属用户阻断
|
||||
{
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'severity': 'auto_create_blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'llm_path_cannot_auto_freeze',
|
||||
'message': '智能识别结果尚未通过自动建单资格检查',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
# 契约降级码:不透传给用户
|
||||
{
|
||||
'code': 'weird_new_issue',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'unknown_business_failure',
|
||||
'message': '业务处理失败,请凭请求编号联系管理员',
|
||||
'next_action': '',
|
||||
},
|
||||
},
|
||||
# 首个可用 blocking issue
|
||||
{
|
||||
'code': 'required_field_missing',
|
||||
'severity': 'blocking',
|
||||
'field_code': 'reservation_id',
|
||||
'explainability': {
|
||||
'reason_code': 'required_field_missing',
|
||||
'message': '缺少创建订单所需字段',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'required_field_missing'
|
||||
assert reason['next_action'] == 'open_order_review'
|
||||
assert reason['details'].get('field_code') == 'reservation_id'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_keeps_mapped_automation_reason_over_validation_fallback(monkeypatch):
|
||||
"""[BR-3] automation 已有映射的具体原因码时不回退,避免覆盖更精确的裁决。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'project_case_automation_status',
|
||||
lambda case, *, validation, post_confirm: {
|
||||
'status': 'manual_fallback',
|
||||
'retryable': False,
|
||||
'reason_code': 'duplicate_decision_required',
|
||||
},
|
||||
)
|
||||
bundle = reconciliation_projector.project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'duplicate_decision_required'
|
||||
assert reason.get('message') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_without_usable_issues_keeps_legacy_blocking_reason():
|
||||
"""[BR-4] 快照无可用 issue 时保持既有兜底行为(不得抛错、不得造原因)。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation={'can_build': True, 'can_auto_create': True, 'issues': []},
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert isinstance(reason, dict)
|
||||
assert reason.get('message') is None
|
||||
assert reason.get('next_action') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_unmapped_automation_reason_uses_existing_generic_i18n_key():
|
||||
"""[BR-5] 未映射原因码的 fail-closed 兜底必须指向前端真实存在的键。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_blocking_reason,
|
||||
)
|
||||
|
||||
reason = project_case_blocking_reason({
|
||||
'status': 'manual_fallback',
|
||||
'reason_code': 'totally_new_unmapped_code',
|
||||
})
|
||||
|
||||
assert reason['code'] == 'totally_new_unmapped_code'
|
||||
# 此前指向不存在的 shipping.review.blocked_generic,任何未映射码都会双重落空
|
||||
assert reason['i18n_key'] == 'chat.shippingProcessing.reasonCode.unknown'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
|
||||
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
@@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
|
||||
@@ -29,6 +29,14 @@ RESERVATION_DEFINITION = {
|
||||
],
|
||||
}
|
||||
|
||||
LN_RESERVATION_DEFINITION = {
|
||||
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
|
||||
'fields': DEFINITION['fields'] + [
|
||||
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line', 'required': True},
|
||||
{'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _row(po: str, part: str) -> dict:
|
||||
return {'status': 'parsed', 'issues': [], 'fields': [
|
||||
@@ -38,6 +46,12 @@ def _row(po: str, part: str) -> dict:
|
||||
]}
|
||||
|
||||
|
||||
def _ln_row(po: str, part: str, ln: str) -> dict:
|
||||
row = _row(po, part)
|
||||
row['fields'].append({'field_id': 'ln', 'value': ln, 'quote': ln})
|
||||
return row
|
||||
|
||||
|
||||
def _page_glyphs(*lines: str) -> list[dict]:
|
||||
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
|
||||
glyphs = []
|
||||
@@ -152,6 +166,63 @@ def test_approved_pdf_marks_conflicting_reservation_region_for_review():
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_approved_pdf_maps_reservation_by_printed_ln_when_ln_non_contiguous():
|
||||
"""PO_6075309 回归:LN=1/2/4/5 非连续时 L#n 必须按 LN 值落行,整单不转复核。
|
||||
|
||||
关键断言:L#4/L#5 分别写入 LN=4/LN=5 行(旧位置序会把 L#4 错配到 LN=5 并把
|
||||
L#5 误报 line_out_of_range);行级 reservation 已全部归属后 source_missing_fields
|
||||
不得残留 line_index 0 的假缺失(``or -1`` falsy bug)。
|
||||
"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [
|
||||
_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2'),
|
||||
_ln_row('PO-1', 'P-4', '4'), _ln_row('PO-1', 'P-5', '5'),
|
||||
]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159370', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation L#1: 1000159370'},
|
||||
{'value': '1000159366', 'scope': 'line', 'line_no': 2, 'raw_text': 'Reservation L#2: 1000159366'},
|
||||
{'value': '1000159379', 'scope': 'line', 'line_no': 4, 'raw_text': 'Reservation L#4: 1000159379'},
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order.get('reservation_region_status') != 'needs_review'
|
||||
assert 'source_missing_fields' not in order
|
||||
expected_by_ln = {'1': '1000159370', '2': '1000159366', '4': '1000159379', '5': '1000159236'}
|
||||
for line in order['lines']:
|
||||
ln = next(item['observations'][0]['value'] for item in line['fields'] if item['field_id'] == 'ln')
|
||||
assert any(
|
||||
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == expected_by_ln[ln]
|
||||
for item in line['fields']
|
||||
)
|
||||
|
||||
|
||||
def test_approved_pdf_keeps_reservation_review_when_referenced_ln_row_is_missing():
|
||||
"""被引用的印刷行号在解析行中不存在时必须转复核,不得按位置静默写入。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2')]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order['reservation_region_status'] == 'needs_review'
|
||||
assert order['reservation_region_review_reasons'] == ['line_out_of_range']
|
||||
# LN=1/LN=2 行无对应候选,reservation 保持缺失供人工补录。
|
||||
assert all(
|
||||
not any(item['field_id'] == 'line-reservation' for item in line['fields'])
|
||||
for line in order['lines']
|
||||
)
|
||||
|
||||
|
||||
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
|
||||
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
|
||||
result = _reservation_region_candidates(
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
"""
|
||||
tests/test_order_profile_header_identity.py
|
||||
|
||||
用途:锁定 schema_canonical_header_atoms / schema_canonical_header_tokens 的表头
|
||||
别名语义归一行为,及其在表头原子硬互斥(_header_discriminator_atoms_conflict)
|
||||
与 signature_conflict 二次机会门禁中的防回归契约;含真实故障单 PO_6075316
|
||||
(日期换词 + 相邻列并格 + 空串 token)的形状回归。
|
||||
依赖:order_profile_matcher.schema_canonical_header_atoms /
|
||||
schema_canonical_header_tokens / _header_token_atoms /
|
||||
_header_discriminator_atoms_conflict。
|
||||
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
|
||||
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
|
||||
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
|
||||
别名的契约下跨措辞对齐,异义词不归并。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_header_discriminator_atoms_conflict,
|
||||
_header_token_atoms,
|
||||
schema_canonical_header_atoms,
|
||||
schema_canonical_header_tokens,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_none_or_empty_mapping_degrades_to_word_atoms():
|
||||
"""未配置别名表时必须与既有词级原子化完全一致(零行为变化)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', 'Unit Price']
|
||||
# 关键断言:None 与空 dict 均退化为 _header_token_atoms,结果与直接调用逐项相等
|
||||
assert schema_canonical_header_atoms(tokens, None) == _header_token_atoms(tokens)
|
||||
assert schema_canonical_header_atoms(tokens, {}) == _header_token_atoms(tokens)
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记原子
|
||||
assert not any(
|
||||
atom.startswith('field::')
|
||||
for atom in schema_canonical_header_atoms(tokens, None)
|
||||
)
|
||||
|
||||
|
||||
def test_exact_phrase_hit_emits_field_marker():
|
||||
"""别名精确命中时短语整体替换为 field::<field_code>,不残留短语内单词。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{'requested ship date': 'requested_receipt_date'},
|
||||
)
|
||||
# 关键断言:命中段落被消费,仅剩语义标记原子,词级原子 requested/ship/date 不再出现
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_merged_cell_greedy_decomposition():
|
||||
"""合并格长文案按贪心最长短语分解为多个 field 标记原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:两个别名短语各自命中并消费整段,互不残留单词原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date', 'field::unit_price'})
|
||||
|
||||
|
||||
def test_greedy_prefers_longest_phrase():
|
||||
"""同一位置长短短语重叠时必须取最长短语(贪心最长匹配)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{
|
||||
'ship date': 'ship_date',
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:最长短语胜出且整段消费,短短语不产生任何残留 field/词级原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_case_insensitive_matching():
|
||||
"""表头与别名 key 大小写不同仍命中(casefold 同源词管线)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['UNIT PRICE'],
|
||||
{'Unit Price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:大小写差异不阻断短语命中,field_code 保留别名表原样
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_unmatched_words_kept_and_short_words_filtered():
|
||||
"""未命中别名的词沿用既有过滤:长度 >=3 且非虚词才保留为词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Total Amount ok the ab'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:total/amount 保留;'ok'/'ab' 过短被滤;'the' 为虚词被滤
|
||||
assert atoms == frozenset({'total', 'amount'})
|
||||
|
||||
mixed = schema_canonical_header_atoms(
|
||||
['Unit Price Remarks ok'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:同一 token 内 field 标记原子与词级原子可共存
|
||||
assert mixed == frozenset({'field::unit_price', 'remarks'})
|
||||
|
||||
|
||||
def test_empty_tokens_skipped():
|
||||
"""空串/纯空白 token(MinerU 空格占位)直接跳过且不影响其余 token。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['', ' ', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:空白 token 不产生原子也不中断匹配,后续 token 照常命中
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_chinese_alias_yields_no_field_atom():
|
||||
"""中文别名切词为空 → 自然跳过(有意行为:词级原子只保留 [a-z0-9])。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['数量', 'Qty'],
|
||||
{'数量': 'quantity'},
|
||||
)
|
||||
# 关键断言:中文别名不产生 field:: 原子;词级原子口径不变(qty 长度 >=3 保留)
|
||||
assert atoms == frozenset({'qty'})
|
||||
|
||||
|
||||
def test_casefold_collision_phrase_discarded():
|
||||
"""同一短语 casefold 后映射到多个 field_code → 整体弃用,回退词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{
|
||||
'Ship Date': 'ship_date',
|
||||
'ship date': 'requested_ship_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:歧义短语不得产出任何 field:: 原子;未命中单词走既有过滤保留
|
||||
assert atoms == frozenset({'ship', 'date'})
|
||||
|
||||
|
||||
def test_casefold_equal_duplicate_alias_kept():
|
||||
"""同短语重复别名但 field_code 仅大小写不同 → 不视为歧义,短语保留。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{'Ship Date': 'ship_date', 'SHIP DATE': 'SHIP_DATE'},
|
||||
)
|
||||
# 关键断言:casefold 视角同码不构成身份歧义,短语照常产出标记原子
|
||||
assert atoms == frozenset({'field::ship_date'})
|
||||
|
||||
|
||||
# --- PO_6075316 真实故障形状回归:别名契约 vs 表头原子硬互斥 ---
|
||||
|
||||
_SIGNATURE_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
_PO6075316_OBSERVED_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
_SCHEMA_V4_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _po6075316_signature() -> dict:
|
||||
"""训练签名(命中模板 HYVE)的明细表 header_tokens 形状。"""
|
||||
return {'table_patterns': [{'header_tokens': list(_SIGNATURE_TRAINING_TOKENS)}]}
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_passes_with_ship_date_alias_contract():
|
||||
"""PO_6075316 形状(日期换词+并格+空串)在含 Ship Date 别名契约下不再互斥。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:两侧经 Schema 别名归一后字段语义原子全等,硬互斥判定为不冲突
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is False
|
||||
# 佐证:'Requested Ship Date' 与 'Requested Arrival Date' 归一为同一标记原子;
|
||||
# 并格长文案贪心分解出日期+单价两个标记原子;空串 token(MinerU 占位)零原子。
|
||||
assert schema_canonical_header_atoms(
|
||||
observed['header_tokens'], _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) == schema_canonical_header_atoms(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_still_conflicts_without_alias_contract():
|
||||
"""同形状不传契约(或契约缺 Ship Date 别名)时互斥仍在——豁免效果来自别名。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:不传 header_to_field 时两侧退化词级原子,arrival≠ship,既有互斥零变化
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(), observed=observed,
|
||||
) is True
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _SCHEMA_V4_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
# 关键断言:契约缺 Ship Date 别名时观测侧 ship 退回词级原子,互斥依旧成立
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
) is True
|
||||
|
||||
|
||||
def test_po6075316_foreign_date_word_not_merged_by_alias():
|
||||
"""日期列换成未配别名的真正异义词(Customer PO Date)时不得归并,互斥仍触发。"""
|
||||
observed = {'header_tokens': [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Customer PO Date Unit Price', '', 'Extension',
|
||||
]}
|
||||
# 关键断言:别名契约只归并已治理措辞,不同语义字段(客户 PO 日期)保持互斥
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is True
|
||||
|
||||
|
||||
# --- schema_canonical_header_tokens:序列语义 canonical 归一(二次机会门禁供料) ---
|
||||
|
||||
def test_tokens_none_or_empty_mapping_returns_input_list_unchanged():
|
||||
"""None/空 dict 时原样返回输入列表(零归一,与 atoms 的退化口径一致)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', '']
|
||||
# 关键断言:None 与空 dict 均不做任何归一,列表内容原样返回
|
||||
assert schema_canonical_header_tokens(tokens, None) == tokens
|
||||
assert schema_canonical_header_tokens(tokens, {}) == tokens
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记项
|
||||
assert not any(item.startswith('field::') for item in schema_canonical_header_tokens(tokens, None))
|
||||
|
||||
|
||||
def test_tokens_hit_phrase_collapses_to_single_item_and_keeps_order():
|
||||
"""命中片段坍缩为单个 field 标记列表项,且保持在原 token 的序列位置。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Requested Ship Date', 'Remarks', 'Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:命中短语各坍缩为单列表项并按原顺序交错排列,短语内单词不残留
|
||||
assert canonical == [
|
||||
'field::requested_receipt_date', 'remarks', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_sequence_semantics_keeps_duplicates_and_unmatched_words():
|
||||
"""序列语义:允许重复、未命中词原样保留——与 atoms 的集合语义形成对照。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Unit Price', 'Total Amount ok the ab', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:重复 token 各自产出标记项(不去重);total/amount 原词保序保留;
|
||||
# 'ok'/'ab' 过短、'the' 为虚词被滤(与 atoms 同一过滤口径)
|
||||
assert canonical == [
|
||||
'field::unit_price', 'total', 'amount', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_dedup_equals_atoms_same_source_semantics():
|
||||
"""同源语义:同一输入下 tokens 版去重即 atoms 版结果(同管线同短语匹配)。"""
|
||||
tokens = ['', ' ', 'Requested Ship Date Unit Price', 'Vendor Item#', 'ok the ab']
|
||||
mapping = {
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
'vendor item': 'part_number',
|
||||
}
|
||||
canonical = schema_canonical_header_tokens(tokens, mapping)
|
||||
atoms = schema_canonical_header_atoms(tokens, mapping)
|
||||
# 关键断言:序列版去重后与集合版逐项相等——两条路径完全同源,不得漂移
|
||||
assert set(canonical) == set(atoms)
|
||||
# 关键断言:空白 token 不产出列表项(与 atoms 跳过口径一致)
|
||||
assert len(canonical) == len([item for item in canonical if item])
|
||||
|
||||
|
||||
def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
|
||||
"""PO_6075316 形状在含 Ship Date 别名下两侧 canonical 序列逐项相等(保序)。"""
|
||||
canonical_expected = schema_canonical_header_tokens(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
canonical_observed = schema_canonical_header_tokens(
|
||||
_PO6075316_OBSERVED_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
# 关键断言:并格长文案贪心分解出的标记原子序列与训练侧完全一致(含顺序),
|
||||
# 供二次机会门禁按序列比较得出满配额软分
|
||||
assert canonical_expected == canonical_observed
|
||||
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
|
||||
assert canonical_expected[0] == 'field::customer_po_line_no'
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/tests/test_shipping_conversation_title.py
|
||||
|
||||
用途:验证订单抽取会话标题纯函数的派生规则(前缀剥离/截断/计数后缀/日期/回退)。
|
||||
依赖:纯函数,无 Flask/DB 夹具。
|
||||
逻辑:命名是内容派生的确定性函数,用逐条断言锁定规则,防止后续误改口径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
|
||||
|
||||
|
||||
def test_strips_leading_mail_prefixes_and_appends_date():
|
||||
"""首个文件名循环剥离 Re/Fw/Fwd/回复/转发 前缀,末尾追加 MM-DD。"""
|
||||
title = derive_order_extraction_title(['回复:转发:FWD: PO#6075309.eml'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 09-15'
|
||||
|
||||
|
||||
def test_multi_files_appends_count_suffix():
|
||||
"""文件总数大于 1 时追加「等 N 个文件」,N 按传入文件名总数计。"""
|
||||
title = derive_order_extraction_title(['PO#6075309.eml', 'invoice.pdf', 'list.pdf'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 等 3 个文件 09-15'
|
||||
|
||||
|
||||
def test_truncates_long_name_to_24_chars():
|
||||
"""主名超过 24 字符截断,且不吞掉日期后缀。"""
|
||||
title = derive_order_extraction_title(['A' * 30 + '.pdf'], datetime(2026, 12, 31))
|
||||
assert title == 'A' * 24 + ' 12-31'
|
||||
|
||||
|
||||
def test_blank_filenames_fall_back_to_default():
|
||||
"""文件名全空(含空列表与纯空白项)回退写死标题「订单抽取」。"""
|
||||
assert derive_order_extraction_title([], datetime(2026, 9, 15)) == '订单抽取'
|
||||
assert derive_order_extraction_title(['', ' '], datetime(2026, 9, 15)) == '订单抽取'
|
||||
@@ -0,0 +1,227 @@
|
||||
"""
|
||||
backend/tests/test_shipping_done_line_report.py
|
||||
|
||||
用途:已完成通知明细行报表(done-lines)查询与专用导出的单测。
|
||||
依赖:pytest、openpyxl、ShippingNotice/OT/Snapshot/Artifact 夹具、done_line_report。
|
||||
逻辑:覆盖 12 字段映射(typed 列 + field_values_json 回源与回退)、可见性(非本人不可见、
|
||||
未上传成功不进报表)、客户/料号/发货通知日期筛选、分页、导出表头与留空行为。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
)
|
||||
from app.services.shipping_notice.done_line_report import (
|
||||
DONE_REPORT_HEADERS,
|
||||
build_done_lines_xlsx,
|
||||
list_done_notice_lines,
|
||||
)
|
||||
|
||||
|
||||
def _seed_report_fixture(db, *, owner: int):
|
||||
"""最小报表夹具:一张已完成双行通知 + 一张仅 ready 未上传的通知(应被排除)。"""
|
||||
order = ShippingOrderTask(task_no="OT-DONE-LINE", source_type="direct_pdf", user_id=owner)
|
||||
pending_order = ShippingOrderTask(task_no="OT-DONE-LINE-PENDING", source_type="direct_pdf", user_id=owner)
|
||||
notice = ShippingNotice(task_no="SN-DONE-LINE", source_type="manual", user_id=owner)
|
||||
pending_notice = ShippingNotice(task_no="SN-DONE-LINE-PENDING", source_type="manual", user_id=owner)
|
||||
db.session.add_all([order, pending_order, notice, pending_notice])
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='DONELINE', display_name='DoneLine', version=1, status='published',
|
||||
storage_bucket='test', storage_key='done.xlsx', original_filename='done.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='DONELINE', display_name='DoneLine', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='DONELINE', display_name='DoneLine')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
|
||||
# 标准字段资产:约定出货日期(行级)与来源单号(表头级),值为 field_id 键 JSON。
|
||||
db.session.add(ShippingOrderField(
|
||||
id='f-req-date', field_code='required_date', scope='line', value_type='date',
|
||||
field_category='order_line', collection_mode='deterministic_context',
|
||||
asset_kind='system_standard', storage_mode='typed_column', storage_column='required_date',
|
||||
))
|
||||
db.session.add(ShippingOrderField(
|
||||
id='f-source-order', field_code='source_order_number', scope='header', value_type='string',
|
||||
field_category='order_header', collection_mode='deterministic_context',
|
||||
asset_kind='system_standard', storage_mode='json_only',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
customer_name='HYVE CS', customer_code='HC001', customer_po_number='306085',
|
||||
order_date=date(2026, 6, 1), required_date=date(2026, 6, 15),
|
||||
header_values_json={'f-source-order': '8301-2606010052'},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, line_no=1,
|
||||
part_number='B3-A08AR10000017-A6', qty=80, unit_price=1525.08,
|
||||
field_values_json={'f-req-date': '2026-06-15'},
|
||||
),
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=2, line_no=2,
|
||||
part_number='D4-A08AR12000001', qty=1000, unit_price=898.72,
|
||||
field_values_json={},
|
||||
),
|
||||
])
|
||||
order.order_snapshot_id = snapshot.id
|
||||
notice.order_task_id = order.id
|
||||
|
||||
extraction_two = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='e' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction_two)
|
||||
db.session.flush()
|
||||
pending_snapshot = ShippingOrderSnapshot(
|
||||
task_id=pending_order.id, extraction_id=extraction_two.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
customer_name='PENDING CS', customer_code='PC001',
|
||||
)
|
||||
db.session.add(pending_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=pending_snapshot.id, position=1, line_no=1, part_number='X-1', qty=1,
|
||||
))
|
||||
pending_order.order_snapshot_id = pending_snapshot.id
|
||||
pending_notice.order_task_id = pending_order.id
|
||||
|
||||
def add_artifact(target, *, artifact_no: str, status: str) -> None:
|
||||
"""为 Notice 建立报表口径所需的最小 Artifact。"""
|
||||
db.session.add(ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=target.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
))
|
||||
|
||||
add_artifact(notice, artifact_no='ART-DONE-LINE', status='uploaded')
|
||||
add_artifact(pending_notice, artifact_no='ART-DONE-LINE-PENDING', status='ready')
|
||||
db.session.commit()
|
||||
return notice
|
||||
|
||||
|
||||
def test_list_done_notice_lines_maps_standard_fields(app):
|
||||
"""明细行平铺不按 OT 聚合;12 字段含 JSON 回源与表头回退,无数据源字段留空。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 88
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
result = list_done_notice_lines(owner, page=1, page_size=20)
|
||||
# 断言:仅 uploaded 通知进入报表;两行明细平铺,OT 不聚合。
|
||||
assert result["total"] == 2
|
||||
assert {item["line_no"] for item in result["items"]} == {1, 2}
|
||||
first = next(item for item in result["items"] if item["line_no"] == 1)
|
||||
# 断言:溯源编号 + 标准 12 字段映射。
|
||||
assert first["task_no"] == "SN-DONE-LINE"
|
||||
assert first["customer_name"] == "HYVE CS"
|
||||
assert first["customer_code"] == "HC001"
|
||||
assert first["order_date"] == "2026-06-01"
|
||||
assert first["part_number"] == "B3-A08AR10000017-A6"
|
||||
assert first["qty"] == 80.0
|
||||
# 行级 field_values_json 有值时优先于快照表头 typed 列。
|
||||
assert first["required_date"] == "2026-06-15"
|
||||
assert first["customer_po_number"] == "306085"
|
||||
assert first["source_order_number"] == "8301-2606010052"
|
||||
assert first["unit_price"] == 1525.08
|
||||
# 已用数量 / open qty 当前无数据源,契约留空。
|
||||
assert first["used_qty"] is None
|
||||
assert first["open_qty"] is None
|
||||
second = next(item for item in result["items"] if item["line_no"] == 2)
|
||||
# 断言:行级无 required_date 时回退快照表头 typed 列。
|
||||
assert second["required_date"] == "2026-06-15"
|
||||
assert second["source_order_number"] == "8301-2606010052"
|
||||
|
||||
# 断言:其他用户不可见(非管理员仅创建者)。
|
||||
assert list_done_notice_lines(999)["total"] == 0
|
||||
|
||||
|
||||
def test_list_done_notice_lines_filters_and_pagination(app):
|
||||
"""客户/料号/发货通知日期筛选与按明细行分页生效。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 89
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
# 客户模糊(大小写不敏感)。
|
||||
assert list_done_notice_lines(owner, customer="hyve")["total"] == 2
|
||||
assert list_done_notice_lines(owner, customer="不存在")["total"] == 0
|
||||
# 料号模糊(命中单行)。
|
||||
part_page = list_done_notice_lines(owner, part_number="B3-")
|
||||
assert part_page["total"] == 1
|
||||
assert part_page["items"][0]["part_number"] == "B3-A08AR10000017-A6"
|
||||
# 发货通知日期范围:今天闭区间命中;未来区间为空。
|
||||
today = datetime.utcnow().date()
|
||||
assert list_done_notice_lines(
|
||||
owner, notice_date_from=today.isoformat(), notice_date_to=today.isoformat(),
|
||||
)["total"] == 2
|
||||
tomorrow = (today + timedelta(days=1)).isoformat()
|
||||
assert list_done_notice_lines(owner, notice_date_from=tomorrow)["total"] == 0
|
||||
# 按明细行分页。
|
||||
page_one = list_done_notice_lines(owner, page=1, page_size=1)
|
||||
page_two = list_done_notice_lines(owner, page=2, page_size=1)
|
||||
assert page_one["total"] == 2
|
||||
assert {page_one["items"][0]["line_no"], page_two["items"][0]["line_no"]} == {1, 2}
|
||||
|
||||
|
||||
def test_build_done_lines_xlsx_writes_fixed_twelve_columns(app):
|
||||
"""导出严格 12 列标准格式:OT 编号不落列,无数据源列留空。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 90
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
stream, filename = build_done_lines_xlsx(owner)
|
||||
assert filename.startswith("done-lines-") and filename.endswith(".xlsx")
|
||||
workbook = load_workbook(stream)
|
||||
sheet = workbook.active
|
||||
rows = list(sheet.iter_rows(values_only=True))
|
||||
# 断言:表头为固定 12 列中文标准格式。
|
||||
assert tuple(rows[0]) == DONE_REPORT_HEADERS
|
||||
# 断言:两行明细,且不含 OT 编号列;数量/单价写数值,无数据源列留空。
|
||||
assert len(rows) == 3
|
||||
first_data = rows[1]
|
||||
assert first_data[0] == "HYVE CS"
|
||||
assert first_data[3] == 1
|
||||
assert first_data[4] == "B3-A08AR10000017-A6"
|
||||
assert first_data[5] == 80.0
|
||||
assert first_data[8] is None
|
||||
assert first_data[9] is None
|
||||
assert first_data[10] == "8301-2606010052"
|
||||
assert first_data[11] == 1525.08
|
||||
@@ -896,3 +896,260 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
|
||||
with pytest.raises(RuntimeError, match='commit failed'):
|
||||
_commit_generated_export(str(path))
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def _build_multi_odm_notice(
|
||||
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
|
||||
):
|
||||
"""
|
||||
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
|
||||
|
||||
Args:
|
||||
odm_values: 单订单行场景下库存行命中的 ODM 值列表。
|
||||
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
|
||||
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
|
||||
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
|
||||
Returns:
|
||||
(notice, customer)。
|
||||
"""
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema); db.session.flush()
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add(version); db.session.flush()
|
||||
draft = excel_template.create_draft(_workbook_upload(), {
|
||||
'template_code': 'ODMSCOPE', 'display_name': 'OdmScope',
|
||||
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
|
||||
{'sheet': 'Detail', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
||||
]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', version=1, status='published', file_format='xlsx',
|
||||
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', login_url='https://invalid',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login]); db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
source_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
customer = ShippingCustomer(
|
||||
standard_name='ODM范围客户', short_code='ODMSC', status='active',
|
||||
odm_ids=list(customer_odm_ids) if customer_odm_ids is not None else None,
|
||||
)
|
||||
db.session.add(customer); db.session.flush()
|
||||
ot = ShippingOrderTask(task_no='OT-ODMSCOPE', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(ot); db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction); db.session.flush()
|
||||
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
|
||||
snapshot_lines = []
|
||||
for index, spec in enumerate(specs, start=1):
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
|
||||
db.session.add(order_line); db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
|
||||
decision_status='accepted', resolved_value_json=spec['part'],
|
||||
)
|
||||
db.session.add(decision); db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
|
||||
value_text=spec['part'], decision_id=decision.id,
|
||||
))
|
||||
snapshot_lines.append((index, part.id, spec['part'], 1, f'100000000{index}'))
|
||||
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
|
||||
inventory_rows = []
|
||||
for spec in specs:
|
||||
for odm in spec['odm_values']:
|
||||
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
storage_path=str(tmp_path / 'odm-scope.xlsx'),
|
||||
inventory_lines_json=inventory_rows,
|
||||
line_count=len(inventory_rows), share_mode='task_only', warehouse_id='DUB', source_code='ODMSCOPE',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add(inventory_file); db.session.flush()
|
||||
snapshot = _freeze_export_snapshot(
|
||||
ot, extraction, version,
|
||||
lines=snapshot_lines,
|
||||
customer_id=customer.id, inventory_file_id=inventory_file.id,
|
||||
)
|
||||
notice = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
|
||||
)
|
||||
if choice_odm is not None:
|
||||
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
match.chosen_odm_id = choice_odm
|
||||
db.session.flush()
|
||||
return notice, customer
|
||||
|
||||
|
||||
def test_export_narrows_odm_by_customer_range(app, tmp_path):
|
||||
"""客户 ODM ID 范围非空时,导出只取范围内库存行;范围命中唯一值写入表头。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['odm-2'],
|
||||
)
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
|
||||
"""客户范围把全部命中排除时,必须报指向客户数据的可行动错误而非「没有匹配」。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-9'],
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='不在客户数据维护的 ODM ID 范围'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_export_applies_notice_odm_choice(app, tmp_path):
|
||||
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], choice_odm='odm-2',
|
||||
)
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_auto_narrows_unique_feasible_odm_without_manual_choice(app, tmp_path):
|
||||
"""无范围、无选择时,整单唯一可行 ODM(各行命中交集恰一个)自动收敛。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
|
||||
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
|
||||
{'part': 'PN-B', 'odm_values': ['ODM-2']},
|
||||
])
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
|
||||
"""无范围、无选择且多值并存时维持折叠冲突阻断,等待用户整单选择。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'])
|
||||
|
||||
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
|
||||
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
|
||||
from app.core.errors import AppError
|
||||
from app.services.shipping_notice.notice_odm_choice_service import (
|
||||
notice_odm_options,
|
||||
set_notice_odm_choice,
|
||||
)
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-2', 'ODM-3'],
|
||||
)
|
||||
|
||||
options = notice_odm_options(task)
|
||||
|
||||
# [断言] 逐行候选是客户范围过滤后的集合,且保留库存行原始大小写。
|
||||
assert options['whitelist_applied'] is True
|
||||
assert options['customer_odm_ids'] == ['ODM-2', 'ODM-3']
|
||||
assert len(options['lines']) == 1
|
||||
assert options['lines'][0]['odm_values'] == ['ODM-2']
|
||||
assert options['lines'][0]['chosen_odm_id'] is None
|
||||
|
||||
snapshot_line_id = options['lines'][0]['snapshot_line_id']
|
||||
result = set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-2')
|
||||
|
||||
assert result['odm_id'] == 'ODM-2'
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert matches and {m.chosen_odm_id for m in matches} == {'ODM-2'}
|
||||
options = notice_odm_options(task)
|
||||
assert options['lines'][0]['chosen_odm_id'] == 'ODM-2'
|
||||
|
||||
with pytest.raises(AppError) as exc:
|
||||
set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-9')
|
||||
assert getattr(exc.value, 'code', '') == 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
|
||||
|
||||
|
||||
def test_notice_odm_choice_syncs_same_snapshot_file_lines(app, tmp_path):
|
||||
"""同一快照文件的行:改任一行 ODM ID,其余行同步落库同一选择。"""
|
||||
from app.services.shipping_notice.notice_odm_choice_service import (
|
||||
notice_odm_options,
|
||||
set_notice_odm_choice,
|
||||
)
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
|
||||
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
|
||||
{'part': 'PN-B', 'odm_values': ['ODM-2', 'ODM-3']},
|
||||
])
|
||||
|
||||
options = notice_odm_options(task)
|
||||
# [断言] 每行有自己的候选;同文件两行的可行集=交集。
|
||||
by_sid = {str(item['snapshot_line_id']): item for item in options['lines']}
|
||||
assert len(by_sid) == 2
|
||||
assert options['lines'][0]['odm_values'] == ['ODM-1', 'ODM-2']
|
||||
|
||||
target_sid = options['lines'][0]['snapshot_line_id']
|
||||
result = set_notice_odm_choice(
|
||||
task, snapshot_line_id=target_sid, odm_id='ODM-2',
|
||||
)
|
||||
|
||||
# [断言] 同步范围=同一快照文件:两行当前匹配行写同一选择。
|
||||
assert result['synced_line_count'] == 2
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert len(matches) == 2
|
||||
assert {m.chosen_odm_id for m in matches} == {'ODM-2'}
|
||||
options = notice_odm_options(task)
|
||||
assert all(item['chosen_odm_id'] == 'ODM-2' for item in options['lines'])
|
||||
|
||||
|
||||
def test_notice_odm_options_empty_when_template_ignores_odm(app, tmp_path):
|
||||
"""模板不消费 odm 字段时投影为空候选,不产生任何选择入口。"""
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1'])
|
||||
options = notice_odm_options(task)
|
||||
assert options['odm_field_id'] is not None
|
||||
assert options['lines'] and options['lines'][0]['odm_values'] == ['ODM-1']
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
backend/tests/test_shipping_my_todo_stage_counts.py
|
||||
|
||||
用途:「我的待办」count 聚合扩展单测(阶段 tab 计数 + 已完成子终态拆分)。
|
||||
依赖:pytest、ShippingNotice / ShippingOrderTask / Artifact 夹具、query_service.count_my_todos。
|
||||
逻辑:覆盖 processing_stage 权威 / 人工原因归属 Gate / todo_category 兜底三路阶段归类;
|
||||
done 桶拆分为已核验上传成功与 复核驳回/作废 两类终态计数。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.constants import RS_REJECTED
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
|
||||
|
||||
def test_count_my_todos_reports_stage_counts_and_done_breakdown(app):
|
||||
"""阶段 tab 计数按权威口径归类;done 拆分为上传成功与驳回作废两类。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 77
|
||||
# [STEP] 四个待处理条目分别覆盖三路归类路径:
|
||||
# OT.stage 权威(waiting_review→订单复核)、原因映射(upload_rpa_failed→货代上传、
|
||||
# inventory_source_unresolved→通知准备)、类别兜底(artifact ready 人工上传→货代上传)。
|
||||
review_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-REVIEW", stage="waiting_review",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
upload_rpa_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-UPLOAD-RPA", pending_human_reason="upload_rpa_failed",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
inventory_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-INVENTORY", pending_human_reason="inventory_source_unresolved",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
rejected_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-REJECTED", review_status=RS_REJECTED,
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
manual_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-MANUAL", source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
manual_notice = ShippingNotice(task_no="SN-STAGE-MANUAL", source_type="manual", user_id=owner)
|
||||
done_notice = ShippingNotice(task_no="SN-STAGE-DONE", source_type="manual", user_id=owner)
|
||||
rejected_notice = ShippingNotice(task_no="SN-STAGE-REJECTED", source_type="manual", user_id=owner)
|
||||
db.session.add_all([
|
||||
review_task, upload_rpa_task, inventory_task, rejected_task, manual_task,
|
||||
manual_notice, done_notice, rejected_notice,
|
||||
])
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='STAGE', display_name='Stage', version=1, status='published',
|
||||
storage_bucket='test', storage_key='stage.xlsx', original_filename='stage.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='STAGE', display_name='Stage', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='STAGE', display_name='Stage')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
manual_notice.order_task_id = manual_task.id
|
||||
rejected_notice.order_task_id = rejected_task.id
|
||||
|
||||
def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact:
|
||||
"""为 Notice 建立待办分类所需的最小正式 Excel Artifact。"""
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
)
|
||||
db.session.add(artifact)
|
||||
return artifact
|
||||
|
||||
# 人工上传待登记(ready→manual_upload);已完成(uploaded→done/upload_complete);
|
||||
# 驳回终态(ready 但 OT 复核驳回→done/reject_void)。
|
||||
add_artifact(manual_notice, artifact_no='ART-STAGE-MANUAL', status='ready')
|
||||
add_artifact(done_notice, artifact_no='ART-STAGE-DONE-UP', status='uploaded')
|
||||
add_artifact(rejected_notice, artifact_no='ART-STAGE-REJ', status='ready')
|
||||
db.session.commit()
|
||||
|
||||
counts = count_my_todos(owner)
|
||||
|
||||
# 断言:四个待处理条目按权威口径落入正确阶段 tab。
|
||||
assert counts["pending"] == 4
|
||||
assert counts["stage_counts"] == {
|
||||
"intake_parse": 0,
|
||||
"order_review": 1,
|
||||
"fulfillment_prep": 1,
|
||||
"freight_upload": 2,
|
||||
}
|
||||
# 断言:done 拆分——uploaded Artifact 计上传成功,OT 复核驳回计驳回作废。
|
||||
assert counts["done"] == 2
|
||||
assert counts["done_counts"] == {"upload_complete": 1, "reject_void": 1}
|
||||
|
||||
# 断言:terminal_kind 子视图过滤——两个终态子 tab 各自只取对应集合,互不重叠。
|
||||
upload_page = list_my_todos(owner, bucket="done", terminal_kind="upload_complete")
|
||||
assert {item["task_no"] for item in upload_page["items"]} == {"SN-STAGE-DONE"}
|
||||
reject_page = list_my_todos(owner, bucket="done", terminal_kind="reject_void")
|
||||
assert {item["task_no"] for item in reject_page["items"]} == {"SN-STAGE-REJECTED"}
|
||||
# 无过滤参数时保持既有行为:done 全量。
|
||||
assert list_my_todos(owner, bucket="done")["total"] == 2
|
||||
@@ -538,7 +538,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result['status'] == 'ok', result
|
||||
assert result['data']['stage'] == 'step5_match_inventory'
|
||||
assert result['data']['stage'] == 'inventory_matching'
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
|
||||
snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id)
|
||||
assert snapshot is not None
|
||||
|
||||
@@ -212,6 +212,35 @@ def test_reservation_region_requires_review_when_numbered_value_has_no_line_targ
|
||||
assert applied.review_reasons == ('line_field_unavailable',)
|
||||
|
||||
|
||||
def test_reservation_region_matches_line_by_printed_ln_number_not_position():
|
||||
"""LN 非连续(部分行已拆单)时必须按 LN 值定位逻辑行,禁止位置错配或误报越界。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text(
|
||||
"Reservation L#1: 1000159370\nReservation L#2: 1000159366\n"
|
||||
"Reservation L#4: 1000159379\nReservation L#5: 1000159236"
|
||||
),
|
||||
header_field_id='header-reservation', line_field_id='line-reservation',
|
||||
line_count=4, line_numbers=[1, 2, 4, 5],
|
||||
)
|
||||
|
||||
assert applied.needs_review is False
|
||||
# 键是逻辑行序号:L#4→第 3 行(LN=4)、L#5→第 4 行(LN=5)。
|
||||
assert applied.line_values == {1: '1000159370', 2: '1000159366', 3: '1000159379', 4: '1000159236'}
|
||||
|
||||
|
||||
def test_reservation_region_flags_review_when_referenced_ln_number_is_absent():
|
||||
"""被引用的印刷行号在解析行中不存在时必须转复核,不得静默按位置写入。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text("Reservation L#5: 1000159236"),
|
||||
header_field_id='header-reservation', line_field_id='line-reservation',
|
||||
line_count=2, line_numbers=[1, 2],
|
||||
)
|
||||
|
||||
assert applied.line_values == {}
|
||||
assert applied.needs_review is True
|
||||
assert applied.review_reasons == ('line_out_of_range',)
|
||||
|
||||
|
||||
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
|
||||
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_conversation_title.py
|
||||
|
||||
用途:验证订单抽取新建会话按 Intake 资产文件名派生标题,且已存在会话标题一律不动。
|
||||
依赖:全局 Flask/SQLite 测试夹具(app)、Run service 的会话解析内部函数。
|
||||
逻辑:新建分支走 conversation_title 派生;追加归属等存量路径保持原标题(含「订单抽取」)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatSession, FileAsset, ShippingOrderIntake, User
|
||||
from app.services.shipping_notice.order_extraction_run_service import _resolve_conversation
|
||||
|
||||
|
||||
def _seed_user_agent(suffix: str) -> tuple[User, Agent]:
|
||||
"""构造用户与货代 Agent;suffix 保证同文件内多用例数据隔离。"""
|
||||
user = User(username=f'title-user-{suffix}', email=f'title-{suffix}@example.com', password_hash='x')
|
||||
agent = Agent(
|
||||
name=f'Title Agent {suffix}',
|
||||
agent_code='shipping_notice',
|
||||
runtime_provider='hybrid',
|
||||
dify_app_id=f'title-agent-{suffix}',
|
||||
dify_api_key='test-key',
|
||||
is_active=True,
|
||||
)
|
||||
user.agents.append(agent)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
return user, agent
|
||||
|
||||
|
||||
def _seed_intake(suffix: str, user: User, filename: str, conversation_id: str | None = None) -> ShippingOrderIntake:
|
||||
"""构造带资产文件名的已解析 Intake。"""
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-TITLE-{suffix}',
|
||||
owner_user_id=user.id,
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/{filename}',
|
||||
content_hash=(suffix.lower() * 64)[:64],
|
||||
file_size=10,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-TITLE-{suffix}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
return intake
|
||||
|
||||
|
||||
def test_new_session_title_derives_from_intake_filenames(app):
|
||||
"""新建会话:标题 = 首个文件名(剥离邮件前缀)+ 等 N 个文件 + 日期后缀。"""
|
||||
user, agent = _seed_user_agent('NEW')
|
||||
first = _seed_intake('NEW1', user, 'RE: PO#6075309 for HOXIN.eml')
|
||||
second = _seed_intake('NEW2', user, 'invoice.pdf')
|
||||
|
||||
session = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[first, second])
|
||||
|
||||
# 日期后缀来自 utcnow,断言前缀避免对当天日期产生脆弱依赖。
|
||||
assert session.title.startswith('PO#6075309 for HOXIN 等 2 个文件 ')
|
||||
|
||||
|
||||
def test_existing_session_title_stays_untouched(app):
|
||||
"""已存在会话:即便标题仍是写死的「订单抽取」,Intake 归属也不改标题。"""
|
||||
user, agent = _seed_user_agent('KEEP')
|
||||
session = ChatSession(session_id='title-session-keep', user_id=user.id, agent_id=agent.id, title='订单抽取')
|
||||
db.session.add(session)
|
||||
db.session.flush()
|
||||
intake = _seed_intake('KEEP1', user, 'RE: PO#6075309.eml', conversation_id=session.session_id)
|
||||
|
||||
resolved = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[intake])
|
||||
|
||||
assert resolved.session_id == session.session_id
|
||||
assert resolved.title == '订单抽取'
|
||||
@@ -5,6 +5,7 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_extract_matching_signature,
|
||||
_observe_layout_features,
|
||||
_resolve_coordinate_transform,
|
||||
_signature_identity_header_tokens,
|
||||
match_frozen_coordinate_profiles,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import (
|
||||
@@ -1386,3 +1387,125 @@ def test_observe_layout_features_applies_business_row_clip():
|
||||
assert bbox is not None
|
||||
assert bbox[3] < 0.62
|
||||
assert bbox[3] > 0.50
|
||||
|
||||
|
||||
# --- PO_6075316 路由级合成回归:别名契约经二次机会门禁清空两道表头硬门禁 ---
|
||||
|
||||
# 训练签名(命中模板 HYVE)的明细表 header_tokens 形状。
|
||||
_PO6075316_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
# 故障 PDF(PO_6075316)观测形状:日期词变更 + 相邻列并格 + 一个 MinerU 空串占位。
|
||||
_PO6075316_FAULT_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
# Schema v4 相关别名(归一化 key → field_code),含治理后的 Requested Ship Date。
|
||||
_PO6075316_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _column_header_glyphs(tokens: list[str], *, x_start: float = 40.0, y0: float = 76.0, y1: float = 88.0, column_gap: float = 12.0) -> list[dict]:
|
||||
"""按列生成表头字符证据。
|
||||
|
||||
列内空格不额外步进(合并格文案保持为单一 span,空格由 boundary 恢复);
|
||||
列间留大间隔强制 positioned_token_spans 切分;空串列不产出字符。
|
||||
"""
|
||||
glyphs: list[dict] = []
|
||||
cursor = x_start
|
||||
for token in tokens:
|
||||
first_of_column = True
|
||||
for index, char in enumerate(token):
|
||||
if char == ' ':
|
||||
continue
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': cursor, 'y0': y0, 'x1': cursor + 3, 'y1': y1},
|
||||
'boundary_before': 'none' if first_of_column else ('space' if index and token[index - 1] == ' ' else 'none'),
|
||||
})
|
||||
first_of_column = False
|
||||
cursor += 4.0
|
||||
cursor += column_gap
|
||||
return glyphs
|
||||
|
||||
|
||||
def _layout_with_column_header(tokens: list[str], *, page_width: float = 640) -> dict:
|
||||
"""以指定列 token 形状构造坐标 layout(沿用 _layout 骨架,整体替换表头字符)。"""
|
||||
layout = _layout()
|
||||
layout['coordinate_evidence']['pages']['1']['width'] = page_width
|
||||
header = _column_header_glyphs(tokens)
|
||||
layout['coordinate_evidence']['tables']['table-1'] = header
|
||||
layout['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
|
||||
*header,
|
||||
]
|
||||
return layout
|
||||
|
||||
|
||||
def test_header_alias_contract_clears_all_po6075316_header_hard_gates():
|
||||
"""路由重放 PO_6075316:含 Ship Date 别名的契约清空 discriminator 与
|
||||
signature_conflict 两道表头硬门禁(二次机会:canonical 序列复评达标)。"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
|
||||
# 构造守卫:冻结签名 token 必须与训练形状逐字一致,防止证据管线漂移使断言空转。
|
||||
signature_body, _ = _extract_matching_signature(profile)
|
||||
assert _signature_identity_header_tokens(signature_body) == _PO6075316_TRAINING_TOKENS
|
||||
|
||||
with_contract = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=_PO6075316_HEADER_TO_FIELD,
|
||||
)
|
||||
without_contract = match_frozen_coordinate_profiles(profiles=[profile], layout=fault)
|
||||
|
||||
contract_candidate = with_contract.candidates[0]
|
||||
plain_candidate = without_contract.candidates[0]
|
||||
# 关键断言:别名契约下第一道 discriminator 互斥被 canonical 原子全等豁免。
|
||||
assert 'profile_header_discriminator_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:第二道 signature_conflict 门禁被二次机会清空——原始分被词级互斥
|
||||
# 压成 0 后,canonical 序列复用同一打分逻辑重估,effective >= 0.35 不再硬拒。
|
||||
assert 'profile_header_signature_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:两道表头硬门禁全清后候选成为硬匹配(表头类原因码不为拦路面)。
|
||||
assert contract_candidate.hard_match is True
|
||||
# 关键断言:不传契约时同形状仍被词级原子互斥拒绝——互斥机制本身未被别名破坏。
|
||||
assert 'profile_header_discriminator_conflict' in plain_candidate.reason_codes
|
||||
|
||||
|
||||
def test_header_alias_contract_without_ship_date_alias_keeps_hard_rejection():
|
||||
"""反向用例:契约缺 Ship Date 别名时二次机会不生效,候选仍被表头硬门禁拒绝。
|
||||
|
||||
证明二次机会来自别名本身而非门禁放水。缺 Ship Date 别名时两侧 canonical
|
||||
原子不再全等,先触发 discriminator 分支——if/elif 结构下 signature_conflict
|
||||
分支被前置分支吸收(不得并列上报同根因),故拦路码为 discriminator;
|
||||
断言落点是「仍被硬拒」:hard_match False 且综合分归零。
|
||||
"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _PO6075316_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
|
||||
partial = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
)
|
||||
candidate = partial.candidates[0]
|
||||
# 关键断言:缺 Ship Date 别名 → 跨措辞(ship vs arrival)无法归一 → 硬互斥仍在。
|
||||
assert 'profile_header_discriminator_conflict' in candidate.reason_codes
|
||||
# 关键断言:候选仍被硬拒(综合分归零、非硬匹配)——别名缺失绝不放行。
|
||||
assert candidate.hard_match is False
|
||||
assert candidate.score == 0.0
|
||||
@@ -372,7 +372,7 @@ def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(ap
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -2962,3 +2962,254 @@ def test_run_lineage_root_walk_loads_parent_runs_without_frozen_snapshot_columns
|
||||
for statement in point_loads:
|
||||
assert 'input_snapshot_json' not in statement
|
||||
assert 'result_json' not in statement
|
||||
|
||||
|
||||
def test_review_queue_flags_blocked_gate_cases_as_needs_attention(app):
|
||||
"""门禁 blocked_manual(如库存缺口)的已建任务单,队列必须下发 needs_attention=True。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NEEDS-ATTN')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-needs-attn',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-ATTN',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='active',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='inventory_sufficiency',
|
||||
sequence_no=16,
|
||||
status='blocked_manual',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
queue = serialize_review_queue([run])
|
||||
|
||||
# 关键断言:库存缺口类门禁阻塞必须在队列可见,不再只依赖当前单的完整详情。
|
||||
assert queue['items'][0]['needs_attention'] is True
|
||||
assert queue['items'][0]['lifecycle_stage'] == 'fulfillment_prep'
|
||||
# 关键断言:needs_attention 抬升 summary needs_action 桶,不得被计成完成/在办。
|
||||
assert queue['summary'] == {'total': 1, 'needs_action': 1, 'processing': 0, 'completed': 0}
|
||||
|
||||
|
||||
def test_review_queue_waiting_external_gate_is_not_needs_attention(app):
|
||||
"""RPA 外部等待(waiting_external)属于系统在办,不得标记 needs_attention。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-WAIT-EXT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-WAIT-EXT',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-wait-ext',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-WAIT',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-WAIT-EXT',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='freight_uploading',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-WAIT-EXT',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='waiting_external',
|
||||
current_gate_code='freight_upload_rpa',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='freight_upload_rpa',
|
||||
sequence_no=18,
|
||||
status='waiting_external',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:外部等待是在办不是待办,图标应走进行中而非需人工。
|
||||
assert item['needs_attention'] is False
|
||||
|
||||
|
||||
def test_review_queue_without_execution_is_not_needs_attention(app):
|
||||
"""已建任务但尚无 Execution(或缓存未命中)时,needs_attention 必须为 False。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NO-EXEC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NO-EXEC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-no-exec',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-NOEXEC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NO-EXEC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:无门禁事实时不臆造需人工标志。
|
||||
assert item['needs_attention'] is False
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_terminal_stage_as_completed(app):
|
||||
"""OT.stage=completed(通知完成)的已建任务单计入 completed,不再计入 processing。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-DONE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-DONE',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-done',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMDONE',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-DONE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='completed',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:summary 与五态图标同口径——confirmed+终态=completed 而非 processing。
|
||||
assert summary['total'] == 1
|
||||
assert summary['completed'] == 1
|
||||
assert summary['processing'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_quality_issue_as_needs_action(app):
|
||||
"""quality_issue(文件质量异常)从 completed 改归 needs_action,与黄⚠图标一致。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-QI')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-QI',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-qi',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMQI',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
case.status = 'quality_issue'
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:质量异常是待办不是完成。
|
||||
assert summary['needs_action'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['processing'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_plain_confirmed_as_processing(app):
|
||||
"""已建任务、无阻塞、非终态的 confirmed 单计入 processing(对应转圈图标)。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-PROC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-PROC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-proc',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMPROC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-PROC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:已创建任务是在办不是完成。
|
||||
assert summary['processing'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
@@ -230,18 +230,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
# 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。
|
||||
uploaded = SimpleNamespace(
|
||||
id=None,
|
||||
current_step='step7_upload', upload_status='uploaded', export_file_path=None,
|
||||
current_step='freight_uploading', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx',
|
||||
current_step='freight_uploading', upload_status='pending', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
|
||||
current_step='inventory_matching', upload_status='', match_status='matching', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
|
||||
@@ -540,7 +540,7 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None
|
||||
owner_agent_id=int(agent.id),
|
||||
candidate_id=None,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -1660,7 +1660,7 @@ def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app)
|
||||
intake_id=intake.id,
|
||||
candidate_id=candidate.id,
|
||||
status='waiting_review',
|
||||
stage='step3_inventory_prepare',
|
||||
stage='inventory_fetching',
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
@@ -1876,6 +1876,73 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No
|
||||
assert summary_leaf['intake_parse_authorized'] is False
|
||||
|
||||
|
||||
def test_summary_leaf_surfaces_primary_validation_issue_for_open_case(app) -> None:
|
||||
"""摘要叶子对建单前 Case 必须透传首要资格 issue,而非 review_case_{status} 状态码。
|
||||
|
||||
回归:批次进度中心对"客户尚未确认"等具体阻断只显示「订单草稿待处理」状态文案,
|
||||
原因是叶子摘要用 Case 状态拼 blocking_reason.code;资格评估已把冻结
|
||||
explainability(code/message/next_action)持久化进 draft.validation_result_json,
|
||||
摘要路径应透传该裁决(drafts_by_id 已批量加载,零额外查询)。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-LEAF-ISSUE-REASON',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-ISSUE-REASON', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='summary-issue-reason',
|
||||
order_extraction_run_id=run.id, is_current_version=True,
|
||||
candidate_status='accepted', po_number='PO-SUMMARY-ISSUE-REASON',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
# 模拟资格评估落库的首要阻断 issue(与 order_build_eligibility 持久化结构一致)
|
||||
draft.validation_result_json = {
|
||||
'can_build': False,
|
||||
'can_auto_create': False,
|
||||
'issues': [{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
summary_leaf = next(
|
||||
child
|
||||
for rows in payload['conversation_processing']['status_groups'].values()
|
||||
for row in rows
|
||||
for child in row.get('aggregate_children', [])
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
|
||||
reason = summary_leaf['ui_state']['blocking_reason']
|
||||
# 关键断言:透传契约三元组;不得再是 review_case_draft 状态码
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
def test_summary_leaf_open_case_with_queued_stp_is_running_not_waiting_human(app) -> None:
|
||||
"""开放 Case 若已有 queued STP Job,摘要必须进系统处理中,不得误报待人工。
|
||||
|
||||
@@ -2860,7 +2927,7 @@ def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(a
|
||||
conversation_id=session.session_id,
|
||||
intake_id=int(intake.id),
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
progress_version=1,
|
||||
@@ -3139,7 +3206,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
progress_version=1,
|
||||
|
||||
@@ -36,21 +36,39 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage():
|
||||
)
|
||||
|
||||
|
||||
def test_legacy_step_key_stage_maps_to_fulfillment_prep():
|
||||
"""OT.stage 若残留 step5_match_inventory,生命周期必须进通知准备而非接收解析。"""
|
||||
def test_stage_mapping_rejects_checkpoint_legacy_keys():
|
||||
"""CheckPoint stepN_* 遗留键已全部清除:阶段映射只认 15 阶契约码。
|
||||
|
||||
历史缺陷:step_key 被写进 OT.stage,靠投影别名兜底;现写路径只产出契约码
|
||||
(set_task_step_progress 校验 + 存量迁移清洗),别名不得再存在。
|
||||
"""
|
||||
legacy_keys = [
|
||||
'step1_notice_submit',
|
||||
'step2_parse_confirm',
|
||||
'step3_inventory_prepare',
|
||||
'step5_match_inventory',
|
||||
'step6_generate_file',
|
||||
'step7_upload_freight',
|
||||
]
|
||||
for key in legacy_keys:
|
||||
assert key not in LIFECYCLE_STAGE_BY_PROCESSING_STAGE, (
|
||||
f"CheckPoint 遗留键 {key!r} 不得再进入阶段映射"
|
||||
)
|
||||
for stage_code in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||||
assert not str(stage_code).startswith('step'), (
|
||||
f"阶段映射出现非契约键 {stage_code!r}"
|
||||
)
|
||||
# 契约码本身仍能正常映射:库存匹配属通知准备,processing_stage 权威生效。
|
||||
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
|
||||
|
||||
result = project_lifecycle(
|
||||
current_gate={'gate_code': 'task_creation', 'status': 'invalidated'},
|
||||
blocking_reason={'code': 'gate_invalidated'},
|
||||
has_candidate_context=True,
|
||||
processing_stage='step5_match_inventory',
|
||||
processing_stage='inventory_matching',
|
||||
)
|
||||
# processing_stage 权威高于错误的 task_creation 门禁。
|
||||
assert result['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert result['lifecycle_authority'] == 'processing_stage'
|
||||
current = next(e for e in result['lifecycle_entries'] if e['state'] == 'current')
|
||||
assert current['code'] == 'fulfillment_prep'
|
||||
|
||||
|
||||
def test_fifteen_stages_inventory_source_before_review():
|
||||
|
||||
@@ -283,7 +283,7 @@ def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(m
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
upload_status='uploaded',
|
||||
current_step='step6_generate_file',
|
||||
current_step='excel_generating',
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
|
||||
@@ -76,7 +76,7 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
|
||||
extraction_run_id=int(run.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_service_chain_customer_confirm_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.review_status = 'pending_confirm'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
notice.customer_id = 1
|
||||
db.session.commit()
|
||||
|
||||
@@ -112,7 +112,7 @@ def test_service_chain_inventory_match_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.match_status = 'matched'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
db.session.commit()
|
||||
|
||||
before, projection = _project_after_sync(notice, order_task, run)
|
||||
@@ -130,7 +130,7 @@ def test_service_chain_excel_generate_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.upload_status = 'pending'
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids)
|
||||
"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.upload_status = 'failed'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
@@ -5,6 +5,41 @@
|
||||
> **同步维护**:流程、字段规则、人工确认节点等变更时,**须同时更新本文件与** **`business.md`**。\
|
||||
> **Dify 文档维护原则**:Dify 编排仅在本文件维护,且以**节点级配置**为准;重点维护各节点的职责、输入、输出、条件、Tool 绑定与连线关系,不再额外维护独立 DSL 解读文档。\
|
||||
|
||||
## 我的待办改版:列表优先 + 按需抽屉 + 已完成明细报表(2026-09-16)
|
||||
|
||||
任务中心「我的待办」(`/workspace/shipping-notice/my-tasks`)布局与数据契约改版,设计稿见 [`docs/superpowers/prototypes/2026-09-16-my-tasks-redesign.html`](../../superpowers/prototypes/2026-09-16-my-tasks-redesign.html),实施计划见 [`docs/superpowers/plans/2026-09-16-my-tasks-redesign.md`](../../superpowers/plans/2026-09-16-my-tasks-redesign.md)。
|
||||
|
||||
**布局**:移除右侧常驻详情面板,改为紧凑表格行 + 点击行弹出右侧抽屉(`ShippingTaskDrawer`,分诊决策面板:头部阶段/阻断、逐行明细 `notice_line_summary` 全量列、文件区、底部深链操作;Esc/遮罩关闭)。组件拆分:`ShippingStageTabs`(阶段筛选 tab)、`ShippingTaskTable`(表格 + 批量浮动条)、`ShippingTaskDrawer`、`ShippingDoneLineReport`(通知完成明细报表),共享口径在 `shippingTaskCenterShared.ts`。
|
||||
|
||||
**阶段与桶**:阶段筛选 tab 收敛为四个可动作阶段(`intake_parse/order_review/fulfillment_prep/freight_upload`),计数来自后端 `my-todos/count` 聚合扩展字段 `stage_counts`(Review Case 走统一生命周期投影、Intake 恒为接收解析、Notice/OT 以 processing_stage 权威 → 人工原因归属 Gate → 类别兜底归类);「通知完成」不再是筛选维度,done 桶拆子视图 tab(`done_counts`:`upload_complete` / `reject_void`)。
|
||||
|
||||
**已完成桶**:默认子视图「通知完成」为跨 OT 平铺的明细行报表(`GET /shipping-tasks/my-todos/done-lines`),行 = 标准 12 字段(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价)+ 页面溯源列(`business_no||task_no`);筛选支持 客户 / 料号 / 发货通知日期(Notice created_at)范围,按明细行分页;导出 `GET .../done-lines/export` 严格 12 列中文表头(OT 不落列,openpyxl 直写,不注册模板)。已用数量/open qty 后端暂无数据源,契约留空;约定出货日期取行级 `required_date`(缺失回退快照表头列)、订单单号取表头 `source_order_number`(field_id 键)、单价取行 `unit_price`。「复核驳回 / 已作废」子视图走既有任务表 + 抽屉,`my-todos` 新增 `terminal_kind` 参数(`upload_complete|reject_void`)服务端过滤。
|
||||
|
||||
**批量操作**:仅「货代上传」阶段的正式 Notice 行有复选框(`isFreightUploadRow`),勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。
|
||||
|
||||
## 阻塞原因具体化:资格快照回退 + 原因/动作语义分离(2026-09-17)
|
||||
|
||||
**背景**:批次中心与工作台「当前任务」对建单前 Review Case 一律显示兜底文案「当前步骤需要人工处理」(同卡重复两遍),而具体原因(如 `customer_unresolved`「客户尚未确认」)早已随资格评估持久化在 `draft.validation_result_json.issues[].explainability`,只是从未进入 `blocking_reason` 通道。
|
||||
|
||||
**后端**(`reconciliation_projector.py`,单一裁决点):`project_review_case_projection_bundle` 在 automation 未携带具体原因码时,回退到 validation 快照的首要 blocking issue(跳过降级为 `unknown_business_failure` 的条目),透传冻结 explainability 契约的 `code / message / next_action / details(field_code, line_index, owning_gate_code)`——不新造任何文案映射;`project_case_blocking_reason` 的 fail-closed 兜底键从不存在的 `shipping.review.blocked_generic` 修正为前端真实存在的 `chat.shippingProcessing.reasonCode.unknown`。`BlockingReason` TypedDict 新增 `message` / `next_action` 可选字段(加法变更,向后兼容)。
|
||||
|
||||
**前端**:①`shippingProcessingLabels.isGenericBlockingReason` 升级判定(Gate 三命名空间任一命中或契约 `message` 非空即具体原因),新增 `resolveBlockingReasonText`(i18n_key → reasonCode → Gate 命名空间 → message,通用兜底返回空串);②批次中心卡(`ShippingConversationProcessingCard`)原因行改用该解析链,未知码不再渲染「当前步骤需要人工处理」空话,workbench 模式下任务卡头原因行由文件行页脚独家承载(去重);③工作台「当前任务」卡(`ReviewCurrentProcessingCard`)「下一步」优先消费 `blocking_reason.next_action` 渲染 `processGate.actionCodes.*` 建议动作(语义=做什么,而非为什么),且具体阻断原因在场时隐藏泛化的 Run 级 statusDetail。原因(客户尚未确认)与动作(确认客户)全链路文案均复用既有契约与四语言目录,未新增文案键。
|
||||
|
||||
**补充收口(同日)**:联调发现两处断点——①批次中心叶子摘要路径(`shipping_processing_projection._leaf`)对建单前 Case 直接下发 `{'code': f'review_case_{status}'}`(前端解析为「订单草稿待处理」状态文案);现新增 `_review_case_blocking_reason` 回退:`reason` 为 `review_case_*` 时从闭包内已批量加载的 `drafts_by_id` 取当前 Draft 校验快照,透传首要资格 issue(零额外查询),无可用 issue 保持状态码兜底。②API 归一化层(`normalizeShippingProcessing.normalizeBlockingReason`)白名单剥离了 `message`/`next_action`,致工作台「下一步」退化为原因文案;现保留两个透传字段(camel/snake 兼容)。
|
||||
|
||||
## CheckPoint 遗留 step_key 彻底清除(2026-09-17)
|
||||
|
||||
**背景缺陷**:`set_task_step_progress`(`tool_common.py`)历史上把 CheckPoint 时代 step_key(`step1_notice_submit` / `step2_parse_confirm` / `step3_inventory_prepare` / `step5_match_inventory` / `step6_generate_file` / `step7_upload_freight`)直接写入 `OT.stage` 与 `OT.current_step`。库存 RPA 失败上报曾把已建单 OT 的 `stage=order_creating` 踩回 `step3_inventory_prepare`;该值不在冻结 15 阶契约(`SHIPPING_PROCESSING_STAGES`)内,工作台投影回退到 Run 的识别期阶段 `candidate_creating`,五阶段步进器因此把已建单订单拉回「接收解析」(`project_lifecycle` 的 processing_stage 权威高于 Gate)。
|
||||
|
||||
**彻底清除(不留兼容层)**:
|
||||
|
||||
- **写路径**:`set_task_step_progress` 入参 `step_key` 改名 `stage`,必须传 15 阶契约码(非法值 `ValueError` 立即失败);`current_step` 与 `current_step_progress` 载荷字段同步改存/改名 `stage`;`OT.stage` 写入带**只进不退守卫**(按 `shipping_processing_stage_index`,仅允许推进或平齐,禁止回退),进度上报永远无法再拉低阶段。
|
||||
- **29 个调用点**全部改传契约码:库存准备/映射/RPA → `inventory_fetching`;库存匹配/文件入库 → `inventory_matching`;Excel 生成 → `excel_generating`;货代上传 → `freight_uploading`;通知重提交/解析确认 → `order_creating` / `waiting_review`。
|
||||
- **读路径别名全部删除**:`lifecycle_projection.LIFECYCLE_STAGE_BY_PROCESSING_STAGE` 与 `processing_projection_invariants._USER_STAGE_TO_CODE` 中的 4 个 stepN_* 别名条目移除,映射表只认契约码;`map_notice_to_processing_status_stage` 对 `current_step` 的子串/前缀启发式(`'upload' in step` / `startswith('step7')` 等)改为契约码精确匹配。
|
||||
- **存量数据**:不落数据迁移——各环境确认无需要清洗的 stepN_* 存量,写路径切换后不再产生新遗留值。
|
||||
- **前端**:`ShippingCurrentStepProgress.step_key` 字段改名 `stage`(无组件消费该字段,仅类型同步)。
|
||||
- **测试**:跨面一致性新增守护用例 `test_stage_mapping_rejects_checkpoint_legacy_keys`(阶段映射禁止任何 stepN_* 键);各测试夹具的遗留字面量已替换为契约码。
|
||||
|
||||
## 五阶段 UI 状态契约(2026-08)
|
||||
|
||||
业务人员只看到五个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(通知准备)→ `freight_upload`(货代上传)→ `upload_complete`(通知完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相。正式 Task 的操作使用 `ui_state.actions.primary/secondary`,批次 / 生命周期投影的操作使用 `ui_state.primary_action/secondary_actions`;两者均由后端下发,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。
|
||||
@@ -399,6 +434,8 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格
|
||||
|
||||
**版面签名证据一致性(2026-08-04)**:表头签名不再扫描整页顶部或按表高固定比例猜测,而是直接冻结模板既有 `header_layout.region`;运行时对每个候选在同一区域独立取证。新旧 PDF 坐标证据统一按视觉行和纯几何词间距恢复表头词组,避免 `boundary_before` 有无造成同文件签名漂移;列中心和列宽由表头词组边界产生,不再使用全表单字符连续聚类。只有同时达到模板最低分和证据覆盖率的候选才参与唯一性与 Margin 决胜。
|
||||
|
||||
**表头身份原子按 Schema 别名归一(2026-09-16)**:无必选锚点模板的两道表头硬门禁——原子集全等互斥(`profile_header_discriminator_conflict`)与软评分硬门槛(`profile_header_signature_conflict`,score<0.35)——在传入 Run 冻结 Schema 编译的表头契约(`compile_table_header_contract().header_to_field`)后,签名侧与观测侧 token 均先按别名归一为字段语义类(`schema_canonical_header_atoms` / `schema_canonical_header_tokens`:贪心最长别名短语匹配,命中归并为 `field::<code>`,未命中词保留词级原子;casefold 后跨字段碰撞的别名短语弃用)再比较/评分。**同字段同义列名不再误杀**(如 `Requested Arrival Date` ≡ `Requested Ship Date`,含 provider 单元格粘连与空格噪声),原子全等互斥的互斥强度与 0.35 硬门槛本身不变;二次机会仅在无锚点前提、契约非空且原始分<0.35 时参与门槛(`effective=max(原始,canonical)`),七维上报的 `header_semantic_position` 维持原始分。别名的同义词治理唯一入口是 Schema 字段 `aliases`(发布碰撞校验沿用);`header_to_field=None` 的调用路径行为不变,已发布模板签名无需重冻结。背景:PO_6075316 因日期列名变体全模板 0 分转人工空单;测试环境 Schema v1(行 id=4)已原位补 `Requested Ship Date` 别名(checksum 同步重算)。
|
||||
|
||||
**邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。**关联收紧(2026-09-15)**:`mpn_fallback` 仅适用于补充行 PO 缺失且料号唯一命中;有 PO 且与 PDF 不一致不得补充。预约号允许短数字行序后缀归一(如 `35354-1` → `35354`)。**无 PO 表头(2026-09-16)**:分配表缺 PO 列但已映射料号或预约号时仍解析补充行(`po_header_missing` 仅作可观测标记);无身份列时仍整表跳过。
|
||||
|
||||
**`llm_extraction` 回退语义(2026-08-01)**:订单字段标记为 `llm_extraction` 表示“确定性解析无法取值时允许 LLM 补充”,不表示必须使用 LLM。通用解析门禁应依据字段是否已有完整、无冲突的确定性证据裁决;已取得必填 Header/Line 值时可直通,缺失时由 `required_field_missing` 转入 LLM/人工复核。
|
||||
@@ -699,7 +736,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
|
||||
|
||||
**阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID,不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。
|
||||
|
||||
**Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` 的值仅写入第 N 个逻辑明细并覆盖默认值。多个不同整单值、同一行不同值、越界行号或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。
|
||||
**Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` / `L#N` 的值按 Customer PO 行号(`customer_po_line_no`,LN 列)定位对应逻辑明细并覆盖默认值(**2026-09-16 修订**:此前按"第 N 个逻辑明细"位置写入,LN 非连续——如部分行已拆到其他 PO——时会错配行归属并把存在的行号误报越界;解析行缺少 LN 取值时才回退位置序以兼容无 LN 字段的旧 Schema)。多个不同整单值、同一行不同值、被引用行号不存在或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。**带复核原因的确定性订单必须保留(2026-09-16)**:Reservation 专区/行校验触发 `needs_review` 时以 `deterministic` 携带原因码交 STP 裁决,已解析订单继续落 provisional Candidate 供复核台编辑;不得以 `review_required` 丢弃取值导致复核草稿空白。
|
||||
|
||||
**阶段 1 历史 Dify 配置**:此段不再适用订单抽取。当前无需为订单抽取配置画布、Prompt、Start/End 变量、Code 节点或 `execution_manifest`;Schema 别名只在 HXOPS 管理端维护。
|
||||
|
||||
@@ -1366,6 +1403,8 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工
|
||||
- 管理端只列出当前 published Schema 中 `enabled=true`、Header 文本类型且 `available_for_customer_identity=true` 的字段。规则集发布时重新校验字段仍可用,不能仅依赖草稿创建时状态。
|
||||
- Resolver 只读取 Candidate 所属 Extraction 中 accepted/corroborated Header FieldValue。EML From、模板指纹、原始 LLM 输出和 Candidate 摘要均不能作为旁路证据。
|
||||
- 规则快照冻结 `context_field_id` 与完整 `field_config`;字段退役、删除或新 Schema 移除引用字段时由定义和草稿/发布规则快照共同阻断。
|
||||
- 客户命中分三级(2026-09-17 起,`shadow-v3`):① canonical 等值(NFKC+casefold+剔除非字母数字,中文保留;吸收标点/空白/大小写打印差异);② 完整包含(注册指纹整体出现在提取值中,指纹 canonical 长度 ≥8);③ 截断包含(提取值疑似指纹截断片段,同 8 字符下限)。证据归一化在导入、影子识别与自动确认复核三处共用 `normalize_identity_evidence_value`(兜底分支折叠内部空白/换行)。邮箱/域名指纹只做精确等值,禁止包含比较;短于 8 字符的指纹由等值路径承担,不享受包含兜底。
|
||||
- 自动确认边界:①级唯一命中且证据 `auto_match_allowed` → `unique_strong_match`;②级唯一且授权 → `unique_containment_match`(审计证据带 `match_kind=containment_strong`);③级与未授权证据永不自动确认,只进入复核面板候选建议。等值命中存在时包含命中不参与裁决;任务期协调器与复核「重新识别」按钮共用 `resolve_auto_customer_decision` 同一裁决,质量门禁分母包含两类唯一命中。
|
||||
- 本阶段为不兼容升级:迁移清空旧定义、规则集、证据、影子匹配及其审计快照,然后物理删除旧适配器列;不提供运行时兼容映射。
|
||||
|
||||
### 阶段 4 可靠性、监控与故障注入
|
||||
@@ -2032,7 +2071,7 @@ pip --version
|
||||
cd C:\HxopsRpaTest
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install playwright openpyxl pyyaml
|
||||
python -m pip install playwright openpyxl pyyaml cryptography
|
||||
python -m playwright install chromium
|
||||
```
|
||||
|
||||
@@ -2590,6 +2629,21 @@ Task 工作台 = 非主界面,仅保留备用深链
|
||||
- **自动建单安全**:分类置信度与 LLM 字段置信度缺失 fail-closed;阈值来源写入 `confidence_policy`(schema / key_field / default_fallback)。
|
||||
- **货代上传**:`SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 默认 `false`(须显式开启);开启时启动/触发前校验 Worker(`freight_upload`)、凭据、共享目录与环境隔离。RPA 进行中投影 `display_lifecycle_status=upload_rpa_pending` 且 `is_waiting_manual_upload=false`,不得仅凭 lifecycle 显示为待人工上传。
|
||||
|
||||
### 会话主区域与批次进度中心(2026-09 方案 A)
|
||||
|
||||
- 货代发货智能体主区域规则:`isShippingNoticeAgent && conversation_id 非空` → 全屏渲染批次进度中心
|
||||
(`ShippingWorkflowTimeline`,常驻无关闭按钮);否则渲染欢迎页 + 输入框(唯一附件提交入口)。
|
||||
判定纯函数:`frontend/src/features/chat/shipping/shippingWorkbenchLayout.ts`。
|
||||
- 提交链路不变:`startRun` 成功 → 路由写回 `conversation_id` → 中心出现;对话流不再出现
|
||||
「本次订单文件处理」卡片入口,`open-batch-workbench` / `compact-shipping-progress` 链路已移除;
|
||||
`ShippingOrderExtractionCard` 保留为历史消息兜底渲染。
|
||||
- 中心头部复用会话标题(父级从侧栏 `displayHistory` 按 conversation_id 匹配传入 `conversation-title`)。
|
||||
- 新建抽取会话命名:`backend/app/services/shipping_notice/conversation_title.py`
|
||||
`derive_order_extraction_title(filenames, created_at)` —— 首个非空文件名去扩展名、剥离
|
||||
Re:/Fw:/Fwd:/回复:/转发:前缀、截 24 字、多文件追加「等 N 个文件」、追加 MM-DD;
|
||||
全空回退「订单抽取」。仅在 `_resolve_conversation` 新建分支调用;存量会话标题一律不改。
|
||||
- 同批次追加附件:中心不提供入口,通过「新建对话」重新提交(后端 append/create 裁决逻辑不变)。
|
||||
|
||||
#### 1.6.0a Gate 统一用户动作裁决(2026-08-19)
|
||||
|
||||
为避免“页面按 checkpoint、状态或 action code 猜按钮位置”导致展示与执行漂移,正式履约任务采用以下职责边界:
|
||||
@@ -2868,6 +2922,166 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui
|
||||
- 生产 Windows RPA 脚本
|
||||
- 上传成功 / 失败回执样例
|
||||
|
||||
### 1.9 收料报表 RPA 共享部署(Windows RPA + Ubuntu 后端)
|
||||
|
||||
> 本节是收料报表 RPA(独立 Windows Worker)的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。
|
||||
> 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。收料**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。
|
||||
> Worker 脚本层速查另见 [scripts/rpa/README.md](../../../scripts/rpa/README.md) 顶部「收料 RPA(独立 Worker)」;本节是部署权威来源。
|
||||
|
||||
#### 1.9.1 与库存 RPA 的边界和目录规划
|
||||
|
||||
**与库存 RPA 完全一致、直接复用(不重复执行)**:
|
||||
|
||||
- Windows RPA 主机、Python 3.12、Playwright Chromium、`hxops_share` 共享账号、两个 SMB 共享与 Ubuntu 挂载(`1.5.2`–`1.5.8`)。
|
||||
- DPAPI Secret 文件(`1.5.10` 的 `new_rpa_worker_secret.ps1`,字段为 `ToolApiKey` + `CredentialKey`):收料启动脚本读取**同一格式、同一文件**,无需新建收料 Secret。
|
||||
- Worker `-ApiBase` 口径与 `1.5.10` 相同:Docker Compose 部署填前端 nginx 网关地址(如 `http://<host>:8890`),以 `{base}/api/...` 可达为准。
|
||||
|
||||
**收料专用、不得与库存混用**:
|
||||
|
||||
| 项 | 库存 RPA | 收料 RPA |
|
||||
| --- | --- | --- |
|
||||
| Worker | `scripts\rpa\inventory\inventory_rpa_worker.py` | `scripts\rpa\receipt\receipt_rpa_worker.py` |
|
||||
| 启动脚本 | `inventory\start_inventory_worker.ps1` | `receipt\start_receipt_worker.ps1` |
|
||||
| trigger 目录 | `data\inventory_triggers` | `data\freight_receipt_rpa\receipt_triggers` |
|
||||
| drop 目录 | `data\inventory_drop` | `data\freight_receipt_rpa\receipt_drop` |
|
||||
| 回调端点 | `/api/shipping-notice/rpa/inventory-batch-ready` | `/api/shipping-notice/rpa/receipt-batch-ready` |
|
||||
| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | **无**:收料 Worker 不发心跳、不写 `.hxops_rpa_shared_mount` |
|
||||
| 结果归属 | 库存快照/库存匹配 | MinIO 原样归档 + 企微投递,绝不进入库存链路 |
|
||||
|
||||
路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`):
|
||||
|
||||
```text
|
||||
Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_triggers
|
||||
Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers
|
||||
|
||||
Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_drop
|
||||
Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop
|
||||
```
|
||||
|
||||
浏览器 Profile:收料 Worker 在 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`(收料启动脚本默认指向 `<WorkerRoot>\data\shipping_notice\freight_rpa\browser_profile`)下,为每个 `connector + profile + login_url` 分组创建 `receipt_*` 临时目录,组处理完立即删除;不保留跨排程登录会话。与库存 Worker 的 `run_*` 一次性 Profile、`{connector}__{profile}_session` 长期会话目录互不影响。
|
||||
|
||||
#### 1.9.2 Windows RPA 主机:部署收料 Worker
|
||||
|
||||
在既有 test/prod WorkerRoot 下追加收料专用目录:
|
||||
|
||||
```powershell
|
||||
foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) {
|
||||
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\receipt_triggers"
|
||||
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\receipt_drop"
|
||||
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\logs"
|
||||
}
|
||||
```
|
||||
|
||||
`receipt_rpa_worker.py` 启动时按「所在目录必须同时存在 `connectors/`、`common/`、`inventory/`、`receipt/` 子目录」定位 RPA 根目录,因此必须复制**整个** `scripts\rpa`(首次部署 `1.5.2` 已覆盖;升级时同样整目录同步,保持 Worker、driver 与公共模块同一版本),不能只复制 `receipt\` 子目录。
|
||||
|
||||
依赖与 `1.5.4` 相同,另需 `cryptography`(解密 RPA Profile 加密凭据;库存 Worker 同样依赖,新增部署时两个 Worker 一起补齐):
|
||||
|
||||
```powershell
|
||||
cd C:\HxopsRpaTest
|
||||
python -m pip install playwright openpyxl pyyaml cryptography
|
||||
python -m playwright install chromium
|
||||
```
|
||||
|
||||
Secret 复用 `1.5.10` 创建的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`。手工启动 test(首次验证用可见窗口;加 `-Mock` 可在不访问货代网站的情况下验证 trigger 消费、回调、归档与企微投递全链路;正式常驻建议验证后再加 `-Headless`):
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
|
||||
"C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1" `
|
||||
-Environment test `
|
||||
-ApiBase "http://<test后端地址>:<端口>" `
|
||||
-WorkerRoot "C:\HxopsRpaTest" `
|
||||
-SecretFile "C:\HxopsRpaSecrets\test.xml"
|
||||
```
|
||||
|
||||
启动成功会输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`,随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。
|
||||
|
||||
后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,仅把动作换成收料启动脚本。收料 Worker 不写 `worker.log`,日志输出到控制台;计划任务建议用 `cmd.exe` 包装做文件重定向:
|
||||
|
||||
```powershell
|
||||
$TestApiBase = "http://<test后端地址>:<端口>"
|
||||
$ReceiptAction = New-ScheduledTaskAction `
|
||||
-Execute "cmd.exe" `
|
||||
-Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_receipt_rpa\logs\receipt_worker.log"" 2>&1" `
|
||||
-WorkingDirectory "C:\HxopsRpaTest"
|
||||
# $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致:
|
||||
# AtLogOn + Interactive;RestartCount 10、RestartInterval 1 分钟、ExecutionTimeLimit 0、MultipleInstances IgnoreNew。
|
||||
Register-ScheduledTask -TaskName "HXOPS Receipt RPA Worker TEST" -Action $ReceiptAction -Trigger $Trigger -Principal $Principal -Settings $Settings
|
||||
```
|
||||
|
||||
任务名建议 `HXOPS Receipt RPA Worker TEST` / `HXOPS Receipt RPA Worker PROD`,与库存任务并存;收料与库存 Worker 可同机、同一交互式用户会话同时运行,日常启停命令与 `1.5.10` 相同(替换任务名即可)。
|
||||
|
||||
#### 1.9.3 Ubuntu 后端:环境变量、排程与归档
|
||||
|
||||
`.env.test` 在 `1.5.9` 基础上追加(正式环境把路径换成 `/mnt/hxops-rpa-prod-data/...`):
|
||||
|
||||
```env
|
||||
# 收料 RPA 共享目录(与 Windows Worker 的 data\freight_receipt_rpa 属同一 SMB 共享的子路径)
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop
|
||||
# 收料排程等待回调超时(秒);超时回收为 RPA.RECEIPT_CALLBACK_TIMEOUT,不自动重试
|
||||
SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
|
||||
```
|
||||
|
||||
> ⚠️ **最容易漏的一步**:不配置这两个目录变量时,后端默认写容器本地 `backend/data/shipping_notice/freight_receipt_rpa/*`,Windows 共享盘永远看不到 trigger,单元会一直等到超时回收。
|
||||
|
||||
容器 bind mount **无需新增**:收料目录位于既有 `/mnt/hxops-rpa-*data` 共享的子路径下,`hxops-backend`、`hxops-schedule-worker` 按 `1.5.9` 挂载后即已覆盖;修改 `.env` 后按惯例重建相关容器。
|
||||
|
||||
归档与通知依赖:
|
||||
|
||||
- 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。
|
||||
- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。
|
||||
- 企微逐文件推送与汇总发给排程任务配置的接收人(`notify_user_ids` + `notify_enabled`),接收人必须已完成企微绑定,否则投递记 `WECOM_USER_UNBOUND` 失败。
|
||||
|
||||
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用收料配置,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `receipt_worker.log` 巡检。
|
||||
|
||||
#### 1.9.4 端到端验证
|
||||
|
||||
1. 管理端「货代管理 → 库存站点」抽屉为目标站点启用收料配置:DBS 必须配置 Warehouse(每个 Warehouse 展开一个单元);Crane 固定 `Inbound Details`,拒绝 Warehouse 与查询条件。
|
||||
2. 链路演练(不依赖真实货代网站):以 `-Mock` 启动收料 Worker → 排程管理手工执行一次「货代收料 RPA」→ 确认回调、MinIO 归档、企微投递全链路成功后停止 Mock Worker。
|
||||
3. 真实链路:启动真实收料 Worker 并触发排程,依次确认:
|
||||
- `ls /mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers` 出现 `receipt_export_batch_{run_no}.json`;
|
||||
- Worker 领取后文件进入同目录 `processing/`,全部单元处理完进入 `processed/`(契约级失败进 `failed/`);
|
||||
- `receipt_drop` 出现 `receipt_{callback_id}_{时间戳}.xlsx`;
|
||||
- 回调 `/api/shipping-notice/rpa/receipt-batch-ready` 成功,单元 `success`,MinIO 出现归档对象;
|
||||
- 接收人企微收到文件消息与汇总,工作台「收料文件」可查看并下载。
|
||||
4. 失败路径:制造一个失败单元(如停用对应 RPA Profile),确认排程终态 `failed` / `partial_failed`、管理端失败单元可查、带原因重试生成新单元且以 `retry_of_id` 关联旧单元;通知重发不触发重新导出。
|
||||
5. 隔离确认:收料文件不出现在 `inventory_drop`,不产生任何 `ShippingInventoryFile` / 库存快照 / 库存匹配记录。
|
||||
|
||||
#### 1.9.5 常见问题
|
||||
|
||||
- trigger 长时间无人消费:收料 Worker 未启动;两端 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` 不一致;或后端未配置变量、写到了容器本地默认路径(见 `1.9.3` 的告警)。
|
||||
- 回调 401/403:Worker `X-Integration-Key` 与该环境 `SHIPPING_NOTICE_TOOL_API_KEY` 不一致,或 `-ApiBase` 未按 `1.5.10` 的网关口径填写。
|
||||
- 回调报 `SHIPPING.RECEIPT_CALLBACK_FILE_INVALID`:`file_path` 不在收料 drop 根内、非 `.xlsx`、空文件或超过 `FILE_ASSET_MAX_SIZE_MB`;多为收料/库存目录串用所致。
|
||||
- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。
|
||||
- DBS/Crane 登录或导出失败:先在 Windows 手工登录确认 MFA/SSO/代理;Crane 无论 Profile 首页保存为何,Worker 均强制进入 `#/inbound-details-query` 用页面默认条件执行;确认 Profile 已启用且 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。
|
||||
- `receipt_drop` 磁盘占用增长:归档完成后本地文件不再被后端读取,收料 Worker **不做本地清理**;按运维周期人工清理,建议保留最近几天便于排障。
|
||||
- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `receipt_worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。
|
||||
|
||||
#### 1.9.6 收料 RPA 三环境速查
|
||||
|
||||
| 运行位置 | 后端目录/环境 | Worker 目录与环境 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| Windows 本地联调 | 本地后端;默认 `backend/data/shipping_notice/freight_receipt_rpa/*` | 当前项目 `scripts/rpa/receipt/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 |
|
||||
| Linux 测试服务器 | `/mnt/hxops-rpa-test-data/freight_receipt_rpa/*`;`.env.test` | `C:\HxopsRpaTest\data\freight_receipt_rpa`;`test` | 与库存测试共用同一 SMB 共享与挂载 |
|
||||
| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/*`;`.env.prod` | `C:\HxopsRpaProd\data\freight_receipt_rpa`;`prod` | 测试真实链路验收通过后再开启正式排程 |
|
||||
|
||||
Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 Worker 指向一致,无需配置目录变量):
|
||||
|
||||
```powershell
|
||||
# 窗口一:启动本地后端(同 2.1 的库存本地联调)。
|
||||
# 窗口二:直接运行收料 Worker(不经启动脚本,免 Secret 文件;MOCK=true 时生成模拟 xlsx,
|
||||
# 走完整 trigger 消费 → 回调 → 归档 → 企微链路)。
|
||||
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
|
||||
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与本地后端一致>"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true"
|
||||
$receiptRoot = Join-Path (Get-Location).Path "backend\data\shipping_notice\freight_receipt_rpa"
|
||||
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt_triggers"
|
||||
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt_drop"
|
||||
python scripts/rpa/receipt/receipt_rpa_worker.py
|
||||
```
|
||||
|
||||
真实本地导出(`MOCK=false`)还需受控注入 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 并设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`;排程下发的真实 trigger 均含加密凭据,Mock 消费真实 trigger 时同样需要该密钥。也可改用启动脚本 `.\scripts\rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://127.0.0.1:5052" ...`(需先按 `1.5.10` 生成本地 Secret 文件)。
|
||||
|
||||
***
|
||||
|
||||
## 2. Dify 手工配置边界
|
||||
@@ -3491,7 +3705,7 @@ DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound D
|
||||
### 可靠性、补偿与审计边界
|
||||
|
||||
- trigger 采用“同目录临时文件写完、`fsync` 后 `os.replace` 原子发布”方式;收料 Worker 只能 claim 完整的 `.json`,不得读取半写入 trigger。
|
||||
- `awaiting_receipt_rpa` 运行受 `SHIPPING_NOTICE_RPA_RECEIPT_CALLBACK_TIMEOUT_SECONDS`(默认值由部署配置决定)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。
|
||||
- `awaiting_receipt_rpa` 运行受 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 `900`,可由部署配置覆盖)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。
|
||||
- Worker 启动及常规扫描均回收超时运行,避免服务或 Worker 重启后运行永久占用排程状态。
|
||||
- 空结果、Worker 失败、归档成功、对象删除失败、企微文件/汇总投递成功或失败、管理员查看失败单元、人工重试和重发均写追加式 `ShippingAuditEvent`。审计包含操作人/时间/对象、结果、脱敏原因或错误码、变更前后状态;不得写入密码、Cookie、令牌、对象存储定位或浏览器会话。
|
||||
- 管理员失败单元查询仅返回运行诊断所需的站点、Warehouse、状态、错误码/脱敏错误和时间;接收人不拥有该查询、配置、重试或重发权限。
|
||||
@@ -3607,3 +3821,22 @@ inventory_preparation Gate
|
||||
|
||||
- 一期规划中的「快照重冻结 + `order_data_version` 递增」由既有 `update_notice_*` ⇒ `_commit_notice_edit` ⇒ `_apply_notice_edit_change_effects` 链路承担(编辑落库后依赖 `change_effect` 失效下游);`order_data_version` 由乐观锁 `_assert_order_data_version` 保护,避免重复冻结引入二次状态机。
|
||||
- 波次通知「按自身行重跑路由」(D8)已实现(见一期章节):不再继承首通知源,`freeze_wave_notice_routing` 按波次自身行冻结候选集;本二期不新增二次波次状态机,与一期波次路由冻结复用同一套链路。
|
||||
|
||||
## 客户数据 ODM ID 范围与整单 ODM 裁决(2026-09)
|
||||
|
||||
- 「客户主数据」页面与文案统一更名为「客户数据」;`ShippingCustomer` 新增可空 `odm_ids`(JSON 字符串清单),由客户数据页维护(每行一个,留空表示不限定)。
|
||||
- 生成发货 Excel 的整单 ODM 裁决(模板 Header 消费 `odm_id` 字段时生效,`export._adjudicate_notice_odm`):
|
||||
1. 客户 `odm_ids` 非空 → 先全局过滤库存命中行,仅保留范围内的 ODM;把原有命中全部排除时报「订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内」。
|
||||
2. 用户选择(`shipping_notice_line_inventory_matches.chosen_odm_id`,task 全部 `is_current` 行统一值)→ 过滤为所选 ODM;在当前库存中不存在时报「已选择的 ODM ID 在当前库存中不存在」。
|
||||
3. 无范围、无选择且各行命中 ODM 交集唯一 → 自动收敛到唯一可行值;交集多个 → 维持折叠冲突阻断,由工作台下发候选。
|
||||
- 工作台「通知准备」面板为**行内 ODM 下拉**(任一行候选多于一个且未生成 Excel 时展示列):候选为该行经客户范围过滤后的命中值(保留原大小写);确认后 `POST /shipping-tasks/<task_no>/odm-choice`(body: `snapshot_line_id` + `odm_id`)落库并自动重试 `regenerate_excel_artifact`。
|
||||
- **同快照文件同步**:选择按 `inventory_snapshot_id` 圈同步——改任一行,同一快照文件的全部 `is_current` 匹配行写同一 `chosen_odm_id`(前后端同步:后端落库即同步,前端刷新后各行回显同一值);校验取同步范围内各行候选的交集,保证选择不会把其他行变成无匹配。
|
||||
- 选择不落 Notice/OT:Notice 在生成失败事务中会回滚,行级匹配事实表才是导出读取库存源/文件的既有事实源;重匹配产生新匹配轮次后旧选择自然失效。Header 契约是整单一个值,若业务需要不同行走不同 ODM(跨快照文件),应拆分通知单。
|
||||
- 迁移:`aa11bb22cc33_customer_odm_scope`(`shipping_customers.odm_ids` + `shipping_notice_line_inventory_matches.chosen_odm_id`,均幂等守卫)。
|
||||
|
||||
## 订单队列五态图标与 needs_attention(2026-09)
|
||||
|
||||
- 队列接口(`serialize_review_queue` / `serialize_review_run` 共用的 `_serialize_review_case_summary`)每个 item 新增 `needs_attention: bool`:复用批量预取的 Execution/Gate 会话缓存(零额外 SQL),当前 Gate(优先 `execution.current_gate_code`,缺失按 `sequence_no` 取第一个活跃 Gate)状态 ∈ {`blocked_manual`, `blocked_retryable`, `failed_terminal`} 时为 True;`waiting_external`/`running`/`pending`/`queued` 属系统在办。前端禁止自行推断阻塞。
|
||||
- 左侧文件队列图标五态口径(`ReviewDocumentNavigation.vue` 的 `navIconKind`,优先级命中即停):失败 ✗ → 需人工 ⚠(`issue_count>0` 或 `needs_attention`,以及 `draft`/`ready`/`unreviewed`/`quality_issue`/`pending_review`/`waiting_review`)→ 终态绿勾 ✓(`lifecycle_stage=upload_complete` 或 `closed`/`completed`)→ 系统在办蓝转圈(`confirmed`/`confirming`/`processing`/`reparse_pending`/`queued`)→ 中性灰圈(`non_order`/`cancelled`/`superseded`)→ 兜底转圈。绿勾不再被「已创建任务」等中间态占用;选中态仅由行高亮表达。
|
||||
- 队列 `summary` 三桶与图标同口径(`_queue_summary_bucket`):`quality_issue` 归 needs_action;`confirmed` 归 processing;仅终态归 completed。前端当前未消费三桶,属契约纠偏。
|
||||
- 已知边界(fail-safe):队列 `lifecycle_stage` 为轻量投影,极端场景会偏早(兜回 `intake_parse`),后果是完成单暂不亮绿勾;反向(未完成亮绿勾)不可能——`upload_complete` 仅由已持久化 `OT.stage=completed` 驱动。
|
||||
+7
-1
@@ -22,8 +22,12 @@
|
||||
- 订单复核:核对订单并确认正式建单。
|
||||
- 通知准备:库存处理、匹配和生成发货通知 Excel;一个 `shipping_notice` 对应一张发货通知单、一个单号和一个 Excel,可包含多条订单明细;RPA 超时优先重新读取已产生的库存结果,用户可再明确选择重新获取库存(RPA)。
|
||||
- 货代上传:下载 Excel、RPA 上传、按发货通知单号人工确认已上传、失败恢复和未知结果核对;未知结果禁止自动重试。
|
||||
- 我的待办改版(2026-09-16):紧凑表格 + 按需详情抽屉;阶段筛选 tab 计数后端全量聚合(仅四个可动作阶段);批量操作仅货代上传阶段可勾选、勾选后浮动操作条;已完成桶拆子视图——「通知完成」为跨单平铺明细报表(客户/料号/发货通知日期筛选,按明细行分页,导出严格 12 列标准 Excel),「复核驳回/已作废」为任务表 + 抽屉。
|
||||
- 阻塞原因具体化(2026-09-17):批次中心/工作台对建单前 Case 回退消费草稿校验快照的首要阻断 issue(冻结 explainability 契约透传 code/message/next_action),展示「客户尚未确认」等具体原因;「下一步」渲染建议动作文案;通用兜底码不再渲染,同卡重复原因行去重。
|
||||
- 通知完成:只读展示已核验的上传成功证据;仅 Task 聚合、全部预约单与成功 Upload Attempt 同时满足时显示并计入完成。
|
||||
- 通知完成:上传通知或登记上传回执;仅服务端确认的上传 Attempt 成功后显示完成结果。
|
||||
- 货代发货会话主区域为批次进度中心:有会话即全屏常驻展示(不可关闭),无会话显示欢迎页与附件提交入口;历史会话点击直达中心
|
||||
- 新建订单抽取会话自动按首个附件文件名命名(剥离邮件前缀 + 等 N 个文件 + 日期后缀);存量会话名不变
|
||||
- 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。
|
||||
- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。
|
||||
- 管理端“知识库配置 → Dify 设置”支持配置新建 Dataset 的默认检索模型(检索方式、重排序、Top K、相似度阈值开关及阈值),以及文档同步的自定义分段参数(最大 Token 数、重叠 Token 数);保存仅更新 HXOPS 运行时配置,不自动回写已创建的 Dify Dataset。
|
||||
@@ -93,6 +97,7 @@
|
||||
| --- | --- | --- |
|
||||
| **统一 ShippingProcessingProjection(15 阶段)+ 正式任务编辑** | 阶段 0–6 已验收 | 库存源硬门禁;复核台原地 formal_task;Schema `task_edit_policy`/`change_effect`;正式编辑审计矩阵;Dify NONE。验收:`unified-progress-formal-edit-stage0~6` + `final-acceptance` + `dify-config`。 |
|
||||
| 订单生命周期工作台状态展示统一(v2) | 已实现 | 五阶段下方横幅移除;右栏「当前任务」卡为唯一状态宿主:状态行=user_status 短标签(Run 级 lifecycle_status 受控兑底映射)+ 状态块内嵌动态说明(`RUN_STATUS_FALLBACK_MAP`/`REDUNDANT_DETAIL_REASON_CODES` 双常量裁决,诊断信息不隐藏);无 Case 瞬态保留单行白名单轻提示;聊天页/任务中心同源接入零视觉变化。设计:[2026-08-31 状态展示统一设计](superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md) |
|
||||
| 订单队列五态图标与门禁阻塞标志 | 已实现 | 队列 item 新增 `needs_attention`(复用批量 Gate 缓存零额外 SQL,blocked_manual/blocked_retryable/failed_terminal 为真);左侧文件队列图标收敛为 需人工⚠/进行中🔄/终态✓/失败✗/中性○ 五态,绿勾仅限通知完成终态;队列 summary 三桶同口径。设计:[2026-09-16 队列图标语义设计](superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md) |
|
||||
| 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) |
|
||||
| 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) |
|
||||
| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 |
|
||||
@@ -114,7 +119,7 @@
|
||||
| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,支持 `External reservation ID` 等冻结 Schema 显式别名;每个 Run 从原始 HTML 重建,避免旧的部分解析结果遮蔽新规则;PDF 数量保持权威,歧义统一进入人工复核 |
|
||||
| PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 |
|
||||
| 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理;只读画布完整展示必需锚点及各受控标签区域的冻结识别值,必需锚点可对照配置值、识别值和匹配状态;标注取字、运行匹配与版本诊断统一按视觉行恢复字符阅读顺序;标注 Reservation ID 专区的模板跨页以 `Vendor Comments` 至首次 `Terms and Condition(s)` 作为语义边界读取预约单号,未标注模板保持原解析路径 |
|
||||
| **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) |
|
||||
| **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;表头身份原子按 Run 冻结 Schema 别名归一,同字段同义列名(如 Requested Arrival/Ship Date)不再触发表头硬互斥;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) |
|
||||
| **XFA 数据路径 Profile(统一回退)** | 代码收口(2026-08-18) | datasets + 拆分规则为首选;失败进入普通 PDF 共用 PDFium/Widget/OCR 证据链,保留 `fallback_from`、原因码与 `value_source`,回退候选固定 Review、禁止 STP;Dify 主链:**NONE**。 |
|
||||
| **XFA 统一视觉标注 + 字段拆分** | 统一入口已收口 | 普通 PDF/XFA 共用 Editor、`/pdf-automark` Job、保存、验证和发布 DTO;`value_binding` + `visual_binding`、RE2、统一 CQ/STP;XFA 仅在首选 datasets 取值与拆分规则上保留适配器差异。 |
|
||||
| **XFA 可见值回读补偿** | 已实现(2026-08-25) | 编辑器在原生坐标、服务端 OCR 与唯一 Widget 无值后,OCR 同一 PDF.js XFA 画布的受控裁剪图(`xfa_rendered_ocr`);仍无值保留值框并提示诊断,可继续绑定 datasets。裁剪图不持久化,datasets 仍为唯一正式值源。 |
|
||||
@@ -179,6 +184,7 @@
|
||||
| **行级人工选源动作 select_line_inventory_source(一期)** | 已实现 | Gate 业务动作(属 `inventory_matching`):校验行冲突、源 ∈ 候选、源启用、通知未生成 Excel(否则 `SHIPPING.LINE_SOURCE_LOCKED`);写候选行覆写 + 仅该行重匹配 + 审计 `review_line_source_selected`。 |
|
||||
| **通知准备行源下拉与锁定渲染(一期)** | 已实现 | `ui_state.preparation` 下发 `source_locked` / `lines[].source_ambiguous` / `source_candidates`;前端歧义行渲染库存源下拉 + 首选高亮 + 确认,`source_locked` 行只读徽标;阶段自动跳转一次性 toast + 清理 `reparse` 死守卫;四语言文案。 |
|
||||
| **波次库存源按自身行重路由(D8)** | 已实现 | `post_ot_fulfillment_wave_service` 创建波次通知不再继承首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,随后走同一套自动探测/匹配/反写。测试:`test_shipping_wave_rerouting.py`。 |
|
||||
| **客户数据 ODM ID 范围与整单 ODM 裁决** | 已实现 | 客户数据(原客户主数据)维护可空 `odm_ids` 清单;生成 Excel 时按客户范围过滤库存命中行,范围后仍多值时工作台整单选择(写入行级匹配事实 `chosen_odm_id`)并自动重试;交集唯一自动收敛。 |
|
||||
| **确认后订单编辑窗谓词(二期 T10)** | 已实现 | `order_edit_window_service.editable_scope`(header=订单任一通知无 Excel 且无活动 Attempt;行=所属通知无 Excel 且无活动 Attempt,未入波次行不受首单 Excel 限制)+ `order_has_active_attempt`;`ui_state` 下发 `edit_window`;测试通过。设计 §3.1。 |
|
||||
| **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 |
|
||||
| **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 |
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# 实施计划:我的待办改版(列表优先 + 按需抽屉 + 已完成明细报表)
|
||||
|
||||
日期:2026-09-16 分支:`hugo-shipping-notice` 设计稿:`docs/superpowers/prototypes/2026-09-16-my-tasks-redesign.html`
|
||||
|
||||
## 背景与目标
|
||||
|
||||
货代发货通知「我的待办」页(`/workspace/shipping-notice/my-tasks`)当前为「卡片列表 + 常驻右侧详情」布局,存在:列表卡片过重、详情面板信息重复低价值、阶段卡片只统计当前页失真、批量工具栏常驻且 i18n key 缺失显示原始 key 等问题。本次改版目标:
|
||||
|
||||
1. 列表改为紧凑表格 + 按需抽屉(待处理/处理中/驳回作废);
|
||||
2. 阶段筛选收敛为 4 个可动作阶段,计数后端全量聚合;
|
||||
3. 「已完成」桶拆子视图:通知完成 = 明细平铺报表(可筛选、按明细行分页、导出 Excel);复核驳回/已作废 = OT 级列表 + 抽屉;
|
||||
4. 批量操作改为情境式浮动条(仅货代上传阶段、勾选后出现);
|
||||
5. 顺带修复 batch i18n key 错位。
|
||||
|
||||
## 已确认的设计决策
|
||||
|
||||
- 待处理列表:紧凑表格行 = [复选框(仅货代上传)] 编号+类别角标+副行(客户·PO·文件) / 阶段徽章 / 状态摘要(阻断红色) / 项次·缺口 / 货代状态;点行开抽屉。
|
||||
- 阶段 tab:`全部 | 接收解析 | 订单复核 | 通知准备 | 货代上传`,计数来自后端聚合(待处理桶),点击即筛选。
|
||||
- 抽屉:头部(编号/客户/PO/阶段/阻断) + 逐行明细(notice_line_summary 全量列) + 文件区 + 底部操作(沿用 ui_state 权限裁决;review/intake 分支迁入)。
|
||||
- 已完成桶子视图 tab:`通知完成(N) | 复核驳回/已作废(M)`。
|
||||
- 通知完成报表:明细行平铺不按 OT 聚合;页面首列 OT 编号;列 = OT编号 + 标准12字段(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价);筛选 = 客户 + 料号 + 发货通知日期范围;按明细行分页。
|
||||
- 导出 Excel:**严格 12 列**(不带 OT 列),专用平铺导出器(不注册模板、不走 per-Notice 模板机制);已用数量/open qty 暂留空。
|
||||
- 字段映射:约定出货日期→`required_date`;订单单号→`source_order_number`;单价→`unit_price`(Schema 未启用则为空);料号→`part_number`。
|
||||
- 批量:无常驻工具栏;货代上传行有复选框,勾选≥1 浮出深色操作条(下载 Excel/确认上传/发起 RPA),全选仅作用当前筛选结果。
|
||||
- 无数据库结构变更、无迁移、无新增依赖。
|
||||
|
||||
## 任务清单(TDD,顺序执行)
|
||||
|
||||
### T1 后端:count 接口扩展(阶段聚合 + 已完成子计数)
|
||||
- `query_service.count_my_todos` 返回结构增加:
|
||||
- `stage_counts: {intake_parse, order_review, fulfillment_prep, freight_upload}`(待处理桶按生命周期阶段聚合,复用既有 lifecycle stage SQL/投影口径);
|
||||
- `done_counts: {upload_complete, reject_or_void}`(done 桶:已核验上传成功 vs 复核驳回∪作废/归档)。
|
||||
- API `GET /shipping-tasks/my-todos/count`(`api/workspace/shipping_notice.py`)透传新字段;保持既有 key(pending/processing/done/total_pending_badge)不变。
|
||||
- 测试:`backend/tests/` 新增/扩展 count 聚合用例(覆盖四阶段计数与 done 两种终态归类)。
|
||||
- 验证:`pytest` 相关用例绿。
|
||||
|
||||
### T2 后端:my-todos 列表支持终态过滤参数
|
||||
- `list_my_todos` 增加可选参数 `terminal_kind`(仅 bucket=done 时生效):`upload_complete` → 仅已核验上传成功;`reject_void` → 仅 复核驳回 ∪ 作废/归档。
|
||||
- 测试:参数过滤用例。
|
||||
- 验证:`pytest` 绿。
|
||||
|
||||
### T3 后端:已完成明细行级查询接口
|
||||
- 新增 service 查询(query_service 或独立模块):跨已完成 Notice 平铺行明细,join 冻结 ShippingOrderSnapshot 行字段。
|
||||
- 返回行字段:`task_no(OT编号), customer_name, customer_code, order_date, line_no, part_number, qty, required_date, customer_po_number, used_qty(None), open_qty(None), source_order_number, unit_price`。
|
||||
- 筛选:`customer`(名称/简码模糊)、`part_number`(模糊)、`notice_date_from/to`(发货通知日期=Notice 创建日期范围);`page/page_size`(默认 20,上限 100)+ `total`。
|
||||
- API:`GET /api/workspace/shipping-tasks/my-todos/done-lines`。
|
||||
- 测试:行字段映射(含字段缺失留空)、筛选、分页用例。
|
||||
- 验证:`pytest` 绿。
|
||||
|
||||
### T4 后端:专用平铺导出器(12 列 xlsx)
|
||||
- 新增导出函数:同 T3 查询(不分页,行数上限 10000 防护),固定写 12 列中文表头,OT 不落列;openpyxl 沿用项目内既有用法。
|
||||
- API:`GET /api/workspace/shipping-tasks/my-todos/done-lines/export`(同筛选参数,流式返回 xlsx)。
|
||||
- 测试:生成的 workbook 表头/行值/空值断言。
|
||||
- 验证:`pytest` 绿。
|
||||
|
||||
### T5 前端:API 层与类型
|
||||
- `features/workspace/api/shipping-tasks.api.ts`:count 返回类型扩展 + done-lines 查询 + 导出下载(复用既有下载工具)。
|
||||
- `features/chat/types/shipping.api.types.ts`:新增行明细类型 `ShippingDoneLineItem` 等。
|
||||
- 验证:`npm run build` 通过(类型层面)。
|
||||
|
||||
### T6 前端:主页面拆分重构(列表态/抽屉态/批量浮动条)
|
||||
- 新组件(`features/workspace/shipping-task-center/`):
|
||||
- `ShippingStageTabs.vue`:阶段 tab(后端计数、点击筛选);
|
||||
- `ShippingTaskTable.vue`:紧凑表格行 + 复选框列(仅货代上传)+ 批量浮动条插槽;
|
||||
- `ShippingTaskDrawer.vue`:抽屉(task/review/intake 三分支 + 文件区 + 操作区,迁移自现页面 1086-1273 行逻辑)。
|
||||
- `ShippingTaskCenterPage.vue`:移除右侧常驻详情与五张阶段卡片;接入新组件;保留桶切换、筛选、分页、轮询(`shippingTaskCenterPolling` 不动)。
|
||||
- 测试:更新 `ShippingTaskCenterPage.notice-batch.spec.ts`(浮动条出现条件、仅货代上传可勾选)+ 新增抽屉渲染测试。
|
||||
- 验证:`npm run test` 相关用例绿;`npm run build` 通过。
|
||||
|
||||
### T7 前端:已完成桶子视图与明细报表
|
||||
- 新组件 `ShippingDoneLineReport.vue`:子视图 tab(通知完成/复核驳回·已作废,计数来自 T1);
|
||||
- 通知完成:13 列表格(OT编号+12字段,横向滚动)+ 客户/料号/发货通知日期筛选 + 按行分页 + 导出按钮(T4 接口);
|
||||
- 复核驳回/已作废:走既有任务列表(T2 参数)+ 抽屉。
|
||||
- 验证:`npm run test` + `npm run build`。
|
||||
|
||||
### T8 i18n 四语言
|
||||
- 修复:`schedule.batch.*` 12 个 key 复制/迁移到各语言 `workspace.json` 的 `shippingNotice.batch`(zh-TW/th 当前整块缺失,按 zh-CN 补齐翻译)。
|
||||
- 新增:阶段 tab、抽屉、报表列头、筛选、终态角标、导出等文案,zh-CN/zh-TW/en/th 四语言同步。
|
||||
- 验证:脚本断言四语言 key 集合一致;页面无裸 key。
|
||||
|
||||
### T9 回归与收尾
|
||||
- 后端:`pytest backend/tests` 全量相关目录通过。
|
||||
- 前端:`npm run test`、`npm run build` 通过。
|
||||
- 文档:`docs/features/shipping-notice/technical.md` 增补改版说明;`funclist.md` 若涉及功能条目变化则同步。
|
||||
- 提交拆分:后端(T1-T4)、前端(T5-T7)、i18n(T8)、文档(T9) 分开提交,遵循 Conventional Commits。
|
||||
|
||||
## 明确不做
|
||||
|
||||
- 虚拟滚动 / 服务端排序 / 保存视图 / 列自定义 / 看板;数据库迁移;新增第三方依赖;通知完成报表行点击行为(后续增量);已用数量、open qty 数据源接入。
|
||||
@@ -0,0 +1,69 @@
|
||||
# 计划:订单模板表头身份原子按 Schema 别名归一(契约层)
|
||||
|
||||
> 状态:已确认(2026-09-16,会话内评审)。执行方式:subagent-driven-development。
|
||||
> 背景:PO_6075316.pdf 因日期列名 `Requested Ship Date`(训练样本为 `Requested Arrival Date`)
|
||||
> 触发 `profile_header_discriminator_conflict`,11 模板全 0 分,layout_drift 转人工空单。
|
||||
> 契约层方案:表头身份原子比较前按冻结 Schema 的字段别名归一为字段语义类;
|
||||
> 原子集全等硬门禁与近亲模板互斥语义**不变**;复用现有别名机制,不新造轮子。
|
||||
|
||||
## Global Constraints(全局约束,评审时的注意力透镜)
|
||||
|
||||
1. 硬门禁不弱化:归一后仍要求原子集**全等**;不同字段类、Schema 外新词照样冲突。
|
||||
2. `header_to_field=None` 的所有路径行为与现状完全一致(向后兼容,已发布签名不重冻结)。
|
||||
3. 同义词唯一治理来源 = Schema `fields[].aliases`;matcher 不新增同义词表/配置面。
|
||||
4. 纯后端改动;不引入新第三方依赖;新函数/文件须满足 AGENTS §5 三层注释。
|
||||
5. 全程不 commit(用户规则);测试环境 Schema v4 **原位**补别名、不升版(用户确认)。
|
||||
6. 已确认:`Requested Ship Date` 归 `requested_receipt_date`。
|
||||
|
||||
## Task 1:核心纯函数 + 单测(文件 `backend/app/services/shipping_notice/document_layout/order_profile_matcher.py`)
|
||||
|
||||
- 新增模块级常量 `_HEADER_FIELD_MARKER = 'field::'`(标记原子前缀;词级原子不可能含冒号,无碰撞)。
|
||||
- 新增 `schema_canonical_header_atoms(tokens: list[str], header_to_field: dict[str, str] | None) -> frozenset[str]`:
|
||||
- `header_to_field` 为 `TableHeaderContract.header_to_field`(普通 dict,鸭子类型,不引入 order_schema→matcher 反向依赖);
|
||||
- **None 时直接返回 `_header_token_atoms(tokens)`**(零行为变化);
|
||||
- 短语字典:对每个 alias key 先 `_HEADER_PAREN_GLOSS` 剥注记 → casefold → 按 `[^a-z0-9]+` 切词元组;**casefold 后跨字段碰撞的短语弃用**(身份归属不允许歧义);
|
||||
- 每个 token:空串跳过(吸收 MinerU 空格);同一词管线(剥注记/casefold/切词)后,**贪心最长短语匹配**(命中 → `_HEADER_FIELD_MARKER + field_code` 原子);未命中的剩余词沿用既有规则(≥`_HEADER_ATOM_MIN_LEN`、非 `_HEADER_ATOM_STOPWORDS`);
|
||||
- 中文别名经 `[^a-z0-9]+` 切词后为空 → 自然跳过(与词级原子只保留 `[a-z0-9]` 的现状一致),docstring 注明。
|
||||
- 单测(新文件 `backend/tests/test_order_profile_header_identity.py`,pure_unit):
|
||||
精确命中 / 合并格贪心分解(`requested ship date unit price` → 两个 field 标记)/ 大小写不敏感 /
|
||||
未命中词保留原词(含过短词过滤)/ 空串跳过 / casefold 碰撞短语弃用 / None 兼容。
|
||||
- Verify:`pytest tests/test_order_profile_header_identity.py -q` 全绿。
|
||||
|
||||
## Task 2:matcher 接线(同文件三层透传)
|
||||
|
||||
- `_header_discriminator_atoms_conflict(..., header_to_field: dict[str, str] | None = None)`:非 None 时两侧均用 Task 1 函数归一后比较;None 走现行为。
|
||||
- `_compute_dimension_results(..., header_to_field=None)` 透传(唯一调用点在 `match_frozen_coordinate_profiles` 主循环)。
|
||||
- `match_frozen_coordinate_profiles(..., header_to_field=None)` 透传 + docstring 同步。
|
||||
- Verify:matcher 既有测试套件全绿(执行时 `grep -rl match_frozen_coordinate_profiles tests/` 定位)。
|
||||
|
||||
## Task 3:调用点传入契约(5 处,与 Task 2 同一派发批次)
|
||||
|
||||
- `order_extraction_workflow.py` 主路由匹配处(约 :1075):传 `contract.header_to_field`(contract 已在作用域)。
|
||||
- `order_extraction_workflow.py` `_apply_reparse_profile_affinity` 内复验调用(约 :1546):先由 `run.input_snapshot_json` 冻结 definition 编译 `compile_table_header_contract` 再传入。
|
||||
- `order_extraction_workflow.py` `_confirmed_profile_order_fields`(约 :2570):同上,definition 已在作用域。
|
||||
- `order_document_profile_validation_service.py` 两处(约 :1246、:1299):从 `profile.schema_version.definition_json`(已在作用域)编译传入——满足"正式/验证/盲测同契约"。
|
||||
- Verify:`test_shipping_xfa_formal_extraction_route / test_shipping_order_extraction_worker / test_shipping_order_extraction_runs / test_shipping_document_profile_quality / test_order_document_profile_preview_service / test_order_extraction_pdf_po_split / test_shipping_notice_reservation_id` 全绿。
|
||||
|
||||
## Task 4:回归测试(新)
|
||||
|
||||
- matcher 级(放入 Task 1 测试文件):PO_6075316 形状观测 `['LN','Quantity','Part Number Vendor Item#','Description','Requested Ship Date Unit Price','','Extension']` vs 签名 token(`Requested Arrival Date` 版)——传契约不冲突;不传冲突;换真正异义词(如 `Customer PO Date` 未配别名)仍冲突。
|
||||
- 路由级合成用例:最小 frozen profile + layout 重放 `match_frozen_coordinate_profiles`,断言不再因 discriminator 拒绝(参考 tests/ 内既有 matcher 测试的构造方式)。
|
||||
- Verify:新旧用例全绿。
|
||||
|
||||
## Task 5:真实数据回归矩阵(离线重放,测试库 192.168.100.192/hxops_testing)
|
||||
|
||||
- T5.1 run 317(`SNER-20260916-C2AF1BF3`)冻结快照 + doc 879(PO_6075316)layout:向冻结 definition 注入 `Requested Ship Date` 别名(模拟治理后)→ 期望 HYVE 不再 `profile_header_discriminator_conflict`、score>0(理想 unique_match)。
|
||||
- T5.2 对照:不注入别名(=当前线上态)→ 仍 conflict(证明效果来自别名契约而非代码放水)。
|
||||
- T5.3 **全文档×全模板无翻转**:对 run 317 快照内全部文档,三种配置重放 `(i) 旧行为(header_to_field=None)`、`(ii) 新逻辑+现网 v4 别名`、`(iii) 新逻辑+注入别名`;断言 (ii)≡(i) 全部一致、(iii) 仅 879 变化其余全部一致。
|
||||
- T5.4 **模板自样本回归**:对每个已发布模板的 training/annotation 样本(layout_version_id 从 `shipping_order_document_profile_samples` 取,含坐标证据资产回填),新逻辑下各模板仍唯一自匹配。
|
||||
- Verify:输出留档 `.zcode/header_alias_replay/`。
|
||||
|
||||
## Task 6:Schema v4 原位补别名(测试库,用户已授权)+ 文档
|
||||
|
||||
- 控制器亲自执行:UPDATE `shipping_order_schema_versions`(version id=4)`definition_json` 中 `requested_receipt_date`(field_id `dfa4544a-b789-478e-ba1a-d19725817ac2`)的 aliases 追加 `'Requested Ship Date'`;改前备份原 JSON 到工作区,改后回读验证;同事务检查有无 checksum 列需同步(执行时核实)。
|
||||
- `docs/features/shipping-notice/technical.md`:补 2026-09-16 契约注记(身份原子按冻结 Schema 别名归一;别名是同义词唯一治理入口;硬互斥不变;v4 原位修订记录)。
|
||||
- `docs/funclist.md`:若存在模板匹配相关条目则补一句(执行时检查)。
|
||||
|
||||
## Task 7:收尾
|
||||
|
||||
全量相关测试套件;汇总验证输出;不 commit。
|
||||
@@ -0,0 +1,667 @@
|
||||
# 订单队列图标语义重映射 + needs_attention 标志 实现计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 队列行内图标收敛为五态语义(需人工⚠/进行中🔄/终态✓/失败✗/中性○),后端队列下发 `needs_attention` 门禁阻塞标志,summary 计数同口径对齐。
|
||||
|
||||
**Architecture:** 后端在既有批量 Gate 缓存上新增只读判定函数(零额外 SQL),`_serialize_review_case_summary` 增量输出字段;前端单组件重写 `navIconKind` 优先级链并新增 LoaderCircle 分支。无迁移、无接口破坏性变更。
|
||||
|
||||
**Tech Stack:** Flask + SQLAlchemy 2.0(后端);Vue 3 `<script setup>` + lucide-vue-next + vitest(前端);pytest(后端测试)。
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 🚫 **禁止自动 commit**(用户强规则,覆盖本 skill 模板的提交步骤):每个任务只落盘 + 跑验证,最后统一停在"完成、未提交"状态;仅当用户当轮明确说提交时才 `git add <具体文件>` + commit。
|
||||
- 外科手术式改动:只改本计划列出的文件与位置;不顺手改注释/格式/相邻代码。
|
||||
- 无数据库迁移;无新增第三方依赖;不改既有字段语义(`status`/`issue_count`/`lifecycle_stage` 原样保留)。
|
||||
- 验证基线:改动文件对应测试通过 + `cd frontend && npm run build` 通过(Task 4 统一回归)。
|
||||
- 注释遵循 AGENTS.md §5:新增函数带含 Args/Returns 的 docstring;逻辑变化同步更新受影响注释。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 后端 `needs_attention` 字段
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/order_review_projection.py`(在 `_queue_current_gate_hint` 之后、`_serialize_review_case_summary` 之前插入辅助函数;在 `_serialize_review_case_summary` 返回 dict 增加一行)
|
||||
- Test: `backend/tests/test_shipping_order_review_service.py`(文件末尾追加 3 个测试)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: 会话级缓存 `shipping_conversation_projection_read_cache` 中的 `execution_by_case_id` / `gates_by_execution_id`(`_load_review_case_summary_batch` 已预取,`:1333-1355`)。
|
||||
- Produces: 队列 item 新增 `'needs_attention': bool`(`serialize_review_queue` 与 `serialize_review_run` 的 items 均携带);模块级函数 `_queue_gate_needs_attention(case: ShippingOrderReviewCase) -> bool`,Task 2 依赖该字段。
|
||||
|
||||
- [ ] **Step 1: 追加失败测试**
|
||||
|
||||
在 `backend/tests/test_shipping_order_review_service.py` 文件末尾追加(fixture 写法仿照同文件 `test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step`,`:351-406`):
|
||||
|
||||
```python
|
||||
def test_review_queue_flags_blocked_gate_cases_as_needs_attention(app):
|
||||
"""门禁 blocked_manual(如库存缺口)的已建任务单,队列必须下发 needs_attention=True。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NEEDS-ATTN')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-needs-attn',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-ATTN',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='active',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='inventory_sufficiency',
|
||||
sequence_no=16,
|
||||
status='blocked_manual',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:库存缺口类门禁阻塞必须在队列可见,不再只依赖当前单的完整详情。
|
||||
assert item['needs_attention'] is True
|
||||
assert item['lifecycle_stage'] == 'fulfillment_prep'
|
||||
|
||||
|
||||
def test_review_queue_waiting_external_gate_is_not_needs_attention(app):
|
||||
"""RPA 外部等待(waiting_external)属于系统在办,不得标记 needs_attention。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-WAIT-EXT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-WAIT-EXT',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-wait-ext',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-WAIT',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-WAIT-EXT',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='freight_uploading',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-WAIT-EXT',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='waiting_external',
|
||||
current_gate_code='freight_upload_rpa',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='freight_upload_rpa',
|
||||
sequence_no=18,
|
||||
status='waiting_external',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:外部等待是在办不是待办,图标应走进行中而非需人工。
|
||||
assert item['needs_attention'] is False
|
||||
|
||||
|
||||
def test_review_queue_without_execution_is_not_needs_attention(app):
|
||||
"""已建任务但尚无 Execution(或缓存未命中)时,needs_attention 必须为 False。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NO-EXEC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NO-EXEC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-no-exec',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-NOEXEC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NO-EXEC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:无门禁事实时不臆造需人工标志。
|
||||
assert item['needs_attention'] is False
|
||||
```
|
||||
|
||||
若文件顶部 import 缺少 `ShippingOrderCandidate` / `ShippingOrderTask` / `ensure_review_case_for_unit` / `db`,按同文件既有测试的 import 方式补齐(它们已在既有测试中使用,通常已在顶部导入)。
|
||||
|
||||
- [ ] **Step 2: 运行验证测试失败**
|
||||
|
||||
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py::test_review_queue_flags_blocked_gate_cases_as_needs_attention -v`
|
||||
Expected: FAIL,`KeyError: 'needs_attention'`
|
||||
|
||||
- [ ] **Step 3: 实现辅助函数与字段**
|
||||
|
||||
3a. 在 `order_review_projection.py` 的 `_queue_current_gate_hint` 函数结束(`:1065` 的 `return None`)与 `_serialize_review_case_summary`(`:1068`)之间插入:
|
||||
|
||||
```python
|
||||
# 队列当前 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
|
||||
```
|
||||
|
||||
3b. 在 `_serialize_review_case_summary` 返回 dict 中,`'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0,`(`:1159`)之后插入一行:
|
||||
|
||||
```python
|
||||
'needs_attention': _queue_gate_needs_attention(case),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 运行新测试通过**
|
||||
|
||||
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v -k "needs_attention"`
|
||||
Expected: 3 passed
|
||||
|
||||
- [ ] **Step 5: 跑整个测试文件防回归**
|
||||
|
||||
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v`
|
||||
Expected: 全部 passed(既有测试只断言 `lifecycle_stage`,不受新字段影响)
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 后端 summary 计数对齐
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/order_review_projection.py`(`serialize_review_queue` 前插入归类函数;替换 `:1447-1452` 的 counts 块)
|
||||
- Test: `backend/tests/test_shipping_order_review_service.py`(追加 2 个测试)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 的 item 字段 `needs_attention`。
|
||||
- Produces: 模块级函数 `_queue_summary_bucket(item: dict[str, Any]) -> str`(返回 `'needs_action' | 'processing' | 'completed'`);`serialize_review_queue` 返回的 `summary` 三桶新口径。
|
||||
|
||||
- [ ] **Step 1: 追加失败测试**
|
||||
|
||||
```python
|
||||
def test_review_queue_summary_counts_terminal_stage_as_completed(app):
|
||||
"""OT.stage=completed(通知完成)的已建任务单计入 completed,不再计入 processing。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-DONE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-DONE',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-done',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMDONE',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-DONE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='completed',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:summary 与五态图标同口径——confirmed+终态=completed 而非 processing。
|
||||
assert summary['total'] == 1
|
||||
assert summary['completed'] == 1
|
||||
assert summary['processing'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_quality_issue_as_needs_action(app):
|
||||
"""quality_issue(文件质量异常)从 completed 改归 needs_action,与黄⚠图标一致。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-QI')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-QI',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-qi',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMQI',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
case.status = 'quality_issue'
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:质量异常是待办不是完成。
|
||||
assert summary['needs_action'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['processing'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_plain_confirmed_as_processing(app):
|
||||
"""已建任务、无阻塞、非终态的 confirmed 单计入 processing(对应转圈图标)。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-PROC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-PROC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-proc',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMPROC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-PROC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:已创建任务是在办不是完成。
|
||||
assert summary['processing'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行验证测试失败**
|
||||
|
||||
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v -k "summary_counts"`
|
||||
Expected: 3 FAILED(terminal 单被计入 processing;quality_issue 被计入 completed;plain confirmed 被计入 completed)
|
||||
|
||||
- [ ] **Step 3: 实现归类函数并替换 counts**
|
||||
|
||||
3a. 在 `serialize_review_queue`(`:1380`)定义之前插入:
|
||||
|
||||
```python
|
||||
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'
|
||||
```
|
||||
|
||||
3b. 将 `serialize_review_queue` 末尾的 counts 块(原 `:1447-1452`):
|
||||
|
||||
```python
|
||||
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')),
|
||||
}
|
||||
```
|
||||
|
||||
替换为:
|
||||
|
||||
```python
|
||||
buckets = [_queue_summary_bucket(item) for item in items]
|
||||
counts = {
|
||||
'total': len(items),
|
||||
'needs_action': buckets.count('needs_action'),
|
||||
'processing': buckets.count('processing'),
|
||||
'completed': buckets.count('completed'),
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 运行新测试通过**
|
||||
|
||||
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v -k "summary_counts or needs_attention"`
|
||||
Expected: 6 passed
|
||||
|
||||
- [ ] **Step 5: 跑整个测试文件防回归**
|
||||
|
||||
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v`
|
||||
Expected: 全部 passed(已核实 `summary` 三桶除本文件外无其他消费方;`test_shipping_conversation_processing_api.py` 等文件的 `needs_action` 属另一投影 `ShippingProcessingProjection`,不受影响)
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 前端类型 + 图标映射重写
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/chat/types/shipping.api.types.ts`(`ShippingOrderReviewCaseSummary`,`:2322` 的 `issue_count` 之后)
|
||||
- Modify: `frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.vue`
|
||||
- Test: `frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: 队列 item 的 `needs_attention?: boolean`(Task 1 下发;旧后端缺省按 false)。
|
||||
- Produces: `navIconKind(item): 'alert' | 'done' | 'failed' | 'processing' | 'idle'`(删除 `'active'`);`ReviewDocumentNavItem` 新增 `needs_attention?: boolean | null`。
|
||||
|
||||
- [ ] **Step 1: 追加失败测试**
|
||||
|
||||
在 `ReviewDocumentNavigation.spec.ts` 的最后一个 `describe` 之后追加:
|
||||
|
||||
```ts
|
||||
describe('ReviewDocumentNavigation queue row status icons', () => {
|
||||
/**
|
||||
* 以指定字段挂载单行侧栏队列,返回该行按钮包装器。
|
||||
*/
|
||||
function mountRow(item: Partial<ReviewDocumentNavItem>) {
|
||||
return mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: [{ case_no: 'C-1', file_name: 'f1.pdf', status: 'draft', ...item }],
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: 'sidebar',
|
||||
},
|
||||
global: { plugins: i18n },
|
||||
}).get('[data-testid="review-doc-nav-C-1"]');
|
||||
}
|
||||
|
||||
it('renders confirmed cases as in-progress spinner instead of done check', () => {
|
||||
const row = mountRow({ status: 'confirmed' });
|
||||
// 关键断言:已创建任务是系统在办中间态,必须转圈而非绿勾。
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(true);
|
||||
expect(row.find('svg.text-emerald-500').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders ready-to-confirm cases as amber attention icon', () => {
|
||||
const row = mountRow({ status: 'ready' });
|
||||
// 关键断言:可确认是等人操作,属于待办而非完成。
|
||||
expect(row.find('svg.text-amber-500').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders backend gate-blocked cases as amber attention icon', () => {
|
||||
const row = mountRow({ status: 'confirmed', needs_attention: true });
|
||||
// 关键断言:needs_attention 是后端门禁裁决,优先于中间态转圈。
|
||||
expect(row.find('svg.text-amber-500').exists()).toBe(true);
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('reserves the green check for terminal upload_complete', () => {
|
||||
const row = mountRow({ status: 'confirmed', lifecycle_stage: 'upload_complete' });
|
||||
expect(row.find('svg.text-emerald-500').exists()).toBe(true);
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders failed and neutral states as before', () => {
|
||||
expect(mountRow({ status: 'failed' }).find('svg.text-rose-500').exists()).toBe(true);
|
||||
const idle = mountRow({ status: 'non_order' });
|
||||
expect(idle.find('svg.text-muted').exists()).toBe(true);
|
||||
expect(idle.find('svg.animate-spin').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the truthful state icon on the selected row', () => {
|
||||
const row = mountRow({ status: 'draft' });
|
||||
// 关键断言:选中态由行高亮表达,图标不再被 active 覆盖成灰圈。
|
||||
expect(row.find('svg.text-amber-500').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('treats missing needs_attention as false for old queue payloads', () => {
|
||||
const row = mountRow({ status: 'confirmed', needs_attention: undefined });
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行验证测试失败**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`
|
||||
Expected: 新增用例 FAIL(confirmed 画绿勾、选中草稿被灰圈覆盖、`needs_attention` 未消费);既有用例仍 PASS
|
||||
|
||||
- [ ] **Step 3: 修改类型 `shipping.api.types.ts`**
|
||||
|
||||
在 `ShippingOrderReviewCaseSummary` 的 `issue_count: number;`(`:2322`)之后插入:
|
||||
|
||||
```ts
|
||||
/** 队列后端按当前门禁裁决:blocked_manual/blocked_retryable/failed_terminal 为 true;前端禁止自行推断阻塞。 */
|
||||
needs_attention?: boolean;
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 重写组件映射与模板**
|
||||
|
||||
4a. `ReviewDocumentNavigation.vue` import 块(`:9-17`)加入 `LoaderCircle`(保持字母序):
|
||||
|
||||
```ts
|
||||
import {
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Circle,
|
||||
LoaderCircle,
|
||||
Search,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
```
|
||||
|
||||
4b. `ReviewDocumentNavItem` 类型(`:21-31`):`issue_count` 之后新增字段,并同步 `lifecycle_stage` 注释:
|
||||
|
||||
```ts
|
||||
issue_count?: number;
|
||||
/** 队列接口按当前门禁裁决的"需人工"标志(blocked_manual/blocked_retryable/failed_terminal);前端禁止自行推断阻塞。 */
|
||||
needs_attention?: boolean | null;
|
||||
po_number?: string | null;
|
||||
customer_name?: string | null;
|
||||
stage_label?: string | null;
|
||||
/** 队列接口下发的生命周期码;用于阶段文字展示与终态(upload_complete)绿勾判定,不参与阶段裁决。 */
|
||||
lifecycle_stage?: ReviewLifecycleStageCode | null;
|
||||
```
|
||||
|
||||
4c. 整体替换 `navIconKind` 函数(`:120-133`):
|
||||
|
||||
```ts
|
||||
/**
|
||||
* 队列状态图标语义,按优先级命中即停:
|
||||
* 失败 → 需人工(草稿问题数 / needs_attention 门禁阻塞)→ 终态绿勾
|
||||
* → 等人状态 ⚠ → 系统在办转圈 → 中性灰圈 → 兜底转圈。
|
||||
* 绿勾只属于终态(upload_complete / closed / completed);选中态由行高亮表达,
|
||||
* 本函数不感知选中,图标永远如实反映状态。
|
||||
*/
|
||||
function navIconKind(item: ReviewDocumentNavItem): 'alert' | 'done' | 'failed' | 'processing' | 'idle' {
|
||||
const status = String(item.status || '').toLowerCase();
|
||||
if (status === 'failed' || status === 'error') return 'failed';
|
||||
if ((item.issue_count && item.issue_count > 0) || item.needs_attention === true) return 'alert';
|
||||
if (item.lifecycle_stage === 'upload_complete' || status === 'completed' || status === 'closed') return 'done';
|
||||
if (['draft', 'ready', 'unreviewed', 'quality_issue', 'pending_review', 'waiting_review'].includes(status)) return 'alert';
|
||||
if (['confirmed', 'confirming', 'processing', 'reparse_pending', 'queued'].includes(status)) return 'processing';
|
||||
if (['non_order', 'cancelled', 'superseded'].includes(status)) return 'idle';
|
||||
return 'processing';
|
||||
}
|
||||
```
|
||||
|
||||
4d. `matchesStatusFilter`(`:142`)的 processing 分支改为:
|
||||
|
||||
```ts
|
||||
if (statusFilter.value === 'processing') return kind === 'processing';
|
||||
```
|
||||
|
||||
4e. tabs 模板分支(`:216-225` 的 `<X>` 块之后、`<Circle>` 之前)插入:
|
||||
|
||||
```html
|
||||
<LoaderCircle
|
||||
v-else-if="navIconKind(item) === 'processing'"
|
||||
class="h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
```
|
||||
|
||||
4f. sidebar 模板分支(`:328-331` 的 `<X>` 块之后、`<Circle>` 之前)插入(该分支图标不带 aria-hidden,保持一致):
|
||||
|
||||
```html
|
||||
<LoaderCircle
|
||||
v-else-if="navIconKind(item) === 'processing'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
|
||||
/>
|
||||
```
|
||||
|
||||
- [ ] **Step 5: 运行新测试通过**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`
|
||||
Expected: 全部 passed(含既有 8 个用例)
|
||||
|
||||
- [ ] **Step 6: 构建验证**
|
||||
|
||||
Run: `cd frontend && npm run build`
|
||||
Expected: 构建通过,无 vue-tsc 类型错误
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 文档同步 + 全量回归
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/features/shipping-notice/technical.md`(文件末尾追加章节)
|
||||
- Modify: `docs/funclist.md`(`:95` 工作台条目所在表格追加一行)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1–3 的最终实现。
|
||||
- Produces: 与代码一致的权威文档(AGENTS.md §9 要求同一 PR 内同步)。
|
||||
|
||||
- [ ] **Step 1: technical.md 末尾追加**
|
||||
|
||||
在 `docs/features/shipping-notice/technical.md` 文件末尾(「客户数据 ODM ID 范围与整单 ODM 裁决(2026-09)」章节之后)追加:
|
||||
|
||||
```markdown
|
||||
## 订单队列五态图标与 needs_attention(2026-09)
|
||||
|
||||
- 队列接口(`serialize_review_queue` / `serialize_review_run` 共用的 `_serialize_review_case_summary`)每个 item 新增 `needs_attention: bool`:复用批量预取的 Execution/Gate 会话缓存(零额外 SQL),当前 Gate(优先 `execution.current_gate_code`,缺失按 `sequence_no` 取第一个活跃 Gate)状态 ∈ {`blocked_manual`, `blocked_retryable`, `failed_terminal`} 时为 True;`waiting_external`/`running`/`pending`/`queued` 属系统在办。前端禁止自行推断阻塞。
|
||||
- 左侧文件队列图标五态口径(`ReviewDocumentNavigation.vue` 的 `navIconKind`,优先级命中即停):失败 ✗ → 需人工 ⚠(`issue_count>0` 或 `needs_attention`,以及 `draft`/`ready`/`unreviewed`/`quality_issue`)→ 终态绿勾 ✓(`lifecycle_stage=upload_complete` 或 `closed`/`completed`)→ 系统在办蓝转圈(`confirmed`/`confirming`/`processing`/`reparse_pending`/`queued`)→ 中性灰圈(`non_order`/`cancelled`/`superseded`)→ 兜底转圈。绿勾不再被「已创建任务」等中间态占用;选中态仅由行高亮表达。
|
||||
- 队列 `summary` 三桶与图标同口径(`_queue_summary_bucket`):`quality_issue` 归 needs_action;`confirmed` 归 processing;仅终态归 completed。前端当前未消费三桶,属契约纠偏。
|
||||
- 已知边界(fail-safe):队列 `lifecycle_stage` 为轻量投影,极端场景会偏早(兜回 `intake_parse`),后果是完成单暂不亮绿勾;反向(未完成亮绿勾)不可能——`upload_complete` 仅由已持久化 `OT.stage=completed` 驱动。
|
||||
```
|
||||
|
||||
- [ ] **Step 2: funclist.md 追加条目**
|
||||
|
||||
在 `docs/funclist.md:95`(「订单生命周期工作台状态展示统一(v2)」行)之后同表追加一行:
|
||||
|
||||
```markdown
|
||||
| 订单队列五态图标与门禁阻塞标志 | 已实现 | 队列 item 新增 `needs_attention`(复用批量 Gate 缓存零额外 SQL,blocked_manual/blocked_retryable/failed_terminal 为真);左侧文件队列图标收敛为 需人工⚠/进行中🔄/终态✓/失败✗/中性○ 五态,绿勾仅限通知完成终态;队列 summary 三桶同口径。设计:[2026-09-16 队列图标语义设计](superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md) |
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 全量回归**
|
||||
|
||||
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v`
|
||||
Expected: 全部 passed
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts && npm run build`
|
||||
Expected: 测试全过、构建通过
|
||||
|
||||
- [ ] **Step 4: 停在"完成、未提交"**
|
||||
|
||||
向用户汇报改动文件清单与验证结果;**不执行任何 git add/commit**,等用户指示。
|
||||
@@ -0,0 +1,724 @@
|
||||
# 货代批次进度中心优先 + 会话业务命名 实施计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 货代发货智能体主区域改为「有会话即全屏批次进度中心、无会话显示欢迎页+输入框」,移除对话流「打开批次进度中心」冗余链路;新建抽取会话按首个附件文件名自动派生业务标题。
|
||||
|
||||
**Architecture:** 后端新增纯函数命名模块并在 `_resolve_conversation` 新建会话时调用;前端把 `ChatViewContent` 的 `batchWorkbenchOpen` 状态机坍缩为 `isShippingNoticeAgent && conversationId` 的纯判定,`ShippingWorkflowTimeline` 常驻主区域(移除关闭按钮、新增会话标题 prop),逐层移除 `open-batch-workbench` / `compact-shipping-progress` prop/emit 链。
|
||||
|
||||
**Tech Stack:** Flask + SQLAlchemy(后端纯函数 + service 接入);Vue 3 Composition API + Vitest(前端);pytest。
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-17-shipping-batch-center-first-design.md`(执行前先读 spec)
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 禁止新增第三方依赖;无数据库结构变更(无 Alembic 迁移);无环境变量变更;无新增 i18n 文案。
|
||||
- 存量会话标题一律不改:`_resolve_conversation` 只在**新建**分支派生标题;不做惰性回填;不做手动改名 API。
|
||||
- `ShippingOrderExtractionCard` 组件整体保留,仅删除「打开批次进度中心」按钮与 `compactProgress` prop。
|
||||
- 注释遵循 AGENTS.md §5:文件层块注释(用途/依赖/逻辑)、函数层 docstring/JSDoc;改动逻辑必须同步更新受影响注释。
|
||||
- 提交信息遵循 Conventional Commits:`<type>(<scope>): 中文祈使句≤100字符`。
|
||||
- ⚠️ 当前分支 `hugo-shipping-notice` 存在大量与本计划无关的未提交改动:每次提交只 `git add` 本任务明确列出的文件,禁止 `git add -A` / `git add .`。
|
||||
- 前端文件顶部如已有块注释被改动逻辑影响,必须同步更新。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 后端纯函数 `derive_order_extraction_title`
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/app/services/shipping_notice/conversation_title.py`
|
||||
- Test: `backend/tests/test_shipping_conversation_title.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: 无(纯函数,仅标准库)。
|
||||
- Produces: `derive_order_extraction_title(filenames: list[str], created_at: datetime) -> str`——Task 2 在 `_resolve_conversation` 中调用。规则:取首个非空文件名去扩展名(`/`、`\` 均视为目录分隔符)→ 循环剥离邮件前缀 `Re:` `Fw:` `Fwd:` `回复:` `转发:`(大小写不敏感)→ 主名截断 24 字符 → 文件总数 > 1 追加 `等 N 个文件`(N 为传入列表长度)→ 追加 ` MM-DD`(`created_at` 月份/日期,不换算时区)→ 全空回退 `订单抽取` → 最终长度钳制 ≤ 60(防御性,正常输入不可达)。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
创建 `backend/tests/test_shipping_conversation_title.py`:
|
||||
|
||||
```python
|
||||
"""
|
||||
backend/tests/test_shipping_conversation_title.py
|
||||
|
||||
用途:验证订单抽取会话标题纯函数的派生规则(前缀剥离/截断/计数后缀/日期/回退)。
|
||||
依赖:纯函数,无 Flask/DB 夹具。
|
||||
逻辑:命名是内容派生的确定性函数,用逐条断言锁定规则,防止后续误改口径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
|
||||
|
||||
|
||||
def test_strips_leading_mail_prefixes_and_appends_date():
|
||||
"""首个文件名循环剥离 Re/Fw/Fwd/回复/转发 前缀,末尾追加 MM-DD。"""
|
||||
title = derive_order_extraction_title(['回复:转发:FWD: PO#6075309.eml'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 09-15'
|
||||
|
||||
|
||||
def test_multi_files_appends_count_suffix():
|
||||
"""文件总数大于 1 时追加「等 N 个文件」,N 按传入文件名总数计。"""
|
||||
title = derive_order_extraction_title(['PO#6075309.eml', 'invoice.pdf', 'list.pdf'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 等 3 个文件 09-15'
|
||||
|
||||
|
||||
def test_truncates_long_name_to_24_chars():
|
||||
"""主名超过 24 字符截断,且不吞掉日期后缀。"""
|
||||
title = derive_order_extraction_title(['A' * 30 + '.pdf'], datetime(2026, 12, 31))
|
||||
assert title == 'A' * 24 + ' 12-31'
|
||||
|
||||
|
||||
def test_blank_filenames_fall_back_to_default():
|
||||
"""文件名全空(含空列表与纯空白项)回退写死标题「订单抽取」。"""
|
||||
assert derive_order_extraction_title([], datetime(2026, 9, 15)) == '订单抽取'
|
||||
assert derive_order_extraction_title(['', ' '], datetime(2026, 9, 15)) == '订单抽取'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/test_shipping_conversation_title.py -v`
|
||||
Expected: FAIL(`ModuleNotFoundError` 或 `ImportError: cannot import name 'derive_order_extraction_title'`)
|
||||
|
||||
- [ ] **Step 3: 最小实现**
|
||||
|
||||
创建 `backend/app/services/shipping_notice/conversation_title.py`:
|
||||
|
||||
```python
|
||||
"""
|
||||
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]
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/test_shipping_conversation_title.py -v`
|
||||
Expected: 4 passed
|
||||
|
||||
- [ ] **Step 5: 提交**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/conversation_title.py backend/tests/test_shipping_conversation_title.py
|
||||
git commit -m "feat(shipping-notice): 新增订单抽取会话业务命名纯函数"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: `_resolve_conversation` 新建会话接入业务标题
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/order_extraction_run_service.py`(`_resolve_conversation`,约 700-757 行;import 区)
|
||||
- Test: `backend/tests/test_shipping_order_extraction_conversation_title.py`(新建)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 的 `derive_order_extraction_title(filenames: list[str], created_at: datetime) -> str`。
|
||||
- Produces: 无对外新接口;`_resolve_conversation` 新建分支产生的 `ChatSession.title` 变为业务标题(Task 4 的中心头部经由侧栏历史间接消费该标题)。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
创建 `backend/tests/test_shipping_order_extraction_conversation_title.py`:
|
||||
|
||||
```python
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_conversation_title.py
|
||||
|
||||
用途:验证订单抽取新建会话按 Intake 资产文件名派生标题,且已存在会话标题一律不动。
|
||||
依赖:全局 Flask/SQLite 测试夹具(app)、Run service 的会话解析内部函数。
|
||||
逻辑:新建分支走 conversation_title 派生;追加归属等存量路径保持原标题(含「订单抽取」)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatSession, FileAsset, ShippingOrderIntake, User
|
||||
from app.services.shipping_notice.order_extraction_run_service import _resolve_conversation
|
||||
|
||||
|
||||
def _seed_user_agent(suffix: str) -> tuple[User, Agent]:
|
||||
"""构造用户与货代 Agent;suffix 保证同文件内多用例数据隔离。"""
|
||||
user = User(username=f'title-user-{suffix}', email=f'title-{suffix}@example.com', password_hash='x')
|
||||
agent = Agent(
|
||||
name=f'Title Agent {suffix}',
|
||||
agent_code='shipping_notice',
|
||||
runtime_provider='hybrid',
|
||||
dify_app_id=f'title-agent-{suffix}',
|
||||
dify_api_key='test-key',
|
||||
is_active=True,
|
||||
)
|
||||
user.agents.append(agent)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
return user, agent
|
||||
|
||||
|
||||
def _seed_intake(suffix: str, user: User, filename: str, conversation_id: str | None = None) -> ShippingOrderIntake:
|
||||
"""构造带资产文件名的已解析 Intake。"""
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-TITLE-{suffix}',
|
||||
owner_user_id=user.id,
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/{filename}',
|
||||
content_hash=(suffix.lower() * 64)[:64],
|
||||
file_size=10,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-TITLE-{suffix}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
return intake
|
||||
|
||||
|
||||
def test_new_session_title_derives_from_intake_filenames(app):
|
||||
"""新建会话:标题 = 首个文件名(剥离邮件前缀)+ 等 N 个文件 + 日期后缀。"""
|
||||
user, agent = _seed_user_agent('NEW')
|
||||
first = _seed_intake('NEW1', user, 'RE: PO#6075309 for HOXIN.eml')
|
||||
second = _seed_intake('NEW2', user, 'invoice.pdf')
|
||||
|
||||
session = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[first, second])
|
||||
|
||||
# 日期后缀来自 utcnow,断言前缀避免对当天日期产生脆弱依赖。
|
||||
assert session.title.startswith('PO#6075309 for HOXIN 等 2 个文件 ')
|
||||
|
||||
|
||||
def test_existing_session_title_stays_untouched(app):
|
||||
"""已存在会话:即便标题仍是写死的「订单抽取」,Intake 归属也不改标题。"""
|
||||
user, agent = _seed_user_agent('KEEP')
|
||||
session = ChatSession(session_id='title-session-keep', user_id=user.id, agent_id=agent.id, title='订单抽取')
|
||||
db.session.add(session)
|
||||
db.session.flush()
|
||||
intake = _seed_intake('KEEP1', user, 'RE: PO#6075309.eml', conversation_id=session.session_id)
|
||||
|
||||
resolved = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[intake])
|
||||
|
||||
assert resolved.session_id == session.session_id
|
||||
assert resolved.title == '订单抽取'
|
||||
```
|
||||
|
||||
注意:若运行时报 `ShippingOrderIntake` 存在其他非空字段缺省不足(以 `app/models/shipping.py:304` 为准),按既有 `tests/test_shipping_order_extraction_runs.py` 的 `_seed_run_input`(188 行起)补齐同款字段,不得改模型。
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/test_shipping_order_extraction_conversation_title.py -v`
|
||||
Expected: `test_new_session_title_derives_from_intake_filenames` FAIL(实际 title == '订单抽取');`test_existing_session_title_stays_untouched` PASS
|
||||
|
||||
- [ ] **Step 3: 最小实现**
|
||||
|
||||
`backend/app/services/shipping_notice/order_extraction_run_service.py`:
|
||||
|
||||
3a. import 区新增(与既有顶层 import 并列):
|
||||
|
||||
```python
|
||||
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
|
||||
```
|
||||
|
||||
3b. 在 `_resolve_conversation` 定义之前新增模块级辅助函数:
|
||||
|
||||
```python
|
||||
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]
|
||||
```
|
||||
|
||||
3c. `_resolve_conversation` 的 `else:` 新建分支(原 736-747 行附近)把写死的 `title='订单抽取',` 替换为派生调用,`FileAsset`/`datetime` 均已在文件顶部导入:
|
||||
|
||||
```python
|
||||
else:
|
||||
session = ChatSession(
|
||||
session_id=uuid.uuid4().hex,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title=derive_order_extraction_title(_intake_filenames(intakes), datetime.utcnow()),
|
||||
status='running',
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_active_at=datetime.utcnow(),
|
||||
)
|
||||
```
|
||||
|
||||
3d. 同步注释:`_resolve_conversation` docstring 的 Returns 行后补一句「新建会话的 title 由 conversation_title 按首个 Intake 文件名派生;已存在会话不改动标题。」;函数头文件顶部块注释如提及标题逻辑则同步(先 grep `订单抽取` 确认)。
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/test_shipping_order_extraction_conversation_title.py tests/test_shipping_conversation_title.py -v`
|
||||
Expected: 6 passed
|
||||
|
||||
- [ ] **Step 5: 回归既有 Run 用例**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/test_shipping_order_extraction_runs.py tests/test_shipping_order_extraction_concurrency.py -v`
|
||||
Expected: 全部 PASS(既有用例若断言了 `title == '订单抽取'`,仅允许把该断言放宽为「非空标题」并注明「标题已业务化」,其余逻辑禁改)
|
||||
|
||||
- [ ] **Step 6: 提交**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/order_extraction_run_service.py backend/tests/test_shipping_order_extraction_conversation_title.py
|
||||
git commit -m "feat(shipping-notice): 新建抽取会话按附件内容派生标题"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 批次进度中心移除关闭入口 + 会话标题展示
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.vue`(props/emits 定义约 71-75 行;头部模板约 861-890 行)
|
||||
- Test: `frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: 无。
|
||||
- Produces: 新 prop `conversationTitle?: string | null`(Task 4 传入);移除 `close` 事件(Task 4 同步移除监听);新增测试锚点 `data-testid="shipping-workflow-conversation-title"`。
|
||||
|
||||
- [ ] **Step 1: 更新/新增组件测试(先失败)**
|
||||
|
||||
在 `ShippingWorkflowTimeline.spec.ts` 中:
|
||||
|
||||
1a. 现有 mount 封装函数(返回 `mount(ShippingWorkflowTimeline, {...})`,约 104-113 行)改为支持透传额外 props(保持原函数名不变):
|
||||
|
||||
```ts
|
||||
function mountTimeline(
|
||||
processing: ConversationProcessingProjection | null,
|
||||
workItems: ShippingProcessingProjection[],
|
||||
extraProps: Record<string, unknown> = {},
|
||||
) {
|
||||
return mount(ShippingWorkflowTimeline, {
|
||||
attachTo: document.body,
|
||||
props: { conversationId: 'conv-1', controller: buildController(processing, workItems), ...extraProps },
|
||||
global: { plugins: [i18n], stubs: { teleport: true } },
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
1b. `describe` 内新增用例:
|
||||
|
||||
```ts
|
||||
it('has no close button and reuses the conversation title in the header', () => {
|
||||
const wrapper = mountTimeline(processingProjection(), [], { conversationTitle: 'PO#6075309 09-15' });
|
||||
|
||||
// 中心常驻不可关闭(方案 A):关闭按钮必须消失。
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-close"]').exists()).toBe(false);
|
||||
|
||||
// 会话标题直接复用侧栏命名,保持两处一致。
|
||||
const titleNode = wrapper.find('[data-testid="shipping-workflow-conversation-title"]');
|
||||
expect(titleNode.exists()).toBe(true);
|
||||
expect(titleNode.text()).toContain('PO#6075309 09-15');
|
||||
});
|
||||
|
||||
it('omits the title node when no conversation title is provided', () => {
|
||||
const wrapper = mountTimeline(processingProjection(), []);
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-conversation-title"]').exists()).toBe(false);
|
||||
});
|
||||
```
|
||||
|
||||
(若现有封装函数的参数名/默认 props 与上文不同,保持既有行为语义不变,仅追加 `extraProps` 透传能力。)
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts`
|
||||
Expected: 新增第一个用例 FAIL(`shipping-workflow-close` 仍存在、`shipping-workflow-conversation-title` 不存在)
|
||||
|
||||
- [ ] **Step 3: 组件实现**
|
||||
|
||||
`ShippingWorkflowTimeline.vue`:
|
||||
|
||||
3a. props 定义(`conversationId` / `refreshTrigger` / `controller` 之后)新增:
|
||||
|
||||
```ts
|
||||
/** 当前会话标题;父级从侧栏历史匹配传入,中心头部直接复用(无新增接口)。 */
|
||||
conversationTitle?: string | null;
|
||||
```
|
||||
|
||||
3b. `defineEmits` 中删除 `close: [];`;随后 grep `emit(` 确认组件内无其余 emit 调用后,整体删除 `const emit = defineEmits<...>();` 块。
|
||||
|
||||
3c. 头部模板删除 × 关闭按钮整块:
|
||||
|
||||
```html
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary"
|
||||
data-testid="shipping-workflow-close"
|
||||
:title="t('chat.shippingProcessing.closeWorkbench')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
```
|
||||
|
||||
3d. 标题行(`panelTitle` 文本所在的 `flex items-center gap-1.5` div 内、`panelTitle` div 之后)新增:
|
||||
|
||||
```html
|
||||
<span
|
||||
v-if="conversationTitle"
|
||||
class="min-w-0 truncate rounded bg-surface-muted px-1.5 py-0.5 text-xs text-secondary"
|
||||
data-testid="shipping-workflow-conversation-title"
|
||||
:title="conversationTitle"
|
||||
>{{ conversationTitle }}</span>
|
||||
```
|
||||
|
||||
3e. 同步文件顶部块注释「标题栏仅保留批次名称、加载与截断提示」→「标题栏保留批次名称、会话标题、加载与截断提示;中心常驻不可关闭(方案 A)」。
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts`
|
||||
Expected: 全部 PASS(含既有用例)
|
||||
|
||||
- [ ] **Step 5: 提交**
|
||||
|
||||
```bash
|
||||
git add frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.vue frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
|
||||
git commit -m "feat(shipping-notice): 批次进度中心移除关闭入口并展示会话标题"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: `ChatViewContent` 规则坍缩为中心常驻
|
||||
|
||||
**Files:**
|
||||
- Create: `frontend/src/features/chat/shipping/shippingWorkbenchLayout.ts`
|
||||
- Modify: `frontend/src/features/chat/components/ChatViewContent.vue`(script 121-152 行、474-478 行、558/580 行、667-674 行、style 824-835 行、文件头注释 9-11 行)
|
||||
- Test: `frontend/src/features/chat/shipping/shippingWorkbenchLayout.spec.ts`(新建)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 3 的 `conversationTitle` prop;页面上下文已有 `page.displayHistory`(`DisplayHistoryItem[]`,含 `conversation_id` / `title` 字段,来自 `useChatSessions.ts:86`)。
|
||||
- Produces: `shouldShowShippingWorkbench(input: { isShippingNoticeAgent: boolean; conversationId: string | null | undefined }): boolean`;`ChatViewContent` 不再暴露 `open-batch-workbench` 监听与 `compact-shipping-progress` prop(Task 5 清理子组件侧)。
|
||||
|
||||
- [ ] **Step 1: 写纯判定函数的失败测试**
|
||||
|
||||
创建 `frontend/src/features/chat/shipping/shippingWorkbenchLayout.spec.ts`:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkbenchLayout.spec.ts
|
||||
* 用途:锁定货代会话主区域显隐规则(有会话即全屏批次进度中心,方案 A)。
|
||||
* 依赖:Vitest、纯函数。
|
||||
* 逻辑:判定必须同时满足货代智能体与非空会话 ID;普通智能体与新会话一律回落欢迎页。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { shouldShowShippingWorkbench } from './shippingWorkbenchLayout';
|
||||
|
||||
describe('shouldShowShippingWorkbench', () => {
|
||||
it('renders the workbench for the shipping agent once a conversation exists', () => {
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: 'conv-1' })).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the welcome composer before a conversation is created', () => {
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: '' })).toBe(false);
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: null })).toBe(false);
|
||||
});
|
||||
|
||||
it('never switches other agents to the workbench', () => {
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: false, conversationId: 'conv-1' })).toBe(false);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/shipping/shippingWorkbenchLayout.spec.ts`
|
||||
Expected: FAIL(模块不存在)
|
||||
|
||||
- [ ] **Step 3: 实现纯判定函数**
|
||||
|
||||
创建 `frontend/src/features/chat/shipping/shippingWorkbenchLayout.ts`:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkbenchLayout.ts
|
||||
* 用途:货代发货会话主区域显隐判定(批次进度中心优先,方案 A)。
|
||||
* 依赖:无(纯函数)。
|
||||
* 逻辑:货代智能体且存在非空会话 ID 时全屏渲染批次进度中心;
|
||||
* 否则(新会话欢迎页)显示欢迎页 + 输入框(唯一附件提交入口)。
|
||||
*/
|
||||
|
||||
export interface ShippingWorkbenchLayoutInput {
|
||||
isShippingNoticeAgent: boolean;
|
||||
conversationId: string | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定是否以批次进度中心作为会话主区域。
|
||||
* @param input - 智能体身份与当前会话 ID(路由 query 与 page 回填同源优先级)。
|
||||
* @returns true 表示全屏渲染批次进度中心;false 表示欢迎页 + 输入框。
|
||||
*/
|
||||
export function shouldShowShippingWorkbench(input: ShippingWorkbenchLayoutInput): boolean {
|
||||
return Boolean(input.isShippingNoticeAgent && String(input.conversationId || '').trim());
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/shipping/shippingWorkbenchLayout.spec.ts`
|
||||
Expected: 3 passed
|
||||
|
||||
- [ ] **Step 5: `ChatViewContent.vue` 接线**
|
||||
|
||||
5a. script 顶部 import 区新增:
|
||||
|
||||
```ts
|
||||
import { shouldShowShippingWorkbench } from '@/features/chat/shipping/shippingWorkbenchLayout';
|
||||
```
|
||||
|
||||
5b. 将 script 中 121-152 行整块(`batchWorkbenchOpen`、`showShippingWorkflowTimeline`、`compactShippingProgress`、`openBatchWorkbench`、`closeBatchWorkbench`、「批次中心只服务于用户主动打开时所在的会话」watcher)替换为:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* 货代发货会话主区域规则(方案 A):
|
||||
* 有会话 ID → 全屏批次进度中心(常驻不可关闭);无会话 → 欢迎页 + 输入框(唯一提交入口)。
|
||||
*/
|
||||
const showShippingWorkflowTimeline = computed(() => shouldShowShippingWorkbench({
|
||||
isShippingNoticeAgent: page.isShippingNoticeAgent,
|
||||
conversationId: activeShippingConversationId.value,
|
||||
}));
|
||||
|
||||
/** 侧栏历史项中的会话标题;批次中心头部直接复用,保持侧栏与中心一致。 */
|
||||
const activeShippingConversationTitle = computed(() => (
|
||||
page.displayHistory.find((item) => item.conversation_id === activeShippingConversationId.value)?.title || ''
|
||||
));
|
||||
```
|
||||
|
||||
(原 watcher 的「切换会话关闭工作台」职责由中心自身按 `conversation-id` prop 重新加载数据取代,删除后无需替代逻辑。)
|
||||
|
||||
5c. 模板中 `ShippingWorkflowTimeline`(667-674 行)改为(删除 `@close`、新增标题 prop):
|
||||
|
||||
```html
|
||||
<ShippingWorkflowTimeline
|
||||
v-if="showShippingWorkflowTimeline"
|
||||
:conversation-id="activeShippingConversationId"
|
||||
:conversation-title="activeShippingConversationTitle"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingProcessing"
|
||||
/>
|
||||
```
|
||||
|
||||
5d. 模板 476-478 行两个包裹 div 移除工作台条件 class(中心 `flex-1` 自然占满,无需压缩列):
|
||||
|
||||
```html
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
```
|
||||
|
||||
```html
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
```
|
||||
|
||||
5e. 删除 `<ChatMessageList>` 上的 `:compact-shipping-progress="compactShippingProgress"`(558 行)与 `@open-batch-workbench="openBatchWorkbench"`(580 行)两行。
|
||||
|
||||
5f. 删除文件底部 `<style scoped>` 中 `@media (min-width: 1024px)` 整块(`.shipping-workbench-layout` / `.shipping-chat-column`);若 style 块因此为空则连 `<style scoped>` 标签一并删除。
|
||||
|
||||
5g. 文件头块注释(9-11 行)「右侧『本次处理』由 conversationId 驱动…」改写为「货代会话主区域:有会话即全屏批次进度中心(常驻),无会话为欢迎页+输入框;会话标题取自侧栏历史并传给中心」。
|
||||
|
||||
- [ ] **Step 6: 类型与测试门禁**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/shipping/shippingWorkbenchLayout.spec.ts src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts && npm run build`
|
||||
Expected: 测试全绿、build 通过(此时 `ChatMessageList` 仍声明但无人传 `compact-shipping-progress`、`open-batch-workbench`,属合法中间态,Task 5 清理)
|
||||
|
||||
- [ ] **Step 7: 提交**
|
||||
|
||||
```bash
|
||||
git add frontend/src/features/chat/shipping/shippingWorkbenchLayout.ts frontend/src/features/chat/shipping/shippingWorkbenchLayout.spec.ts frontend/src/features/chat/components/ChatViewContent.vue
|
||||
git commit -m "feat(shipping-notice): 货代会话主区域切换为批次中心常驻"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: 移除 `open-batch-workbench` / `compactShippingProgress` 冗余链路
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/chat/components/ChatMessageList.vue`(props 57 行、emits 71 行、模板 210/220 行)
|
||||
- Modify: `frontend/src/features/chat/components/messages/ChatMessageBubble.vue`(props 78 行、emits 92 行、模板 750/754 行)
|
||||
- Modify: `frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.vue`(props `compactProgress` 约 50-52 行、emits 约 55 行、lucide import 15 行、CTA 模板块约 947-960 行)
|
||||
- Test: `frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts`(77、111-124、829、917、959 行附近)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 4 已移除父级监听/传参。
|
||||
- Produces: `ShippingOrderExtractionCard` 对外不再有 `open-batch-workbench` 事件与 `compactProgress` prop;消息链不再透传两者。组件其余能力(状态卡渲染/重试/刷新/取消)全部保留。
|
||||
|
||||
- [ ] **Step 1: 更新卡片测试(先失败)**
|
||||
|
||||
`ShippingOrderExtractionCard.spec.ts`:
|
||||
|
||||
1a. 77、829、917、959 行四处 `expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);` 全部改为:
|
||||
|
||||
```ts
|
||||
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
```
|
||||
|
||||
1b. 删除用例 `collapses file-level progress when the batch workbench is open`(约 111-124 行,`compactProgress` prop 已不存在,紧凑模式语义随之移除)。
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts`
|
||||
Expected: 1a 改动后的四处断言 FAIL(按钮仍渲染)
|
||||
|
||||
- [ ] **Step 3: 删除链路实现**
|
||||
|
||||
3a. `ShippingOrderExtractionCard.vue`:
|
||||
- 删除 CTA 整块(外层 `div.flex.justify-end.border-t.border-default.bg-brand-50\/60.p-3` 连同内部「打开批次进度中心」按钮,约 947-960 行);
|
||||
- emits 定义删除 `'open-batch-workbench': [];`;props 删除 `compactProgress?: boolean;` 及其注释行;
|
||||
- 文件内 grep `ArrowRight`:仅按钮在用时从 lucide import 中移除;
|
||||
- 文件头块注释「唯一主 CTA、查看详情」与「批次工作台打开后切换为紧凑摘要」改为「无对话流 CTA(批次中心常驻,方案 A)」。
|
||||
|
||||
3b. `ChatMessageBubble.vue`:props 删除 `compactShippingProgress?: boolean;`(78 行);emits 删除 `'open-batch-workbench': [];`(92 行);模板删除 `:compact-progress="compactShippingProgress"`(750 行)与 `@open-batch-workbench="emit('open-batch-workbench')"`(754 行)。
|
||||
|
||||
3c. `ChatMessageList.vue`:props 删除 `compactShippingProgress?: boolean;`(57 行);emits 删除 `'open-batch-workbench': [];`(71 行);模板删除 `:compact-shipping-progress="compactShippingProgress"`(210 行)与 `@open-batch-workbench="emit('open-batch-workbench')"`(220 行)。
|
||||
|
||||
3d. 三处文件头块注释若提及 CTA/紧凑模式,同步为「对话流仅保留状态卡渲染(历史兜底),批次中心入口已移除(方案 A)」。
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts && npm run build`
|
||||
Expected: 卡片 spec 全绿;build 通过(无未使用变量/导入的 TS 报错)
|
||||
|
||||
- [ ] **Step 5: 相关组件回归**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat`
|
||||
Expected: chat 域全部 spec 通过(重点:`ChatMessageList` 相关、`ShippingConversationProcessingCard.spec.ts`、`ChatViewContent` 无既有 spec 不受影响)
|
||||
|
||||
- [ ] **Step 6: 提交**
|
||||
|
||||
```bash
|
||||
git add frontend/src/features/chat/components/ChatMessageList.vue frontend/src/features/chat/components/messages/ChatMessageBubble.vue frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.vue frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts
|
||||
git commit -m "refactor(shipping-notice): 移除对话流打开批次中心冗余链路"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: 文档同步与全量门禁
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/funclist.md`(货代发货功能清单小节)
|
||||
- Modify: `docs/features/shipping-notice/technical.md`(交互链路章节)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1-5 的最终行为。
|
||||
- Produces: 与代码一致的文档(AGENTS.md §9 强制)。
|
||||
|
||||
- [ ] **Step 1: 更新 `docs/funclist.md`**
|
||||
|
||||
`grep -n "货代发货" docs/funclist.md` 定位小节;`grep -n "打开批次进度中心\|批次进度" docs/funclist.md` 找到既有相关行。在该小节新增两行(沿用本文件既有条目格式,列表或表格随原文):
|
||||
|
||||
```
|
||||
- 货代发货会话主区域为批次进度中心:有会话即全屏常驻展示(不可关闭),无会话显示欢迎页与附件提交入口;历史会话点击直达中心
|
||||
- 新建订单抽取会话自动按首个附件文件名命名(剥离邮件前缀 + 等 N 个文件 + 日期后缀);存量会话名不变
|
||||
```
|
||||
|
||||
既有「打开批次进度中心」相关条目改为「(已下线对话流入口,批次中心为会话主区域)」措辞,不删除历史行文风格。
|
||||
|
||||
- [ ] **Step 2: 更新 `docs/features/shipping-notice/technical.md`**
|
||||
|
||||
`grep -n "批次进度中心\|openBatchWorkbench\|batchWorkbenchOpen" docs/features/shipping-notice/technical.md` 定位相关章节,更新/新增如下要点(跟随原文档章节结构,不另起重复章节):
|
||||
|
||||
```markdown
|
||||
### 会话主区域与批次进度中心(2026-09 方案 A)
|
||||
|
||||
- 货代发货智能体主区域规则:`isShippingNoticeAgent && conversation_id 非空` → 全屏渲染批次进度中心
|
||||
(`ShippingWorkflowTimeline`,常驻无关闭按钮);否则渲染欢迎页 + 输入框(唯一附件提交入口)。
|
||||
判定纯函数:`frontend/src/features/chat/shipping/shippingWorkbenchLayout.ts`。
|
||||
- 提交链路不变:`startRun` 成功 → 路由写回 `conversation_id` → 中心出现;对话流不再出现
|
||||
「本次订单文件处理」卡片入口,`open-batch-workbench` / `compact-shipping-progress` 链路已移除;
|
||||
`ShippingOrderExtractionCard` 保留为历史消息兜底渲染。
|
||||
- 中心头部复用会话标题(父级从侧栏 `displayHistory` 按 conversation_id 匹配传入 `conversation-title`)。
|
||||
- 新建抽取会话命名:`backend/app/services/shipping_notice/conversation_title.py`
|
||||
`derive_order_extraction_title(filenames, created_at)` —— 首个非空文件名去扩展名、剥离
|
||||
Re:/Fw:/Fwd:/回复:/转发:前缀、截 24 字、多文件追加「等 N 个文件」、追加 MM-DD;
|
||||
全空回退「订单抽取」。仅在 `_resolve_conversation` 新建分支调用;存量会话标题一律不改。
|
||||
- 同批次追加附件:中心不提供入口,通过「新建对话」重新提交(后端 append/create 裁决逻辑不变)。
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 全量门禁**
|
||||
|
||||
Run: `cd frontend && npm run build`
|
||||
Expected: 构建通过
|
||||
Run: `cd backend && python -m pytest tests/test_shipping_conversation_title.py tests/test_shipping_order_extraction_conversation_title.py tests/test_shipping_order_extraction_runs.py -v`
|
||||
Expected: 全部 PASS
|
||||
|
||||
- [ ] **Step 4: 提交**
|
||||
|
||||
```bash
|
||||
git add docs/funclist.md docs/features/shipping-notice/technical.md
|
||||
git commit -m "docs(shipping-notice): 同步批次中心优先与会话命名说明"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 验收核对(对照 spec §8)
|
||||
|
||||
1. 新会话发附件 → 提交成功后全屏批次进度中心,无对话卡、无关闭按钮(Task 3/4);
|
||||
2. 历史会话点击 → 直达该会话中心(Task 4 规则天然覆盖);
|
||||
3. 新批次会话名形如 `PO#6075309 for HOXIN 等 2 个文件 09-15`;存量名不变(Task 1/2);
|
||||
4. 普通智能体零变化;前端 build 与后端相关 pytest 全绿(Task 4-6)。
|
||||
@@ -0,0 +1,338 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>我的待办 · 改版原型(方案A:列表优先 + 按需抽屉)</title>
|
||||
<style>
|
||||
:root{
|
||||
--blue:#2f7bff; --blue-weak:#eaf1ff; --bg:#f4f6fa; --line:#e5e9f2;
|
||||
--red:#e5484d; --red-weak:#fdecec; --text:#1f2733; --sub:#6b7686;
|
||||
--green:#188a4c; --green-weak:#e6f7ec; --amber:#b26a00; --amber-weak:#fff4e0;
|
||||
--purple:#7a4fd3; --purple-weak:#f1e9ff;
|
||||
}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{background:#e9edf4;color:var(--text);font-family:"Segoe UI","Microsoft YaHei",system-ui,sans-serif;padding-bottom:80px}
|
||||
|
||||
.proto-banner{position:sticky;top:0;z-index:99;background:#111c33;color:#c6d2e8;padding:10px 22px;font-size:13px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}
|
||||
.proto-banner b{color:#fff}
|
||||
.proto-banner .pill{background:var(--blue);color:#fff;border-radius:999px;padding:2px 10px;font-size:12px;white-space:nowrap}
|
||||
.proto-banner .warn{color:#ffd479;font-size:12px}
|
||||
|
||||
.screen{max-width:1220px;margin:40px auto 0;padding:0 22px}
|
||||
.screen-head{display:flex;align-items:baseline;gap:10px;margin-bottom:12px;flex-wrap:wrap}
|
||||
.chip{background:var(--blue);color:#fff;border-radius:6px;font-weight:700;font-size:13px;padding:2px 9px}
|
||||
.screen-head h2{font-size:17px}
|
||||
.screen-head span{font-size:13px;color:var(--sub)}
|
||||
.frame{background:#fff;border:1px solid var(--line);border-radius:14px;box-shadow:0 10px 30px rgba(31,39,51,.08);overflow:hidden}
|
||||
.notes{margin:10px 4px 0;font-size:12.5px;color:#5b6779;line-height:1.9}
|
||||
.notes i{font-style:normal;color:var(--blue);font-weight:700}
|
||||
|
||||
/* ---- 页面骨架 ---- */
|
||||
.topbar{display:flex;justify-content:space-between;align-items:flex-start;padding:20px 22px 8px}
|
||||
.topbar h1{font-size:22px}
|
||||
.topbar p{font-size:13px;color:var(--sub);margin-top:4px}
|
||||
.seg{display:inline-flex;background:#eef1f7;border-radius:10px;padding:3px;margin:10px 22px 0}
|
||||
.seg button{border:0;background:transparent;padding:7px 18px;border-radius:8px;font-size:13.5px;color:var(--sub);cursor:default}
|
||||
.seg button.on{background:#fff;color:var(--text);font-weight:600;box-shadow:0 1px 4px rgba(31,39,51,.12)}
|
||||
.buckets{display:flex;gap:8px;padding:14px 22px 4px}
|
||||
.bucket{border:1px solid var(--line);background:#fff;border-radius:999px;padding:6px 16px;font-size:13px;color:var(--sub)}
|
||||
.bucket.on{background:var(--blue);border-color:var(--blue);color:#fff;font-weight:600}
|
||||
.stages{display:flex;gap:8px;padding:12px 22px;border-bottom:1px solid var(--line);flex-wrap:wrap}
|
||||
.stage{border:1px solid var(--line);border-radius:999px;padding:5px 14px;font-size:13px;color:var(--sub);background:#fff}
|
||||
.stage b{margin-left:4px}
|
||||
.stage.on{background:var(--blue-weak);border-color:var(--blue);color:var(--blue);font-weight:600}
|
||||
.filters{display:flex;gap:10px;align-items:center;padding:14px 22px;border-bottom:1px solid var(--line);flex-wrap:wrap}
|
||||
.filters select,.filters input{border:1px solid var(--line);border-radius:8px;padding:7px 10px;font-size:13px;color:var(--sub);background:#fff}
|
||||
.filters input{width:190px}
|
||||
.filters .grow{flex:1}
|
||||
.btn{border:1px solid var(--line);background:#fff;border-radius:8px;padding:7px 14px;font-size:13px;color:var(--text)}
|
||||
.btn.primary{background:var(--blue);border-color:var(--blue);color:#fff;font-weight:600}
|
||||
.btn.ghost{color:var(--blue);border-color:#c9dcff}
|
||||
.btn.dark{background:#1b2740;border-color:#1b2740;color:#fff}
|
||||
.btn.sm{padding:5px 11px;font-size:12.5px}
|
||||
|
||||
/* ---- 表格 ---- */
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
th{ text-align:left;color:var(--sub);font-weight:500;padding:10px 14px;border-bottom:1px solid var(--line);background:#fafbfd;white-space:nowrap}
|
||||
td{padding:9px 14px;border-bottom:1px solid #f0f3f8;vertical-align:middle}
|
||||
tr.row:hover td{background:#f7faff}
|
||||
.no{font-weight:600;letter-spacing:.2px}
|
||||
.no .tag{font-weight:400}
|
||||
.sub{color:var(--sub);font-size:12px;margin-top:3px;font-weight:400}
|
||||
.tag{display:inline-block;font-size:11px;color:var(--amber);background:var(--amber-weak);border-radius:4px;padding:1px 6px;margin-left:8px;vertical-align:1px}
|
||||
.tag.blue{color:#3b6fd4;background:#eef4ff}
|
||||
.badge{display:inline-block;padding:2px 10px;border-radius:999px;font-size:12px;white-space:nowrap}
|
||||
.st-intake{background:#eef4ff;color:#3b6fd4}
|
||||
.st-review{background:var(--amber-weak);color:var(--amber)}
|
||||
.st-prepare{background:#e8f3ff;color:#1677d9}
|
||||
.st-upload{background:var(--purple-weak);color:var(--purple)}
|
||||
.st-done{background:var(--green-weak);color:var(--green)}
|
||||
.st-reject{background:var(--red-weak);color:var(--red)}
|
||||
.st-void{background:#eef1f7;color:var(--sub)}
|
||||
.block{color:var(--red)}
|
||||
.short{color:var(--red);font-weight:700}
|
||||
.muted{color:var(--sub)}
|
||||
.pager{display:flex;justify-content:center;align-items:center;gap:18px;padding:14px;font-size:13px;color:var(--sub)}
|
||||
|
||||
/* ---- 批量浮动条 ---- */
|
||||
.batchbar{display:flex;align-items:center;gap:12px;background:#1b2740;color:#e8eefb;padding:10px 18px;font-size:13px}
|
||||
.batchbar .cnt{background:var(--blue);border-radius:999px;padding:2px 12px;font-weight:600}
|
||||
.batchbar .sp{flex:1}
|
||||
|
||||
/* ---- 抽屉态 ---- */
|
||||
.split{position:relative;height:820px;background:var(--bg)}
|
||||
.backdrop{position:absolute;inset:0;overflow:hidden;opacity:.38;filter:grayscale(.2)}
|
||||
.scrim{position:absolute;inset:0;background:rgba(23,32,51,.35)}
|
||||
.drawer{position:absolute;top:0;right:0;bottom:0;width:540px;max-width:94%;background:#fff;box-shadow:-16px 0 40px rgba(15,23,42,.25);display:flex;flex-direction:column}
|
||||
.d-head{padding:18px 22px 12px;border-bottom:1px solid var(--line)}
|
||||
.d-head .t{display:flex;justify-content:space-between;align-items:center}
|
||||
.d-head .t h3{font-size:17px;letter-spacing:.2px}
|
||||
.d-head .x{border:0;background:#eef1f7;border-radius:8px;width:28px;height:28px;color:var(--sub);font-size:14px}
|
||||
.d-head .meta{font-size:12.5px;color:var(--sub);margin-top:6px}
|
||||
.d-body{flex:1;overflow:auto;padding:16px 22px}
|
||||
.banner{background:var(--red-weak);border:1px solid #f5c6c8;color:var(--red);border-radius:10px;padding:10px 14px;font-size:13px;margin-bottom:16px}
|
||||
.sec{font-size:13px;font-weight:700;margin:18px 0 8px;display:flex;align-items:center;gap:8px}
|
||||
.sec::after{content:"";flex:1;height:1px;background:var(--line)}
|
||||
.mini td,.mini th{padding:7px 10px;font-size:12.5px}
|
||||
.mini td.num{font-variant-numeric:tabular-nums}
|
||||
.chip-red{background:var(--red-weak);color:var(--red);border-radius:4px;padding:1px 7px;font-size:11.5px;font-weight:700}
|
||||
.chip-gray{background:#eef1f7;color:var(--sub);border-radius:4px;padding:1px 7px;font-size:11.5px}
|
||||
.file{display:flex;align-items:center;gap:10px;border:1px solid var(--line);border-radius:10px;padding:9px 12px;font-size:13px;margin-bottom:8px}
|
||||
.file .ic{width:30px;height:30px;border-radius:8px;background:#eef4ff;color:#3b6fd4;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700}
|
||||
.file .sp{flex:1}
|
||||
.file a{color:var(--blue);font-size:12.5px;text-decoration:none}
|
||||
.d-foot{border-top:1px solid var(--line);padding:14px 22px;display:flex;flex-direction:column;gap:10px;background:#fff}
|
||||
.d-foot .r1{display:flex;gap:10px}
|
||||
.d-foot select{border:1px solid var(--line);border-radius:8px;padding:8px 10px;font-size:13px;color:var(--text)}
|
||||
.d-foot .r1 .btn.primary{flex:1}
|
||||
.d-foot .r2{display:flex;gap:10px;align-items:center}
|
||||
.link{color:var(--blue);font-size:12.5px;text-decoration:none}
|
||||
.d-foot .hint{font-size:11.5px;color:var(--sub)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="proto-banner">
|
||||
<span class="pill">设计原型 · 静态稿</span>
|
||||
<b>货代发货通知「我的待办」改版</b>
|
||||
<span>方案 A:列表优先 + 按需抽屉 · 2026-09-16</span>
|
||||
<span class="warn">仅用于评审,非实现代码</span>
|
||||
</div>
|
||||
|
||||
<!-- ================= 状态 1:列表态 ================= -->
|
||||
<div class="screen">
|
||||
<div class="screen-head"><span class="chip">状态 1</span><h2>列表态(全部 tab)</h2><span>卡片列表 → 紧凑表格;右侧常驻详情面板移除</span></div>
|
||||
<div class="frame">
|
||||
<div class="topbar">
|
||||
<div><h1>我的待办</h1><p>按文件查看接收解析与订单生命周期进度;处理详情在订单生命周期工作台完成。</p></div>
|
||||
<button class="btn">⟳ 刷新</button>
|
||||
</div>
|
||||
<div class="seg"><button class="on">我的待办</button><button>我的识别</button></div>
|
||||
<div class="buckets"><span class="bucket on">待处理(13)</span><span class="bucket">处理中(0)</span><span class="bucket">已完成(0)</span></div>
|
||||
<div class="stages">
|
||||
<span class="stage on">全部<b>13</b></span>
|
||||
<span class="stage">接收解析<b>2</b></span>
|
||||
<span class="stage">订单复核<b>4</b></span>
|
||||
<span class="stage">通知准备<b>3</b></span>
|
||||
<span class="stage">货代上传<b>4</b></span>
|
||||
</div>
|
||||
<div class="filters">
|
||||
<select><option>待办类型:全部</option></select>
|
||||
<input placeholder="客户名称或简码">
|
||||
<input placeholder="SN 编号">
|
||||
<span class="grow"></span>
|
||||
<button class="btn primary">应用筛选</button>
|
||||
<button class="btn">重置</button>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th style="width:36px"></th><th>编号 / 客户 · PO · 文件</th><th style="width:90px">阶段</th>
|
||||
<th>状态摘要</th><th style="width:96px">项次/缺口</th><th style="width:88px">货代状态</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr class="row"><td></td>
|
||||
<td><div class="no">SORC-25CEF2F1FA504685<span class="tag">订单复核</span></div><div class="sub">微软 · PO_6075309.pdf</div></td>
|
||||
<td><span class="badge st-review">订单复核</span></td><td>复核草稿待继续编辑</td><td class="muted">—</td><td class="muted">—</td></tr>
|
||||
<tr class="row"><td></td>
|
||||
<td><div class="no">OT-20260916-769EF9D3-C680</div><div class="sub">华为 · PO_6075309 · PO_6075309.pdf</div></td>
|
||||
<td><span class="badge st-prepare">通知准备</span></td><td class="block">库存存在缺口,需人工处理</td><td><b>5 项</b> · <span class="short">缺 1</span></td><td class="muted">—</td></tr>
|
||||
<tr class="row"><td></td>
|
||||
<td><div class="no">OT-20260916-769EF9D3-C679</div><div class="sub">华为 · PO_6075310 · PO_6075310.pdf</div></td>
|
||||
<td><span class="badge st-prepare">通知准备</span></td><td class="block">库存存在缺口,需人工处理</td><td><b>4 项</b> · <span class="short">缺 2</span></td><td class="muted">—</td></tr>
|
||||
<tr class="row"><td><input type="checkbox"></td>
|
||||
<td><div class="no">OT-20260916-04BCBB1A</div><div class="sub">中兴 · PO_6075312 · PO_6075312.xlsx</div></td>
|
||||
<td><span class="badge st-upload">货代上传</span></td><td>备货完成,可上传货代</td><td><b>3 项</b></td><td>待上传</td></tr>
|
||||
<tr class="row"><td><input type="checkbox"></td>
|
||||
<td><div class="no">OT-20260916-04BCBB1B</div><div class="sub">中兴 · PO_6075313 · PO_6075313.xlsx</div></td>
|
||||
<td><span class="badge st-upload">货代上传</span></td><td>已上传,待确认</td><td><b>6 项</b></td><td>已上传</td></tr>
|
||||
<tr class="row"><td></td>
|
||||
<td><div class="no">INT-20260916-7712<span class="tag blue">材料解析</span></div><div class="sub">东风 · DFM_PO_0091.pdf</div></td>
|
||||
<td><span class="badge st-intake">接收解析</span></td><td>解析完成,待确认明细</td><td class="muted">—</td><td class="muted">—</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pager">‹ 上一页<span>第 1 / 1 页</span>下一页 ›</div>
|
||||
</div>
|
||||
<div class="notes">
|
||||
<i>①</i> 阶段 tab 计数来自后端聚合(替换现在只统计当前页的五张卡片),点击即筛选;<b>「通知完成」不再是筛选 tab</b>——终态任务统一收进「已完成」桶,行上用角标区分:上传完成 / 复核驳回 / 已作废。<br>
|
||||
<i>②</i> 复选框仅「货代上传」阶段的行存在,其余阶段该列为空。<br>
|
||||
<i>③</i> 点击行任意位置 → 打开右侧详情抽屉(状态 3 / 状态 4);行高约为原卡片一半,一屏可见 12~15 条。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================= 状态 2:批量态 ================= -->
|
||||
<div class="screen">
|
||||
<div class="screen-head"><span class="chip">状态 2</span><h2>批量操作态</h2><span>仅货代上传 tab;勾选 ≥1 后操作条浮出,无常驻工具栏</span></div>
|
||||
<div class="frame">
|
||||
<div class="stages">
|
||||
<span class="stage">全部<b>13</b></span>
|
||||
<span class="stage">接收解析<b>2</b></span>
|
||||
<span class="stage">订单复核<b>4</b></span>
|
||||
<span class="stage">通知准备<b>3</b></span>
|
||||
<span class="stage on">货代上传<b>4</b></span>
|
||||
<span class="stage">通知完成<b>0</b></span>
|
||||
</div>
|
||||
<div class="batchbar">
|
||||
<span class="cnt">已选 2 张</span>
|
||||
<button class="btn sm dark">⬇ 批量下载 Excel</button>
|
||||
<button class="btn sm dark">✓ 批量确认已上传</button>
|
||||
<button class="btn sm dark">▲ 批量发起 RPA</button>
|
||||
<span class="sp"></span>
|
||||
<button class="btn sm" style="background:transparent;color:#9fb0d0;border-color:#3a4a6e">清除选择</button>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th style="width:36px"><input type="checkbox" checked></th><th>编号 / 客户 · PO · 文件</th><th style="width:90px">阶段</th>
|
||||
<th>状态摘要</th><th style="width:96px">项次/缺口</th><th style="width:88px">货代状态</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr class="row"><td><input type="checkbox" checked></td>
|
||||
<td><div class="no">OT-20260916-04BCBB1A</div><div class="sub">中兴 · PO_6075312 · PO_6075312.xlsx</div></td>
|
||||
<td><span class="badge st-upload">货代上传</span></td><td>备货完成,可上传货代</td><td><b>3 项</b></td><td>待上传</td></tr>
|
||||
<tr class="row"><td><input type="checkbox" checked></td>
|
||||
<td><div class="no">OT-20260916-04BCBB1B</div><div class="sub">中兴 · PO_6075313 · PO_6075313.xlsx</div></td>
|
||||
<td><span class="badge st-upload">货代上传</span></td><td>已上传,待确认</td><td><b>6 项</b></td><td>已上传</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pager">‹ 上一页<span>第 1 / 1 页</span>下一页 ›</div>
|
||||
</div>
|
||||
<div class="notes">
|
||||
<i>①</i> 深色浮动操作条只在勾选 ≥1 行后出现,替代现在常驻(且 i18n 缺失、显示原始 key)的工具栏。<br>
|
||||
<i>②</i> 表头复选框 = 全选当前筛选结果;离开本阶段 tab 或清除后自动收起。<br>
|
||||
<i>③</i> 按钮文案使用修复后的 <code>shippingNotice.batch.*</code> 四语言 key。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================= 状态 3:抽屉态 ================= -->
|
||||
<div class="screen">
|
||||
<div class="screen-head"><span class="chip">状态 3</span><h2>详情抽屉态</h2><span>点击列表行滑出;逐行明细 = 分诊决策依据</span></div>
|
||||
<div class="frame">
|
||||
<div class="split">
|
||||
<div class="backdrop">
|
||||
<div class="topbar"><div><h1>我的待办</h1><p>按文件查看接收解析与订单生命周期进度。</p></div></div>
|
||||
<div class="buckets"><span class="bucket on">待处理(13)</span></div>
|
||||
<table>
|
||||
<thead><tr><th style="width:36px"></th><th>编号 / 客户 · PO · 文件</th><th style="width:90px">阶段</th><th>状态摘要</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td></td><td><div class="no">SORC-25CEF2F1FA504685<span class="tag">订单复核</span></div></td><td><span class="badge st-review">订单复核</span></td><td>复核草稿待继续编辑</td></tr>
|
||||
<tr><td></td><td><div class="no" style="outline:2px solid #2f7bff;outline-offset:-2px;border-radius:6px">OT-20260916-769EF9D3-C680</div></td><td><span class="badge st-prepare">通知准备</span></td><td>库存存在缺口</td></tr>
|
||||
<tr><td></td><td><div class="no">OT-20260916-769EF9D3-C679</div></td><td><span class="badge st-prepare">通知准备</span></td><td>库存存在缺口</td></tr>
|
||||
<tr><td><input type="checkbox"></td><td><div class="no">OT-20260916-04BCBB1A</div></td><td><span class="badge st-upload">货代上传</span></td><td>备货完成</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="scrim"></div>
|
||||
<div class="drawer">
|
||||
<div class="d-head">
|
||||
<div class="t"><h3>OT-20260916-769EF9D3-C680</h3><button class="x">✕</button></div>
|
||||
<div class="meta">华为 · PO_6075309 · PO_6075309.pdf</div>
|
||||
<div style="margin-top:8px"><span class="badge st-prepare">通知准备 · 当前阶段</span></div>
|
||||
</div>
|
||||
<div class="d-body">
|
||||
<div class="banner">⚠ 阻断:库存存在缺口,需要人工处理 —— 处理详情请在订单生命周期工作台完成。</div>
|
||||
|
||||
<div class="sec">逐行明细(notice_line_summary)</div>
|
||||
<table class="mini">
|
||||
<thead><tr><th>行</th><th>料号</th><th>客户料号</th><th>预约号</th><th>本次发货</th><th>可用库存</th><th>缺口</th><th>状态</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="num">01</td><td>9527-100-A</td><td>HW-100-A</td><td>R20260916-01</td><td class="num">100</td><td class="num">100</td><td class="num">0</td><td><span class="chip-gray">在库</span></td></tr>
|
||||
<tr><td class="num">02</td><td>9527-200-B</td><td>HW-200-B</td><td>R20260916-02</td><td class="num">50</td><td class="num">30</td><td class="num short">20</td><td><span class="chip-red">缺料</span></td></tr>
|
||||
<tr><td class="num">03</td><td>9527-150-C</td><td>—</td><td>—</td><td class="num">20</td><td class="num">20</td><td class="num">0</td><td><span class="chip-gray">在库</span></td></tr>
|
||||
<tr><td class="num">04</td><td>9527-400-D</td><td>HW-400-D</td><td>R20260916-04</td><td class="num">10</td><td class="num">10</td><td class="num">0</td><td><span class="chip-gray">在库</span></td></tr>
|
||||
<tr><td class="num">05</td><td>9527-050-E</td><td>—</td><td>—</td><td class="num">5</td><td class="num">0</td><td class="num short">5</td><td><span class="chip-red">缺料</span></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="sec">文件</div>
|
||||
<div class="file"><span class="ic">源</span>PO_6075309.pdf<span class="sp"></span><a href="#">查看</a></div>
|
||||
<div class="file"><span class="ic">Excel</span>HW-PO_6075309.xlsx(导出)<span class="sp"></span><a href="#">⬇ 下载</a></div>
|
||||
</div>
|
||||
<div class="d-foot">
|
||||
<div class="r1">
|
||||
<select><option>阶段目标:通知准备</option><option>货代上传</option></select>
|
||||
<button class="btn primary">进入订单生命周期工作台</button>
|
||||
</div>
|
||||
<div class="r2">
|
||||
<button class="btn ghost">打开 Chat 会话</button>
|
||||
<a class="link" href="#">重试自动推进</a>
|
||||
<span class="hint">入口与按钮按后端 ui_state 权限裁决显示</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="notes">
|
||||
<i>①</i> 抽屉承载原卡片里塞不下的明细:逐行料号 / 预约号 / 发货量 / 可用量 / 缺口 —— 不用跳转即可判断「这张单能不能走」。<br>
|
||||
<i>②</i> 底部操作条沿用现有三分支逻辑(review / intake / task),权限仍由后端 ui_state 决定。<br>
|
||||
<i>③</i> Esc / 点遮罩 / ✕ 关闭;移动端抽屉全屏。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================= 状态 4:已完成桶(通知完成明细报表) ================= -->
|
||||
<div class="screen">
|
||||
<div class="screen-head"><span class="chip">状态 4</span><h2>已完成桶:通知完成 → 明细报表</h2><span>明细平铺不按 OT 聚合;OT 编号仅页面展示,导出严格 12 列</span></div>
|
||||
<div class="frame">
|
||||
<div class="topbar">
|
||||
<div><h1>我的待办</h1><p>按文件查看接收解析与订单生命周期进度;处理详情在订单生命周期工作台完成。</p></div>
|
||||
<button class="btn">⟳ 刷新</button>
|
||||
</div>
|
||||
<div class="seg"><button class="on">我的待办</button><button>我的识别</button></div>
|
||||
<div class="buckets"><span class="bucket">待处理(13)</span><span class="bucket">处理中(0)</span><span class="bucket on">已完成(45)</span></div>
|
||||
<div class="stages">
|
||||
<span class="stage on">通知完成<b>42</b></span>
|
||||
<span class="stage">复核驳回 / 已作废<b>3</b></span>
|
||||
</div>
|
||||
<div class="filters">
|
||||
<select><option>客户:全部</option></select>
|
||||
<input placeholder="日期范围">
|
||||
<input placeholder="料号">
|
||||
<span class="grow"></span>
|
||||
<button class="btn primary">⬇ 导出 Excel(当前筛选)</button>
|
||||
</div>
|
||||
<div style="overflow-x:auto">
|
||||
<table style="min-width:1560px">
|
||||
<thead><tr>
|
||||
<th>OT 编号</th><th>客户</th><th>客户编号</th><th>订单日期</th><th>订单项次</th><th>料号</th><th>数量</th>
|
||||
<th>约定出货日期</th><th>客户PO</th><th>已用数量</th><th>open qty</th><th>订单单号</th><th>单价</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr class="row"><td class="no">OT-20260916-769EF9D3-C672</td><td>HYVE CS</td><td>HC001</td><td>06-01</td><td>1</td><td>B3-A08AR10000017-A6</td><td class="num">80</td><td>06-15</td><td>306085</td><td class="num">80</td><td class="num">0</td><td>8301-2606010052</td><td class="num">1525.08</td></tr>
|
||||
<tr class="row"><td class="no">OT-20260916-769EF9D3-C672</td><td>FLEX-SLC</td><td>FS002</td><td>06-01</td><td>2</td><td>D4-A08AR12000001</td><td class="num">1000</td><td>06-15</td><td>269T23413</td><td></td><td></td><td>8301-2606010041</td><td class="num">898.72</td></tr>
|
||||
<tr class="row"><td class="no">OT-20260916-769EF9D3-C672</td><td>FLEX-SLC</td><td>FS002</td><td>06-01</td><td>3</td><td>B3-AR1000270A1</td><td class="num">1000</td><td>06-15</td><td>269T23415</td><td></td><td></td><td>8301-2606010043</td><td class="num">50.43</td></tr>
|
||||
<tr class="row"><td class="no">OT-20260916-769EF9D3-C671</td><td>HYVE CS</td><td>HC001</td><td>06-01</td><td>1</td><td>B3-A08AR10000017-A6</td><td class="num">200</td><td>06-18</td><td>306085</td><td class="num">200</td><td class="num">0</td><td>8301-2606010038</td><td class="num">1520.00</td></tr>
|
||||
<tr class="row"><td class="no">OT-20260916-04BCBB09</td><td>FLEX-SLC</td><td>FS002</td><td>06-02</td><td>1</td><td>D4-A08AR12000009</td><td class="num">500</td><td>06-20</td><td>269T23420</td><td class="num">500</td><td class="num">0</td><td>8301-2606010035</td><td class="num">899.50</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="pager">‹ 上一页<span>第 1 / 9 页(按明细行分页)</span>下一页 ›</div>
|
||||
</div>
|
||||
<div class="notes">
|
||||
<i>①</i> 已完成桶子视图:`通知完成`=明细报表(平铺、无抽屉、无行级操作);`复核驳回 / 已作废`=仍是 OT 级任务列表 + 抽屉(查驳回原因 / 源文件,可重新处理)。<br>
|
||||
<i>②</i> <b>OT 编号仅页面首列展示,导出 Excel 严格按标准 12 字段</b>(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价),OT 只作查询参数不落列。<br>
|
||||
<i>③</i> 已用数量 / open qty 暂留空待接入数据源;默认映射:约定出货日期→required_date、订单单号→source_order_number、单价→unit_price。<br>
|
||||
<i>④</i> 后端新增:明细行级查询(跨 OT 分页/筛选)+ 多 OT 合并导出生成器(复用模板映射引擎);子视图计数并入 count 聚合接口。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,120 @@
|
||||
# 订单队列图标语义重映射 + 门禁阻塞标志 设计文档
|
||||
|
||||
- 日期:2026-09-16
|
||||
- 分支:hugo-shipping-notice
|
||||
- 状态:待评审
|
||||
|
||||
## 1. 背景与问题
|
||||
|
||||
订单生命周期工作台左侧"本批订单队列"(`ReviewDocumentNavigation.vue`)的行内状态图标存在语义错位:
|
||||
|
||||
1. **绿勾被中间态占用**:图标映射把 Case 状态 `confirmed`(已创建任务)、`ready`(可确认)判为 `done` 画绿勾,但它们分别处于"系统/RPA 进行中"和"等待人工确认",并非终态。用户看到"通知准备/货代上传 · 已创建任务"亮绿勾,误读为"该阶段已完成"。`ready`(可确认)明明等人操作却画绿勾,是第二个语义错误。
|
||||
2. **选中项图标被覆盖**:`navIconKind()` 首行"当前选中返回 `active`"使选中草稿单的 ⚠️ 被灰圈覆盖,图标不再如实反映状态(选中态已有蓝色边框+底色表达)。
|
||||
3. **"进行中"与"中性"不可区分**:`processing`/`reparse_pending`/`confirmed` 与 `non_order`/`superseded` 都渲染灰圈。
|
||||
4. **库存缺口阻塞在队列不可见**:`issue_count` 只统计草稿复核问题(`order_review_projection.py:1159`),通知准备阶段的库存缺口记录在 Process Gate(`blocked_manual` 等)上,队列序列化刻意不读阻断信息(`blocking_reason=None`,性能约束),队列无字段携带"被库存缺口卡住需人工"。
|
||||
|
||||
同页面顶部阶段条的视觉语言是 ✓=已完成、蓝点/转圈=进行中、🔒=阻塞;队列图标必须与之同义。
|
||||
|
||||
## 2. 目标 / 非目标
|
||||
|
||||
**目标**
|
||||
|
||||
- 队列行内图标收敛为行业通用的五态语义:需人工(黄⚠)/ 进行中(蓝转圈)/ 已完成(绿✓,仅终态)/ 失败(红✗)/ 中性(灰○)。
|
||||
- 选中项只靠行高亮表达,图标永远如实反映状态。
|
||||
- 后端队列 item 新增 `needs_attention` 标志,利用已批量预取的 Gate 缓存判定(零额外 SQL),使"库存缺口等门禁阻塞需人工"在队列可见。
|
||||
- 队列 `summary` 计数与新语义对齐(现状把 `confirmed`/`quality_issue` 计入 completed,与新图标矛盾;前端已核实无消费方,仅测试引用)。
|
||||
|
||||
**非目标**
|
||||
|
||||
- 不改 Gate/Execution 写路径、状态机与任何动作授权。
|
||||
- 不改队列接口既有字段语义(`issue_count`、`status`、`lifecycle_stage` 原样保留)。
|
||||
- 不新增 i18n 文案(图标为 aria-hidden 装饰元素,状态文字已有)。
|
||||
- 不改收起模式(数字轨)与窄屏抽屉(无图标)。
|
||||
|
||||
## 3. 设计原则
|
||||
|
||||
1. 一个图标只回答一个问题:"这单现在什么状态、要不要我处理"。
|
||||
2. 图标永远如实反映状态;选中态由行高亮(既有蓝色边框+底色)表达。
|
||||
3. 绿勾只属于终态;宁可少亮绿勾(用户多看一眼),不可错亮绿勾(漏单)。
|
||||
4. 同页面同一图形必须同义(与顶部阶段条对齐)。
|
||||
|
||||
## 4. 前端:图标映射重写
|
||||
|
||||
文件:`frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.vue`
|
||||
|
||||
`navIconKind()` 按以下优先级自上而下判定,命中即停。输入:`status`、`issue_count`、`needs_attention`、`lifecycle_stage`。
|
||||
|
||||
| 优先级 | 条件 | 图标 | 含义 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | `status` ∈ {`failed`, `error`} | 红 ✗(X) | 失败 |
|
||||
| 2 | `issue_count > 0` **或** `needs_attention === true` | 黄 ⚠️(TriangleAlert) | 需人工处理(草稿问题 / 门禁阻塞如库存缺口) |
|
||||
| 3 | 终态:`lifecycle_stage === 'upload_complete'` 或 `status` ∈ {`completed`, `closed`} | 绿 ✓(Check) | 整单完成(通知完成) |
|
||||
| 4 | 需人工状态:`status` ∈ {`draft`, `ready`, `unreviewed`, `quality_issue`, `pending_review`, `waiting_review`} | 黄 ⚠️(TriangleAlert) | 等人操作 |
|
||||
| 5 | 进行中:`status` ∈ {`confirmed`, `processing`, `reparse_pending`, `queued`, `confirming`} | 蓝 🔄(LoaderCircle + animate-spin) | 系统/RPA 在办 |
|
||||
| 6 | 中性:`status` ∈ {`non_order`, `cancelled`, `superseded`} | 灰 ○(Circle) | 不适用/已废弃 |
|
||||
| 7 | 兜底(含 `unknown`) | 蓝 🔄(LoaderCircle + animate-spin) | 未知按仍在流转处理 |
|
||||
|
||||
- 删除 `active` 返回值与选中优先分支;返回值联合类型收敛为 `'alert' | 'done' | 'failed' | 'processing' | 'idle'`。
|
||||
- `matchesStatusFilter()`:`processing` 过滤改判 `kind === 'processing'`(删 `|| kind === 'active'`)。
|
||||
- 模板 tabs 分支与 sidebar 分支的图标链各插入 `LoaderCircle`(`h-3.5 w-3.5` + `animate-spin` + `text-brand-600`,与 `ReviewLifecycleStageNavigation.vue:85` 顶部阶段条进行中样式一致);沿用既有重复写法,不抽子组件。
|
||||
- 视觉:⚠️ amber-500、✓ emerald-500、✗ rose-500、○ muted,全部不变。
|
||||
- 注释同步(AGENTS.md §5.3):`navIconKind` docstring 写明优先级链与"绿勾=终态"约束;`lifecycle_stage` 字段注释更新为"用于阶段文字展示与终态(upload_complete)绿勾判定,不参与阶段裁决";`ReviewDocumentNavItem` 类型新增 `needs_attention?: boolean | null` 并注明来源为队列接口。
|
||||
- 类型:`frontend/src/features/chat/types/shipping.api.types.ts` 的 `ShippingOrderReviewCaseSummary` 新增 `needs_attention?: boolean`(后端可选下发,缺省视为 false)。
|
||||
|
||||
对照截图的可见变化:6 个"通知准备/货代上传 · 已创建任务"绿勾 → 蓝转圈;"可确认"绿勾 → 黄⚠;仅"通知完成"终态亮绿勾。
|
||||
|
||||
## 5. 后端:needs_attention 标志
|
||||
|
||||
文件:`backend/app/services/shipping_notice/order_review_projection.py`
|
||||
|
||||
1. **现状复用**:`_load_review_case_summary_batch` 已批量预取 `executions_by_case_id` / `gates_by_execution_id` 并写入会话缓存(`:1333-1355`、`:1213-1215`),`_queue_current_gate_hint` 已从中取当前 Gate 码。本改动不新增任何 SQL。
|
||||
2. **当前 Gate 判定**:优先 `execution.current_gate_code` 对应 Gate;缺失时按 `sequence_no` 取第一个状态 ∈ {`pending`, `queued`, `running`, `blocked_retryable`, `blocked_manual`, `waiting_external`, `failed_terminal`} 的 Gate(在 `_queue_current_gate_hint` 活跃口径上补 `queued` 与 `failed_terminal`,避免终态失败的单被漏判)。
|
||||
3. **`needs_attention` 裁决**:当前 Gate `status` ∈ {`blocked_manual`, `blocked_retryable`, `failed_terminal`} → `true`;无 Execution / 无活跃 Gate → `false`。`waiting_external`(RPA 外部等待)、`running`/`pending`/`queued` 视为在办,不算需人工。
|
||||
4. **输出**:`_serialize_review_case_summary` 返回 dict 新增 `'needs_attention': bool`;`serialize_review_run` 与 `serialize_review_queue` 两个队列数据源自动携带(共用同一序列化函数)。仅对 `case.confirmed_task_id` 存在的 Case 有意义,但字段恒输出(布尔,不缺键)。
|
||||
5. **docstring**:函数注释写明裁决口径与"禁止前端自行推断阻塞"的约束。
|
||||
|
||||
## 6. 后端:summary 计数对齐
|
||||
|
||||
`serialize_review_queue` 的 counts(`order_review_projection.py:1447-1452`)重算,与 item 口径一致:
|
||||
|
||||
- `needs_action`:`status` ∈ {`unreviewed`, `draft`, `ready`, `quality_issue`} 或 `needs_attention` 为真。
|
||||
- `completed`:终态——`status` ∈ {`non_order`, `closed`, `completed`} 或 `lifecycle_stage === 'upload_complete'`。
|
||||
- `processing`:其余(`confirmed`/`confirming`/`reparse_pending` 等进行中)。
|
||||
|
||||
依据:前端已核实无任何组件消费 `queue.summary` 的三个计数(仅 `items` 与 `total` 语义被使用),后端仅 `backend/tests/test_shipping_order_review_service.py` 引用,风险可控。若不改,summary 的 completed 会与 item 的 needs_attention 图标互相矛盾,成为下一个"为什么"。
|
||||
|
||||
注意:summary 三个桶是"队列处置去向"粗粒度归类,与五态图标不是一一映射(如 `non_order` 计入 completed,但图标为中性别灰 ○);桶口径只需与"要不要再看这单"一致,不要求与图形一致。
|
||||
|
||||
## 7. 已知边界(明示,非缺陷)
|
||||
|
||||
- **阶段偏早(fail-safe)**:队列 `lifecycle_stage` 是轻量投影,极端场景(OT.stage 脏值且 Gate 缓存缺失)会兜回 `intake_parse`(`order_review_projection.py:1105`、`:1133`);异步回调成功但 OT.stage 未落库的瞬间也会短暂偏早。方向安全:完成单不亮绿勾只亮转圈,用户多看一眼;反向(未完成亮绿勾)不可能——`upload_complete` 仅由已持久化 `OT.stage == 'completed'` 驱动,队列不采信异步回执(`lifecycle_projection.py:138-146`)。
|
||||
- **`ready` 归黄⚠ 的口径变化**:`ready`(可确认)从绿勾改为黄⚠。若产品上希望"可确认"用独立图标(如待办蓝框),另行迭代,本版不引入第六种图形。
|
||||
|
||||
## 8. 测试计划
|
||||
|
||||
**后端**(`backend/tests/test_shipping_order_review_service.py`)
|
||||
|
||||
- `confirmed` Case + 当前 Gate `blocked_manual`(库存缺口场景)→ item `needs_attention=true`,summary `needs_action` 含该单。
|
||||
- 当前 Gate `waiting_external` → `needs_attention=false`。
|
||||
- 无 Execution 的 `confirmed` Case → `needs_attention=false`。
|
||||
- summary 计数:`quality_issue` 归 needs_action、`confirmed` 归 processing、`upload_complete` 归 completed。
|
||||
- 关键断言按 `docs/test_plan_matrix.md` §1 附意图注释。
|
||||
|
||||
**前端**(`frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`)
|
||||
|
||||
- 映射表逐行:`confirmed`→转圈、`ready`→⚠、`draft`→⚠、`upload_complete`→✓、`failed`→✗、`non_order`→○、`needs_attention=true`+`confirmed`→⚠。
|
||||
- 选中项:选中 `draft` 单,图标仍为 ⚠(行高亮独立表达选中)。
|
||||
- `needs_attention` 缺省(旧后端响应)→ 按 false 处理,不报错。
|
||||
|
||||
**构建**:`cd frontend && npm run build` 必须通过;后端跑相关 pytest 文件。
|
||||
|
||||
## 9. 文档同步(与代码同一提交/PR)
|
||||
|
||||
- `docs/features/shipping-notice/technical.md`:队列投影小节补 `needs_attention` 字段与五态图标口径。
|
||||
- `docs/funclist.md`:涉及的功能条目措辞同步(如已有队列状态展示条目)。
|
||||
|
||||
## 10. 改动量与风险
|
||||
|
||||
- 后端 1 个文件(+辅助函数、+字段、+计数重算)+ 1 个测试文件;无迁移、无新依赖、无接口破坏性变更(纯增量字段)。
|
||||
- 前端 2 个文件(组件 + 类型)+ 1 个测试文件。
|
||||
- 主要风险:summary 计数语义变化(已核实无前端消费方);图标语义变化对用户习惯的影响(正是本次目的)。
|
||||
@@ -0,0 +1,146 @@
|
||||
# 设计:货代发货批次进度中心优先(对话视图退役)+ 会话业务命名
|
||||
|
||||
日期:2026-09-17 分支:`hugo-shipping-notice`
|
||||
状态:已与需求方确认方向(方案 A + 命名仅新建会话时生效),待评审
|
||||
|
||||
## 1. 背景与问题
|
||||
|
||||
货代发货智能体(shipping notice)当前提交附件后的体验链路为:
|
||||
|
||||
1. 对话流出现「本次订单文件处理」摘要卡(`ShippingOrderExtractionCard`);
|
||||
2. 用户手动点击卡上「打开批次进度中心」→ 右侧渲染 `ShippingWorkflowTimeline`,
|
||||
左侧对话列压缩为 `clamp(360px, 32vw, 520px)` 但仍可见。
|
||||
|
||||
问题:
|
||||
|
||||
- 批次信息在对话流与批次进度中心**重复展示两遍**,用户不需要对话视图;
|
||||
- 侧栏历史会话名全部写死为「订单抽取」(`order_extraction_run_service.py` 新建
|
||||
`ChatSession` 时 `title='订单抽取'`),多条批次完全无法区分;
|
||||
- 全站没有会话改名入口。
|
||||
|
||||
## 2. 已确认的设计决策(需求方拍板)
|
||||
|
||||
| 决策点 | 结论 |
|
||||
| --- | --- |
|
||||
| 批次中心打开期间对话窗口 | 整体隐藏,中心占满主区域 |
|
||||
| 中心是否可关闭 | 不提供关闭;打开后常驻 |
|
||||
| 自动打开触发范围 | 每次提交后中心即呈现;因不可关闭,实际等价于「有会话即中心」 |
|
||||
| 历史会话回访 | 直接进入该会话的批次进度中心,不展示消息流 |
|
||||
| 同批次追加附件 | 中心不提供上传入口;新文件走「新建对话」重新提交 |
|
||||
| 会话命名 | 规则化业务命名(PO/主题 + 文件数 + 日期),**仅新建会话时生效**;存量「订单抽取」不处理、不做手动改名(如后续有需要另起设计) |
|
||||
|
||||
## 3. 方案 A:对话视图退役(前端)
|
||||
|
||||
### 3.1 目标规则
|
||||
|
||||
货代智能体主区域显示逻辑坍缩为一条:
|
||||
|
||||
```
|
||||
isShippingNoticeAgent && activeShippingConversationId 非空 → 全屏渲染批次进度中心
|
||||
否则(新会话欢迎页) → 欢迎页 + 输入框(唯一提交入口)
|
||||
```
|
||||
|
||||
- `ChatViewContent.vue`:删除 `batchWorkbenchOpen` / `openBatchWorkbench` /
|
||||
`closeBatchWorkbench` / `compactShippingProgress` 状态与函数;
|
||||
`showShippingWorkflowTimeline` 改为上式的纯计算属性;删除
|
||||
`@open-batch-workbench` 监听与「切换会话/Agent 关闭工作台」的 watcher;
|
||||
删除 `<style>` 中 `.shipping-workbench-layout` / `.shipping-chat-column`
|
||||
压缩列样式(中心 `flex-1` 天然占满)。
|
||||
- `ShippingWorkflowTimeline.vue`:移除标题栏 × 关闭按钮与 `close` 事件
|
||||
(`ChatViewContent` 不再监听)。
|
||||
- `ChatMessageList.vue` / `ChatMessageBubble.vue`:移除 `compact-shipping-progress`
|
||||
prop 透传链与 `open-batch-workbench` emit 链。
|
||||
- 提交链路不变:`startRun` 成功 → `onConversationResolved` 写回路由
|
||||
`conversation_id` → 中心自动出现;中间的「本次订单文件处理」对话卡态不再可见。
|
||||
|
||||
### 3.2 保留与删除边界
|
||||
|
||||
- **保留**:`ShippingOrderExtractionCard` 及货代消息渲染链(含
|
||||
`shipping-match-result` 等历史类型)原样保留、不再可达。理由:本地消息仍照常
|
||||
落库(`saveLocalMessageToBackend`),数据完整性不受影响;渲染链保留为兜底与
|
||||
可回滚点,不在本次范围内做大段删除。后续若中心优先稳定,可另起清理任务。
|
||||
- **保留**:输入框与上传链路(欢迎页提交的唯一入口);`order-review` 复核工作台
|
||||
路由模式(`mode=order-review`)不受影响,仍由中心阶段动作导航进入。
|
||||
- **删除**:仅「打开批次进度中心」按钮及上述状态机/样式/emit 链。
|
||||
|
||||
### 3.3 已知边界(接受)
|
||||
|
||||
- 货代智能体里直接发送纯文本:回复不再有展示区。按「运营工具而非聊天」定位接受;
|
||||
输入框行为不变(仍可发送,数据照常保存)。
|
||||
- 移动端与桌面端同样适用「有会话即中心」;原压缩列样式仅桌面生效,删除后无回归面。
|
||||
|
||||
## 4. 会话业务命名(后端,仅新建会话)
|
||||
|
||||
### 4.1 规则化命名
|
||||
|
||||
新模块 `backend/app/services/shipping_notice/conversation_title.py`,纯函数:
|
||||
|
||||
```python
|
||||
derive_order_extraction_title(filenames: list[str], created_at: datetime) -> str
|
||||
```
|
||||
|
||||
规则(按序):
|
||||
|
||||
1. 取首个文件名(EML 或 direct_pdf 资产文件名),去扩展名;
|
||||
2. 去邮件前缀:`Re:` `Fw:` `Fwd:` `回复:` `转发:`(循环剥离,大小写不敏感);
|
||||
3. 截断至 24 字符(字符安全截断);
|
||||
4. 文件数 > 1 时追加 `等 N 个文件`;
|
||||
5. 追加 ` MM-DD`(提交日,服务器 UTC 不换算,直接取 `created_at`)消歧;
|
||||
6. 文件名全空时回退 `订单抽取`;总长钳制 ≤ 60 字符。
|
||||
|
||||
落点:`_resolve_conversation` **新建** `ChatSession` 时以本次冻结 intakes 的资产
|
||||
文件名推导 `title`(intakes 在事务内已在手,不产生额外查询)。已存在的会话一律
|
||||
不改动标题(含标题仍为「订单抽取」的存量会话)。标题是内容派生文本而非 UI 文案,
|
||||
与现状写死中文标题一致,不进 i18n。
|
||||
|
||||
### 4.2 批次中心头部复用
|
||||
|
||||
`ShippingWorkflowTimeline` 新增 `conversationTitle` prop,由 `ChatViewContent`
|
||||
从 `page.displayHistory` 按 `conversation_id` 匹配取 `title` 传入,不新增接口;
|
||||
标题为空时维持现有占位。
|
||||
|
||||
## 5. 非目标
|
||||
|
||||
- 不删除 `ShippingOrderExtractionCard` 及货代消息渲染链(见 3.2);
|
||||
- 不做惰性回填:存量「订单抽取」标题不处理、不更新(含追加提交场景);
|
||||
- 不做会话手动改名(改名 API 与侧栏改名入口均不做);
|
||||
- 不做 LLM 标题生成;不引入新依赖;
|
||||
- 无数据库结构变更、无 Alembic 迁移、无环境变量变更;
|
||||
- 不改动提交/抽取/投影后端链路(仅 `_resolve_conversation` 新建会话标题);
|
||||
- 我的待办页(`/workspace/shipping-notice/my-tasks`)改版另行推进,不在本设计内。
|
||||
|
||||
## 6. 测试策略
|
||||
|
||||
后端(pytest):
|
||||
|
||||
- `conversation_title` 纯函数:前缀剥离、截断、N>1 后缀、日期、空回退、长度钳制;
|
||||
- `_resolve_conversation`:新建会话标题派生;已存在会话标题一律不变(含
|
||||
「订单抽取」存量)。
|
||||
|
||||
前端(vitest,新建/扩展现有 spec 文件):
|
||||
|
||||
- `ChatViewContent`:货代 + 有 conversationId → 渲染中心;无 → 欢迎页;普通智能体
|
||||
不受影响;
|
||||
- `ShippingWorkflowTimeline`:无关闭按钮;头部批次名展示;
|
||||
- 更新受影响断言:`ShippingOrderExtractionCard.spec.ts`(移除
|
||||
`open-batch-workbench` 按钮用例)、涉及 `compact-shipping-progress` 的用例。
|
||||
|
||||
构建门禁:`cd frontend && npm run build` 通过;后端相关 pytest 绿。
|
||||
|
||||
## 7. 文档同步(与代码同一提交/PR)
|
||||
|
||||
- `docs/funclist.md`:货代发货下新增「批次进度中心为会话主界面」「新建批次会话
|
||||
按附件内容自动命名」条目,调整原「打开批次进度中心」描述;
|
||||
- `docs/features/shipping-notice/technical.md`:更新交互链路章节(提交 → 中心)、
|
||||
会话标题推导规则;
|
||||
- i18n:无新增文案(本次仅删除「打开批次进度中心」入口,无新 UI 文本;遗留
|
||||
unused key 清理交由后续清理任务)。
|
||||
|
||||
## 8. 验收标准
|
||||
|
||||
1. 货代智能体新会话发送附件 → 提交成功后主区域直接全屏显示批次进度中心,
|
||||
全程不出现「本次订单文件处理」对话卡;中心无关闭按钮;
|
||||
2. 侧栏点开历史「批次」会话 → 直接进入该会话的中心;
|
||||
3. 新提交创建的批次会话名形如 `PO#6075309 for Vendor#10804 等 11 个文件 09-15`,
|
||||
同日多批次可区分;存量会话名保持原样;
|
||||
4. 普通智能体(通用入口等)聊天体验零变化;`npm run build` 与相关测试全绿。
|
||||
@@ -66,7 +66,7 @@ export const workspaceRoutes: RouteRecordRaw[] = [
|
||||
path: 'shipping-notice/customers',
|
||||
name: 'workspace-shipping-customers',
|
||||
component: () => import('@/features/shipping-notice/customers/ShippingCustomersPage.vue'),
|
||||
meta: { title: '货代客户主数据', requiresAdmin: true },
|
||||
meta: { title: '货代客户数据', requiresAdmin: true },
|
||||
},
|
||||
{
|
||||
path: 'shipping-notice/my-tasks',
|
||||
|
||||
@@ -166,6 +166,16 @@ export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
|
||||
{ priority: 'low' },
|
||||
);
|
||||
|
||||
/** 整单 ODM 裁决:保存行级选择(同快照文件行后端同步),随后可重试生成 Excel。 */
|
||||
export const setWorkspaceShippingTaskOdmChoice = (
|
||||
taskNo: string,
|
||||
payload: { snapshot_line_id: string | number; odm_id: string },
|
||||
) =>
|
||||
requestJson<{ task_id: number; odm_id: string; synced_line_count: number; odm_values: string[] }>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/odm-choice`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/**
|
||||
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
|
||||
*/
|
||||
|
||||
@@ -54,7 +54,6 @@ const {
|
||||
pinMessagesToBottom?: boolean;
|
||||
/** 供父级滚动逻辑绑定 main 元素 */
|
||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||
compactShippingProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -68,7 +67,6 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
/** 在途仓自动调拨:业务流激活时向上冒泡,父级据此隐藏聊天输入框。 */
|
||||
'transfer-flow-active': [active: boolean];
|
||||
}>();
|
||||
@@ -207,7 +205,6 @@ const hasFollowingShippingProgressCard = (items: ChatMessage[], index: number):
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
:training-handlers="trainingHandlers"
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
:attachment-summary-only="hasFollowingShippingProgressCard(messages, index)"
|
||||
@copy="emit('copy', { message: msg, index })"
|
||||
@edit="emit('edit', $event)"
|
||||
@@ -217,7 +214,6 @@ const hasFollowingShippingProgressCard = (items: ChatMessage[], index: number):
|
||||
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
|
||||
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
|
||||
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
|
||||
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
|
||||
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、立账凭证 Agent 用 Tab 作业面替换消息列表与输入框。
|
||||
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、立账凭证 Agent 用 Tab 作业面替换消息列表与输入框;
|
||||
* 货代会话主区域:有会话即全屏批次进度中心(常驻),无会话为欢迎页+输入框,会话标题取自侧栏历史并传给中心。
|
||||
|
||||
*/
|
||||
|
||||
@@ -34,6 +35,8 @@ import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
|
||||
import ShippingWorkflowTimeline from '@/features/chat/components/shipping/ShippingWorkflowTimeline.vue';
|
||||
|
||||
import { shouldShowShippingWorkbench } from '@/features/chat/shipping/shippingWorkbenchLayout';
|
||||
|
||||
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
|
||||
|
||||
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
|
||||
@@ -135,38 +138,19 @@ const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value ||
|
||||
const transferFlowActive = ref(false);
|
||||
watch(isInTransitTransferAgent, (isTransfer) => { if (!isTransfer) transferFlowActive.value = false; });
|
||||
|
||||
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
|
||||
const batchWorkbenchOpen = ref(false);
|
||||
|
||||
|
||||
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& batchWorkbenchOpen.value
|
||||
&& Boolean(activeShippingConversationId.value)
|
||||
));
|
||||
|
||||
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
|
||||
|
||||
function openBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = true;
|
||||
}
|
||||
|
||||
function closeBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批次中心只服务于用户主动打开时所在的会话。切换历史会话或 Agent 后必须关闭,
|
||||
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
|
||||
* 货代发货会话主区域规则(方案 A):
|
||||
* 有会话 ID → 全屏批次进度中心(常驻不可关闭);无会话 → 欢迎页 + 输入框(唯一提交入口)。
|
||||
*/
|
||||
watch(
|
||||
() => [activeShippingConversationId.value, Number(page.currentAgentId || 0)] as const,
|
||||
(next, previous) => {
|
||||
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
|
||||
batchWorkbenchOpen.value = false;
|
||||
},
|
||||
);
|
||||
const showShippingWorkflowTimeline = computed(() => shouldShowShippingWorkbench({
|
||||
isShippingNoticeAgent: page.isShippingNoticeAgent,
|
||||
conversationId: activeShippingConversationId.value,
|
||||
}));
|
||||
|
||||
/** 侧栏历史项中的会话标题;批次中心头部直接复用,保持侧栏与中心一致。 */
|
||||
const activeShippingConversationTitle = computed(() => (
|
||||
page.displayHistory.find((item) => item.conversation_id === activeShippingConversationId.value)?.title || ''
|
||||
));
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
|
||||
@@ -498,9 +482,10 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
<VoucherCheckChatPanel v-else-if="isVoucherCheckAgentPage" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1" :class="showShippingWorkflowTimeline ? 'shipping-workbench-layout' : ''">
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col" :class="showShippingWorkflowTimeline ? 'shipping-chat-column' : ''">
|
||||
<!-- 中心展示时对话列整体隐藏(含输入框),新文件提交走新建对话(spec 方案 A 硬性决策)。 -->
|
||||
<div v-show="!showShippingWorkflowTimeline" class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
|
||||
<TrainingWorkspacePanel
|
||||
|
||||
@@ -580,8 +565,6 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@edit="page.input = $event"
|
||||
@@ -602,8 +585,6 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
|
||||
|
||||
@open-batch-workbench="openBatchWorkbench"
|
||||
|
||||
@transfer-flow-active="transferFlowActive = $event"
|
||||
|
||||
/>
|
||||
@@ -692,10 +673,9 @@ watch(() => page.currentAgentId, () => {
|
||||
<ShippingWorkflowTimeline
|
||||
v-if="showShippingWorkflowTimeline"
|
||||
:conversation-id="activeShippingConversationId"
|
||||
:conversation-title="activeShippingConversationTitle"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingProcessing"
|
||||
|
||||
@close="closeBatchWorkbench"
|
||||
/>
|
||||
|
||||
|
||||
@@ -846,16 +826,3 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/** 打开批次工作台后,左侧对话保留为压缩入口,右侧取得主工作区宽度。 */
|
||||
@media (min-width: 1024px) {
|
||||
.shipping-workbench-layout {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.shipping-chat-column {
|
||||
flex: 0 0 clamp(360px, 32vw, 520px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -75,7 +75,6 @@ const {
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMessageHandlers;
|
||||
trainingHandlers: TrainingHandlers;
|
||||
compactShippingProgress?: boolean;
|
||||
/** 下方已有货代进度卡时,用户气泡附件只显示摘要。 */
|
||||
attachmentSummaryOnly?: boolean;
|
||||
}>();
|
||||
@@ -89,7 +88,6 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const authStore = useAuthStore();
|
||||
@@ -747,11 +745,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:retrying="retryingOrderExtraction"
|
||||
:refreshing="refreshingOrderExtraction"
|
||||
:cancelling="cancellingOrderExtraction"
|
||||
:compact-progress="compactShippingProgress"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@refresh="refreshShippingOrderExtraction"
|
||||
@cancel="cancelShippingOrderExtraction"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
|
||||
+54
@@ -22,6 +22,7 @@ const i18n = createI18n({
|
||||
actionCodes: {
|
||||
reload_inventory_result: '重新读取库存结果',
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
confirm_customer: '确认客户',
|
||||
},
|
||||
inventoryActions: {
|
||||
reloadInventoryResult: '重新读取库存结果',
|
||||
@@ -337,4 +338,57 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
// 关键断言:无 statusDetail 时说明行完全不渲染,不留空壳。
|
||||
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders the suggested next action instead of the reason text when next_action is present', () => {
|
||||
// v4 语义分离:「下一步」给建议动作(确认客户),原因文案(客户尚未确认)
|
||||
// 属于阻塞原因位,不得再挤进下一步槽位。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: {
|
||||
code: 'customer_unresolved',
|
||||
message: '客户尚未确认',
|
||||
nextAction: 'confirm_customer',
|
||||
} as any,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('确认客户');
|
||||
});
|
||||
|
||||
it('hides the generic run-level status detail when a specific blocking reason is shown', () => {
|
||||
// v4 去重:具体阻断原因已由「下一步」承载时,泛化的「当前步骤需要人工处理」属纯重复。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: {
|
||||
code: 'customer_unresolved',
|
||||
message: '客户尚未确认',
|
||||
nextAction: 'confirm_customer',
|
||||
} as any,
|
||||
statusDetail: { text: '当前步骤需要人工处理' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the run-level status detail when the blocking reason is generic', () => {
|
||||
// 无具体原因(未知码、无契约文案)时,Run 级等待说明仍是唯一信息,必须保留。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: { code: 'internal_gate_reason' } as any,
|
||||
statusDetail: { text: '当前步骤需要人工处理' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-status-detail"]').text()).toBe('当前步骤需要人工处理');
|
||||
});
|
||||
});
|
||||
+27
-6
@@ -10,7 +10,9 @@
|
||||
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
|
||||
loading 仅在挂载期抑制可执行动作,等权威投影到达后再放行(fail-closed);
|
||||
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载;
|
||||
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2)。
|
||||
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2);
|
||||
v4 语义分离:下一步优先消费 blocking_reason.next_action 的建议动作文案,
|
||||
且具体阻断原因在场时隐藏泛化 statusDetail(防同卡三行「待人工」空话)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -20,7 +22,10 @@ import type {
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingPrimaryAction,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import {
|
||||
isGenericBlockingReason,
|
||||
resolveShippingProcessingStageLabel,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
|
||||
import { lookupWorkbenchAction, shouldRenderWorkbenchAction } from '@/features/shipping-progress/workbenchActionRegistry';
|
||||
import { inventoryActionLabelKey, isInternalInventoryAction } from '@/features/shipping-progress/actionPresentation';
|
||||
@@ -147,9 +152,15 @@ const nextStepText = computed(() => {
|
||||
// 其余按 user_status/blocking_reason 照常渲染,空态自然落在「状态待确认」,不做骨架二次刷新。
|
||||
const automationMessage = props.loading ? safeMessage(props.automation?.message) : '';
|
||||
if (automationMessage) return automationMessage;
|
||||
// 1) blocking_reason → 用后端给的 i18n_key 渲染具体阻断
|
||||
// 1) blocking_reason → 先给契约注册的「建议动作」(下一步=做什么),
|
||||
// 再回退原因文案(i18n_key / Gate 命名空间);禁止裸露内部原因码。
|
||||
const br = props.blockingReason;
|
||||
if (br) {
|
||||
const nextAction = String(br.nextAction || br.next_action || '').trim();
|
||||
const actionKey = nextAction
|
||||
? `workspace.shippingNotice.processGate.actionCodes.${nextAction}`
|
||||
: '';
|
||||
if (actionKey && te(actionKey)) return t(actionKey);
|
||||
const i18nKey = String(br.i18nKey || '').trim();
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
@@ -205,6 +216,15 @@ const showNextStep = computed(() => {
|
||||
return !['completed', 'cancelled'].includes(status);
|
||||
});
|
||||
|
||||
/**
|
||||
* 状态块内嵌动态说明的显隐:具体阻断原因已由「下一步」承载时,
|
||||
* Run 级泛化等待说明(如「当前步骤需要人工处理」)属纯重复,隐藏。
|
||||
*/
|
||||
const showStatusDetail = computed(() => {
|
||||
if (!props.statusDetail?.text) return false;
|
||||
return isGenericBlockingReason(props.blockingReason, te);
|
||||
});
|
||||
|
||||
/**
|
||||
* 判断当前工作台是否应隐藏后端下发的纯导航动作。
|
||||
* 批次中心可用它打开工作台;进入工作台后必须复用注册表规则,避免当前阶段再次显示
|
||||
@@ -382,13 +402,14 @@ type ReviewCurrentUserStatus =
|
||||
/>
|
||||
{{ statusLabel }}
|
||||
</dd>
|
||||
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;显隐裁决在视图侧)。 -->
|
||||
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;
|
||||
v4:blocking_reason 已含具体原因时隐藏,避免与「下一步」重复)。 -->
|
||||
<p
|
||||
v-if="statusDetail?.text"
|
||||
v-if="showStatusDetail"
|
||||
class="w-full text-[11px] leading-4 text-muted"
|
||||
data-testid="review-current-task-status-detail"
|
||||
aria-live="polite"
|
||||
>{{ statusDetail.text }}</p>
|
||||
>{{ statusDetail?.text }}</p>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
|
||||
+61
@@ -173,3 +173,64 @@ describe('ReviewDocumentNavigation', () => {
|
||||
narrow.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ReviewDocumentNavigation queue row status icons', () => {
|
||||
/**
|
||||
* 以指定字段挂载单行侧栏队列,返回该行按钮包装器。
|
||||
*/
|
||||
function mountRow(item: Partial<ReviewDocumentNavItem>) {
|
||||
return mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: [{ case_no: 'C-1', file_name: 'f1.pdf', status: 'draft', ...item }],
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: 'sidebar',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
}).get('[data-testid="review-doc-nav-C-1"]');
|
||||
}
|
||||
|
||||
it('renders confirmed cases as in-progress spinner instead of done check', () => {
|
||||
const row = mountRow({ status: 'confirmed' });
|
||||
// 关键断言:已创建任务是系统在办中间态,必须转圈而非绿勾。
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(true);
|
||||
expect(row.find('svg.text-emerald-500').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders ready-to-confirm cases as amber attention icon', () => {
|
||||
const row = mountRow({ status: 'ready' });
|
||||
// 关键断言:可确认是等人操作,属于待办而非完成。
|
||||
expect(row.find('svg.text-amber-500').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders backend gate-blocked cases as amber attention icon', () => {
|
||||
const row = mountRow({ status: 'confirmed', needs_attention: true });
|
||||
// 关键断言:needs_attention 是后端门禁裁决,优先于中间态转圈。
|
||||
expect(row.find('svg.text-amber-500').exists()).toBe(true);
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('reserves the green check for terminal upload_complete', () => {
|
||||
const row = mountRow({ status: 'confirmed', lifecycle_stage: 'upload_complete' });
|
||||
expect(row.find('svg.text-emerald-500').exists()).toBe(true);
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders failed and neutral states as before', () => {
|
||||
expect(mountRow({ status: 'failed' }).find('svg.text-rose-500').exists()).toBe(true);
|
||||
const idle = mountRow({ status: 'non_order' });
|
||||
expect(idle.find('svg.text-muted').exists()).toBe(true);
|
||||
expect(idle.find('svg.animate-spin').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the truthful state icon on the selected row', () => {
|
||||
const row = mountRow({ status: 'draft' });
|
||||
// 关键断言:选中态由行高亮表达,图标不再被 active 覆盖成灰圈。
|
||||
expect(row.find('svg.text-amber-500').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('treats missing needs_attention as false for old queue payloads', () => {
|
||||
const row = mountRow({ status: 'confirmed', needs_attention: undefined });
|
||||
expect(row.find('svg.animate-spin').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
+25
-10
@@ -11,6 +11,7 @@ import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Circle,
|
||||
LoaderCircle,
|
||||
Search,
|
||||
TriangleAlert,
|
||||
X,
|
||||
@@ -23,10 +24,12 @@ export type ReviewDocumentNavItem = {
|
||||
file_name?: string | null;
|
||||
status: string;
|
||||
issue_count?: number;
|
||||
/** 队列接口按当前门禁裁决的"需人工"标志(blocked_manual/blocked_retryable/failed_terminal);前端禁止自行推断阻塞。 */
|
||||
needs_attention?: boolean | null;
|
||||
po_number?: string | null;
|
||||
customer_name?: string | null;
|
||||
stage_label?: string | null;
|
||||
/** 队列接口下发的生命周期码;仅用于本地化展示,不参与阶段裁决。 */
|
||||
/** 队列接口下发的生命周期码;用于阶段文字展示与终态(upload_complete)绿勾判定,不参与阶段裁决。 */
|
||||
lifecycle_stage?: ReviewLifecycleStageCode | null;
|
||||
};
|
||||
|
||||
@@ -118,17 +121,20 @@ function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
|
||||
}
|
||||
|
||||
/**
|
||||
* 导航状态图标语义。
|
||||
* 队列状态图标语义,按优先级命中即停:
|
||||
* 失败 → 需人工(草稿问题数 / needs_attention 门禁阻塞)→ 终态绿勾
|
||||
* → 等人状态 ⚠ → 系统在办转圈 → 中性灰圈 → 兜底转圈。
|
||||
* 绿勾只属于终态(upload_complete / closed / completed);选中态由行高亮表达,
|
||||
* 本函数不感知选中,图标永远如实反映状态。
|
||||
*/
|
||||
function navIconKind(item: ReviewDocumentNavItem): 'active' | 'alert' | 'processing' | 'done' | 'failed' | 'idle' {
|
||||
if (props.activeCaseNo === item.case_no) return 'active';
|
||||
function navIconKind(item: ReviewDocumentNavItem): 'alert' | 'done' | 'failed' | 'processing' | 'idle' {
|
||||
const status = String(item.status || '').toLowerCase();
|
||||
if (item.issue_count && item.issue_count > 0) return 'alert';
|
||||
if (status === 'failed' || status === 'error') return 'failed';
|
||||
if (status === 'confirmed' || status === 'completed' || status === 'ready' || status === 'closed') return 'done';
|
||||
if (status === 'processing' || status === 'reparse_pending' || status === 'queued') return 'processing';
|
||||
if (status === 'non_order' || status === 'cancelled' || status === 'superseded') return 'idle';
|
||||
if (status === 'draft' || status === 'pending_review' || status === 'waiting_review') return 'alert';
|
||||
if ((item.issue_count && item.issue_count > 0) || item.needs_attention === true) return 'alert';
|
||||
if (item.lifecycle_stage === 'upload_complete' || status === 'completed' || status === 'closed') return 'done';
|
||||
if (['draft', 'ready', 'unreviewed', 'quality_issue', 'pending_review', 'waiting_review'].includes(status)) return 'alert';
|
||||
if (['confirmed', 'confirming', 'processing', 'reparse_pending', 'queued'].includes(status)) return 'processing';
|
||||
if (['non_order', 'cancelled', 'superseded'].includes(status)) return 'idle';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
@@ -139,7 +145,7 @@ function matchesStatusFilter(item: ReviewDocumentNavItem): boolean {
|
||||
if (statusFilter.value === 'all') return true;
|
||||
const kind = navIconKind(item);
|
||||
if (statusFilter.value === 'needs_action') return kind === 'alert';
|
||||
if (statusFilter.value === 'processing') return kind === 'processing' || kind === 'active';
|
||||
if (statusFilter.value === 'processing') return kind === 'processing';
|
||||
if (statusFilter.value === 'done') return kind === 'done';
|
||||
if (statusFilter.value === 'failed') return kind === 'failed';
|
||||
return true;
|
||||
@@ -218,6 +224,11 @@ function onSelect(caseNo: string) {
|
||||
class="h-3.5 w-3.5 shrink-0 text-rose-500"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<LoaderCircle
|
||||
v-else-if="navIconKind(item) === 'processing'"
|
||||
class="h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Circle
|
||||
v-else
|
||||
class="h-3 w-3 shrink-0 text-muted"
|
||||
@@ -329,6 +340,10 @@ function onSelect(caseNo: string) {
|
||||
v-else-if="navIconKind(item) === 'failed'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-rose-500"
|
||||
/>
|
||||
<LoaderCircle
|
||||
v-else-if="navIconKind(item) === 'processing'"
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
|
||||
/>
|
||||
<Circle
|
||||
v-else
|
||||
class="mt-0.5 h-3 w-3 shrink-0 text-muted"
|
||||
|
||||
+82
@@ -1184,4 +1184,86 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
|
||||
expect(row.findAll('button')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('shows a specific blocking reason once per waiting-human card without header duplication', async () => {
|
||||
// v4 去重:具体原因由文件行页脚独家承载;任务卡头不再重复同一句。
|
||||
// ui_state 挂在任务条目上(与后端 EML 聚合下发形态一致:任务级为代表子项原因)。
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'waiting_human', [{
|
||||
user_task_no: 'OT-REASON-ONCE', group: 'waiting_human', status_label: 'pending_review',
|
||||
file_count: 1, run_no: 'RUN-REASON-ONCE', can_append: false,
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'customer_unresolved', message: '客户尚未确认' },
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
objects: [{
|
||||
kind: 'document', object_key: 'DOC-REASON', label: 'reason.pdf', filename: 'reason.pdf',
|
||||
document_id: 91, root_document_id: 91, status_label: 'pending_review',
|
||||
}],
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-REASON-ONCE', {
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'reason.pdf', documentId: 91,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-REASON',
|
||||
},
|
||||
status: 'waiting_human',
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'customer_unresolved', message: '客户尚未确认' },
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [workItem], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:具体原因全文只出现一次,且带「阻塞原因:」前缀落在文件行页脚。
|
||||
const matches = wrapper.text().match(/客户尚未确认/g) || [];
|
||||
expect(matches.length).toBe(1);
|
||||
expect(wrapper.text()).toContain('阻塞原因:客户尚未确认');
|
||||
});
|
||||
|
||||
it('hides the blocker line when the backend only provides a generic fallback reason', async () => {
|
||||
// v4:未知原因码不得渲染成「当前步骤需要人工处理」空话;状态芯片已表达待人工。
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'waiting_human', [{
|
||||
user_task_no: 'OT-REASON-GENERIC', group: 'waiting_human', status_label: 'pending_review',
|
||||
file_count: 1, run_no: 'RUN-REASON-GENERIC', can_append: false,
|
||||
objects: [{
|
||||
kind: 'document', object_key: 'DOC-GENERIC', label: 'generic.pdf', filename: 'generic.pdf',
|
||||
document_id: 92, root_document_id: 92, status_label: 'pending_review',
|
||||
}],
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-REASON-GENERIC', {
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'generic.pdf', documentId: 92,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-GENERIC',
|
||||
},
|
||||
status: 'waiting_human',
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'mystery_internal_code' },
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [workItem], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.text()).not.toContain('阻塞原因');
|
||||
expect(wrapper.text()).not.toContain('当前步骤需要人工处理');
|
||||
});
|
||||
});
|
||||
+16
-7
@@ -30,8 +30,8 @@ import {
|
||||
toggleTaskDetails,
|
||||
} from '@/features/chat/shipping/conversationProcessingState';
|
||||
import {
|
||||
resolveBlockingReasonText,
|
||||
resolveShippingProcessingMessage,
|
||||
resolveShippingProcessingReasonLabel,
|
||||
resolveShippingProcessingStageLabel,
|
||||
resolveShippingProcessingStatusLabel,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
@@ -593,7 +593,8 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
|
||||
const reason = file.projection.uiState
|
||||
? file.projection.uiState.blocking_reason
|
||||
: file.projection.blockingReason;
|
||||
return resolveShippingProcessingReasonLabel(reason, te, t);
|
||||
// v4:具体原因才展示(Gate 命名空间/契约 message 可解析),通用兜底返回空串隐藏。
|
||||
return resolveBlockingReasonText(reason, te, t);
|
||||
}
|
||||
return taskReasonLabel(task);
|
||||
}
|
||||
@@ -686,12 +687,20 @@ function stageLabel(task: ConversationProcessingUserTask): string {
|
||||
return intakeStageLabel(projection);
|
||||
}
|
||||
|
||||
/** 展示后端 ui_state 已裁决的阻断原因;i18n 仅负责翻译,不映射或猜测业务原因。 */
|
||||
/** 展示后端 ui_state 已裁决的阻断原因;v4:具体原因才展示,通用兜底返回空串。 */
|
||||
function taskReasonLabel(task: ConversationProcessingUserTask): string {
|
||||
const reason = task.uiState
|
||||
? task.uiState.blocking_reason
|
||||
: task.blockingReason;
|
||||
return resolveShippingProcessingReasonLabel(reason, te, t);
|
||||
return resolveBlockingReasonText(reason, te, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务卡头原因行显隐:workbench 模式下文件行页脚已逐文件承载原因,
|
||||
* 卡头不再重复同一句;非 workbench(折叠聚合卡)仍由卡头独家展示。
|
||||
*/
|
||||
function taskHeaderReasonVisible(task: ConversationProcessingUserTask): boolean {
|
||||
return !props.workbenchMode || visibleWorkbenchFileRows(task).length === 0;
|
||||
}
|
||||
|
||||
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
|
||||
@@ -960,7 +969,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
|
||||
@@ -1056,7 +1065,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
|
||||
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
|
||||
</button>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
|
||||
@@ -1323,7 +1332,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-emerald-200/70 pt-2">
|
||||
|
||||
+12
-16
@@ -74,7 +74,8 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not present historical handling items or CTA as current work when the live projection exists', () => {
|
||||
@@ -115,16 +116,6 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('collapses file-level progress when the batch workbench is open', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-COMPACT', compactProgress: true },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-status-groups"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses unified EML aggregation and keeps candidate creation out of completed', async () => {
|
||||
const aggregate = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1',
|
||||
@@ -643,7 +634,8 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('3 个文件');
|
||||
expect(wrapper.text()).toContain('系统处理中');
|
||||
expect(wrapper.text()).toContain('处理时间偏长');
|
||||
expect(wrapper.text()).toContain('打开批次进度中心');
|
||||
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
|
||||
expect(wrapper.text()).not.toContain('打开批次进度中心');
|
||||
expect(wrapper.text()).not.toContain('刷新状态');
|
||||
expect(wrapper.text()).not.toContain('取消本次识别');
|
||||
expect(wrapper.text()).not.toContain('PO-450003.pdf');
|
||||
@@ -731,7 +723,8 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
});
|
||||
expect(wrapper.text()).toContain('订单候选已生成');
|
||||
expect(wrapper.text()).toContain('候选待人工确认 · 2 项');
|
||||
expect(wrapper.text()).toContain('打开批次进度中心');
|
||||
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
|
||||
expect(wrapper.text()).not.toContain('打开批次进度中心');
|
||||
expect(wrapper.text()).not.toContain('部分附件需人工处理');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
|
||||
});
|
||||
@@ -826,7 +819,8 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
});
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-view-details"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render multi-OT ChatProgressSummary list', () => {
|
||||
@@ -914,7 +908,8 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render the removed view details link', () => {
|
||||
@@ -956,7 +951,8 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('共 1 个文件');
|
||||
});
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:聊天主区「本次订单文件处理」摘要卡——标题、文件数+状态、一行 handling 摘要、唯一主 CTA、查看详情。
|
||||
* 用途:聊天主区「本次订单文件处理」摘要卡——标题、文件数+状态、一行 handling 摘要、无对话流 CTA(批次中心常驻,方案 A)。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、vue-router、vue-i18n。
|
||||
* 逻辑:对话区默认展示状态-EML 聚合;批次工作台打开后切换为紧凑摘要,长进度/Gate/刷新取消由工作台承接。
|
||||
* 逻辑:对话区默认展示状态-EML 聚合;无对话流 CTA(批次中心常驻,方案 A),长进度/Gate/刷新取消由工作台承接。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { AlertCircle, ArrowRight, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
|
||||
import { AlertCircle, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
|
||||
import type {
|
||||
ShippingOrderExtractionHandlingItemState,
|
||||
ShippingOrderExtractionFileState,
|
||||
@@ -44,15 +44,12 @@ const props = defineProps<{
|
||||
readonlyReason?: string | null;
|
||||
/** 可选统一投影;摘要卡不再渲染进度,仅保留 prop 兼容宿主。 */
|
||||
processingProjection?: ShippingProcessingProjection | null;
|
||||
/** 批次工作台打开时,左侧只保留摘要,避免与工作台重复展示文件明细。 */
|
||||
compactProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
refresh: [];
|
||||
cancel: [reason?: string];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -425,7 +422,6 @@ const hasAnyStatusGroupTask = computed(() => (
|
||||
*/
|
||||
const recognizingPlaceholderVisible = computed(() => (
|
||||
hasConversationStatusGroups.value
|
||||
&& !props.compactProgress
|
||||
&& !hasAnyStatusGroupTask.value
|
||||
&& (submittedFileCount.value ?? 0) > 0
|
||||
));
|
||||
@@ -850,7 +846,7 @@ async function onPrimaryChatAction() {
|
||||
<div v-if="handlingSummaryLine && !hasConversationStatusGroups" class="mt-1 text-sm text-secondary">{{ handlingSummaryLine }}</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasConversationStatusGroups && !compactProgress" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
|
||||
<div v-if="hasConversationStatusGroups" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
|
||||
<div v-if="recognizingPlaceholderVisible" class="flex items-center gap-2 rounded-lg border border-default bg-surface p-3 text-sm text-muted">
|
||||
<LoaderCircle class="h-4 w-4 animate-spin text-brand-500" />
|
||||
<span data-testid="shipping-order-extraction-recognizing-placeholder">{{ t('chat.shippingProcessing.recognizingAttachments') }}</span>
|
||||
@@ -899,7 +895,7 @@ async function onPrimaryChatAction() {
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
<div v-else-if="!compactProgress && emlAggregate" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
|
||||
<div v-else-if="emlAggregate" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
|
||||
<article class="overflow-hidden rounded-lg border border-default bg-surface shadow-sm">
|
||||
<div class="flex items-start gap-3 border-b border-default bg-surface-soft p-3 dark:bg-slate-950/30">
|
||||
<Mail class="mt-0.5 h-5 w-5 text-brand-500" />
|
||||
@@ -926,7 +922,7 @@ async function onPrimaryChatAction() {
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30">
|
||||
<div v-else class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30">
|
||||
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-default bg-surface shadow-sm">
|
||||
<div class="flex items-start gap-3 border-b border-default bg-surface-soft p-3 dark:bg-slate-950/30"><Mail class="mt-0.5 h-5 w-5 text-brand-500" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-brand-200 bg-brand-100/70 text-brand-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-muted">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
|
||||
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-default bg-surface-soft p-3 pl-4 dark:border-slate-700 dark:bg-slate-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-brand-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
|
||||
@@ -936,20 +932,6 @@ async function onPrimaryChatAction() {
|
||||
<div v-for="row in failedRows" :key="`failed-${row.unitId}`" class="rounded-lg border border-rose-200 bg-rose-50 p-3 dark:border-rose-800 dark:bg-rose-950/30"><div class="flex items-center justify-between text-rose-600"><span class="flex items-center gap-2 font-medium"><AlertCircle class="h-5 w-5" />{{ row.fileName }}</span><span class="rounded bg-rose-100 px-2 py-0.5 text-xs">{{ t('chat.shippingProcessing.batchException') }}</span></div><p class="mt-2 pl-7 text-sm">{{ row.explainability?.message || t('chat.shippingProcessing.batchManualVerify') }}</p></div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end border-t border-default bg-brand-50/60 p-3 dark:bg-brand-950/20">
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
v-if="!compactProgress && (hasConversationStatusGroups || String(props.runNo || '').trim())"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-brand-700"
|
||||
data-testid="shipping-order-extraction-open-batch-workbench"
|
||||
@click="emit('open-batch-workbench')"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.openBatchWorkbench') }}
|
||||
<ArrowRight class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="false" class="flex items-start gap-3">
|
||||
<CircleX class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
|
||||
@@ -104,10 +104,11 @@ function buildController(
|
||||
function mountTimeline(
|
||||
processing = processingProjection(),
|
||||
workItems: ShippingProcessingProjection[] = [],
|
||||
extraProps: Record<string, unknown> = {},
|
||||
) {
|
||||
return mount(ShippingWorkflowTimeline, {
|
||||
attachTo: document.body,
|
||||
props: { conversationId: 'conv-1', controller: buildController(processing, workItems) },
|
||||
props: { conversationId: 'conv-1', controller: buildController(processing, workItems), ...extraProps },
|
||||
global: { plugins: [i18n], stubs: { teleport: true } },
|
||||
});
|
||||
}
|
||||
@@ -124,6 +125,24 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
gateRecovery.submitPrimaryAction.mockClear();
|
||||
});
|
||||
|
||||
it('has no close button and reuses the conversation title in the header', () => {
|
||||
const wrapper = mountTimeline(processingProjection(), [], { conversationTitle: 'PO#6075309 09-15' });
|
||||
|
||||
// 中心常驻不可关闭(方案 A):关闭按钮必须消失。
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-close"]').exists()).toBe(false);
|
||||
|
||||
// 会话标题直接复用侧栏命名,保持两处一致。
|
||||
const titleNode = wrapper.find('[data-testid="shipping-workflow-conversation-title"]');
|
||||
expect(titleNode.exists()).toBe(true);
|
||||
expect(titleNode.text()).toContain('PO#6075309 09-15');
|
||||
});
|
||||
|
||||
it('omits the title node when no conversation title is provided', () => {
|
||||
const wrapper = mountTimeline(processingProjection(), []);
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-conversation-title"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('prefers backend five-stage lifecycle nodes and shows the authorized download toolbar in freight upload', async () => {
|
||||
const processing = processingProjection({
|
||||
lifecycle_nodes: [
|
||||
@@ -205,25 +224,6 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-9"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('labels a manually actionable batch as action needed instead of processing', async () => {
|
||||
const task = { ...processingProjection().processing[0], group: 'needs_action' };
|
||||
const processing = processingProjection({
|
||||
summary: { total_files: 1, processing_files: 0, completed_files: 0, waiting_human_files: 1, failed_files: 0 },
|
||||
needs_action: [task], processing: [],
|
||||
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection({
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
})]);
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:锁定表示仍有待办,不得与「处理中 0」形成视觉矛盾。
|
||||
expect(wrapper.get('[data-testid="shipping-workflow-panel-pinned"]').text()).toBe('待处理');
|
||||
});
|
||||
|
||||
it('navigates only through the backend lifecycle entry', async () => {
|
||||
const file = fileProjection({
|
||||
uiState: {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 用途:聊天页右侧「批次进度中心」——后端批次投影、五阶段进度和文件行操作。
|
||||
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
|
||||
* ReasonDialog、ProcessGateRecoveryCard。
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏保留批次名称、会话标题、加载与截断提示;中心常驻不可关闭(方案 A),
|
||||
* 文件总览和进度仅消费后端批次 summary;
|
||||
* 文件清单消费后端 conversation_processing.status_groups;work_items 仅用于定位同一
|
||||
* 展示 DTO 的操作对象;整批操作走 Run API,单文件取消走 Unit API;
|
||||
@@ -14,7 +14,7 @@
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ChevronDown, ChevronRight, Lock, RefreshCw } from 'lucide-vue-next';
|
||||
import { RefreshCw } from 'lucide-vue-next';
|
||||
import {
|
||||
downloadWorkspaceShippingExcelFile,
|
||||
downloadWorkspaceShippingExportArchive,
|
||||
@@ -59,10 +59,8 @@ const props = defineProps<{
|
||||
refreshTrigger?: number;
|
||||
/** 测试或父级注入时可直接传入控制器,跳过自建轮询。 */
|
||||
controller?: UseShippingNoticeWorkflowReturn | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
/** 当前会话标题;父级从侧栏历史匹配传入,中心头部直接复用(无新增接口)。 */
|
||||
conversationTitle?: string | null;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -91,11 +89,6 @@ const ctl = computed((): UseShippingNoticeWorkflowReturn => (
|
||||
props.controller || injected || localController
|
||||
));
|
||||
|
||||
/**
|
||||
* 侧栏折叠态:默认展开。
|
||||
* 有处理中/待处理/未查看完成任务时强制展开,仅允许收起文件详情。
|
||||
*/
|
||||
const collapsed = ref(false);
|
||||
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
|
||||
const focusTaskBanner = ref<string | null>(null);
|
||||
const actionBusyItemNo = ref<string | null>(null);
|
||||
@@ -249,34 +242,6 @@ const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
|
||||
const manualRefreshing = computed(() => Boolean(ctl.value.manualRefreshing?.value));
|
||||
const isRefreshing = computed(() => Boolean(ctl.value.isRefreshing?.value));
|
||||
const error = computed(() => ctl.value.error.value);
|
||||
/**
|
||||
* 右侧仍有用户必须持续可见的任务时,禁止收起整个处理面板。
|
||||
* 核心逻辑:处理中 / 待处理 / 未查看完成均属活跃可见任务;无此类任务才允许收起侧栏。
|
||||
*/
|
||||
const hasPinnedProcessingTasks = computed(() => {
|
||||
const projection = displayProcessing.value;
|
||||
if (!projection) return false;
|
||||
return statusGroupTasks('failed', 'waiting_human', 'processing', 'completed').length > 0;
|
||||
});
|
||||
|
||||
/**
|
||||
* 切换侧栏折叠:活跃任务存在时强制保持展开。
|
||||
*/
|
||||
function togglePanelCollapsed() {
|
||||
if (hasPinnedProcessingTasks.value) {
|
||||
collapsed.value = false;
|
||||
return;
|
||||
}
|
||||
collapsed.value = !collapsed.value;
|
||||
}
|
||||
|
||||
watch(
|
||||
hasPinnedProcessingTasks,
|
||||
(pinned) => {
|
||||
if (pinned) collapsed.value = false;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* 移除右侧常驻「批次与文件列表」长列表抽屉(UI-REFACTOR 方案 7)。
|
||||
@@ -839,7 +804,6 @@ watch(
|
||||
return;
|
||||
}
|
||||
if (!focusedTaskExists.value) return;
|
||||
collapsed.value = false;
|
||||
focusTaskBanner.value = normalized;
|
||||
// [UI-01/UI-02] 真正选中进度卡,禁止只显示提示条。
|
||||
await onProcessingFocus(normalized);
|
||||
@@ -856,31 +820,12 @@ watch(
|
||||
|
||||
<template>
|
||||
<aside
|
||||
class="flex min-w-0 flex-1 shrink-0 flex-col border-l border-default bg-surface shadow-[-16px_0_40px_rgba(15,23,42,0.10)] transition-[width] duration-200"
|
||||
:class="collapsed ? '!w-14' : ''"
|
||||
class="flex min-w-0 flex-1 shrink-0 flex-col bg-surface"
|
||||
data-testid="shipping-workflow-timeline"
|
||||
>
|
||||
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary"
|
||||
data-testid="shipping-workflow-close"
|
||||
:title="t('chat.shippingProcessing.closeWorkbench')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<component
|
||||
:is="hasPinnedProcessingTasks ? 'div' : 'button'"
|
||||
:type="hasPinnedProcessingTasks ? undefined : 'button'"
|
||||
class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left"
|
||||
:class="hasPinnedProcessingTasks
|
||||
? 'cursor-default'
|
||||
: 'hover:bg-surface-muted/60'"
|
||||
data-testid="shipping-workflow-panel-toggle"
|
||||
@click="togglePanelCollapsed"
|
||||
>
|
||||
<div v-if="!collapsed" class="min-w-0">
|
||||
<div class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ te('chat.shippingProcessing.panelTitle')
|
||||
@@ -888,14 +833,11 @@ watch(
|
||||
: t('chat.shippingProcessing.title') }}
|
||||
</div>
|
||||
<span
|
||||
v-if="hasPinnedProcessingTasks"
|
||||
class="inline-flex items-center gap-0.5 rounded bg-surface-muted px-1.5 py-0.5 text-[10px] font-medium text-secondary"
|
||||
data-testid="shipping-workflow-panel-pinned"
|
||||
:title="t('chat.shippingProcessing.panelPinnedHint')"
|
||||
>
|
||||
<Lock class="h-3 w-3 shrink-0" aria-hidden="true" />
|
||||
{{ t('chat.shippingProcessing.panelPinnedLabel') }}
|
||||
</span>
|
||||
v-if="conversationTitle"
|
||||
class="min-w-0 truncate rounded bg-surface-muted px-1.5 py-0.5 text-xs text-secondary"
|
||||
data-testid="shipping-workflow-conversation-title"
|
||||
:title="conversationTitle"
|
||||
>{{ conversationTitle }}</span>
|
||||
</div>
|
||||
<div class="mt-0.5 space-y-0.5 text-xs text-secondary" data-testid="shipping-workflow-panel-summary">
|
||||
<template v-if="initialLoading && !displayProcessing">
|
||||
@@ -918,12 +860,7 @@ watch(
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<ChevronDown
|
||||
v-if="!collapsed && !hasPinnedProcessingTasks"
|
||||
class="h-4 w-4 shrink-0 text-muted"
|
||||
/>
|
||||
<ChevronRight v-else-if="collapsed" class="h-4 w-4 shrink-0 text-muted" />
|
||||
</component>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary disabled:opacity-50"
|
||||
@@ -939,7 +876,7 @@ watch(
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-y-auto p-5">
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-5">
|
||||
<div
|
||||
v-if="initialLoading && !displayProcessing"
|
||||
class="mb-4 space-y-3"
|
||||
|
||||
@@ -649,6 +649,42 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.intakeParseLoadFailed.value).toBe(true);
|
||||
});
|
||||
|
||||
it('loads intake parse context for a formal-downstream Case while activeCase stays unloaded', async () => {
|
||||
// 选法 2:正式下游(货代上传等)切 PDF 不拉 Case/Evidence,activeCase 保持 null。
|
||||
// 关键断言:接收解析工作面回看已完成阶段时,上下文仍必须按 requestedCaseNo 拉取,
|
||||
// 不得因 activeCase 为 null 静默跳过(否则面板渲染成空白)。
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
|
||||
items: [{
|
||||
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
|
||||
has_formal_ot: true,
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available' },
|
||||
{ code: 'order_review', state: 'available' },
|
||||
{ code: 'fulfillment_prep', state: 'available' },
|
||||
{ code: 'freight_upload', state: 'current' },
|
||||
],
|
||||
}],
|
||||
});
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-2');
|
||||
|
||||
api.getCase.mockClear();
|
||||
api.getEvidence.mockClear();
|
||||
await review.selectCase('CASE-2');
|
||||
// 选法 2 关键断言:正式下游切换不拉复核 Case/Evidence,activeCase 为空。
|
||||
expect(api.getCase).not.toHaveBeenCalled();
|
||||
expect(review.activeCase.value).toBeNull();
|
||||
expect(review.requestedCaseNo.value).toBe('CASE-2');
|
||||
|
||||
await expect(review.ensureIntakeParseContextLoaded('CASE-2')).resolves.toBe(true);
|
||||
expect(api.getIntakeParseContext).toHaveBeenLastCalledWith('CASE-2');
|
||||
expect(review.intakeParseContext.value?.case_no).toBe('CASE-2');
|
||||
expect(review.intakeParseLoading.value).toBe(false);
|
||||
expect(review.intakeParseLoadFailed.value).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the latest same-Case intake context when an older success resolves last', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
@@ -771,6 +807,48 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
|
||||
});
|
||||
|
||||
it('beginCrossRunSwitch drops the previous file intake context and rejects its stale success', async () => {
|
||||
// 关键断言:跨 Run 切文件(如 PO_6075309 → PO_6075316)切换即清空接收解析上下文,
|
||||
// 迟到的旧 Case 上下文成功响应也不得把旧附件名/邮件正文写回新文件工作面。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
await review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
expect(review.intakeParseContext.value?.attachment.filename).toBe('order.pdf');
|
||||
|
||||
let resolveStale: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getIntakeParseContext.mockImplementationOnce(
|
||||
() => new Promise((resolve) => { resolveStale = resolve; }),
|
||||
);
|
||||
const pendingStale = review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
review.beginCrossRunSwitch('CASE-2');
|
||||
|
||||
expect(review.intakeParseContext.value).toBeNull();
|
||||
expect(review.intakeParseLoading.value).toBe(false);
|
||||
expect(review.intakeParseLoadFailed.value).toBe(false);
|
||||
resolveStale?.({
|
||||
case_no: 'CASE-1',
|
||||
attachment: { document_id: 1, filename: 'order.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' },
|
||||
email: null,
|
||||
});
|
||||
await pendingStale;
|
||||
expect(review.intakeParseContext.value).toBeNull();
|
||||
});
|
||||
|
||||
it('load fast path drops the stale intake context when the target Case changes', async () => {
|
||||
// 关键断言:稳定工作台直达 load 换 Case(重解析落位/重试等入口)同样撤销旧上下文。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
await review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
|
||||
|
||||
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
|
||||
await review.load('RUN-1', 'CASE-2');
|
||||
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-2');
|
||||
expect(review.intakeParseContext.value).toBeNull();
|
||||
expect(review.intakeParseLoading.value).toBe(false);
|
||||
});
|
||||
|
||||
it('discards stale selectCase responses when switching PDFs quickly', async () => {
|
||||
// 关键断言:A 后发先至不得覆盖后选的 B;切换时先清空瞬态。
|
||||
let resolveA: ((value: ShippingOrderReviewCase) => void) | null = null;
|
||||
|
||||
@@ -993,10 +993,13 @@ export function useShippingOrderReview(options: {
|
||||
/**
|
||||
* 仅在用户打开接收解析工作面时按需读取当前 Case 的附件与邮件正文。
|
||||
* Case/代次双校验避免迟到响应把旧附件或 EML 写回当前工作面;失败保持空上下文。
|
||||
* 选法 2(正式下游)下 activeCase 刻意为 null,此时以 requestedCaseNo 校验目标,
|
||||
* 与 ensurePreviewLoaded 的兜底口径一致;否则回看已完成接收解析阶段会静默跳过加载。
|
||||
*/
|
||||
const ensureIntakeParseContextLoaded = async (caseNo: string): Promise<boolean> => {
|
||||
const target = String(caseNo || '').trim();
|
||||
if (!target || activeCase.value?.case_no !== target) {
|
||||
const expectedCaseNo = String(requestedCaseNo.value || activeCase.value?.case_no || '').trim();
|
||||
if (!target || target !== expectedCaseNo) {
|
||||
++intakeParseRequestGeneration;
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
@@ -1014,7 +1017,7 @@ export function useShippingOrderReview(options: {
|
||||
if (
|
||||
requestGeneration !== intakeParseRequestGeneration
|
||||
|| generation !== caseLoadGeneration
|
||||
|| activeCase.value?.case_no !== target
|
||||
|| String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() !== target
|
||||
) return false;
|
||||
intakeParseContext.value = context;
|
||||
return true;
|
||||
@@ -1022,7 +1025,7 @@ export function useShippingOrderReview(options: {
|
||||
if (
|
||||
requestGeneration === intakeParseRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
&& String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() === target
|
||||
) {
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoadFailed.value = true;
|
||||
@@ -1032,7 +1035,7 @@ export function useShippingOrderReview(options: {
|
||||
if (
|
||||
requestGeneration === intakeParseRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
&& String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() === target
|
||||
) {
|
||||
intakeParseLoading.value = false;
|
||||
}
|
||||
@@ -1096,6 +1099,13 @@ export function useShippingOrderReview(options: {
|
||||
// 已有稳定工作台且路由明确目标 PDF 时,目标详情是用户切换的关键路径;
|
||||
// Run/Queue 只负责后续更新导航和阶段摘要,不能用其慢投影阻塞当前文件显示。
|
||||
if (hasStableWorkbench && preferredCaseNo) {
|
||||
// 稳定工作台直达 load 换 Case 时(如重解析落位/重试),同样必须撤销旧文件的
|
||||
// 接收解析上下文;新上下文由视图层 Case 变化 watcher 按目标 Case 重载。
|
||||
if (String(preferredCaseNo || '').trim() !== String(activeCase.value?.case_no || '').trim()) {
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
}
|
||||
const [caseSnapshot, caseEvidence] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(preferredCaseNo),
|
||||
getWorkspaceShippingOrderReviewEvidence(preferredCaseNo),
|
||||
@@ -1189,6 +1199,8 @@ export function useShippingOrderReview(options: {
|
||||
* 核心逻辑:保留 activeCase/工作台壳(避免大骨架闪动),但清空 user_task_no,
|
||||
* 让 shippingProcessingProjection 立即丢弃上一份 PDF 的右卡/库存态;目标 Case
|
||||
* 仍由随后的 load(preferredCaseNo) 目标优先路径写入。
|
||||
* 接收解析上下文必须与预览一并撤销:Run 变更即 Case 变更,旧文件的附件名/邮件正文
|
||||
* 不得残留在新文件工作面(新上下文由视图层 Case 变化 watcher 重载)。
|
||||
* @param caseNo - 目标复核 Case 编号
|
||||
*/
|
||||
const beginCrossRunSwitch = (caseNo: string) => {
|
||||
@@ -1212,6 +1224,9 @@ export function useShippingOrderReview(options: {
|
||||
};
|
||||
}
|
||||
clearPreview();
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -108,6 +108,46 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('preserves explainability message and next_action on blocking_reason', () => {
|
||||
// v4 阻塞原因具体化:冻结 explainability 契约透传的 message / next_action
|
||||
// 是「阻塞原因行」与「下一步建议动作」的数据源,归一化不得剥离。
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-REASON',
|
||||
work_item_type: 'order_task',
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
ui_state: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: {
|
||||
code: 'customer_unresolved',
|
||||
message: '客户尚未确认',
|
||||
next_action: 'confirm_customer',
|
||||
},
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
source_summary: {
|
||||
email_subject: null,
|
||||
filename: 'reason.pdf',
|
||||
document_id: 91,
|
||||
document_count: 1,
|
||||
parsed_document_count: 1,
|
||||
candidate_count: 1,
|
||||
customer_name: null,
|
||||
po_number: null,
|
||||
failure_reason_code: null,
|
||||
parse_attempt_count: 0,
|
||||
asset_status: 'ready',
|
||||
},
|
||||
child_order_tasks: [],
|
||||
});
|
||||
const reason = normalized?.uiState?.blocking_reason;
|
||||
expect(reason?.code).toBe('customer_unresolved');
|
||||
expect(reason?.message).toBe('客户尚未确认');
|
||||
expect(reason?.nextAction).toBe('confirm_customer');
|
||||
});
|
||||
|
||||
it('normalizes the EML status-partition file count', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'INTAKE:SNI-EML',
|
||||
|
||||
@@ -108,12 +108,16 @@ function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 blocking_reason(后端 snake_case {code, i18n_key, details})。
|
||||
* v4:保留冻结 explainability 契约透传的 message(中文兜底文案)与
|
||||
* next_action(下一步建议动作码,camel/snake 兼容),供「阻塞原因行」与
|
||||
* 「下一步」槽位消费;禁止剥离,否则 UI 退化为通用状态文案。
|
||||
*/
|
||||
function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const code = String(item.code ?? '').trim();
|
||||
if (!code) return null;
|
||||
const nextAction = item.next_action ?? item.nextAction;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
@@ -121,6 +125,8 @@ function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason
|
||||
typeof item.details === 'object' && item.details != null
|
||||
? (item.details as Record<string, unknown>)
|
||||
: {},
|
||||
message: item.message != null ? String(item.message) : null,
|
||||
nextAction: nextAction != null ? String(nextAction) : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
extractExtractionProgressReasonCode,
|
||||
isGenericBlockingReason,
|
||||
isRedundantExtractionDetail,
|
||||
resolveBlockingReasonText,
|
||||
resolveExtractionActivityMessage,
|
||||
resolveRunLifecycleUserStatus,
|
||||
resolveShippingProcessingReasonLabel,
|
||||
@@ -175,3 +177,38 @@ describe('extraction lifecycle display (v2 状态展示统一)', () => {
|
||||
expect(isRedundantExtractionDetail('', 'waiting_human')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('blocking reason text resolution (v4 阻塞原因具体化)', () => {
|
||||
// 仅登记通用兜底与一个 Gate 命名空间码,验证解析链与隐藏判定
|
||||
const REASON_TEXT: Record<string, string> = {
|
||||
'chat.shippingProcessing.reasonCode.unknown': '当前步骤需要人工处理',
|
||||
'workspace.shippingNotice.processGate.reasons.customer_unresolved': '客户尚未确认',
|
||||
};
|
||||
const te = (key: string) => key in REASON_TEXT;
|
||||
const t = (key: string) => REASON_TEXT[key] ?? key;
|
||||
|
||||
it('resolveBlockingReasonText:Gate 命名空间可解析的原因码返回具体文案', () => {
|
||||
expect(resolveBlockingReasonText({ code: 'customer_unresolved' }, te, t)).toBe('客户尚未确认');
|
||||
});
|
||||
|
||||
it('resolveBlockingReasonText:命名空间未命中时回退契约透传 message', () => {
|
||||
// 关键断言:后端 explainability.message 是 i18n 之后的最后兜底,不是首选
|
||||
expect(resolveBlockingReasonText({
|
||||
code: 'budget_stopped',
|
||||
message: '订单识别预算已用尽,请检查文档后进入复核',
|
||||
}, te, t)).toBe('订单识别预算已用尽,请检查文档后进入复核');
|
||||
});
|
||||
|
||||
it('resolveBlockingReasonText:通用兜底返回空串,调用方据此隐藏原因行', () => {
|
||||
expect(resolveBlockingReasonText({ code: 'internal_gate_reason' }, te, t)).toBe('');
|
||||
expect(resolveBlockingReasonText(null, te, t)).toBe('');
|
||||
expect(resolveBlockingReasonText(undefined, te, t)).toBe('');
|
||||
});
|
||||
|
||||
it('isGenericBlockingReason:Gate 命名空间可解析即非通用;仅未知码为通用', () => {
|
||||
// 关键断言:i18n 命名空间可解析(四语言齐备)才算具体原因
|
||||
expect(isGenericBlockingReason({ code: 'customer_unresolved' }, te)).toBe(false);
|
||||
expect(isGenericBlockingReason({ code: 'internal_gate_reason' }, te)).toBe(true);
|
||||
expect(isGenericBlockingReason(null, te)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -87,6 +87,44 @@ export function resolveShippingProcessingReasonLabel(
|
||||
return te(unknownKey) ? t(unknownKey) : '当前步骤需要人工处理';
|
||||
}
|
||||
|
||||
/** Gate 原因码的多命名空间查找键(与 resolveGateReasonLabel 保持同源顺序)。 */
|
||||
function gateReasonNamespaceKeys(code: string): string[] {
|
||||
return [
|
||||
`chat.shippingProcessing.gateReasons.${code}`,
|
||||
`workspace.shippingNotice.workflowReasons.${code}`,
|
||||
`workspace.shippingNotice.processGate.reasons.${code}`,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析批次中心行内「阻塞原因」文案;通用兜底返回空串(调用方隐藏原因行)。
|
||||
* 核心逻辑:i18n_key → reasonCode 专用键 → Gate 三命名空间 → 契约透传 message;
|
||||
* 与 isGenericBlockingReason 同一判据,保证「隐藏的」与「展示的」口径一致。
|
||||
*/
|
||||
export function resolveBlockingReasonText(
|
||||
reason: {
|
||||
code?: string | null;
|
||||
i18nKey?: string | null;
|
||||
i18n_key?: string | null;
|
||||
message?: string | null;
|
||||
} | null | undefined,
|
||||
te: (key: string) => boolean,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
if (isGenericBlockingReason(reason, te)) return '';
|
||||
const i18nKey = String(reason?.i18nKey || reason?.i18n_key || '').trim();
|
||||
if (i18nKey && te(i18nKey)) return t(i18nKey);
|
||||
const code = String(reason?.code || '').trim();
|
||||
if (code) {
|
||||
const reasonCodeKey = `chat.shippingProcessing.reasonCode.${code}`;
|
||||
if (te(reasonCodeKey)) return t(reasonCodeKey);
|
||||
for (const key of gateReasonNamespaceKeys(code)) {
|
||||
if (te(key)) return t(key);
|
||||
}
|
||||
}
|
||||
return String(reason?.message || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析统一处理文案。
|
||||
*
|
||||
@@ -197,22 +235,33 @@ export function resolveShippingLifecycleStageLabel(
|
||||
/**
|
||||
* 判定阻塞原因是否为「通用兜底」(应在行内隐藏,避免与状态芯片重复)。
|
||||
*
|
||||
* 三方约定:仅当下发到具体、非兜底的阻塞原因(有真实 i18n 文案)才展示原因行;
|
||||
* 进到 reasonCode.unknown / 无 i18n_key 的通用码一律视为重复信息。
|
||||
* 三方约定:仅当下发到具体、非兜底的阻塞原因才展示原因行。具体判据:
|
||||
* i18n_key 命中、reasonCode 专用键命中、Gate 三命名空间任一命中
|
||||
* (四语言齐备),或契约透传了具体 message(无命名空间时的最后兜底)。
|
||||
* 进到 unknown / 全部未命中的一律视为重复信息。
|
||||
*
|
||||
* @param reason - 后端 blocking_reason(code / i18n_key)
|
||||
* @param reason - 后端 blocking_reason(code / i18n_key / message)
|
||||
* @param te - i18n te
|
||||
* @returns true=通用兜底(应隐藏)
|
||||
*/
|
||||
export function isGenericBlockingReason(
|
||||
reason: { code?: string | null; i18nKey?: string | null; i18n_key?: string | null } | null | undefined,
|
||||
reason: {
|
||||
code?: string | null;
|
||||
i18nKey?: string | null;
|
||||
i18n_key?: string | null;
|
||||
message?: string | null;
|
||||
} | null | undefined,
|
||||
te: (key: string) => boolean,
|
||||
): boolean {
|
||||
if (!reason) return true;
|
||||
const i18nKey = String(reason.i18nKey || reason.i18n_key || '').trim();
|
||||
if (i18nKey && te(i18nKey)) return false;
|
||||
const code = String(reason.code || '').trim();
|
||||
if (code && code !== 'unknown' && te(`chat.shippingProcessing.reasonCode.${code}`)) return false;
|
||||
if (code && code !== 'unknown') {
|
||||
if (te(`chat.shippingProcessing.reasonCode.${code}`)) return false;
|
||||
if (gateReasonNamespaceKeys(code).some((key) => te(key))) return false;
|
||||
}
|
||||
if (String(reason.message || '').trim()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkbenchLayout.spec.ts
|
||||
* 用途:锁定货代会话主区域显隐规则(有会话即全屏批次进度中心,方案 A)。
|
||||
* 依赖:Vitest、纯函数。
|
||||
* 逻辑:判定必须同时满足货代智能体与非空会话 ID;普通智能体与新会话一律回落欢迎页。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { shouldShowShippingWorkbench } from './shippingWorkbenchLayout';
|
||||
|
||||
describe('shouldShowShippingWorkbench', () => {
|
||||
it('renders the workbench for the shipping agent once a conversation exists', () => {
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: 'conv-1' })).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the welcome composer before a conversation is created', () => {
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: '' })).toBe(false);
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: null })).toBe(false);
|
||||
});
|
||||
|
||||
it('never switches other agents to the workbench', () => {
|
||||
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: false, conversationId: 'conv-1' })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkbenchLayout.ts
|
||||
* 用途:货代发货会话主区域显隐判定(批次进度中心优先,方案 A)。
|
||||
* 依赖:无(纯函数)。
|
||||
* 逻辑:货代智能体且存在非空会话 ID 时全屏渲染批次进度中心;
|
||||
* 否则(新会话欢迎页)显示欢迎页 + 输入框(唯一附件提交入口)。
|
||||
*/
|
||||
|
||||
export interface ShippingWorkbenchLayoutInput {
|
||||
isShippingNoticeAgent: boolean;
|
||||
conversationId: string | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定是否以批次进度中心作为会话主区域。
|
||||
* @param input - 智能体身份与当前会话 ID(路由 query 与 page 回填同源优先级)。
|
||||
* @returns true 表示全屏渲染批次进度中心;false 表示欢迎页 + 输入框。
|
||||
*/
|
||||
export function shouldShowShippingWorkbench(input: ShippingWorkbenchLayoutInput): boolean {
|
||||
return Boolean(input.isShippingNoticeAgent && String(input.conversationId || '').trim());
|
||||
}
|
||||
@@ -167,6 +167,11 @@ export interface ShippingProcessingBlockingReason {
|
||||
code: string;
|
||||
i18nKey?: string | null;
|
||||
details?: Record<string, unknown>;
|
||||
/** 建单前资格快照回退透传(冻结 explainability 契约):中文兜底文案,前端优先 i18n。 */
|
||||
message?: string | null;
|
||||
/** 契约注册的下一步动作码(processGate.actionCodes.*),camel/snake 兼容读取。 */
|
||||
nextAction?: string | null;
|
||||
next_action?: string | null;
|
||||
}
|
||||
/**
|
||||
* 用户态统一 Projection 主动作(T8 决策 F2;后端对象 {code, i18n_key, parameters})。
|
||||
@@ -955,7 +960,8 @@ export interface ShippingRpaRuntime {
|
||||
}
|
||||
|
||||
export interface ShippingCurrentStepProgress {
|
||||
step_key?: string;
|
||||
/** 15 阶契约阶段码(CheckPoint 时代 stepN_* 遗留键已清除)。 */
|
||||
stage?: string;
|
||||
step_title?: string;
|
||||
status?: 'running' | 'completed' | 'needs_human' | 'pending' | string;
|
||||
message?: string;
|
||||
@@ -1498,6 +1504,15 @@ export interface ShippingTaskUiState {
|
||||
}>;
|
||||
/** 人工覆写库存源(方案 3·放开):全部已启用源,供行级下拉人工指定。 */
|
||||
source_options?: Array<{ source_code?: string | null; display_name?: string | null }>;
|
||||
/**
|
||||
* 整单 ODM 裁决摘要:conflict=true 表示范围限定后仍有多行存在多值,
|
||||
* 由行内 odm 下发候选,用户改任一行后同一快照文件的其他行同步。
|
||||
*/
|
||||
odm_options?: {
|
||||
conflict?: boolean;
|
||||
customer_odm_ids?: Array<string>;
|
||||
whitelist_applied?: boolean;
|
||||
};
|
||||
/** 阶段能力(Task 2 下发);prep 工作台能力工具条消费,scope=task 级。 */
|
||||
capabilities?: ShippingStageCapability[];
|
||||
/** 仅当前任务活动关联的库存快照才可下载。 */
|
||||
@@ -1523,6 +1538,10 @@ export interface ShippingTaskUiState {
|
||||
/** 多文件冲突行(D5):候选源列表供行内下拉,选定后走 override_line_inventory_source。 */
|
||||
source_ambiguous?: boolean;
|
||||
source_candidates?: Array<string>;
|
||||
/** 整单 ODM 裁决:本行候选(经客户范围过滤);同快照文件行同步同一 chosen 值。 */
|
||||
odm_values?: Array<string>;
|
||||
chosen_odm_id?: string | null;
|
||||
odm_conflict?: boolean;
|
||||
}>;
|
||||
artifact?: { file_name?: string | null; status?: string | null } | null;
|
||||
} | null;
|
||||
@@ -2307,6 +2326,8 @@ export interface ShippingOrderReviewCaseSummary {
|
||||
intake_parse_authorized?: boolean;
|
||||
draft_version?: number | null;
|
||||
issue_count: number;
|
||||
/** 队列后端按当前门禁裁决:blocked_manual/blocked_retryable/failed_terminal 为 true;前端禁止自行推断阻塞。 */
|
||||
needs_attention?: boolean;
|
||||
available_actions: string[];
|
||||
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
|
||||
intake_no?: string | null;
|
||||
|
||||
@@ -993,6 +993,47 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('reloads the intake parse context by requested Case when activeCase is unloaded (formal downstream)', async () => {
|
||||
// 用户场景:正式下游文件(货代上传 · 已创建任务)切进后 activeCase 为 null(选法 2),
|
||||
// 此时回看「接收解析」已完成阶段,上下文必须按 requestedCaseNo 发起请求;
|
||||
// 静默跳过会让 ReviewIntakeParsePanel 以空 context 渲染成整块空白。
|
||||
const originalQueue = reviewQueue.value;
|
||||
const originalActiveCase = activeCase.value;
|
||||
const originalRequested = requestedCaseNo.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
has_formal_ot: true,
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available' },
|
||||
{ code: 'order_review', state: 'available' },
|
||||
{ code: 'fulfillment_prep', state: 'available' },
|
||||
{ code: 'freight_upload', state: 'current' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
activeCase.value = null;
|
||||
requestedCaseNo.value = 'CASE-1';
|
||||
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
|
||||
|
||||
ensureIntakeParseContextLoaded.mockClear();
|
||||
await (wrapper.vm as any).selectLifecycleStage('intake_parse');
|
||||
await flushPromises();
|
||||
|
||||
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
|
||||
.toBe('intake_parse');
|
||||
// 关键断言:activeCase 为 null 时不得跳过上下文加载,且以目标 Case 请求。
|
||||
expect(ensureIntakeParseContextLoaded).toHaveBeenCalledWith('CASE-1');
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
activeCase.value = originalActiveCase;
|
||||
requestedCaseNo.value = originalRequested;
|
||||
}
|
||||
});
|
||||
|
||||
it('stops the pending reparse navigation when the user selects another PDF', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
retryShippingNoticeIntake,
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
waveWorkspaceShippingOrderReviewLineFulfillment,
|
||||
setWorkspaceShippingTaskOdmChoice,
|
||||
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
|
||||
} from '../api/shipping.api';
|
||||
import type {
|
||||
@@ -325,7 +326,9 @@ const lifecycleUiState = computed(() => {
|
||||
};
|
||||
}
|
||||
// [STEP 3] 建单前:Run/Queue 项仍由后端下发生命周期入口。
|
||||
const currentCaseNo = String(activeCase.value?.case_no || '').trim();
|
||||
// 选法 2(正式下游回看)下 activeCase 刻意为 null,此时以切换管线的 requestedCaseNo
|
||||
// 定位队列项,否则 entries 永远为空、阶段导航整体退化为 blocked。
|
||||
const currentCaseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
|
||||
const reviewEntry = (reviewQueue.value?.items || reviewRun.value?.items || []).find(
|
||||
(item) => String(item.case_no || '').trim() === currentCaseNo,
|
||||
);
|
||||
@@ -398,6 +401,13 @@ const intakeParseContextAuthorized = computed(() => {
|
||||
|| lifecycleEntryIsEnterable(entry)
|
||||
);
|
||||
});
|
||||
/**
|
||||
* 接收解析工作面的目标 Case:选法 2(正式下游回看)下 activeCase 刻意为 null,
|
||||
* 必须以切换管线的 requestedCaseNo 兜底,否则上下文加载会被静默跳过(面板空白)。
|
||||
*/
|
||||
const intakeTargetCaseNo = computed(() => (
|
||||
String(activeCase.value?.case_no || requestedCaseNo.value || '').trim()
|
||||
));
|
||||
const lifecycleStageItems = computed<ReviewLifecycleStageItem[]>(() => {
|
||||
const blocker = lifecycleUiState.value.blocker;
|
||||
const entries = lifecycleUiState.value.entries;
|
||||
@@ -483,8 +493,8 @@ async function retryCurrentIntakeParse(): Promise<void> {
|
||||
await Promise.all([
|
||||
reloadLatestDraft(),
|
||||
refreshShippingProcessing(),
|
||||
activeCase.value?.case_no
|
||||
? ensureIntakeParseContextLoaded(activeCase.value.case_no)
|
||||
intakeTargetCaseNo.value
|
||||
? ensureIntakeParseContextLoaded(intakeTargetCaseNo.value)
|
||||
: Promise.resolve(false),
|
||||
]);
|
||||
} catch (error) {
|
||||
@@ -575,8 +585,8 @@ async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { r
|
||||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||||
}
|
||||
}
|
||||
if (code === 'intake_parse' && intakeParseContextAuthorized.value && activeCase.value?.case_no) {
|
||||
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
|
||||
if (code === 'intake_parse' && intakeParseContextAuthorized.value && intakeTargetCaseNo.value) {
|
||||
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
|
||||
}
|
||||
const mode: ReviewWorkbenchMode = code === 'order_review' || code === 'intake_parse'
|
||||
? 'standard'
|
||||
@@ -2643,6 +2653,38 @@ async function submitOverrideSource(line: { snapshot_line_id?: number | null; li
|
||||
}
|
||||
}
|
||||
|
||||
/** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */
|
||||
const formalPreparationOdmColumnVisible = computed(() =>
|
||||
(formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1),
|
||||
);
|
||||
const lineOdmSelections = ref<Record<string, string>>({});
|
||||
const lineOdmBusy = ref(false);
|
||||
|
||||
/**
|
||||
* 提交行级 ODM 选择:后端把同一快照文件的全部当前匹配行同步为同一值,
|
||||
* 刷新详情后其他行回显同步结果,并在门禁仍授权时自动重试生成 Excel。
|
||||
*/
|
||||
async function submitLineOdmChoice(line: { snapshot_line_id?: number | null }) {
|
||||
const selectionKey = String(line.snapshot_line_id ?? '');
|
||||
const odmId = String(lineOdmSelections.value[selectionKey] || '').trim();
|
||||
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
|
||||
if (!odmId || !taskNo || lineOdmBusy.value) return;
|
||||
lineOdmBusy.value = true;
|
||||
try {
|
||||
await setWorkspaceShippingTaskOdmChoice(taskNo, { snapshot_line_id: selectionKey, odm_id: odmId });
|
||||
delete lineOdmSelections.value[selectionKey];
|
||||
await loadFormalTaskDetail();
|
||||
const canRegenerate = formalTaskActions.value.some(
|
||||
(action) => action.enabled && String(action.code || '').trim() === 'regenerate_excel_artifact',
|
||||
);
|
||||
if (canRegenerate) await submitFormalGateAction('regenerate_excel_artifact');
|
||||
} catch (error) {
|
||||
msg.error(resolveReviewErrorMessage(error));
|
||||
} finally {
|
||||
lineOdmBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function formalPreparationLineAllows(
|
||||
line: { snapshot_line_id?: number | null },
|
||||
action: 'retry_inventory_preparation' | 'retry_inventory_matching' | 'close_unfulfillable' | 'release_inventory_shortage',
|
||||
@@ -4397,7 +4439,14 @@ watch(
|
||||
);
|
||||
|
||||
watch(
|
||||
[lifecycleActiveStageCode, hasFormalOt, intakeParseContextAuthorized],
|
||||
[
|
||||
lifecycleActiveStageCode,
|
||||
hasFormalOt,
|
||||
intakeParseContextAuthorized,
|
||||
// 接收解析文件互切时 stage/授权通常不变;必须以 Case 变化触发新附件/邮件上下文重载,
|
||||
// 否则接收解析工作面停留上一份 PDF 的附件名且预览不再自动加载。
|
||||
() => String(activeCase.value?.case_no || '').trim(),
|
||||
],
|
||||
([code, , intakeAuthorized]) => {
|
||||
// 确认进度是当前阶段内的短暂辅助视图,不由生命周期页签覆盖。
|
||||
if (workbenchMode.value === 'confirm_progress') return;
|
||||
@@ -4405,8 +4454,8 @@ watch(
|
||||
// surface 反向成为前端阶段裁决。
|
||||
if (code === null) return;
|
||||
syncLifecycleWorkbenchMode(code);
|
||||
if (code === 'intake_parse' && intakeAuthorized && activeCase.value?.case_no) {
|
||||
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
|
||||
if (code === 'intake_parse' && intakeAuthorized && intakeTargetCaseNo.value) {
|
||||
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
@@ -4487,10 +4536,15 @@ function retryFormalTaskDetail() {
|
||||
*/
|
||||
const REVIEW_EDITOR_NEEDED_STAGES: ReviewLifecycleStageCode[] = ['intake_parse', 'order_review', 'fulfillment_prep'];
|
||||
watch(
|
||||
lifecycleCurrentStageCode,
|
||||
// 用户查看面(含回看已完成阶段)驱动 Case 懒加载:选法 2 正式下游切 PDF 后 activeCase
|
||||
// 为 null,回看接收解析/订单复核/通知准备时必须按需补拉目标 Case,否则这些工作面
|
||||
// 只能渲染空白或残留上一份 PDF 的数据。
|
||||
lifecycleActiveStageCode,
|
||||
(stage) => {
|
||||
if (!stage || !REVIEW_EDITOR_NEEDED_STAGES.includes(stage)) return;
|
||||
const caseNo = String(displayCase.value?.case_no || '').trim();
|
||||
// 禁止使用 displayCase 兜底:它可能停留在上一份 PDF 的快照上造成串味;
|
||||
// 目标一律取当前工作面的 activeCase 或切换管线的 requestedCaseNo。
|
||||
const caseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
|
||||
if (!caseNo) return;
|
||||
if (stage === 'fulfillment_prep') {
|
||||
if (activeCase.value) return;
|
||||
@@ -4857,12 +4911,12 @@ watch(
|
||||
class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-950/30 dark:text-brand-300"
|
||||
>{{ formalPreparationStatusLabel(formalPreparationContext?.status) }}</span>
|
||||
</div>
|
||||
<div v-if="formalPreparationDisplayLines.length" class="review-fulfillment-prep-workspace mt-4 rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
|
||||
<!-- 标题与选行操作条固定不参与横向滚动,仅表头/表体横向滑动。 -->
|
||||
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
|
||||
<div class="text-xs font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.matchWorkspace') }}</div>
|
||||
<span class="text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineCount', { count: formalPreparationDisplayLines.length }) }}</span>
|
||||
</div>
|
||||
<div v-if="formalPreparationDisplayLines.length" class="review-fulfillment-prep-workspace mt-4 rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
|
||||
<!-- 标题与选行操作条固定不参与横向滚动,仅表头/表体横向滑动。 -->
|
||||
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
|
||||
<div class="text-xs font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.matchWorkspace') }}</div>
|
||||
<span class="text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineCount', { count: formalPreparationDisplayLines.length }) }}</span>
|
||||
</div>
|
||||
<div v-if="preparationEditable && formalHeaderEditable()" class="flex flex-wrap items-center justify-between gap-2 border-b border-default bg-brand-50/50 px-3 py-2 text-xs dark:bg-brand-950/20">
|
||||
<div class="flex items-center gap-3 text-secondary">
|
||||
<span class="font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.selectReady') }}</span>
|
||||
@@ -4872,8 +4926,8 @@ watch(
|
||||
</div>
|
||||
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
|
||||
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
|
||||
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
|
||||
<tbody><tr v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`" :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary">{{ line.reservation_id || '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="line.part_number || '—'">{{ line.part_number || '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.required_qty ?? '—' }}</td><td class="max-w-[220px] px-3 py-2"><div v-if="line.source_ambiguous && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-source-ambiguous-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceAmbiguous')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.source_code || ''" @change="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="code in line.source_candidates || []" :key="code" :value="code">{{ lineSourceOptionLabel(code) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || lineSourceBusy || !preparationEditable" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" @click="submitLineSourceSelection(line)"><Check class="h-3.5 w-3.5" /></button></div><span v-else-if="line.source_ambiguous && formalPreparationSourceLocked" class="text-xs text-secondary" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked')">{{ t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked') }}</span><span v-else-if="!formalPreparationSourceLocked && formSourceOptions.length" class="flex items-center gap-1" :data-testid="`review-line-source-override-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-override-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.selected_source_code || line.source_code || ''" @change="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="s in formSourceOptions" :key="String(s.source_code)" :value="String(s.source_code)">{{ overrideSourceOptionLabel(String(s.source_code)) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-override-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || overrideSourceBusy" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :data-line-index="lineIndex" @click="submitOverrideSource(line)"><Check class="h-3.5 w-3.5" /></button></span><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) }}</span></td><td class="whitespace-nowrap px-3 py-2">{{ line.available_qty ?? '—' }}</td><td class="whitespace-nowrap px-3 py-2 font-medium" :class=Line truncated
|
||||
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
|
||||
<tbody><tr v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`" :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary">{{ line.reservation_id || '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="line.part_number || '—'">{{ line.part_number || '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.required_qty ?? '—' }}</td><td class="max-w-[220px] px-3 py-2"><div v-if="line.source_ambiguous && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-source-ambiguous-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceAmbiguous')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.source_code || ''" @change="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="code in line.source_candidates || []" :key="code" :value="code">{{ lineSourceOptionLabel(code) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || lineSourceBusy || !preparationEditable" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" @click="submitLineSourceSelection(line)"><Check class="h-3.5 w-3.5" /></button></div><span v-else-if="line.source_ambiguous && formalPreparationSourceLocked" class="text-xs text-secondary" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked')">{{ t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked') }}</span><span v-else-if="!formalPreparationSourceLocked && formSourceOptions.length" class="flex items-center gap-1" :data-testid="`review-line-source-override-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-override-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.selected_source_code || line.source_code || ''" @change="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="s in formSourceOptions" :key="String(s.source_code)" :value="String(s.source_code)">{{ overrideSourceOptionLabel(String(s.source_code)) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-override-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || overrideSourceBusy" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :data-line-index="lineIndex" @click="submitOverrideSource(line)"><Check class="h-3.5 w-3.5" /></button></span><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalLine truncated
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
@@ -5079,8 +5133,8 @@ watch(
|
||||
:load-failed="intakeParseLoadFailed"
|
||||
:preview-url="previewUrl || null"
|
||||
:preview-loading="previewLoading"
|
||||
@retry-context="() => { if (activeCase?.case_no) void ensureIntakeParseContextLoaded(activeCase.case_no); }"
|
||||
@load-preview="() => { if (activeCase?.case_no) void ensurePreviewLoaded(activeCase.case_no); }"
|
||||
@retry-context="() => { if (intakeTargetCaseNo) void ensureIntakeParseContextLoaded(intakeTargetCaseNo); }"
|
||||
@load-preview="() => { if (intakeTargetCaseNo) void ensurePreviewLoaded(intakeTargetCaseNo); }"
|
||||
/>
|
||||
<!-- 仅「固定为侧栏」时 PDF 占网格列;默认浮窗挂在根节点,不挤压订单区。 -->
|
||||
<div
|
||||
|
||||
@@ -58,16 +58,21 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.name') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.shortCode') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.status') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.odmIds') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.identityEvidences') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.notices') }}</th>
|
||||
<th class="px-5 py-4 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr v-if="admin.customers.value.length === 0"><td colspan="6" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
|
||||
<tr v-if="admin.customers.value.length === 0"><td colspan="7" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
|
||||
<tr v-for="customer in admin.customers.value" :key="customer.id">
|
||||
<td class="px-5 py-4"><div class="font-medium text-primary">{{ customer.standard_name }}</div><div v-if="customer.remark" class="text-xs text-muted truncate max-w-sm">{{ customer.remark }}</div></td>
|
||||
<td class="px-5 py-4 font-mono text-sm">{{ customer.short_code }}</td>
|
||||
<td class="px-5 py-4"><span class="text-sm" :class="customer.status === 'active' ? 'text-emerald-600' : 'text-muted'">{{ t(`admin.shippingCustomers.status.${customer.status}`) }}</span></td>
|
||||
<td class="px-5 py-4 text-sm">
|
||||
<span v-if="customer.odm_ids?.length" class="font-mono text-xs">{{ customer.odm_ids.join(', ') }}</span>
|
||||
<span v-else class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsUnlimited') }}</span>
|
||||
</td>
|
||||
<td class="px-5 py-4 text-sm">{{ customer.identity_evidence_count || 0 }}</td>
|
||||
<td class="px-5 py-4 text-sm">{{ customer.notice_count }}</td>
|
||||
<td class="px-5 py-4"><div class="flex justify-end gap-1">
|
||||
|
||||
@@ -42,6 +42,16 @@ const { t } = useI18n();
|
||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.remark') }}</span>
|
||||
<textarea v-model="form.remark" rows="3" class="input-field text-sm resize-y" />
|
||||
</label>
|
||||
<label class="block space-y-1.5">
|
||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.odmIds') }}</span>
|
||||
<textarea
|
||||
v-model="form.odm_ids_text"
|
||||
rows="3"
|
||||
class="input-field text-sm resize-y font-mono"
|
||||
:placeholder="t('admin.shippingCustomers.fields.odmIdsHint')"
|
||||
/>
|
||||
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsHint') }}</span>
|
||||
</label>
|
||||
<label v-if="form.id" class="block space-y-1.5">
|
||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.changeReason') }}</span>
|
||||
<textarea v-model="form.reason" rows="2" class="input-field text-sm resize-y" :placeholder="t('admin.shippingCustomers.fields.changeReasonHint')" />
|
||||
|
||||
+10
@@ -158,11 +158,21 @@ export function useShippingCustomersAdmin() {
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
// ODM ID 清单:文本域逐行解析,去空去重;整体为空提交 null 表示不限定。
|
||||
const odmIds = Array.from(
|
||||
new Set(
|
||||
form.odm_ids_text
|
||||
.split(/\r?\n/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
);
|
||||
const payload = {
|
||||
standard_name: form.standard_name.trim(),
|
||||
short_code: form.short_code.trim().toUpperCase(),
|
||||
status: form.status,
|
||||
remark: form.remark.trim(),
|
||||
odm_ids: odmIds.length ? odmIds : null,
|
||||
reason: form.reason.trim(),
|
||||
};
|
||||
if (form.id) await updateShippingCustomer(form.id, payload);
|
||||
|
||||
@@ -29,6 +29,8 @@ export interface ShippingCustomerRow {
|
||||
status: ShippingCustomerStatus;
|
||||
merged_into_customer_id?: number | null;
|
||||
remark?: string | null;
|
||||
/** 客户可用的 ODM ID 清单;null/空数组表示不限定。 */
|
||||
odm_ids?: string[] | null;
|
||||
notice_count: number;
|
||||
identifier_count: number;
|
||||
identity_evidence_count?: number;
|
||||
@@ -282,6 +284,8 @@ export interface ShippingCustomerFormState {
|
||||
short_code: string;
|
||||
status: ShippingCustomerStatus;
|
||||
remark: string;
|
||||
/** 文本域原文:每行一个 ODM ID;保存时解析为 odm_ids 数组。 */
|
||||
odm_ids_text: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
@@ -309,6 +313,7 @@ export const createEmptyShippingCustomerForm = (): ShippingCustomerFormState =>
|
||||
short_code: '',
|
||||
status: 'active',
|
||||
remark: '',
|
||||
odm_ids_text: '',
|
||||
reason: '',
|
||||
});
|
||||
|
||||
@@ -319,6 +324,7 @@ export const shippingCustomerToForm = (customer: ShippingCustomerRow): ShippingC
|
||||
short_code: customer.short_code,
|
||||
status: customer.status,
|
||||
remark: customer.remark || '',
|
||||
odm_ids_text: (customer.odm_ids || []).join('\n'),
|
||||
reason: '',
|
||||
});
|
||||
|
||||
|
||||
@@ -24,11 +24,57 @@ export interface ShippingMyTodosCount {
|
||||
processing: number;
|
||||
done: number;
|
||||
total_pending_badge: number;
|
||||
/** 待处理桶按可动作生命周期阶段的全量聚合计数(阶段筛选 tab)。 */
|
||||
stage_counts?: {
|
||||
intake_parse: number;
|
||||
order_review: number;
|
||||
fulfillment_prep: number;
|
||||
freight_upload: number;
|
||||
};
|
||||
/** done 桶终态拆分:通知完成 vs 复核驳回/作废。 */
|
||||
done_counts?: {
|
||||
upload_complete: number;
|
||||
reject_void: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** 已完成通知明细行(通知完成报表):标准 12 字段 + 溯源编号。 */
|
||||
export interface ShippingDoneLineItem {
|
||||
task_no: string;
|
||||
business_no: string | null;
|
||||
customer_name: string | null;
|
||||
customer_code: string | null;
|
||||
order_date: string | null;
|
||||
line_no: number;
|
||||
part_number: string | null;
|
||||
qty: number | null;
|
||||
required_date: string | null;
|
||||
customer_po_number: string | null;
|
||||
/** 无数据源,契约占位恒为 null(页面与导出留空)。 */
|
||||
used_qty: number | null;
|
||||
open_qty: number | null;
|
||||
source_order_number: string | null;
|
||||
unit_price: number | null;
|
||||
}
|
||||
|
||||
export interface ShippingDoneLinesPage {
|
||||
items: ShippingDoneLineItem[];
|
||||
page: number;
|
||||
page_size: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ShippingDoneLineFilters {
|
||||
customer?: string;
|
||||
part_number?: string;
|
||||
notice_date_from?: string;
|
||||
notice_date_to?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页拉取「我的待办」。
|
||||
* @param params.bucket - pending | processing | done
|
||||
* @param params.terminal_kind - done 桶终态子视图(upload_complete | reject_void)
|
||||
*/
|
||||
export function listWorkspaceShippingMyTodos(params?: {
|
||||
bucket?: 'pending' | 'processing' | 'done' | string;
|
||||
@@ -37,6 +83,7 @@ export function listWorkspaceShippingMyTodos(params?: {
|
||||
todo_category?: string;
|
||||
customer?: string;
|
||||
task_no?: string;
|
||||
terminal_kind?: string;
|
||||
}) {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.bucket) sp.set('bucket', params.bucket);
|
||||
@@ -45,6 +92,7 @@ export function listWorkspaceShippingMyTodos(params?: {
|
||||
if (params?.todo_category) sp.set('todo_category', params.todo_category);
|
||||
if (params?.customer) sp.set('customer', params.customer);
|
||||
if (params?.task_no) sp.set('task_no', params.task_no);
|
||||
if (params?.terminal_kind) sp.set('terminal_kind', params.terminal_kind);
|
||||
const q = sp.toString();
|
||||
return requestJson<ShippingMyTodosPage>(
|
||||
`/api/workspace/shipping-tasks/my-todos${q ? `?${q}` : ''}`,
|
||||
@@ -58,6 +106,68 @@ export function countWorkspaceShippingMyTodos() {
|
||||
return requestJson<ShippingMyTodosCount>('/api/workspace/shipping-tasks/my-todos/count');
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页拉取已完成通知的平铺明细行(通知完成报表)。
|
||||
* 明细行跨 Notice 混排、不按 OT 聚合,仅含已核验上传成功的通知。
|
||||
*/
|
||||
export function listWorkspaceShippingDoneLines(params?: {
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
} & ShippingDoneLineFilters) {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.page) sp.set('page', String(params.page));
|
||||
if (params?.page_size) sp.set('page_size', String(params.page_size));
|
||||
if (params?.customer) sp.set('customer', params.customer);
|
||||
if (params?.part_number) sp.set('part_number', params.part_number);
|
||||
if (params?.notice_date_from) sp.set('notice_date_from', params.notice_date_from);
|
||||
if (params?.notice_date_to) sp.set('notice_date_to', params.notice_date_to);
|
||||
const q = sp.toString();
|
||||
return requestJson<ShippingDoneLinesPage>(
|
||||
`/api/workspace/shipping-tasks/my-todos/done-lines${q ? `?${q}` : ''}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载当前筛选下的已完成通知明细 Excel(固定 12 列标准格式,不含 OT 编号)。
|
||||
* 核心逻辑:浏览器受控 a[download] 下载,后端复核可见性与筛选参数。
|
||||
*/
|
||||
export async function downloadWorkspaceShippingDoneLinesExcel(
|
||||
filters?: ShippingDoneLineFilters,
|
||||
): Promise<void> {
|
||||
const sp = new URLSearchParams();
|
||||
if (filters?.customer) sp.set('customer', filters.customer);
|
||||
if (filters?.part_number) sp.set('part_number', filters.part_number);
|
||||
if (filters?.notice_date_from) sp.set('notice_date_from', filters.notice_date_from);
|
||||
if (filters?.notice_date_to) sp.set('notice_date_to', filters.notice_date_to);
|
||||
const q = sp.toString();
|
||||
const url = `/api/workspace/shipping-tasks/my-todos/done-lines/export${q ? `?${q}` : ''}`;
|
||||
const { getAuthHeaders } = await import('@/shared/utils/auth');
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
(body as { error?: string; message?: string })?.error
|
||||
|| (body as { message?: string })?.message
|
||||
|| res.statusText,
|
||||
);
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition');
|
||||
const blob = await res.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = objectUrl;
|
||||
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'done-lines.xlsx';
|
||||
try {
|
||||
anchor.download = decodeURIComponent(rawName);
|
||||
} catch {
|
||||
anchor.download = rawName;
|
||||
}
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
document.body.removeChild(anchor);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
|
||||
export {
|
||||
downloadWorkspaceShippingExcelFile,
|
||||
markWorkspaceShippingManualUploaded,
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
<!--
|
||||
features/workspace/shipping-task-center/ShippingDoneLineReport.vue
|
||||
用途:已完成桶「通知完成」子视图——跨 OT 平铺的明细行报表(13 列 + 筛选 + 导出)。
|
||||
依赖:shipping-tasks.api 类型;导出下载由父级执行。
|
||||
逻辑:只读报表(无抽屉、无行操作);首列 OT/business 编号仅页面展示,
|
||||
导出为固定 12 列标准格式(后端裁决);分页按明细行计。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { Download } from 'lucide-vue-next';
|
||||
import type { ShippingDoneLineItem } from '@/features/workspace/api/shipping-tasks.api';
|
||||
import type { ShippingDoneLineFilters } from '@/features/workspace/api/shipping-tasks.api';
|
||||
|
||||
const props = defineProps<{
|
||||
items: ShippingDoneLineItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
loading?: boolean;
|
||||
exportBusy?: boolean;
|
||||
filters?: ShippingDoneLineFilters;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'update:filters', value: ShippingDoneLineFilters): void;
|
||||
(event: 'apply'): void;
|
||||
(event: 'page-change', page: number): void;
|
||||
(event: 'export'): void;
|
||||
}>();
|
||||
|
||||
const totalPages = () => Math.max(1, Math.ceil(props.total / props.pageSize));
|
||||
|
||||
function setFilter(key: keyof ShippingDoneLineFilters, event: Event) {
|
||||
const value = String((event.target as HTMLInputElement).value || '');
|
||||
emit('update:filters', { ...props.filters, [key]: value });
|
||||
}
|
||||
|
||||
function onExport(): void {
|
||||
emit('export');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-3">
|
||||
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3">
|
||||
<label class="space-y-1">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.customer') }}</span>
|
||||
<input
|
||||
type="text"
|
||||
class="input-field text-sm min-w-[10rem]"
|
||||
:value="filters?.customer || ''"
|
||||
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
|
||||
data-testid="done-lines-filter-customer"
|
||||
@change="setFilter('customer', $event)"
|
||||
@keyup.enter="emit('apply')"
|
||||
>
|
||||
</label>
|
||||
<label class="space-y-1">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.partNumber') }}</span>
|
||||
<input
|
||||
type="text"
|
||||
class="input-field text-sm min-w-[10rem]"
|
||||
:value="filters?.part_number || ''"
|
||||
data-testid="done-lines-filter-part"
|
||||
@change="setFilter('part_number', $event)"
|
||||
@keyup.enter="emit('apply')"
|
||||
>
|
||||
</label>
|
||||
<label class="space-y-1">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateFrom') }}</span>
|
||||
<input
|
||||
type="date"
|
||||
class="input-field text-sm"
|
||||
:value="filters?.notice_date_from || ''"
|
||||
data-testid="done-lines-filter-date-from"
|
||||
@change="setFilter('notice_date_from', $event)"
|
||||
>
|
||||
</label>
|
||||
<label class="space-y-1">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateTo') }}</span>
|
||||
<input
|
||||
type="date"
|
||||
class="input-field text-sm"
|
||||
:value="filters?.notice_date_to || ''"
|
||||
data-testid="done-lines-filter-date-to"
|
||||
@change="setFilter('notice_date_to', $event)"
|
||||
>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="emit('apply')"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl border border-brand-300 px-3 py-1.5 text-sm font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50"
|
||||
:disabled="exportBusy || loading || !total"
|
||||
data-testid="done-lines-export"
|
||||
@click="onExport"
|
||||
>
|
||||
<Download class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.doneReport.export') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!items.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.myTodos.empty') }}
|
||||
</div>
|
||||
<div v-else class="overflow-x-auto rounded-2xl border border-default bg-surface">
|
||||
<table class="w-full min-w-[1200px] border-collapse text-[13px]" data-testid="done-lines-table">
|
||||
<thead>
|
||||
<tr class="border-b border-default bg-surface-soft/60 text-left text-xs text-muted">
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.taskNo') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customer') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerCode') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.orderDate') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.lineNo') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.partNumber') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.qty') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.requiredDate') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerPo') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.usedQty') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.openQty') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.sourceOrderNo') }}</th>
|
||||
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.unitPrice') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="line in items"
|
||||
:key="`${line.task_no}-${line.line_no}`"
|
||||
class="border-b border-[#f0f3f8]"
|
||||
>
|
||||
<td class="px-3 py-2 font-mono text-xs font-semibold text-primary">
|
||||
{{ line.business_no || line.task_no }}
|
||||
</td>
|
||||
<td class="px-3 py-2">{{ line.customer_name || '—' }}</td>
|
||||
<td class="px-3 py-2">{{ line.customer_code || '—' }}</td>
|
||||
<td class="px-3 py-2 tabular-nums">{{ line.order_date || '—' }}</td>
|
||||
<td class="px-3 py-2 tabular-nums">{{ line.line_no }}</td>
|
||||
<td class="px-3 py-2 font-mono">{{ line.part_number || '—' }}</td>
|
||||
<td class="px-3 py-2 tabular-nums">{{ line.qty ?? '' }}</td>
|
||||
<td class="px-3 py-2 tabular-nums">{{ line.required_date || '—' }}</td>
|
||||
<td class="px-3 py-2">{{ line.customer_po_number || '—' }}</td>
|
||||
<td class="px-3 py-2 tabular-nums">{{ line.used_qty ?? '' }}</td>
|
||||
<td class="px-3 py-2 tabular-nums">{{ line.open_qty ?? '' }}</td>
|
||||
<td class="px-3 py-2 font-mono">{{ line.source_order_number || '—' }}</td>
|
||||
<td class="px-3 py-2 tabular-nums">{{ line.unit_price ?? '' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="totalPages() > 1" class="flex items-center justify-between gap-2 text-xs text-muted">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="page <= 1 || loading"
|
||||
@click="emit('page-change', page - 1)"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.pagination.previous') }}
|
||||
</button>
|
||||
<span>{{ page }}/{{ totalPages() }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="page >= totalPages() || loading"
|
||||
@click="emit('page-change', page + 1)"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.pagination.next') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,63 @@
|
||||
<!--
|
||||
features/workspace/shipping-task-center/ShippingStageTabs.vue
|
||||
用途:阶段筛选 tab(全部 + 四个可动作阶段),计数来自后端全量聚合。
|
||||
依赖:shippingTaskCenterShared 的 ACTIONABLE_TODO_STAGES 口径。
|
||||
逻辑:点击切换筛选并向上同步;「通知完成」不再作为筛选维度(归 done 桶终态子视图)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ACTIONABLE_TODO_STAGES, type LifecycleStageCode } from './shippingTaskCenterShared';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: 'all' | LifecycleStageCode;
|
||||
/** 后端聚合的阶段计数(缺省按 0 展示)。 */
|
||||
counts?: Partial<Record<LifecycleStageCode, number>>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'update:modelValue', value: 'all' | LifecycleStageCode): void;
|
||||
}>();
|
||||
|
||||
function countOf(stage: LifecycleStageCode): number {
|
||||
return Number(props.counts?.[stage] ?? 0);
|
||||
}
|
||||
|
||||
function stageLabel(stage: LifecycleStageCode): string {
|
||||
return t(`workspace.shippingNotice.myTodos.lifecycleStages.${stage}`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex flex-wrap gap-2"
|
||||
data-testid="my-todos-lifecycle-stage-filter"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors"
|
||||
:class="modelValue === 'all'
|
||||
? 'bg-brand-600 text-white'
|
||||
: 'border border-default text-secondary hover:bg-surface-soft'"
|
||||
data-testid="my-todos-stage-filter-all"
|
||||
@click="emit('update:modelValue', 'all')"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.all') }}
|
||||
</button>
|
||||
<button
|
||||
v-for="stage in ACTIONABLE_TODO_STAGES"
|
||||
:key="stage"
|
||||
type="button"
|
||||
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors"
|
||||
:class="modelValue === stage
|
||||
? 'bg-brand-600 text-white'
|
||||
: 'border border-default text-secondary hover:bg-surface-soft'"
|
||||
:data-testid="`my-todos-stage-filter-${stage}`"
|
||||
@click="emit('update:modelValue', stage)"
|
||||
>
|
||||
{{ stageLabel(stage) }}
|
||||
<span class="ml-1 font-mono text-xs opacity-80">{{ countOf(stage) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
+151
-30
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts
|
||||
* 用途:验收任务中心只按发货通知单 business_no 展示与执行货代批量操作。
|
||||
* 用途:验收任务中心改版——紧凑表格、货代上传阶段限定批量、阶段 tab 后端计数、
|
||||
* done 桶子视图(通知完成明细报表 / 驳回作废任务表)与详情抽屉。
|
||||
* 依赖:ShippingTaskCenterPage、货代 API、我的待办 API、Vue Test Utils。
|
||||
* 逻辑:正式 Notice 可选择并传 business_nos;Review/Intake 不能进入选择集;列表行只显示服务端投影的通知明细。
|
||||
* 逻辑:批量仅正式 Notice 且货代上传阶段可选;明细行详情进抽屉(Teleport 到 body);
|
||||
* 通知完成子视图消费 done-lines 平铺报表;驳回作废子视图带 terminal_kind 过滤。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
@@ -14,6 +16,11 @@ const batchConfirm = vi.fn(async () => ({ results: [{ status: 'confirmed' }] }))
|
||||
const batchRpa = vi.fn(async () => ({ results: [{ status: 'accepted' }] }));
|
||||
const downloadArchive = vi.fn(async () => undefined);
|
||||
const listTodos = vi.fn(async () => ({ items: [], page: 1, page_size: 20, total: 0 }));
|
||||
const listDoneLines = vi.fn(async () => ({ items: [], page: 1, page_size: 50, total: 0 }));
|
||||
const downloadDoneLinesExcel = vi.fn(async () => undefined);
|
||||
const countTodos = vi.fn(async () => ({
|
||||
pending: 0, processing: 0, done: 0, total_pending_badge: 0,
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
SHIPPING_NOTICE_AGENT_CODE: 'shipping_notice',
|
||||
@@ -26,7 +33,9 @@ vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
|
||||
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
|
||||
listWorkspaceShippingMyTodos: (...args: unknown[]) => listTodos(...args),
|
||||
countWorkspaceShippingMyTodos: vi.fn(async () => ({ pending: 0, processing: 0, done: 0, total_pending_badge: 0 })),
|
||||
countWorkspaceShippingMyTodos: (...args: unknown[]) => countTodos(...args),
|
||||
listWorkspaceShippingDoneLines: (...args: unknown[]) => listDoneLines(...args),
|
||||
downloadWorkspaceShippingDoneLinesExcel: (...args: unknown[]) => downloadDoneLinesExcel(...args),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/workspace/composables/useShippingTodoBadge', () => ({
|
||||
@@ -53,6 +62,7 @@ const i18n = createI18n({
|
||||
subtitle: '按文件查看进度',
|
||||
lifecycleStages: {
|
||||
filterLabel: '阶段',
|
||||
viewStage: '查看阶段',
|
||||
intake_parse: '接收解析',
|
||||
order_review: '订单复核',
|
||||
fulfillment_prep: '通知准备',
|
||||
@@ -60,6 +70,12 @@ const i18n = createI18n({
|
||||
upload_complete: '通知完成',
|
||||
},
|
||||
buckets: { pending: '待处理', processing: '处理中', done: '已完成' },
|
||||
subTabs: { uploadComplete: '通知完成', rejectVoid: '复核驳回 / 已作废' },
|
||||
table: {
|
||||
no: '编号', stage: '阶段', summary: '状态摘要', lines: '项次',
|
||||
lineUnit: '项', shortage: '缺 {count}', freightStatus: '货代状态',
|
||||
},
|
||||
terminal: { uploadComplete: '上传完成', rejectVoid: '复核驳回' },
|
||||
filters: {
|
||||
todoCategory: '待办类型', all: '全部', review: '待复核', exception: '异常',
|
||||
manualUpload: '人工上传', intakeParse: '接收解析', customer: '客户',
|
||||
@@ -75,9 +91,44 @@ const i18n = createI18n({
|
||||
intakeParseBadge: '材料解析',
|
||||
progressSummary: '当前阶段:{stage}',
|
||||
progressBlocker: '当前阻断:{reason}',
|
||||
viewStage: '查看阶段',
|
||||
drawer: {
|
||||
details: '逐行明细',
|
||||
files: '文件',
|
||||
close: '关闭',
|
||||
exportExcel: '导出 Excel',
|
||||
lineTable: {
|
||||
lineNo: '行', partNumber: '料号', customerPartNumber: '客户料号',
|
||||
reservationId: '预约号', shipmentQty: '本次发货', availableQty: '可用库存',
|
||||
shortageQty: '缺口', status: '状态',
|
||||
},
|
||||
},
|
||||
doneReport: {
|
||||
export: '导出 Excel(当前筛选)',
|
||||
exportStarted: '已开始下载',
|
||||
filters: { customer: '客户', partNumber: '料号', dateFrom: '通知日期起', dateTo: '通知日期止' },
|
||||
columns: {
|
||||
taskNo: 'OT 编号', customer: '客户', customerCode: '客户编号', orderDate: '订单日期',
|
||||
lineNo: '订单项次', partNumber: '料号', qty: '数量', requiredDate: '约定出货日期',
|
||||
customerPo: '客户PO', usedQty: '已用数量', openQty: 'open qty',
|
||||
sourceOrderNo: '订单单号', unitPrice: '单价',
|
||||
},
|
||||
},
|
||||
},
|
||||
openChat: '打开对话',
|
||||
batch: {
|
||||
selectAll: '全选当前页通知单',
|
||||
selected: '已选 {count} 张',
|
||||
download: '批量下载 Excel',
|
||||
confirm: '批量确认已上传',
|
||||
rpa: '批量发起 RPA',
|
||||
clearSelection: '清除选择',
|
||||
downloadStarted: '已开始下载',
|
||||
success: '成功 {count} 张',
|
||||
partialResult: '部分成功 {accepted}/{accepted}/{blocked}',
|
||||
},
|
||||
todo: { adminViewOnlyShort: '只读' },
|
||||
actions: { failed: '操作失败' },
|
||||
pagination: { previous: '上一页', next: '下一页' },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -90,12 +141,17 @@ const routes = [{
|
||||
component: ShippingTaskCenterPage,
|
||||
}];
|
||||
|
||||
/** 待处理货代上传阶段 Notice:批量可选 + 列表投影。 */
|
||||
function notice(businessNo: string, poNumber: string, partNumber: string) {
|
||||
return {
|
||||
id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo,
|
||||
item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave',
|
||||
po_number: poNumber, customer_name: 'Customer', upload_status: 'pending',
|
||||
notice_line_summary: [{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }],
|
||||
ui_state: { stage: { code: 'freight_upload', label: '货代上传' }, lifecycle_entries: [] },
|
||||
notice_line_summary: [
|
||||
{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' },
|
||||
{ line_no: '20', part_number: `${partNumber}-B`, shipment_qty: '2', available_qty: '9', shortage_qty: 1 },
|
||||
],
|
||||
artifact_summary: { export_file_name: `${businessNo}.xlsx` },
|
||||
};
|
||||
}
|
||||
@@ -115,12 +171,17 @@ async function mountPage() {
|
||||
});
|
||||
}
|
||||
|
||||
function drawerText(): string {
|
||||
return document.body.querySelector('[data-testid="my-todos-drawer"]')?.textContent || '';
|
||||
}
|
||||
|
||||
describe('ShippingTaskCenterPage notice batch operations', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('only makes formal Notices selectable and displays each Notice projection', async () => {
|
||||
it('only makes freight-upload Notices selectable and shows line details in drawer', async () => {
|
||||
listTodos.mockResolvedValueOnce({
|
||||
items: [
|
||||
notice('WYC26082301', 'PO-100', 'PART-A'),
|
||||
@@ -132,13 +193,20 @@ describe('ShippingTaskCenterPage notice batch operations', () => {
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
|
||||
// 断言:货代上传阶段 Notice 可勾选;Review/Intake 行无复选框。
|
||||
expect(wrapper.get('[aria-label="WYC26082301"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[aria-label="WYC26082302"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[aria-label="SNRC-30"]').exists()).toBe(false);
|
||||
// 断言:表格副行展示 客户 · PO · 文件。
|
||||
expect(wrapper.text()).toContain('PO-100');
|
||||
expect(wrapper.text()).toContain('PART-A');
|
||||
expect(wrapper.text()).toContain('PART-B');
|
||||
expect(wrapper.text()).toContain('WYC26082301.xlsx');
|
||||
// 断言:点行打开抽屉,逐行明细承载料号(列表不再堆明细)。
|
||||
await wrapper.get('[data-testid="my-todos-row-WYC26082301"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(document.body.querySelector('[data-testid="my-todos-drawer"]')).not.toBeNull();
|
||||
const drawer = drawerText();
|
||||
expect(drawer).toContain('PART-A');
|
||||
expect(drawer).toContain('PART-A-B');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
@@ -152,53 +220,106 @@ describe('ShippingTaskCenterPage notice batch operations', () => {
|
||||
await wrapper.get('[aria-label="WYC26082301"]').setValue(true);
|
||||
await wrapper.get('[aria-label="WYC26082302"]').setValue(true);
|
||||
|
||||
const toolbar = wrapper.get('[data-testid="shipping-notice-batch-toolbar"]');
|
||||
const buttons = toolbar.findAll('button');
|
||||
// 断言:勾选后浮出操作条,三个动作按序对应 download/confirm/rpa。
|
||||
// 每次 action 后列表会静默重载(表格重挂载),因此逐次重新查询按钮。
|
||||
const toolbarButtons = () => wrapper
|
||||
.get('[data-testid="shipping-notice-batch-toolbar"]')
|
||||
.findAll('button');
|
||||
const buttons = toolbarButtons();
|
||||
expect(buttons.length).toBeGreaterThanOrEqual(3);
|
||||
await buttons[0].trigger('click');
|
||||
expect(downloadArchive).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
|
||||
|
||||
await buttons[1].trigger('click');
|
||||
await flushPromises();
|
||||
await toolbarButtons()[1].trigger('click');
|
||||
await flushPromises();
|
||||
expect(batchConfirm).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
|
||||
|
||||
await buttons[2].trigger('click');
|
||||
await toolbarButtons()[2].trigger('click');
|
||||
await flushPromises();
|
||||
expect(batchRpa).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('keeps all five lifecycle stage filters on one wide-screen row', async () => {
|
||||
it('renders one row of stage tabs covering all plus four actionable stages', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
|
||||
const track = wrapper.get('[data-testid="my-todos-lifecycle-stage-filter"]');
|
||||
expect(track.classes()).toContain('xl:grid-cols-5');
|
||||
// 断言:全部 + 四个可动作阶段;「通知完成」不再是筛选维度。
|
||||
expect(track.findAll('button')).toHaveLength(5);
|
||||
expect(track.text()).toContain('货代上传');
|
||||
expect(track.text()).not.toContain('通知完成');
|
||||
expect(track.text()).not.toContain('workspace.shippingNotice.myTodos.lifecycleStages.freight_upload');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('counts a pending review item from its backend stage even without an enterable lifecycle entry', async () => {
|
||||
listTodos.mockResolvedValueOnce({
|
||||
items: [{
|
||||
item_kind: 'review_case',
|
||||
task_no: '',
|
||||
review_run_no: 'RUN-1',
|
||||
review_case_no: 'CASE-1',
|
||||
ui_state: {
|
||||
stage: { code: 'order_review', label: '订单复核', index: 2, total: 5 },
|
||||
lifecycle_entries: [],
|
||||
},
|
||||
}],
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
total: 1,
|
||||
it('shows backend aggregated stage counts instead of current-page counting', async () => {
|
||||
countTodos.mockResolvedValueOnce({
|
||||
pending: 13, processing: 0, done: 0, total_pending_badge: 13,
|
||||
stage_counts: { intake_parse: 2, order_review: 4, fulfillment_prep: 3, freight_upload: 4 },
|
||||
done_counts: { upload_complete: 0, reject_void: 0 },
|
||||
});
|
||||
listTodos.mockResolvedValueOnce({ items: [], page: 1, page_size: 20, total: 0 });
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('1');
|
||||
// 断言:阶段计数来自后端聚合(当前页为空列表也显示全量计数)。
|
||||
expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('4');
|
||||
expect(wrapper.get('[data-testid="my-todos-stage-filter-fulfillment_prep"]').text()).toContain('3');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('defaults done bucket to the flat done-lines report and exports current filters', async () => {
|
||||
listDoneLines.mockResolvedValue({
|
||||
items: [{
|
||||
task_no: 'SN-DONE-1', business_no: 'BIZ-1', customer_name: 'HYVE CS', customer_code: 'HC001',
|
||||
order_date: '2026-06-01', line_no: 1, part_number: 'B3-A08AR1', qty: 80,
|
||||
required_date: '2026-06-15', customer_po_number: '306085', used_qty: null,
|
||||
open_qty: null, source_order_number: '8301-1', unit_price: 1525.08,
|
||||
}],
|
||||
page: 1, page_size: 50, total: 1,
|
||||
});
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 断言:done 桶默认进入通知完成明细报表,消费 done-lines 接口。
|
||||
expect(listDoneLines).toHaveBeenCalled();
|
||||
const table = wrapper.get('[data-testid="done-lines-table"]');
|
||||
expect(table.text()).toContain('B3-A08AR1');
|
||||
expect(table.text()).toContain('8301-1');
|
||||
// 断言:导出按钮把当前筛选交给受控下载。
|
||||
await wrapper.get('[data-testid="done-lines-export"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(downloadDoneLinesExcel).toHaveBeenCalled();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('loads reject_void sub tab with terminal_kind filter and badges rows', async () => {
|
||||
listTodos.mockResolvedValue({
|
||||
items: [{
|
||||
id: 41, task_no: 'SN-REJ-1', business_no: 'BIZ-R1', item_kind: 'task',
|
||||
todo_ref: 'SN-REJ-1', todo_category: 'done',
|
||||
ui_state: { stage: { code: 'upload_complete', label: '通知完成' }, lifecycle_entries: [] },
|
||||
}],
|
||||
page: 1, page_size: 20, total: 1,
|
||||
});
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click');
|
||||
await flushPromises();
|
||||
const subtabs = wrapper.findAll('[data-testid="my-todos-done-subtabs"] button');
|
||||
await subtabs[1].trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 断言:驳回/作废子视图按 terminal_kind 拉任务表,行带终态角标。
|
||||
expect(listTodos).toHaveBeenCalledWith(expect.objectContaining({
|
||||
bucket: 'done',
|
||||
terminal_kind: 'reject_void',
|
||||
}));
|
||||
expect(wrapper.get('[data-testid="my-todos-row-BIZ-R1"]').text()).toContain('复核驳回');
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user