""" 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]