Files
inquiry_robot/inquiry-agent/agent/handlers/group_collab.py
T
linmianxun 04e00f0cfc checkpoint: 提交当前工作区代码(同义词配置初版 + 既有流程改动)
- 新增 inq_synonym 表、62组同义词种子与智能体只读接口
- Python 同义词加载/归一化与 1板/2箱 机读
- 同步当前分支既有协作、报价识别、陆运等改动
2026-11-24 16:26:49 +08:00

531 lines
18 KiB
Python

"""
意图:海运协同群入站(文字意图 / 附件)。
本文件职责:对上工单后交给 sea_group_ops;一类动作一条分支。
禁止:改询价七项;终态装没看见;把销售附件当报价。
"""
from __future__ import annotations
import logging
from typing import Any, Optional
from agent.channel.wecom.models import InboundMessage
from agent.policy.sea_group_ops import (
apply_collab_update,
apply_confirm_tms_quote,
apply_group_deal,
apply_product_quote,
apply_tms_quote_choice,
capture_group_lost_reason,
dissolve_group,
dissolve_orphan_group,
group_client_of,
handle_group_file,
hydrate_ticket,
is_handoff_ticket,
peek_pending_product_quote,
send_group_text,
ticket_no,
ticket_view,
)
from agent.policy.sea_text_flow import get_sea_text_flow
logger = logging.getLogger(__name__)
def handle_group_collab(
message: InboundMessage,
*,
flow=None,
ledger=None,
injected_intent: str = "",
injected_quote: Optional[dict[str, Any]] = None,
) -> str:
"""
处理一条群聊入站。兼容旧测试名。
必须能对上已绑定工单,且发言人是被拉进来的销售或产品。
"""
return handle_group_inbound(
message,
flow=flow,
ledger=ledger,
injected_intent=injected_intent,
injected_quote=injected_quote,
)
def handle_group_inbound(
message: InboundMessage,
*,
flow=None,
ledger=None,
injected_intent: str = "",
injected_quote: Optional[dict[str, Any]] = None,
) -> str:
"""
群里一条文字或附件。
文字走 DeepSeek A(单测可注入);附件只看扩展名。
已成交/未成交/已关闭要回话。真正转人工后群里不再跟、不回。
"""
if (message.chat_type or "") != "group":
return "group_ignore"
if not message.has_sender():
return "reject_no_sender"
engine = flow or get_sea_text_flow()
book = ledger or engine.ledger
chat_id = (message.chat_id or "").strip()
if not chat_id:
return "group_ignore"
ticket = _find_ticket(book, chat_id)
if ticket is None:
logger.info("group_inbound 对不上工单 chat=%s", chat_id)
# 老群/迁库丢绑定:对不上工单时,「解散群」仍按企微当前成员清人。
from agent.routing.group_intent import INTENT_DISSOLVE, classify_group_text
kind_orphan = (message.msg_type or "text").lower()
if kind_orphan in {"", "text"} and (
classify_group_text(message.content or "", injected=injected_intent)
== INTENT_DISSOLVE
):
conflict = _room_ticket_conflict(book, chat_id)
if conflict:
# Redis 说本群是某张单的,但那张单主账上绑的是别的群:脏索引。
# 按孤儿清群会误踢真实协同群成员,这里只记日志不动手。
logger.warning(
"group_inbound 房间索引与本群绑群冲突,拒绝孤儿解散 chat=%s room_wo=%s",
chat_id,
conflict,
)
return "group_ignored"
logger.info(
"group_inbound 无工单仍解散 chat=%s sender=%s",
chat_id,
message.sender_id,
)
return dissolve_orphan_group(
flow=engine,
chat_id=chat_id,
sender_id=message.sender_id or "",
)
# BOT 群已 @ 了机器人,但对不上任何工单:按产品口径提示重新下达任务,
# 不能装没听见(此时 dispatch 已保证这条是 @BOT 的文字)。
from agent.redis_coord.group_bot import is_group_bot
if (
is_group_bot(chat_id)
and kind_orphan in {"", "text"}
and (message.content or "").strip()
):
from agent.policy import inquiry_copy as copy
send_group_text(group_client_of(engine), chat_id, copy.air_need_work_order())
return "need_work_order"
# 明确 @ 过机器人却发来附件、群里又对不上工单:同样要回一句,
# 否则真机就是「发文件 + @机器人,BOT 一声不吭」(2026-11-21)。
if is_group_bot(chat_id) and (message.raw or {}).get("at_burst_explicit"):
from agent.policy import inquiry_copy as copy
send_group_text(group_client_of(engine), chat_id, copy.air_need_work_order())
return "need_work_order"
return "group_ignore"
if flow is None:
view0 = ticket_view(ticket)
line = str(
view0.get("business_line")
or view0.get("businessLine")
or getattr(ticket, "business_line", "")
or ""
).upper()
if line == "LAND":
from agent.policy.land_text_flow import get_land_text_flow
engine = get_land_text_flow()
view0 = ticket_view(ticket)
line = str(
view0.get("business_line")
or view0.get("businessLine")
or getattr(ticket, "business_line", "")
or ""
).upper()
if line == "MULTI":
from agent.policy.multi_group_ops import (
apply_multi_file,
bot_sender_when_air_multi,
handle_multi_inbound,
sender_mode,
)
if not (
_sender_allowed(ticket, message.sender_id)
or sender_mode(engine, message.sender_id)
):
logger.info("group_inbound 多段忽略非成员 sender=%s", message.sender_id)
return "group_ignore"
kind_multi = (message.msg_type or "text").lower()
# 附件走归段落库;禁止把文件名塞进文字报价。
if kind_multi in {"file", "image", "video"}:
media = dict(message.media or {})
filename = str(
media.get("filename") or media.get("FileName") or (message.content or "")
).strip()
with bot_sender_when_air_multi(ticket):
return apply_multi_file(
flow=engine,
ticket=ticket,
chat_id=chat_id,
sender_id=message.sender_id,
filename=filename,
media=media,
explicit=bool((message.raw or {}).get("at_burst_explicit")),
)
# 按需出表:多段群也认「生成报价单」,不要先被段报价抽取抢走。
from agent.routing.group_intent import (
INTENT_GENERATE_PDF,
INTENT_GENERATE_SHEET,
classify_group_text,
)
multi_intent = classify_group_text(
message.content or "", injected=injected_intent
)
if multi_intent in {INTENT_GENERATE_SHEET, INTENT_GENERATE_PDF}:
from agent.policy.group_quote_sheet import apply_request_quote_sheet
with bot_sender_when_air_multi(ticket):
return apply_request_quote_sheet(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
chat_id=chat_id,
sess=None,
text=message.content or "",
kind="PDF" if multi_intent == INTENT_GENERATE_PDF else "Excel",
)
# 会话存档听到的报价也走这里。含空运时群是机器人建的,必须改走桥才能发得出去。
with bot_sender_when_air_multi(ticket):
return handle_multi_inbound(
flow=engine,
ticket=ticket,
chat_id=chat_id,
sender_id=message.sender_id,
text=message.content or "",
injected_quote=injected_quote,
)
ticket = hydrate_ticket(engine, ticket)
if not _sender_allowed(ticket, message.sender_id):
logger.info("group_inbound 忽略非成员 sender=%s chat=%s", message.sender_id, chat_id)
return "group_ignore"
from agent.policy.system_exception import (
cabin_failure_pause,
reply_paused_ticket,
ticket_is_paused,
)
# 锁舱失败不挡海运/陆运群里的后续报价。查价失败的暂停仍要停。
if ticket_is_paused(ticket) and not cabin_failure_pause(ticket):
reply_paused_ticket(
ticket=ticket,
reply=lambda text: send_group_text(group_client_of(engine), chat_id, text),
)
return "system_exception_paused"
sess = _session_of_ticket(engine, ticket)
if is_handoff_ticket(ticket, sess):
# 转人工后不再跟报价/成交/补字段,但「解散群」仍要执行,否则协同群清不掉。
from agent.routing.group_intent import INTENT_DISSOLVE, classify_group_text
kind0 = (message.msg_type or "text").lower()
if kind0 in {"", "text"} and (
classify_group_text(message.content or "", injected=injected_intent)
== INTENT_DISSOLVE
):
logger.info(
"group_inbound 转人工仍解散 wo=%s chat=%s",
ticket_no(ticket),
chat_id,
)
return dissolve_group(flow=engine, ticket=ticket, sess=sess)
logger.info(
"group_inbound 转人工不再跟 wo=%s chat=%s",
ticket_no(ticket),
chat_id,
)
return "handoff_ignore"
view = ticket_view(ticket)
if view.get("collab_ended") or (sess is not None and getattr(sess, "collab_ended", False)):
from agent.policy import inquiry_copy as copy
send_group_text(
group_client_of(engine),
chat_id,
copy.group_dissolved(work_order_no=ticket_no(ticket)),
)
return "group_already_ended"
kind = (message.msg_type or "text").lower()
if kind in {"file", "image", "video"}:
media = dict(message.media or {})
filename = str(
media.get("filename") or media.get("FileName") or (message.content or "")
).strip()
return handle_group_file(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
filename=filename,
media=media,
sess=sess,
# dispatch 打的「本次指令明确 @ 过机器人」标记:处理完必须回一句,不能静默存档。
explicit=bool((message.raw or {}).get("at_burst_explicit")),
)
from agent.routing.group_intent import (
INTENT_CONFIRM_TMS,
INTENT_DEAL,
INTENT_DISSOLVE,
INTENT_DROP_TMS,
INTENT_FIELDS,
INTENT_GENERATE_PDF,
INTENT_GENERATE_SHEET,
INTENT_KEEP_TMS,
INTENT_LOST,
INTENT_NEGOTIATE,
INTENT_ADJUST,
INTENT_QUOTE,
classify_group_text,
)
lost = capture_group_lost_reason(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
text=message.content or "",
sess=sess,
)
if lost:
return lost
# 产品 2026-11-24:待确认的报价/调价,成员 @机器人 回「确认/确定」后才落账。
from agent.policy.quote_adjust_ops import confirm_pending_group_adjust
from agent.policy.sea_group_ops import confirm_pending_group_quote
confirmed = confirm_pending_group_adjust(engine, ticket, message, sess)
if confirmed:
return confirmed
confirmed = confirm_pending_group_quote(engine, ticket, message, sess)
if confirmed:
return confirmed
intent = classify_group_text(message.content or "", injected=injected_intent)
logger.info(
"group_inbound 文字 chat=%s sender=%s intent=%s chars=%s",
chat_id,
message.sender_id,
intent,
len((message.content or "").strip()),
)
if intent in {INTENT_GENERATE_SHEET, INTENT_GENERATE_PDF}:
from agent.policy.group_quote_sheet import apply_request_quote_sheet
return apply_request_quote_sheet(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
chat_id=chat_id,
sess=sess,
text=message.content or "",
kind="PDF" if intent == INTENT_GENERATE_PDF else "Excel",
)
if intent in {INTENT_DEAL, INTENT_LOST, INTENT_NEGOTIATE}:
outcome = {
INTENT_DEAL: "已成交",
INTENT_LOST: "未成交",
INTENT_NEGOTIATE: "协商中",
}[intent]
return apply_group_deal(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
outcome=outcome,
sess=sess,
text=message.content or "",
)
if intent == INTENT_CONFIRM_TMS:
phase = apply_confirm_tms_quote(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
sess=sess,
)
return phase
if intent in {INTENT_KEEP_TMS, INTENT_DROP_TMS}:
return apply_tms_quote_choice(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
keep_tms=intent == INTENT_KEEP_TMS,
sess=sess,
)
if intent == INTENT_FIELDS:
return apply_collab_update(
flow=engine,
ticket=ticket,
text=message.content or "",
sender_id=message.sender_id,
sess=sess,
)
from agent.policy.sea_group_ops import is_sales
from agent.routing.group_intent import resolve_price_intent
# 产品写出「报关费改为300」是报价。不是这张单的销售时,不能回调价话术。
priced = resolve_price_intent(
intent,
message.content or "",
sales=is_sales(ticket, message.sender_id),
)
if priced != intent:
logger.info("group_inbound 报价/调价改判 %s -> %s chat=%s", intent, priced, chat_id)
intent = priced
if intent == INTENT_ADJUST:
from agent.policy.quote_adjust_ops import apply_group_adjust
return apply_group_adjust(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
text=message.content or "",
sess=sess,
chat_id=chat_id,
)
if intent == INTENT_QUOTE:
return apply_product_quote(
flow=engine,
ticket=ticket,
text=message.content or "",
sender_id=message.sender_id,
sess=sess,
injected_quote=injected_quote,
)
if intent == INTENT_DISSOLVE:
return dissolve_group(flow=engine, ticket=ticket, sess=sess)
parked = peek_pending_product_quote(ticket_no(ticket), sess)
if parked:
from agent.policy import inquiry_copy as copy
send_group_text(group_client_of(engine), chat_id, copy.group_tms_choice_unclear())
return "wait_tms_choice"
logger.info("group_inbound 其它意图 chat=%s intent=%s", chat_id, intent)
return "group_ignore"
def _find_ticket(book: object, chat_id: str):
finder = getattr(book, "find_by_collab_chat", None)
if callable(finder):
hit = finder(chat_id=chat_id)
if hit is not None:
return _ticket_for_room(hit, chat_id)
try:
from agent.channel.wshoto.rooms import ticket_no_for_room
no = ticket_no_for_room(chat_id)
except Exception:
logger.exception("存档房间反查工单失败 chat=%s", chat_id)
no = ""
if not no:
return None
getter = getattr(book, "get_ticket", None)
if callable(getter):
hit = getter(work_order_no=no)
if hit is not None:
return _ticket_for_room(hit, chat_id)
getter = getattr(book, "get_for_agent", None)
if callable(getter):
hit = getter(work_order_no=no, sender_id="")
return _ticket_for_room(hit, chat_id) if hit else None
return None
def _ticket_for_room(hit: object, chat_id: str):
"""
反查出来的工单必须确实服务这个群。
Redis 房间→工单是短索引,售卖给别的工单换群/书签串单时会残留旧号。
拿别的群的单在本群回话,就会出现「陆运单的群已解散发进空运群」(2026-11-23 真机):
解散语沿用了本次入站群的回复通道,工单号却来自另一张单。
绑群号是空的(改造前老群)仍按原逻辑放行;有绑群号且不是本群就整条忽略。
"""
if hit is None:
return None
view = ticket_view(hit)
bound = str(view.get("collab_chat_id") or "").strip()
room = (chat_id or "").strip()
if bound and room and bound != room:
logger.warning(
"group_inbound 群与工单绑群不一致 chat=%s wo=%s bound=%s,忽略该工单",
room,
ticket_no(hit) or "-",
bound,
)
return None
return hit
def _room_ticket_conflict(book: object, chat_id: str) -> str:
"""
Redis 房间索引把本群指向一张单,但那张单主账上绑的是别的群。
这种脏索引不能当「本群无主」处理:孤儿解散会按企微实时成员清人,
误伤真实协同群。返回冲突的工单号,空串表示没有冲突。
"""
try:
from agent.channel.wshoto.rooms import ticket_no_for_room
no = str(ticket_no_for_room(chat_id) or "").strip()
except Exception:
return ""
if not no:
return ""
getter = getattr(book, "get_ticket", None)
hit = None
if callable(getter):
try:
hit = getter(work_order_no=no)
except Exception:
logger.exception("冲突校验读主账失败 wo=%s", no)
return ""
if hit is None:
return ""
bound = str(ticket_view(hit).get("collab_chat_id") or "").strip()
if bound and bound != (chat_id or "").strip():
return no
return ""
def _session_of_ticket(engine: object, ticket: object):
"""用工单号找回销售侧书签,方便写 collab_facts / deal_version。"""
no = ticket_no(ticket)
getter = getattr(engine, "session_by_work_order", None)
if callable(getter) and no:
return getter(no)
by_ticket = getattr(engine, "_by_ticket", None)
if isinstance(by_ticket, dict) and no:
return by_ticket.get(no)
return None
def _sender_allowed(ticket: object, sender_id: str) -> bool:
uid = (sender_id or "").strip()
if not uid:
return False
view = ticket_view(ticket)
sales = str(view.get("sales_wecom_id") or view.get("salesWecomId") or "")
members = view.get("collab_member_ids") or view.get("memberIds") or []
if uid == sales:
return True
return uid in {str(x) for x in members}