""" Case Content Blocks API ======================= Universal, domain-agnostic rich content blocks that attach to any case. Each block can hold any data type: text · heading · image · gallery · table · code · video · audio file · embed · metric · checklist · chart · quote · divider message · link_card · timeline · kanban Prefix : /api/v1/cases/blocks Auth : JWT cookie OR Bearer header (required) Perf : SQLite, indexed on (tenant_id, case_id, position) """ from __future__ import annotations import json from datetime import datetime, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 import jwt as pyjwt from fastapi import APIRouter, HTTPException, Query, Request from fastapi.responses import HTMLResponse, JSONResponse from pydantic import BaseModel, Field from core.helpers import JWT_ALGO, JWT_SECRET, get_sqlite as _db router = APIRouter(prefix="/api/v1/cases/blocks", tags=["Case Content Blocks"]) # ── Icons for each block type ───────────────────────────────────────────────── BLOCK_META: Dict[str, Dict[str, str]] = { "text": {"icon": "📝", "label": "Text"}, "heading": {"icon": "🔤", "label": "Heading"}, "image": {"icon": "🖼", "label": "Image"}, "gallery": {"icon": "🗂", "label": "Gallery"}, "table": {"icon": "⊞", "label": "Table"}, "code": {"icon": "💻", "label": "Code"}, "video": {"icon": "🎬", "label": "Video"}, "audio": {"icon": "🎵", "label": "Audio"}, "file": {"icon": "📎", "label": "File"}, "embed": {"icon": "🔗", "label": "Embed"}, "metric": {"icon": "📊", "label": "Metric"}, "checklist": {"icon": "☑️", "label": "Checklist"}, "chart": {"icon": "📈", "label": "Chart"}, "quote": {"icon": "❝", "label": "Quote"}, "divider": {"icon": "—", "label": "Divider"}, "message": {"icon": "💬", "label": "Message"}, "link_card": {"icon": "🔗", "label": "Link Card"}, "timeline": {"icon": "📅", "label": "Timeline"}, "kanban": {"icon": "🗃", "label": "Kanban"}, "short": {"icon": "🎥", "label": "Short Video"}, } # ── DB helpers ──────────────────────────────────────────────────────────────── def _ensure_tables() -> None: with _db() as c: c.execute(""" CREATE TABLE IF NOT EXISTS case_content_blocks ( id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL, case_id TEXT NOT NULL, case_domain TEXT DEFAULT '', user_id TEXT NOT NULL, block_type TEXT DEFAULT 'text', title TEXT, content TEXT DEFAULT '{}', position INTEGER DEFAULT 0, is_pinned INTEGER DEFAULT 0, is_visible INTEGER DEFAULT 1, tags TEXT, created_at TEXT, updated_at TEXT, deleted_at TEXT ) """) c.execute(""" CREATE TABLE IF NOT EXISTS case_interests ( id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL, user_id TEXT NOT NULL, case_id TEXT NOT NULL, case_domain TEXT DEFAULT '', interest_type TEXT DEFAULT 'starred', created_at TEXT ) """) c.execute("CREATE INDEX IF NOT EXISTS idx_ccb_case ON case_content_blocks(tenant_id, case_id)") c.execute("CREATE INDEX IF NOT EXISTS idx_ccb_pos ON case_content_blocks(case_id, position)") c.execute("CREATE INDEX IF NOT EXISTS idx_ci_user ON case_interests(tenant_id, user_id)") c.commit() try: _ensure_tables() except Exception: pass def _auth(request: Request) -> dict: raw = "" h = request.headers.get("Authorization", "") if h.startswith("Bearer "): raw = h[7:] else: raw = request.cookies.get("access_token", "").replace("Bearer ", "") if not raw: raise HTTPException(status_code=401, detail="Not authenticated") try: return pyjwt.decode(raw, JWT_SECRET, algorithms=[JWT_ALGO]) except Exception: raise HTTPException(status_code=401, detail="Session expired") def _row(r) -> dict: d = dict(r) try: d["content"] = json.loads(d.get("content") or "{}") except Exception: d["content"] = {} d["is_pinned"] = bool(d.get("is_pinned", 0)) d["is_visible"] = bool(d.get("is_visible", 1)) return d # ── Pydantic schemas ────────────────────────────────────────────────────────── class BlockCreate(BaseModel): case_id: str case_domain: str = "" block_type: str = "text" title: Optional[str] = None content: Dict[str, Any] = Field(default_factory=dict) position: Optional[int] = None tags: Optional[str] = None class BlockUpdate(BaseModel): title: Optional[str] = None content: Optional[Dict[str, Any]] = None position: Optional[int] = None is_pinned: Optional[bool] = None is_visible: Optional[bool] = None tags: Optional[str] = None class InterestToggle(BaseModel): case_id: str case_domain: str = "" interest_type: str = "starred" # starred | watching | assigned # ── Endpoints ───────────────────────────────────────────────────────────────── @router.get("/{case_id}") async def list_blocks( case_id: str, request: Request, domain: Optional[str] = Query(None), ): """ List content blocks for a case. Returns HTML fragment for HTMX requests, JSON list for API clients. """ _auth(request) with _db() as c: rows = c.execute( "SELECT * FROM case_content_blocks " "WHERE case_id=? AND deleted_at IS NULL AND is_visible=1 " "ORDER BY position ASC, created_at ASC", (case_id,), ).fetchall() blocks = [_row(r) for r in rows] if request.headers.get("hx-request") or "text/html" in request.headers.get("accept", ""): return _render_blocks_html(blocks, case_id) return blocks @router.post("", status_code=201) async def create_block(body: BlockCreate, request: Request): """Add a new content block to a case.""" user = _auth(request) if body.position is None: with _db() as c: r = c.execute( "SELECT COALESCE(MAX(position),0) AS mp FROM case_content_blocks " "WHERE case_id=? AND deleted_at IS NULL", (body.case_id,), ).fetchone() position = (r["mp"] or 0) + 10 else: position = body.position bid = str(uuid4()) now = datetime.now(timezone.utc).isoformat() tid = user.get("tenant_id") or "default" uid = user.get("sub", "") with _db() as c: c.execute( "INSERT INTO case_content_blocks " "(id,tenant_id,case_id,case_domain,user_id,block_type,title,content," "position,is_pinned,is_visible,tags,created_at,updated_at) " "VALUES (?,?,?,?,?,?,?,?,?,0,1,?,?,?)", (bid, tid, body.case_id, body.case_domain, uid, body.block_type, body.title, json.dumps(body.content), position, body.tags, now, now), ) c.commit() return {"id": bid, "position": position, "block_type": body.block_type} @router.patch("/{block_id}") async def update_block(block_id: str, body: BlockUpdate, request: Request): """Update a content block's content, position, or visibility.""" _auth(request) updates, values = [], [] if body.title is not None: updates.append("title=?"); values.append(body.title) if body.content is not None: updates.append("content=?"); values.append(json.dumps(body.content)) if body.position is not None: updates.append("position=?"); values.append(body.position) # type: ignore[arg-type, assignment] if body.is_pinned is not None: updates.append("is_pinned=?"); values.append(int(body.is_pinned)) # type: ignore[arg-type, assignment] if body.is_visible is not None: updates.append("is_visible=?"); values.append(int(body.is_visible)) # type: ignore[arg-type, assignment] if body.tags is not None: updates.append("tags=?"); values.append(body.tags) if not updates: raise HTTPException(status_code=400, detail="Nothing to update") updates.append("updated_at=?"); values.append(datetime.now(timezone.utc).isoformat()) user = _auth(request) tid = user.get("tenant_id") or "default" values.extend([block_id, tid]) with _db() as c: c.execute(f"UPDATE case_content_blocks SET {', '.join(updates)} WHERE id=? AND tenant_id=?", values) c.commit() return {"id": block_id, "updated": True} @router.delete("/{block_id}", status_code=204) async def delete_block(block_id: str, request: Request): """Soft-delete a content block.""" user = _auth(request) tid = user.get("tenant_id") or "default" with _db() as c: c.execute( "UPDATE case_content_blocks SET deleted_at=? WHERE id=? AND tenant_id=?", (datetime.now(timezone.utc).isoformat(), block_id, tid), ) c.commit() # ── Interest / Star API ─────────────────────────────────────────────────────── @router.post("/interests/toggle") async def toggle_interest(body: InterestToggle, request: Request): """Star / unstar a case for the current user.""" user = _auth(request) uid = user.get("sub", "") tid = user.get("tenant_id") or "default" with _db() as c: existing = c.execute( "SELECT id FROM case_interests WHERE user_id=? AND case_id=? AND interest_type=?", (uid, body.case_id, body.interest_type), ).fetchone() if existing: c.execute("DELETE FROM case_interests WHERE id=?", (existing["id"],)) c.commit() return {"action": "removed", "case_id": body.case_id} else: c.execute( "INSERT INTO case_interests (id,tenant_id,user_id,case_id,case_domain,interest_type,created_at) " "VALUES (?,?,?,?,?,?,?)", (str(uuid4()), tid, uid, body.case_id, body.case_domain, body.interest_type, datetime.now(timezone.utc).isoformat()), ) c.commit() return {"action": "added", "case_id": body.case_id} @router.get("/interests/mine") async def my_interests(request: Request): """List all cases the current user has starred.""" user = _auth(request) uid = user.get("sub", "") with _db() as c: rows = c.execute( "SELECT case_id, case_domain, interest_type, created_at " "FROM case_interests WHERE user_id=? ORDER BY created_at DESC", (uid,), ).fetchall() return [dict(r) for r in rows] # ── HTML Render Helpers ─────────────────────────────────────────────────────── def _render_blocks_html(blocks: list, case_id: str) -> HTMLResponse: if not blocks: return HTMLResponse( '
' '
✨
' '
' 'Blank canvas — start building
' '
Add text, images, tables, metrics and more ' 'using the toolbar above.
' '
' ) items = [] for b in blocks: btype = b.get("block_type", "text") meta = BLOCK_META.get(btype, {"icon": "📄", "label": btype.title()}) icon = meta["icon"] label = meta["label"] title = b.get("title") or "" content = b.get("content") or {} bid = b["id"] pin = "📌 " if b.get("is_pinned") else "" body_html = _render_body(btype, content, case_id) items.append( f'
' f'
' f'{icon}' f'{pin}{label.upper()}' f'{f"{title}" if title else ""}' f'
' f'' f'' f'
' f'
' f'
{body_html}
' f'
' ) return HTMLResponse("\n".join(items)) def _render_body(btype: str, c: dict, case_id: str = "") -> str: if btype == "text": body = c.get("body", "") return f'
{body}
' elif btype == "heading": lvl = min(max(int(c.get("level", 2)), 1), 4) txt = c.get("text", "") sizes = {1: "22px", 2: "18px", 3: "15px", 4: "13px"} fw = {1: "800", 2: "700", 3: "600", 4: "600"} return (f'
{txt}
') elif btype == "image": url = c.get("url", "") cap = c.get("caption", "") if not url: return '
No image URL set.
' cap_html = (f'
{cap}
') if cap else "" return f'{cap}{cap_html}' elif btype == "gallery": imgs = c.get("images", []) if not imgs: return '
No images in gallery.
' cols = '
' for img in imgs: u = img.get("url", "") cp = img.get("caption", "") cols += (f'
' f'{cp}' f'{"
"+cp+"
" if cp else ""}' f'
') return cols + "
" elif btype == "table": headers = c.get("headers", []) rows = c.get("rows", []) if not headers and not rows: return '
Empty table.
' ths = "".join( f'{h}' for h in headers ) trs = "".join( '' + "".join( f'{cell}' for cell in row ) + '' for row in rows ) return (f'
' f'' f'{ths}' f'{trs}
') elif btype == "metric": label = c.get("label", "Metric") value = c.get("value", "—") unit = c.get("unit", "") trend = c.get("trend", "") color = c.get("color", "var(--primary)") trend_icon = {"up": "↑", "down": "↓", "stable": "→"}.get(trend, "") trend_color = {"up": "#56a066", "down": "#c74b4b", "stable": "#c2883b"}.get(trend, "var(--text-muted)") return ( f'
' f'{value}' f'{unit}' f'{trend_icon}' f'
' f'
{label}
' ) elif btype == "code": lang = c.get("language", "") code = c.get("code", "") lang_badge = (f'{lang}') if lang else "" return (f'
{lang_badge}
' f'
'
                f'{code}
') elif btype == "video": url = c.get("url", "") title = c.get("title", "Video") if not url: return '
No video URL.
' if "youtube.com" in url or "youtu.be" in url: vid = url.split("v=")[-1].split("&")[0] if "v=" in url else url.split("/")[-1] return (f'
' f'
') return f'' elif btype == "short": url = c.get("url", "") title = c.get("title", "Short") if not url: return '
No video URL.
' return (f'
' f'' f'
{title}
' f'
') elif btype == "audio": url = c.get("url", "") title = c.get("title", "Audio") return (f'
' f'
🎵 {title}
' f'
') elif btype == "file": name = c.get("name", "File") url = c.get("url", "#") size = c.get("size", 0) size_str = f" · {size // 1024} KB" if size else "" mime = c.get("mime_type", "") ext = name.rsplit(".", 1)[-1].upper() if "." in name else "FILE" return (f'' f'{ext}' f'{name}' f'{size_str}' f'') elif btype == "embed": url = c.get("url", "") title = c.get("title", "Embedded content") return (f'
' f'
' f'🔗 {title}
' f'
') elif btype == "checklist": items_list = c.get("items", []) if not items_list: return '
Empty checklist.
' done = sum(1 for i in items_list if i.get("done")) pct = round(done / len(items_list) * 100) if items_list else 0 progress = (f'
' f'
' f'Progress{done}/{len(items_list)}
' f'
' f'
') lis = "".join( f'
' f'{"✅" if item.get("done") else "⬜"}' f'' f'{item.get("text", "")}
' for item in items_list ) return progress + lis elif btype == "chart": chart_type = c.get("type", "bar") labels = c.get("labels", []) datasets = c.get("datasets", []) if not labels: return '
No chart data.
' cid = f"chart-{uuid4().hex[:8]}" chart_data = json.dumps({"type": chart_type, "data": {"labels": labels, "datasets": datasets}, "options": {"responsive": True, "maintainAspectRatio": True}}) return (f'
' f'
' f'') elif btype == "quote": text = c.get("text", "") author = c.get("author", "") return (f'
{text}' f'{"" if author else ""}' f'
') elif btype == "divider": label = c.get("label", "") if label: return (f'
' f'
' f'{label}' f'
') return '
' elif btype == "message": text = c.get("text", "") author = c.get("author", "") ts = c.get("timestamp", "") return (f'
' f'
' f'
' f'{author[:1].upper() if author else "?"}
' f'{author}' f'{""+ts+"" if ts else ""}' f'
' f'
{text}
' f'
') elif btype == "link_card": url = c.get("url", "#") title = c.get("title", url) desc = c.get("description", "") img = c.get("image", "") img_html = (f'') if img else "" return (f'' f'{img_html}' f'
' f'
{title}
' f'{"
"+desc+"
" if desc else ""}' f'
{url[:60]}…
' f'
') elif btype == "timeline": events = c.get("events", []) if not events: return '
No timeline events.
' items = [] for ev in events: ts = ev.get("date", "") label = ev.get("label", "") desc = ev.get("description", "") done = ev.get("done", False) color = "#56a066" if done else "var(--border)" items.append( f'
' f'
' f'
' f'
' f'
' f'
{label}
' f'{"
"+ts+"
" if ts else ""}' f'{"
"+desc+"
" if desc else ""}' f'
' ) return "".join(items) else: raw = str(c)[:300] return f'
{raw}
'