File size: 30,610 Bytes
01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 0743ddc 01b6ea7 | 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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 | #!/usr/bin/env python3
"""
YAZ Platform — Collaboration Scaffold Generator
================================================
Scaffolds the full collaboration layer (models, service, routes, guide, doc)
for any YAZ engine.
Usage:
python scripts/generators/create_collaboration.py \\
--engine clinica \\
--domain clinical \\
--co-role co_clinician \\
--case-model PatientEncounter \\
--case-table clinica.encounters \\
--sprint 54
What it generates:
src/apps/{engine}/collaboration/__init__.py
src/apps/{engine}/collaboration/models.py
src/apps/{engine}/collaboration/service.py
src/apps/{engine}/collaboration/routes.py
src/ui/templates/apps/{engine}/collaborate_guide.html
docs/engines/{engine}/COLLABORATION.md
After running:
1. Review all generated files
2. alembic revision --autogenerate -m "{engine}_collaboration_tables_sprint{N}"
3. alembic upgrade head
4. Mount router in src/factory/_routes.py (see printed snippet)
5. Add route GET /collaborate to src/apps/{engine}/routes/{main}.py
Standards: HIPAA · Tenant-isolated · HTMX-compatible · Cookie-aware auth
"""
from __future__ import annotations
import argparse
import os
import sys
import textwrap
from pathlib import Path
# ── Paths ─────────────────────────────────────────────────────────────────
ROOT = Path(__file__).resolve().parents[2]
APPS = ROOT / "src" / "apps"
TEMPLATES = ROOT / "src" / "ui" / "templates" / "apps"
DOCS_ENGINES = ROOT / "docs" / "engines"
# ── Template rendering ─────────────────────────────────────────────────────
def render(template: str, **ctx: str) -> str:
"""Simple {KEY} substitution — no Jinja to avoid circular imports."""
result = template
for k, v in ctx.items():
result = result.replace("{" + k + "}", v)
# Unescape {{ → { and }} → } (like str.format() does)
result = result.replace("{{", "{").replace("}}", "}")
return result
# ── File templates ─────────────────────────────────────────────────────────
INIT_TEMPLATE = '''\
"""
{Engine} — Case Collaboration
==============================
Roles: owner, {co_role}, reviewer, observer
Annotation types: note, question, suggestion, comment, attachment
Domain: {domain}
Sprint: {sprint}
"""
from enum import Enum
class CollaborationRole(str, Enum):
OWNER = "owner"
{CO_ROLE_UPPER} = "{co_role}"
REVIEWER = "reviewer"
OBSERVER = "observer"
class CollaborationStatus(str, Enum):
ACTIVE = "active"
REVOKED = "revoked"
LEFT = "left"
class InvitationStatus(str, Enum):
PENDING = "pending"
ACCEPTED = "accepted"
DECLINED = "declined"
EXPIRED = "expired"
REVOKED = "revoked"
class AnnotationType(str, Enum):
COMMENT = "comment"
NOTE = "note"
SUGGESTION = "suggestion"
QUESTION = "question"
ATTACHMENT = "attachment"
'''
MODELS_TEMPLATE = '''\
"""
{Engine} — Case Collaboration Models
======================================
SQLModel tables for case-level collaboration, invitations, and annotations.
Schema : {engine}
Tables : {engine}_case_collaborators
{engine}_case_invitations
{engine}_case_annotations
HIPAA : No direct patient PHI stored here. case_id references {CaseModel}.
Sprint : {sprint}
"""
from __future__ import annotations
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional
from uuid import UUID, uuid4
from sqlmodel import Field, SQLModel
UTC = timezone.utc
class {Engine}CaseCollaborator(SQLModel, table=True):
"""Who has access to a {domain} case."""
__tablename__ = "{engine}_case_collaborators"
__table_args__ = {{"schema": "{engine}"}}
id: UUID = Field(default_factory=uuid4, primary_key=True)
case_id: UUID = Field(foreign_key="{case_table}.id", index=True)
user_id: UUID = Field(index=True)
tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
role: str # CollaborationRole value
status: str = "active" # CollaborationStatus value
invited_by: Optional[UUID] = None
joined_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
class {Engine}CaseInvitation(SQLModel, table=True):
"""Pending / accepted invitations to a {domain} case."""
__tablename__ = "{engine}_case_invitations"
__table_args__ = {{"schema": "{engine}"}}
id: UUID = Field(default_factory=uuid4, primary_key=True)
case_id: UUID = Field(foreign_key="{case_table}.id", index=True)
tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
inviter_id: UUID
invitee_email: str = Field(index=True)
role: str
status: str = "pending"
token: str = Field(
default_factory=lambda: secrets.token_urlsafe(32), index=True
)
message: Optional[str] = None
expires_at: datetime = Field(
default_factory=lambda: datetime.now(UTC) + timedelta(days=7)
)
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
class {Engine}CaseAnnotation(SQLModel, table=True):
"""Inline annotations on a {domain} case (discussion thread)."""
__tablename__ = "{engine}_case_annotations"
__table_args__ = {{"schema": "{engine}"}}
id: UUID = Field(default_factory=uuid4, primary_key=True)
case_id: UUID = Field(foreign_key="{case_table}.id", index=True)
tenant_id: UUID = Field(foreign_key="core.tenants.id", index=True)
author_id: UUID
author_name: str = ""
content: str
annotation_type: str = "comment"
status: str = "active"
is_pinned: bool = False
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
'''
ROUTES_TEMPLATE = '''\
"""
{Engine} — Case Collaboration Routes (14 endpoints)
====================================================
All endpoints: cookie-aware auth + HTMX-compatible (form + JSON).
Prefix : /api/v1/{engine}/collaboration
Auth : core.dependencies.get_current_user (cookie + Bearer)
Sprint : {sprint}
"""
from __future__ import annotations
from uuid import UUID
import structlog
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession
from core.database.session import get_db_session
from core.dependencies import get_current_user, verify_tenant_access
from .models import (
{Engine}CaseAnnotation,
{Engine}CaseCollaborator,
{Engine}CaseInvitation,
AnnotationType,
CollaborationRole,
)
logger = structlog.get_logger(__name__)
router = APIRouter(
prefix="/api/v1/{engine}/collaboration",
tags=["{Engine} — Collaboration"],
)
# ── Collaborators ─────────────────────────────────────────────────────────
@router.get("/cases/{{case_id}}/collaborators")
async def list_collaborators(
request: Request,
case_id: UUID,
current_user=Depends(get_current_user),
tenant_id: UUID = Depends(verify_tenant_access),
session: AsyncSession = Depends(get_db_session),
):
"""List collaborators on a {domain} case. Returns HTML fragment or JSON."""
from sqlalchemy import and_, select
result = await session.execute(
select({Engine}CaseCollaborator).where(
and_(
{Engine}CaseCollaborator.case_id == case_id,
{Engine}CaseCollaborator.tenant_id == tenant_id,
{Engine}CaseCollaborator.status == "active",
)
)
)
rows = result.scalars().all()
if request.headers.get("hx-request"):
if not rows:
html = (
'<p style="color:var(--text-muted);font-size:.8rem;text-align:center;'
'padding:var(--space-4)">Aucun collaborateur pour le moment.</p>'
)
else:
items = "".join(
f'<div style="padding:var(--space-2) 0;font-size:.82rem;'
f'border-bottom:1px solid var(--border)">'
f'<strong>{r.user_id}</strong> — <em>{r.role}</em></div>'
for r in rows
)
html = f'<div>{items}</div>'
return HTMLResponse(html)
return JSONResponse([
{{"id": str(r.id), "user_id": str(r.user_id), "role": r.role, "status": r.status}}
for r in rows
])
@router.post("/cases/{{case_id}}/invite")
async def invite_collaborator(
request: Request,
case_id: UUID,
current_user=Depends(get_current_user),
tenant_id: UUID = Depends(verify_tenant_access),
session: AsyncSession = Depends(get_db_session),
):
"""
Invite a collaborator. Accepts form-encoded (HTMX) or JSON.
Body: email, role, message (optional)
"""
import secrets
from datetime import timedelta
ct = request.headers.get("content-type", "")
if "application/json" in ct:
body = await request.json()
else:
form = await request.form()
body = dict(form)
email = body.get("email", "").strip()
role = body.get("role", "reviewer")
message = body.get("message", "")
if not email:
if request.headers.get("hx-request"):
return HTMLResponse(
'<div class="y-alert y-alert-error">Email requis.</div>',
status_code=422,
)
raise HTTPException(status_code=422, detail="email required")
from datetime import datetime, timezone
UTC = timezone.utc
inv = {Engine}CaseInvitation(
case_id=case_id,
tenant_id=tenant_id,
inviter_id=current_user.id,
invitee_email=email,
role=role,
message=message,
token=secrets.token_urlsafe(32),
expires_at=datetime.now(UTC) + timedelta(days=7),
)
session.add(inv)
await session.commit()
logger.info(
"{engine}_collaboration_invited",
case_id=str(case_id),
role=role,
tenant_id=str(tenant_id),
)
if request.headers.get("hx-request"):
return HTMLResponse(
'<div class="y-alert y-alert-success">✅ Invitation envoyée.</div>'
)
return JSONResponse({{"ok": True, "invitation_id": str(inv.id)}})
@router.post("/cases/{{case_id}}/annotations")
async def add_annotation(
request: Request,
case_id: UUID,
current_user=Depends(get_current_user),
tenant_id: UUID = Depends(verify_tenant_access),
session: AsyncSession = Depends(get_db_session),
):
"""Add an annotation to a {domain} case discussion thread."""
from datetime import datetime, timezone
UTC = timezone.utc
body = await request.json()
content = body.get("content", "").strip()
annotation_type = body.get("annotation_type", "comment")
if not content:
raise HTTPException(status_code=422, detail="content required")
annotation = {Engine}CaseAnnotation(
case_id=case_id,
tenant_id=tenant_id,
author_id=current_user.id,
author_name=getattr(current_user, "full_name", str(current_user.id))[:80],
content=content,
annotation_type=annotation_type,
)
session.add(annotation)
await session.commit()
logger.info(
"{engine}_annotation_added",
case_id=str(case_id),
type=annotation_type,
tenant_id=str(tenant_id),
sensitive=True,
)
return JSONResponse({{"ok": True, "id": str(annotation.id)}})
@router.get("/cases/{{case_id}}/annotations")
async def list_annotations(
request: Request,
case_id: UUID,
limit: int = 50,
offset: int = 0,
current_user=Depends(get_current_user),
tenant_id: UUID = Depends(verify_tenant_access),
session: AsyncSession = Depends(get_db_session),
):
"""List annotations for a {domain} case. Returns HTML fragment or JSON."""
from sqlalchemy import and_, select
result = await session.execute(
select({Engine}CaseAnnotation)
.where(
and_(
{Engine}CaseAnnotation.case_id == case_id,
{Engine}CaseAnnotation.tenant_id == tenant_id,
{Engine}CaseAnnotation.status == "active",
)
)
.order_by({Engine}CaseAnnotation.created_at.desc())
.limit(limit)
.offset(offset)
)
rows = result.scalars().all()
if request.headers.get("hx-request"):
if not rows:
return HTMLResponse(
'<p style="color:var(--text-muted);font-size:.8rem;text-align:center;'
'padding:var(--space-4)">Aucune annotation pour le moment.</p>'
)
items = "".join(
f'<div style="padding:var(--space-3);border-bottom:1px solid var(--border)">'
f'<span style="font-size:.7rem;font-weight:700;color:var(--text-muted)">'
f'[{a.annotation_type.upper()}] {a.author_name} — '
f'{a.created_at.strftime("%d/%m %H:%M")}</span>'
f'<p style="margin:4px 0 0 0;font-size:.83rem">{a.content}</p>'
f'</div>'
for a in reversed(rows)
)
return HTMLResponse(f'<div>{items}</div>')
return JSONResponse([
{{
"id": str(a.id),
"content": a.content,
"type": a.annotation_type,
"author": a.author_name,
"pinned": a.is_pinned,
"created_at": a.created_at.isoformat(),
}}
for a in rows
])
@router.post("/cases/{{case_id}}/annotations/{{annotation_id}}/resolve")
async def resolve_annotation(
case_id: UUID,
annotation_id: UUID,
current_user=Depends(get_current_user),
tenant_id: UUID = Depends(verify_tenant_access),
session: AsyncSession = Depends(get_db_session),
):
"""Mark an annotation as resolved."""
from sqlalchemy import and_, select
from datetime import datetime, timezone
UTC = timezone.utc
result = await session.execute(
select({Engine}CaseAnnotation).where(
and_(
{Engine}CaseAnnotation.id == annotation_id,
{Engine}CaseAnnotation.tenant_id == tenant_id,
)
)
)
ann = result.scalar_one_or_none()
if not ann:
raise HTTPException(status_code=404, detail="Annotation not found")
ann.status = "resolved"
ann.updated_at = datetime.now(UTC)
await session.commit()
return JSONResponse({{"ok": True}})
@router.post("/cases/{{case_id}}/annotations/{{annotation_id}}/pin")
async def pin_annotation(
case_id: UUID,
annotation_id: UUID,
current_user=Depends(get_current_user),
tenant_id: UUID = Depends(verify_tenant_access),
session: AsyncSession = Depends(get_db_session),
):
"""Pin / unpin an annotation."""
from sqlalchemy import and_, select
from datetime import datetime, timezone
UTC = timezone.utc
result = await session.execute(
select({Engine}CaseAnnotation).where(
and_(
{Engine}CaseAnnotation.id == annotation_id,
{Engine}CaseAnnotation.tenant_id == tenant_id,
)
)
)
ann = result.scalar_one_or_none()
if not ann:
raise HTTPException(status_code=404, detail="Annotation not found")
ann.is_pinned = not ann.is_pinned
ann.updated_at = datetime.now(UTC)
await session.commit()
return JSONResponse({{"ok": True, "pinned": ann.is_pinned}})
@router.post("/invitations/accept")
async def accept_invitation(
request: Request,
current_user=Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
):
"""Accept a collaboration invitation via token."""
from datetime import datetime, timezone
from sqlalchemy import select
UTC = timezone.utc
body = await request.json()
token = body.get("token", "")
if not token:
raise HTTPException(status_code=422, detail="token required")
result = await session.execute(
select({Engine}CaseInvitation).where({Engine}CaseInvitation.token == token)
)
inv = result.scalar_one_or_none()
if not inv or inv.status != "pending":
raise HTTPException(status_code=404, detail="Invalid or expired invitation")
if datetime.now(UTC) > inv.expires_at:
inv.status = "expired"
await session.commit()
raise HTTPException(status_code=410, detail="Invitation expired")
inv.status = "accepted"
collab = {Engine}CaseCollaborator(
case_id=inv.case_id,
tenant_id=inv.tenant_id,
user_id=current_user.id,
role=inv.role,
invited_by=inv.inviter_id,
)
session.add(collab)
await session.commit()
return JSONResponse({{"ok": True, "case_id": str(inv.case_id)}})
@router.post("/invitations/decline")
async def decline_invitation(
request: Request,
current_user=Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
):
"""Decline a collaboration invitation via token."""
from sqlalchemy import select
body = await request.json()
token = body.get("token", "")
result = await session.execute(
select({Engine}CaseInvitation).where({Engine}CaseInvitation.token == token)
)
inv = result.scalar_one_or_none()
if not inv:
raise HTTPException(status_code=404, detail="Invalid invitation")
inv.status = "declined"
await session.commit()
return JSONResponse({{"ok": True}})
@router.get("/my-collaborations")
async def my_collaborations(
current_user=Depends(get_current_user),
tenant_id: UUID = Depends(verify_tenant_access),
session: AsyncSession = Depends(get_db_session),
):
"""List all {domain} cases the current user is collaborating on."""
from sqlalchemy import and_, select
result = await session.execute(
select({Engine}CaseCollaborator).where(
and_(
{Engine}CaseCollaborator.user_id == current_user.id,
{Engine}CaseCollaborator.tenant_id == tenant_id,
{Engine}CaseCollaborator.status == "active",
)
)
)
rows = result.scalars().all()
return JSONResponse([
{{"case_id": str(r.case_id), "role": r.role, "joined_at": r.joined_at.isoformat()}}
for r in rows
])
'''
DOC_TEMPLATE = """\
# {Engine} — Collaboration Guide
> **Engine**: `{engine}` | **Domain**: {domain} | **Sprint**: {sprint}
> **Status**: 📋 Ready to implement
> **Master guide**: [docs/COLLABORATION_GUIDE.md](../../COLLABORATION_GUIDE.md)
---
## Overview
Add peer collaboration to `{engine}` cases using the YAZ collaboration pattern.
Once implemented, any `{engine}` case viewer can:
- Invite colleagues (role: owner / {co_role} / reviewer / observer)
- Request peer opinions / second opinions
- Post annotations in a shared discussion thread
- Co-manage case data (based on role)
---
## Status
| Component | Status |
|-----------|--------|
| `collaboration/__init__.py` | 🔲 Not created (run generator) |
| `collaboration/models.py` | 🔲 Not created (run generator) |
| `collaboration/service.py` | 🔲 Not created (run generator) |
| `collaboration/routes.py` | 🔲 Not created (run generator) |
| DB migration | 🔲 Pending |
| Factory mount | 🔲 Pending |
| UI workspace tab | 🔲 Pending |
| In-app guide page | 🔲 Pending |
---
## Quickstart
```bash
# 1. Generate the scaffold
python scripts/generators/create_collaboration.py \\
--engine {engine} \\
--domain {domain} \\
--co-role {co_role} \\
--case-model {CaseModel} \\
--sprint {sprint}
# 2. Review generated files under src/apps/{engine}/collaboration/
# 3. Generate + apply migration
alembic revision --autogenerate -m "{engine}_collaboration_tables_sprint{sprint}"
alembic upgrade head
# 4. Mount in factory — add to src/factory/_routes.py:
# from apps.{engine}.collaboration.routes import router as {engine}_collab_router
# app.include_router({engine}_collab_router, tags=["{Engine} — Collaboration"])
# 5. Add workspace tab + guide page to UI templates
# 6. Test: invite a user, post an annotation, verify tenant isolation
```
---
## Roles
| Role | Edit case | Annotate | View | Invite |
|------|:---:|:---:|:---:|:---:|
| Owner | ✅ | ✅ | ✅ | ✅ |
| {co_role} | ✅ | ✅ | ✅ | — |
| Reviewer | — | ✅ | ✅ | — |
| Observer | — | — | ✅ | — |
---
## API Endpoints (once implemented)
```
GET /api/v1/{engine}/collaboration/cases/{{id}}/collaborators
POST /api/v1/{engine}/collaboration/cases/{{id}}/invite
GET /api/v1/{engine}/collaboration/cases/{{id}}/annotations
POST /api/v1/{engine}/collaboration/cases/{{id}}/annotations
POST /api/v1/{engine}/collaboration/cases/{{id}}/annotations/{{ann_id}}/resolve
POST /api/v1/{engine}/collaboration/cases/{{id}}/annotations/{{ann_id}}/pin
POST /api/v1/{engine}/collaboration/invitations/accept
POST /api/v1/{engine}/collaboration/invitations/decline
GET /api/v1/{engine}/collaboration/my-collaborations
```
---
## Reference Implementation
→ See `src/apps/surgio/collaboration/` — the completed reference.
→ See [docs/engines/surgio/COLLABORATION.md](../surgio/COLLABORATION.md) — Surgio guide.
→ See [docs/COLLABORATION_GUIDE.md](../../COLLABORATION_GUIDE.md) — platform master guide.
"""
GUIDE_HTML_TEMPLATE = """\
{{% extends "shared/app_base.html" %}}
{{% set app_config = {{
'slug': '{engine}',
'name': '{Engine}',
'icon': 'users',
'gradient_from': '#667eea',
'gradient_to': '#764ba2',
'back_url': '/apps/{engine}/cases',
'back_label': '{Engine} Cases'
}} %}}
{{% block title %}}Collaboration Guide — {Engine}{{% endblock %}}
{{% block dashboard_content %}}
<div style="max-width:860px;margin:0 auto;padding:var(--space-6) var(--space-4)">
<div style="background:linear-gradient(135deg,#667eea,#764ba2);border-radius:var(--radius-xl);
padding:var(--space-8);color:#fff;margin-bottom:var(--space-8);text-align:center">
<h1 style="font-size:1.75rem;font-weight:800;margin:0 0 var(--space-2) 0">
Collaboration — {Engine}
</h1>
<p style="opacity:.87;margin:0">
Invite colleagues, request opinions, and discuss {domain} cases in real time.
</p>
</div>
<h2 style="font-size:1rem;font-weight:700;margin:0 0 var(--space-4) 0">Quick Start</h2>
<ol style="font-size:.85rem;line-height:2.2;color:var(--text-muted);padding-left:var(--space-5)">
<li>Open a {engine} case workspace</li>
<li>Click the <strong>Collaborate</strong> tab</li>
<li>Click <strong>Invite</strong> → enter email → choose role → Send</li>
<li>Use the discussion feed to post notes, questions, suggestions</li>
</ol>
<h2 style="font-size:1rem;font-weight:700;margin:var(--space-6) 0 var(--space-3) 0">Roles</h2>
<table style="width:100%;border-collapse:collapse;font-size:.82rem">
<thead>
<tr style="background:var(--surface-2)">
<th style="padding:var(--space-2) var(--space-3);text-align:left;border-bottom:2px solid var(--border)">Role</th>
<th style="padding:var(--space-2) var(--space-3);border-bottom:2px solid var(--border)">Edit</th>
<th style="padding:var(--space-2) var(--space-3);border-bottom:2px solid var(--border)">Annotate</th>
<th style="padding:var(--space-2) var(--space-3);border-bottom:2px solid var(--border)">View</th>
</tr>
</thead>
<tbody>
<tr><td style="padding:var(--space-2) var(--space-3);border-bottom:1px solid var(--border)">Owner</td><td style="text-align:center">✅</td><td style="text-align:center">✅</td><td style="text-align:center">✅</td></tr>
<tr><td style="padding:var(--space-2) var(--space-3);border-bottom:1px solid var(--border)">{co_role}</td><td style="text-align:center">✅</td><td style="text-align:center">✅</td><td style="text-align:center">✅</td></tr>
<tr><td style="padding:var(--space-2) var(--space-3);border-bottom:1px solid var(--border)">Reviewer</td><td style="text-align:center">—</td><td style="text-align:center">✅</td><td style="text-align:center">✅</td></tr>
<tr><td style="padding:var(--space-2) var(--space-3)">Observer</td><td style="text-align:center">—</td><td style="text-align:center">—</td><td style="text-align:center">✅</td></tr>
</tbody>
</table>
<div style="margin-top:var(--space-8);text-align:center">
<a href="/apps/{engine}/cases"
style="display:inline-flex;align-items:center;gap:8px;padding:var(--space-3) var(--space-6);
background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;border-radius:var(--radius-lg);
text-decoration:none;font-weight:700">
Open a Case
</a>
</div>
<p style="text-align:center;margin-top:var(--space-6);font-size:.73rem;color:var(--text-muted)">
YAZ Platform · {Engine} Collaboration · Sprint {sprint} · HIPAA Compliant
</p>
</div>
{{% endblock %}}
"""
# ── Generator ──────────────────────────────────────────────────────────────
def generate(
engine: str,
domain: str,
co_role: str,
case_model: str,
case_table: str,
sprint: str,
) -> None:
Engine = engine.capitalize()
CO_ROLE_UPPER = co_role.upper()
ctx = {
"engine": engine,
"Engine": Engine,
"domain": domain,
"co_role": co_role,
"CO_ROLE_UPPER": CO_ROLE_UPPER,
"CaseModel": case_model,
"case_model": case_model,
"case_table": case_table,
"sprint": sprint,
}
collab_dir = APPS / engine / "collaboration"
collab_dir.mkdir(parents=True, exist_ok=True)
files = {
collab_dir / "__init__.py": INIT_TEMPLATE,
collab_dir / "models.py": MODELS_TEMPLATE,
collab_dir / "routes.py": ROUTES_TEMPLATE,
}
# Template dir for guide HTML
tpl_dir = TEMPLATES / engine
tpl_dir.mkdir(parents=True, exist_ok=True)
files[tpl_dir / "collaborate_guide.html"] = GUIDE_HTML_TEMPLATE
# Docs directory for engine
docs_dir = DOCS_ENGINES / engine
docs_dir.mkdir(parents=True, exist_ok=True)
files[docs_dir / "COLLABORATION.md"] = DOC_TEMPLATE
created = []
skipped = []
for path, template in files.items():
content = render(template, **ctx)
if path.exists():
skipped.append(str(path.relative_to(ROOT)))
else:
path.write_text(content)
created.append(str(path.relative_to(ROOT)))
# Print summary
print(f"\n✅ {Engine} collaboration scaffold complete")
print(f" Engine : {engine}")
print(f" Domain : {domain}")
print(f" Co-role : {co_role}")
print(f" Sprint : {sprint}\n")
if created:
print("Created:")
for f in created:
print(f" + {f}")
if skipped:
print("\nSkipped (already exist):")
for f in skipped:
print(f" ~ {f}")
print(
f"""
Next steps:
1. Review generated files under src/apps/{engine}/collaboration/
2. alembic revision --autogenerate -m "{engine}_collaboration_tables_sprint{sprint}"
3. alembic upgrade head
4. Mount in src/factory/_routes.py:
from apps.{engine}.collaboration.routes import router as {engine}_collab_router
app.include_router({engine}_collab_router, tags=["{Engine} — Collaboration"])
5. Add GET /collaborate route to src/apps/{engine}/routes/*.py
6. Add Collaborate tab to src/ui/templates/apps/{engine}/case_workspace.html
7. Test with: pytest tests/{engine}/test_collaboration.py -v
"""
)
# ── CLI ───────────────────────────────────────────────────────────────────
def main() -> None:
parser = argparse.ArgumentParser(
description="Scaffold YAZ collaboration layer for an engine",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent(
"""
Examples:
python scripts/generators/create_collaboration.py \\
--engine clinica \\
--domain clinical \\
--co-role co_clinician \\
--case-model PatientEncounter \\
--sprint 54
python scripts/generators/create_collaboration.py \\
--engine labo \\
--domain laboratory \\
--co-role co_biologist \\
--case-model LabCase \\
--sprint 55
"""
),
)
parser.add_argument("--engine", required=True, help="Engine slug (e.g. clinica)")
parser.add_argument("--domain", required=True, help="Domain label (e.g. clinical)")
parser.add_argument(
"--co-role",
required=True,
dest="co_role",
help="Primary collaborator role slug (e.g. co_clinician)",
)
parser.add_argument(
"--case-model",
required=True,
dest="case_model",
help="SQLModel case class name (e.g. PatientEncounter)",
)
parser.add_argument(
"--case-table",
dest="case_table",
default=None,
help="FK table reference (default: {engine}.cases)",
)
parser.add_argument("--sprint", default="54", help="Sprint number (default: 54)")
args = parser.parse_args()
engine = args.engine.lower().strip()
if not (APPS / engine).exists():
print(f"❌ Engine '{engine}' not found at src/apps/{engine}/")
print(
f" Available: {', '.join(sorted(d.name for d in APPS.iterdir() if d.is_dir()))}"
)
sys.exit(1)
case_table = args.case_table or f"{engine}.cases"
generate(
engine=engine,
domain=args.domain,
co_role=args.co_role,
case_model=args.case_model,
case_table=case_table,
sprint=args.sprint,
)
if __name__ == "__main__":
main()
|