""" 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( '
'
f'{code}')
elif btype == "video":
url = c.get("url", "")
title = c.get("title", "Video")
if not url:
return '{text}' f'{"" if author else ""}' f'') elif btype == "divider": label = c.get("label", "") if label: return (f'