Spaces:
Paused

yaz / docs /COLLABORATION_GUIDE.md
anaselamr's picture
[PLATFORM] docs(collab): Sprint 53 — collaboration pattern for all 19 engines
01b6ea7
|
Raw History Blame Contribute Delete
20.8 kB
# YAZ Platform — Collaboration Pattern Master Guide
> **Version**: Sprint 53 | **Updated**: May 2026
> **Scope**: Platform-wide — applies to ALL 19 engines
> **Audience**: Practitioners (all domains) · Developers · Engine authors
> **In-app**: `/apps/surgio/collaborate` (Surgio reference implementation)
> **Per-engine docs**: See [docs/engines/{engine}/COLLABORATION.md](#per-engine-guides)
---
## 📋 Table of Contents
1. [What Is Case Collaboration?](#what-is-case-collaboration)
2. [Quick Start — Surgio (Reference)](#quick-start-surgio-reference)
3. [Roles & Permissions](#roles--permissions)
4. [Discussion Feed — Annotation Types](#discussion-feed--annotation-types)
5. [Requesting a Clinical Opinion](#requesting-a-clinical-opinion)
6. [Accepting an Invitation](#accepting-an-invitation)
7. [Platform Collaboration Pillar](#platform-collaboration-pillar)
8. [API Reference](#api-reference)
9. [Adding Collaboration to Any Engine](#adding-collaboration-to-any-engine)
10. [Generator Script](#generator-script)
11. [Per-Engine Guides](#per-engine-guides)
12. [Privacy & Security](#privacy--security)
13. [Troubleshooting](#troubleshooting)
14. [Roadmap](#roadmap)
---
## What Is Case Collaboration?
The YAZ collaboration layer lets any engine invite practitioners to a case/record
so they can discuss, annotate, request opinions, and co-manage — within the platform.
No emails, no screenshots. Everything stays in the record: traceable, HIPAA-compliant,
tenant-isolated.
**Domain examples:**
| Engine | Case type | Who collaborates |
|--------|-----------|-----------------|
| Surgio | Surgical case | Surgeon + Resident + Reviewer |
| Clinica | Patient encounter | GP + Specialist + Nurse |
| Labo | Lab result | Biologist + Clinician |
| Movio | Transport operation | Dispatcher + Driver + Coordinator |
| Banko | Finance case | Accountant + Auditor |
| Insura | Insurance claim | Agent + Medical Expert |
The pattern is **identical across all engines** — only the domain vocabulary changes.
---
## Quick Start — Surgio (Reference)
### Step 1 — Open a Case Workspace
1. Go to **Surgio → Cases** (`/apps/surgio/cases`)
2. Click any case to open it
3. Click the **"Collaborer"** tab in the top navigation rail
> **Direct URL**: `/apps/surgio/cases/{case_id}/workspace?tab=collab`
---
### Step 2 — Invite a Colleague
1. Click **"Inviter un collègue"** (blue button at the top of the Collaboration tab)
2. Enter your colleague's **email address**
3. Choose their **role**:
| Role | Can edit case | Can annotate | Can view | Notes |
|------|:---:|:---:|:---:|------|
| **Co-Chirurgien** | ✅ | ✅ | ✅ | Full co-surgeon access |
| **Reviewer** | ❌ | ✅ | ✅ | Can annotate, cannot modify case data |
| **Observateur** | ❌ | ❌ | ✅ | Read-only — for students, trainees |
4. Click **"Envoyer l'invitation"**
Your colleague receives an email with a secure link to accept the invitation.
Once accepted, they appear in the **Collaborators** list immediately.
---
### Step 3 — Discuss the Case
Once collaborators are on the case, use the **Discussion & Clinical Notes** feed:
| Action | How |
|--------|-----|
| Write a clinical note | Select **📋 Note** → type → press Enter |
| Ask a clinical question | Select **❓ Question** → type → press Enter |
| Post a suggestion | Select **💡 Suggestion** → type → press Enter |
| Leave a comment | Select **💬 Commentaire** → type → press Enter |
| Resolve an annotation | Click **✓ Resolve** on any annotation |
| Pin important notes | Click **📌 Pin** on any annotation |
The feed **auto-refreshes every 30 seconds** — no manual reload needed.
---
## Request a Clinical Opinion ("Demander un avis")
The fastest way to ask a specific clinical question on a case:
1. Click **"Demander un avis clinique"** (ghost button, next to Invite)
2. Type your clinical question in the text area
> *Example: "Que pensez-vous du risque anastomotique compte tenu de l'état nutritionnel et de l'ASA III ?"*
3. **Optional**: add a colleague's email to invite them at the same time
4. Click **"Envoyer la demande d'avis"**
This does both things in one action:
- Posts the question as a **❓ Question** annotation in the shared discussion thread
- Invites the colleague (if email provided) with **Reviewer** access
- Everyone on the case who is connected sees the new annotation within 30s
---
## Accepting an Invitation (for Collaborators)
When invited, you receive an email with a link. Click it and:
1. Log in to YAZ (or create account if new)
2. You are automatically taken to the case workspace
3. Your role determines what you can see and do (see role table above)
No special setup required.
---
## Collaboration Roles — What Each Can Do
```
Owner (case creator)
├── Invite / revoke colleagues
├── Change collaborator roles
├── Edit all case data
├── Post any annotation type
└── Delete annotations
Co-Chirurgien
├── Edit case data
├── Post any annotation type
└── Resolve / pin annotations
Reviewer
├── Post annotations (all types)
├── Resolve annotations
└── View full case record
Observateur
└── View full case record (read-only)
```
---
## Discussion Feed — Annotation Types
| Icon | Type | Use For |
|------|------|---------|
| 📋 | **Clinical Note** | Intraop observations, vitals trends, exam findings |
| ❓ | **Question** | Clinical questions for colleagues ("Should we change approach?") |
| 💡 | **Suggestion** | Protocol or technique suggestions |
| 💬 | **Comment** | General discussion, follow-up responses |
| 🔬 | **Image Markup** | Annotated images (radiology, intraop photos) |
---
## Privacy & Security
- All collaboration data is **tenant-isolated** — visible only to users in your organisation
- Annotations are **immutable audit records** — they cannot be deleted by non-owners
- Invitations expire after **7 days** if not accepted
- PHI (patient name, diagnosis) is **never included in invitation emails**
- All actions are logged to the **audit trail** (HIPAA compliant)
- Observation access is **read-only** — no accidental edits from trainees
---
## API Reference (for Developers)
All endpoints require authentication (session cookie or Bearer token).
```
GET /api/v1/surgio/collaboration/cases/{case_id}/collaborators
POST /api/v1/surgio/collaboration/cases/{case_id}/invite (form or JSON)
PUT /api/v1/surgio/collaboration/cases/{case_id}/collaborators/{user_id}/role
DELETE /api/v1/surgio/collaboration/cases/{case_id}/collaborators/{user_id}
GET /api/v1/surgio/collaboration/cases/{case_id}/annotations
POST /api/v1/surgio/collaboration/cases/{case_id}/annotations (JSON)
POST /api/v1/surgio/collaboration/cases/{case_id}/annotations/{id}/resolve
POST /api/v1/surgio/collaboration/cases/{case_id}/annotations/{id}/pin
POST /api/v1/surgio/collaboration/invitations/accept {token}
POST /api/v1/surgio/collaboration/invitations/decline {token}
GET /api/v1/surgio/collaboration/my-collaborations
```
**POST Annotation (JSON)**:
```json
{
"content": "Patient haemodynamically stable intraop",
"annotation_type": "clinical_note"
}
```
`annotation_type` values: `clinical_note` | `question` | `suggestion` | `comment` | `image_markup`
**POST Invite (form or JSON)**:
```json
{ "email": "colleague@hospital.com", "role": "reviewer", "message": "Optional context" }
```
`role` values: `co_surgeon` | `reviewer` | `observer`
---
## Platform Collaboration Pillar
The platform exposes a generic collaboration pillar at `src/core/tools/collaboration/`.
Engine-specific collaboration modules (like Surgio's) **compose** this pillar rather
than re-implementing it from scratch.
```
src/core/tools/collaboration/ ← Platform pillar (generic)
│ ├── models.py ← Base classes / enums
│ └── routes.py ← Generic listing endpoints
src/apps/surgio/collaboration/ ← Engine-specific implementation
│ ├── __init__.py ← Enums + role/type definitions
│ ├── models.py ← 3 SQLModel tables (collaborators, invitations, annotations)
│ ├── service.py ← Business logic (invite, annotate, resolve, pin)
│ └── routes.py ← 14 FastAPI endpoints (HTMX + JSON)
```
**URL pattern per engine:**
```
/api/v1/{engine}/collaboration/cases/{case_id}/collaborators
/api/v1/{engine}/collaboration/cases/{case_id}/annotations
/api/v1/{engine}/collaboration/invitations/accept
```
---
## Adding Collaboration to Any Engine
> **Fastest path**: Use the generator script (see next section). Below is the manual recipe for reference.
### Step 1 — Create the collaboration package
```bash
mkdir -p src/apps/{engine}/collaboration
touch src/apps/{engine}/collaboration/__init__.py
```
`__init__.py`:
```python
"""
{Engine} — Case Collaboration
Roles: owner, co_{domain}, reviewer, observer
"""
from enum import Enum
class CollaborationRole(str, Enum):
OWNER = "owner"
CO_{DOMAIN} = "co_{domain}" # e.g. CO_CLINICIAN, CO_ANALYST
REVIEWER = "reviewer"
OBSERVER = "observer"
class AnnotationType(str, Enum):
COMMENT = "comment"
NOTE = "note" # rename to domain vocabulary
SUGGESTION = "suggestion"
QUESTION = "question"
ATTACHMENT = "attachment"
```
### Step 2 — models.py (3 tables)
```python
from sqlmodel import Field, SQLModel
from uuid import UUID, uuid4
from datetime import datetime, timezone
from typing import Optional
from .{engine}_models import {Engine}Case # import base case model
UTC = timezone.utc
class {Engine}CaseCollaborator(SQLModel, table=True):
__tablename__ = "{engine}_case_collaborators"
__table_args__ = {"schema": "{engine}"}
id: UUID = Field(default_factory=uuid4, primary_key=True)
case_id: UUID = Field(foreign_key="{engine}.cases.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):
__tablename__ = "{engine}_case_invitations"
__table_args__ = {"schema": "{engine}"}
id: UUID = Field(default_factory=uuid4, primary_key=True)
case_id: UUID = Field(foreign_key="{engine}.cases.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
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
class {Engine}CaseAnnotation(SQLModel, table=True):
__tablename__ = "{engine}_case_annotations"
__table_args__ = {"schema": "{engine}"}
id: UUID = Field(default_factory=uuid4, primary_key=True)
case_id: UUID = Field(foreign_key="{engine}.cases.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))
```
### Step 3 — service.py (business logic)
```python
from core.services.base import BaseService
from .models import {Engine}CaseCollaborator, {Engine}CaseInvitation, {Engine}CaseAnnotation
class {Engine}CollaborationService(BaseService):
async def list_collaborators(self, case_id: UUID, tenant_id: UUID): ...
async def invite(self, case_id, email, role, inviter_id, tenant_id, message=""): ...
async def accept_invitation(self, token: str, user_id: UUID): ...
async def add_annotation(self, case_id, content, annotation_type, author_id, tenant_id): ...
async def list_annotations(self, case_id, tenant_id, limit=50, offset=0): ...
async def resolve_annotation(self, annotation_id, tenant_id): ...
async def pin_annotation(self, annotation_id, tenant_id): ...
```
Copy `src/apps/surgio/collaboration/service.py` as a starting point — replace
`Surgio`/`surgio`/`surgery` with your engine name throughout.
### Step 4 — routes.py (14 endpoints)
```python
from fastapi import APIRouter, Request
from core.dependencies import get_current_user, verify_tenant_access
router = APIRouter(
prefix="/api/v1/{engine}/collaboration",
tags=["{Engine} — Collaboration"]
)
# Copy src/apps/surgio/collaboration/routes.py and s/surgio/{engine}/g
```
**HTMX compatibility rules** (mandatory):
- Accept both `application/json` AND `application/x-www-form-urlencoded` on POST endpoints
- Return HTML fragment when `HX-Request` header is present, JSON otherwise
- Always use `core.dependencies.get_current_user` (reads cookie + Bearer)
### Step 5 — Alembic migration
```bash
alembic revision --autogenerate -m "{engine}_collaboration_tables_sprint{N}"
# Review the generated file, then:
alembic upgrade head
```
### Step 6 — Mount in factory
```python
# src/factory/_routes.py (inside try/except block)
try:
from apps.{engine}.collaboration.routes import router as {engine}_collab_router
app.include_router({engine}_collab_router, tags=["{Engine} — Collaboration"])
logger.info("✅ {Engine} Collaboration API mounted")
except Exception as e:
logger.info("{Engine} Collaboration API not available: %s", e)
```
### Step 7 — Add UI tab to case workspace
In `src/ui/templates/apps/{engine}/case_workspace.html` (or equivalent):
```html
{# ── COLLABORATE tab ─────────────────────────────── #}
<div id="panel-collab" class="cw-panel-inner"
hx-get="/api/v1/{engine}/collaboration/cases/{{ case_id }}/collaborators"
hx-trigger="intersect once"
hx-target="#collab-content"
hx-swap="innerHTML">
<div style="display:flex;gap:var(--space-2);flex-wrap:wrap;margin-bottom:var(--space-3)">
<button onclick="document.getElementById('invite-modal').classList.remove('hidden')"
class="y-btn y-btn-primary y-btn-sm">
<i data-lucide="user-plus"></i> Invite
</button>
<a href="/apps/{engine}/collaborate" target="_blank" class="y-btn y-btn-ghost y-btn-sm">
<i data-lucide="book-open"></i> Guide
</a>
</div>
<div id="collab-content">...</div>
<div id="annotations-feed"
hx-get="/api/v1/{engine}/collaboration/cases/{{ case_id }}/annotations"
hx-trigger="load, every 30s"
hx-swap="innerHTML">
</div>
</div>
```
### Step 8 — Add in-app guide page
```bash
cp src/ui/templates/apps/surgio/collaborate_guide.html \
src/ui/templates/apps/{engine}/collaborate_guide.html
# Edit: replace 'surgio' with engine slug, update domain labels
```
Add route in `src/apps/{engine}/routes/{cases}.py`:
```python
@router.get("/collaborate", response_class=HTMLResponse)
async def collaboration_guide(request: Request, tenant_id: UUID = Depends(verify_tenant_access)):
return templates.TemplateResponse(request, "apps/{engine}/collaborate_guide.html",
{"tenant_id": str(tenant_id)})
```
---
## Generator Script
**Auto-scaffold collaboration for any engine in one command:**
```bash
cd /home/dell/yaz
source .venv/bin/activate
python scripts/generators/create_collaboration.py \
--engine clinica \
--domain clinical \
--co-role co_clinician \
--case-model PatientEncounter \
--sprint 54
```
This 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`
- `docs/engines/{engine}/COLLABORATION.md`
See: [scripts/generators/create_collaboration.py](../scripts/generators/create_collaboration.py)
---
## Per-Engine Guides
| Engine | Domain | Status | Guide |
|--------|--------|--------|-------|
| **surgio** | Surgical | ✅ Production (Sprint 53) | [COLLABORATION.md](engines/surgio/COLLABORATION.md) |
| **clinica** | Clinical care | 📋 Ready to implement | [COLLABORATION.md](engines/clinica/COLLABORATION.md) |
| **labo** | Laboratory | 📋 Ready to implement | [COLLABORATION.md](engines/labo/COLLABORATION.md) |
| **ayrad** | Surgeon workspace | 📋 Ready to implement | [COLLABORATION.md](engines/ayrad/COLLABORATION.md) |
| **movio** | Mobility/Transport | 📋 Ready to implement | [COLLABORATION.md](engines/movio/COLLABORATION.md) |
| **banko** | Finance | 📋 Ready to implement | [COLLABORATION.md](engines/banko/COLLABORATION.md) |
| **insura** | Insurance | 📋 Ready to implement | [COLLABORATION.md](engines/insura/COLLABORATION.md) |
| **pharma** | Pharmacy | 📋 Ready to implement | [COLLABORATION.md](engines/pharma/COLLABORATION.md) |
| **stoka** | Inventory | 📋 Ready to implement | [COLLABORATION.md](engines/stoka/COLLABORATION.md) |
| **medio** | Education | 📋 Ready to implement | [COLLABORATION.md](engines/medio/COLLABORATION.md) |
| **azul** | Billing/CRM | 📋 Ready to implement | [COLLABORATION.md](engines/azul/COLLABORATION.md) |
| **campo** | Field ops | 📋 Ready to implement | [COLLABORATION.md](engines/campo/COLLABORATION.md) |
| **casa** | Accommodation | 📋 Ready to implement | [COLLABORATION.md](engines/casa/COLLABORATION.md) |
| **educa** | Training | 📋 Ready to implement | [COLLABORATION.md](engines/educa/COLLABORATION.md) |
| **fabrica** | Manufacturing | 📋 Ready to implement | [COLLABORATION.md](engines/fabrica/COLLABORATION.md) |
| **luiz** | Legal | 📋 Ready to implement | [COLLABORATION.md](engines/luiz/COLLABORATION.md) |
| **stay** | Hospitality | 📋 Ready to implement | [COLLABORATION.md](engines/stay/COLLABORATION.md) |
| **amraved** | AI agent | 📋 Ready to implement | [COLLABORATION.md](engines/amraved/COLLABORATION.md) |
| **trena** | Training | 📋 Ready to implement | [COLLABORATION.md](engines/trena/COLLABORATION.md) |
---
## Privacy & Security
- All collaboration data is **tenant-isolated** — visible only to users in your organisation
- Annotations are **immutable audit records** — cannot be deleted by non-owners
- Invitations expire after **7 days** if not accepted
- PHI (patient name, diagnosis) is **never included in invitation emails**
- All actions are logged to the **audit trail** (HIPAA compliant)
- Observation access is **read-only** — no accidental edits from trainees
**Auth pattern** (mandatory for all engines):
```python
# ✅ Always use core.dependencies — cookie-aware, reads Bearer + session cookie
from core.dependencies import get_current_user, verify_tenant_access
# ❌ Never use auth.dependencies directly — it re-exports but may miss cookie context
```
---
## Troubleshooting
| Problem | Cause | Fix |
|---------|-------|-----|
| 401 on collaboration API | Not logged in | Log in at `/login` |
| Invitation link expired | >7 days old | Owner resends invite |
| Collaborator list not updating | Browser cache | Click 🔄 Refresh button |
| Annotation not appearing | 30s refresh interval | Wait or click refresh |
| Role change not reflected | Stale session | Colleague re-logs in |
| Cannot invite (403) | Not case owner | Ask case owner to invite |
| 422 on invite POST from HTMX | Wrong content-type | Accept `form` AND `json` in route |
| Import error at startup | Missing db tables | Run `alembic upgrade head` |
---
## Roadmap
| Feature | Status | Sprint |
|---------|--------|--------|
| Surgio collaboration (full) | ✅ Done | 53 |
| In-app guide page (`/apps/surgio/collaborate`) | ✅ Done | 53 |
| Generator script | ✅ Done | 53 |
| Redis pub/sub live push | 🔄 Planned | 54 |
| Presence indicator (online/offline) | 🔄 Planned | 54 |
| WebSocket real-time updates | 🔄 Planned | 54 |
| Clinica collaboration | 🔄 Planned | 54 |
| Labo collaboration | 🔄 Planned | 55 |
| Mobile collaboration view | 🔄 Planned | 55 |
---
*YAZ Care Platform — Sprint 53 — Platform Collaboration Layer*
*Pattern applies to all 19 engines · HIPAA compliant · Tenant-isolated · Audit-trailed*
*Reference implementation: Surgio · Generator: `scripts/generators/create_collaboration.py`*