Files
ERP/bot
whqreza 0adadd2cf8 feat(monitoring): bot observability dashboards — Grafana + Persian RTL ERP page
Grafana (full use of the existing monitoring/ stack, per OSS policy):
- datasources.yml: BotPostgres (uid bot-postgres) over the shared network;
  grafana service joins 'shared' + carries the datasource env
- db_init.py: idempotent read-only role obs_reader (USAGE on schema public +
  SELECT on bot_traces/bot_trace_events; skipped when
  OBS_READER_PASSWORD empty; ALTER ROLE for rotation) + composite index
  ix_bot_trace_events_stage_time (stage, created_at DESC) — senior-engineer
  review applied with the column-name fix (event_type -> stage); (trace_id)
  already covered by the existing (trace_id, created_at) index
- dashboards/bot-observability.json: KPI row (real traffic, events, Jev/
  fallback errors, Jev p95, tokens, commits, archive guard), events/day,
  per-stage p50/p95, mention statuses (arbiter+fallback aggregates + legacy
  rows), DeepSeek arbiter actions, tokens/day, model-drift vs jev-1.13.0,
  user-choice A/B, STT + audio.enhance health, archive size guard
- dashboards/bot-trace-explorer.json: trace table + full event drill-down
  via the trace_id variable

ERP page (admin-only, Persian RTL, recharts@^3 for React 19):
- backend bot_metrics.py: read-only require_role('admin') endpoints
  (summary/routing/quality/jev/stt/traces + trace detail); aggregates count
  real traffic only (calibration/demo/chat_id=0 excluded)
- frontend BotMonitorPage at /bot-monitor (KPI cards, daily events,
  status donut, arbiter actions, user-choice A/B, STT/enhance tables,
  stage latency, tokens chart, traces table + detail drawer with payload
  viewer); entry link from the admin panel; MobileTabBar hidden there
- api.ts: typed botMetrics client section

Tooling/docs:
- tools/seed_observability_demo.py: deterministic demo traces (source='demo',
  every current pipeline stage incl. audio.enhance/jev.failure/arbitration/
  fallback/user choices) — excluded from real-traffic aggregates
- monitoring/README.md + bot/docs/DEPLOY-AND-MONITORING.md: setup, seed and
  rollback notes; alerts deliberately deferred (owner decision 2026-10-24)

Verified locally: obs_reader SELECT ok / INSERT denied; panels' SQL run as
obs_reader with data; datasource health OK; both dashboards survive a grafana
restart; endpoints 200 as admin and 403 without role; tsc + vite build clean;
page renders in-browser (admin session); bot startup provisions role+index.
2026-10-24 15:09:01 +03:30
..

procurement_ai_agent — Bale chatbot for the procurement ERP

A Bale messenger bot that turns Persian chat messages and voice notes into procurement actions in the procurement ERP — draft-first: it captures what it understood, tells you what it did and what is still empty, and commits only after you approve with a ✅ button.

you (Bale, text/voice)                      ┌─────────────────────────────────┐
        │  getUpdates (long poll)           │        procurement_ai_agent     │
        ▼                                   │  ffmpeg → STT (Persian)         │
┌──────────────────┐   POST {base}/bot<T>    │  LLM → intent + entities        │
│   tapi.bale.ai   │◄───────────────────────►│  fuzzy resolve → draft payload  │
└──────────────────┘   sendMessage / buttons │  review + «چه چیزهایی خالی مونده»│
                                             └───────────────┬─────────────────┘
                                                             │ HTTP + X-Actor-Id
                                                             ▼
                                             ┌─────────────────────────────────┐
                                             │   ERP api  (/api/v1)            │
                                             │   quotes · suppliers · materials│
                                             └─────────────────────────────────┘

What it can do

Activity Example (voice or text) Committed via
Register a supplier quote «سازان نو برای پروژه برج آسمان ۵۰۰ کیلو میلگرد A3 سایز ۱۴، هر کیلو ۴۵ تومن، پرداخت ۳ فاز» POST /quotes
Add a supplier «تأمین‌کننده جدید پروفیل بر، دسته لوله و اتصالات، تلفن ۰۹۱۲…» POST /suppliers
Add a material «کالای جدید میلگرد A3 سایز ۱۸ با واحد کیلوگرم» POST /materials
Status queries «استعلام‌های در انتظار؟» / «کدام‌ها به‌زودی منقضی می‌شوند؟» GET /quotes?…
Accept a quote «استعلام سازان نو را قبول کن» PATCH /quotes/{id}/accept
Announce a delivery «اقلام سازان نو رسید، ۵۰۰ و ۲۰۰» PATCH /quotes/{id}/arrive-items

The draft → approve loop

  1. Send a message or voice note. Voice → ffmpeg → STT; text/STT text → LLM extracts a typed intent + entities (JSON mode, Persian digits normalized).
  2. Names are fuzzy-matched against the ERP. Several candidates → inline pick buttons; no match → listed as missing.
  3. The bot replies with a review card: everything captured + a ✅/⚠️/❌ list of what is still empty.
  4. Keep chatting to refine («قیمت میلگرد ۴۷ شد») — the open draft updates and re-renders. Drafts survive bot restarts (postgres-backed, TTL-swept).
  5. Nothing is written to the ERP until you tap ✅. After commit you get the created quote id and the fields left empty.

Team access & attribution

Each member links their Bale chat once: /start → Casdoor username → password (validated via the ERP's real POST /auth/login, used once, never stored). Every mutating call carries X-Actor-Id: <users.id> so quote_events.actor records the human who asked.

Commands: /start · /help · /drafts · /cancel · /whoami · /unlink

Quick start (Docker)

cp .env.example .env          # fill PROCUREMENT_BOT_BOT_TOKEN + AI_API_KEY
docker build -t procurement-ai-agent .
docker run -d --name procurement-bot --env-file .env \
  --add-host host.docker.internal:host-gateway \
  procurement-ai-agent
docker logs -f procurement-bot

Or as part of the ERP stack — see integration/ (compose service + the one tiny ERP-side patch).

Full setup, env-var reference, flows and troubleshooting: docs/SETUP.md.

Architecture

app/
├── main.py          ensure bot tables → sweeper task → getUpdates long-poll loop
├── config.py        pydantic-settings, PROCUREMENT_BOT_ prefix
├── bale/client.py   Telegram-compatible Bale API (poll, send, edit, buttons, files)
├── api/client.py    ERP /api/v1 client (X-Actor-Id attribution, error envelope)
├── stt.py           ffmpeg (OGG/Opus → MP3) → OpenAI-compatible /audio/transcriptions
├── nlu.py           Persian intent+entity extraction (JSON-mode chat completions)
├── resolve.py       fuzzy name→id matching (difflib over ilike search), TTL caches
├── drafts.py        draft store · QuoteCreate payload builder · missing-field logic
├── keyboards.py     inline keyboards (callback_data ≤ 64 B op-codes)
├── texts.py         Persian message templates
├── runtime.py       context, link store, in-memory pending flows
├── models.py        bot_links / bot_drafts / bot_messages / bot_meta (own schema)
└── handlers/        dispatch · commands · callbacks · links ·
                     quote · supplier · material · queries · decisions

Design notes:

  • Telegram-compatible Bale API (tapi.bale.ai): getUpdates long polling — no public port, no webhook, resumable offset persisted across restarts.
  • Draft-first: bot_drafts.payload holds a talking-friendly JSON that is converted into the exact POST /quotes request body (temp_id cross-references) only on approval; the API deliberately tolerates incomplete quotes, so partial commits are explicit, never accidental.
  • Accept flow echoes the termsheet's existing schedule_steps back to PATCH /quotes/{id}/accept (the API replaces steps with what it receives).
  • Persian-aware matching: Persian/Arabic digit normalization, ZWNJ folding, Arabic ya/ka folding, difflib ranking on top of the API's ilike search.
  • Voice notes arrive as OGG/Opus; ffmpeg converts to mono 16 kHz MP3 before STT. The LLM provider and the STT provider are configured independently (e.g. DeepSeek for NLU + any whisper-compatible endpoint for voice).

Testing

An offline end-to-end harness stubs Bale/ERP/AI and drives the real handler pipeline with fake updates — no token, DB or API key needed:

pip install -r requirements.txt
python tools/smoke_test.py     # → ALL PASSED: 48 passed