Files
inquiry_robot/inquiry-agent/tests/test_group_quote_sheet_ondemand.py
T

338 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""协同群有价后不自动发表;销售说「生成报价单」才出 Excel。"""
from __future__ import annotations
import os
import sys
import unittest
from typing import Any
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
os.environ.setdefault("YTD_ENV", "test")
os.environ.setdefault("REDIS_BACKEND", "memory")
os.environ.setdefault("CHECKPOINT_BACKEND", "memory")
os.environ.setdefault("MESSAGE_STORE_BACKEND", "memory")
os.environ.setdefault("LLM_DATA_USAGE_CONFIRMED", "false")
os.environ.setdefault("LLM_ALLOW_NETWORK", "false")
os.environ.setdefault("LEDGER_BACKEND", "memory")
from agent.channel.wecom.models import InboundMessage
from agent.handlers.group_collab import handle_group_collab
from agent.ledger.memory_ledger import MemoryLedger
from agent.policy import inquiry_copy as copy
from agent.policy.sea_text_flow import SeaTextInquiryFlow
from agent.routing.group_intent import (
INTENT_GENERATE_PDF,
INTENT_GENERATE_SHEET,
classify_group_text,
)
from tests.test_sea_text_inquiry import COMPLETE_SEA, FakeGroupClient, drive_sea
class GroupQuoteSheetOndemandTests(unittest.TestCase):
def setUp(self) -> None:
self.ledger = MemoryLedger()
self.ledger.set_quote_templates(
[
{
"templateId": "mem-default-sea",
"name": "海运默认",
"bizType": "海运",
"keywords": [],
"isDefault": True,
}
]
)
self.ledger.set_sea_staff(
[
{
"wecomId": "prod4",
"name": "产品甲",
"roleCode": "sea",
"routes": "海运·全部线路",
"status": "active",
}
]
)
self.groups = FakeGroupClient()
self.flow = SeaTextInquiryFlow(self.ledger, group_client=self.groups)
self.replies: list[str] = []
def _reply(self, text: str = "", extra=None) -> str:
if text:
self.replies.append(text)
return ""
def _open_group(self) -> tuple[str, str]:
facts = dict(COMPLETE_SEA)
facts["目的港"] = "无价港"
drive_sea(
self.flow,
sender_id="sales1",
text="海运无价",
reply=self._reply,
injected_facts=facts,
injected_mode="SEA",
)
self.flow.on_button(
sender_id="sales1",
action=copy.BTN_PULL_COLLAB,
reply=self._reply,
)
sess = self.flow.session_of("sales1")
return sess.work_order_no, sess.collab_chat_id
def test_classify_generate_sheet_hints(self) -> None:
self.assertEqual(classify_group_text("生成报价单", allow_network=False), INTENT_GENERATE_SHEET)
self.assertEqual(classify_group_text("下载报价单", allow_network=False), INTENT_GENERATE_SHEET)
self.assertEqual(classify_group_text("给我报价单", allow_network=False), INTENT_GENERATE_SHEET)
self.assertEqual(classify_group_text("生成PDF报价单", allow_network=False), INTENT_GENERATE_PDF)
self.assertEqual(classify_group_text("下载 pdf", allow_network=False), INTENT_GENERATE_PDF)
def test_product_quote_does_not_auto_send_file(self) -> None:
wo, chat = self._open_group()
self.assertTrue(wo and chat)
self.groups.sent.clear()
phase = handle_group_collab(
InboundMessage(
sender_id="prod4",
message_id="g-quote",
content="海运费:USD 100.00\n燃油附加费:USD 15.00",
chat_id=chat,
chat_type="group",
),
flow=self.flow,
ledger=self.ledger,
injected_intent="product_quote",
)
self.assertEqual(phase, "product_quote_sent")
files = [x for x in self.groups.sent if x.get("kind") == "file"]
self.assertEqual(files, [], msg="有价后不应自动发 Excel")
def test_sales_can_request_blank_excel_without_quote(self) -> None:
"""群里还没有任何报价:不拦截,按空白模板出 Excel(2026-11-17 需求)。"""
wo, chat = self._open_group()
self.assertTrue(wo and chat)
self.groups.sent.clear()
phase = handle_group_collab(
InboundMessage(
sender_id="sales1",
message_id="g-sheet-blank",
content="生成报价单",
chat_id=chat,
chat_type="group",
),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "sheet_excel_sent")
files = [x for x in self.groups.sent if x.get("kind") == "file"]
self.assertTrue(files, msg="无报价也应发出空白 Excel")
blocked = copy.group_sheet_need_quote(work_order_no=wo)
self.assertFalse(
[x for x in self.groups.sent if x.get("kind") == "text" and blocked in str(x.get("content") or "")],
msg="无报价不应再提示先报价",
)
def test_sales_can_request_excel_after_quote(self) -> None:
wo, chat = self._open_group()
handle_group_collab(
InboundMessage(
sender_id="prod4",
message_id="g-quote2",
content="海运费:USD 100.00\n燃油附加费:USD 15.00",
chat_id=chat,
chat_type="group",
),
flow=self.flow,
ledger=self.ledger,
injected_intent="product_quote",
)
self.groups.sent.clear()
phase = handle_group_collab(
InboundMessage(
sender_id="sales1",
message_id="g-sheet",
content="生成报价单",
chat_id=chat,
chat_type="group",
),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "sheet_excel_sent")
files = [x for x in self.groups.sent if x.get("kind") == "file"]
self.assertTrue(files, msg="指令后应发出 Excel")
self.assertTrue(any(str(x.get("filename") or "").endswith(".xlsx") for x in files))
# ---- 出表后再推一次成交跟进 ----
def _deal_cards(self) -> list[dict]:
"""本次记录里所有成交跟进卡(task_id 以 deal-<工单号> 开头)。"""
return [
item
for item in self.groups.sent
if item.get("kind") == "card"
and str((item.get("template_card") or {}).get("task_id") or "").startswith("deal-")
]
def _deal_text_indexes(self) -> list[int]:
"""群内成交跟进的文字位置(含「请确认成交状态」那一句)。"""
return [
i
for i, item in enumerate(self.groups.sent)
if item.get("kind") == "text"
and "请确认成交状态" in str(item.get("content") or "")
]
def test_sheet_after_quote_pushes_deal_followup_again(self) -> None:
"""
报价单发进群后,成交跟进要再推一次,内容和报价落定那次一模一样。
为什么测:表一发就把成交卡压到上面几屏,销售要往上翻才点得到;
产品口径是「表出来后再提醒一次成交状态」。
"""
wo, chat = self._open_group()
self.groups.sent.clear()
handle_group_collab(
InboundMessage(
sender_id="prod4",
message_id="g-quote-deal",
content="海运费:USD 100.00\n燃油附加费:USD 15.00",
chat_id=chat,
chat_type="group",
),
flow=self.flow,
ledger=self.ledger,
injected_intent="product_quote",
)
first_cards = self._deal_cards()
self.assertEqual(len(first_cards), 1, msg="报价落定发一张成交跟进")
self.groups.sent.clear()
phase = handle_group_collab(
InboundMessage(
sender_id="sales1",
message_id="g-sheet-deal",
content="生成报价单",
chat_id=chat,
chat_type="group",
),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "sheet_excel_sent")
texts = self._deal_text_indexes()
cards = self._deal_cards()
self.assertEqual(len(texts), 1, msg="出表后要再推一次成交跟进文字")
self.assertEqual(len(cards), 1, msg="出表后要再推一次成交跟进卡")
# 顺序:先文件、后成交跟进;不能提醒在表前面。
files = [i for i, x in enumerate(self.groups.sent) if x.get("kind") == "file"]
self.assertTrue(files)
self.assertGreater(texts[0], files[-1], msg="成交跟进必须在报价单之后")
# 内容与之前一致:@销售、工单号、三个按钮。
body = cards[0]["template_card"]
self.assertEqual(body["card_type"], "button_interaction")
self.assertTrue(str(body.get("main_title", {}).get("title") or "").endswith(wo))
self.assertEqual(
[b["text"] for b in body.get("button_list") or []],
[copy.BTN_DEAL, copy.BTN_LOST, copy.BTN_NEGOTIATE],
)
# 版本不涨:按钮 key 与之前那张完全相同,旧卡仍然点得动,不会提示旧版失效。
self.assertEqual(
[b["key"] for b in body.get("button_list") or []],
[b["key"] for b in first_cards[0]["template_card"].get("button_list") or []],
)
def test_reemit_deal_keeps_version_and_session_status(self) -> None:
"""
出表补推不动书签:版本不涨(旧卡仍可点),也不把「协商中」降回「已报价」。
为什么测:重发成交卡如果顺手改了 phase/status/wait_version,
销售刚确认的协商中会被悄悄冲掉,等待计时的起点也会被推后。
"""
from agent.policy.sea_group_ops import emit_group_deal
wo, chat = self._open_group()
sess = self.flow.session_of("sales1")
sess.status = "协商中"
sess.deal_version = 2
wait_before = sess.wait_version
self.groups.sent.clear()
emit_group_deal(
flow=self.flow,
ticket=self.ledger.get_ticket(work_order_no=wo),
sess=sess,
quote={"total": "1000", "currency": "USD"},
bump_version=False,
)
again = self.flow.session_of("sales1")
self.assertEqual(again.deal_version, 2)
self.assertEqual(again.status, "协商中")
self.assertEqual(again.wait_version, wait_before)
cards = self._deal_cards()
self.assertEqual(len(cards), 1)
# 按钮 key 沿用当前版本 v2,之前那张卡照样点得动。
self.assertEqual(
cards[0]["template_card"]["button_list"][0]["key"],
f"{copy.BTN_DEAL_KEY}:{wo}:v2",
)
def test_blank_sheet_does_not_push_deal_followup(self) -> None:
"""空白表(还没人报价)后面不推成交跟进:让人确认一个不存在的价没意义。"""
wo, chat = self._open_group()
self.groups.sent.clear()
phase = handle_group_collab(
InboundMessage(
sender_id="sales1",
message_id="g-sheet-blank-deal",
content="生成报价单",
chat_id=chat,
chat_type="group",
),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "sheet_excel_sent")
self.assertEqual(self._deal_cards(), [], msg="空白表不应补推成交跟进卡")
self.assertEqual(self._deal_text_indexes(), [], msg="空白表不应补推成交跟进文字")
def test_air_handoff_sheet_does_not_push_deal_followup(self) -> None:
"""
空运转人工群:出表后也不补推成交跟进。
空运转人工群本来就不发成交跟进:成本由销售在后台谈,报价落定时已明确
不发「是否成交」卡;补推如果绕过这条,等于把刚关掉的动作又放回来。
"""
class _FakeFlow:
"""只在补推判断里用到群客户端;不走 Graph、不碰主账。"""
def __init__(self, client) -> None:
self._group_client = client
self.ledger = None
from agent.policy.group_quote_sheet import _push_deal_followup_after_sheet
client = FakeGroupClient()
ticket = {
"work_order_no": "WO202611170009",
"business_line": "AIR",
"collab_mode": "handoff",
"collab_chat_id": "wr_air_handoff",
}
_push_deal_followup_after_sheet(
flow=_FakeFlow(client),
ticket=ticket,
sess=None,
quote={"total": "100", "currency": "CNY"},
line="AIR",
)
self.assertEqual(client.sent, [], msg="空运转人工群不应补推成交跟进")
if __name__ == "__main__":
unittest.main()