feat(agent): integrate procurement AI agent with Bale bot, real-time draft sync, and git history bundle
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
"""Update dispatch — the heart of the bot.
|
||||
|
||||
Pipeline per update:
|
||||
callback_query → callbacks router (link-gated)
|
||||
message text starting "/" → command router
|
||||
voice/audio → download → STT → treated as text (source=voice)
|
||||
text → pending-flow interception (linking / accept-arrive confirmations)
|
||||
→ auth gate (link or admin)
|
||||
→ NLU → intent router
|
||||
"""
|
||||
import logging
|
||||
|
||||
from app import drafts as draft_store
|
||||
from app.config import settings
|
||||
from app.nlu import understand
|
||||
from app.runtime import BotContext, LinkedUser
|
||||
from app.stt import transcribe
|
||||
from app.texts import CANCELLED, LINK_START, NOTHING_TO_COMMIT, STT_FAILED, UNKNOWN_HINT, VOICE_EMPTY
|
||||
|
||||
from . import commands, callbacks, quote, supplier, material, queries, decisions
|
||||
|
||||
logger = logging.getLogger("bot.handlers")
|
||||
|
||||
|
||||
async def handle_update(ctx: BotContext, update: dict) -> None:
|
||||
if update.get("callback_query"):
|
||||
await callbacks.handle_callback(ctx, update["callback_query"])
|
||||
return
|
||||
message = update.get("message") or update.get("edited_message")
|
||||
if not message:
|
||||
return
|
||||
chat_id = message["chat"]["id"]
|
||||
try:
|
||||
await handle_message(ctx, chat_id, message)
|
||||
except Exception:
|
||||
logger.exception("message handling failed for chat %s", chat_id)
|
||||
await ctx.send(chat_id, "خطای غیرمنتظره رخ داد؛ دوباره تلاش کن.")
|
||||
|
||||
|
||||
async def handle_message(ctx: BotContext, chat_id: int, message: dict) -> None:
|
||||
text = (message.get("text") or "").strip()
|
||||
source = "text"
|
||||
|
||||
if text.startswith("/"):
|
||||
await commands.handle_command(ctx, chat_id, text)
|
||||
return
|
||||
|
||||
if not text and (message.get("voice") or message.get("audio") or message.get("document")):
|
||||
source = "voice"
|
||||
await ctx.bale.send_chat_action(chat_id, "typing")
|
||||
file_id = (message.get("voice") or message.get("audio") or message.get("document"))["file_id"]
|
||||
try:
|
||||
audio = await ctx.bale.download_file(file_id)
|
||||
text = await transcribe(settings, audio,
|
||||
mime_type=(message.get("voice") or {}).get("mime_type"),
|
||||
filename=(message.get("voice") or {}).get("file_name"))
|
||||
except Exception as exc:
|
||||
detail = "هوش مصنوعی تنظیم نشده" if "not configured" in str(exc) else str(exc)[:200]
|
||||
await ctx.send(chat_id, STT_FAILED.format(detail=esc(detail)))
|
||||
return
|
||||
if not text:
|
||||
await ctx.send(chat_id, VOICE_EMPTY)
|
||||
return
|
||||
await ctx._log(chat_id, "in", "voice", text)
|
||||
|
||||
# Pending multi-step interactions take the message first.
|
||||
flow = ctx.pending.get(chat_id)
|
||||
if flow:
|
||||
handled = await _route_to_flow(ctx, chat_id, flow, text)
|
||||
if handled:
|
||||
return
|
||||
ctx.pending.pop(chat_id) # stale/irrelevant flow → fall through
|
||||
|
||||
user = await _gate(ctx, chat_id, message)
|
||||
if user is None:
|
||||
return # gate either started linking or is mid-linking
|
||||
|
||||
draft = await draft_store.get_active(chat_id)
|
||||
draft_summary = _draft_summary(draft)
|
||||
result = await understand(settings, text, draft_summary)
|
||||
intent, patch = result.get("intent"), result.get("patch") or {}
|
||||
logger.info("chat %s intent=%s conf=%s", chat_id, intent, result.get("confidence"))
|
||||
|
||||
if intent in ("register_quote", "update_draft"):
|
||||
await quote.handle_entities(ctx, chat_id, user, patch, source)
|
||||
elif intent == "commit_draft":
|
||||
active = await draft_store.get_active(chat_id)
|
||||
if active is None:
|
||||
await ctx.send(chat_id, NOTHING_TO_COMMIT)
|
||||
elif active.kind == draft_store.KIND_QUOTE:
|
||||
await quote.commit(ctx, chat_id, user, active)
|
||||
elif active.kind == draft_store.KIND_SUPPLIER:
|
||||
await supplier.commit(ctx, chat_id, user, active)
|
||||
elif active.kind == draft_store.KIND_MATERIAL:
|
||||
await material.commit(ctx, chat_id, user, active)
|
||||
elif intent == "discard_draft":
|
||||
active = await draft_store.get_active(chat_id)
|
||||
if active:
|
||||
await draft_store.set_status(active.id, "cancelled")
|
||||
ctx.pending.pop(chat_id)
|
||||
await ctx.send(chat_id, CANCELLED)
|
||||
elif intent == "show_draft":
|
||||
active = await draft_store.get_active(chat_id)
|
||||
if active is None:
|
||||
await ctx.send(chat_id, NOTHING_TO_COMMIT)
|
||||
elif active.kind == draft_store.KIND_QUOTE:
|
||||
await quote.render(ctx, chat_id, active, fresh=False)
|
||||
elif active.kind == draft_store.KIND_SUPPLIER:
|
||||
await supplier.render(ctx, chat_id, active)
|
||||
elif active.kind == draft_store.KIND_MATERIAL:
|
||||
await material.render(ctx, chat_id, active)
|
||||
elif intent == "add_supplier":
|
||||
await supplier.handle_entities(ctx, chat_id, user, patch, source)
|
||||
elif intent == "add_material":
|
||||
await material.handle_entities(ctx, chat_id, user, patch, source)
|
||||
elif intent == "status_query":
|
||||
await queries.handle_query(ctx, chat_id, user, patch)
|
||||
elif intent == "accept_quote":
|
||||
await decisions.start_accept(ctx, chat_id, user, patch)
|
||||
elif intent == "arrive_items":
|
||||
await decisions.start_arrive(ctx, chat_id, user, patch)
|
||||
else:
|
||||
await ctx.send(chat_id, UNKNOWN_HINT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _gate(ctx: BotContext, chat_id: int, message: dict) -> LinkedUser | None:
|
||||
"""Link or admin gate. Returns None when the message was consumed by linking."""
|
||||
from . import links
|
||||
|
||||
link = await ctx.links.get(chat_id)
|
||||
if link and link.user_id:
|
||||
return LinkedUser(chat_id, link.user_id, link.display_name, link.role, is_admin=False)
|
||||
if chat_id in ctx.admin_chat_ids:
|
||||
return LinkedUser(chat_id, None, None, None, is_admin=True)
|
||||
|
||||
flow = ctx.pending.get(chat_id)
|
||||
if flow and flow.kind == "link_password":
|
||||
await links.finish_link(ctx, chat_id, flow, text=None, password=message.get("text") or "")
|
||||
return None
|
||||
if flow and flow.kind == "link_username":
|
||||
await links.finish_username_step(ctx, chat_id, flow, message.get("text") or "")
|
||||
return None
|
||||
await ctx.send(chat_id, LINK_START)
|
||||
ctx.pending.set(chat_id, "link_username", {})
|
||||
return None
|
||||
|
||||
|
||||
async def _route_to_flow(ctx: BotContext, chat_id: int, flow, text: str) -> bool:
|
||||
from . import links, decisions
|
||||
|
||||
if flow.kind == "link_username":
|
||||
await links.finish_username_step(ctx, chat_id, flow, text)
|
||||
return True
|
||||
if flow.kind == "link_password":
|
||||
await links.finish_link(ctx, chat_id, flow, text=text, password=text)
|
||||
return True
|
||||
if flow.kind == "quote_pick":
|
||||
await decisions.handle_quote_pick_text(ctx, chat_id, flow, text)
|
||||
return True
|
||||
if flow.kind in ("accept", "arrive_qty", "arrive_confirm"):
|
||||
return await decisions.handle_flow_text(ctx, chat_id, flow, text)
|
||||
return False
|
||||
|
||||
|
||||
def _draft_summary(draft) -> str | None:
|
||||
if draft is None:
|
||||
return None
|
||||
import json
|
||||
|
||||
payload = draft.payload or {}
|
||||
if draft.kind == draft_store.KIND_QUOTE:
|
||||
items = ", ".join(
|
||||
f"{it.get('material_name') or '?'}"
|
||||
+ (f" {it.get('quantity')}" if it.get("quantity") else "")
|
||||
+ (f" {it.get('unit_name')}" if it.get("unit_name") else "")
|
||||
for it in payload.get("items") or []
|
||||
)
|
||||
summary = (
|
||||
f"kind=quote; supplier={payload.get('supplier_name') or '?'}; project={payload.get('project_name') or '?'}; "
|
||||
f"items=[{items}]; terms={[t.get('label') for t in payload.get('termsheets') or []]}"
|
||||
)
|
||||
elif draft.kind == draft_store.KIND_SUPPLIER:
|
||||
summary = f"kind=add_supplier; name={payload.get('name') or '?'}; category={payload.get('category_name') or '?'}"
|
||||
elif draft.kind == draft_store.KIND_MATERIAL:
|
||||
summary = f"kind=add_material; name={payload.get('name') or '?'}; unit={payload.get('unit_name') or '?'}"
|
||||
else:
|
||||
summary = json.dumps(payload, ensure_ascii=False)[:500]
|
||||
return summary
|
||||
Reference in New Issue
Block a user