""" 协同群按需生成报价单(Excel / PDF)。 本文件职责:群内任何成员(销售/商务/产品/航线)说「生成报价单」等指令时, 校验有价后出表发群;无价也出空白表。非群成员由群入口先拦,不在这里判岗位。 禁止:产品报价落定时自动调用;回调线程同步 LibreOffice;私聊采用出单走这里。 """ from __future__ import annotations import logging import uuid from pathlib import Path from typing import Any, Optional from agent.policy import inquiry_copy as copy logger = logging.getLogger(__name__) def _group_outbound_channel(flow: Any) -> str: """ 当前群出站通道:空运 Aibot 桥,海运/陆运企微应用 appchat。 与 Excel 发群同源,避免 PDF 写死走错通道后转换成功却发不进群。 """ from agent.channel.aibot.reply import AibotReplyClient from agent.jobs.pdf_job import OUTBOUND_AIBOT, OUTBOUND_APPCHAT from agent.policy.sea_group_ops import group_client_of client = group_client_of(flow) if isinstance(client, AibotReplyClient): return OUTBOUND_AIBOT return OUTBOUND_APPCHAT def can_request_quote_sheet(flow: Any, ticket: object, sender_id: str) -> bool: """ 谁能喊「生成报价单」:群内任何成员都可以(产品口径 2026-11-22 起开放)。 以前只放本单销售、员工管理岗位 sales(商务)、航线·空运,产品在群里要 PDF 报价单会被回「只有销售、商务或航线可以说」;真机反馈销售/产品一起 看价时,产品才是要表的人,于是产品拍板:谁能进这个协同群,谁就能要表。 为什么不在这里再查岗位:岗位只决定「能不能报/调价」,不决定「能不能看 已经谈好的价目」;而且转人工群、自动协同群、多段群口径本来就该一致。 非群成员不是靠这里拦,而是 group_collab 入口的 _sender_allowed 先按群 成员过滤掉了,所以本函数只做「有发送人」的兜底判空。 保留 flow / ticket 形参:调用方与测试仍按原签名传,且未来若再收紧权限 不必大改调用点;本函数无副作用、不查主账。 """ return bool((sender_id or "").strip()) def quote_usable_for_sheet(quote: Optional[dict[str, Any]]) -> bool: """人工价或 TMS 价:有总价或费用行即可出表。""" from agent.policy.sea_group_ops import _quote_fee_rows src = dict(quote or {}) total = str(src.get("total") or src.get("salePrice") or "").strip() if total and total != "-": return True if _quote_fee_rows(src): return True if src.get("weightPrices") or src.get("vehicleRates") or src.get("vehicle_rates"): return True opts = src.get("airOptions") or src.get("air_options") or [] if isinstance(opts, list) and opts: return True return False def _push_deal_followup_after_sheet( *, flow: Any, ticket: object, sess: Any, quote: dict[str, Any], line: str, ) -> None: """ 报价单发进群后,再推一次成交跟进(@销售 + 成交卡),与报价落定那次一模一样。 为什么补推:表一发出去,成交跟进就被压到上面几屏,销售要往上翻才点得到; 产品口径是「表出来后再提醒一次成交状态」。 只推有价的单:空白报价单(还没人报价)旁边让人确认成交没有意义。 多段联运各段口径不同,由 _request_multi_sheets 自己补推,这里跳过。 空运转人工群本来就不发成交跟进(成交由销售在后台处理),也不补推。 版本不涨(bump_version=False),旧卡与新卡都能点,不会提示「旧版已失效」。 副作用:发群文字 + 模板卡;失败只记日志,不回滚已经发出去的表。 """ if not quote_usable_for_sheet(quote): return from agent.policy.sea_group_ops import emit_group_deal, ticket_no line_now = str(line or "").strip().upper() if line_now == "MULTI": return if line_now == "AIR": try: from agent.policy.air_group_ops import is_handoff_collab if is_handoff_collab(flow, ticket): logger.info("sheet.deal_followup skip air_handoff wo=%s", ticket_no(ticket)) return except Exception: logger.exception("出表补推判断空运转人工失败 wo=%s", ticket_no(ticket)) try: emit_group_deal( flow=flow, ticket=ticket, sess=sess, quote=dict(quote or {}), bump_version=False, ) logger.info("sheet.deal_followup wo=%s line=%s", ticket_no(ticket), line or "-") except Exception: logger.exception("出表后补推成交跟进失败 wo=%s", ticket_no(ticket)) def detect_sheet_kind(text: str) -> str: """ 指令要 Excel 还是 PDF。 含 PDF/pdf/生成pdf/下载pdf → PDF;其余生成/下载/给我报价单 → Excel。 """ blob = (text or "").replace(" ", "").replace(" ", "").lower() if "pdf" in blob: return "PDF" return "Excel" def looks_like_sheet_request(text: str) -> bool: """本地口令:生成/下载/给我/发我 + 报价单;或单独说生成/下载 PDF。""" blob = (text or "").replace(" ", "").replace(" ", "").lower() if not blob: return False triggers = ("生成", "下载", "给我", "发我", "出一份", "来一份", "要一份", "发一下", "出一下") if not any(x in blob for x in triggers): return False if "报价单" in blob or "报价表" in blob: return True # 「生成pdf」「下载 pdf」也认,避免必须带「报价单」三字。 return "pdf" in blob def handoff_template_name(view: dict[str, Any]) -> str: """ 陆运按需出表用的模板名:业务类型 / 运输类型+线路 反查后台模板名。 为什么要反查:陆运 7 种业务靠关键词猜必错(国内拼车的「零担/集拼」会抢走 中港集拼,WO202611180001)。转人工卡上的 biz_type_label 优先;没有时用 工单事实里的运输类型+线路类别配对(自动协同群同样适用)。 非陆运、或认不出来时返回空串,交回关键词匹配。 副作用:无。 """ line = str(view.get("business_line") or view.get("businessLine") or "").strip().upper() if line != "LAND": return "" from agent.schema.handoff_options import biz_by_key, biz_for_pair label = str(view.get("biz_type_label") or view.get("bizTypeLabel") or "").strip() biz = biz_by_key(label) if label else None if biz is None: facts = dict(view.get("facts") or {}) biz = biz_for_pair( str(facts.get("运输类型") or "").strip(), str(facts.get("线路类别") or "").strip(), ) return biz.template_name if biz else "" def apply_request_quote_sheet( *, flow: Any, ticket: object, sender_id: str, chat_id: str = "", sess: Any = None, text: str = "", kind: str = "", ) -> str: """ 群里按指令生成报价单并发群。 副作用:主账 render(可写附件)、企微发文件;PDF 入 LibreOffice 槽。 线程:Worker / inbox 消费线程,禁止本函数内跑 soffice。 """ from agent.policy.sea_group_ops import ( _current_quote, _facts_for_fill, _render_and_send_sheet, group_client_of, halt_closed_group, hydrate_ticket, send_group_text, ticket_no, ticket_view, ) ticket = hydrate_ticket(flow, ticket) no = ticket_no(ticket) view = ticket_view(ticket) room = ( chat_id or str((sess.collab_chat_id if sess else "") or view.get("collab_chat_id") or "") ).strip() client = group_client_of(flow) stopped = halt_closed_group(flow=flow, ticket=ticket, sess=sess, chat_id=room) if stopped: return stopped sheet_kind = (kind or detect_sheet_kind(text) or "Excel").strip() if sheet_kind not in {"Excel", "PDF"}: sheet_kind = "Excel" if not can_request_quote_sheet(flow, ticket, sender_id): send_group_text(client, room, copy.group_sheet_request_not_allowed()) return "sheet_not_allowed" line = str(view.get("business_line") or view.get("businessLine") or "SEA").strip().upper() # 陆运转人工:按工单业务类型反查模板名,出表时按名直取。 template_name = handoff_template_name(view) if line == "MULTI": return _request_multi_sheets( flow=flow, ticket=ticket, sender_id=sender_id, chat_id=room, sheet_kind=sheet_kind, ) quote = _current_quote(view, sess) if line == "AIR": from agent.policy.air_group_ops import _sheet_quote_with_tms_sale_total tms = copy.resolve_tms_quote(sess, view) quote = _sheet_quote_with_tms_sale_total( quote, tms=tms or quote, facts=dict(view.get("facts") or {}) ) # 2026-11-17 产品口径:出不出表不再判断「是否已报价」。 # 没有可用价时按空白报价单出表(金额/费用栏留空),不拦截、不提示先报价。 # 与激活空白模版一致:空白表只发群,不写后台附件列(persist=False)。 blank_sheet = not quote_usable_for_sheet(quote) if blank_sheet: quote = {} if sheet_kind == "Excel": send_group_text(client, room, copy.group_sheet_generating(kind="Excel")) facts = dict(view.get("facts") or {}) if sess is not None and getattr(sess, "facts", None): facts.update(dict(sess.facts or {})) collab = dict(view.get("collab_facts") or {}) if sess is not None and getattr(sess, "collab_facts", None): collab.update(dict(sess.collab_facts or {})) out = _render_and_send_sheet( flow=flow, chat_id=room, work_order_no=no, facts=_facts_for_fill( facts, collab, business_line=line, sales_name=str(view.get("sales_name") or view.get("salesName") or ""), ), quote=quote, sales_id=sender_id, business_line=line or "SEA", persist_attachment=not blank_sheet, template_name=template_name, ) ok = bool(out.get("ok")) if ok: # 表已进群:再推一次成交跟进,销售不用往上翻找那张卡。 _push_deal_followup_after_sheet( flow=flow, ticket=ticket, sess=sess, quote=quote, line=line ) return "sheet_excel_sent" if ok else "sheet_send_fail" return _request_pdf( flow=flow, ticket=ticket, view=view, sess=sess, quote=quote, sender_id=sender_id, chat_id=room, work_order_no=no, business_line=line or "SEA", persist_attachment=not blank_sheet, template_name=template_name, ) def _request_multi_sheets( *, flow: Any, ticket: object, sender_id: str, chat_id: str, sheet_kind: str, ) -> str: """多段:有价段各自出表;一段都没有价时逐段发空白报价单。""" from agent.policy.multi_group_ops import load_segments, segment_quotes from agent.policy.sea_group_ops import group_client_of, send_group_text, ticket_no segments = load_segments(ticket) quotes = segment_quotes(ticket) or {} usable = [ seg for seg in segments if quote_usable_for_sheet(dict(quotes.get(seg.mode) or {})) ] client = group_client_of(flow) no = ticket_no(ticket) # 2026-11-17 产品口径:无任一段有价也不再拦截,逐段发空白报价单(金额留空)。 # 只有「连段数据都没有」时才没有模板维度可分,保留先报价提示。 blank_all = not usable if blank_all and not segments: send_group_text(client, chat_id, copy.group_sheet_need_quote(work_order_no=no)) return "sheet_need_quote" targets = usable or segments if sheet_kind == "PDF": send_group_text(client, chat_id, "多段工单群内暂只生成 Excel 报价单;PDF 请按段在出表后逐段说明。") sheet_kind = "Excel" send_group_text(client, chat_id, copy.group_sheet_generating(kind="Excel")) from agent.policy.multi_group_ops import _send_sheet for seg in targets: _send_sheet( flow=flow, ticket=ticket, chat_id=chat_id, segment=seg, quote=dict(quotes.get(seg.mode) or {}), sheet_fn=None, ) # 各段表都发完后补推一次整票成交跟进(每段一行,不出现段间加总)。 # 与段报价落定那次同一份文字和卡;版本不涨,旧卡仍可点。 if not blank_all: from agent.policy.multi_group_ops import emit_multi_deal try: emit_multi_deal( flow=flow, ticket=ticket, chat_id=chat_id, segments=segments, stored=dict(quotes or {}), ) except Exception: logger.exception("多段出表后补推成交跟进失败 wo=%s", no) return "sheet_excel_sent" def _request_pdf( *, flow: Any, ticket: object, view: dict[str, Any], sess: Any, quote: dict[str, Any], sender_id: str, chat_id: str, work_order_no: str, business_line: str, persist_attachment: bool = True, template_name: str = "", ) -> str: """主账填 xlsx 后入 PDF 槽;失败则改发 Excel。 persist_attachment:有价正式出单 True;无价空白出单 False,不写后台附件列。 PDF 是异步转换的:成交跟进不能在排队时先发(那时群里还没有表), 而是把待补推标记随任务带下去,由 LibreOffice 槽发完文件后再推。 """ from agent.policy.sea_group_ops import ( _facts_for_fill, _render_and_send_sheet, group_client_of, send_group_text, ) client = group_client_of(flow) send_group_text(client, chat_id, copy.group_sheet_generating(kind="PDF")) renderer = getattr(flow.ledger, "render_quote", None) if not callable(renderer): send_group_text(client, chat_id, copy.quote_template_missing()) return "sheet_no_template" facts = dict(view.get("facts") or {}) if sess is not None and getattr(sess, "facts", None): facts.update(dict(sess.facts or {})) collab = dict(view.get("collab_facts") or {}) if sess is not None and getattr(sess, "collab_facts", None): collab.update(dict(sess.collab_facts or {})) filled_facts = _facts_for_fill( facts, collab, business_line=business_line, sales_name=str(view.get("sales_name") or view.get("salesName") or ""), ) result = renderer( work_order_no=work_order_no, business_line=business_line, facts=filled_facts, quote=quote, format="pdf", sales_wecom_id=sender_id, persist_attachment=bool(persist_attachment), template_name=(template_name or "").strip(), ) or {} if not result.get("ok"): send_group_text(client, chat_id, str(result.get("message") or copy.quote_template_missing())) return "sheet_no_template" from agent.quote_templates.filename import filename_from_render pdf_name = filename_from_render(work_order_no, result, suffix=".pdf") xlsx_name = filename_from_render(work_order_no, result, suffix=".xlsx") if result.get("needsPdf"): outbound = _group_outbound_channel(flow) queued = _enqueue_group_pdf( result, work_order_no=work_order_no, chat_id=chat_id, filename=pdf_name, quote=quote, facts=filled_facts, business_line=business_line, outbound_channel=outbound, # 只有真报了价的单才补推成交跟进;空白表不推。 deal_followup=quote_usable_for_sheet(quote), sales_name=str(view.get("sales_name") or view.get("salesName") or ""), ) if queued: return "sheet_pdf_queued" send_group_text(client, chat_id, "PDF 转换排队失败,已改发 Excel 报价单。") out = _render_and_send_sheet( flow=flow, chat_id=chat_id, work_order_no=work_order_no, facts=filled_facts, quote=quote, sales_id=sender_id, business_line=business_line, persist_attachment=bool(persist_attachment), template_name=(template_name or "").strip(), ) _ = xlsx_name if out.get("ok"): # PDF 退化成 Excel 同样是「表已进群」,成交跟进照推一次。 _push_deal_followup_after_sheet( flow=flow, ticket=ticket, sess=sess, quote=quote, line=business_line ) return "sheet_excel_sent" if out.get("ok") else "sheet_send_fail" def _enqueue_group_pdf( result: dict[str, Any], *, work_order_no: str, chat_id: str, filename: str, quote: dict[str, Any], facts: dict[str, Any], business_line: str, outbound_channel: str = "", deal_followup: bool = False, sales_name: str = "", ) -> bool: """ 把已填 xlsx 入 LibreOffice 槽,转换后按与 Excel 相同通道发到协同群。 deal_followup:发完 PDF 后再推一次成交跟进(与 Excel 出表后同一口径)。 sales_name:群里 @ 销售用的名字,随任务带下去,Worker 里不必再查一遍工单。 """ raw_b64 = str(result.get("fileBase64") or "").strip() if not raw_b64: return False try: import base64 import tempfile from agent.jobs.pdf_job import enqueue_pdf_job data = base64.b64decode(raw_b64) work_dir = Path(tempfile.gettempdir()) / "inquiry_quote" work_dir.mkdir(parents=True, exist_ok=True) xlsx_path = work_dir / f"{work_order_no}_group_quote.xlsx" xlsx_path.write_bytes(data) queued = enqueue_pdf_job( xlsx_path=str(xlsx_path), inquiry_no=work_order_no, quote_version=1, idempotency_key=f"pdf-group:{work_order_no}:{uuid.uuid4().hex[:8]}", touser="", chat_id=chat_id, filename=filename, quote=quote, facts=facts, business_line=business_line, skip_deal_card=True, outbound_channel=outbound_channel, deal_followup=bool(deal_followup), sales_name=sales_name, ) return bool(queued.accepted) except Exception: logger.exception("群报价 PDF 入队失败 wo=%s", work_order_no) return False