Spaces:
Paused

File size: 26,354 Bytes
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d753528
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
 
6867d8a
2a99443
 
 
6867d8a
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d753528
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
6867d8a
2a99443
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
 
6867d8a
2a99443
 
 
 
 
 
 
 
6867d8a
 
2a99443
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
2a99443
 
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
2a99443
 
 
 
 
 
6867d8a
 
 
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
6867d8a
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
 
 
 
 
 
 
2a99443
6867d8a
 
 
2a99443
 
 
 
 
6867d8a
 
 
 
 
 
 
 
2a99443
6867d8a
 
 
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
6867d8a
 
 
 
 
 
 
 
2a99443
6867d8a
 
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
 
 
 
2a99443
 
 
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
6867d8a
 
 
 
2a99443
 
 
 
 
6867d8a
 
 
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
6867d8a
579285c
 
6867d8a
579285c
6867d8a
 
 
 
 
 
 
 
579285c
6867d8a
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
6867d8a
2a99443
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
"""
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)