Pain Management Support Group Platform
Generated: November 20, 2026 at 03:22 AM
Document: Technical Manual - Developer Guide

# Pain Management Support Group Platform

Complete Technical and Programming Manual

Version 1.0

---

Table of Contents

  1. Introduction
  2. System Architecture
  3. Technology Stack
  4. Development Environment Setup
  5. Database Architecture
  6. Backend API Documentation
  7. RAG System Implementation
  8. Assessment and Analytics
  9. Frontend Development
  10. 10. Deployment 11. Security and Compliance 12. Testing 13. Maintenance and Monitoring 14. Troubleshooting 15. Contributing Guidelines 16. API Reference

    ---

    Introduction

    Purpose

    This technical manual provides comprehensive documentation for developers, DevOps engineers, and technical facilitators working on the Pain Management Support Group platform.

    Audience

    Document Conventions

    Code blocks show working examples def example_function(): pass

    Bold text: Important concepts or warnings Italic text: File paths or variable names inline code: Commands or code snippets

    ---

    System Architecture

    High-Level Overview

    ┌─────────────────┐
    │   React Frontend│
    │   (Port 3000)   │
    └────────┬────────┘
             │ HTTP/REST
             ▼
    ┌─────────────────┐
    │  FastAPI Backend│◄───┐
    │   (Port 8000)   │    │
    └────┬────┬───┬───┘    │
         │    │   │        │
         │    │   │    ┌───┴─────┐
         │    │   │    │ Celery  │
         │    │   │    │ Worker  │
         │    │   │    └───┬─────┘
         │    │   │        │
         ▼    ▼   ▼        ▼
    ┌────────┐┌──────┐┌────────┐
    │Postgres││Redis ││Pinecone│
    │  DB    ││Cache ││/Chroma │
    └────────┘└──────┘└────────┘
    

    Component Description

    Frontend (React): Backend (FastAPI): Database (PostgreSQL): Cache (Redis): Vector Database (Pinecone/ChromaDB): Background Workers (Celery):

    Data Flow

    User Authentication Flow:
    1. User submits credentials → Frontend
    
    1. Frontend → POST /api/v1/auth/login → Backend
    2. Backend verifies credentials → Database
    3. Backend generates JWT token
    4. Backend → Token → Frontend
    5. Frontend stores token
    6. Frontend includes token in subsequent requests
    RAG Query Flow:
    1. User asks question → Frontend
    
    1. Frontend → POST /api/v1/rag/query → Backend
    2. Backend → Embedding Generation → OpenAI API
    3. Backend → Similarity Search → Vector DB
    4. Vector DB → Top K chunks → Backend
    5. Backend → LLM with context → OpenAI/Claude API
    6. LLM → Generated answer → Backend
    7. Backend → Save conversation → Database
    8. Backend → Response with sources → Frontend

    ---

    Technology Stack

    Backend

    | Technology | Version | Purpose | ------------|---------|--------- Python | 3.11+ | Programming language FastAPI | 0.109+ | Web framework SQLAlchemy | 2.0+ | ORM Pydantic | 2.5+ | Data validation PostgreSQL | 15+ | Primary database Redis | 7+ | Cache and queue Celery | 5.3+ | Background tasks LangChain | 0.1+ | RAG orchestration OpenAI API | 1.10+ | LLM and embeddings Pinecone | 3.0+ | Vector database (option 1) ChromaDB | 0.4+ | Vector database (option 2)

    Frontend

    | Technology | Version | Purpose | ------------|---------|--------- React | 18+ | UI framework TypeScript | 5+ | Type safety React Router | 6+ | Routing Axios | 1+ | HTTP client Chart.js | 4+ | Visualizations TailwindCSS | 3+ | Styling Material-UI | 5+ | Component library

    DevOps

    | Technology | Version | Purpose | ------------|---------|--------- Docker | 24+ | Containerization Docker Compose | 2+ | Orchestration (dev) GitHub Actions | - | CI/CD Nginx | 1.25+ | Reverse proxy

    Analytics

    | Technology | Version | Purpose | ------------|---------|--------- Pandas | 2.1+ | Data analysis NumPy | 1.26+ | Numerical computing R | 4.3+ | Statistical analysis ggplot2 | 3.4+ | Visualizations

    ---

    Development Environment Setup

    Prerequisites

    Before starting, ensure you have:

    Initial Setup

    1. Clone Repository

    git clone https://github.com/your-org/pain-management-support-group.git
    cd pain-management-support-group
    

    2. Environment Variables

    cp .env.example .env
    

    Edit .env with your settings:

    Required OPENAI_API_KEY=sk-your-key-here SECRET_KEY=generate-secure-random-key DATABASE_URL=postgresql://postgres:postgres@localhost:5432/pain_management

    Optional (for Pinecone) PINECONE_API_KEY=your-key PINECONE_ENVIRONMENT=us-west1-gcp USE_PINECONE=true

    Generate SECRET_KEY:
    import secrets
    print(secrets.token_urlsafe(32))
    

    3. Docker Setup (Recommended)

    Start all services docker-compose up -d

    Check status docker-compose ps

    View logs docker-compose logs -f backend

    Stop services docker-compose down

    Access Points:

    4. Manual Setup (Alternative)

    Backend:
    cd backend
    
    

    Create virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate

    Install dependencies pip install -r requirements.txt

    Set up database createdb pain_management

    Run migrations alembic upgrade head

    Seed data (optional) python scripts/seed_data.py

    Start server uvicorn main:app --reload --host 0.0.0.0 --port 8000

    Frontend:
    cd frontend
    
    

    Install dependencies npm install

    Start development server npm start

    Redis:

    macOS brew install redis brew services start redis

    Linux sudo apt-get install redis-server sudo systemctl start redis

    Verify redis-cli ping # Should return PONG

    Celery Worker:
    cd backend
    celery -A backend.tasks worker --loglevel=info
    

    Verify Installation

    Test backend curl http://localhost:8000/health

    Expected response:

    {"status":"healthy","app":"Pain Management Support Group API","version":"1.0.0"}

    Test database connection docker-compose exec backend python -c "from backend.models.base import engine; print(engine.connect())"

    Test Redis docker-compose exec redis redis-cli ping

    ---

    Database Architecture

    Schema Overview

    The database consists of 12 main tables organized into logical groups:

    User Management: Curriculum: Assessments: Pain Tracking: Progress: Social: Resources: AI/RAG:

    Entity Relationship Diagram

    users
      │
      ├─── pain_logs (1:N)
      ├─── assessment_submissions (1:N)
      │    └─── assessment_answers (1:N)
      │         └─── assessment_questions (N:1)
      ├─── progress_tracking (1:N)
      │    └─── sessions (N:1)
      ├─── discussion_posts (1:N)
      │    └─── discussion_replies (1:N)
      └─── rag_conversations (1:N)
           └─── rag_messages (1:N)
    
    

    weeks ├─── sessions (1:N) │ └─── session_content (1:N) └─── assessments (1:N) └─── assessment_questions (1:N)

    Key Tables

    users

    CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        email VARCHAR(255) UNIQUE NOT NULL,
        username VARCHAR(100) UNIQUE NOT NULL,
        hashed_password VARCHAR(255) NOT NULL,
        first_name VARCHAR(100) NOT NULL,
        last_name VARCHAR(100) NOT NULL,
        date_of_birth DATE,
        phone VARCHAR(20),
        role VARCHAR(20) NOT NULL DEFAULT 'patient',
        is_active BOOLEAN NOT NULL DEFAULT TRUE,
        is_verified BOOLEAN NOT NULL DEFAULT FALSE,
        primary_pain_condition VARCHAR(200),
        pain_conditions TEXT,
        current_medications TEXT,
        enrollment_date TIMESTAMP WITH TIME ZONE,
        program_start_date TIMESTAMP WITH TIME ZONE,
        current_week INTEGER DEFAULT 1,
        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
        updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
        last_login TIMESTAMP WITH TIME ZONE
    );
    
    

    CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_users_username ON users(username);

    pain_logs

    CREATE TABLE pain_logs (
        id SERIAL PRIMARY KEY,
        user_id INTEGER NOT NULL REFERENCES users(id),
        pain_level INTEGER NOT NULL CHECK (pain_level >= 0 AND pain_level <= 10),
        pain_locations TEXT NOT NULL,
        pain_quality TEXT,
        activity_before_pain TEXT,
        medications_taken TEXT,
        non_med_strategies TEXT,
        sleep_quality INTEGER CHECK (sleep_quality >= 0 AND sleep_quality <= 10),
        fatigue_level INTEGER CHECK (fatigue_level >= 0 AND fatigue_level <= 10),
        anxiety_level INTEGER CHECK (anxiety_level >= 0 AND anxiety_level <= 10),
        function_level INTEGER CHECK (function_level >= 0 AND function_level <= 10),
        notes TEXT,
        log_date TIMESTAMP WITH TIME ZONE NOT NULL,
        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
        updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    );
    
    

    CREATE INDEX idx_pain_logs_user_id ON pain_logs(user_id); CREATE INDEX idx_pain_logs_log_date ON pain_logs(log_date);

    Migrations

    We use Alembic for database migrations.

    Create Migration:
    cd backend
    alembic revision --autogenerate -m "Description of changes"
    
    Apply Migrations:

    Upgrade to latest alembic upgrade head

    Upgrade to specific revision alembic upgrade

    Downgrade one revision alembic downgrade -1

    View history alembic history

    Current revision alembic current

    Example Migration:

    migrations/versions/001_initial.py from alembic import op import sqlalchemy as sa

    def upgrade(): op.create_table( 'users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('email', sa.String(255), nullable=False), sa.Column('username', sa.String(100), nullable=False), # ... more columns sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'), sa.UniqueConstraint('username') )

    def downgrade(): op.drop_table('users')

    Database Backup

    Manual Backup:

    Backup pg_dump -U postgres pain_management > backup.sql

    With Docker docker-compose exec postgres pg_dump -U postgres pain_management > backup.sql

    Restore psql -U postgres pain_management < backup.sql

    Automated Backup (add to cron):
    #!/bin/bash
    

    backup.sh DATE=$(date +%Y%m%d_%H%M%S) BACKUP_DIR="/backups" docker-compose exec -T postgres pg_dump -U postgres pain_management | gzip > $BACKUP_DIR/backup_$DATE.sql.gz

    Keep only last 30 days find $BACKUP_DIR -name "backup_*.sql.gz" -mtime +30 -delete

    ---

    Backend API Documentation

    Project Structure

    backend/
    ├── api/
    │   ├── __init__.py
    │   ├── routes/
    │   │   ├── __init__.py
    │   │   ├── auth.py          # Authentication endpoints
    │   │   ├── users.py         # User management
    │   │   ├── curriculum.py    # Curriculum access
    │   │   ├── assessments.py   # Tests and quizzes
    │   │   ├── pain_tracking.py # Pain logs
    │   │   ├── progress.py      # Progress tracking
    │   │   ├── discussions.py   # Forums
    │   │   ├── resources.py     # Educational materials
    │   │   └── rag.py          # AI Q&A
    │   └── middleware/
    │       └── auth.py          # Auth middleware
    ├── models/
    │   ├── __init__.py
    │   ├── base.py             # Base model and DB session
    │   ├── user.py
    │   ├── curriculum.py
    │   ├── assessment.py
    │   ├── pain_log.py
    │   ├── progress.py
    │   ├── discussion.py
    │   ├── resource.py
    │   └── rag.py
    ├── controllers/
    │   └── ...                 # Business logic (optional layer)
    ├── services/
    │   ├── rag_service.py      # RAG implementation
    │   ├── email_service.py    # Email notifications
    │   └── assessment_service.py
    ├── utils/
    │   ├── security.py         # Password hashing, tokens
    │   └── helpers.py
    ├── config/
    │   └── settings.py         # Configuration
    ├── tasks/
    │   └── celery_tasks.py     # Background tasks
    ├── main.py                 # FastAPI application
    └── requirements.txt
    

    Authentication System

    Implementation: backend/api/routes/auth.py

    Password Hashing

    from passlib.context import CryptContext
    
    

    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

    def get_password_hash(password: str) -> str: return pwd_context.hash(password)

    def verify_password(plain_password: str, hashed_password: str) -> bool: return pwd_context.verify(plain_password, hashed_password)

    JWT Tokens

    from jose import jwt
    from datetime import datetime, timedelta
    
    

    def create_access_token(data: dict) -> str: to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=30) to_encode.update({"exp": expire}) return jwt.encode(to_encode, SECRET_KEY, algorithm="HS256")

    Protected Routes

    from fastapi import Depends, HTTPException, status
    from fastapi.security import OAuth2PasswordBearer
    
    

    oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

    def get_current_user(token: str = Depends(oauth2_scheme)) -> User: try: payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) username: str = payload.get("sub") if username is None: raise HTTPException(status_code=401, detail="Invalid token") except JWTError: raise HTTPException(status_code=401, detail="Invalid token")

    user = db.query(User).filter(User.username == username).first() if user is None: raise HTTPException(status_code=401, detail="User not found") return user

    @router.get("/protected") def protected_route(current_user: User = Depends(get_current_user)): return {"message": f"Hello {current_user.username}"}

    Creating New Endpoints

    Step 1: Define Pydantic Schemas

    api/schemas/pain_log.py from pydantic import BaseModel, Field from datetime import datetime

    class PainLogCreate(BaseModel): pain_level: int = Field(..., ge=0, le=10) pain_locations: str sleep_quality: int | None = Field(None, ge=0, le=10) notes: str | None = None

    class PainLogResponse(BaseModel): id: int user_id: int pain_level: int log_date: datetime

    class Config: from_attributes = True

    Step 2: Create Route Handler

    api/routes/pain_tracking.py from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import List

    router = APIRouter()

    @router.post("/log", response_model=PainLogResponse) def create_pain_log( pain_log: PainLogCreate, current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): """Create a new pain log entry""" new_log = PainLog( user_id=current_user.id, log_date=datetime.utcnow(), **pain_log.dict() ) db.add(new_log) db.commit() db.refresh(new_log) return new_log

    @router.get("/history", response_model=List[PainLogResponse]) def get_pain_history( limit: int = 30, current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): """Get user's pain log history""" logs = db.query(PainLog).filter( PainLog.user_id == current_user.id ).order_by(PainLog.log_date.desc()).limit(limit).all() return logs

    Step 3: Register Router

    main.py from api.routes import pain_tracking

    app.include_router( pain_tracking.router, prefix="/api/v1/pain", tags=["Pain Tracking"] )

    Error Handling

    Custom Exception Classes:

    utils/exceptions.py from fastapi import HTTPException, status

    class NotFoundException(HTTPException): def __init__(self, detail: str = "Resource not found"): super().__init__(status_code=status.HTTP_404_NOT_FOUND, detail=detail)

    class UnauthorizedException(HTTPException): def __init__(self, detail: str = "Unauthorized"): super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail)

    Global Exception Handler:

    main.py from fastapi import Request from fastapi.responses import JSONResponse

    @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): logger.error(f"Unexpected error: {str(exc)}") return JSONResponse( status_code=500, content={"detail": "Internal server error"} )

    Request Validation

    FastAPI uses Pydantic for automatic validation:

    from pydantic import BaseModel, validator, Field
    from typing import List
    
    

    class PainLogCreate(BaseModel): pain_level: int = Field(..., ge=0, le=10, description="Pain level 0-10") pain_locations: List[str]

    @validator('pain_locations') def validate_locations(cls, v): valid_locations = ['lower_back', 'neck', 'shoulder', 'hip', 'knee'] if not all(loc in valid_locations for loc in v): raise ValueError('Invalid pain location') return v

    Database Transactions

    from sqlalchemy.orm import Session
    from contextlib import contextmanager
    
    

    @contextmanager def transaction(db: Session): """Context manager for database transactions""" try: yield db db.commit() except Exception as e: db.rollback() raise e finally: db.close()

    Usage with transaction(db) as session: user = User(email="test@example.com", username="testuser") session.add(user) pain_log = PainLog(user_id=user.id, pain_level=5) session.add(pain_log)

    Pagination

    from typing import Generic, TypeVar, List
    from pydantic import BaseModel
    
    

    T = TypeVar('T')

    class PaginatedResponse(BaseModel, Generic[T]): items: List[T] total: int page: int page_size: int total_pages: int

    def paginate(query, page: int = 1, page_size: int = 20): """Paginate SQLAlchemy query""" total = query.count() items = query.offset((page - 1) * page_size).limit(page_size).all()

    return PaginatedResponse( items=items, total=total, page=page, page_size=page_size, total_pages=(total + page_size - 1) // page_size )

    Usage @router.get("/pain-logs") def get_pain_logs(page: int = 1, page_size: int = 20, db: Session = Depends(get_db)): query = db.query(PainLog) return paginate(query, page, page_size)

    ---

    RAG System Implementation

    Architecture

    The RAG (Retrieval-Augmented Generation) system enables AI-powered Q&A by:

    1. Embedding medical literature into a vector database
    2. Retrieving relevant context based on user queries
    3. Generating informed answers with citations
    4. Implementation: backend/services/rag_service.py

      Key Components

      1. Document Ingestion
      from langchain.document_loaders import PyPDFLoader
      from langchain.text_splitter import RecursiveCharacterTextSplitter
      
      

      async def ingest_document(self, file_content: bytes, filename: str): """Ingest a document into the vector store"""

      # Save temporary file temp_path = f"/tmp/{filename}" with open(temp_path, "wb") as f: f.write(file_content)

      # Load document loader = PyPDFLoader(temp_path) documents = loader.load()

      # Split into chunks text_splitter = RecursiveCharacterTextSplitter( chunk_size=512, chunk_overlap=50, separators=["\n\n", "\n", ". ", " ", ""] ) chunks = text_splitter.split_documents(documents)

      # Add metadata for i, chunk in enumerate(chunks): chunk.metadata.update({ "source": filename, "chunk_index": i, "document_id": hashlib.md5(file_content).hexdigest() })

      # Add to vector store self.vector_store.add_documents(chunks)

      os.remove(temp_path) return {"chunks_created": len(chunks)}

      2. Query Processing
      from langchain.chains import ConversationalRetrievalChain
      from langchain.memory import ConversationBufferMemory
      
      

      async def query(self, query: str, conversation_history: List[Dict] = None): """Query the knowledge base"""

      # Create retriever retriever = self.vector_store.as_retriever( search_kwargs={"k": settings.TOP_K_RESULTS} )

      # Create memory memory = ConversationBufferMemory( memory_key="chat_history", return_messages=True, output_key="answer" )

      # Add conversation history if conversation_history: for msg in conversation_history: if msg["role"] == "user": memory.chat_memory.add_user_message(msg["content"]) else: memory.chat_memory.add_ai_message(msg["content"])

      # Create chain qa_chain = ConversationalRetrievalChain.from_llm( llm=self.llm, retriever=retriever, memory=memory, return_source_documents=True )

      # Get response result = qa_chain({"question": query})

      # Extract sources sources = [ { "content": doc.page_content[:200], "source": doc.metadata.get("source"), "chunk_index": doc.metadata.get("chunk_index") } for doc in result.get("source_documents", []) ]

      return { "response": result["answer"], "sources": sources }

      3. Custom Prompts
      from langchain.prompts import PromptTemplate
      
      

      PAIN_MANAGEMENT_PROMPT = PromptTemplate( input_variables=["context", "question"], template="""You are an expert pain management educator for a chronic pain support group.

      Your role is to provide accurate, evidence-based information about:

      • Pain physiology and anatomy
      • Medication mechanisms and safety
      • Alternative pain management techniques
      • Nutrition and lifestyle factors
      • Self-advocacy and patient rights

      Use the following context to answer the question. If the answer is not in the context, say so and provide general guidance while recommending they discuss with their healthcare provider.

      Always:

      1. Cite sources when using information from the context
      2. Use accessible language (12th-grade reading level)
      3. Show empathy for people living with chronic pain
      4. Distinguish between educational information and medical advice
      5. Encourage self-advocacy and shared decision-making
      6. Context: {context}

        Question: {question}

        Answer:""" )

      Vector Database Setup

      Option 1: Pinecone (Cloud)
      import pinecone
      from langchain.vectorstores import Pinecone as LangchainPinecone
      
      

      Initialize pinecone.init( api_key=settings.PINECONE_API_KEY, environment=settings.PINECONE_ENVIRONMENT )

      Create index if settings.PINECONE_INDEX_NAME not in pinecone.list_indexes(): pinecone.create_index( name=settings.PINECONE_INDEX_NAME, dimension=3072, # text-embedding-3-large metric="cosine" )

      Create vector store vector_store = LangchainPinecone.from_existing_index( index_name=settings.PINECONE_INDEX_NAME, embedding=embeddings )

      Option 2: ChromaDB (Local)
      import chromadb
      from langchain.vectorstores import Chroma
      
      

      Initialize client client = chromadb.PersistentClient(path=settings.CHROMA_DB_PATH)

      Create vector store vector_store = Chroma( client=client, collection_name="pain_management_docs", embedding_function=embeddings )

      Embedding Generation

      from langchain.embeddings import OpenAIEmbeddings
      
      

      embeddings = OpenAIEmbeddings( openai_api_key=settings.OPENAI_API_KEY, model=settings.OPENAI_EMBEDDING_MODEL # text-embedding-3-large )

      Generate embedding text = "How do NSAIDs reduce inflammation?" embedding = embeddings.embed_query(text)

      Returns: List[float] with 3072 dimensions

      Testing RAG System

      Test document ingestion with open("test_document.pdf", "rb") as f: content = f.read()

      result = await rag_service.ingest_document(content, "test_document.pdf") print(f"Created {result['chunks_created']} chunks")

      Test query response = await rag_service.query( query="What are the side effects of NSAIDs?", conversation_history=[] )

      print(f"Answer: {response['response']}") print(f"Sources: {response['sources']}")

      Monitoring RAG Performance

      Track query metrics import time

      start_time = time.time() response = await rag_service.query(query) response_time = (time.time() - start_time) * 1000

      Log metrics logger.info(f"RAG Query: {query[:50]}... | Response time: {response_time}ms | Sources: {len(response['sources'])}")

      Store in database for analysis metric = RAGMetric( query=query, response_time_ms=response_time, chunks_retrieved=len(response['sources']), model_used=settings.OPENAI_MODEL ) db.add(metric) db.commit()

      ---

      Assessment and Analytics

      Python Assessment System

      Location: assessments/python/assessment_generator.py

      Creating Assessments

      from assessments.python.assessment_generator import AssessmentGenerator
      
      

      Initialize generator generator = AssessmentGenerator()

      Generate Week 1 pre-test pretest = generator.generate_assessment( week_number=1, assessment_type="pre_test", num_questions=15 )

      Export to JSON generator.export_to_json(pretest, "week1_pretest.json")

      Score assessment user_answers = { "w1_q1": "B", "w1_q2": "A", # ... more answers }

      results = generator.score_assessment(pretest, user_answers) print(f"Score: {results['percentage']}%") print(f"Passed: {results['passed']}")

      Adding New Questions

      from assessments.python.assessment_generator import Question, QuestionType, QuestionDifficulty
      
      

      Add to question bank new_question = Question( id="w2_q5", text="What is the maximum daily dose of acetaminophen for adults?", type=QuestionType.MULTIPLE_CHOICE, options=[ "A. 1000mg", "B. 2000mg", "C. 3000-4000mg", "D. 6000mg" ], correct_answer="C", explanation="The maximum recommended daily dose is 3000-4000mg to avoid liver toxicity.", topic="Medication Safety", difficulty=QuestionDifficulty.EASY, points=1 )

      Add to question bank generator.question_bank[2].append(new_question)

      Python Analytics System

      Location: assessments/python/outcome_analytics.py

      Generating Patient Reports

      from assessments.python.outcome_analytics import OutcomeAnalytics
      
      

      analytics = OutcomeAnalytics()

      Generate comprehensive report report = analytics.generate_patient_report( user_id=user_id, pain_logs=pain_logs_list, assessment_scores={ 1: {"pre_score": 60, "post_score": 85}, 2: {"pre_score": 65, "post_score": 90}, # ... more weeks }, program_completion=True )

      Export analytics.export_report_to_json(report, f"patient_{user_id}_report.json") analytics.export_report_to_csv(report, f"patient_{user_id}_summary.csv")

      Access results print(f"Pain reduction: {report['changes']['pain_level']['absolute_change']}") print(f"Clinically significant: {report['clinically_significant']['pain_level']}")

      R Statistical Analysis

      Location: assessments/r/statistical_analysis.R

      Running Analysis

      cd assessments/r
      
      

      Run full analysis Rscript statistical_analysis.R --input ../data/patient_outcomes.csv

      Or from R console source("statistical_analysis.R") results <- main("../data/patient_outcomes.csv")

      Key Functions

      Paired T-Tests:

      Perform paired t-tests ttests <- perform_paired_ttests(data)

      Results include:

      - n_pairs: number of complete pairs

      - mean_baseline: average at baseline

      - mean_endpoint: average at week 8

      - t_statistic, p_value

      - cohens_d: effect size

      Longitudinal Models:

      Fit mixed-effects models models <- fit_longitudinal_models(data)

      Access results summary(models$models$pain_level) models$summaries$pain_level$slope # Change per week

      Generate Report:

      Generate HTML report with plots results <- generate_statistical_report( data, output_path = "reports/statistical_report.html" )

      Integrating Analytics with API

      api/routes/analytics.py from fastapi import APIRouter, Depends from assessments.python.outcome_analytics import OutcomeAnalytics

      router = APIRouter()

      @router.get("/patient/{user_id}/report") async def get_patient_report( user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): """Generate patient outcome report"""

      # Authorization check if current_user.role not in ["admin", "instructor"] and current_user.id != user_id: raise HTTPException(status_code=403, detail="Forbidden")

      # Get data pain_logs = db.query(PainLog).filter(PainLog.user_id == user_id).all()

      # Generate report analytics = OutcomeAnalytics() report = analytics.generate_patient_report( user_id=user_id, pain_logs=[log.__dict__ for log in pain_logs], assessment_scores={}, # Get from database program_completion=True )

      return report

      ---

      Frontend Development

      Project Structure (React)

      frontend/
      ├── public/
      │   ├── index.html
      │   └── favicon.ico
      ├── src/
      │   ├── components/
      │   │   ├── common/          # Reusable components
      │   │   ├── auth/            # Login, register
      │   │   ├── dashboard/       # Patient dashboard
      │   │   ├── curriculum/      # Week/session viewers
      │   │   ├── assessments/     # Test interfaces
      │   │   ├── pain-tracking/   # Pain log forms
      │   │   ├── chat/           # AI chatbot
      │   │   └── forums/         # Discussion forums
      │   ├── pages/
      │   │   ├── HomePage.tsx
      │   │   ├── DashboardPage.tsx
      │   │   ├── WeekPage.tsx
      │   │   └── ...
      │   ├── hooks/
      │   │   ├── useAuth.ts
      │   │   ├── usePainLogs.ts
      │   │   └── ...
      │   ├── context/
      │   │   ├── AuthContext.tsx
      │   │   └── ThemeContext.tsx
      │   ├── services/
      │   │   └── api.ts          # API client
      │   ├── types/
      │   │   └── index.ts        # TypeScript types
      │   ├── utils/
      │   │   └── helpers.ts
      │   ├── styles/
      │   │   └── globals.css
      │   ├── App.tsx
      │   └── index.tsx
      ├── package.json
      └── tsconfig.json
      

      API Client Setup

      // src/services/api.ts
      import axios from 'axios';
      
      

      const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000';

      export const api = axios.create({ baseURL: API_URL, headers: { 'Content-Type': 'application/json', }, });

      // Add token to requests api.interceptors.request.use((config) => { const token = localStorage.getItem('access_token'); if (token) { config.headers.Authorization = Bearer ${token}; } return config; });

      // Handle token expiration api.interceptors.response.use( (response) => response, async (error) => { if (error.response?.status === 401) { localStorage.removeItem('access_token'); window.location.href = '/login'; } return Promise.reject(error); } );

      // API functions export const authAPI = { login: (username: string, password: string) => api.post('/api/v1/auth/login', { username, password }), register: (data: RegisterData) => api.post('/api/v1/auth/register', data), };

      export const painAPI = { createLog: (data: PainLogData) => api.post('/api/v1/pain/log', data), getHistory: (limit: number = 30) => api.get(/api/v1/pain/history?limit=${limit}), };

      Authentication Hook

      // src/hooks/useAuth.ts
      import { createContext, useContext, useState, useEffect } from 'react';
      import { authAPI } from '../services/api';
      
      

      interface AuthContextType { user: User | null; login: (username: string, password: string) => Promise; logout: () => void; isAuthenticated: boolean; }

      const AuthContext = createContext(undefined);

      export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [user, setUser] = useState(null);

      useEffect(() => { // Check for stored token const token = localStorage.getItem('access_token'); if (token) { // Fetch user info fetchCurrentUser(); } }, []);

      const login = async (username: string, password: string) => { const response = await authAPI.login(username, password); localStorage.setItem('access_token', response.data.access_token); await fetchCurrentUser(); };

      const logout = () => { localStorage.removeItem('access_token'); setUser(null); };

      const fetchCurrentUser = async () => { try { const response = await api.get('/api/v1/auth/me'); setUser(response.data); } catch (error) { logout(); } };

      return ( {children} ); };

      export const useAuth = () => { const context = useContext(AuthContext); if (!context) throw new Error('useAuth must be used within AuthProvider'); return context; };

      Component Example: Pain Log Form

      // src/components/pain-tracking/PainLogForm.tsx
      import React, { useState } from 'react';
      import { painAPI } from '../../services/api';
      
      

      export const PainLogForm: React.FC = () => { const [painLevel, setPainLevel] = useState(5); const [locations, setLocations] = useState([]); const [notes, setNotes] = useState('');

      const handleSubmit = async (e: React.FormEvent) => { e.preventDefault();

      try { await painAPI.createLog({ pain_level: painLevel, pain_locations: JSON.stringify(locations), notes, });

      alert('Pain log saved!'); // Reset form or redirect } catch (error) { console.error('Error saving pain log:', error); alert('Failed to save pain log'); } };

      return (

      setPainLevel(Number(e.target.value))} /> {painLevel}