Spaces:
Paused

yaz / src /api /cases /sheet_api.py
anaselamr's picture
[PLATFORM] fix(endpoints+templates): Sprint 52 — zero-error operational pass
579285c
Raw History Blame Contribute Delete
26.4 kB
"""
Case Sheet API — Domain-agnostic case indexing & transfer tracking
==================================================================
Spreadsheet-style registry for cases by status.
Works with any tool (surgio, clinica, labo, …) via `tool_slug`.
Routes:
GET /apps/transfert/data → HTMX <tr> rows (filtered)
GET /apps/transfert/stats → JSON counts by status
POST /apps/transfert/entries → create → returns <tr>
PATCH /apps/transfert/entries/{id} → update → returns <tr>
DELETE /apps/transfert/entries/{id} → soft-delete → returns ""
GET /apps/transfert/export.csv → CSV download
POST /apps/transfert/share → generate/get share token
GET /cases/sheet/public/{token} → public view (read/edit)
DB Table: case_sheet_entries (auto-created on first import)
Standards: HIPAA — no PHI in logs | Multi-tenant | <50ms p95
i18n: client-side FR / AR / EN / ES (see template)
"""
from __future__ import annotations
import csv
import html as htmllib
import io
import json
import secrets
from datetime import datetime, timezone
from typing import Optional
from uuid import uuid4
import jwt as pyjwt
from fastapi import APIRouter, Form, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, Response
from core.helpers import JWT_ALGO, JWT_SECRET, get_sqlite as _db
try:
from core.services.display_id_service import mask_mrn, pseudonymize_name
except ImportError:
def pseudonymize_name(n: str) -> str:
if not n or len(n) < 2:
return n or "—"
return n[0] + "." + (n.split()[-1][0] + "." if " " in n else "")
def mask_mrn(m: str) -> str:
return f"••••{m[-2:]}" if m and len(m) >= 2 else "——"
router = APIRouter(tags=["Case Sheet"])
# ── Status definitions ────────────────────────────────────────────────────────
STATUS_META: dict = {
"scheduled": {
"label_fr": "Programmé",
"label_en": "Scheduled",
"color": "#5c6bc0",
"bg": "#eef0fb",
},
"urgent": {"label_fr": "Urgent", "label_en": "Urgent", "color": "#c2883b", "bg": "#fef3c7"},
"transfer": {
"label_fr": "Transféré",
"label_en": "Transferred",
"color": "#c74b4b",
"bg": "#fee2e2",
},
"completed": {
"label_fr": "Terminé",
"label_en": "Completed",
"color": "#56a066",
"bg": "#d1fae5",
},
"cancelled": {
"label_fr": "Annulé",
"label_en": "Cancelled",
"color": "#6b7280",
"bg": "#f3f4f6",
},
}
COLUMNS = [
"id",
"tenant_id",
"tool_slug",
"case_ref",
"patient_name",
"cin",
"age",
"gender",
"diagnosis",
"indication",
"management",
"transfer_reason",
"destination",
"status",
"notes",
"created_by",
"created_at",
"updated_at",
"deleted_at",
"share_token",
"is_public",
"allow_edit",
]
# ── DB helpers ────────────────────────────────────────────────────────────────
def _ensure_tables() -> None:
with _db() as c:
c.execute(
"""
CREATE TABLE IF NOT EXISTS case_sheet_entries (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
tool_slug TEXT NOT NULL DEFAULT 'transfert',
case_ref TEXT DEFAULT '',
patient_name TEXT DEFAULT '',
cin TEXT DEFAULT '',
age TEXT DEFAULT '',
gender TEXT DEFAULT 'M',
diagnosis TEXT DEFAULT '',
indication TEXT DEFAULT '',
management TEXT DEFAULT '',
transfer_reason TEXT DEFAULT '',
destination TEXT DEFAULT '',
status TEXT DEFAULT 'scheduled',
notes TEXT DEFAULT '',
created_by TEXT DEFAULT '',
created_at TEXT DEFAULT '',
updated_at TEXT DEFAULT '',
deleted_at TEXT DEFAULT NULL,
share_token TEXT DEFAULT NULL,
is_public INTEGER DEFAULT 0,
allow_edit INTEGER DEFAULT 0
)
"""
)
c.execute(
"CREATE INDEX IF NOT EXISTS idx_cse_tenant "
"ON case_sheet_entries(tenant_id, tool_slug, deleted_at)"
)
c.execute(
"CREATE INDEX IF NOT EXISTS idx_cse_status "
"ON case_sheet_entries(tenant_id, status, deleted_at)"
)
c.execute(
"CREATE INDEX IF NOT EXISTS idx_cse_token "
"ON case_sheet_entries(share_token) "
"WHERE share_token IS NOT NULL"
)
_ensure_tables()
def _auth(request: Request) -> Optional[dict]:
raw = request.cookies.get("access_token", "").replace("Bearer ", "")
if not raw:
raw = request.headers.get("Authorization", "").replace("Bearer ", "")
if not raw:
return None
try:
return pyjwt.decode(raw, JWT_SECRET, algorithms=[JWT_ALGO])
except Exception:
return None
def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
def _row_html(row: dict, editable: bool = True) -> str:
"""Render a single <tr> for the sheet table."""
s = row.get("status", "scheduled")
sm = STATUS_META.get(s, STATUS_META["scheduled"])
rid = row.get("id", "")
gender = row.get("gender", "M")
gender_icon = "♂" if gender == "M" else "♀" if gender == "F" else "—"
gender_color = "#5b8fc7" if gender == "M" else "#c77b8f"
# Encode row data for client-side edit drawer
data_json = htmllib.escape(
json.dumps(
{
"id": rid,
"case_ref": row.get("case_ref", ""),
"patient_name": row.get("patient_name", ""),
"cin": row.get("cin", ""),
"age": row.get("age", ""),
"gender": gender,
"diagnosis": row.get("diagnosis", ""),
"indication": row.get("indication", ""),
"management": row.get("management", ""),
"transfer_reason": row.get("transfer_reason", ""),
"destination": row.get("destination", ""),
"status": s,
"notes": row.get("notes", ""),
}
),
quote=True,
)
actions = ""
if editable:
actions = (
f"<button onclick=\"sheetEditOpen('{rid}')\" "
f'style="background:none;border:none;cursor:pointer;padding:4px 6px;'
f'color:var(--text-muted);border-radius:4px;" '
f'title="Modifier">'
f'<i data-lucide="pencil" style="width:13px;height:13px;"></i></button>'
f"<button onclick=\"sheetDelete('{rid}')\" "
f'style="background:none;border:none;cursor:pointer;padding:4px 6px;'
f'color:#c74b4b;border-radius:4px;" '
f'title="Supprimer">'
f'<i data-lucide="trash-2" style="width:13px;height:13px;"></i></button>'
)
# Status quick-change select (fires PATCH via JS)
status_opts = "".join(
f'<option value="{k}" {"selected" if k == s else ""}>{v["label_fr"]}</option>'
for k, v in STATUS_META.items()
)
status_sel = (
f"<select onchange=\"sheetQuickStatus('{rid}',this.value)\" "
f'style="font-size:11px;font-weight:700;padding:2px 6px;border-radius:9999px;'
f'background:{sm["bg"]};color:{sm["color"]};border:1px solid {sm["color"]}44;cursor:pointer;">'
f"{status_opts}</select>"
)
td = 'style="padding:7px 10px;font-size:12px;vertical-align:middle;white-space:nowrap;'
td_w = 'style="padding:7px 10px;font-size:12px;vertical-align:middle;' # wrappable
return (
f'<tr id="row-{rid}" data-row="{data_json}" data-status="{s}" '
f'style="border-bottom:1px solid var(--border);transition:opacity 0.25s,background 0.2s;"'
f" onmouseenter=\"this.style.background='var(--bg)'\" "
f"onmouseleave=\"this.style.background=''\">"
f'<td {td}color:var(--text-muted);font-family:Courier New,monospace;font-size:11px;">'
f'{row.get("case_ref", "")}</td>'
f'<td {td}font-weight:600;color:var(--text);">'
f'{pseudonymize_name(row.get("patient_name", "")) or "—"}</td>'
f'<td {td}font-family:Courier New,monospace;color:var(--text-muted);">'
f'{row.get("cin", "")}</td>'
f'<td {td}text-align:center;color:var(--text-muted);">{row.get("age", "")}</td>'
f'<td {td}text-align:center;color:{gender_color};font-size:14px;">{gender_icon}</td>'
f'<td {td_w}max-width:160px;color:var(--text);">'
f'{row.get("diagnosis", "")}</td>'
f'<td {td_w}max-width:140px;color:var(--text-muted);">'
f'{row.get("indication", "")}</td>'
f'<td {td_w}max-width:150px;color:var(--text);">'
f'{row.get("management", "")}</td>'
f'<td {td_w}max-width:160px;color:var(--text-muted);">'
f'{row.get("transfer_reason", "")}</td>'
f'<td {td}color:var(--text-muted);">{row.get("destination", "")}</td>'
f'<td style="padding:7px 10px;vertical-align:middle;">{status_sel}</td>'
f'<td {td}color:var(--text-muted);">{row.get("created_at", "")[:10]}</td>'
f'<td style="padding:7px 6px;vertical-align:middle;white-space:nowrap;">'
f"{actions}</td>"
f"</tr>"
)
# ── Routes ────────────────────────────────────────────────────────────────────
@router.get("/apps/transfert/data", response_class=HTMLResponse)
async def sheet_data(
request: Request,
status: str = Query(""),
search: str = Query(""),
tool: str = Query("transfert"),
):
"""HTMX: return <tr> rows matching filters."""
user = _auth(request)
if not user:
return HTMLResponse(
'<tr><td colspan="13" style="padding:20px;text-align:center;'
'color:var(--text-muted);">Connexion requise</td></tr>'
)
tenant_id = user.get("tenant_id", "default")
q = (
"SELECT * FROM case_sheet_entries "
"WHERE tenant_id=? AND tool_slug=? AND deleted_at IS NULL"
)
params: list = [tenant_id, tool]
if status:
q += " AND status=?"
params.append(status)
if search:
q += (
" AND (patient_name LIKE ? OR cin LIKE ? "
"OR diagnosis LIKE ? OR case_ref LIKE ? OR destination LIKE ?)"
)
s = f"%{search}%"
params += [s, s, s, s, s]
q += " ORDER BY created_at DESC LIMIT 200"
try:
with _db() as c:
rows = [dict(r) for r in c.execute(q, params).fetchall()]
except Exception:
rows = []
if not rows:
return HTMLResponse(
'<tr><td colspan="13" style="padding:48px;text-align:center;'
'color:var(--text-muted);">'
'<div style="font-size:36px;margin-bottom:10px;">📋</div>'
'<div style="font-size:14px;font-weight:600;color:var(--text);">'
"Aucun cas enregistré</div>"
'<div style="font-size:12px;margin-top:4px;">'
"Cliquez sur <strong>+ Nouveau Cas</strong> pour commencer.</div>"
"</td></tr>"
)
return HTMLResponse("\n".join(_row_html(r) for r in rows))
@router.get("/apps/transfert/stats")
async def sheet_stats(request: Request, tool: str = Query("transfert")):
"""JSON counts by status for the badge row."""
user = _auth(request)
if not user:
return JSONResponse({"total": 0})
tenant_id = user.get("tenant_id", "default")
try:
with _db() as c:
rows = c.execute(
"SELECT status, COUNT(*) as n FROM case_sheet_entries "
"WHERE tenant_id=? AND tool_slug=? AND deleted_at IS NULL "
"GROUP BY status",
(tenant_id, tool),
).fetchall()
counts = {r["status"]: r["n"] for r in rows}
total = sum(counts.values())
return JSONResponse(
{
"total": total,
"scheduled": counts.get("scheduled", 0),
"urgent": counts.get("urgent", 0),
"transfer": counts.get("transfer", 0),
"completed": counts.get("completed", 0),
"cancelled": counts.get("cancelled", 0),
}
)
except Exception:
return JSONResponse(
{"total": 0, "scheduled": 0, "urgent": 0, "transfer": 0, "completed": 0, "cancelled": 0}
)
@router.post("/apps/transfert/entries", response_class=HTMLResponse)
async def create_entry(
request: Request,
case_ref: str = Form(""),
patient_name: str = Form(""),
cin: str = Form(""),
age: str = Form(""),
gender: str = Form("M"),
diagnosis: str = Form(""),
indication: str = Form(""),
management: str = Form(""),
transfer_reason: str = Form(""),
destination: str = Form(""),
status: str = Form("scheduled"),
notes: str = Form(""),
tool_slug: str = Form("transfert"),
):
user = _auth(request)
if not user:
return HTMLResponse("", status_code=401)
tenant_id = user.get("tenant_id", "default")
uid = user.get("sub", "")
now = _now()
eid = str(uuid4())
try:
with _db() as c:
c.execute(
"INSERT INTO case_sheet_entries "
"(id,tenant_id,tool_slug,case_ref,patient_name,cin,age,gender,"
"diagnosis,indication,management,transfer_reason,destination,"
"status,notes,created_by,created_at,updated_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
eid,
tenant_id,
tool_slug,
case_ref,
patient_name,
cin,
age,
gender,
diagnosis,
indication,
management,
transfer_reason,
destination,
status,
notes,
uid,
now,
now,
),
)
row = {
"id": eid,
"tenant_id": tenant_id,
"tool_slug": tool_slug,
"case_ref": case_ref,
"patient_name": patient_name,
"cin": cin,
"age": age,
"gender": gender,
"diagnosis": diagnosis,
"indication": indication,
"management": management,
"transfer_reason": transfer_reason,
"destination": destination,
"status": status,
"notes": notes,
"created_at": now,
}
return HTMLResponse(_row_html(row))
except Exception as exc:
return HTMLResponse(
f'<tr><td colspan="13" style="color:#c74b4b;padding:10px;">'
f"Erreur: {htmllib.escape(str(exc))}</td></tr>"
)
@router.patch("/apps/transfert/entries/{entry_id}", response_class=HTMLResponse)
async def update_entry(
request: Request,
entry_id: str,
case_ref: str = Form(""),
patient_name: str = Form(""),
cin: str = Form(""),
age: str = Form(""),
gender: str = Form("M"),
diagnosis: str = Form(""),
indication: str = Form(""),
management: str = Form(""),
transfer_reason: str = Form(""),
destination: str = Form(""),
status: str = Form("scheduled"),
notes: str = Form(""),
):
user = _auth(request)
if not user:
return HTMLResponse("", status_code=401)
tenant_id = user.get("tenant_id", "default")
now = _now()
try:
with _db() as c:
c.execute(
"UPDATE case_sheet_entries SET "
"case_ref=?,patient_name=?,cin=?,age=?,gender=?,"
"diagnosis=?,indication=?,management=?,transfer_reason=?,"
"destination=?,status=?,notes=?,updated_at=? "
"WHERE id=? AND tenant_id=?",
(
case_ref,
patient_name,
cin,
age,
gender,
diagnosis,
indication,
management,
transfer_reason,
destination,
status,
notes,
now,
entry_id,
tenant_id,
),
)
row = {
"id": entry_id,
"case_ref": case_ref,
"patient_name": patient_name,
"cin": cin,
"age": age,
"gender": gender,
"diagnosis": diagnosis,
"indication": indication,
"management": management,
"transfer_reason": transfer_reason,
"destination": destination,
"status": status,
"notes": notes,
"created_at": now,
}
return HTMLResponse(_row_html(row))
except Exception as exc:
return HTMLResponse(
f'<tr><td colspan="13" style="color:#c74b4b;padding:10px;">'
f"Erreur: {htmllib.escape(str(exc))}</td></tr>"
)
@router.delete("/apps/transfert/entries/{entry_id}", response_class=HTMLResponse)
async def delete_entry(request: Request, entry_id: str):
user = _auth(request)
if not user:
return HTMLResponse("", status_code=401)
tenant_id = user.get("tenant_id", "default")
now = _now()
try:
with _db() as c:
c.execute(
"UPDATE case_sheet_entries SET deleted_at=? " "WHERE id=? AND tenant_id=?",
(now, entry_id, tenant_id),
)
except Exception:
pass
return HTMLResponse("") # HTMX swaps row with nothing → disappears
@router.get("/apps/transfert/export.csv")
async def export_csv(
request: Request,
status: str = Query(""),
tool: str = Query("transfert"),
):
user = _auth(request)
if not user:
return Response("Unauthorized", status_code=401)
tenant_id = user.get("tenant_id", "default")
q = (
"SELECT * FROM case_sheet_entries "
"WHERE tenant_id=? AND tool_slug=? AND deleted_at IS NULL"
)
params: list = [tenant_id, tool]
if status:
q += " AND status=?"
params.append(status)
q += " ORDER BY created_at DESC"
try:
with _db() as c:
rows = [dict(r) for r in c.execute(q, params).fetchall()]
except Exception:
rows = []
output = io.StringIO()
fields = [
"case_ref",
"patient_name",
"cin",
"age",
"gender",
"diagnosis",
"indication",
"management",
"transfer_reason",
"destination",
"status",
"notes",
"created_at",
]
writer = csv.DictWriter(output, fieldnames=fields, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
fname = f"cases_{tool}_{datetime.now().strftime('%Y%m%d')}.csv"
return Response(
content=output.getvalue(),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{fname}"'},
)
@router.post("/apps/transfert/share")
async def create_share(request: Request):
user = _auth(request)
if not user:
return JSONResponse({"error": "not authenticated"}, status_code=401)
tenant_id = user.get("tenant_id", "default")
try:
body = await request.json()
except Exception:
body = {}
tool_slug = body.get("tool_slug", "transfert")
allow_edit = 1 if body.get("allow_edit") else 0
is_public = 1
token = secrets.token_urlsafe(24)
try:
with _db() as c:
c.execute(
"UPDATE case_sheet_entries "
"SET share_token=?, is_public=?, allow_edit=? "
"WHERE tenant_id=? AND tool_slug=? AND deleted_at IS NULL",
(token, is_public, allow_edit, tenant_id, tool_slug),
)
base = str(request.base_url).rstrip("/")
return JSONResponse(
{
"token": token,
"url": f"{base}/cases/sheet/public/{token}",
"allow_edit": bool(allow_edit),
}
)
except Exception as exc:
return JSONResponse({"error": str(exc)}, status_code=500)
# ── Public shared view ────────────────────────────────────────────────────────
@router.get("/cases/sheet/public/{token}", response_class=HTMLResponse)
async def public_sheet(
request: Request,
token: str,
status: str = Query(""),
search: str = Query(""),
lang: str = Query("fr"),
):
try:
with _db() as c:
q = (
"SELECT * FROM case_sheet_entries "
"WHERE share_token=? AND is_public=1 AND deleted_at IS NULL"
)
params: list = [token]
if status:
q += " AND status=?"
params.append(status)
if search:
q += (
" AND (patient_name LIKE ? OR cin LIKE ? "
"OR diagnosis LIKE ? OR case_ref LIKE ?)"
)
s = f"%{search}%"
params += [s, s, s, s]
q += " ORDER BY created_at DESC"
rows = [dict(r) for r in c.execute(q, params).fetchall()]
if not rows:
check = c.execute(
"SELECT allow_edit FROM case_sheet_entries "
"WHERE share_token=? AND is_public=1 LIMIT 1",
(token,),
).fetchone()
if not check:
return HTMLResponse(
"<html><body style='font-family:system-ui;padding:40px;'>"
"<h2>🔒 Lien invalide ou expiré</h2></body></html>",
status_code=404,
)
allow_edit = check["allow_edit"] if check else 0
else:
allow_edit = rows[0].get("allow_edit", 0)
tool_slug = rows[0].get("tool_slug", "transfert") if rows else "transfert"
except Exception:
rows = []
allow_edit = 0
tool_slug = "transfert"
# Try Jinja2 template first, fallback to bare HTML
try:
from core.templates import get_templates
tpl = get_templates(request)
return tpl.TemplateResponse(
request,
"cases/sheet_public.html",
{
"rows": rows,
"token": token,
"status_filter": status,
"search": search,
"allow_edit": allow_edit,
"tool_slug": tool_slug,
"STATUS_META": STATUS_META,
"lang": lang
},
)
except Exception:
pass # fallback below
# ── Bare-HTML fallback (always works) ──
SM = STATUS_META
header = (
"<!DOCTYPE html><html><head><meta charset='UTF-8'>"
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
"<title>Registre Partagé</title>"
"<style>*{box-sizing:border-box}body{font-family:system-ui,sans-serif;"
"margin:0;padding:20px;background:#f8f9fa;color:#1f2937}"
"h2{margin-bottom:4px}p{color:#6b7280;margin-top:0}.wrap{overflow-x:auto}"
"table{border-collapse:collapse;width:100%;min-width:900px;background:#fff;"
"border-radius:8px;box-shadow:0 1px 4px #0001}"
"th{padding:10px 12px;background:#f3f4f6;font-size:12px;text-align:left;"
"font-weight:700;color:#374151;border-bottom:2px solid #e5e7eb}"
"td{padding:8px 12px;font-size:12px;border-bottom:1px solid #f3f4f6}"
".badge{display:inline-block;padding:2px 10px;border-radius:9999px;"
"font-size:11px;font-weight:700}"
"</style></head><body>"
"<h2>📋 Registre des Cas</h2>"
f"<p>{len(rows)} cas — partagé publiquement</p>"
"<div class='wrap'><table>"
"<thead><tr><th>Réf.</th><th>Patient</th><th>CIN</th><th>Âge</th>"
"<th>Sexe</th><th>Diagnostic</th><th>Indication</th><th>C.A.T</th>"
"<th>Raison</th><th>Destination</th><th>Statut</th><th>Date</th>"
"</tr></thead><tbody>"
)
body_rows = ""
for r in rows:
sm = SM.get(r.get("status", "scheduled"), SM["scheduled"])
body_rows += (
f"<tr>"
f'<td><code>{htmllib.escape(r.get("case_ref",""))}</code></td>'
f'<td><strong>{htmllib.escape(r.get("patient_name",""))}</strong></td>'
f'<td><code>{htmllib.escape(r.get("cin",""))}</code></td>'
f'<td>{htmllib.escape(r.get("age",""))}</td>'
f'<td>{"♂" if r.get("gender")=="M" else "♀"}</td>'
f'<td>{htmllib.escape(r.get("diagnosis",""))}</td>'
f'<td>{htmllib.escape(r.get("indication",""))}</td>'
f'<td>{htmllib.escape(r.get("management",""))}</td>'
f'<td>{htmllib.escape(r.get("transfer_reason",""))}</td>'
f'<td>{htmllib.escape(r.get("destination",""))}</td>'
f'<td><span class="badge" style="background:{sm["bg"]};color:{sm["color"]};">'
f'{sm["label_fr"]}</span></td>'
f'<td>{r.get("created_at","")[:10]}</td>'
f"</tr>"
)
footer = "</tbody></table></div></body></html>"
return HTMLResponse(header + body_rows + footer)