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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import sqlite3
|
| 5 |
+
import logging
|
| 6 |
+
import threading
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import List, Dict, Any, Optional
|
| 9 |
+
from supabase import create_client, Client
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
# Local fallback queue. If Supabase is unreachable, save_report writes here
|
| 14 |
+
# so the report is never lost. flush_pending() can be called periodically to
|
| 15 |
+
# replay. The HF container has ephemeral disk, so this only protects against
|
| 16 |
+
# transient outages, not full container loss — that's acceptable.
|
| 17 |
+
_DEFAULT_FALLBACK_PATH = os.getenv(
|
| 18 |
+
"OPS_FALLBACK_DB", str(Path(__file__).parent.parent / ".ops_fallback.db")
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class StoreDB:
|
| 23 |
+
def __init__(self, url: str, key: str, fallback_path: str = _DEFAULT_FALLBACK_PATH):
|
| 24 |
+
if not url or not key:
|
| 25 |
+
raise ValueError("StoreDB: Supabase url and key are required")
|
| 26 |
+
self.supabase: Client = create_client(url, key)
|
| 27 |
+
self._fb_path = fallback_path
|
| 28 |
+
self._fb_lock = threading.Lock()
|
| 29 |
+
self._init_fallback()
|
| 30 |
+
|
| 31 |
+
# ─── Fallback queue (SQLite WAL) ────────────────────────────────────────────
|
| 32 |
+
def _init_fallback(self) -> None:
|
| 33 |
+
try:
|
| 34 |
+
with sqlite3.connect(self._fb_path) as conn:
|
| 35 |
+
# WAL = crash-safe + concurrent readers
|
| 36 |
+
conn.execute("PRAGMA journal_mode=WAL;")
|
| 37 |
+
conn.execute(
|
| 38 |
+
"""
|
| 39 |
+
CREATE TABLE IF NOT EXISTS pending_reports (
|
| 40 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 41 |
+
payload TEXT NOT NULL,
|
| 42 |
+
attempts INTEGER NOT NULL DEFAULT 0,
|
| 43 |
+
last_error TEXT,
|
| 44 |
+
created_at REAL NOT NULL
|
| 45 |
+
);
|
| 46 |
+
"""
|
| 47 |
+
)
|
| 48 |
+
conn.commit()
|
| 49 |
+
except Exception as e:
|
| 50 |
+
logger.warning("StoreDB: could not init fallback queue at %s: %s", self._fb_path, e)
|
| 51 |
+
|
| 52 |
+
def _queue_pending(self, payload: Dict[str, Any], last_error: str) -> None:
|
| 53 |
+
try:
|
| 54 |
+
with self._fb_lock, sqlite3.connect(self._fb_path) as conn:
|
| 55 |
+
conn.execute(
|
| 56 |
+
"INSERT INTO pending_reports (payload, attempts, last_error, created_at) "
|
| 57 |
+
"VALUES (?, ?, ?, ?)",
|
| 58 |
+
(json.dumps(payload, default=str), 99, last_error[:500], time.time()),
|
| 59 |
+
)
|
| 60 |
+
conn.commit()
|
| 61 |
+
except Exception as e:
|
| 62 |
+
logger.error("StoreDB: failed to queue pending report: %s", e)
|
| 63 |
+
|
| 64 |
+
def flush_pending(self, max_items: int = 50) -> int:
|
| 65 |
+
"""
|
| 66 |
+
Try to replay queued reports into Supabase. Returns number successfully flushed.
|
| 67 |
+
Safe to call periodically (e.g. hourly cron / health endpoint).
|
| 68 |
+
"""
|
| 69 |
+
flushed = 0
|
| 70 |
+
try:
|
| 71 |
+
with self._fb_lock, sqlite3.connect(self._fb_path) as conn:
|
| 72 |
+
conn.row_factory = sqlite3.Row
|
| 73 |
+
rows = conn.execute(
|
| 74 |
+
"SELECT id, payload FROM pending_reports ORDER BY id ASC LIMIT ?",
|
| 75 |
+
(max_items,),
|
| 76 |
+
).fetchall()
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logger.warning("StoreDB.flush_pending: could not read queue: %s", e)
|
| 79 |
+
return 0
|
| 80 |
+
|
| 81 |
+
for row in rows:
|
| 82 |
+
try:
|
| 83 |
+
payload = json.loads(row["payload"])
|
| 84 |
+
self.supabase.table("store_reports").insert(payload).execute()
|
| 85 |
+
with self._fb_lock, sqlite3.connect(self._fb_path) as conn:
|
| 86 |
+
conn.execute("DELETE FROM pending_reports WHERE id = ?", (row["id"],))
|
| 87 |
+
conn.commit()
|
| 88 |
+
flushed += 1
|
| 89 |
+
except Exception as e:
|
| 90 |
+
logger.warning("StoreDB.flush_pending: replay failed for id=%s: %s", row["id"], e)
|
| 91 |
+
with self._fb_lock, sqlite3.connect(self._fb_path) as conn:
|
| 92 |
+
conn.execute(
|
| 93 |
+
"UPDATE pending_reports SET attempts = attempts + 1, last_error = ? WHERE id = ?",
|
| 94 |
+
(str(e)[:500], row["id"]),
|
| 95 |
+
)
|
| 96 |
+
conn.commit()
|
| 97 |
+
return flushed
|
| 98 |
+
|
| 99 |
+
def pending_count(self) -> int:
|
| 100 |
+
try:
|
| 101 |
+
with self._fb_lock, sqlite3.connect(self._fb_path) as conn:
|
| 102 |
+
cur = conn.execute("SELECT COUNT(*) FROM pending_reports")
|
| 103 |
+
return int(cur.fetchone()[0])
|
| 104 |
+
except Exception:
|
| 105 |
+
return -1
|
| 106 |
+
|
| 107 |
+
# ─── Public API ─────────────────────────────────────────────────────────────
|
| 108 |
+
def save_report(self, report_data: Dict[str, Any]) -> Any:
|
| 109 |
+
"""
|
| 110 |
+
Saves a parsed report to the 'store_reports' table.
|
| 111 |
+
On Supabase failure, queues the report locally so it's not lost.
|
| 112 |
+
"""
|
| 113 |
+
data = {
|
| 114 |
+
"store_id": report_data.get("store_id"),
|
| 115 |
+
"sales": (report_data.get("metrics") or {}).get("sales"),
|
| 116 |
+
"inventory_status": (report_data.get("metrics") or {}).get("inventory_status"),
|
| 117 |
+
"staffing": (report_data.get("metrics") or {}).get("staffing"),
|
| 118 |
+
"issues": report_data.get("issues") or [],
|
| 119 |
+
"analysis": report_data.get("analysis"),
|
| 120 |
+
"actions": report_data.get("actions_needed") or [],
|
| 121 |
+
"report_date": time.strftime('%Y-%m-%d') # Force ISO date for Dashboard sync
|
| 122 |
+
}
|
| 123 |
+
try:
|
| 124 |
+
return self.supabase.table("store_reports").insert(data).execute()
|
| 125 |
+
except Exception as e:
|
| 126 |
+
logger.error("StoreDB.save_report: Supabase insert failed, queuing locally: %s", e)
|
| 127 |
+
self._queue_pending(data, str(e))
|
| 128 |
+
# Re-raise so the caller (Telegram handler) can decide UX.
|
| 129 |
+
raise
|
| 130 |
+
|
| 131 |
+
def get_latest_reports(self, limit: int = 20) -> Any:
|
| 132 |
+
return (
|
| 133 |
+
self.supabase.table("store_reports")
|
| 134 |
+
.select("*")
|
| 135 |
+
.order("created_at", desc=True)
|
| 136 |
+
.limit(limit)
|
| 137 |
+
.execute()
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def get_all_store_summaries(self) -> Any:
|
| 141 |
+
return self.supabase.table("store_reports").select("*").execute()
|
| 142 |
+
|
| 143 |
+
def get_recent_operator_actions(self, limit: int = 50) -> Any:
|
| 144 |
+
"""For the dashboard's operator log panel."""
|
| 145 |
+
return (
|
| 146 |
+
self.supabase.table("operator_logs")
|
| 147 |
+
.select("*")
|
| 148 |
+
.order("timestamp", desc=True)
|
| 149 |
+
.limit(limit)
|
| 150 |
+
.execute()
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def log_operator_action(self, store_id: str, action: str, notes: str) -> Any:
|
| 154 |
+
"""
|
| 155 |
+
Logs a manual operator correction/intervention to a separate audit table.
|
| 156 |
+
"""
|
| 157 |
+
data = {
|
| 158 |
+
"store_id": store_id,
|
| 159 |
+
"action_type": action,
|
| 160 |
+
"notes": notes,
|
| 161 |
+
"timestamp": "now()",
|
| 162 |
+
}
|
| 163 |
+
return self.supabase.table("operator_logs").insert(data).execute()
|
| 164 |
+
|
| 165 |
+
def save_bulk_reports(self, reports: List[Dict[str, Any]]) -> Any:
|
| 166 |
+
"""
|
| 167 |
+
Saves a list of reports in a single batch operation.
|
| 168 |
+
Essential for processing large Excel/CSV imports without hitting API limits.
|
| 169 |
+
"""
|
| 170 |
+
try:
|
| 171 |
+
return self.supabase.table("store_reports").insert(reports).execute()
|
| 172 |
+
except Exception as e:
|
| 173 |
+
logger.error("StoreDB.save_bulk_reports: Batch insert failed: %s", e)
|
| 174 |
+
for report in reports:
|
| 175 |
+
try:
|
| 176 |
+
self.save_report(report)
|
| 177 |
+
except:
|
| 178 |
+
pass
|
| 179 |
+
raise e
|
brain/ops_brain.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import logging
|
| 5 |
+
from typing import List, Dict, Any, Optional
|
| 6 |
+
from groq import Groq
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
# Default model. Groq deprecated `llama-3.3-70b-versatile` — llama-3.1-70b
|
| 11 |
+
# is the supported current SKU. Override via env for fast A/B.
|
| 12 |
+
DEFAULT_MODEL = os.getenv("OPS_BRAIN_MODEL", "llama-3.1-70b-versatile")
|
| 13 |
+
|
| 14 |
+
GROQ_TIMEOUT_S = 15.0
|
| 15 |
+
GROQ_MAX_RETRIES = 2
|
| 16 |
+
GROQ_RETRY_BACKOFF_S = 1.5
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _safe_json_loads(raw: str) -> Optional[Dict[str, Any]]:
|
| 20 |
+
"""
|
| 21 |
+
Parse JSON from a model response, tolerating stray prose / markdown fences.
|
| 22 |
+
Returns None if unparseable.
|
| 23 |
+
"""
|
| 24 |
+
if not raw:
|
| 25 |
+
return None
|
| 26 |
+
text = raw.strip()
|
| 27 |
+
|
| 28 |
+
# Strip ```json ... ``` fences if present.
|
| 29 |
+
if text.startswith("```"):
|
| 30 |
+
first_nl = text.find("\n")
|
| 31 |
+
if first_nl != -1:
|
| 32 |
+
text = text[first_nl + 1 :]
|
| 33 |
+
if text.endswith("```"):
|
| 34 |
+
text = text[:-3]
|
| 35 |
+
|
| 36 |
+
# First attempt: strict.
|
| 37 |
+
try:
|
| 38 |
+
return json.loads(text)
|
| 39 |
+
except json.JSONDecodeError:
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
# Second attempt: find the first '{' and last '}' and try that slice.
|
| 43 |
+
start = text.find("{")
|
| 44 |
+
end = text.rfind("}")
|
| 45 |
+
if start != -1 and end != -1 and end > start:
|
| 46 |
+
try:
|
| 47 |
+
return json.loads(text[start : end + 1])
|
| 48 |
+
except json.JSONDecodeError:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
logger.error("ops_brain: could not parse JSON from model output: %r", raw[:300])
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _groq_chat(client: Groq, prompt: str, model: str) -> Optional[Dict[str, Any]]:
|
| 56 |
+
"""Call Groq with timeout, retry, and JSON repair."""
|
| 57 |
+
last_err: Optional[Exception] = None
|
| 58 |
+
for attempt in range(1, GROQ_MAX_RETRIES + 1):
|
| 59 |
+
try:
|
| 60 |
+
completion = client.chat.completions.create(
|
| 61 |
+
model=model,
|
| 62 |
+
messages=[{"role": "user", "content": prompt}],
|
| 63 |
+
response_format={"type": "json_object"},
|
| 64 |
+
timeout=GROQ_TIMEOUT_S,
|
| 65 |
+
)
|
| 66 |
+
raw = completion.choices[0].message.content
|
| 67 |
+
parsed = _safe_json_loads(raw)
|
| 68 |
+
if parsed is not None:
|
| 69 |
+
return parsed
|
| 70 |
+
last_err = ValueError("json parse failed")
|
| 71 |
+
except Exception as e: # groq.GroqError, httpx.TimeoutException, etc.
|
| 72 |
+
last_err = e
|
| 73 |
+
logger.warning("ops_brain: groq attempt %d/%d failed: %s", attempt, GROQ_MAX_RETRIES, e)
|
| 74 |
+
|
| 75 |
+
if attempt < GROQ_MAX_RETRIES:
|
| 76 |
+
time.sleep(GROQ_RETRY_BACKOFF_S * attempt)
|
| 77 |
+
|
| 78 |
+
logger.error("ops_brain: giving up after %d attempts. last_err=%s", GROQ_MAX_RETRIES, last_err)
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class OpsManagerAI:
|
| 83 |
+
def __init__(self, api_key: str, model: str = DEFAULT_MODEL):
|
| 84 |
+
if not api_key or not api_key.strip():
|
| 85 |
+
raise ValueError("OpsManagerAI: api_key is empty")
|
| 86 |
+
self.client = Groq(api_key=api_key)
|
| 87 |
+
self.model = model
|
| 88 |
+
|
| 89 |
+
def process_telegram_message(self, text: str) -> Dict[str, Any]:
|
| 90 |
+
"""
|
| 91 |
+
Parses store reports into structured JSON using Groq.
|
| 92 |
+
Returns a safe-default dict (with store_id=None) if the model fails,
|
| 93 |
+
so the bot never crashes the handler thread.
|
| 94 |
+
"""
|
| 95 |
+
prompt = f"""
|
| 96 |
+
You are a Professional AI Operations Manager. Your task is to parse store reports into a strict JSON format.
|
| 97 |
+
|
| 98 |
+
The user provides reports in a specific template like:
|
| 99 |
+
'Daily Update [ Store Name ] Date: [Date] 💵 Sales:; (Value) 🛍️Transactions: [Value] 📊Average Transaction (AT): [Value] ⬆️⬇️AT Yesterday[ Value]'
|
| 100 |
+
|
| 101 |
+
Input Text: {text}
|
| 102 |
+
|
| 103 |
+
Required JSON Output:
|
| 104 |
+
{{
|
| 105 |
+
"store_id": "Extract the name inside the brackets [ ]",
|
| 106 |
+
"metrics": {{
|
| 107 |
+
"sales": float or null,
|
| 108 |
+
"inventory_status": "Good|Warning|Critical",
|
| 109 |
+
"staffing": "OK|Understaffed|Overstaffed"
|
| 110 |
+
}},
|
| 111 |
+
"issues": ["List any mentioned anomalies or low stock, otherwise empty"],
|
| 112 |
+
"analysis": "A brief analytical summary of the store's health today",
|
| 113 |
+
"actions_needed": ["Concrete, actionable steps based on the sales/AT trends"]
|
| 114 |
+
}}
|
| 115 |
+
Return ONLY the JSON object. No preamble.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
parsed = _groq_chat(self.client, prompt, self.model)
|
| 119 |
+
if parsed is not None and parsed.get("store_id"):
|
| 120 |
+
return parsed
|
| 121 |
+
|
| 122 |
+
# Safe fallback so caller can decide to reply with an error instead of crashing.
|
| 123 |
+
return {
|
| 124 |
+
"store_id": None,
|
| 125 |
+
"metrics": {"sales": None, "inventory_status": None, "staffing": None},
|
| 126 |
+
"issues": [],
|
| 127 |
+
"analysis": "AI could not extract a valid store report from the message.",
|
| 128 |
+
"actions_needed": [],
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
def generate_hot_list_analysis(self, all_stores_data: List[Dict]) -> Dict[str, Any]:
|
| 132 |
+
"""
|
| 133 |
+
Analyze the full fleet to find critical areas.
|
| 134 |
+
"""
|
| 135 |
+
prompt = f"""
|
| 136 |
+
Analyze the following store data and provide a strategic operation summary.
|
| 137 |
+
Data: {json.dumps(all_stores_data)}
|
| 138 |
+
|
| 139 |
+
Return JSON:
|
| 140 |
+
{{
|
| 141 |
+
"top_performers": ["Store name"],
|
| 142 |
+
"critical_stores": ["Store name"],
|
| 143 |
+
"global_dev_area": "General area needing improvement",
|
| 144 |
+
"strategic_priority": "Top immediate action for the owner"
|
| 145 |
+
}}
|
| 146 |
+
Return ONLY JSON.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
parsed = _groq_chat(self.client, prompt, self.model)
|
| 150 |
+
if parsed is not None:
|
| 151 |
+
return parsed
|
| 152 |
+
return {
|
| 153 |
+
"top_performers": [],
|
| 154 |
+
"critical_stores": [],
|
| 155 |
+
"global_dev_area": "AI analysis unavailable.",
|
| 156 |
+
"strategic_priority": "Manual review required.",
|
| 157 |
+
}
|