Download app.py from ineeds/now: direct link, hf CLI and curl.
- Browser
- Download file 140 kB
-
https://huggingface.co/spaces/ineeds/now/resolve/main/app.py
- Command line
-
hf download hf://spaces/ineeds/now/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ineeds/now/resolve/main/app.py
140 kB
import json, os, uuid, sqlite3, time, base64, re, io, asyncio, hashlib, hmac
import logging
from pathlib import Path
from datetime import datetime, timezone, timedelta
from typing import Any
import gradio as gr
try:
import spaces
except ImportError:
spaces = None
from starlette.middleware import Middleware
from starlette.types import ASGIApp, Scope, Receive, Send
from fastapi import FastAPI, HTTPException, Request, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import Response
import bcrypt
import requests
from jose import jwt
from pydantic import BaseModel, Field, validator
from database import (
get_db as _db_get, close_db as _db_close, fetch_one, fetch_all,
execute as db_execute, commit as db_commit, rollback as db_rollback,
init_db as _db_init, IS_POSTGRES, close_all as db_close_all,
)
from cache import cache_get, cache_set, cache_delete, cache_clear, close_cache
log = logging.getLogger("ineed-now")
# ββ Config ββ
_data_dir = Path("/data")
if not _data_dir.exists():
_data_dir = Path(__file__).parent / "data"
_data_dir.mkdir(exist_ok=True)
DB_PATH = str(_data_dir / "app.db")
JWT_SECRET = os.environ.get("JWT_SECRET", "super-secret-key-change-in-production")
JWT_ALGORITHM = "HS256"
IMAGEKIT_PRIVATE_KEY = os.environ.get("IMAGEKIT_PRIVATE_KEY", "")
IMAGEKIT_URL_ENDPOINT = os.environ.get("IMAGEKIT_URL_ENDPOINT", "https://ik.imagekit.io/ceo2gbv21")
JWT_EXPIRE_HOURS = 24 # 24 hours (was 10 years β reduced for security)
JWT_REFRESH_EXPIRE_HOURS = 7 * 24 # Refresh token lasts 7 days
dist = Path(__file__).parent / "dist"
# ββ Database (delegated to database.py) ββ
def get_db():
"""Legacy wrapper β returns a connection via the abstraction layer."""
return _db_get()
def _close(conn):
"""Legacy wrapper β closes/returns connection to pool."""
_db_close(conn)
def _to_dict(row) -> dict:
"""Convert a row (sqlite3.Row or DictRow) to a plain dict."""
if row is None:
return {}
if hasattr(row, 'dict'):
return row.dict()
return dict(row)
def _setting(key: str, default: str = "") -> str:
"""Read a single system_settings value with Redis cache."""
cache_key = f"setting:{key}"
cached = cache_get(cache_key)
if cached is not None:
return cached
conn = get_db()
try:
if IS_POSTGRES:
row = fetch_one(conn, "SELECT setting_value FROM system_settings WHERE setting_key=%s", (key,))
else:
row = fetch_one(conn, "SELECT setting_value FROM system_settings WHERE setting_key=?", (key,))
val = _to_dict(row).get("setting_value", default) if row else default
finally:
_close(conn)
cache_set(cache_key, val, ttl=600)
return val
def _invalidate_settings_cache():
"""Clear all cached settings."""
cache_clear("setting:*")
def init_db():
"""Initialize database schema and seed data."""
_db_init()
# SQLite-specific seeds (PostgreSQL uses schema.sql)
if not IS_POSTGRES:
_seed_sqlite()
def _seed_sqlite():
"""Seed default data for SQLite (PostgreSQL uses schema.sql)."""
conn = get_db()
try:
count = conn.execute("SELECT COUNT(*) FROM system_settings").fetchone()[0]
if count == 0:
conn.executemany(
"INSERT OR IGNORE INTO system_settings (setting_key, setting_value, description) VALUES (?,?,?)",
[("store_name", "My Store", "Store display name"),
("store_phone", "", "Store contact phone"),
("currency", "LAK", "Default currency"),
("tax_percent", "7", "Default tax rate"),
("store_logo", "", "Store logo URL")])
if conn.execute("SELECT COUNT(*) FROM system_settings WHERE setting_key LIKE 'ai_%'").fetchone()[0] == 0:
env_keys = os.environ.get("OPENAI_API_KEYS", "").strip()
keys = [k.strip() for k in env_keys.split(",") if k.strip()] if env_keys else [
"sk-80me9SFL8uQb7pSZat1Szon1pxyhYZDScfA0jvmLG3WEZTQb8owNgXN84hGNHRqg",
"sk-4YsUfewUpwSzX61w5Jg8ODDPdPjlEXNN6FsrjVDj2n6TUINloMKF8ShiDdlyIwZ0",
"sk-DhLK6jcWe8gs8yWFlnFnNYQI9LQHtvoQwXcIay9K5VTKApzROHfFDdzjrIUFsIQz",
]
store = conn.execute("SELECT setting_value FROM system_settings WHERE setting_key='store_name'").fetchone()
sname = store["setting_value"] if store else "ineed-now"
default_prompt = (_DEFAULT_AI_PROMPT
.replace("{agent}", "ineed-now Assistant")
.replace("{store}", sname)
.replace("{markers}", _PLAN_MARKER_START)
.replace("{end}", _PLAN_MARKER_END))
conn.executemany(
"INSERT OR IGNORE INTO system_settings (setting_key, setting_value, description) VALUES (?,?,?)",
[("ai_enabled", "true", "AI agent on/off"),
("ai_agent_name", "ineed-now Assistant", "Agent display name"),
("ai_model", "openrouter/free", "Chat model"),
("ai_base_url", "https://openrouter.ai/api/v1", "OpenAI-compatible base URL"),
("ai_api_keys", json.dumps(keys), "API keys, rotated automatically on rate limit"),
("ai_system_prompt", default_prompt, "System prompt for the AI agent"),
("ai_max_tokens", "900", "Max response tokens"),
("ai_temperature", "0.7", "Sampling temperature"),
("ai_models", json.dumps(_DEFAULT_AI_MODELS), "Available model choices (JSON array)")])
# Merge any newly-added default models into the existing list so old DBs stay current.
try:
row = conn.execute("SELECT setting_value FROM system_settings WHERE setting_key='ai_models'").fetchone()
if row:
existing = json.loads(row["setting_value"])
if not isinstance(existing, list):
existing = []
merged = list(existing)
added = False
for m in _DEFAULT_AI_MODELS:
if m not in merged:
merged.append(m)
added = True
if added:
conn.execute(
"UPDATE system_settings SET setting_value=?, updated_at=datetime('now') WHERE setting_key='ai_models'",
(json.dumps(merged),))
conn.commit()
except Exception:
pass
if conn.execute("SELECT COUNT(*) FROM categories").fetchone()[0] == 0:
conn.executemany(
"INSERT OR IGNORE INTO categories (id,name,slug,description,sort_order,is_active) VALUES (?,?,?,?,?,1)",
[("059d9d35-0230-44a2-b171-bfa66c41b917", "Electronics", "electronics", "Phones, tablets, and accessories", 1),
("7ca35ac8-fc4a-4078-8c75-5e00031b1512", "Clothing", "clothing", "Men and women fashion", 2),
("5c5f2981-25d3-414a-9cfe-6625d5560646", "Home & Garden", "home-garden", "Furniture and home decor", 3),
("bcc138c6-1b22-4cb2-9b41-08f688b2cb23", "Sports", "sports", "Sports equipment and gear", 4),
("5295dd27-badf-417b-a492-f9891fc0af04", "Books", "books", "Physical and digital books", 5)])
if conn.execute("SELECT COUNT(*) FROM products").fetchone()[0] == 0:
conn.executemany(
"""INSERT OR IGNORE INTO products
(id,name,slug,sku,category_id,description,cost_price,selling_price,compare_price,stock,images,is_featured,is_active)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",
_SEED_PRODUCTS)
if conn.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 0:
conn.execute("INSERT INTO users (id,email,password_hash,full_name,role,is_active) VALUES (?,?,?,?,?,?)",
(str(uuid.uuid4()), "admin@ineed-now.com",
bcrypt.hashpw(b"admin123", bcrypt.gensalt()).decode(), "Admin", "admin", 1))
if conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0] == 0:
row = conn.execute("SELECT id FROM users ORDER BY created_at ASC LIMIT 1").fetchone()
uid = row["id"] if row else str(uuid.uuid4())
for i in range(5):
statuses = ["pending", "confirmed", "processing", "shipped", "delivered"]
conn.execute(
"INSERT INTO orders (id,order_number,user_id,status,payment_status,grand_total) VALUES (?,?,?,?,?,?)",
(str(uuid.uuid4()), f"ORD-{int(time.time()*1000)}-{i}", uid,
statuses[i % len(statuses)], "paid" if i % 2 == 0 else "unpaid", round(50 + i * 30.5, 2)))
conn.commit()
finally:
_close(conn)
_SEED_PRODUCTS = [
("47ee8455-fb24-4923-87d7-a7e2cd955367", "Test Product", "test-product", "TP001", "", "Demo product", 50.00, 99.99, 0, 100, "[]", 0),
("33677a32-33ce-459e-817f-e4f9ec42821b", "iPhone 15 Pro Max", "iphone-15-pro-max", "IPH15PM", "059d9d35-0230-44a2-b171-bfa66c41b917", "Latest Apple smartphone with A17 Pro chip", 999.00, 1299.99, 0, 25, "[]", 1),
("ec02f33d-5ed9-42d4-8dc5-36a1dd8d114b", "Samsung Galaxy S24", "samsung-galaxy-s24", "SGS24", "059d9d35-0230-44a2-b171-bfa66c41b917", "Samsung flagship with AI features", 699.00, 899.99, 0, 30, "[]", 1),
("bf9cf888-cc33-4125-b855-a8184ce870f8", "MacBook Air M3", "macbook-air-m3", "MBA3", "059d9d35-0230-44a2-b171-bfa66c41b917", "Ultra-thin laptop with M3 chip", 899.00, 1099.99, 0, 15, "[]", 1),
("a0d2e3ef-9c30-435f-bf94-77c1d1248522", "AirPods Pro 2", "airpods-pro-2", "APP2", "059d9d35-0230-44a2-b171-bfa66c41b917", "Active noise cancelling earbuds", 179.99, 249.99, 0, 50, "[]", 0),
("b71f79af-c617-4dc5-be2a-6d2cfd8ea300", "USB-C Hub 7-in-1", "usb-c-hub-7in1", "USB7", "059d9d35-0230-44a2-b171-bfa66c41b917", "Multiport adapter for MacBook", 19.99, 39.99, 0, 100, "[]", 0),
("c78a62db-ef42-40c9-8449-c70ad101a249", "Classic Cotton T-Shirt", "classic-cotton-tshirt", "CCT01", "7ca35ac8-fc4a-4078-8c75-5e00031b1512", "100% cotton casual t-shirt", 10.00, 24.99, 0, 200, "[]", 0),
("7e9f5e51-87bc-42e6-9184-ce1794444a7d", "Denim Jacket", "denim-jacket", "DJ01", "7ca35ac8-fc4a-4078-8c75-5e00031b1512", "Vintage style denim jacket", 40.00, 79.99, 0, 50, "[]", 1),
("ef8849cb-dc14-4374-a35d-907f94e942c3", "Running Shoes Pro", "running-shoes-pro", "RSP01", "7ca35ac8-fc4a-4078-8c75-5e00031b1512", "Lightweight running shoes", 65.00, 129.99, 0, 75, "[]", 0),
("c5ed3df7-6b41-422d-b9f5-33548891cfcd", "Ergonomic Office Chair", "ergonomic-office-chair", "EOC01", "5c5f2981-25d3-414a-9cfe-6625d5560646", "Adjustable lumbar support chair", 180.00, 349.99, 0, 20, "[]", 1),
("ffac1073-feae-45c7-b526-ac0bff9e8eb1", "LED Desk Lamp", "led-desk-lamp", "LDL01", "5c5f2981-25d3-414a-9cfe-6625d5560646", "Dimmable LED desk lamp with USB port", 25.00, 49.99, 0, 60, "[]", 0),
("1aed088a-062b-4ae3-a909-4cd39c193f72", "Yoga Mat Premium", "yoga-mat-premium", "YMP01", "bcc138c6-1b22-4cb2-9b41-08f688b2cb23", "Non-slip exercise yoga mat", 15.00, 39.99, 0, 80, "[]", 0),
("68ed210a-d924-4c25-9059-025f1aa1efff", "Adjustable Dumbbells", "adjustable-dumbbells", "AD01", "bcc138c6-1b22-4cb2-9b41-08f688b2cb23", "5-25 lb adjustable dumbbell set", 100.00, 199.99, 0, 30, "[]", 1),
("c73518d7-8317-45d6-9fc5-14b3ae1da938", "The Art of Code", "the-art-of-code", "TAOC", "5295dd27-badf-417b-a492-f9891fc0af04", "Modern software engineering patterns", 10.00, 29.99, 0, 100, "[]", 0),
("11e47c7c-11ee-4bbe-bf81-45a94e02ec36", "Business Strategy 101", "business-strategy-101", "BS101", "5295dd27-badf-417b-a492-f9891fc0af04", "Essential business strategy guide", 12.00, 34.99, 0, 60, "[]", 0),
]
# ββ AI agent helpers (no GPU) ββ
_PLAN_MARKER_START = "[[PLAN_START]]"
_PLAN_MARKER_END = "[[PLAN_END]]"
_UI_MARKER_START = "[[UI_START]]"
_UI_MARKER_END = "[[UI_END]]"
_AI_STATE = {"key_idx": 0}
# Paid / general-purpose models (OpenAI, Anthropic, Google, DeepSeek, Groq, etc.)
_DEFAULT_AI_MODELS = [
"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o3-mini",
"claude-3-5-sonnet", "claude-3-5-haiku",
"gemini-1.5-pro", "gemini-1.5-flash",
"deepseek-chat", "deepseek-reasoner",
"llama-3.3-70b-versatile", "mixtral-8x7b-32768",
]
# Free models on OpenCode Zen (base_url https://opencode.ai/zen/v1)
_ZEN_FREE_MODELS = [
"mimo-v2.5-free",
"big-pickle", "hy3-preview-free", "hy3-free",
"deepseek-v4-flash-free",
"nemotron-3-ultra-free", "north-mini-code-free",
"laguna-s-2.1-free", "ling-3.0-flash-free", "minimax-m2.5-free",
]
# Free models on OpenRouter (base_url https://openrouter.ai/api/v1)
_OPENROUTER_FREE_MODELS = [
"openrouter/free",
"nvidia/nemotron-3-ultra-550b-a55b:free",
"nvidia/nemotron-3-super-120b-a12b:free",
"nvidia/nemotron-3-nano-30b-a3b:free",
"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free",
"google/gemma-4-31b-it:free",
"google/gemma-4-26b-a4b-it:free",
"openai/gpt-oss-20b:free",
"cohere/north-mini-code:free",
"inclusionai/ling-3.0-flash:free",
"poolside/laguna-s-2.1:free",
"poolside/laguna-xs-2.1:free",
"nvidia/nemotron-nano-12b-v2-vl:free",
"nvidia/nemotron-nano-9b-v2:free",
"xiaomi/mimo-v2.5:free",
]
_DEFAULT_AI_MODELS = _DEFAULT_AI_MODELS + _ZEN_FREE_MODELS + _OPENROUTER_FREE_MODELS
_DEFAULT_AI_PROMPT = """You are {agent}, a friendly AI assistant and booking agent for {store}.
Help users:
- discover and buy products from the catalog
- order food delivery
- plan trips and sightseeing itineraries
- find flights, hotels, hostels, apartments, and car rentals
- find land/house rentals and properties
- book anything they need
RULES:
1. Be concise, warm, and helpful. Reply in the same language the user writes in.
2. For any booking, order, itinerary, or plan, output a single structured plan between the markers.
3. Only recommend items that exist in the catalog below. Never invent prices or stock.
4. If the user asks for account or payment details, ask them to log in and check their account page.
5. If you cannot help, say so politely and offer the closest alternative.
6. Respect the user's auth status below: a guest must be asked to sign in before any booking/order/rental can be confirmed.
7. When appropriate, use interactive UI components to enhance responses (tables, lists, buttons, etc.).
8. NEVER show raw JSON, code blocks, or markup markers in your reply text. Write natural, friendly language.
- Use [[UI_START]]...[[UI_END]] for interactive components (tables, buttons, forms, etc.)
- Use [[PLAN_START]]...[[PLAN_END]] for booking/plan cards
- Your visible reply text should be clean, human-readable sentences only.
{CATALOG_CONTEXT}
{USER_CONTEXT}
{AUTH_CONTEXT}
When the user wants a booking/order/plan, wrap exactly one JSON object between these markers:
{markers}
{{"type": "trip", "title": "short title", "details": ["step 1", "step 2"], "estimate": "optional total in LAK"}}
{end}
Keep the JSON valid and compact (no markdown fences inside the markers).
DYNAMIC UI COMPONENTS:
When you want to show interactive UI elements, wrap them between UI markers:
[[UI_START]]
[
{{"id": "unique-id", "type": "table", "props": {{"columns": ["Name", "Price"], "rows": [["Item 1", "10000"], ["Item 2", "20000"]]}}}},
{{"id": "unique-id-2", "type": "button", "props": {{"label": "Click Me", "variant": "default"}}}}
]
[[UI_END]]
Available component types:
- table: {{"columns": [...], "rows": [[...], ...]}}
- checkbox: {{"label": "...", "checked": false, "badge": "optional"}}
- input: {{"label": "...", "placeholder": "...", "buttonLabel": "..."}}
- button: {{"label": "...", "variant": "default|outline|destructive|secondary", "size": "sm|default|lg"}}
- dropdown: {{"label": "...", "options": [{{"label": "...", "value": "..."}}], "placeholder": "..."}}
- collapse: {{"title": "...", "content": "...", "defaultOpen": false}}
- modal: {{"buttonLabel": "...", "title": "...", "description": "...", "content": "...", "actionLabel": "..."}}
- confirm: {{"buttonLabel": "...", "title": "...", "description": "...", "confirmLabel": "...", "confirmMessage": "..."}}
- alert: {{"variant": "info|success|warning|error", "title": "...", "message": "..."}}
- tabs: {{"tabs": [{{"label": "...", "content": "..."}}]}}
- progress: {{"label": "...", "value": 75}}
- heading: {{"level": 2, "text": "..."}}
- text: {{"text": "...", "className": "..."}}
- code: {{"code": "..."}}
- list: {{"items": ["..."], "ordered": false}}
- rating: {{"max": 5, "value": 3}}
- toggle: {{"label": "...", "checked": false}}
- stepper: {{"steps": ["Step 1", "Step 2", "Step 3"], "current": 1}}
- divider: {{}}
- image: {{"src": "...", "alt": "...", "caption": "..."}}"""
_AUTH_CONTEXT_SIGNED_IN = """## Auth status
The user is signed in and may confirm bookings, orders, and rentals.
If the user asks to book, order, or rent something, confirm the details with them, then present the plan.
"""
_AUTH_CONTEXT_GUEST = """## Auth status
The user is browsing as a guest and is NOT signed in.
- You may answer questions, give advice, and sketch ideas.
- You must NOT confirm or create any booking, order, or rental for a guest.
- When the user asks to book, order, buy, or rent something, confirm the request with them (ask clarifying questions), then politely ask them to sign in first β for example: "I can help you with that! Please sign in to your account first, then I'll place your booking."
- Do NOT output a plan marker for a guest's booking/order/rental request. Tell them to sign in instead.
"""
def _get_setting(conn, key: str, default: str = ""):
row = conn.execute("SELECT setting_value FROM system_settings WHERE setting_key=?", (key,)).fetchone()
return row["setting_value"] if row else default
def _ai_keys():
"""Return all configured AI API keys, merging env vars with the DB's
`ai_api_keys` setting (deduplicated). A single stale/invalid env key must
not shadow valid keys stored in the admin panel, so env and DB keys are
combined and rotated together."""
produced: list[dict] = []
env_openrouter = (os.environ.get("OPENROUTER_API_KEY") or os.environ.get("OPENROUTER_API_KEYS") or "").strip()
env_keys = (os.environ.get("OPENCODE_API_KEY") or os.environ.get("OPENAI_API_KEYS") or "").strip()
for raw in (env_openrouter, env_keys):
for k in (x.strip() for x in raw.split(",") if x.strip()):
produced.append({"key": k, "base_url": "https://openrouter.ai/api/v1" if k.lower().startswith("sk-or-") else ""})
conn = get_db()
raw = conn.execute("SELECT setting_value FROM system_settings WHERE setting_key='ai_api_keys'").fetchone()
conn.close()
if raw:
try:
parsed = json.loads(raw["setting_value"])
except Exception:
parsed = None
if isinstance(parsed, list):
for e in parsed:
if isinstance(e, str) and e.strip():
key = e.strip()
produced.append({"key": key, "base_url": "https://openrouter.ai/api/v1" if key.lower().startswith("sk-or-") else ""})
elif isinstance(e, dict) and e.get("key") and str(e["key"]).strip():
key = str(e["key"]).strip()
base = str(e.get("base_url") or "").strip()
if not base and key.lower().startswith("sk-or-"):
base = "https://openrouter.ai/api/v1"
produced.append({"key": key, "base_url": base})
seen: set[tuple[str, str]] = set()
out: list[dict] = []
for e in produced:
sig = (e["key"], e["base_url"])
if sig in seen:
continue
seen.add(sig)
out.append(e)
return out
def _catalog_context(limit: int = 40) -> str:
conn = get_db()
rows = conn.execute(
"SELECT name, selling_price, stock FROM products WHERE deleted_at IS NULL AND is_active=1 "
"ORDER BY is_featured DESC, name LIMIT ?", (limit,)).fetchall()
conn.close()
if not rows:
return "## Available catalog\n(empty catalog)"
lines = ["## Available catalog (name | price LAK | stock)"]
for r in rows:
lines.append(f"- {r['name']} | {r['selling_price']} | {r['stock']}")
return "\n".join(lines)
def _user_context(user_id: str, limit: int = 8) -> str:
conn = get_db()
rows = conn.execute(
"SELECT role, content, created_at FROM chat_messages "
"WHERE session_id IN (SELECT id FROM chat_sessions WHERE user_id=?) "
"ORDER BY created_at DESC, rowid DESC LIMIT ?", (user_id, limit)).fetchall()
conn.close()
if not rows:
return "## Recent history\n(no prior conversation)"
lines = ["## Recent conversation"]
for r in reversed(rows):
snippet = (r["content"] or "").replace("\n", " ")[:200]
lines.append(f"- [{r['role']}] {snippet}")
return "\n".join(lines)
def _ai_model_list() -> list:
conn = get_db()
raw = conn.execute("SELECT setting_value FROM system_settings WHERE setting_key='ai_models'").fetchone()
conn.close()
if not raw:
return list(_DEFAULT_AI_MODELS)
try:
parsed = json.loads(raw["setting_value"])
return [m for m in parsed if isinstance(m, str) and m.strip()] or list(_DEFAULT_AI_MODELS)
except Exception:
return list(_DEFAULT_AI_MODELS)
def _notify_admins(type_: str, title: str, message: str = "", data: dict | None = None) -> None:
"""Insert a notification for every admin/superadmin, deduped within 10 minutes."""
try:
conn = get_db()
admins = conn.execute(
"SELECT id FROM users WHERE role IN ('admin','superadmin') AND is_active=1").fetchall()
payload = json.dumps(data or {})
now_ts = "datetime('now', '-10 minutes')"
for a in admins:
dup = conn.execute(
f"SELECT 1 FROM notifications WHERE user_id=? AND type=? AND title=? AND message=? "
f"AND is_read=0 AND created_at >= {now_ts}",
(a["id"], type_, title, message)).fetchone()
if dup:
continue
conn.execute(
"INSERT INTO notifications (id, user_id, type, title, message, data) VALUES (?,?,?,?,?,?)",
(str(uuid.uuid4()), a["id"], type_, title, message, payload))
conn.commit(); conn.close()
except Exception:
pass
def _resolve_model_base_url(model_id: str, default_base_url: str) -> str:
"""Return the correct API base_url for a given model ID."""
mid = model_id.lower()
if "/" in mid:
return "https://openrouter.ai/api/v1"
for prefix in ("mimo-", "big-pickle", "hy3-", "deepseek-v4", "nemotron-3",
"north-mini", "laguna-", "ling-", "minimax-"):
if mid.startswith(prefix):
return "https://opencode.ai/zen/v1"
return default_base_url
def _model_provider_rank(model_id: str) -> int:
"""Lower rank is tried first in the fallback chain. OpenRouter models get
priority because OpenCode Zen's free tier only works from inside OpenCode."""
mid = model_id.lower()
if mid.startswith("openrouter/") or "/" in mid:
return 0
for prefix in ("mimo-", "big-pickle", "hy3-", "deepseek-v4", "nemotron-3",
"north-mini", "laguna-", "ling-", "minimax-"):
if mid.startswith(prefix):
return 2
return 1
def _ai_chat(messages: list, max_tokens: int = 900, temperature: float = 0.7, model: str | None = None, timeout: int = 120) -> str:
conn = get_db()
default_base_url = os.environ.get("AI_BASE_URL") or _get_setting(conn, "ai_base_url", "https://openrouter.ai/api/v1")
if not model:
model = os.environ.get("AI_MODEL") or _get_setting(conn, "ai_model", "openrouter/free")
conn.close()
keys = _ai_keys()
if not keys:
raise HTTPException(500, "AI is not configured: no API keys set")
# Fallback chain: requested model first, then the rest of the configured models.
# Models are ranked so OpenRouter is tried before general/OpenAI models, and
# OpenCode Zen models last (their public free tier only works from inside OpenCode).
rest = [m for m in _ai_model_list() if m and m != model]
rest.sort(key=_model_provider_rank)
model_list = [model] + rest
n = len(keys)
last_err = "unknown error"
switched = False
notified = False
tried_models: list[str] = []
blocked_bases: set[str] = set()
bad_keys: set[tuple[str, str]] = set()
errs: list[str] = []
for midx, cand_model in enumerate(model_list):
tried_models.append(cand_model)
cand_base_url = _resolve_model_base_url(cand_model, default_base_url)
if cand_base_url in blocked_bases and midx:
errs.append(f"provider blocked on {cand_model}")
switched = True
continue
payload = {"model": cand_model, "messages": messages, "max_tokens": max_tokens, "temperature": temperature}
for i in range(n):
idx = (_AI_STATE["key_idx"] + i) % n
entry = keys[idx]
key = entry["key"]
key_base = (entry.get("base_url") or "").strip()
combo = (key, key_base or cand_base_url)
# A key already rejected by this provider will reject every model on it β skip.
if combo in bad_keys:
continue
url = combo[1].rstrip("/") + "/chat/completions"
try:
resp = requests.post(url, headers={"Authorization": f"Bearer {key}"}, json=payload, timeout=timeout)
if resp.status_code == 429:
last_err = f"rate limited on {cand_model}"
errs.append(last_err)
switched = True
# On rate limit: skip remaining keys for this model, move to next model immediately.
break
if resp.status_code in (401, 403):
body = resp.text[:500]
last_err = f"HTTP {resp.status_code}: {body}"
# OpenCode Zen's free tier is blocked outside OpenCode β skip every
# other model that would use the same provider so we reach OpenRouter fast.
if resp.status_code == 403 and ("free tier" in body or "FreeTier" in body):
blocked_bases.add(combo[1])
errs.append(f"provider blocked on {cand_model}")
switched = True
break
# On auth error: this key is invalid for this provider β try next key,
# and never reuse it for another model on the same provider.
bad_keys.add(combo)
errs.append(f"HTTP {resp.status_code} on {cand_model}")
_AI_STATE["key_idx"] = (idx + 1) % n
continue
if resp.status_code >= 400:
last_err = f"HTTP {resp.status_code}: {resp.text[:300]}"
errs.append(f"{cand_model}: {last_err}")
switched = True
# On other errors: skip remaining keys for this model, move to next model.
break
msg = resp.json()["choices"][0]["message"]
text = (msg.get("content") or "").strip()
if not text:
text = (msg.get("reasoning_content") or "").strip()
if switched:
_notify_admins("ai_limit", "AI switched model automatically",
f"'{model}' was rate limited or failed; replied using '{cand_model}'. No action needed.",
{"from_model": model, "to_model": cand_model, "tried_models": tried_models})
notified = True
return text
except HTTPException:
raise
except requests.exceptions.Timeout:
last_err = f"timeout on {cand_model}"
errs.append(last_err)
switched = True
# On timeout: skip remaining keys for this model, move to next model.
break
except requests.exceptions.ConnectionError:
last_err = f"connection error on {cand_model}"
errs.append(last_err)
switched = True
break
except Exception as e:
last_err = f"{cand_model}: {e}"
errs.append(last_err)
switched = True
break
if switched and not notified:
_notify_admins("ai_limit", "AI rate limit reached",
f"Model '{model}' and all fallback models were rate limited or failed. "
f"Tried: {', '.join(tried_models)}. Check your API keys.",
{"from_model": model, "tried_models": tried_models})
detail = errs[-1] if errs else last_err
# If every failure was an auth/credential error, give an actionable message instead of
# the raw last error so admins know to add a valid provider API key.
auth_only = errs and all(
"HTTP 401" in e or "HTTP 403" in e or e.startswith("provider blocked") for e in errs
)
if auth_only:
detail = ("All configured API keys were rejected by every provider "
f"(HTTP 401/403). Add a valid API key (e.g. OpenRouter 'sk-or-...') in "
f"Admin β AI Assistant β API Keys, or set the OPENROUTER_API_KEY env var. "
f"Tried: {', '.join(tried_models[:10])}β¦")
raise HTTPException(502, f"AI request failed after trying all models: {detail}")
def _extract_plans(text: str) -> list:
plans = []
if _PLAN_MARKER_START not in text:
return plans
for part in text.split(_PLAN_MARKER_START)[1:]:
chunk = part.split(_PLAN_MARKER_END, 1)[0].strip()
if not chunk:
continue
try:
obj = json.loads(chunk)
if isinstance(obj, dict):
plans.append(obj)
continue
except Exception:
pass
for maybe in re.findall(r"\{.*?\}", chunk, re.DOTALL):
try:
obj = json.loads(maybe)
if isinstance(obj, dict):
plans.append(obj)
break
except Exception:
continue
return plans
def _extract_dynamic_ui(text: str) -> list:
"""Extract dynamic UI components from AI reply using [[UI_START]]...[[UI_END]] markers."""
components = []
if _UI_MARKER_START not in text:
return components
for part in text.split(_UI_MARKER_START)[1:]:
chunk = part.split(_UI_MARKER_END, 1)[0].strip()
if not chunk:
continue
try:
obj = json.loads(chunk)
if isinstance(obj, list):
components.extend(obj)
elif isinstance(obj, dict):
components.append(obj)
continue
except Exception:
pass
for maybe in re.findall(r"\[?\{.*?\}\]?", chunk, re.DOTALL):
try:
obj = json.loads(maybe)
if isinstance(obj, dict):
components.append(obj)
break
except Exception:
continue
return components
def _save_plans(session_id: str, user_id: str, plans: list) -> int:
conn = get_db()
count = 0
for p in plans:
btype = str(p.get("type", "other"))[:50]
title = str(p.get("title", "Plan"))[:255]
details = p.get("details", [])
if isinstance(details, str):
details = [details]
detail_strs = [str(d) for d in details if str(d).strip()][:20]
estimate = str(p.get("estimate", "")).strip()[:100]
desc = " β’ ".join(detail_strs)[:500]
if estimate:
desc = f"{estimate} | " + desc if desc else estimate
conn.execute(
"INSERT INTO bookings (id, session_id, user_id, type, title, description, items, status) "
"VALUES (?,?,?,?,?,?,?,?)",
(str(uuid.uuid4()), session_id, user_id, btype, title, desc, json.dumps(detail_strs), "planned"))
count += 1
conn.commit(); conn.close()
return count
def _save_message(session_id: str, role: str, content: str, plans: list | None = None, source: str = "ai", answered_by: str = "", channel: str = "", dynamic_ui: list | None = None):
conn = get_db()
conn.execute(
"INSERT INTO chat_messages (id, session_id, role, content, plans, source, answered_by, channel, dynamic_ui) VALUES (?,?,?,?,?,?,?,?,?)",
(str(uuid.uuid4()), session_id, role, content, json.dumps(plans or []), source, answered_by, channel, json.dumps(dynamic_ui or [])))
conn.execute("UPDATE chat_sessions SET updated_at=datetime('now') WHERE id=?", (session_id,))
conn.commit(); conn.close()
def _ensure_session(user_id: str | None, session_id: str | None = None, guest_id: str | None = None) -> str:
uid = user_id or ""
gid = (guest_id or "").strip()[:64]
conn = get_db()
if session_id:
row = conn.execute("SELECT user_id, guest_id FROM chat_sessions WHERE id=?", (session_id,)).fetchone()
if row:
owner = row["user_id"] or ""
row_guest = row["guest_id"] or ""
if uid and owner == "":
conn.execute("UPDATE chat_sessions SET user_id=?, guest_id='' WHERE id=?", (uid, session_id))
conn.commit(); conn.close()
return session_id
if uid and owner == uid:
conn.close()
return session_id
if not uid and owner == "":
if row_guest == "":
conn.execute("UPDATE chat_sessions SET guest_id=? WHERE id=?", (gid, session_id))
conn.commit(); conn.close()
return session_id
if row_guest == gid:
conn.close()
return session_id
session_id = None
sid = session_id or str(uuid.uuid4())
conn.execute("INSERT OR IGNORE INTO chat_sessions (id, user_id, guest_id, title) VALUES (?,?,?,?)",
(sid, uid, gid if not uid else "", "New chat"))
conn.commit(); conn.close()
return sid
def _user_agent_config(user_id: str | None) -> dict:
if not user_id:
return {"scope": "", "instructions": "", "model": ""}
conn = get_db()
row = conn.execute("SELECT scope, instructions, model FROM user_agent_config WHERE user_id=?", (user_id,)).fetchone()
conn.close()
if not row:
return {"scope": "", "instructions": "", "model": ""}
return {"scope": row["scope"] or "", "instructions": row["instructions"] or "", "model": row["model"] or ""}
def _build_messages(user_id: str | None, history: list, user_content: str, language: str | None = None) -> list:
conn = get_db()
raw_prompt = _get_setting(conn, "ai_system_prompt", _DEFAULT_AI_PROMPT)
conn.close()
auth_ctx = _AUTH_CONTEXT_SIGNED_IN if user_id else _AUTH_CONTEXT_GUEST
system = (raw_prompt
.replace("{CATALOG_CONTEXT}", _catalog_context())
.replace("{USER_CONTEXT}", _user_context(user_id) if user_id else "## Recent history\n(no prior conversation)")
.replace("{AUTH_CONTEXT}", auth_ctx))
if "{AUTH_CONTEXT}" not in raw_prompt:
system = f"{system}\n\n{auth_ctx}"
if language:
system = f"{system}\n\n## Language instruction\nThe user selected **{language}** as their reply language. Always write your entire reply in {language}, even if the user writes in a different language. Keep product names, prices, addresses, and proper nouns exactly as they are."
messages = [{"role": "system", "content": system}]
for m in history:
role = m.get("role")
if role not in ("user", "assistant"):
continue
messages.append({"role": role, "content": (m.get("content") or "")[:4000]})
messages.append({"role": "user", "content": user_content})
return messages
# ββ Channel integrations (WhatsApp, Telegram, Line, Messenger) ββ
_CHANNELS = ["telegram", "messenger", "line", "whatsapp"]
_PUBLIC_BASE = os.environ.get("PUBLIC_BASE_URL", "https://ineeds-now.hf.space")
_REQUIRED_CHANNEL_FIELD = {
"telegram": "bot_token",
"messenger": "page_access_token",
"line": "channel_access_token",
"whatsapp": "access_token",
}
def _get_channel_config(channel: str) -> dict:
conn = get_db()
row = conn.execute("SELECT config, is_enabled FROM channel_configs WHERE channel=?", (channel,)).fetchone()
conn.close()
cfg = {}
enabled = False
if row:
enabled = bool(row["is_enabled"])
try:
cfg = json.loads(row["config"])
except Exception:
cfg = {}
if not isinstance(cfg, dict):
cfg = {}
cfg["enabled"] = enabled
if not str(cfg.get("webhook_secret") or ""):
cfg["webhook_secret"] = str(uuid.uuid4())[:24]
_save_channel_config(channel, cfg, enabled)
return cfg
def _save_channel_config(channel: str, config: dict, enabled: bool = False) -> None:
conn = get_db()
conn.execute(
"INSERT INTO channel_configs (channel, config, is_enabled, updated_at) VALUES (?,?,?,datetime('now')) "
"ON CONFLICT(channel) DO UPDATE SET config=excluded.config, is_enabled=excluded.is_enabled, updated_at=excluded.updated_at",
(channel, json.dumps(config), 1 if enabled else 0))
conn.commit(); conn.close()
def _webhook_url(channel: str, secret: str = "") -> str:
cfg = _get_channel_config(channel)
secret = secret or str(cfg.get("webhook_secret") or "")
return f"{_PUBLIC_BASE}/api/v1/channels/{channel}/webhook/{secret}"
def _upsert_channel_user(channel: str, external_id: str, name: str = "", avatar_url: str = "", raw: dict | None = None) -> None:
conn = get_db()
row = conn.execute("SELECT id FROM channel_users WHERE channel=? AND external_id=?", (channel, str(external_id))).fetchone()
if row:
conn.execute(
"UPDATE channel_users SET name=COALESCE(NULLIF(?,''), name), avatar_url=COALESCE(NULLIF(?,''), avatar_url), "
"last_seen_at=datetime('now') WHERE id=?", (name, avatar_url, row["id"]))
else:
conn.execute(
"INSERT INTO channel_users (id, channel, external_id, name, avatar_url, raw_data) VALUES (?,?,?,?,?,?)",
(str(uuid.uuid4()), channel, str(external_id), name, avatar_url, json.dumps(raw or {})))
conn.commit(); conn.close()
def _ensure_channel_session(channel: str, external_id: str) -> str:
conn = get_db()
row = conn.execute(
"SELECT id FROM chat_sessions WHERE channel=? AND channel_user_id=? ORDER BY updated_at DESC LIMIT 1",
(channel, str(external_id))).fetchone()
if row:
conn.close()
return row["id"]
sid = str(uuid.uuid4())
conn.execute(
"INSERT OR IGNORE INTO chat_sessions (id, user_id, title, channel, channel_user_id) VALUES (?,?,?,?,?)",
(sid, "", "New chat", channel, str(external_id)))
conn.commit(); conn.close()
return sid
def _mark_channel_inbound(channel: str, msg_id: str) -> bool:
"""Returns True if this inbound message is new, False if already processed (duplicate)."""
if not msg_id:
return True
conn = get_db()
try:
cur = conn.execute("INSERT OR IGNORE INTO channel_inbound (channel, external_msg_id) VALUES (?,?)", (channel, str(msg_id)))
conn.commit()
return cur.rowcount > 0
except Exception:
return True
finally:
conn.close()
def _channel_name(channel: str) -> str:
return {"telegram": "Telegram", "messenger": "Messenger", "line": "Line", "whatsapp": "WhatsApp"}.get(channel, channel.title())
def _process_channel_message(channel: str, external_id: str, name: str, text: str,
avatar_url: str = "", msg_id: str = "") -> dict:
cfg = _get_channel_config(channel)
if not cfg.get("enabled"):
return {"ok": True, "skipped": "channel disabled"}
if not text or not text.strip():
return {"ok": True, "skipped": "empty message"}
if not _mark_channel_inbound(channel, msg_id):
return {"ok": True, "skipped": "duplicate"}
_upsert_channel_user(channel, external_id, name, avatar_url)
sid = _ensure_channel_session(channel, external_id)
conn = get_db()
is_new = conn.execute("SELECT COUNT(*) FROM chat_messages WHERE session_id=?", (sid,)).fetchone()[0] == 0
conn.close()
conn = get_db()
conn.execute("UPDATE chat_sessions SET title=?, channel_user_name=?, updated_at=datetime('now') WHERE id=? AND title='New chat'",
(text[:60] or "New chat", name, sid))
conn.commit(); conn.close()
_save_message(sid, "user", text.strip(), [], source="channel", channel=channel)
if is_new:
_notify_admins("channel", f"New {_channel_name(channel)} conversation",
f"{name or external_id}: {text.strip()[:200]}", {"channel": channel, "session_id": sid})
conn = get_db()
history = conn.execute(
"SELECT role, content FROM chat_messages WHERE session_id=? ORDER BY created_at, rowid", (sid,)).fetchall()
max_tokens = int(float(_get_setting(conn, "ai_max_tokens", "900")))
temperature = float(_get_setting(conn, "ai_temperature", "0.7"))
conn.close()
history = [dict(h) for h in history][:-1]
try:
messages = _build_messages(None, history, text.strip())
reply = _ai_chat(messages, max_tokens=max_tokens, temperature=temperature)
except HTTPException as e:
return {"ok": False, "error": e.detail}
except Exception as e:
return {"ok": False, "error": str(e)}
plans = _extract_plans(reply)
_save_message(sid, "assistant", reply, plans, source="ai", channel=channel)
sent, err = _send_channel_reply(channel, external_id, reply)
return {"ok": True, "session_id": sid, "reply": reply, "sent": sent, "error": err if not sent else ""}
def _send_channel_reply(channel: str, target: str, text: str) -> tuple:
cfg = _get_channel_config(channel)
if not cfg.get("enabled"):
return False, "channel disabled"
c = cfg
try:
if channel == "telegram":
token = c.get("bot_token", "")
if not token:
return False, "bot_token not configured"
r = requests.post(f"https://api.telegram.org/bot{token}/sendMessage",
json={"chat_id": target, "text": text[:4000]}, timeout=30)
return r.ok, r.text[:300] if not r.ok else ""
if channel == "messenger":
token = c.get("page_access_token", "")
if not token:
return False, "page_access_token not configured"
r = requests.post("https://graph.facebook.com/v21.0/me/messages",
params={"access_token": token},
json={"recipient": {"id": target}, "message": {"text": text[:2000]}}, timeout=30)
return r.ok, r.text[:300] if not r.ok else ""
if channel == "line":
token = c.get("channel_access_token", "")
if not token:
return False, "channel_access_token not configured"
r = requests.post("https://api.line.me/v2/bot/message/push",
headers={"Authorization": f"Bearer {token}"},
json={"to": target, "messages": [{"type": "text", "text": text[:5000]}]}, timeout=30)
return r.ok, r.text[:300] if not r.ok else ""
if channel == "whatsapp":
token = c.get("access_token", "")
pid = c.get("phone_number_id", "")
if not token:
return False, "access_token not configured"
if not pid:
return False, "phone_number_id not configured"
r = requests.post(f"https://graph.facebook.com/v21.0/{pid}/messages",
headers={"Authorization": f"Bearer {token}"},
json={"messaging_product": "whatsapp", "to": target,
"type": "text", "text": {"body": text[:4000]}}, timeout=30)
return r.ok, r.text[:300] if not r.ok else ""
except requests.exceptions.RequestException as e:
return False, f"network error: {e}"
return False, f"unknown channel {channel}"
def _test_channel(channel: str) -> dict:
cfg = _get_channel_config(channel)
c = cfg
if channel == "telegram":
token = c.get("bot_token", "")
if not token:
return {"ok": False, "error": "bot_token is required"}
try:
r = requests.get(f"https://api.telegram.org/bot{token}/getMe", timeout=20)
d = r.json() if r.ok else {}
if d.get("ok"):
return {"ok": True, "info": d.get("result", {})}
return {"ok": False, "error": d.get("description", r.text[:300])}
except requests.exceptions.RequestException as e:
return {"ok": False, "error": f"network error: {e}"}
if channel == "messenger":
token = c.get("page_access_token", "")
if not token:
return {"ok": False, "error": "page_access_token is required"}
try:
r = requests.get("https://graph.facebook.com/v21.0/me", params={"access_token": token}, timeout=20)
d = r.json() if r.ok else {}
if r.ok and d.get("id"):
return {"ok": True, "info": d}
return {"ok": False, "error": d.get("error", {}).get("message", r.text[:300])}
except requests.exceptions.RequestException as e:
return {"ok": False, "error": f"network error: {e}"}
if channel == "line":
token = c.get("channel_access_token", "")
if not token:
return {"ok": False, "error": "channel_access_token is required"}
try:
r = requests.get("https://api.line.me/v2/bot/info", headers={"Authorization": f"Bearer {token}"}, timeout=20)
d = r.json() if r.ok else {}
if r.ok:
return {"ok": True, "info": d}
return {"ok": False, "error": d.get("message", r.text[:300])}
except requests.exceptions.RequestException as e:
return {"ok": False, "error": f"network error: {e}"}
if channel == "whatsapp":
token = c.get("access_token", "")
pid = c.get("phone_number_id", "")
if not token:
return {"ok": False, "error": "access_token is required"}
if not pid:
return {"ok": False, "error": "phone_number_id is required"}
try:
r = requests.get(f"https://graph.facebook.com/v21.0/{pid}", headers={"Authorization": f"Bearer {token}"}, timeout=20)
d = r.json() if r.ok else {}
if r.ok:
return {"ok": True, "info": d}
return {"ok": False, "error": d.get("error", {}).get("message", r.text[:300])}
except requests.exceptions.RequestException as e:
return {"ok": False, "error": f"network error: {e}"}
return {"ok": False, "error": f"unknown channel {channel}"}
# ββ Token helpers ββ
_token_blacklist: set[str] = set() # In-memory; use Redis in production
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_password(plain: str, hashed: str) -> bool:
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
def create_token(user_id: str, role: str) -> str:
exp = datetime.now(timezone.utc) + timedelta(hours=JWT_EXPIRE_HOURS)
return jwt.encode({"sub": user_id, "role": role, "exp": exp, "type": "access"}, JWT_SECRET, algorithm=JWT_ALGORITHM)
def create_refresh_token(user_id: str, role: str) -> str:
exp = datetime.now(timezone.utc) + timedelta(hours=JWT_REFRESH_EXPIRE_HOURS)
return jwt.encode({"sub": user_id, "role": role, "exp": exp, "type": "refresh"}, JWT_SECRET, algorithm=JWT_ALGORITHM)
def decode_token(token: str) -> dict | None:
if token in _token_blacklist:
return None
try:
return jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
except jwt.ExpiredSignatureError:
return None
except jwt.JWTError:
return None
def blacklist_token(token: str) -> None:
"""Add a token to the blacklist (for logout)."""
_token_blacklist.add(token)
def _validate_password(password: str) -> None:
"""Enforce password complexity rules."""
if len(password) < 8:
raise HTTPException(400, "Password must be at least 8 characters")
if len(password) > 128:
raise HTTPException(400, "Password must be at most 128 characters")
if not any(c.isupper() for c in password):
raise HTTPException(400, "Password must contain at least one uppercase letter")
if not any(c.islower() for c in password):
raise HTTPException(400, "Password must contain at least one lowercase letter")
if not any(c.isdigit() for c in password):
raise HTTPException(400, "Password must contain at least one digit")
def _validate_email(email: str) -> str:
"""Validate and normalize email."""
import re
email = email.strip().lower()
if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
raise HTTPException(400, "Invalid email format")
return email
def require_admin(request: Request) -> dict:
"""Dependency: require admin or superadmin role. Returns the user dict."""
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
return user
def get_current_user(token: str) -> dict:
payload = decode_token(token)
if not payload:
raise HTTPException(401, "invalid token")
conn = get_db()
user = conn.execute("SELECT * FROM users WHERE id=?", (payload["sub"],)).fetchone()
conn.close()
if not user:
raise HTTPException(401, "user not found")
return dict(user)
def _bearer_token(request: Request) -> str:
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer "):
raise HTTPException(401, "unauthorized")
return auth.split(" ", 1)[1]
# ββ DB helpers (shared by both Gradio and REST, no @spaces.GPU) ββ
def db_health():
conn = get_db()
u = conn.execute("SELECT COUNT(*) FROM users").fetchone()[0]
p = conn.execute("SELECT COUNT(*) FROM products WHERE deleted_at IS NULL").fetchone()[0]
o = conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
conn.close()
return {"status":"ok","users":u,"products":p,"orders":o}
def db_products():
conn = get_db()
rows = conn.execute("SELECT * FROM products WHERE deleted_at IS NULL ORDER BY created_at DESC").fetchall()
conn.close()
out = []
for r in rows:
d = dict(r)
if isinstance(d.get("images"), str):
try: d["images"] = json.loads(d["images"])
except: d["images"] = []
out.append(d)
return out
def db_orders():
conn = get_db()
rows = conn.execute("SELECT * FROM orders ORDER BY created_at DESC").fetchall()
conn.close()
return [dict(r) for r in rows]
# ββ Gradio functions ββ
if spaces:
@spaces.GPU
def gr_health():
return db_health()
else:
def gr_health():
return db_health()
def gr_login(email: str, password: str):
conn = get_db()
user = conn.execute("SELECT * FROM users WHERE email=?", (email.lower(),)).fetchone()
conn.close()
if not user or not verify_password(password, user["password_hash"]):
return {"error": "invalid credentials"}
token = create_token(user["id"], user["role"])
u = {"id": user["id"], "email": user["email"], "full_name": user["full_name"],
"phone": user["phone"] if "phone" in user.keys() else "",
"role": user["role"], "is_active": bool(user["is_active"])}
return {"access_token": token, "token_type": "bearer", "user": u}
def gr_register(email: str, password: str, full_name: str, phone: str = ""):
conn = get_db()
email = email.lower().strip() if email else None
phone = phone.strip() if phone else None
if not email and not phone:
conn.close()
return {"error": "email or phone is required"}
if email and conn.execute("SELECT 1 FROM users WHERE email=?", (email,)).fetchone():
conn.close()
return {"error": "email already registered"}
if phone and conn.execute("SELECT 1 FROM users WHERE phone=?", (phone,)).fetchone():
conn.close()
return {"error": "phone already registered"}
uid = str(uuid.uuid4())
hashed = hash_password(password)
conn.execute("INSERT INTO users (id,email,password_hash,full_name,phone,role) VALUES (?,?,?,?,?,?)",
(uid, email, hashed, full_name, phone or "", "user"))
conn.commit(); conn.close()
token = create_token(uid, "user")
return {"access_token": token, "token_type": "bearer",
"user": {"id": uid, "email": email, "full_name": full_name, "phone": phone or "", "role": "user", "is_active": True}}
def gr_products():
return db_products()
def gr_orders():
return db_orders()
# ββ Gradio Blocks UI ββ
with gr.Blocks(title="ineed-now", theme=gr.themes.Soft(), css="*{margin:0;padding:0}") as demo:
if dist.is_dir() and (dist / "index.html").exists():
gr.HTML((dist / "index.html").read_text())
else:
gr.Markdown("# ineed-now\nFull-Stack Web + API")
# ββ Module-level setup ββ
init_db()
# HF runs `gradio app.py` which creates its own FastAPI on demo.app.
# We add ALL routes + middleware to demo.app so they work under Gradio's server.
app = demo.app
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:8081", "http://localhost:3000", "http://localhost:7860", "https://ineeds-now.hf.space"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ββ Manual Gradio protocol ββ
_event_results: dict[str, Any] = {}
def _make_sse(result: Any) -> str:
inner = json.dumps(result, default=str)
outer = json.dumps([inner])
return f"event: complete\ndata: {outer}\n\n"
@app.post("/api/v1/_call/{fn_name}")
async def gradio_call(fn_name: str, request: Request):
event_id = str(uuid.uuid4())
body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {"data": []}
data = body.get("data", [])
try:
if fn_name == "gr_health": result = gr_health()
elif fn_name == "gr_login": result = gr_login(data[0] if len(data)>0 else "", data[1] if len(data)>1 else "")
elif fn_name == "gr_register": result = gr_register(data[0] if len(data)>0 else "", data[1] if len(data)>1 else "", data[2] if len(data)>2 else "", data[3] if len(data)>3 else "")
elif fn_name == "gr_products": result = gr_products()
elif fn_name == "gr_orders": result = gr_orders()
else: result = {"error": f"unknown: {fn_name}"}
except Exception as e:
result = {"error": str(e)}
_event_results[event_id] = result
return {"event_id": event_id}
@app.get("/api/v1/_call/{fn_name}/{event_id}")
async def gradio_result(fn_name: str, event_id: str):
result = _event_results.get(event_id)
if result is None:
raise HTTPException(404, "event not found or expired")
del _event_results[event_id]
return Response(content=_make_sse(result), media_type="text/event-stream")
# ββ REST API ββ
import re as _re
_VALID_ROLES = {"user", "admin", "superadmin"}
class LoginReq(BaseModel):
email: str
password: str = Field(..., min_length=1, max_length=255)
class RegisterReq(BaseModel):
email: str | None = None
password: str = Field(..., min_length=8, max_length=128)
full_name: str = Field(..., min_length=1, max_length=255)
phone: str = ""
class ProductReq(BaseModel):
name: str = Field(..., min_length=1, max_length=255)
slug: str = Field(..., min_length=1, max_length=255)
sku: str = ""
category_id: str = ""
selling_price: float = Field(0, ge=0)
cost_price: float = Field(0, ge=0)
stock: int = Field(0, ge=0)
images: list[str] = []
class CreateUserReq(BaseModel):
email: str
password: str = Field(..., min_length=8, max_length=128)
full_name: str = Field(..., min_length=1, max_length=255)
phone: str = ""
role: str = "user"
avatar_url: str = ""
@validator("role")
def validate_role(cls, v):
if v not in _VALID_ROLES:
raise ValueError(f"role must be one of: {', '.join(_VALID_ROLES)}")
return v
class UpdateUserReq(BaseModel):
full_name: str | None = None
phone: str | None = None
role: str | None = None
is_active: bool | None = None
avatar_url: str | None = None
@app.get("/api/v1/health")
def rest_health():
"""Health check endpoint for load balancers and monitoring."""
from cache import cache_stats
conn = get_db()
try:
conn.execute("SELECT 1")
db_ok = True
except Exception:
db_ok = False
finally:
_close(conn)
return {
"status": "ok" if db_ok else "degraded",
"database": "postgresql" if IS_POSTGRES else "sqlite",
"db_connected": db_ok,
"cache": cache_stats(),
}
@app.post("/api/v1/auth/register")
def api_register(data: RegisterReq):
conn = get_db()
email = _validate_email(data.email) if data.email else None
phone = data.phone.strip() if data.phone else None
_validate_password(data.password)
if not email and not phone:
conn.close(); raise HTTPException(400, "email or phone is required")
if email and conn.execute("SELECT 1 FROM users WHERE email=?", (email,)).fetchone():
conn.close(); raise HTTPException(409, "email already registered")
if phone and conn.execute("SELECT 1 FROM users WHERE phone=?", (phone,)).fetchone():
conn.close(); raise HTTPException(409, "phone already registered")
uid = str(uuid.uuid4()); hashed = hash_password(data.password)
conn.execute("INSERT INTO users (id,email,password_hash,full_name,phone,role,is_active) VALUES (?,?,?,?,?,?,?)",
(uid, email, hashed, data.full_name, phone or "", "user", 1))
conn.commit(); conn.close()
token = create_token(uid, "user")
return {"access_token": token, "token_type": "bearer", "user": {"id": uid, "email": email, "full_name": data.full_name, "phone": phone or "", "avatar_url": "", "role": "user", "is_active": True}}
@app.post("/api/v1/auth/login")
@app.post("/api/v1/admin/login")
def api_login(data: LoginReq):
email = data.email.strip().lower()
conn = get_db()
user = conn.execute("SELECT * FROM users WHERE email=?", (email,)).fetchone()
conn.close()
if not user or not verify_password(data.password, user["password_hash"]):
raise HTTPException(401, "invalid credentials")
if not user["is_active"]:
raise HTTPException(403, "account is disabled")
access_token = create_token(user["id"], user["role"])
refresh_token = create_refresh_token(user["id"], user["role"])
u = {"id": user["id"], "email": user["email"], "full_name": user["full_name"],
"phone": user["phone"], "avatar_url": user["avatar_url"] or "" if "avatar_url" in user.keys() else "",
"role": user["role"], "is_active": bool(user["is_active"])}
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer", "user": u}
@app.get("/api/v1/auth/me")
def api_me(request: Request):
user = get_current_user(_bearer_token(request))
return user
class ProfileUpdateReq(BaseModel):
full_name: str | None = None
phone: str | None = None
avatar_url: str | None = None
@app.put("/api/v1/auth/me")
def api_update_me(data: ProfileUpdateReq, request: Request):
user = get_current_user(_bearer_token(request))
conn = get_db()
updates = {}
if data.full_name is not None: updates["full_name"] = data.full_name
if data.phone is not None: updates["phone"] = data.phone
if data.avatar_url is not None: updates["avatar_url"] = data.avatar_url
if updates:
set_clause = ", ".join(f"{k}=?" for k in updates)
conn.execute(f"UPDATE users SET {set_clause} WHERE id=?", (*updates.values(), user["id"]))
conn.commit()
row = conn.execute("SELECT id,email,full_name,phone,avatar_url,role,is_active,created_at FROM users WHERE id=?", (user["id"],)).fetchone()
conn.close()
return _format_user(row)
@app.post("/api/v1/auth/refresh")
def api_refresh(request: Request):
"""Refresh an access token using a valid refresh token."""
token = _bearer_token(request)
payload = decode_token(token)
if not payload or payload.get("type") != "refresh":
raise HTTPException(401, "invalid or expired refresh token")
conn = get_db()
user = conn.execute("SELECT * FROM users WHERE id=?", (payload["sub"],)).fetchone()
conn.close()
if not user or not user["is_active"]:
raise HTTPException(401, "user not found or inactive")
access_token = create_token(user["id"], user["role"])
refresh_token = create_refresh_token(user["id"], user["role"])
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@app.post("/api/v1/auth/logout")
@app.post("/api/v1/admin/logout")
def api_logout(request: Request):
"""Blacklist the current token (logout)."""
try:
token = _bearer_token(request)
blacklist_token(token)
except HTTPException:
pass
return {"message": "logged out"}
# ββ WebAuthn / Fingerprint Authentication ββ
import hashlib, secrets, base64 as _b64
WEBAUTHN_RP_NAME = "ineed-now"
_challenge_store: dict[str, dict] = {} # In-memory; use Redis in production
def _get_rp_id(request: Request, origin: str = None) -> str:
"""Get RP ID - prefer origin from frontend, fallback to request host."""
if origin:
# Frontend sends its hostname (e.g., "localhost" or "ineeds-now.hf.space")
return origin.split(":")[0] # Remove port if present
host = request.headers.get("host", "localhost").split(":")[0]
return host
def _b64url_encode(data: bytes) -> str:
return _b64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def _b64url_decode(s: str) -> bytes:
s += "=" * (-len(s) % 4)
return _b64.urlsafe_b64decode(s)
def _generate_challenge() -> bytes:
return secrets.token_bytes(32)
class WebAuthnRegisterReq(BaseModel):
email: str
nickname: str = ""
origin: str = "" # Frontend hostname for RP ID
class WebAuthnRegisterVerifyReq(BaseModel):
email: str
credential_id: str
client_data_json: str
attestation_object: str
nickname: str = ""
origin: str = "" # Frontend hostname for RP ID
class WebAuthnAuthReq(BaseModel):
email: str
origin: str = "" # Frontend hostname for RP ID
class WebAuthnAuthVerifyReq(BaseModel):
email: str
credential_id: str
client_data_json: str
authenticator_data: str
signature: str
@app.post("/api/v1/auth/webauthn/register/options")
def api_webauthn_register_options(data: WebAuthnRegisterReq, request: Request):
"""Get WebAuthn registration options (challenge + user info)."""
rp_id = _get_rp_id(request, data.origin)
email = data.email.strip().lower()
challenge = _generate_challenge()
challenge_key = _b64url_encode(challenge)
_challenge_store[email] = {"challenge": challenge, "type": "register", "ts": time.time(), "rp_id": rp_id}
conn = get_db()
user = conn.execute("SELECT id FROM users WHERE email=?", (email,)).fetchone()
_close(conn)
user_id = user["id"] if user else email
return {
"challenge": challenge_key,
"rp": {"name": WEBAUTHN_RP_NAME, "id": rp_id},
"user": {
"id": _b64url_encode(user_id.encode()),
"name": email,
"displayName": email,
},
"pubKeyCredParams": [
{"type": "public-key", "alg": -7}, # ES256
{"type": "public-key", "alg": -257}, # RS256
],
"timeout": 60000,
"attestation": "none",
"authenticatorSelection": {
"residentKey": "preferred",
"userVerification": "discouraged",
},
}
@app.post("/api/v1/auth/webauthn/register/verify")
def api_webauthn_register_verify(data: WebAuthnRegisterVerifyReq):
"""Verify WebAuthn registration and store credential."""
email = data.email.strip().lower()
stored = _challenge_store.pop(email, None)
if not stored or stored["type"] != "register":
raise HTTPException(400, "No registration challenge found")
if time.time() - stored["ts"] > 120:
raise HTTPException(400, "Challenge expired")
conn = get_db()
user = conn.execute("SELECT id FROM users WHERE email=?", (email,)).fetchone()
if not user:
_close(conn)
raise HTTPException(404, "User not found")
cred_id = data.credential_id
existing = conn.execute("SELECT id FROM webauthn_credentials WHERE credential_id=?", (cred_id,)).fetchone()
if existing:
_close(conn)
raise HTTPException(409, "Credential already registered")
credential = {
"id": str(uuid.uuid4()),
"user_id": user["id"],
"credential_id": cred_id,
"public_key": data.attestation_object,
"counter": 0,
"nickname": data.nickname or "Fingerprint",
"device_type": "platform",
}
conn.execute(
"INSERT INTO webauthn_credentials (id, user_id, credential_id, public_key, counter, nickname, device_type) VALUES (?,?,?,?,?,?,?)",
(credential["id"], credential["user_id"], credential["credential_id"],
credential["public_key"], credential["counter"], credential["nickname"], credential["device_type"])
)
conn.commit()
_close(conn)
return {"ok": True, "credential_id": cred_id, "message": "Fingerprint registered successfully"}
@app.post("/api/v1/auth/webauthn/authenticate/options")
def api_webauthn_authenticate_options(data: WebAuthnAuthReq, request: Request):
"""Get WebAuthn authentication options (challenge)."""
rp_id = _get_rp_id(request, data.origin)
email = data.email.strip().lower()
challenge = _generate_challenge()
challenge_key = _b64url_encode(challenge)
_challenge_store[email] = {"challenge": challenge, "type": "authenticate", "ts": time.time(), "rp_id": rp_id}
conn = get_db()
user = conn.execute("SELECT id FROM users WHERE email=?", (email,)).fetchone()
if not user:
_close(conn)
raise HTTPException(404, "User not found")
creds = conn.execute(
"SELECT credential_id, transports FROM webauthn_credentials WHERE user_id=?", (user["id"],)
).fetchall()
_close(conn)
allow_credentials = []
for c in creds:
allow_credentials.append({
"type": "public-key",
"id": c["credential_id"],
"transports": ["internal"],
})
return {
"challenge": challenge_key,
"timeout": 60000,
"rpId": rp_id,
"allowCredentials": allow_credentials,
"userVerification": "discouraged",
}
@app.post("/api/v1/auth/webauthn/authenticate/verify")
def api_webauthn_authenticate_verify(data: WebAuthnAuthVerifyReq):
"""Verify WebAuthn authentication and issue JWT."""
email = data.email.strip().lower()
stored = _challenge_store.pop(email, None)
if not stored or stored["type"] != "authenticate":
raise HTTPException(400, "No authentication challenge found")
if time.time() - stored["ts"] > 120:
raise HTTPException(400, "Challenge expired")
conn = get_db()
user = conn.execute("SELECT * FROM users WHERE email=?", (email,)).fetchone()
if not user:
_close(conn)
raise HTTPException(404, "User not found")
cred = conn.execute(
"SELECT * FROM webauthn_credentials WHERE credential_id=? AND user_id=?",
(data.credential_id, user["id"])
).fetchone()
if not cred:
_close(conn)
raise HTTPException(404, "Credential not found")
# Update counter and last used
conn.execute(
"UPDATE webauthn_credentials SET counter=counter+1, last_used_at=datetime('now') WHERE id=?",
(cred["id"],)
)
conn.commit()
_close(conn)
if not user["is_active"]:
raise HTTPException(403, "Account is disabled")
access_token = create_token(user["id"], user["role"])
refresh_token = create_refresh_token(user["id"], user["role"])
u = {"id": user["id"], "email": user["email"], "full_name": user["full_name"],
"phone": user["phone"], "avatar_url": user["avatar_url"] or "" if "avatar_url" in user.keys() else "",
"role": user["role"], "is_active": bool(user["is_active"])}
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer", "user": u}
@app.get("/api/v1/auth/webauthn/credentials")
def api_webauthn_list_credentials(request: Request):
"""List registered WebAuthn credentials for the current user."""
user = get_current_user(_bearer_token(request))
conn = get_db()
creds = conn.execute(
"SELECT id, credential_id, nickname, device_type, created_at, last_used_at FROM webauthn_credentials WHERE user_id=?",
(user["id"],)
).fetchall()
_close(conn)
return [{"id": c["id"], "credential_id": c["credential_id"], "nickname": c["nickname"],
"device_type": c["device_type"], "created_at": c["created_at"],
"last_used_at": c["last_used_at"]} for c in creds]
@app.delete("/api/v1/auth/webauthn/credentials/{cred_id}")
def api_webauthn_delete_credential(cred_id: str, request: Request):
"""Delete a WebAuthn credential."""
user = get_current_user(_bearer_token(request))
conn = get_db()
conn.execute("DELETE FROM webauthn_credentials WHERE id=? AND user_id=?", (cred_id, user["id"]))
conn.commit()
_close(conn)
return {"message": "Credential deleted"}
class LocationReq(BaseModel):
latitude: float
longitude: float
@app.post("/api/v1/auth/location")
def api_update_location(data: LocationReq, request: Request):
user = get_current_user(_bearer_token(request))
conn = get_db()
conn.execute(
"UPDATE users SET latitude=?, longitude=?, location_updated_at=datetime('now') WHERE id=?",
(data.latitude, data.longitude, user["id"])
)
conn.commit()
conn.close()
return {"message": "location updated"}
@app.post("/api/v1/guest/location")
def api_guest_location(data: LocationReq, request: Request):
session_id = request.headers.get("X-Session-Id", "")
ip = request.client.host if request.client else ""
ua = request.headers.get("User-Agent", "")
conn = get_db()
existing = conn.execute("SELECT id FROM guest_locations WHERE session_id=?", (session_id,)).fetchone()
if existing:
conn.execute(
"UPDATE guest_locations SET latitude=?, longitude=?, ip_address=?, user_agent=?, updated_at=datetime('now') WHERE session_id=?",
(data.latitude, data.longitude, ip, ua, session_id)
)
else:
conn.execute(
"INSERT INTO guest_locations (id, session_id, latitude, longitude, ip_address, user_agent) VALUES (?,?,?,?,?,?)",
(str(uuid.uuid4()), session_id, data.latitude, data.longitude, ip, ua)
)
conn.commit()
conn.close()
return {"message": "guest location saved"}
def _dump_sql() -> str:
conn = get_db()
lines = []
for line in conn.iterdump():
lines.append(line)
conn.close()
return "\n".join(lines)
@app.get("/api/v1/admin/export")
def api_admin_export(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
content = _dump_sql()
return Response(content=content, media_type="application/sql",
headers={"Content-Disposition": "attachment; filename=export.sql"})
@app.post("/api/v1/admin/backup")
def api_admin_backup(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
content = _dump_sql()
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
return Response(content=content, media_type="application/sql",
headers={"Content-Disposition": f"attachment; filename=backup_{ts}.sql"})
@app.post("/api/v1/admin/import")
def api_admin_import(request: Request, file: UploadFile = File(...)):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
content = file.file.read().decode("utf-8")
statements = [s.strip() for s in content.split(";") if s.strip()]
executed = 0; failed = 0
conn = get_db()
for stmt in statements:
try:
conn.execute(stmt)
executed += 1
except Exception:
failed += 1
conn.commit(); conn.close()
return {"message": f"Import: {executed} executed, {failed} failed.", "executed": executed, "failed": failed}
class AdminBulkIdsReq(BaseModel):
ids: list[str]
@app.get("/api/v1/products")
def api_products():
cached = cache_get("products:list")
if cached is not None:
return cached
result = db_products()
cache_set("products:list", result, ttl=300)
return result
@app.post("/api/v1/products")
def api_create_product(data: ProductReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
pid = str(uuid.uuid4())
conn = get_db()
conn.execute("INSERT INTO products (id,name,slug,sku,category_id,selling_price,cost_price,stock,images,is_active) VALUES (?,?,?,?,?,?,?,?,?,?)",
(pid, data.name, data.slug, data.sku, data.category_id, data.selling_price, data.cost_price, data.stock, json.dumps(data.images), 1))
conn.commit(); conn.close()
cache_delete("products:list")
return {"id": pid, "name": data.name, "slug": data.slug, "sku": data.sku, "selling_price": data.selling_price, "cost_price": data.cost_price, "stock": data.stock, "images": data.images, "is_active": True}
class ProductUpdateReq(BaseModel):
name: str | None = None; slug: str | None = None; sku: str | None = None
category_id: str | None = None; selling_price: float | None = None
cost_price: float | None = None; stock: int | None = None
images: list[str] | None = None; is_active: bool | None = None
@app.put("/api/v1/products/{pid}")
def api_update_product(pid: str, data: ProductUpdateReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
existing = conn.execute("SELECT * FROM products WHERE id=? AND deleted_at IS NULL", (pid,)).fetchone()
if not existing: conn.close(); raise HTTPException(404, "product not found")
updates = {}
if data.name is not None: updates["name"] = data.name
if data.slug is not None: updates["slug"] = data.slug
if data.sku is not None: updates["sku"] = data.sku
if data.category_id is not None: updates["category_id"] = data.category_id
if data.selling_price is not None: updates["selling_price"] = data.selling_price
if data.cost_price is not None: updates["cost_price"] = data.cost_price
if data.stock is not None: updates["stock"] = data.stock
if data.images is not None: updates["images"] = json.dumps(data.images)
if data.is_active is not None: updates["is_active"] = 1 if data.is_active else 0
if updates:
set_clause = ", ".join(f"{k}=?" for k in updates)
conn.execute(f"UPDATE products SET {set_clause} WHERE id=?", (*updates.values(), pid))
conn.commit()
row = conn.execute("SELECT * FROM products WHERE id=?", (pid,)).fetchone()
conn.close()
cache_delete("products:list")
d = dict(row)
if isinstance(d.get("images"), str):
try: d["images"] = json.loads(d["images"])
except: d["images"] = []
return d
@app.delete("/api/v1/products/{pid}")
def api_delete_product(pid: str, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
existing = conn.execute("SELECT * FROM products WHERE id=? AND deleted_at IS NULL", (pid,)).fetchone()
if not existing: conn.close(); raise HTTPException(404, "product not found")
conn.execute("UPDATE products SET deleted_at=datetime('now') WHERE id=?", (pid,))
conn.commit(); conn.close()
cache_delete("products:list")
return {"message": "product deleted"}
@app.post("/api/v1/products/delete")
def api_delete_products(data: AdminBulkIdsReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
ids = [i for i in data.ids if i]
if not ids: raise HTTPException(400, "no ids provided")
conn = get_db()
placeholders = ",".join("?" * len(ids))
cur = conn.execute(f"UPDATE products SET deleted_at=datetime('now') WHERE id IN ({placeholders}) AND deleted_at IS NULL", ids)
conn.commit(); conn.close()
return {"message": "products deleted", "deleted": cur.rowcount}
@app.post("/api/v1/upload")
def api_upload(request: Request, file: UploadFile = File(...)):
user = get_current_user(_bearer_token(request))
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
ALLOWED_UPLOAD_TYPES = ("image/", "application/pdf")
ct = (file.content_type or "").lower()
if not any(ct.startswith(p) for p in ALLOWED_UPLOAD_TYPES):
raise HTTPException(415, "Only image and PDF uploads are allowed")
total = 0
chunks = []
while True:
chunk = file.file.read(1024 * 1024)
if not chunk:
break
total += len(chunk)
if total > MAX_UPLOAD_BYTES:
raise HTTPException(413, "Upload exceeds the 10 MB size limit")
chunks.append(chunk)
body = b"".join(chunks)
IMAGEKIT_PRIVATE_KEY = os.environ.get("IMAGEKIT_PRIVATE_KEY", "private_xzkLqhKSPN8wM93+hUC9LfVfdP0=")
IMAGEKIT_URL_ENDPOINT = os.environ.get("IMAGEKIT_URL_ENDPOINT", "https://ik.imagekit.io/7zjgqregy")
if IMAGEKIT_PRIVATE_KEY:
auth = base64.b64encode(f"{IMAGEKIT_PRIVATE_KEY}:".encode()).decode()
resp = requests.post(
"https://upload.imagekit.io/api/v1/files/upload",
headers={"Authorization": f"Basic {auth}"},
files={"file": (file.filename, io.BytesIO(body), ct or "application/octet-stream")},
data={"fileName": file.filename or "upload", "folder": "/ineed-now"},
)
if not resp.ok:
raise HTTPException(500, f"ImageKit upload failed: {resp.text}")
result = resp.json()
result["url_endpoint"] = IMAGEKIT_URL_ENDPOINT
if "url" in result and "?" not in result["url"]:
result["url"] = result["url"] + "?updatedAt=" + str(int(__import__("time").time() * 1000))
if "thumbnailUrl" in result and "?" not in result["thumbnailUrl"]:
result["thumbnailUrl"] = result["thumbnailUrl"] + "?updatedAt=" + str(int(__import__("time").time() * 1000))
return result
upload_dir = Path("data/uploads")
upload_dir.mkdir(parents=True, exist_ok=True)
ext = Path(file.filename or "upload").suffix or ".bin"
fname = f"{uuid.uuid4().hex}{ext}"
(upload_dir / fname).write_bytes(body)
base_url = str(request.base_url).rstrip("/")
return {"url": f"{base_url}/data/uploads/{fname}", "filePath": f"data/uploads/{fname}"}
@app.get("/api/v1/categories")
def api_categories():
conn = get_db()
rows = conn.execute("SELECT * FROM categories WHERE is_active=1 ORDER BY sort_order, name").fetchall()
conn.close()
return [dict(r) for r in rows]
@app.get("/api/v1/orders")
def api_orders(request: Request):
get_current_user(_bearer_token(request))
conn = get_db(); rows = conn.execute("SELECT * FROM orders ORDER BY created_at DESC").fetchall(); conn.close()
return [dict(r) for r in rows]
@app.post("/api/v1/orders/delete")
def api_delete_orders(data: AdminBulkIdsReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
ids = [i for i in data.ids if i]
if not ids: raise HTTPException(400, "no ids provided")
conn = get_db()
placeholders = ",".join("?" * len(ids))
cur = conn.execute(f"DELETE FROM orders WHERE id IN ({placeholders})", ids)
conn.commit(); conn.close()
return {"message": "orders deleted", "deleted": cur.rowcount}
def _format_user(row: sqlite3.Row) -> dict:
d = {"id": row["id"], "email": row["email"], "full_name": row["full_name"],
"phone": row["phone"], "avatar_url": row["avatar_url"] or "" if "avatar_url" in row.keys() else "",
"role": row["role"], "is_active": bool(row["is_active"]),
"email_verified": False, "created_at": row["created_at"]}
if "latitude" in row.keys():
d["latitude"] = row["latitude"] or 0
d["longitude"] = row["longitude"] or 0
d["location_updated_at"] = row["location_updated_at"] or ""
return d
@app.get("/api/v1/users")
def api_users(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"): raise HTTPException(403, "admin required")
cached = cache_get("users:list")
if cached is not None:
return cached
conn = get_db()
rows = conn.execute("SELECT id,email,full_name,phone,avatar_url,role,latitude,longitude,location_updated_at,is_active,created_at FROM users ORDER BY created_at DESC").fetchall()
out = []
for r in rows:
d = _format_user(r)
d["agent_scope"] = ""
d["agent_instructions"] = ""
d["agent_model"] = ""
cfg = conn.execute("SELECT scope, instructions, model FROM user_agent_config WHERE user_id=?", (d["id"],)).fetchone()
if cfg:
d["agent_scope"] = cfg["scope"] or ""
d["agent_instructions"] = cfg["instructions"] or ""
d["agent_model"] = cfg["model"] or ""
d["chat_count"] = conn.execute(
"SELECT COUNT(*) FROM chat_sessions WHERE user_id=?", (d["id"],)).fetchone()[0]
d["last_chat_at"] = conn.execute(
"SELECT MAX(updated_at) FROM chat_sessions WHERE user_id=?", (d["id"],)).fetchone()[0]
out.append(d)
conn.close()
cache_set("users:list", out, ttl=120)
return out
@app.post("/api/v1/users")
def api_create_user(data: CreateUserReq, request: Request):
user = require_admin(request)
email = _validate_email(data.email)
_validate_password(data.password)
conn = get_db()
if conn.execute("SELECT 1 FROM users WHERE email=?", (email,)).fetchone():
conn.close(); raise HTTPException(409, "email already registered")
uid = str(uuid.uuid4())
hashed = hash_password(data.password)
conn.execute("INSERT INTO users (id,email,password_hash,full_name,phone,role,is_active,avatar_url) VALUES (?,?,?,?,?,?,?,?)",
(uid, email, hashed, data.full_name, data.phone, data.role, 1, data.avatar_url))
conn.commit()
row = conn.execute("SELECT id,email,full_name,phone,role,is_active,created_at,avatar_url FROM users WHERE id=?", (uid,)).fetchone()
conn.close()
cache_delete("users:list")
return _format_user(row)
@app.put("/api/v1/users/{uid}")
def api_update_user(uid: str, data: UpdateUserReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"): raise HTTPException(403, "admin required")
conn = get_db()
existing = conn.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
if not existing: conn.close(); raise HTTPException(404, "user not found")
updates = {}
if data.full_name is not None: updates["full_name"] = data.full_name
if data.phone is not None: updates["phone"] = data.phone
if data.role is not None: updates["role"] = data.role
if data.is_active is not None: updates["is_active"] = 1 if data.is_active else 0
if data.avatar_url is not None: updates["avatar_url"] = data.avatar_url
if updates:
set_clause = ", ".join(f"{k}=?" for k in updates)
conn.execute(f"UPDATE users SET {set_clause} WHERE id=?", (*updates.values(), uid))
conn.commit()
row = conn.execute("SELECT id,email,full_name,phone,role,is_active,created_at,avatar_url FROM users WHERE id=?", (uid,)).fetchone()
conn.close()
cache_delete("users:list")
return _format_user(row)
@app.delete("/api/v1/users/{uid}")
def api_delete_user(uid: str, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"): raise HTTPException(403, "admin required")
if user["id"] == uid: raise HTTPException(400, "cannot delete yourself")
conn = get_db()
existing = conn.execute("SELECT 1 FROM users WHERE id=?", (uid,)).fetchone()
if not existing: conn.close(); raise HTTPException(404, "user not found")
conn.execute("DELETE FROM users WHERE id=?", (uid,))
conn.commit(); conn.close()
cache_delete("users:list")
return {"message": "user deleted"}
@app.post("/api/v1/users/delete")
def api_delete_users(data: AdminBulkIdsReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
ids = [i for i in data.ids if i]
if not ids: raise HTTPException(400, "no ids provided")
if user["id"] in ids: raise HTTPException(400, "cannot delete yourself")
conn = get_db()
placeholders = ",".join("?" * len(ids))
cur = conn.execute(f"DELETE FROM users WHERE id IN ({placeholders})", ids)
conn.commit(); conn.close()
cache_delete("users:list")
return {"message": "users deleted", "deleted": cur.rowcount}
# ββ Admin: per-user agent config + chat history ββ
class AgentConfigReq(BaseModel):
scope: str = ""
instructions: str = ""
model: str = ""
@app.get("/api/v1/admin/users/{uid}/chats")
def api_admin_user_chats(uid: str, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"): raise HTTPException(403, "admin required")
conn = get_db()
if not conn.execute("SELECT 1 FROM users WHERE id=?", (uid,)).fetchone():
conn.close(); raise HTTPException(404, "user not found")
rows = conn.execute("""
SELECT s.id, s.user_id, s.title, s.created_at, s.updated_at,
(SELECT COUNT(*) FROM chat_messages m WHERE m.session_id=s.id) AS message_count,
(SELECT COUNT(*) FROM bookings b WHERE b.session_id=s.id) AS booking_count
FROM chat_sessions s WHERE s.user_id=? ORDER BY s.updated_at DESC LIMIT 200""", (uid,)).fetchall()
conn.close()
return [dict(r) for r in rows]
@app.get("/api/v1/admin/users/{uid}/chats/{sid}")
def api_admin_user_chat_detail(uid: str, sid: str, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"): raise HTTPException(403, "admin required")
conn = get_db()
sess = conn.execute("SELECT * FROM chat_sessions WHERE id=? AND user_id=?", (sid, uid)).fetchone()
if not sess:
conn.close(); raise HTTPException(404, "session not found")
msgs = conn.execute(
"SELECT role, content, plans, created_at, source, answered_by FROM chat_messages WHERE session_id=? "
"ORDER BY created_at, rowid", (sid,)).fetchall()
books = conn.execute(
"SELECT * FROM bookings WHERE session_id=? ORDER BY created_at", (sid,)).fetchall()
conn.close()
out_msgs = []
for r in msgs:
d = dict(r)
try: d["plans"] = json.loads(d["plans"])
except Exception: d["plans"] = []
out_msgs.append(d)
return {"session": dict(sess), "messages": out_msgs, "bookings": [dict(b) for b in books]}
@app.put("/api/v1/admin/users/{uid}/agent")
def api_admin_user_agent(uid: str, data: AgentConfigReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"): raise HTTPException(403, "admin required")
conn = get_db()
if not conn.execute("SELECT 1 FROM users WHERE id=?", (uid,)).fetchone():
conn.close(); raise HTTPException(404, "user not found")
scope = (data.scope or "").strip()
instructions = (data.instructions or "").strip()
model = (data.model or "").strip()
conn.execute(
"INSERT INTO user_agent_config (user_id, scope, instructions, model, updated_at) VALUES (?,?,?,?,datetime('now')) "
"ON CONFLICT(user_id) DO UPDATE SET scope=excluded.scope, instructions=excluded.instructions, "
"model=excluded.model, updated_at=excluded.updated_at",
(uid, scope, instructions, model))
conn.commit(); conn.close()
return {"message": "agent config saved", "scope": scope, "instructions": instructions, "model": model}
@app.get("/api/v1/dashboard/stats")
def api_stats(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"): raise HTTPException(403, "admin required")
conn = get_db()
result = {"total_users": conn.execute("SELECT COUNT(*) FROM users").fetchone()[0],
"total_products": conn.execute("SELECT COUNT(*) FROM products WHERE deleted_at IS NULL").fetchone()[0],
"total_orders": conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0],
"total_categories": 0, "total_revenue": 0, "pending_orders": 0}
conn.close()
return result
@app.get("/api/v1/settings")
def api_settings():
cached = cache_get("settings:all")
if cached is not None:
return cached
conn = get_db()
rows = conn.execute("SELECT setting_key, setting_value, description FROM system_settings ORDER BY id").fetchall()
conn.close()
if not rows:
result = [
{"key": "store_name", "value": "ineed-now"},
{"key": "store_phone", "value": ""},
{"key": "currency", "value": "LAK"},
{"key": "tax_percent", "value": "7"},
{"key": "store_logo", "value": ""},
]
else:
result = [{"key": r["setting_key"], "value": r["setting_value"], "description": r["description"]} for r in rows]
cache_set("settings:all", result, ttl=600)
return result
_ALLOWED_SETTINGS = {"store_name", "store_phone", "currency", "tax_percent", "store_logo"}
_MAX_SETTING_VALUE = 1_000_000
class SettingUpdate(BaseModel):
key: str
value: str
class SettingsUpdateReq(BaseModel):
settings: list[SettingUpdate]
@app.put("/api/v1/settings")
def api_update_settings(data: SettingsUpdateReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
if not data.settings:
raise HTTPException(400, "settings required")
conn = get_db()
for item in data.settings:
if item.key not in _ALLOWED_SETTINGS:
continue
if len(item.value) > _MAX_SETTING_VALUE:
conn.close()
raise HTTPException(400, f"setting '{item.key}' value is too large")
conn.execute(
"INSERT INTO system_settings (setting_key, setting_value, description) VALUES (?,?,?) "
"ON CONFLICT(setting_key) DO UPDATE SET setting_value=excluded.setting_value, updated_at=datetime('now')",
(item.key, item.value, ""))
conn.commit()
rows = conn.execute("SELECT setting_key, setting_value, description FROM system_settings ORDER BY id").fetchall()
conn.close()
cache_delete("settings:all")
_invalidate_settings_cache()
return [{"key": r["setting_key"], "value": r["setting_value"], "description": r["description"]} for r in rows]
# ββ AI / chat / bookings ββ
class AIChatReq(BaseModel):
message: str = ""
session_id: str | None = None
language: str | None = None
files: list = []
model: str | None = None
admin_reply: str | None = None
guest_id: str | None = None
class ChatRatingReq(BaseModel):
rating: int = 0
note: str = ""
@app.post("/api/v1/ai/chat")
def api_ai_chat(data: AIChatReq, request: Request):
user = None
try:
user = get_current_user(_bearer_token(request))
except HTTPException:
user = None
msg = (data.message or "").strip()
files = data.files or []
if not msg and not files and not data.admin_reply:
raise HTTPException(400, "message required")
# Manual admin reply: inject an assistant message instead of calling the AI.
admin_reply = (data.admin_reply or "").strip()
if admin_reply:
admin = None
try:
admin = get_current_user(_bearer_token(request))
except HTTPException:
raise HTTPException(401, "admin auth required")
if admin["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
row = conn.execute(
"SELECT user_id FROM chat_sessions WHERE id=?", (data.session_id,)).fetchone()
conn.close()
if not row:
raise HTTPException(404, "session not found")
sid = data.session_id
_save_message(sid, "assistant", admin_reply, [], source="admin", answered_by=admin["id"])
return {"session_id": sid, "reply": admin_reply, "plans": [], "agent": "Admin", "requires_auth": False}
conn = get_db()
enabled = _get_setting(conn, "ai_enabled", "true").lower()
conn.close()
if enabled in ("false", "0", "no", "off"):
raise HTTPException(503, "AI assistant is disabled")
uid = user["id"] if user else ""
# Build the user content: plain text + uploaded files (images β vision, others β text preview)
user_parts: list = []
has_image = False
file_names: list = []
for f in files:
fname = str(f.get("name") or "file")[:120]
ftype = str(f.get("type") or "").lower()
fdata = f.get("data") or ""
if fname:
file_names.append(fname)
if ftype.startswith("image/") and fdata:
try:
base64.b64decode(fdata, validate=True)
has_image = True
mime = ftype if ftype in ("image/png", "image/jpeg", "image/webp", "image/gif") else "image/png"
user_parts.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{fdata}"}})
continue
except Exception:
pass
if isinstance(fdata, str) and fdata.strip():
text = fdata[:8000]
garbled = text.count("\ufffd") / max(len(text), 1)
if garbled > 0.05:
user_parts.append({"type": "text", "text": f"[User attached a file: {fname}]"})
else:
user_parts.append({"type": "text", "text": f"[User attached file: {fname}]\n{text}"})
stored_msg = msg
if file_names:
suffix = "[Attached: " + ", ".join(file_names[:5]) + "]"
stored_msg = f"{msg}\n{suffix}" if msg else suffix
sid = _ensure_session(uid, data.session_id, data.guest_id)
_save_message(sid, "user", stored_msg)
conn = get_db()
history = conn.execute(
"SELECT role, content FROM chat_messages WHERE session_id=? ORDER BY created_at, rowid", (sid,)).fetchall()
max_tokens = int(os.environ.get("AI_MAX_TOKENS") or float(_get_setting(conn, "ai_max_tokens", "900")))
temperature = float(os.environ.get("AI_TEMPERATURE") or _get_setting(conn, "ai_temperature", "0.7"))
agent_name = os.environ.get("AI_AGENT_NAME") or _get_setting(conn, "ai_agent_name", "ineed-now Assistant")
conn.close()
history = [dict(h) for h in history][:-1]
messages = _build_messages(uid or None, history, msg, language=data.language)
if files:
if not user_parts:
user_parts.append({"type": "text", "text": msg or "[User attached files]"})
elif msg:
user_parts.insert(0, {"type": "text", "text": msg})
messages[-1] = {"role": "user", "content": user_parts}
# Per-user agent config: scope + instructions + model override.
ucfg = _user_agent_config(uid) if uid else {"scope": "", "instructions": "", "model": ""}
if ucfg.get("scope") or ucfg.get("instructions"):
extra = []
if ucfg.get("scope"):
extra.append(f"Agent scope for this user: {ucfg['scope']}")
if ucfg.get("instructions"):
extra.append(f"Specific instructions for answering this user: {ucfg['instructions']}")
sys_msg = messages[0]
sys_msg = {"role": "system", "content": sys_msg["content"] + "\n\n## Per-user agent configuration\n" + "\n".join(extra)}
messages = [sys_msg] + messages[1:]
model = data.model or (ucfg.get("model") or None)
try:
reply = _ai_chat(messages, max_tokens=max_tokens, temperature=temperature, model=model)
except HTTPException as e:
# A provider that doesn't support vision rejects image parts β retry text-only.
if has_image and e.status_code == 502:
final_parts = [p for p in user_parts if not (isinstance(p, dict) and p.get("type") == "image_url")]
if not final_parts:
final_parts = [{"type": "text", "text": msg or "[User attached files]"}]
text_content = final_parts if len(final_parts) > 1 else final_parts[0]["text"]
messages[-1] = {"role": "user", "content": text_content}
reply = _ai_chat(messages, max_tokens=max_tokens, temperature=temperature, model=model)
else:
raise
plans = _extract_plans(reply)
dynamic_ui = _extract_dynamic_ui(reply)
requires_auth = bool(plans) and not user
if plans and user:
_save_plans(sid, uid, plans)
# Clean reply: remove UI/plan markers from displayed text
clean = re.sub(r"\[\[UI_START\]\][\s\S]*?\[\[UI_END\]\]", "", reply)
clean = re.sub(r"\[\[PLAN_START\]\][\s\S]*?\[\[PLAN_END\]\]", "", clean)
clean = re.sub(r"```json[\s\S]*?```", "", clean).strip()
_save_message(sid, "assistant", clean, plans, dynamic_ui=dynamic_ui)
conn = get_db()
conn.execute("UPDATE chat_sessions SET title=? WHERE id=? AND title='New chat'", (msg[:60] or "New chat", sid))
conn.commit(); conn.close()
return {"session_id": sid, "reply": clean, "plans": plans, "agent": agent_name, "requires_auth": requires_auth, "dynamic_ui": dynamic_ui}
@app.get("/api/v1/ai/sessions")
def api_ai_sessions(request: Request):
user = get_current_user(_bearer_token(request))
conn = get_db()
rows = conn.execute(
"SELECT * FROM chat_sessions WHERE user_id=? ORDER BY updated_at DESC LIMIT 50",
(user["id"],)).fetchall()
out = []
for r in rows:
d = dict(r)
d["message_count"] = conn.execute(
"SELECT COUNT(*) FROM chat_messages WHERE session_id=?", (d["id"],)).fetchone()[0]
out.append(d)
conn.close()
return out
@app.get("/api/v1/ai/sessions/{sid}/messages")
def api_ai_messages(sid: str, request: Request):
user = get_current_user(_bearer_token(request))
conn = get_db()
sess = conn.execute("SELECT * FROM chat_sessions WHERE id=? AND user_id=?", (sid, user["id"])).fetchone()
if not sess:
conn.close(); raise HTTPException(404, "session not found")
rows = conn.execute(
"SELECT role, content, plans, created_at, source, answered_by FROM chat_messages WHERE session_id=? "
"ORDER BY created_at, rowid", (sid,)).fetchall()
conn.close()
out = []
for r in rows:
d = dict(r)
try: d["plans"] = json.loads(d["plans"])
except Exception: d["plans"] = []
try: d["dynamic_ui"] = json.loads(d["dynamic_ui"])
except Exception: d["dynamic_ui"] = []
out.append(d)
return {"session": dict(sess), "messages": out}
@app.delete("/api/v1/ai/sessions/{sid}")
def api_ai_delete_session(sid: str, request: Request):
user = get_current_user(_bearer_token(request))
conn = get_db()
sess = conn.execute("SELECT 1 FROM chat_sessions WHERE id=? AND user_id=?", (sid, user["id"])).fetchone()
if not sess:
conn.close(); raise HTTPException(404, "session not found")
conn.execute("DELETE FROM chat_messages WHERE session_id=?", (sid,))
conn.execute("DELETE FROM bookings WHERE session_id=?", (sid,))
conn.execute("DELETE FROM chat_sessions WHERE id=?", (sid,))
conn.commit(); conn.close()
return {"message": "deleted"}
@app.get("/api/v1/admin/ai/settings")
def api_admin_ai_settings(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
rows = conn.execute(
"SELECT setting_key, setting_value, description FROM system_settings "
"WHERE setting_key LIKE 'ai_%' ORDER BY id").fetchall()
conn.close()
out = []
for r in rows:
d = {"key": r["setting_key"], "value": r["setting_value"], "description": r["description"]}
if d["key"] == "ai_api_keys":
try:
keys = json.loads(d["value"])
if not isinstance(keys, list):
keys = []
clean = []
for e in keys:
if isinstance(e, str):
clean.append({"key": e, "base_url": ""})
elif isinstance(e, dict):
clean.append({"key": e.get("key", ""), "base_url": e.get("base_url", "")})
d["keys"] = [c for c in clean if c["key"]]
except Exception:
d["keys"] = []
d["value"] = ", ".join(c["key"] for c in d["keys"])
elif d["key"] == "ai_models":
try:
models = json.loads(d["value"])
if not isinstance(models, list):
models = []
d["models"] = [m for m in models if isinstance(m, str) and m.strip()]
except Exception:
d["models"] = []
d["value"] = ", ".join(d["models"])
out.append(d)
return out
_ALLOWED_AI_SETTINGS = {
"ai_enabled", "ai_agent_name", "ai_model", "ai_base_url",
"ai_api_keys", "ai_system_prompt", "ai_max_tokens", "ai_temperature",
"ai_models",
}
@app.put("/api/v1/admin/ai/settings")
def api_admin_ai_settings_update(data: SettingsUpdateReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
for item in data.settings:
if item.key not in _ALLOWED_AI_SETTINGS:
continue
value = item.value
if item.key == "ai_api_keys":
stripped = value.strip()
try:
parsed = json.loads(stripped)
if isinstance(parsed, list):
keys = []
for e in parsed:
if isinstance(e, str) and e.strip():
keys.append(e.strip())
elif isinstance(e, dict) and e.get("key") and str(e["key"]).strip():
keys.append({"key": str(e["key"]).strip(), "base_url": str(e.get("base_url") or "").strip()})
value = json.dumps(keys)
else:
value = json.dumps([])
except Exception:
keys = [k.strip() for k in stripped.replace("\n", ",").split(",") if k.strip()]
value = json.dumps(keys)
if len(value) > _MAX_SETTING_VALUE:
conn.close()
raise HTTPException(400, f"setting '{item.key}' value is too large")
conn.execute(
"INSERT INTO system_settings (setting_key, setting_value, description) VALUES (?,?,?) "
"ON CONFLICT(setting_key) DO UPDATE SET setting_value=excluded.setting_value, updated_at=datetime('now')",
(item.key, value, ""))
conn.commit(); conn.close()
return {"message": "AI settings updated"}
@app.get("/api/v1/admin/ai/fetch-models")
def api_admin_fetch_models(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
result = {"opencode": [], "openrouter": []}
try:
res = requests.get("https://openrouter.ai/api/v1/models", timeout=10)
if res.ok:
data = res.json().get("data", [])
for m in data:
mid = m.get("id", "")
pricing = m.get("pricing", {})
prompt_price = float(pricing.get("prompt", "1") or "1")
completion_price = float(pricing.get("completion", "1") or "1")
if ":free" in mid or (prompt_price == 0 and completion_price == 0):
result["openrouter"].append({
"id": mid,
"name": m.get("name", mid),
"provider": "openrouter",
})
except Exception:
pass
try:
res = requests.get("https://opencode.ai/zen/v1/models", timeout=10)
if res.ok:
data = res.json().get("data", [])
for m in data:
mid = m.get("id", "")
result["opencode"].append({
"id": mid,
"name": m.get("name", mid),
"provider": "opencode",
})
except Exception:
pass
result["opencode"] = result["opencode"][:50]
result["openrouter"] = result["openrouter"][:50]
return result
@app.get("/api/v1/admin/ai/chats")
def api_admin_ai_chats(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
rows = conn.execute("""
SELECT s.id, s.user_id, s.title, s.channel, s.channel_user_id, s.channel_user_name,
s.guest_id, s.rating, s.rating_note,
s.created_at, s.updated_at,
COALESCE(u.email, '') AS email, COALESCE(u.full_name, cu.name, '') AS full_name,
gl.latitude AS guest_lat, gl.longitude AS guest_lng, gl.ip_address AS guest_ip,
(SELECT COUNT(*) FROM chat_messages m WHERE m.session_id=s.id) AS message_count,
(SELECT COUNT(*) FROM bookings b WHERE b.session_id=s.id) AS booking_count
FROM chat_sessions s
LEFT JOIN users u ON u.id=s.user_id
LEFT JOIN channel_users cu ON cu.channel=s.channel AND cu.external_id=s.channel_user_id
LEFT JOIN guest_locations gl ON gl.session_id=s.guest_id
ORDER BY s.updated_at DESC LIMIT 200""").fetchall()
conn.close()
return [dict(r) for r in rows]
@app.get("/api/v1/admin/ai/chats/{sid}")
def api_admin_ai_chat_detail(sid: str, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
sess = conn.execute("SELECT * FROM chat_sessions WHERE id=?", (sid,)).fetchone()
if not sess:
conn.close(); raise HTTPException(404, "session not found")
msgs = conn.execute(
"SELECT role, content, plans, created_at, source, answered_by, channel FROM chat_messages WHERE session_id=? "
"ORDER BY created_at, rowid", (sid,)).fetchall()
books = conn.execute(
"SELECT * FROM bookings WHERE session_id=? ORDER BY created_at", (sid,)).fetchall()
cu = None
if sess["channel"] and sess["channel_user_id"]:
cu = conn.execute("SELECT * FROM channel_users WHERE channel=? AND external_id=?",
(sess["channel"], sess["channel_user_id"])).fetchone()
gl = None
if sess["guest_id"]:
gl = conn.execute("SELECT latitude, longitude, ip_address, user_agent FROM guest_locations WHERE session_id=?",
(sess["guest_id"],)).fetchone()
conn.close()
out_msgs = []
for r in msgs:
d = dict(r)
try: d["plans"] = json.loads(d["plans"])
except Exception: d["plans"] = []
out_msgs.append(d)
return {"session": dict(sess), "messages": out_msgs, "bookings": [dict(b) for b in books],
"channel_user": dict(cu) if cu else None, "guest_location": dict(gl) if gl else None}
@app.post("/api/v1/admin/ai/chats/{sid}/rating")
def api_admin_ai_chat_rating(sid: str, data: ChatRatingReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
rating = max(0, min(5, int(data.rating or 0)))
note = (data.note or "").strip()[:500]
conn = get_db()
cur = conn.execute("UPDATE chat_sessions SET rating=?, rating_note=?, updated_at=datetime('now') WHERE id=?",
(rating, note, sid))
conn.commit(); conn.close()
if cur.rowcount == 0:
raise HTTPException(404, "session not found")
return {"message": "rating saved", "rating": rating, "rating_note": note}
@app.get("/api/v1/admin/ai/analytics")
def api_admin_ai_analytics(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
total_sessions = conn.execute("SELECT COUNT(*) FROM chat_sessions").fetchone()[0]
total_messages = conn.execute("SELECT COUNT(*) FROM chat_messages").fetchone()[0]
total_bookings = conn.execute("SELECT COUNT(*) FROM bookings").fetchone()[0]
user_messages = conn.execute("SELECT content FROM chat_messages WHERE role='user'").fetchall()
conn.close()
STOP_WORDS = {
"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers",
"herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves",
"what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are",
"was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does",
"did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until",
"while", "of", "at", "by", "for", "with", "about", "against", "between", "through",
"during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out",
"on", "off", "over", "under", "again", "further", "then", "once", "here", "there",
"when", "where", "why", "how", "all", "both", "each", "few", "more", "most", "other",
"some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very",
"s", "t", "can", "will", "just", "don", "should", "now", "d", "ll", "m", "o", "re",
"ve", "y", "ain", "aren", "couldn", "didn", "doesn", "hadn", "hasn", "haven", "isn",
"ma", "mightn", "mustn", "needn", "shan", "shouldn", "wasn", "weren", "won", "wouldn",
"hello", "hi", "hey", "please", "thank", "thanks", "ok", "yes", "no", "would", "like",
"want", "need", "know", "get", "go", "come", "make", "tell", "say", "said", "one",
"also", "could", "may", "much", "many", "well", "back", "even", "still", "new", "good",
"right", "way", "thing", "things", "something", "anything", "everything", "nothing",
"place", "time", "day", "night", "today", "tomorrow", "week", "month", "year",
}
word_freq = {}
for row in user_messages:
content = (row["content"] or "").lower()
words = re.findall(r'\b[a-z]{3,}\b', content)
for w in words:
if w not in STOP_WORDS:
word_freq[w] = word_freq.get(w, 0) + 1
top_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:30]
CATEGORY_KEYWORDS = {
"hotels": ["hotel", "hostel", "accommodation", "stay", "room", "booking", "lodge", "resort", "inn"],
"flights": ["flight", "airline", "airport", "fly", "plane", "ticket", "airfare"],
"food": ["food", "restaurant", "delivery", "eat", "meal", "order", "menu", "dinner", "lunch", "breakfast"],
"shopping": ["shop", "buy", "product", "store", "price", "sell", "item", "cart", "purchase"],
"car_rental": ["car", "rent", "rental", "vehicle", "drive", "driver"],
"trips": ["trip", "travel", "tour", "visit", "sightseeing", "itinerary", "destination"],
"apartments": ["apartment", "rent", "house", "property", "lease", "condo"],
"general": ["help", "info", "question", "how", "what", "where", "when"],
}
category_counts = {cat: 0 for cat in CATEGORY_KEYWORDS}
for row in user_messages:
content = (row["content"] or "").lower()
for cat, keywords in CATEGORY_KEYWORDS.items():
if any(kw in content for kw in keywords):
category_counts[cat] += 1
top_categories = sorted(category_counts.items(), key=lambda x: x[1], reverse=True)
top_categories = [(cat, cnt) for cat, cnt in top_categories if cnt > 0]
return {
"total_sessions": total_sessions,
"total_messages": total_messages,
"total_user_messages": len(user_messages),
"total_bookings": total_bookings,
"top_words": [{"word": w, "count": c} for w, c in top_words],
"top_categories": [{"category": cat, "count": cnt} for cat, cnt in top_categories],
}
@app.get("/api/v1/admin/ai/bookings")
def api_admin_ai_bookings(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
rows = conn.execute("""
SELECT b.*, COALESCE(u.email, 'unknown') AS email, COALESCE(u.full_name, '') AS full_name,
COALESCE(s.title, '') AS session_title
FROM bookings b
LEFT JOIN users u ON u.id=b.user_id
LEFT JOIN chat_sessions s ON s.id=b.session_id
ORDER BY b.created_at DESC LIMIT 200""").fetchall()
conn.close()
out = []
for r in rows:
d = dict(r)
try: d["items"] = json.loads(d["items"])
except Exception: d["items"] = []
out.append(d)
return out
@app.post("/api/v1/admin/ai/chats/delete")
def api_admin_ai_chats_delete(data: AdminBulkIdsReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
ids = [i for i in data.ids if i]
if not ids:
raise HTTPException(400, "ids required")
ph = ",".join("?" for _ in ids)
conn = get_db()
conn.execute(f"DELETE FROM chat_messages WHERE session_id IN ({ph})", ids)
conn.execute(f"DELETE FROM bookings WHERE session_id IN ({ph})", ids)
cur = conn.execute(f"DELETE FROM chat_sessions WHERE id IN ({ph})", ids)
conn.commit(); conn.close()
return {"message": "deleted", "deleted": cur.rowcount}
@app.post("/api/v1/admin/ai/bookings/delete")
def api_admin_ai_bookings_delete(data: AdminBulkIdsReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
ids = [i for i in data.ids if i]
if not ids:
raise HTTPException(400, "ids required")
ph = ",".join("?" for _ in ids)
conn = get_db()
cur = conn.execute(f"DELETE FROM bookings WHERE id IN ({ph})", ids)
conn.commit(); conn.close()
return {"message": "deleted", "deleted": cur.rowcount}
# ββ Admin: notifications ββ
class NotifReadReq(BaseModel):
ids: list[str] = []
@app.get("/api/v1/admin/notifications")
def api_admin_notifications(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
rows = conn.execute(
"SELECT id, type, title, message, data, is_read, created_at FROM notifications "
"WHERE user_id=? ORDER BY created_at DESC, rowid DESC LIMIT 100", (user["id"],)).fetchall()
unread = conn.execute(
"SELECT COUNT(*) FROM notifications WHERE user_id=? AND is_read=0", (user["id"],)).fetchone()[0]
conn.close()
out = []
for r in rows:
d = dict(r)
try: d["data"] = json.loads(d["data"])
except Exception: d["data"] = {}
d["is_read"] = bool(d["is_read"])
out.append(d)
return {"notifications": out, "unread": unread}
@app.post("/api/v1/admin/notifications/read")
def api_admin_notifications_read(data: NotifReadReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
ids = [i for i in data.ids if i]
if ids:
ph = ",".join("?" for _ in ids)
cur = conn.execute(
f"UPDATE notifications SET is_read=1 WHERE user_id=? AND id IN ({ph})", [user["id"], *ids])
else:
cur = conn.execute(
"UPDATE notifications SET is_read=1 WHERE user_id=? AND is_read=0", (user["id"],))
conn.commit(); conn.close()
return {"message": "marked read", "updated": cur.rowcount}
# ββ Channel webhooks (WhatsApp, Telegram, Line, Messenger) ββ
# Public endpoints. Each URL includes a per-channel secret so unconfigured
# or disabled channels simply acknowledge the ping instead of processing it.
@app.post("/api/v1/channels/telegram/webhook/{secret}")
async def api_channel_telegram_webhook(secret: str, request: Request):
body = await request.json()
cfg = _get_channel_config("telegram")
if not cfg.get("enabled") or cfg.get("webhook_secret") != secret:
return {"ok": True}
update = body.get("message") or body.get("edited_message") or {}
chat = update.get("chat") or {}
chat_id = str(chat.get("id", ""))
if not chat_id:
return {"ok": True}
text = (update.get("text") or "").strip()
name = ((chat.get("first_name") or "") + " " + (chat.get("last_name") or "")).strip()
name = name or chat.get("username") or chat_id
await asyncio.to_thread(_process_channel_message, "telegram", chat_id, name, text, "",
str(body.get("update_id", "")))
return {"ok": True}
@app.get("/api/v1/channels/messenger/webhook/{secret}")
def api_channel_messenger_verify(secret: str, request: Request):
q = request.query_params
cfg = _get_channel_config("messenger")
if (q.get("hub.mode") == "subscribe" and q.get("hub.verify_token")
and q.get("hub.verify_token") == cfg.get("verify_token", "")):
return Response(content=q.get("hub.challenge", "ok"), media_type="text/plain")
raise HTTPException(403, "verification failed")
@app.post("/api/v1/channels/messenger/webhook/{secret}")
async def api_channel_messenger_webhook(secret: str, request: Request):
body = await request.json()
cfg = _get_channel_config("messenger")
if not cfg.get("enabled") or cfg.get("webhook_secret") != secret:
return {"ok": True}
for entry in body.get("entry", []):
for event in entry.get("messaging", []):
sender = event.get("sender") or {}
message = event.get("message") or {}
psid = str(sender.get("id", ""))
text = (message.get("text") or "").strip()
if not psid or not text:
continue
await asyncio.to_thread(_process_channel_message, "messenger", psid, "", text, "",
str(message.get("mid", "")))
return {"ok": True}
@app.post("/api/v1/channels/line/webhook/{secret}")
async def api_channel_line_webhook(secret: str, request: Request):
raw = await request.body()
cfg = _get_channel_config("line")
c = cfg
if not cfg.get("enabled") or c.get("webhook_secret") != secret:
return {"ok": True}
signature = request.headers.get("X-Line-Signature", "")
channel_secret = c.get("channel_secret", "")
if channel_secret:
expected = hmac.new(channel_secret.encode(), raw, hashlib.sha256).hexdigest()
if signature != expected:
return {"ok": True}
body = json.loads(raw)
for ev in body.get("events", []):
if ev.get("type") != "message":
continue
src = ev.get("source") or {}
msg = ev.get("message") or {}
uid = str(src.get("userId", ""))
text = (msg.get("text") or "").strip()
if not uid or msg.get("type") != "text":
continue
await asyncio.to_thread(_process_channel_message, "line", uid, "", text, "",
str(msg.get("id", "")))
return {"ok": True}
@app.get("/api/v1/channels/whatsapp/webhook/{secret}")
def api_channel_whatsapp_verify(secret: str, request: Request):
q = request.query_params
cfg = _get_channel_config("whatsapp")
if (q.get("hub.mode") == "subscribe" and q.get("hub.verify_token")
and q.get("hub.verify_token") == cfg.get("verify_token", "")):
return Response(content=q.get("hub.challenge", "ok"), media_type="text/plain")
raise HTTPException(403, "verification failed")
@app.post("/api/v1/channels/whatsapp/webhook/{secret}")
async def api_channel_whatsapp_webhook(secret: str, request: Request):
body = await request.json()
cfg = _get_channel_config("whatsapp")
if not cfg.get("enabled") or cfg.get("webhook_secret") != secret:
return {"ok": True}
for entry in body.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value") or {}
if change.get("field") == "statuses":
continue
contacts = value.get("contacts") or []
name = ""
if contacts and contacts[0].get("profile"):
name = contacts[0]["profile"].get("name", "")
for msg in value.get("messages", []):
text = ((msg.get("text") or {}).get("body") or "").strip()
phone = str(msg.get("from", ""))
if not phone or not text:
continue
await asyncio.to_thread(_process_channel_message, "whatsapp", phone, name, text, "",
str(msg.get("id", "")))
return {"ok": True}
# ββ Admin: channel integrations ββ
class ChannelConfigItem(BaseModel):
channel: str
config: dict = {}
is_enabled: bool = True
class ChannelsUpdateReq(BaseModel):
channels: list[ChannelConfigItem] = []
class ChannelTestReq(BaseModel):
channel: str
class ChannelWebhookReq(BaseModel):
channel: str
class ChannelReplyReq(BaseModel):
session_id: str
message: str
class ChannelSendReq(BaseModel):
channel: str
external_id: str
message: str
name: str = ""
def _admin_channel_payload() -> dict:
conn = get_db()
out = []
for ch in _CHANNELS:
cfg = _get_channel_config(ch)
c = dict(cfg)
c["webhook_secret"] = str(c.get("webhook_secret") or "")
required = _REQUIRED_CHANNEL_FIELD.get(ch, "")
conv = conn.execute("SELECT COUNT(*) FROM chat_sessions WHERE channel=?", (ch,)).fetchone()[0]
out.append({
"channel": ch,
"is_enabled": bool(cfg.get("enabled")),
"config": c,
"configured": bool(required and c.get(required)),
"conversation_count": conv,
"webhook_url": _webhook_url(ch),
})
conn.close()
return {"base_url": _PUBLIC_BASE, "channels": out}
@app.get("/api/v1/admin/channels")
def api_admin_channels(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
return _admin_channel_payload()
@app.put("/api/v1/admin/channels")
def api_admin_channels_update(data: ChannelsUpdateReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
for item in data.channels:
if item.channel not in _CHANNELS:
continue
cfg = _get_channel_config(item.channel)
c = dict(cfg)
for k, v in (item.config or {}).items():
if k == "webhook_secret":
continue
c[str(k)] = str(v).strip() if isinstance(v, str) else v
c.setdefault("webhook_secret", cfg.get("webhook_secret") or str(uuid.uuid4())[:24])
_save_channel_config(item.channel, c, item.is_enabled)
return _admin_channel_payload()
@app.post("/api/v1/admin/channels/test")
def api_admin_channel_test(data: ChannelTestReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
if data.channel not in _CHANNELS:
raise HTTPException(400, "unknown channel")
return _test_channel(data.channel)
@app.post("/api/v1/admin/channels/set-webhook")
def api_admin_channel_set_webhook(data: ChannelWebhookReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
ch = data.channel
if ch not in _CHANNELS:
raise HTTPException(400, "unknown channel")
url = _webhook_url(ch)
if ch == "telegram":
cfg = _get_channel_config(ch)
token = cfg.get("bot_token", "")
if not token:
raise HTTPException(400, "bot_token is required first")
try:
r = requests.post(f"https://api.telegram.org/bot{token}/setWebhook",
data={"url": url, "drop_pending_updates": "true"}, timeout=20)
d = r.json() if r.ok else {}
if d.get("ok"):
return {"ok": True, "url": url, "detail": d.get("description", "")}
return {"ok": False, "url": url, "error": d.get("description", r.text[:300])}
except requests.exceptions.RequestException as e:
return {"ok": False, "url": url, "error": f"network error: {e}"}
return {"ok": False, "url": url,
"error": "This channel does not support automatic webhook registration. Copy the webhook URL into your platform dashboard."}
@app.get("/api/v1/admin/channels/conversations")
def api_admin_channel_conversations(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
rows = conn.execute("""
SELECT s.id, s.user_id, s.channel, s.channel_user_id, s.channel_user_name, s.title,
s.created_at, s.updated_at,
COALESCE(cu.name, s.channel_user_name, '') AS full_name,
(SELECT COUNT(*) FROM chat_messages m WHERE m.session_id=s.id) AS message_count,
(SELECT COUNT(*) FROM bookings b WHERE b.session_id=s.id) AS booking_count,
(SELECT content FROM chat_messages m WHERE m.session_id=s.id AND m.role='user'
ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1) AS last_user_message
FROM chat_sessions s
LEFT JOIN channel_users cu ON cu.channel=s.channel AND cu.external_id=s.channel_user_id
WHERE s.channel IS NOT NULL AND s.channel != ''
ORDER BY s.updated_at DESC LIMIT 200""").fetchall()
conn.close()
return [dict(r) for r in rows]
@app.get("/api/v1/admin/channels/conversations/{sid}")
def api_admin_channel_conversation_detail(sid: str, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
sess = conn.execute(
"SELECT * FROM chat_sessions WHERE id=? AND channel IS NOT NULL AND channel != ''", (sid,)).fetchone()
if not sess:
conn.close()
raise HTTPException(404, "session not found")
msgs = conn.execute(
"SELECT role, content, plans, created_at, source, answered_by, channel FROM chat_messages "
"WHERE session_id=? ORDER BY created_at, rowid", (sid,)).fetchall()
books = conn.execute(
"SELECT * FROM bookings WHERE session_id=? ORDER BY created_at", (sid,)).fetchall()
cu = conn.execute(
"SELECT * FROM channel_users WHERE channel=? AND external_id=?",
(sess["channel"], sess["channel_user_id"])).fetchone()
conn.close()
out_msgs = []
for r in msgs:
d = dict(r)
try: d["plans"] = json.loads(d["plans"])
except Exception: d["plans"] = []
out_msgs.append(d)
return {"session": dict(sess), "messages": out_msgs, "bookings": [dict(b) for b in books],
"channel_user": dict(cu) if cu else None}
@app.post("/api/v1/admin/channels/reply")
def api_admin_channel_reply(data: ChannelReplyReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
msg = (data.message or "").strip()
if not msg:
raise HTTPException(400, "message required")
conn = get_db()
sess = conn.execute(
"SELECT * FROM chat_sessions WHERE id=? AND channel IS NOT NULL AND channel != ''",
(data.session_id,)).fetchone()
conn.close()
if not sess:
raise HTTPException(404, "session not found")
_save_message(data.session_id, "assistant", msg, [], source="admin",
answered_by=user["id"], channel=sess["channel"])
sent, err = _send_channel_reply(sess["channel"], sess["channel_user_id"], msg)
return {"ok": sent, "error": err if not sent else ""}
@app.post("/api/v1/admin/channels/send")
def api_admin_channel_send(data: ChannelSendReq, request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
ch = data.channel
if ch not in _CHANNELS:
raise HTTPException(400, "unknown channel")
msg = (data.message or "").strip()
if not msg or not data.external_id:
raise HTTPException(400, "message and external_id required")
sid = _ensure_channel_session(ch, data.external_id)
_save_message(sid, "assistant", msg, [], source="admin", answered_by=user["id"], channel=ch)
sent, err = _send_channel_reply(ch, data.external_id, msg)
return {"ok": sent, "error": err if not sent else "", "session_id": sid}
@app.get("/api/v1/admin/channels/users")
def api_admin_channel_users(request: Request):
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
rows = conn.execute("""
SELECT cu.id, cu.channel, cu.external_id, cu.name, cu.avatar_url, cu.last_seen_at, cu.created_at,
(SELECT COUNT(*) FROM chat_sessions s
WHERE s.channel=cu.channel AND s.channel_user_id=cu.external_id) AS session_count,
(SELECT COUNT(*) FROM chat_messages m JOIN chat_sessions s ON s.id=m.session_id
WHERE s.channel=cu.channel AND s.channel_user_id=cu.external_id AND m.role='user') AS message_count
FROM channel_users cu ORDER BY cu.last_seen_at DESC LIMIT 200""").fetchall()
conn.close()
return [_to_dict(r) for r in rows]
@app.get("/api/v1/metrics")
def api_metrics(request: Request):
"""Basic metrics endpoint (admin only)."""
user = get_current_user(_bearer_token(request))
if user["role"] not in ("admin", "superadmin"):
raise HTTPException(403, "admin required")
conn = get_db()
try:
stats = {}
for tbl in ["users", "products", "orders", "chat_sessions", "chat_messages"]:
if IS_POSTGRES:
row = fetch_one(conn, f"SELECT COUNT(*) as c FROM {tbl}")
stats[f"total_{tbl}"] = row.get("c", 0) if row else 0
else:
row = conn.execute(f"SELECT COUNT(*) FROM {tbl}").fetchone()
stats[f"total_{tbl}"] = row[0] if row else 0
finally:
_close(conn)
from cache import cache_stats
stats["cache"] = cache_stats()
stats["database_engine"] = "postgresql" if IS_POSTGRES else "sqlite"
return stats
# ββ Rate limiting (in-memory, per-IP) ββ
_rate_limit_store: dict[str, list[float]] = {}
RATE_LIMIT_WINDOW = 60 # seconds
RATE_LIMIT_MAX = 100 # requests per window
class _RateLimitMiddleware:
"""Simple in-memory rate limiter. Skips health checks and static files."""
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
path = scope.get("path", "")
# Skip rate limiting for health checks and static files
if path.startswith("/api/v1/health") or path.startswith("/api/v1/metrics") or not path.startswith("/api/"):
await self.app(scope, receive, send)
return
# Get client IP
client = scope.get("client", ("0.0.0.0", 0))
ip = client[0] if client else "0.0.0.0"
now = time.time()
# Clean old entries
if ip in _rate_limit_store:
_rate_limit_store[ip] = [t for t in _rate_limit_store[ip] if now - t < RATE_LIMIT_WINDOW]
else:
_rate_limit_store[ip] = []
if len(_rate_limit_store[ip]) >= RATE_LIMIT_MAX:
from fastapi.responses import JSONResponse
await JSONResponse(
{"error": "rate limit exceeded", "retry_after": RATE_LIMIT_WINDOW},
status_code=429
)(scope, receive, send)
return
_rate_limit_store[ip].append(now)
await self.app(scope, receive, send)
app.add_middleware(_RateLimitMiddleware)
# ββ Structured logging ββ
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("ineed-now")
# ββ Graceful shutdown ββ
@app.on_event("shutdown")
def shutdown_event():
"""Clean up database pool and cache on shutdown."""
log.info("Shutting down β closing database and cache connections")
db_close_all()
close_cache()
log.info("Shutdown complete")
# ββ Serve React SPA from dist/ ββ
# Gradio's App.create_app() creates a brand new App() instance, discarding
# demo.app and all routes we added. Fix: pass demo.app to create_app() so
# Gradio reuses it (with our API routes), then inject SPA middleware.
_MIME = {
".js": "application/javascript", ".css": "text/css",
".svg": "image/svg+xml", ".ico": "image/x-icon",
".webmanifest": "application/manifest+json", ".html": "text/html",
".json": "application/json", ".png": "image/png",
}
_API_PREFIXES = ("/api/", "/theme.css", "/static/", "/file=", "/data/", "/gradio_api/")
class _SPAMiddleware:
"""ASGI middleware that serves the React SPA from the dist/ directory."""
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send):
if scope["type"] == "http" and scope.get("method") in ("GET", "HEAD"):
path = scope.get("path", "/")
rel = path.lstrip("/")
if rel.startswith("data/uploads/"):
fp = Path(rel)
if fp.exists() and fp.is_file():
body = fp.read_bytes()
ct = _MIME.get(fp.suffix, "application/octet-stream")
await send({"type": "http.response.start", "status": 200, "headers": [
(b"content-type", ct.encode()), (b"content-length", str(len(body)).encode()),
]})
await send({"type": "http.response.body", "body": body})
return
fp = (dist / rel) if rel else (dist / "index.html")
if fp.exists() and fp.is_file():
body = fp.read_bytes()
ct = _MIME.get(fp.suffix, "application/octet-stream")
await send({"type": "http.response.start", "status": 200, "headers": [
(b"content-type", ct.encode()), (b"content-length", str(len(body)).encode()),
]})
await send({"type": "http.response.body", "body": body})
return
if not path.startswith(_API_PREFIXES):
index = dist / "index.html"
if index.exists() and index.is_file():
body = index.read_bytes()
await send({"type": "http.response.start", "status": 200, "headers": [
(b"content-type", b"text/html"), (b"content-length", str(len(body)).encode()),
]})
await send({"type": "http.response.body", "body": body})
return
await self.app(scope, receive, send)
try:
import gradio.routes as _gr_routes
import starlette.routing as _sr
_orig_create_app = _gr_routes.App.create_app
# Snapshot all API routes registered on demo.app BEFORE Gradio rebuilds
_api_routes_snapshot = [
r for r in list(demo.app.routes)
if isinstance(r, (_sr.Route,)) and getattr(r, "path", "").startswith("/api/")
]
@staticmethod
def _patched_create_app(blocks, *a, **kw):
_app = _orig_create_app(blocks, *a, **kw)
# Re-inject API routes that Gradio's create_app discarded
existing_paths = {getattr(r, "path", "") for r in _app.routes}
for route in _api_routes_snapshot:
if getattr(route, "path", "") not in existing_paths:
_app.routes.append(route)
_app.add_middleware(_SPAMiddleware)
return _app
_gr_routes.App.create_app = _patched_create_app
except Exception:
pass
if __name__ == "__main__":
demo.queue()
_port = int(os.environ.get("PORT", 7860))
demo.launch(server_name="0.0.0.0", server_port=_port, prevent_thread_lock=True, ssr_mode=False)
demo.block_thread()
import json, os, uuid, sqlite3, time, base64, re, io, asyncio, hashlib, hmac
import logging
from pathlib import Path
from datetime import datetime, timezone, timedelta
from typing import Any
import gradio as gr
try:
import spaces
except ImportError:
spaces = None
from starlette.middleware import Middleware
from starlette.types import ASGIApp, Scope, Receive, Send
from fastapi import FastAPI, HTTPException, Request, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import Response
import bcrypt
import requests
from jose import jwt
from pydantic import BaseModel, Field, validator
from database import (
get_db as _db_get, close_db as _db_close, fetch_one, fetch_all,
execute as db_execute, commit as db_commit, rollback as db_rollback,
init_db as _db_init, IS_POSTGRES, close_all as db_close_all,
)
from cache import cache_get, cache_set, cache_delete, cache_clear, close_cache
log = logging.getLogger("ineed-now")
# ββ Config ββ
_data_dir = Path("/data")
if not _data_dir.exists():
_data_dir = Path(__file__).parent / "data"
_data_dir.mkdir(exist_ok=True)
DB_PATH = str(_data_dir / "app.db")
JWT_SECRET = os.environ.get("JWT_SECRET", "super-secret-key-change-in-production")
JWT_ALGORITHM = "HS256"
IMAGEKIT_PRIVATE_KEY = os.environ.get("IMAGEKIT_PRIVATE_KEY", "")
IMAGEKIT_URL_ENDPOINT = os.environ.get("IMAGEKIT_URL_ENDPOINT", "https://ik.imagekit.io/ceo2gbv21")
JWT_EXPIRE_HOURS = 24 # 24 hours (was 10 years β reduced for security)
JWT_REFRESH_EXPIRE_HOURS = 7 * 24 # Refresh token lasts 7 days
dist = Path(__file__).parent / "dist"
# ββ Database (delegated to database.py) ββ
def get_db():
"""Legacy wrapper β returns a connection via the abstraction layer."""
return _db_get()
def _close(conn):
"""Legacy wrapper β closes/returns connection to pool."""
_db_close(conn)
def _to_dict(row) -> dict:
"""Convert a row (sqlite3.Row or DictRow) to a plain dict."""
if row is None:
return {}
if hasattr(row, 'dict'):
return row.dict()
return dict(row)
def _setting(key: str, default: str = "") -> str:
"""Read a single system_settings value with Redis cache."""
cache_key = f"setting:{key}"
cached = cache_get(cache_key)
if cached is not None:
return cached
conn = get_db()
try:
if IS_POSTGRES:
row = fetch_one(conn, "SELECT setting_value FROM system_settings WHERE setting_key=%s", (key,))
else:
row = fetch_one(conn, "SELECT setting_value FROM system_settings WHERE setting_key=?", (key,))
val = _to_dict(row).get("setting_value", default) if row else default
finally:
_close(conn)
cache_set(cache_key, val, ttl=600)
return val
def _invalidate_settings_cache():
"""Clear all cached settings."""
cache_clear("setting:*")
def init_db():
"""Initialize database schema and seed data."""
_db_init()
# SQLite-specific seeds (PostgreSQL uses schema.sql)
if not IS_POSTGRES:
_seed_sqlite()
def _seed_sqlite():
"""Seed default data for SQLite (PostgreSQL uses schema.sql)."""
conn = get_db()
try:
count = conn.execute("SELECT COUNT(*) FROM system_settings").fetchone()[0]
if count == 0:
conn.executemany(
"INSERT OR IGNORE INTO system_settings (setting_key, setting_value, description) VALUES (?,?,?)",
[("store_name", "My Store", "Store display name"),