Download scripts/generators/create_collaboration.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 30.6 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/generators/create_collaboration.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/generators/create_collaboration.py
-
curl -L -o create_collaboration.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/generators/create_collaboration.py
30.6 kB
| #!/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() | |