405 lines
16 KiB
Python
405 lines
16 KiB
Python
"""
|
||
转人工:缺项连问计数、虚拟工单号、正式单兜底、空运群提交、入口/冻结判定。
|
||
|
||
职责边界:
|
||
- 纯函数与轻量序号(补问计数、VT 号);不直接改六态。
|
||
- 转人工改用 collab_mode=handoff 表达「产品群内手工报价」,禁止再写六态「转人工」——
|
||
那会把报价和群消息一起冻死。
|
||
- 空运群提交(try_commit_air_group_handoff)会发一条摘要、绑群、登记会话存档监听。
|
||
|
||
调用:Worker / 私聊流程 / 群入站。禁止在回调线程里同步建群或等模型。
|
||
为何独立:海运/陆运/空运共用同一套计数与号码,避免三份 if。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import threading
|
||
import uuid
|
||
from datetime import datetime
|
||
from typing import Any, Optional
|
||
from zoneinfo import ZoneInfo
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||
|
||
# 新询价第一次补问不计数;之后同一批缺项再问满 3 次仍不齐,第 3 次出入口。
|
||
CLARIFY_LIMIT = 3
|
||
VIRTUAL_PREFIX = "VT"
|
||
|
||
# 陆运类型+线路还对不上时,转人工摘要仍列出这一套协同项,全部为「-」。
|
||
_LAND_HANDOFF_COLLAB_FALLBACK = (
|
||
"客户名称",
|
||
"HS编码",
|
||
"贸易条款",
|
||
"包装方式",
|
||
"是否为危险品",
|
||
)
|
||
|
||
_seq_lock = threading.Lock()
|
||
_seq_by_day: dict[str, int] = {}
|
||
|
||
HANDOFF_STATUS = "转人工"
|
||
TERMINAL_STATUSES = frozenset({"已成交", "未成交", "已关闭", HANDOFF_STATUS})
|
||
FROZEN_STATUSES = frozenset({HANDOFF_STATUS})
|
||
|
||
# 协同模式:与主账 inq_ticket.collab_mode 同义。
|
||
# auto=系统自动协同;handoff=销售转人工,产品在群里手工报价。
|
||
COLLAB_MODE_AUTO = "auto"
|
||
COLLAB_MODE_HANDOFF = "handoff"
|
||
|
||
|
||
def is_handoff_collab(sess: Any) -> bool:
|
||
"""这一路是否转人工协同。转人工协同不是六态冻结,群报价要照常收。"""
|
||
return str(getattr(sess, "collab_mode", "") or "").strip().lower() == COLLAB_MODE_HANDOFF
|
||
|
||
|
||
def missing_signature(keys: list[str] | tuple[str, ...] | None) -> str:
|
||
"""缺项集合签名:顺序无关,用来判断是不是同一批。"""
|
||
return "|".join(sorted({str(k).strip() for k in (keys or []) if str(k).strip()}))
|
||
|
||
|
||
def note_clarify_round(sess: Any, missing_keys: list[str] | tuple[str, ...] | None) -> str:
|
||
"""
|
||
记下本轮缺项。返回 ask(继续补问)或 handoff(该出转人工入口)。
|
||
|
||
新询价(或缺项集合刚变)的第一次补问不计数、不打(1/3)。
|
||
之后同一签名再问:1/3、2/3;第 3 次仍不齐返回 handoff(调用方先发 3/3 再出入口)。
|
||
签名变了:计数清零,并作废「3 次反问」那张入口(handoff_offer=clarify)。
|
||
副作用:改 sess.clarify_* / 可能清 handoff_offer。
|
||
"""
|
||
sig = missing_signature(missing_keys)
|
||
if not sig:
|
||
if getattr(sess, "handoff_offer", "") == "clarify":
|
||
sess.handoff_offer = ""
|
||
sess.clarify_missing_sig = ""
|
||
sess.clarify_retry = 0
|
||
return "ask"
|
||
prev = str(getattr(sess, "clarify_missing_sig", "") or "")
|
||
retry = int(getattr(sess, "clarify_retry", 0) or 0)
|
||
if prev == sig:
|
||
retry = retry + 1
|
||
sess.clarify_retry = retry
|
||
if retry >= CLARIFY_LIMIT:
|
||
return "handoff"
|
||
return "ask"
|
||
if str(getattr(sess, "handoff_offer", "") or "") == "clarify":
|
||
sess.handoff_offer = ""
|
||
sess.clarify_missing_sig = sig
|
||
sess.clarify_retry = 0
|
||
return "ask"
|
||
|
||
|
||
def next_virtual_no(*, now: datetime | None = None) -> str:
|
||
"""
|
||
虚拟工单号:VT + 上海日历日 8 位 + 当日 4 位流水。
|
||
|
||
不占正式 WO。进程内计数;有 Redis 时尽量用 INCR,失败则回退内存。
|
||
"""
|
||
day = (now or datetime.now(_SHANGHAI)).strftime("%Y%m%d")
|
||
seq = _next_seq(day)
|
||
return f"{VIRTUAL_PREFIX}{day}{seq:04d}"
|
||
|
||
|
||
def _next_seq(day: str) -> int:
|
||
try:
|
||
from agent.config import get_settings
|
||
from agent.redis_coord.keys import join_key
|
||
|
||
settings = get_settings()
|
||
raw = getattr(settings, "redis_url", "") or ""
|
||
prefix = getattr(settings, "redis_key_prefix", "") or "inquiry_robot:"
|
||
if raw:
|
||
import redis
|
||
|
||
client = redis.Redis.from_url(raw, socket_timeout=2, socket_connect_timeout=2)
|
||
key = join_key(prefix, "vtseq", day)
|
||
n = int(client.incr(key))
|
||
client.expire(key, 3 * 24 * 3600)
|
||
return n
|
||
except Exception:
|
||
logger.info("虚拟号 Redis 序号不可用,改用进程内计数 day=%s", day)
|
||
with _seq_lock:
|
||
n = _seq_by_day.get(day, 0) + 1
|
||
_seq_by_day[day] = n
|
||
return n
|
||
|
||
|
||
def reset_virtual_seq_for_test() -> None:
|
||
"""单测重置当日流水。"""
|
||
with _seq_lock:
|
||
_seq_by_day.clear()
|
||
|
||
|
||
def is_virtual_no(work_order_no: str) -> bool:
|
||
raw = (work_order_no or "").strip().upper()
|
||
return raw.startswith(VIRTUAL_PREFIX) and len(raw) >= 10
|
||
|
||
|
||
def is_frozen_status(status: str) -> bool:
|
||
return (status or "").strip() in FROZEN_STATUSES
|
||
|
||
|
||
def is_handoff_frozen(sess: Any) -> bool:
|
||
"""这一票已经真正转人工,私聊不应再把它当当前询价。"""
|
||
if sess is None:
|
||
return False
|
||
if bool(getattr(sess, "handoff_committed", False)):
|
||
return True
|
||
return is_frozen_status(str(getattr(sess, "status", "") or ""))
|
||
|
||
|
||
def is_closed_for_handoff(status: str) -> bool:
|
||
"""已成交/未成交/已关闭不再出转人工入口。转人工本身也不再重复入口。"""
|
||
st = (status or "").strip()
|
||
return st in {"已成交", "未成交", "已关闭", HANDOFF_STATUS}
|
||
|
||
|
||
def display_ticket_no(sess: Any) -> str:
|
||
"""群/卡片展示号:转人工正式号 → 正式号 → 虚拟号。"""
|
||
return (
|
||
str(getattr(sess, "handoff_work_order_no", "") or "").strip()
|
||
or str(getattr(sess, "work_order_no", "") or "").strip()
|
||
or str(getattr(sess, "virtual_work_order_no", "") or "").strip()
|
||
)
|
||
|
||
|
||
def ensure_virtual_no(sess: Any) -> str:
|
||
"""还没有正式号时确保有虚拟号。已有正式号不生成。"""
|
||
real = str(getattr(sess, "work_order_no", "") or "").strip()
|
||
if real:
|
||
return real
|
||
vt = str(getattr(sess, "virtual_work_order_no", "") or "").strip()
|
||
if vt:
|
||
return vt
|
||
vt = next_virtual_no()
|
||
sess.virtual_work_order_no = vt
|
||
return vt
|
||
|
||
|
||
# 这些阶段还没为本票建正式单,转人工入口必须用虚拟号。
|
||
_PRE_CREATE_PHASES = frozenset(
|
||
{
|
||
"",
|
||
"idle",
|
||
"clarify",
|
||
"need_mode",
|
||
"need_land_options",
|
||
"wait_confirm",
|
||
"handoff_offer",
|
||
}
|
||
)
|
||
|
||
|
||
def ticket_no_for_handoff_offer(sess: Any) -> str:
|
||
"""
|
||
转人工入口上给销售看的号码。
|
||
|
||
已经为本票建过转人工正式单:直接给 WO。
|
||
本票还在补问/核对本、没建正式单:给 VT,丢掉会话里挂着的旧 WO。
|
||
已经出过正式单(已报价/协同中等):沿用 WO。
|
||
"""
|
||
hno = str(getattr(sess, "handoff_work_order_no", "") or "").strip()
|
||
if hno and not is_virtual_no(hno):
|
||
return hno
|
||
phase = str(getattr(sess, "phase", "") or "").strip()
|
||
real = str(getattr(sess, "work_order_no", "") or "").strip()
|
||
if real and not is_virtual_no(real) and phase not in _PRE_CREATE_PHASES:
|
||
return real
|
||
if real and not is_virtual_no(real):
|
||
sess.work_order_no = ""
|
||
return ensure_virtual_no(sess)
|
||
|
||
|
||
def ensure_formal_ticket_for_handoff(
|
||
flow: Any,
|
||
sess: Any,
|
||
*,
|
||
business_line: str = "",
|
||
biz_type_label: str = "",
|
||
) -> str:
|
||
"""
|
||
转人工前确保本票有正式工单号;没有就现在建。
|
||
|
||
为什么要建:空运不自动建群,销售要把航线和智能体拉进原空运群并「发工单号」;
|
||
陆运/海运建群也要群名、模板、报价版本都能对上一张真单。给虚拟号会让产品在后台
|
||
搜不到,群里报的价也挂不上,等于白转。
|
||
已建过正式号直接返回;建单失败退回虚拟号,流程不至于断。
|
||
副作用:可能新开一张 inq_ticket(collab_mode=handoff),并写 sess.handoff_work_order_no。
|
||
"""
|
||
real = str(getattr(sess, "handoff_work_order_no", "") or "").strip()
|
||
if real and not is_virtual_no(real):
|
||
return real
|
||
# 本票已经出过正式单(已报价/协同中等):沿用,禁止再开一张。
|
||
# 补问阶段的 work_order_no 可能是上一张单,不能沿用(和 ticket_no_for_handoff_offer 同口径)。
|
||
phase = str(getattr(sess, "phase", "") or "").strip()
|
||
existing = str(getattr(sess, "work_order_no", "") or "").strip()
|
||
if existing and not is_virtual_no(existing) and phase not in _PRE_CREATE_PHASES:
|
||
sess.handoff_work_order_no = existing
|
||
return existing
|
||
book = getattr(flow, "ledger", None)
|
||
creator = getattr(book, "create_ticket", None)
|
||
if not callable(creator):
|
||
return ensure_virtual_no(sess)
|
||
line = (business_line or getattr(sess, "business_line", "") or "").strip().upper()
|
||
if not line:
|
||
line = "AIR"
|
||
sender = str(getattr(sess, "sender_id", "") or "").strip()
|
||
try:
|
||
out = creator(
|
||
sender_id=sender,
|
||
business_line=line,
|
||
facts=dict(getattr(sess, "facts", {}) or {}),
|
||
idempotency_key=f"handoff-create:{sender}:{uuid.uuid4().hex}",
|
||
biz_type_label=(biz_type_label or "").strip(),
|
||
collab_mode=COLLAB_MODE_HANDOFF,
|
||
) or {}
|
||
except Exception:
|
||
logger.exception("转人工建正式单失败 sender=%s line=%s", sender or "-", line)
|
||
return ensure_virtual_no(sess)
|
||
no = str(out.get("work_order_no") or "").strip()
|
||
if not no:
|
||
logger.warning("转人工建正式单未返回工单号 sender=%s line=%s out=%s", sender or "-", line, out)
|
||
return ensure_virtual_no(sess)
|
||
# 旧书签上挂的工单号不是本票(补问阶段常见),留着会被当成当前单去补字段。
|
||
stale = str(getattr(sess, "work_order_no", "") or "").strip()
|
||
if stale and stale.upper() != no.upper():
|
||
sess.work_order_no = ""
|
||
sess.handoff_work_order_no = no
|
||
void_virtual_no(sess)
|
||
return no
|
||
|
||
|
||
def inherit_pre_create_ticket(sess: Any, new_sess: Any) -> None:
|
||
"""
|
||
同一轮补问可以接着用号;从已出票旧书签开新补问则不带旧 WO/群。
|
||
"""
|
||
prev = str(getattr(sess, "phase", "") or "").strip()
|
||
if prev not in _PRE_CREATE_PHASES:
|
||
return
|
||
if not str(getattr(new_sess, "work_order_no", "") or "").strip():
|
||
new_sess.work_order_no = str(getattr(sess, "work_order_no", "") or "").strip()
|
||
if not str(getattr(new_sess, "collab_chat_id", "") or "").strip():
|
||
new_sess.collab_chat_id = str(getattr(sess, "collab_chat_id", "") or "").strip()
|
||
# 转人工正式号与协同模式跟着补问轮次走,否则第二轮就退回虚拟号/自动协同。
|
||
if not str(getattr(new_sess, "handoff_work_order_no", "") or "").strip():
|
||
new_sess.handoff_work_order_no = str(
|
||
getattr(sess, "handoff_work_order_no", "") or ""
|
||
).strip()
|
||
if not str(getattr(new_sess, "collab_mode", "") or "").strip():
|
||
new_sess.collab_mode = str(getattr(sess, "collab_mode", "") or "").strip()
|
||
|
||
|
||
def void_virtual_no(sess: Any) -> None:
|
||
"""正式建单后作废虚拟号。"""
|
||
sess.virtual_work_order_no = ""
|
||
|
||
|
||
def has_collab_group(sess: Any) -> bool:
|
||
return bool(str(getattr(sess, "collab_chat_id", "") or "").strip())
|
||
|
||
|
||
def transport_label(business_line: str) -> str:
|
||
code = (business_line or "").strip().upper()
|
||
return {"SEA": "海运", "AIR": "空运", "LAND": "陆运"}.get(code, "")
|
||
|
||
|
||
def try_commit_air_group_handoff(flow: Any, *, chat_id: str, work_order_no: str) -> str:
|
||
"""
|
||
空运群里出现待转人工的工单号:发转人工摘要并进入人工协同。
|
||
|
||
改造要点(2026-11 转人工群报价):
|
||
- 不把六态写成「转人工」。写进去会冻结报价、群消息也被当冻结单丢掉;
|
||
产品在群里报的价必须能落账,六态照常 询价中 → 已报价。
|
||
- 用主账 collab_mode=handoff 记住「这一单是人工协同」,报价只留档、不发成交跟进。
|
||
- 停止原来的自动报价等待监控,避免转人工后还在催产品走系统价。
|
||
|
||
对不上或虚拟号已作废:返回空,交给原激活逻辑。
|
||
"""
|
||
no = (work_order_no or "").strip().upper()
|
||
if not no:
|
||
return ""
|
||
getter = getattr(flow, "session_by_work_order", None)
|
||
sess = getter(no) if callable(getter) else None
|
||
if sess is None:
|
||
return ""
|
||
if not sess.handoff_offer or sess.handoff_committed:
|
||
return ""
|
||
display = display_ticket_no(sess).upper()
|
||
if display != no:
|
||
return ""
|
||
from agent.policy import inquiry_copy as copy
|
||
from agent.policy.sea_group_ops import group_client_of, send_group_text
|
||
|
||
book = getattr(flow, "ledger", None)
|
||
airline_names: list[str] = []
|
||
lister = getattr(book, "list_staff_by_role", None) if book else None
|
||
if callable(lister):
|
||
try:
|
||
for row in lister(role_code="air") or []:
|
||
name = str(row.get("name") or "").strip()
|
||
if name:
|
||
airline_names.append(name)
|
||
except Exception:
|
||
logger.exception("空运转人工取航线名单失败")
|
||
sales = ""
|
||
namer = getattr(flow, "_sales_display_name", None)
|
||
if callable(namer):
|
||
sales = namer(sess.sender_id)
|
||
brief = copy.handoff_group_brief(
|
||
work_order_no=display_ticket_no(sess),
|
||
facts=sess.facts,
|
||
business_line="AIR",
|
||
sales_name=sales,
|
||
airline_names=airline_names,
|
||
)
|
||
send_group_text(group_client_of(flow), chat_id, brief)
|
||
real = display_ticket_no(sess)
|
||
if real and not is_virtual_no(real):
|
||
binder = getattr(book, "bind_collab_group", None) if book else None
|
||
if callable(binder):
|
||
try:
|
||
binder(
|
||
work_order_no=real,
|
||
chat_id=chat_id,
|
||
member_ids=[],
|
||
collab_mode=COLLAB_MODE_HANDOFF,
|
||
)
|
||
except Exception:
|
||
# 绑群失败不能把摘要/会话状态一起回滚:下次激活还会再绑。
|
||
logger.exception("空运转人工绑群失败 wo=%s chat=%s", real, chat_id)
|
||
from agent.policy.event_exception import clear_wait
|
||
|
||
clear_wait(book, work_order_no=real)
|
||
# 空运转人工不走 activate_ticket,必须在这里登记会话存档监听;
|
||
# 否则产品在群里发的文字/文件系统根本收不到,等于没转。
|
||
try:
|
||
from agent.channel.wshoto.rooms import watch_collab_room
|
||
|
||
watch_collab_room(chat_id, work_order_no=real)
|
||
except Exception:
|
||
logger.exception("空运转人工登记存档监听失败 chat=%s wo=%s", chat_id, real)
|
||
sess.collab_mode = COLLAB_MODE_HANDOFF
|
||
sess.handoff_committed = True
|
||
sess.handoff_offer = ""
|
||
sess.phase = "handoff_done"
|
||
sess.collab_chat_id = chat_id
|
||
saver = getattr(flow, "_save", None)
|
||
if callable(saver):
|
||
saver(sess)
|
||
return "handoff_done"
|
||
|
||
|
||
def collab_keys_for_handoff(facts: dict[str, str] | None, business_line: str) -> tuple[str, ...]:
|
||
"""转人工摘要要列出的协同键;对不上陆运套餐时用兜底五项。"""
|
||
from agent.schema.field_validate import SEA_COLLAB_FIELDS, collab_fields_for_ticket
|
||
|
||
line = (business_line or "").strip().upper()
|
||
keys = collab_fields_for_ticket(facts, line)
|
||
if keys:
|
||
return keys
|
||
if line == "LAND":
|
||
return _LAND_HANDOFF_COLLAB_FALLBACK
|
||
return SEA_COLLAB_FIELDS
|