Files
aimsight-app/app/server/suggestions.py
T

45 lines
2.3 KiB
Python
Raw Normal View History

"""The Suggestions page: the support agent's suggestions (~/aimsight-support), read-only from the Supabase project
Conversations (table suggestions, bucket suggestions): per customer message, its status, the reason it was left to a
person, or the draft reply and its figures to paste into the mail. The person sends it from LibreDesk; nothing is sent
from here. SUPABASE_CONVERSATIONS_URL and SUPABASE_CONVERSATIONS_KEY come from the app's environment (.env through the
service's EnvironmentFile); standard library only.
"""
import json
import os
import re
import urllib.parse
import urllib.request
import station
FIGURE = re.compile(r"^\d+/\d+\.png$") # <suggestion id>/<n>.png, as the agent writes them
MISSING = "no SUPABASE_CONVERSATIONS_URL / SUPABASE_CONVERSATIONS_KEY in the app's environment (README)"
def _get(path: str) -> bytes:
url, key = os.environ.get("SUPABASE_CONVERSATIONS_URL"), os.environ.get("SUPABASE_CONVERSATIONS_KEY")
if not url or not key:
raise station.Refusal(MISSING)
r = urllib.request.Request(url.rstrip("/") + path, headers={"apikey": key})
if key.startswith("eyJ"): # an old JWT key; a new sb_secret_ key goes only in apikey
r.add_header("Authorization", f"Bearer {key}")
with urllib.request.urlopen(r, timeout=30) as answer:
return answer.read()
def list_suggestions() -> list[dict]:
"""The latest 200 suggestions, newest first, each with its conversation's reference and subject."""
if not os.environ.get("SUPABASE_CONVERSATIONS_URL") or not os.environ.get("SUPABASE_CONVERSATIONS_KEY"):
raise station.Refusal(MISSING)
rows = json.loads(_get("/rest/v1/suggestions?select=*&order=created_at.desc&limit=200"))
uuids = ",".join(sorted({r["conversation_uuid"] for r in rows}))
convs = {c["uuid"]: c for c in json.loads(_get(
f"/rest/v1/conversations?select=uuid,reference_number,subject&uuid=in.({urllib.parse.quote(uuids)})"))} if rows else {}
return [r | {"reference": convs.get(r["conversation_uuid"], {}).get("reference_number", ""),
"subject": convs.get(r["conversation_uuid"], {}).get("subject", "")} for r in rows]
def figure(path: str) -> bytes:
if not FIGURE.match(path):
raise station.Refusal(f"not a suggestion figure: {path}")
return _get(f"/storage/v1/object/suggestions/{path}")