feat(shipping-notice): 货代会话主区域切换为批次中心常驻并按附件派生会话标题
- 会话命名:新增业务命名纯函数,新建抽取会话按附件内容派生标题,仅新建不回填不改名 - 批次中心常驻主区域并展示会话标题:移除关闭入口、隐藏对话列、去除面板外壳与折叠/钉住徽标 - 清理对话流打开批次中心的冗余链路 - 新增设计文档与实施计划,同步功能清单说明
This commit is contained in:
1 parent
d396371020
commit
e472abc4e3
21 files changed
+1198
-206
No files matched your search
@@ -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]
|
||||
@@ -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(),
|
||||
|
||||
@@ -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,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 == '订单抽取'
|
||||
Reference in new issue
Block a user