diff --git a/README.md b/README.md index fb6032b6..ddb9b3d1 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,236 @@ -Dask Example Notebooks -====================== +# Physiotherapy Patient Management System - Complete Solution Documentation -This repository includes easy-to-run example notebooks for Dask. -They are intended to be educational and give users a start on common workflows. +## πŸ“‹ Overview -They should be easy to run locally if you download this repository. -They are also available on the cloud by clicking on the link below: +This repository contains comprehensive documentation for developing a complete physiotherapy patient management system that includes web, iOS, and Android applications. The system enables patients to book appointments, manage payments, and share videos, while providing physiotherapists with complete patient records, session tracking, and content management capabilities. -[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/dask/dask-examples/master?urlpath=lab) -[![Build Status](https://travis-ci.org/dask/dask-examples.svg?branch=master)](https://travis-ci.org/dask/dask-examples) +## πŸ“ Documentation Structure +### 🎯 [Main Specification Document](./physiotherapy-management-system-specification.md) +**Complete technical specification and system overview** +- Executive summary and system architecture +- Technology stack recommendations +- Security and compliance considerations +- Cost estimation and risk assessment +- Success metrics and next steps -Contributing ------------- +### πŸ—„οΈ [Database Schema](./database-schema.sql) +**Complete PostgreSQL database schema** +- All tables with relationships and constraints +- Indexes for optimal performance +- Triggers for automated updates +- Views for common queries +- Sample data for development -This repository is a great opportunity to start contributing to Dask. -Please note that examples submitted to this repository should follow these -guidelines: +### πŸ”Œ [API Documentation](./api-documentation.md) +**Comprehensive REST API specification** +- All endpoints with request/response examples +- Authentication and authorization details +- Error handling and status codes +- Rate limiting and security measures +- SDK examples for multiple languages -1. Run top-to-bottom without intervention from the user -2. Not require external data sources that may disappear over time - (external data sources that are highly unlikely to disappear are fine) -3. Not be resource intensive, and should run within 2GB of memory -4. Be clear and contain enough prose to explain the topic at hand -5. Be concise and limited to one or two topics, such that a reader can - get through the example within a few minutes of reading -6. Be of general relevance to Dask users, and so not too specific on a - particular problem or use case +### πŸš€ [Deployment Guide](./deployment-guide.md) +**Complete deployment and infrastructure setup** +- Development environment setup with Docker +- Production deployment on AWS/GCP +- CI/CD pipeline configuration +- Monitoring and logging setup +- Security configuration and SSL setup - As an example "how to do dataframe joins" is a great topic while "how to - do dataframe joins in the particular case when one column is a categorical - and the other is object dtype" is probably too specific -7. If the example requires a library not included in `binder/environment.yml` - then it would be `pip` installed` in the first cell of the notebook, with a - brief explanation about what functionality the library adds. A brief - example follows: +### πŸ—“οΈ [Development Roadmap](./development-roadmap.md) +**24-week phased development plan** +- Detailed timeline with milestones +- Team structure and resource allocation +- Risk mitigation strategies +- Success metrics and KPIs +- Post-launch enhancement roadmap - ``` - ### Install Extra Dependencies +## πŸ—οΈ System Architecture - We first install the library X for interacting with Y - ``` +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Frontend Applications β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Web App β”‚ iOS App β”‚ Android App β”‚ +β”‚ (React.js) β”‚ (Swift/RN) β”‚ (Kotlin/RN) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ API Gateway & Load Balancer β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Backend Services β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Auth Service β”‚ Core API β”‚ Video Service β”‚ +β”‚ (JWT/OAuth) β”‚ (Node.js) β”‚ (Streaming) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Data Layer β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ PostgreSQL β”‚ Redis Cache β”‚ File Storage β”‚ +β”‚ (Primary DB) β”‚ (Sessions) β”‚ (AWS S3/GCS) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` - ``` - !pip install X - ``` +## 🎯 Core Features + +### πŸ‘₯ Patient Portal +- **Appointment Booking**: Schedule sessions with available physiotherapists +- **Payment Management**: Pay bills online with multiple payment options +- **Video Sharing**: Upload initial assessment videos and receive treatment videos +- **Session History**: View past sessions and treatment progress +- **Exercise Tracking**: Complete assigned exercises and track progress + +### πŸ₯ Physiotherapist Dashboard +- **Patient Management**: Complete patient records and medical history +- **Session Tracking**: Record session details, treatments, and progress notes +- **Appointment Management**: View, confirm, and reschedule appointments +- **Billing System**: Generate invoices and track payments +- **Video Management**: Upload treatment videos and view patient submissions +- **Analytics**: Session statistics, patient progress, and revenue reports + +### πŸ“± Mobile Applications +- **Native iOS App**: Swift/SwiftUI with HealthKit integration +- **Native Android App**: Kotlin/Jetpack Compose with Google Fit integration +- **Cross-Platform Option**: React Native for faster development +- **Offline Capabilities**: View session history and exercise plans offline +- **Push Notifications**: Appointment reminders and important updates + +## πŸ’» Technology Stack + +### Frontend +- **Web**: React.js 18+, TypeScript, Tailwind CSS +- **Mobile**: React Native or Native (Swift/Kotlin) +- **State Management**: Redux Toolkit or Zustand +- **UI Components**: Material-UI or Chakra UI + +### Backend +- **Runtime**: Node.js 18+ or Python 3.11+ +- **Framework**: Express.js or FastAPI +- **Authentication**: JWT with refresh tokens +- **File Upload**: Multer or FastAPI File Upload +- **Real-time**: WebSocket for notifications + +### Database & Storage +- **Primary Database**: PostgreSQL 15+ +- **Caching**: Redis 7+ +- **File Storage**: AWS S3 or Google Cloud Storage +- **CDN**: CloudFlare or AWS CloudFront + +### Infrastructure +- **Cloud Provider**: AWS, Google Cloud, or DigitalOcean +- **Containerization**: Docker with Docker Compose +- **CI/CD**: GitHub Actions or GitLab CI +- **Monitoring**: Sentry, DataDog, or New Relic + +## πŸ“Š Project Timeline & Budget + +### Development Timeline: 24 Weeks (6 Months) + +| Phase | Duration | Focus | Key Deliverables | +|-------|----------|-------|------------------| +| **Phase 1** | Weeks 1-4 | Foundation & Core Setup | Authentication, User Management, Basic UI | +| **Phase 2** | Weeks 5-8 | Appointment & Session Management | Booking System, Session Tracking, Patient Portal | +| **Phase 3** | Weeks 9-12 | Billing & Payment Integration | Payment Processing, Mobile App Start | +| **Phase 4** | Weeks 13-16 | Video Features & Advanced Functionality | Video Upload/Streaming, Communication | +| **Phase 5** | Weeks 17-20 | Polish & Advanced Features | UX Enhancement, Advanced Analytics, Mobile Completion | +| **Phase 6** | Weeks 21-24 | Deployment & Launch | Production Deployment, Training, Full Launch | + +### Budget Estimation + +**Core Team Development (24 weeks):** +- **Total Range**: $251,200 - $369,600 +- **Monthly Infrastructure**: $500 - $1,450 +- **Third-party Services**: Variable based on usage + +**Lean Team Alternative:** +- **Reduced Cost**: ~$180,000 - $250,000 +- **Extended Timeline**: 28-32 weeks + +## πŸ”’ Security & Compliance + +### HIPAA Compliance +- End-to-end encryption for all patient data +- Audit logs for all data access and modifications +- Secure user authentication with MFA +- Data retention and deletion policies +- Business Associate Agreements (BAA) with vendors + +### Security Measures +- JWT-based authentication with refresh tokens +- Role-based access control (RBAC) +- API rate limiting and DDoS protection +- Regular security audits and penetration testing +- SSL/TLS encryption for all communications + +## πŸ“ˆ Success Metrics + +### Technical KPIs +- **System Uptime**: >99.9% +- **API Response Time**: <200ms average +- **Mobile App Performance**: <3 second load times +- **Video Upload Success Rate**: >95% + +### Business KPIs +- **User Adoption Rate**: 80% within 3 months +- **Appointment Show Rate**: 15% improvement +- **Payment Success Rate**: >98% +- **Customer Satisfaction**: >4.5/5 rating + +## πŸš€ Getting Started + +### For Developers +1. Review the [Main Specification](./physiotherapy-management-system-specification.md) +2. Set up development environment using the [Deployment Guide](./deployment-guide.md) +3. Implement database schema from [Database Schema](./database-schema.sql) +4. Follow the [Development Roadmap](./development-roadmap.md) for phased implementation + +### For Project Managers +1. Review the complete [Development Roadmap](./development-roadmap.md) +2. Assess team requirements and budget allocation +3. Set up project management tools and processes +4. Plan stakeholder communication and feedback loops + +### For Stakeholders +1. Start with the [Main Specification](./physiotherapy-management-system-specification.md) executive summary +2. Review feature requirements and technical approach +3. Understand timeline and budget implications +4. Plan for user training and change management + +## πŸ“ž Next Steps + +1. **Stakeholder Review**: Present this documentation to your physiotherapist friend for feedback and requirements validation +2. **Team Assembly**: Recruit developers, designers, and project managers based on the roadmap +3. **Technical Validation**: Set up a proof-of-concept to validate technical decisions +4. **Project Planning**: Create detailed user stories and sprint planning based on the roadmap +5. **Development Start**: Begin with Phase 1 foundation setup and core authentication + +## πŸ“ Documentation Updates + +This documentation is designed to be a living document that should be updated throughout the development process: + +- **Requirements Changes**: Update specifications based on stakeholder feedback +- **Technical Decisions**: Document any changes to the technology stack or architecture +- **Timeline Adjustments**: Modify roadmap based on actual development progress +- **Lessons Learned**: Add insights and best practices discovered during development + +## 🀝 Contributing + +When working on this project: + +1. **Follow the Roadmap**: Use the phased approach outlined in the development roadmap +2. **Maintain Documentation**: Keep all documentation updated with changes +3. **Security First**: Always consider HIPAA compliance and security implications +4. **Test Thoroughly**: Implement comprehensive testing at each phase +5. **User-Centric Design**: Always prioritize user experience and accessibility + +--- + +**Project Status**: Documentation Complete βœ… +**Next Phase**: Stakeholder Review and Team Assembly +**Estimated Start Date**: Based on stakeholder approval and team availability + +This comprehensive documentation package provides everything needed to successfully develop and deploy a professional physiotherapy patient management system across web and mobile platforms. \ No newline at end of file diff --git a/api-documentation.md b/api-documentation.md new file mode 100644 index 00000000..9b818456 --- /dev/null +++ b/api-documentation.md @@ -0,0 +1,973 @@ +# Physiotherapy Management System - API Documentation + +## Base URL +- **Development**: `http://localhost:3000/api` +- **Production**: `https://api.physiomanagement.com/api` + +## Authentication +All authenticated endpoints require a Bearer token in the Authorization header: +``` +Authorization: Bearer +``` + +## Response Format +All API responses follow this standard format: +```json +{ + "success": true, + "data": {}, + "message": "Success message", + "pagination": { + "page": 1, + "limit": 10, + "total": 100, + "totalPages": 10 + } +} +``` + +Error responses: +```json +{ + "success": false, + "error": { + "code": "ERROR_CODE", + "message": "Error description", + "details": {} + } +} +``` + +## Authentication Endpoints + +### POST /auth/register +Register a new user account. + +**Request Body:** +```json +{ + "email": "user@example.com", + "password": "securePassword123", + "firstName": "John", + "lastName": "Doe", + "phone": "+1234567890", + "role": "patient", + "dateOfBirth": "1990-01-01" +} +``` + +**Response:** +```json +{ + "success": true, + "data": { + "user": { + "id": "uuid", + "email": "user@example.com", + "firstName": "John", + "lastName": "Doe", + "role": "patient" + }, + "token": "jwt_token", + "refreshToken": "refresh_token" + } +} +``` + +### POST /auth/login +Authenticate user and receive access token. + +**Request Body:** +```json +{ + "email": "user@example.com", + "password": "securePassword123" +} +``` + +**Response:** +```json +{ + "success": true, + "data": { + "user": { + "id": "uuid", + "email": "user@example.com", + "firstName": "John", + "lastName": "Doe", + "role": "patient" + }, + "token": "jwt_token", + "refreshToken": "refresh_token" + } +} +``` + +### POST /auth/refresh +Refresh access token using refresh token. + +**Request Body:** +```json +{ + "refreshToken": "refresh_token" +} +``` + +### POST /auth/logout +Logout user and invalidate tokens. + +**Headers:** `Authorization: Bearer ` + +### POST /auth/forgot-password +Request password reset email. + +**Request Body:** +```json +{ + "email": "user@example.com" +} +``` + +### POST /auth/reset-password +Reset password using reset token. + +**Request Body:** +```json +{ + "token": "reset_token", + "newPassword": "newSecurePassword123" +} +``` + +## User Management Endpoints + +### GET /users/profile +Get current user's profile information. + +**Headers:** `Authorization: Bearer ` + +**Response:** +```json +{ + "success": true, + "data": { + "id": "uuid", + "email": "user@example.com", + "firstName": "John", + "lastName": "Doe", + "phone": "+1234567890", + "role": "patient", + "profilePictureUrl": "https://...", + "createdAt": "2023-01-01T00:00:00Z" + } +} +``` + +### PUT /users/profile +Update current user's profile. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "firstName": "John", + "lastName": "Doe", + "phone": "+1234567890", + "dateOfBirth": "1990-01-01" +} +``` + +### POST /users/upload-avatar +Upload profile picture. + +**Headers:** `Authorization: Bearer ` +**Content-Type:** `multipart/form-data` + +**Form Data:** +- `avatar`: Image file (JPG, PNG, max 5MB) + +## Patient Management Endpoints + +### GET /patients +Get list of patients (therapist/admin only). + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number (default: 1) +- `limit`: Items per page (default: 10) +- `search`: Search by name or email +- `therapistId`: Filter by assigned therapist + +**Response:** +```json +{ + "success": true, + "data": [ + { + "id": "uuid", + "firstName": "Jane", + "lastName": "Doe", + "email": "jane@example.com", + "phone": "+1234567890", + "insuranceProvider": "Blue Cross", + "totalSessions": 5, + "lastSessionDate": "2023-12-01T10:00:00Z" + } + ], + "pagination": { + "page": 1, + "limit": 10, + "total": 50, + "totalPages": 5 + } +} +``` + +### GET /patients/:id +Get patient details. + +**Headers:** `Authorization: Bearer ` + +**Response:** +```json +{ + "success": true, + "data": { + "id": "uuid", + "firstName": "Jane", + "lastName": "Doe", + "email": "jane@example.com", + "phone": "+1234567890", + "dateOfBirth": "1990-01-01", + "medicalHistory": "Previous knee surgery...", + "currentMedications": "Ibuprofen 400mg", + "allergies": "None known", + "emergencyContact": { + "name": "John Doe", + "phone": "+1234567891", + "relationship": "Spouse" + }, + "insurance": { + "provider": "Blue Cross", + "policyNumber": "BC123456" + }, + "address": { + "street": "123 Main St", + "city": "Anytown", + "state": "NY", + "zipCode": "12345" + } + } +} +``` + +### PUT /patients/:id +Update patient information. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "medicalHistory": "Updated medical history...", + "currentMedications": "Updated medications", + "allergies": "Penicillin", + "emergencyContactName": "John Doe", + "emergencyContactPhone": "+1234567891", + "insuranceProvider": "Blue Cross", + "insurancePolicyNumber": "BC123456" +} +``` + +### GET /patients/:id/sessions +Get patient's session history. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `startDate`: Filter sessions from date +- `endDate`: Filter sessions to date + +## Physiotherapist Management Endpoints + +### GET /physiotherapists +Get list of physiotherapists. + +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `specialization`: Filter by specialization +- `availableDate`: Check availability for specific date + +**Response:** +```json +{ + "success": true, + "data": [ + { + "id": "uuid", + "firstName": "Dr. John", + "lastName": "Smith", + "email": "dr.smith@example.com", + "specializations": ["Orthopedic", "Sports Medicine"], + "bio": "Experienced physiotherapist...", + "hourlyRate": 120.00, + "rating": 4.8, + "totalReviews": 25, + "isAcceptingPatients": true + } + ] +} +``` + +### GET /physiotherapists/:id +Get physiotherapist details. + +### GET /physiotherapists/:id/availability +Get physiotherapist availability. + +**Query Parameters:** +- `date`: Specific date (YYYY-MM-DD) +- `week`: Week starting date + +**Response:** +```json +{ + "success": true, + "data": { + "date": "2023-12-01", + "availableSlots": [ + { + "startTime": "09:00", + "endTime": "10:00", + "available": true + }, + { + "startTime": "10:00", + "endTime": "11:00", + "available": false + } + ] + } +} +``` + +## Appointment Management Endpoints + +### GET /appointments +Get appointments list. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `status`: Filter by status +- `date`: Filter by date +- `patientId`: Filter by patient (therapist/admin only) +- `therapistId`: Filter by therapist + +**Response:** +```json +{ + "success": true, + "data": [ + { + "id": "uuid", + "patientName": "Jane Doe", + "therapistName": "Dr. John Smith", + "appointmentDate": "2023-12-01T10:00:00Z", + "duration": 60, + "status": "scheduled", + "appointmentType": "Follow-up", + "notes": "Follow-up for knee rehabilitation" + } + ] +} +``` + +### POST /appointments +Create new appointment. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "therapistId": "uuid", + "appointmentDate": "2023-12-01T10:00:00Z", + "duration": 60, + "appointmentType": "Initial Assessment", + "chiefComplaint": "Lower back pain", + "notes": "Patient reports pain for 2 weeks" +} +``` + +### GET /appointments/:id +Get appointment details. + +### PUT /appointments/:id +Update appointment. + +**Request Body:** +```json +{ + "appointmentDate": "2023-12-01T11:00:00Z", + "duration": 90, + "notes": "Updated notes" +} +``` + +### DELETE /appointments/:id +Cancel appointment. + +**Request Body:** +```json +{ + "cancellationReason": "Patient requested reschedule" +} +``` + +### POST /appointments/:id/confirm +Confirm appointment (therapist only). + +### POST /appointments/:id/complete +Mark appointment as completed and create session record. + +**Request Body:** +```json +{ + "sessionNotes": { + "subjectiveNotes": "Patient reports decreased pain", + "objectiveFindings": "Improved range of motion", + "assessment": "Good progress", + "plan": "Continue current exercises", + "treatmentProvided": "Manual therapy and exercises", + "painLevelBefore": 7, + "painLevelAfter": 4 + } +} +``` + +## Session Management Endpoints + +### GET /sessions +Get sessions list. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `patientId`: Filter by patient +- `therapistId`: Filter by therapist +- `startDate`: Filter from date +- `endDate`: Filter to date + +### POST /sessions +Create session record. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "appointmentId": "uuid", + "patientId": "uuid", + "sessionDate": "2023-12-01T10:00:00Z", + "duration": 60, + "subjectiveNotes": "Patient reports improvement", + "objectiveFindings": "Increased ROM", + "assessment": "Good progress", + "plan": "Continue treatment", + "treatmentProvided": "Manual therapy", + "exercisesPrescribed": "Knee strengthening exercises", + "painLevelBefore": 6, + "painLevelAfter": 3 +} +``` + +### GET /sessions/:id +Get session details. + +### PUT /sessions/:id +Update session notes. + +### GET /sessions/stats +Get session statistics. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `period`: 'week', 'month', 'year' +- `therapistId`: Filter by therapist (admin only) + +**Response:** +```json +{ + "success": true, + "data": { + "totalSessions": 150, + "completedSessions": 140, + "cancelledSessions": 10, + "averagePainReduction": 3.2, + "patientSatisfaction": 4.7, + "revenueGenerated": 18000.00 + } +} +``` + +## Billing & Payment Endpoints + +### GET /invoices +Get invoices list. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `status`: Filter by status +- `patientId`: Filter by patient +- `dueDate`: Filter by due date + +### POST /invoices +Create invoice. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "patientId": "uuid", + "sessionId": "uuid", + "amount": 120.00, + "taxRate": 0.0875, + "description": "Physical therapy session", + "dueDate": "2023-12-31" +} +``` + +### GET /invoices/:id +Get invoice details. + +### PUT /invoices/:id +Update invoice. + +### POST /invoices/:id/send +Send invoice to patient via email. + +### POST /payments/create-intent +Create payment intent for Stripe. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "invoiceId": "uuid", + "paymentMethodId": "pm_stripe_id" +} +``` + +### POST /payments/confirm +Confirm payment. + +**Request Body:** +```json +{ + "paymentIntentId": "pi_stripe_id", + "invoiceId": "uuid" +} +``` + +### GET /payments/:id +Get payment details. + +## Video Management Endpoints + +### GET /videos +Get videos list. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `type`: Filter by video type +- `patientId`: Filter by patient +- `isPublic`: Filter public videos + +### POST /videos/upload +Upload video file. + +**Headers:** `Authorization: Bearer ` +**Content-Type:** `multipart/form-data` + +**Form Data:** +- `video`: Video file (MP4, MOV, AVI, max 500MB) +- `title`: Video title +- `description`: Video description +- `type`: Video type ('initial_assessment', 'treatment', 'exercise', 'progress') +- `patientId`: Associated patient ID (optional) +- `tags`: Comma-separated tags + +### GET /videos/:id +Get video details. + +### PUT /videos/:id +Update video metadata. + +**Request Body:** +```json +{ + "title": "Updated title", + "description": "Updated description", + "tags": ["exercise", "knee", "rehabilitation"], + "isPublic": false +} +``` + +### DELETE /videos/:id +Delete video. + +### GET /videos/:id/stream +Stream video content. + +**Query Parameters:** +- `quality`: Video quality ('720p', '480p', '360p') + +## Exercise Library Endpoints + +### GET /exercises +Get exercises library. + +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `category`: Filter by category +- `bodyPart`: Filter by body part +- `difficulty`: Filter by difficulty level + +**Response:** +```json +{ + "success": true, + "data": [ + { + "id": "uuid", + "name": "Knee Extension", + "description": "Strengthen quadriceps muscles", + "category": "Strength", + "bodyPart": "Knee", + "difficulty": 2, + "duration": 15, + "repetitions": 10, + "sets": 3, + "equipmentNeeded": ["Resistance band"], + "videoUrl": "https://...", + "imageUrl": "https://..." + } + ] +} +``` + +### POST /exercises +Create new exercise (therapist only). + +### GET /exercises/:id +Get exercise details. + +### PUT /exercises/:id +Update exercise. + +### DELETE /exercises/:id +Delete exercise. + +### POST /exercises/:id/assign +Assign exercise to patient. + +**Request Body:** +```json +{ + "patientId": "uuid", + "targetRepetitions": 10, + "targetSets": 3, + "targetFrequency": "Daily", + "specialInstructions": "Start with low resistance" +} +``` + +### GET /patients/:patientId/exercises +Get patient's assigned exercises. + +### POST /exercises/completion +Record exercise completion. + +**Request Body:** +```json +{ + "patientExerciseId": "uuid", + "repetitionsCompleted": 10, + "setsCompleted": 3, + "duration": 15, + "painLevelBefore": 5, + "painLevelAfter": 3, + "difficultyRating": 3, + "notes": "Felt good today" +} +``` + +## Notification Endpoints + +### GET /notifications +Get user notifications. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `isRead`: Filter by read status + +### PUT /notifications/:id/read +Mark notification as read. + +### POST /notifications/preferences +Update notification preferences. + +**Request Body:** +```json +{ + "emailNotifications": true, + "pushNotifications": true, + "smsNotifications": false, + "appointmentReminders": true, + "paymentReminders": true +} +``` + +## Communication Endpoints + +### GET /messages +Get messages. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `page`: Page number +- `limit`: Items per page +- `conversationWith`: Filter by conversation partner + +### POST /messages +Send message. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "recipientId": "uuid", + "subject": "Question about exercises", + "messageText": "I have a question about the knee exercises...", + "parentMessageId": "uuid" +} +``` + +### GET /messages/:id +Get message details. + +### PUT /messages/:id/read +Mark message as read. + +## Review & Rating Endpoints + +### GET /reviews +Get reviews. + +**Query Parameters:** +- `therapistId`: Filter by therapist +- `page`: Page number +- `limit`: Items per page + +### POST /reviews +Create review. + +**Headers:** `Authorization: Bearer ` + +**Request Body:** +```json +{ + "therapistId": "uuid", + "sessionId": "uuid", + "rating": 5, + "reviewText": "Excellent service and care", + "isAnonymous": false +} +``` + +## Analytics & Reporting Endpoints + +### GET /analytics/dashboard +Get dashboard analytics. + +**Headers:** `Authorization: Bearer ` +**Query Parameters:** +- `period`: 'week', 'month', 'quarter', 'year' + +**Response:** +```json +{ + "success": true, + "data": { + "totalPatients": 150, + "totalSessions": 1200, + "totalRevenue": 144000.00, + "averageRating": 4.8, + "sessionCompletionRate": 0.95, + "patientRetentionRate": 0.85, + "monthlyGrowth": 0.12 + } +} +``` + +### GET /analytics/revenue +Get revenue analytics. + +### GET /analytics/patients +Get patient analytics. + +### GET /analytics/sessions +Get session analytics. + +## System Settings Endpoints + +### GET /settings +Get system settings (admin only). + +### PUT /settings +Update system settings (admin only). + +**Request Body:** +```json +{ + "appointmentDurationDefault": 60, + "businessHoursStart": "08:00", + "businessHoursEnd": "18:00", + "taxRate": 0.0875 +} +``` + +## Error Codes + +| Code | Description | +|------|-------------| +| `VALIDATION_ERROR` | Request validation failed | +| `AUTHENTICATION_REQUIRED` | Authentication token required | +| `INVALID_CREDENTIALS` | Invalid email or password | +| `INSUFFICIENT_PERMISSIONS` | User lacks required permissions | +| `RESOURCE_NOT_FOUND` | Requested resource not found | +| `RESOURCE_CONFLICT` | Resource conflict (e.g., duplicate email) | +| `RATE_LIMIT_EXCEEDED` | Too many requests | +| `FILE_TOO_LARGE` | Uploaded file exceeds size limit | +| `INVALID_FILE_TYPE` | Unsupported file type | +| `PAYMENT_FAILED` | Payment processing failed | +| `APPOINTMENT_CONFLICT` | Appointment time conflict | +| `INTERNAL_SERVER_ERROR` | Server error | + +## Rate Limiting + +API endpoints are rate limited to prevent abuse: +- **Authentication endpoints**: 5 requests per minute +- **File upload endpoints**: 10 requests per hour +- **General endpoints**: 100 requests per minute +- **Public endpoints**: 1000 requests per hour + +Rate limit headers are included in responses: +``` +X-RateLimit-Limit: 100 +X-RateLimit-Remaining: 95 +X-RateLimit-Reset: 1640995200 +``` + +## Webhooks + +The system supports webhooks for real-time notifications: + +### Payment Events +- `payment.succeeded` +- `payment.failed` +- `invoice.payment_succeeded` + +### Appointment Events +- `appointment.created` +- `appointment.updated` +- `appointment.cancelled` +- `appointment.completed` + +### Webhook Payload Example +```json +{ + "id": "evt_uuid", + "type": "appointment.created", + "created": 1640995200, + "data": { + "object": { + "id": "uuid", + "patientId": "uuid", + "therapistId": "uuid", + "appointmentDate": "2023-12-01T10:00:00Z", + "status": "scheduled" + } + } +} +``` + +## SDK Examples + +### JavaScript/TypeScript +```javascript +import { PhysioAPI } from '@physio/api-client'; + +const api = new PhysioAPI({ + baseURL: 'https://api.physiomanagement.com/api', + apiKey: 'your-api-key' +}); + +// Get appointments +const appointments = await api.appointments.list({ + page: 1, + limit: 10, + status: 'scheduled' +}); + +// Create appointment +const newAppointment = await api.appointments.create({ + therapistId: 'uuid', + appointmentDate: '2023-12-01T10:00:00Z', + duration: 60, + appointmentType: 'Initial Assessment' +}); +``` + +### Python +```python +from physio_api import PhysioClient + +client = PhysioClient( + base_url='https://api.physiomanagement.com/api', + api_key='your-api-key' +) + +# Get appointments +appointments = client.appointments.list( + page=1, + limit=10, + status='scheduled' +) + +# Create appointment +new_appointment = client.appointments.create({ + 'therapist_id': 'uuid', + 'appointment_date': '2023-12-01T10:00:00Z', + 'duration': 60, + 'appointment_type': 'Initial Assessment' +}) +``` + +This API documentation provides comprehensive coverage of all endpoints needed for the physiotherapy management system, including authentication, patient management, appointments, billing, video handling, and more. \ No newline at end of file diff --git a/database-schema.sql b/database-schema.sql new file mode 100644 index 00000000..a288908d --- /dev/null +++ b/database-schema.sql @@ -0,0 +1,488 @@ +-- Physiotherapy Management System Database Schema +-- PostgreSQL 15+ compatible + +-- Enable UUID extension +CREATE EXTENSION IF NOT EXISTS "pgcrypto"; + +-- Create custom types +CREATE TYPE user_role AS ENUM ('patient', 'physiotherapist', 'admin'); +CREATE TYPE appointment_status AS ENUM ('scheduled', 'confirmed', 'completed', 'cancelled', 'no_show'); +CREATE TYPE invoice_status AS ENUM ('pending', 'paid', 'overdue', 'cancelled'); +CREATE TYPE video_type AS ENUM ('initial_assessment', 'treatment', 'exercise', 'progress'); +CREATE TYPE notification_type AS ENUM ('appointment_reminder', 'payment_due', 'session_completed', 'video_uploaded', 'system'); + +-- Users table (base table for all system users) +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(255) UNIQUE NOT NULL, + password_hash VARCHAR(255) NOT NULL, + role user_role NOT NULL, + first_name VARCHAR(100) NOT NULL, + last_name VARCHAR(100) NOT NULL, + phone VARCHAR(20), + date_of_birth DATE, + profile_picture_url VARCHAR(500), + is_active BOOLEAN DEFAULT TRUE, + email_verified BOOLEAN DEFAULT FALSE, + last_login TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Patients table (extends users for patient-specific data) +CREATE TABLE patients ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID UNIQUE REFERENCES users(id) ON DELETE CASCADE, + medical_history TEXT, + current_medications TEXT, + allergies TEXT, + emergency_contact_name VARCHAR(100), + emergency_contact_phone VARCHAR(20), + emergency_contact_relationship VARCHAR(50), + insurance_provider VARCHAR(100), + insurance_policy_number VARCHAR(50), + address TEXT, + city VARCHAR(100), + state VARCHAR(50), + zip_code VARCHAR(20), + country VARCHAR(50) DEFAULT 'USA', + preferred_language VARCHAR(20) DEFAULT 'English', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Physiotherapists table (extends users for therapist-specific data) +CREATE TABLE physiotherapists ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID UNIQUE REFERENCES users(id) ON DELETE CASCADE, + license_number VARCHAR(50) UNIQUE NOT NULL, + license_expiry_date DATE, + specializations TEXT[], + bio TEXT, + education TEXT, + certifications TEXT[], + years_of_experience INTEGER, + hourly_rate DECIMAL(10,2), + availability_schedule JSONB, -- Store weekly schedule as JSON + is_accepting_patients BOOLEAN DEFAULT TRUE, + rating DECIMAL(3,2) DEFAULT 0.00, + total_reviews INTEGER DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Appointments table +CREATE TABLE appointments ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + patient_id UUID NOT NULL REFERENCES patients(id) ON DELETE CASCADE, + physiotherapist_id UUID NOT NULL REFERENCES physiotherapists(id) ON DELETE CASCADE, + appointment_date TIMESTAMP NOT NULL, + duration_minutes INTEGER DEFAULT 60, + status appointment_status DEFAULT 'scheduled', + appointment_type VARCHAR(100), -- e.g., 'Initial Assessment', 'Follow-up', 'Maintenance' + chief_complaint TEXT, + notes TEXT, + cancellation_reason TEXT, + cancelled_by UUID REFERENCES users(id), + cancelled_at TIMESTAMP, + confirmed_at TIMESTAMP, + reminder_sent BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Sessions table (records of completed appointments) +CREATE TABLE sessions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + appointment_id UUID UNIQUE REFERENCES appointments(id) ON DELETE CASCADE, + patient_id UUID NOT NULL REFERENCES patients(id) ON DELETE CASCADE, + physiotherapist_id UUID NOT NULL REFERENCES physiotherapists(id) ON DELETE CASCADE, + session_date TIMESTAMP NOT NULL, + duration_minutes INTEGER NOT NULL, + session_number INTEGER, -- Track session count for the patient + subjective_notes TEXT, -- Patient's reported symptoms/progress + objective_findings TEXT, -- Therapist's observations and measurements + assessment TEXT, -- Clinical assessment and diagnosis + plan TEXT, -- Treatment plan and next steps + treatment_provided TEXT, + exercises_prescribed TEXT, + home_program TEXT, + progress_notes TEXT, + pain_level_before INTEGER CHECK (pain_level_before >= 0 AND pain_level_before <= 10), + pain_level_after INTEGER CHECK (pain_level_after >= 0 AND pain_level_after <= 10), + functional_improvement TEXT, + next_session_recommendations TEXT, + goals_achieved TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Invoices table +CREATE TABLE invoices ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + invoice_number VARCHAR(50) UNIQUE NOT NULL, + patient_id UUID NOT NULL REFERENCES patients(id) ON DELETE CASCADE, + session_id UUID REFERENCES sessions(id) ON DELETE SET NULL, + physiotherapist_id UUID NOT NULL REFERENCES physiotherapists(id) ON DELETE CASCADE, + amount DECIMAL(10,2) NOT NULL, + tax_rate DECIMAL(5,4) DEFAULT 0.0000, + tax_amount DECIMAL(10,2) DEFAULT 0, + discount_amount DECIMAL(10,2) DEFAULT 0, + total_amount DECIMAL(10,2) NOT NULL, + status invoice_status DEFAULT 'pending', + description TEXT, + due_date DATE NOT NULL, + issued_date DATE DEFAULT CURRENT_DATE, + paid_at TIMESTAMP, + payment_method VARCHAR(50), + transaction_id VARCHAR(100), + stripe_payment_intent_id VARCHAR(100), + notes TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Videos table +CREATE TABLE videos ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + uploader_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + patient_id UUID REFERENCES patients(id) ON DELETE CASCADE, + session_id UUID REFERENCES sessions(id) ON DELETE SET NULL, + title VARCHAR(255) NOT NULL, + description TEXT, + file_url VARCHAR(500) NOT NULL, + thumbnail_url VARCHAR(500), + file_name VARCHAR(255), + file_size BIGINT, + duration_seconds INTEGER, + video_type video_type NOT NULL, + tags TEXT[], + is_public BOOLEAN DEFAULT FALSE, + is_processed BOOLEAN DEFAULT FALSE, + processing_status VARCHAR(50) DEFAULT 'pending', -- pending, processing, completed, failed + view_count INTEGER DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Exercise library table +CREATE TABLE exercises ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + description TEXT, + instructions TEXT, + category VARCHAR(100), -- e.g., 'Strength', 'Flexibility', 'Balance' + body_part VARCHAR(100), -- e.g., 'Lower Back', 'Shoulder', 'Knee' + difficulty_level INTEGER CHECK (difficulty_level >= 1 AND difficulty_level <= 5), + duration_minutes INTEGER, + repetitions INTEGER, + sets INTEGER, + equipment_needed TEXT[], + contraindications TEXT, + video_url VARCHAR(500), + image_url VARCHAR(500), + created_by UUID REFERENCES physiotherapists(id), + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Patient exercise assignments +CREATE TABLE patient_exercises ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + patient_id UUID NOT NULL REFERENCES patients(id) ON DELETE CASCADE, + exercise_id UUID NOT NULL REFERENCES exercises(id) ON DELETE CASCADE, + session_id UUID REFERENCES sessions(id) ON DELETE SET NULL, + assigned_by UUID NOT NULL REFERENCES physiotherapists(id) ON DELETE CASCADE, + assigned_date DATE DEFAULT CURRENT_DATE, + target_repetitions INTEGER, + target_sets INTEGER, + target_frequency VARCHAR(50), -- e.g., 'Daily', '3x per week' + special_instructions TEXT, + is_active BOOLEAN DEFAULT TRUE, + completed_sessions INTEGER DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Exercise completion tracking +CREATE TABLE exercise_completions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + patient_exercise_id UUID NOT NULL REFERENCES patient_exercises(id) ON DELETE CASCADE, + completion_date DATE DEFAULT CURRENT_DATE, + repetitions_completed INTEGER, + sets_completed INTEGER, + duration_minutes INTEGER, + pain_level_before INTEGER CHECK (pain_level_before >= 0 AND pain_level_before <= 10), + pain_level_after INTEGER CHECK (pain_level_after >= 0 AND pain_level_after <= 10), + difficulty_rating INTEGER CHECK (difficulty_rating >= 1 AND difficulty_rating <= 5), + notes TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Notifications table +CREATE TABLE notifications ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + type notification_type NOT NULL, + title VARCHAR(255) NOT NULL, + message TEXT NOT NULL, + related_id UUID, -- Can reference appointment, session, invoice, etc. + is_read BOOLEAN DEFAULT FALSE, + is_sent BOOLEAN DEFAULT FALSE, + send_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + read_at TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Reviews and ratings table +CREATE TABLE reviews ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + patient_id UUID NOT NULL REFERENCES patients(id) ON DELETE CASCADE, + physiotherapist_id UUID NOT NULL REFERENCES physiotherapists(id) ON DELETE CASCADE, + session_id UUID REFERENCES sessions(id) ON DELETE SET NULL, + rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5), + review_text TEXT, + is_anonymous BOOLEAN DEFAULT FALSE, + is_approved BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(patient_id, session_id) -- One review per session +); + +-- Messages table for in-app communication +CREATE TABLE messages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + recipient_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + subject VARCHAR(255), + message_text TEXT NOT NULL, + is_read BOOLEAN DEFAULT FALSE, + read_at TIMESTAMP, + parent_message_id UUID REFERENCES messages(id) ON DELETE SET NULL, + attachment_url VARCHAR(500), + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- System settings table +CREATE TABLE system_settings ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + setting_key VARCHAR(100) UNIQUE NOT NULL, + setting_value TEXT, + description TEXT, + is_public BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Audit log table for tracking changes +CREATE TABLE audit_logs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(id) ON DELETE SET NULL, + table_name VARCHAR(100) NOT NULL, + record_id UUID NOT NULL, + action VARCHAR(20) NOT NULL, -- INSERT, UPDATE, DELETE + old_values JSONB, + new_values JSONB, + ip_address INET, + user_agent TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Create indexes for better performance +CREATE INDEX idx_users_email ON users(email); +CREATE INDEX idx_users_role ON users(role); +CREATE INDEX idx_appointments_patient_id ON appointments(patient_id); +CREATE INDEX idx_appointments_physiotherapist_id ON appointments(physiotherapist_id); +CREATE INDEX idx_appointments_date ON appointments(appointment_date); +CREATE INDEX idx_appointments_status ON appointments(status); +CREATE INDEX idx_sessions_patient_id ON sessions(patient_id); +CREATE INDEX idx_sessions_physiotherapist_id ON sessions(physiotherapist_id); +CREATE INDEX idx_sessions_date ON sessions(session_date); +CREATE INDEX idx_invoices_patient_id ON invoices(patient_id); +CREATE INDEX idx_invoices_status ON invoices(status); +CREATE INDEX idx_invoices_due_date ON invoices(due_date); +CREATE INDEX idx_videos_patient_id ON videos(patient_id); +CREATE INDEX idx_videos_uploader_id ON videos(uploader_id); +CREATE INDEX idx_videos_type ON videos(video_type); +CREATE INDEX idx_notifications_user_id ON notifications(user_id); +CREATE INDEX idx_notifications_is_read ON notifications(is_read); +CREATE INDEX idx_messages_sender_id ON messages(sender_id); +CREATE INDEX idx_messages_recipient_id ON messages(recipient_id); +CREATE INDEX idx_audit_logs_table_record ON audit_logs(table_name, record_id); + +-- Create triggers for updated_at timestamps +CREATE OR REPLACE FUNCTION update_updated_at_column() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ language 'plpgsql'; + +CREATE TRIGGER update_users_updated_at BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_patients_updated_at BEFORE UPDATE ON patients FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_physiotherapists_updated_at BEFORE UPDATE ON physiotherapists FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_appointments_updated_at BEFORE UPDATE ON appointments FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_sessions_updated_at BEFORE UPDATE ON sessions FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_invoices_updated_at BEFORE UPDATE ON invoices FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_videos_updated_at BEFORE UPDATE ON videos FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_exercises_updated_at BEFORE UPDATE ON exercises FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_patient_exercises_updated_at BEFORE UPDATE ON patient_exercises FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_reviews_updated_at BEFORE UPDATE ON reviews FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +CREATE TRIGGER update_system_settings_updated_at BEFORE UPDATE ON system_settings FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); + +-- Function to automatically update physiotherapist ratings +CREATE OR REPLACE FUNCTION update_physiotherapist_rating() +RETURNS TRIGGER AS $$ +BEGIN + UPDATE physiotherapists + SET + rating = ( + SELECT COALESCE(AVG(rating::DECIMAL), 0.00) + FROM reviews + WHERE physiotherapist_id = NEW.physiotherapist_id + AND is_approved = TRUE + ), + total_reviews = ( + SELECT COUNT(*) + FROM reviews + WHERE physiotherapist_id = NEW.physiotherapist_id + AND is_approved = TRUE + ) + WHERE id = NEW.physiotherapist_id; + RETURN NEW; +END; +$$ language 'plpgsql'; + +CREATE TRIGGER update_physiotherapist_rating_trigger + AFTER INSERT OR UPDATE ON reviews + FOR EACH ROW + EXECUTE FUNCTION update_physiotherapist_rating(); + +-- Function to generate invoice numbers +CREATE OR REPLACE FUNCTION generate_invoice_number() +RETURNS TRIGGER AS $$ +BEGIN + IF NEW.invoice_number IS NULL THEN + NEW.invoice_number := 'INV-' || TO_CHAR(CURRENT_DATE, 'YYYY') || '-' || + LPAD(NEXTVAL('invoice_number_seq')::TEXT, 6, '0'); + END IF; + RETURN NEW; +END; +$$ language 'plpgsql'; + +-- Create sequence for invoice numbers +CREATE SEQUENCE invoice_number_seq START 1; + +CREATE TRIGGER generate_invoice_number_trigger + BEFORE INSERT ON invoices + FOR EACH ROW + EXECUTE FUNCTION generate_invoice_number(); + +-- Insert default system settings +INSERT INTO system_settings (setting_key, setting_value, description, is_public) VALUES +('appointment_duration_default', '60', 'Default appointment duration in minutes', TRUE), +('appointment_buffer_time', '15', 'Buffer time between appointments in minutes', TRUE), +('business_hours_start', '08:00', 'Business hours start time', TRUE), +('business_hours_end', '18:00', 'Business hours end time', TRUE), +('working_days', '["monday", "tuesday", "wednesday", "thursday", "friday"]', 'Working days of the week', TRUE), +('timezone', 'America/New_York', 'System timezone', TRUE), +('currency', 'USD', 'System currency', TRUE), +('tax_rate', '0.0875', 'Default tax rate (8.75%)', FALSE), +('late_fee_percentage', '0.05', 'Late fee percentage (5%)', FALSE), +('payment_terms_days', '30', 'Payment terms in days', TRUE), +('max_video_size_mb', '500', 'Maximum video file size in MB', TRUE), +('allowed_video_formats', '["mp4", "mov", "avi", "wmv"]', 'Allowed video file formats', TRUE), +('session_reminder_hours', '24', 'Hours before appointment to send reminder', TRUE), +('payment_reminder_days', '7', 'Days before due date to send payment reminder', TRUE); + +-- Create views for common queries +CREATE VIEW patient_summary AS +SELECT + p.id, + u.first_name, + u.last_name, + u.email, + u.phone, + p.insurance_provider, + COUNT(DISTINCT s.id) as total_sessions, + COUNT(DISTINCT a.id) as total_appointments, + COALESCE(SUM(i.total_amount), 0) as total_billed, + COALESCE(SUM(CASE WHEN i.status = 'paid' THEN i.total_amount ELSE 0 END), 0) as total_paid, + MAX(s.session_date) as last_session_date +FROM patients p +JOIN users u ON p.user_id = u.id +LEFT JOIN sessions s ON p.id = s.patient_id +LEFT JOIN appointments a ON p.id = a.patient_id +LEFT JOIN invoices i ON p.id = i.patient_id +GROUP BY p.id, u.first_name, u.last_name, u.email, u.phone, p.insurance_provider; + +CREATE VIEW therapist_summary AS +SELECT + pt.id, + u.first_name, + u.last_name, + u.email, + u.phone, + pt.specializations, + pt.hourly_rate, + pt.rating, + pt.total_reviews, + COUNT(DISTINCT s.id) as total_sessions, + COUNT(DISTINCT CASE WHEN a.appointment_date >= CURRENT_DATE THEN a.id END) as upcoming_appointments, + COALESCE(SUM(i.total_amount), 0) as total_revenue +FROM physiotherapists pt +JOIN users u ON pt.user_id = u.id +LEFT JOIN sessions s ON pt.id = s.physiotherapist_id +LEFT JOIN appointments a ON pt.id = a.physiotherapist_id +LEFT JOIN invoices i ON pt.id = i.physiotherapist_id +GROUP BY pt.id, u.first_name, u.last_name, u.email, u.phone, pt.specializations, pt.hourly_rate, pt.rating, pt.total_reviews; + +-- Create a view for appointment calendar +CREATE VIEW appointment_calendar AS +SELECT + a.id, + a.appointment_date, + a.duration_minutes, + a.status, + a.appointment_type, + CONCAT(pu.first_name, ' ', pu.last_name) as patient_name, + CONCAT(tu.first_name, ' ', tu.last_name) as therapist_name, + pu.phone as patient_phone, + tu.phone as therapist_phone, + a.notes +FROM appointments a +JOIN patients p ON a.patient_id = p.id +JOIN users pu ON p.user_id = pu.id +JOIN physiotherapists pt ON a.physiotherapist_id = pt.id +JOIN users tu ON pt.user_id = tu.id +ORDER BY a.appointment_date; + +-- Sample data (optional - for development/testing) +-- Uncomment the following lines to insert sample data + +/* +-- Insert sample admin user +INSERT INTO users (email, password_hash, role, first_name, last_name, phone) VALUES +('admin@physio.com', '$2b$10$example_hash', 'admin', 'Admin', 'User', '+1234567890'); + +-- Insert sample physiotherapist +INSERT INTO users (email, password_hash, role, first_name, last_name, phone, date_of_birth) VALUES +('dr.smith@physio.com', '$2b$10$example_hash', 'physiotherapist', 'John', 'Smith', '+1234567891', '1980-05-15'); + +INSERT INTO physiotherapists (user_id, license_number, specializations, bio, hourly_rate) VALUES +((SELECT id FROM users WHERE email = 'dr.smith@physio.com'), 'PT12345', + ARRAY['Orthopedic', 'Sports Medicine'], + 'Experienced physiotherapist specializing in sports injuries and orthopedic rehabilitation.', + 120.00); + +-- Insert sample patient +INSERT INTO users (email, password_hash, role, first_name, last_name, phone, date_of_birth) VALUES +('patient@example.com', '$2b$10$example_hash', 'patient', 'Jane', 'Doe', '+1234567892', '1990-08-22'); + +INSERT INTO patients (user_id, medical_history, emergency_contact_name, emergency_contact_phone, address) VALUES +((SELECT id FROM users WHERE email = 'patient@example.com'), + 'Previous knee surgery in 2020. No known allergies.', + 'John Doe', '+1234567893', '123 Main St, Anytown, NY 12345'); +*/ \ No newline at end of file diff --git a/deployment-guide.md b/deployment-guide.md new file mode 100644 index 00000000..6d7739a7 --- /dev/null +++ b/deployment-guide.md @@ -0,0 +1,1195 @@ +# Physiotherapy Management System - Deployment Guide + +## Overview + +This guide provides step-by-step instructions for deploying the physiotherapy management system across different environments (development, staging, and production) using various cloud providers and deployment strategies. + +## Prerequisites + +### System Requirements +- **Node.js**: 18.x or higher +- **PostgreSQL**: 15.x or higher +- **Redis**: 7.x or higher +- **Docker**: 20.x or higher (optional but recommended) +- **Git**: Latest version + +### Cloud Services +- **AWS Account** (recommended) or **Google Cloud Platform** or **DigitalOcean** +- **Domain name** for production deployment +- **SSL Certificate** (Let's Encrypt recommended) +- **CDN Service** (CloudFlare recommended) + +## Environment Setup + +### 1. Development Environment + +#### Local Setup with Docker Compose + +Create `docker-compose.yml`: +```yaml +version: '3.8' + +services: + postgres: + image: postgres:15-alpine + environment: + POSTGRES_DB: physio_dev + POSTGRES_USER: physio_user + POSTGRES_PASSWORD: physio_password + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./database-schema.sql:/docker-entrypoint-initdb.d/init.sql + + redis: + image: redis:7-alpine + ports: + - "6379:6379" + command: redis-server --appendonly yes + volumes: + - redis_data:/data + + api: + build: ./backend + ports: + - "3000:3000" + environment: + - NODE_ENV=development + - DATABASE_URL=postgresql://physio_user:physio_password@postgres:5432/physio_dev + - REDIS_URL=redis://redis:6379 + - JWT_SECRET=your-jwt-secret-key + - STRIPE_SECRET_KEY=sk_test_your_stripe_key + - AWS_ACCESS_KEY_ID=your-aws-key + - AWS_SECRET_ACCESS_KEY=your-aws-secret + - S3_BUCKET_NAME=physio-dev-uploads + depends_on: + - postgres + - redis + volumes: + - ./backend:/app + - /app/node_modules + + web: + build: ./frontend + ports: + - "3001:3000" + environment: + - REACT_APP_API_URL=http://localhost:3000/api + - REACT_APP_STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_key + volumes: + - ./frontend:/app + - /app/node_modules + +volumes: + postgres_data: + redis_data: +``` + +#### Start Development Environment +```bash +# Clone the repository +git clone https://github.com/your-org/physio-management-system.git +cd physio-management-system + +# Start services +docker-compose up -d + +# Install dependencies (if not using Docker) +cd backend && npm install +cd ../frontend && npm install + +# Run migrations +npm run migrate + +# Seed development data +npm run seed:dev +``` + +### 2. Production Environment Setup + +## AWS Deployment (Recommended) + +### Infrastructure Setup with Terraform + +Create `infrastructure/main.tf`: +```hcl +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" + } + } +} + +provider "aws" { + region = var.aws_region +} + +# VPC Configuration +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" + enable_dns_hostnames = true + enable_dns_support = true + + tags = { + Name = "physio-vpc" + } +} + +# Subnets +resource "aws_subnet" "public" { + count = 2 + vpc_id = aws_vpc.main.id + cidr_block = "10.0.${count.index + 1}.0/24" + availability_zone = data.aws_availability_zones.available.names[count.index] + + map_public_ip_on_launch = true + + tags = { + Name = "physio-public-subnet-${count.index + 1}" + } +} + +resource "aws_subnet" "private" { + count = 2 + vpc_id = aws_vpc.main.id + cidr_block = "10.0.${count.index + 10}.0/24" + availability_zone = data.aws_availability_zones.available.names[count.index] + + tags = { + Name = "physio-private-subnet-${count.index + 1}" + } +} + +# RDS Instance +resource "aws_db_instance" "postgres" { + identifier = "physio-postgres" + engine = "postgres" + engine_version = "15.4" + instance_class = "db.t3.micro" + + allocated_storage = 20 + max_allocated_storage = 100 + storage_encrypted = true + + db_name = "physio_prod" + username = var.db_username + password = var.db_password + + vpc_security_group_ids = [aws_security_group.rds.id] + db_subnet_group_name = aws_db_subnet_group.main.name + + backup_retention_period = 7 + backup_window = "03:00-04:00" + maintenance_window = "sun:04:00-sun:05:00" + + skip_final_snapshot = false + final_snapshot_identifier = "physio-postgres-final-snapshot" + + tags = { + Name = "physio-postgres" + } +} + +# ElastiCache Redis +resource "aws_elasticache_subnet_group" "main" { + name = "physio-cache-subnet" + subnet_ids = aws_subnet.private[*].id +} + +resource "aws_elasticache_cluster" "redis" { + cluster_id = "physio-redis" + engine = "redis" + node_type = "cache.t3.micro" + num_cache_nodes = 1 + parameter_group_name = "default.redis7" + port = 6379 + subnet_group_name = aws_elasticache_subnet_group.main.name + security_group_ids = [aws_security_group.redis.id] +} + +# ECS Cluster +resource "aws_ecs_cluster" "main" { + name = "physio-cluster" + + setting { + name = "containerInsights" + value = "enabled" + } +} + +# Application Load Balancer +resource "aws_lb" "main" { + name = "physio-alb" + internal = false + load_balancer_type = "application" + security_groups = [aws_security_group.alb.id] + subnets = aws_subnet.public[*].id + + enable_deletion_protection = false + + tags = { + Name = "physio-alb" + } +} + +# S3 Bucket for file uploads +resource "aws_s3_bucket" "uploads" { + bucket = "physio-uploads-${random_string.bucket_suffix.result}" +} + +resource "aws_s3_bucket_versioning" "uploads" { + bucket = aws_s3_bucket.uploads.id + versioning_configuration { + status = "Enabled" + } +} + +resource "aws_s3_bucket_encryption" "uploads" { + bucket = aws_s3_bucket.uploads.id + + server_side_encryption_configuration { + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } + } +} + +# CloudFront Distribution +resource "aws_cloudfront_distribution" "main" { + origin { + domain_name = aws_lb.main.dns_name + origin_id = "physio-alb" + + custom_origin_config { + http_port = 80 + https_port = 443 + origin_protocol_policy = "https-only" + origin_ssl_protocols = ["TLSv1.2"] + } + } + + enabled = true + is_ipv6_enabled = true + default_root_object = "index.html" + + default_cache_behavior { + allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] + cached_methods = ["GET", "HEAD"] + target_origin_id = "physio-alb" + + forwarded_values { + query_string = false + cookies { + forward = "none" + } + } + + viewer_protocol_policy = "redirect-to-https" + min_ttl = 0 + default_ttl = 3600 + max_ttl = 86400 + } + + restrictions { + geo_restriction { + restriction_type = "none" + } + } + + viewer_certificate { + cloudfront_default_certificate = true + } +} +``` + +### ECS Task Definitions + +Create `infrastructure/ecs-tasks.tf`: +```hcl +# Backend Task Definition +resource "aws_ecs_task_definition" "backend" { + family = "physio-backend" + requires_compatibilities = ["FARGATE"] + network_mode = "awsvpc" + cpu = 512 + memory = 1024 + execution_role_arn = aws_iam_role.ecs_execution.arn + task_role_arn = aws_iam_role.ecs_task.arn + + container_definitions = jsonencode([ + { + name = "backend" + image = "${aws_ecr_repository.backend.repository_url}:latest" + + portMappings = [ + { + containerPort = 3000 + protocol = "tcp" + } + ] + + environment = [ + { + name = "NODE_ENV" + value = "production" + }, + { + name = "PORT" + value = "3000" + } + ] + + secrets = [ + { + name = "DATABASE_URL" + valueFrom = aws_ssm_parameter.database_url.arn + }, + { + name = "REDIS_URL" + valueFrom = aws_ssm_parameter.redis_url.arn + }, + { + name = "JWT_SECRET" + valueFrom = aws_ssm_parameter.jwt_secret.arn + }, + { + name = "STRIPE_SECRET_KEY" + valueFrom = aws_ssm_parameter.stripe_secret.arn + } + ] + + logConfiguration = { + logDriver = "awslogs" + options = { + awslogs-group = aws_cloudwatch_log_group.backend.name + awslogs-region = var.aws_region + awslogs-stream-prefix = "ecs" + } + } + + healthCheck = { + command = ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"] + interval = 30 + timeout = 5 + retries = 3 + startPeriod = 60 + } + } + ]) +} + +# Frontend Task Definition +resource "aws_ecs_task_definition" "frontend" { + family = "physio-frontend" + requires_compatibilities = ["FARGATE"] + network_mode = "awsvpc" + cpu = 256 + memory = 512 + execution_role_arn = aws_iam_role.ecs_execution.arn + + container_definitions = jsonencode([ + { + name = "frontend" + image = "${aws_ecr_repository.frontend.repository_url}:latest" + + portMappings = [ + { + containerPort = 80 + protocol = "tcp" + } + ] + + logConfiguration = { + logDriver = "awslogs" + options = { + awslogs-group = aws_cloudwatch_log_group.frontend.name + awslogs-region = var.aws_region + awslogs-stream-prefix = "ecs" + } + } + } + ]) +} +``` + +### Deployment Scripts + +Create `scripts/deploy.sh`: +```bash +#!/bin/bash + +set -e + +# Configuration +AWS_REGION="us-east-1" +CLUSTER_NAME="physio-cluster" +BACKEND_SERVICE="physio-backend" +FRONTEND_SERVICE="physio-frontend" +BACKEND_REPO="physio-backend" +FRONTEND_REPO="physio-frontend" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +echo_info() { + echo -e "${GREEN}[INFO]${NC} $1" +} + +echo_warn() { + echo -e "${YELLOW}[WARN]${NC} $1" +} + +echo_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# Check prerequisites +check_prerequisites() { + echo_info "Checking prerequisites..." + + if ! command -v aws &> /dev/null; then + echo_error "AWS CLI is not installed" + exit 1 + fi + + if ! command -v docker &> /dev/null; then + echo_error "Docker is not installed" + exit 1 + fi + + if ! command -v terraform &> /dev/null; then + echo_error "Terraform is not installed" + exit 1 + fi + + echo_info "Prerequisites check passed" +} + +# Build and push Docker images +build_and_push() { + echo_info "Building and pushing Docker images..." + + # Get ECR login token + aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $(aws sts get-caller-identity --query Account --output text).dkr.ecr.$AWS_REGION.amazonaws.com + + # Build and push backend + echo_info "Building backend image..." + cd backend + docker build -t $BACKEND_REPO . + docker tag $BACKEND_REPO:latest $(aws sts get-caller-identity --query Account --output text).dkr.ecr.$AWS_REGION.amazonaws.com/$BACKEND_REPO:latest + docker push $(aws sts get-caller-identity --query Account --output text).dkr.ecr.$AWS_REGION.amazonaws.com/$BACKEND_REPO:latest + cd .. + + # Build and push frontend + echo_info "Building frontend image..." + cd frontend + docker build -t $FRONTEND_REPO . + docker tag $FRONTEND_REPO:latest $(aws sts get-caller-identity --query Account --output text).dkr.ecr.$AWS_REGION.amazonaws.com/$FRONTEND_REPO:latest + docker push $(aws sts get-caller-identity --query Account --output text).dkr.ecr.$AWS_REGION.amazonaws.com/$FRONTEND_REPO:latest + cd .. + + echo_info "Images pushed successfully" +} + +# Deploy infrastructure +deploy_infrastructure() { + echo_info "Deploying infrastructure with Terraform..." + + cd infrastructure + terraform init + terraform plan -out=tfplan + terraform apply tfplan + cd .. + + echo_info "Infrastructure deployed successfully" +} + +# Update ECS services +update_services() { + echo_info "Updating ECS services..." + + # Update backend service + aws ecs update-service \ + --cluster $CLUSTER_NAME \ + --service $BACKEND_SERVICE \ + --force-new-deployment \ + --region $AWS_REGION + + # Update frontend service + aws ecs update-service \ + --cluster $CLUSTER_NAME \ + --service $FRONTEND_SERVICE \ + --force-new-deployment \ + --region $AWS_REGION + + echo_info "Services updated successfully" +} + +# Wait for deployment to complete +wait_for_deployment() { + echo_info "Waiting for deployment to complete..." + + aws ecs wait services-stable \ + --cluster $CLUSTER_NAME \ + --services $BACKEND_SERVICE $FRONTEND_SERVICE \ + --region $AWS_REGION + + echo_info "Deployment completed successfully" +} + +# Run database migrations +run_migrations() { + echo_info "Running database migrations..." + + # Get the task definition ARN + TASK_DEF_ARN=$(aws ecs describe-task-definition --task-definition physio-backend --query 'taskDefinition.taskDefinitionArn' --output text) + + # Run migration task + aws ecs run-task \ + --cluster $CLUSTER_NAME \ + --task-definition $TASK_DEF_ARN \ + --overrides '{ + "containerOverrides": [ + { + "name": "backend", + "command": ["npm", "run", "migrate"] + } + ] + }' \ + --network-configuration '{ + "awsvpcConfiguration": { + "subnets": ["subnet-xxx", "subnet-yyy"], + "securityGroups": ["sg-xxx"], + "assignPublicIp": "ENABLED" + } + }' \ + --region $AWS_REGION + + echo_info "Migrations completed" +} + +# Main deployment function +main() { + echo_info "Starting deployment process..." + + check_prerequisites + build_and_push + deploy_infrastructure + update_services + wait_for_deployment + run_migrations + + echo_info "Deployment completed successfully!" + echo_info "Application is available at: https://$(aws cloudfront list-distributions --query 'DistributionList.Items[0].DomainName' --output text)" +} + +# Run main function +main "$@" +``` + +### Docker Configuration + +#### Backend Dockerfile +Create `backend/Dockerfile`: +```dockerfile +FROM node:18-alpine + +WORKDIR /app + +# Install dependencies +COPY package*.json ./ +RUN npm ci --only=production + +# Copy source code +COPY . . + +# Build the application +RUN npm run build + +# Create non-root user +RUN addgroup -g 1001 -S nodejs +RUN adduser -S nodejs -u 1001 + +# Change ownership of the app directory +RUN chown -R nodejs:nodejs /app +USER nodejs + +EXPOSE 3000 + +# Health check +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD curl -f http://localhost:3000/health || exit 1 + +CMD ["npm", "start"] +``` + +#### Frontend Dockerfile +Create `frontend/Dockerfile`: +```dockerfile +# Build stage +FROM node:18-alpine as build + +WORKDIR /app + +# Install dependencies +COPY package*.json ./ +RUN npm ci + +# Copy source and build +COPY . . +RUN npm run build + +# Production stage +FROM nginx:alpine + +# Copy built app +COPY --from=build /app/build /usr/share/nginx/html + +# Copy nginx configuration +COPY nginx.conf /etc/nginx/nginx.conf + +EXPOSE 80 + +CMD ["nginx", "-g", "daemon off;"] +``` + +#### Nginx Configuration +Create `frontend/nginx.conf`: +```nginx +events { + worker_connections 1024; +} + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + + sendfile on; + keepalive_timeout 65; + + # Gzip compression + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_proxied any; + gzip_comp_level 6; + gzip_types + text/plain + text/css + text/xml + text/javascript + application/json + application/javascript + application/xml+rss + application/atom+xml + image/svg+xml; + + server { + listen 80; + server_name localhost; + root /usr/share/nginx/html; + index index.html; + + # Security headers + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "no-referrer-when-downgrade" always; + add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always; + + # Handle client-side routing + location / { + try_files $uri $uri/ /index.html; + } + + # API proxy + location /api { + proxy_pass http://backend:3000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + } + + # Static assets caching + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + } + } +} +``` + +## Environment Variables + +### Production Environment Variables +Create `.env.production`: +```bash +# Application +NODE_ENV=production +PORT=3000 +API_URL=https://api.yourdomain.com + +# Database +DATABASE_URL=postgresql://username:password@your-rds-endpoint:5432/physio_prod +REDIS_URL=redis://your-elasticache-endpoint:6379 + +# Authentication +JWT_SECRET=your-super-secure-jwt-secret-key +JWT_EXPIRES_IN=24h +REFRESH_TOKEN_EXPIRES_IN=7d + +# AWS Services +AWS_REGION=us-east-1 +AWS_ACCESS_KEY_ID=your-access-key +AWS_SECRET_ACCESS_KEY=your-secret-key +S3_BUCKET_NAME=your-s3-bucket-name +CLOUDFRONT_DOMAIN=your-cloudfront-domain + +# Payment Processing +STRIPE_SECRET_KEY=sk_live_your_stripe_secret_key +STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret + +# Email Service +SENDGRID_API_KEY=your-sendgrid-api-key +FROM_EMAIL=noreply@yourdomain.com + +# Push Notifications +FCM_SERVER_KEY=your-fcm-server-key + +# Monitoring +SENTRY_DSN=your-sentry-dsn +NEW_RELIC_LICENSE_KEY=your-newrelic-license-key + +# Security +CORS_ORIGIN=https://yourdomain.com +RATE_LIMIT_WINDOW_MS=900000 +RATE_LIMIT_MAX_REQUESTS=100 + +# File Upload +MAX_FILE_SIZE=500MB +ALLOWED_FILE_TYPES=mp4,mov,avi,wmv,jpg,jpeg,png,pdf + +# Business Settings +DEFAULT_TIMEZONE=America/New_York +DEFAULT_CURRENCY=USD +TAX_RATE=0.0875 +``` + +## CI/CD Pipeline + +### GitHub Actions Workflow +Create `.github/workflows/deploy.yml`: +```yaml +name: Deploy to Production + +on: + push: + branches: [main] + pull_request: + branches: [main] + +env: + AWS_REGION: us-east-1 + ECR_REPOSITORY_BACKEND: physio-backend + ECR_REPOSITORY_FRONTEND: physio-frontend + ECS_CLUSTER: physio-cluster + ECS_SERVICE_BACKEND: physio-backend + ECS_SERVICE_FRONTEND: physio-frontend + +jobs: + test: + runs-on: ubuntu-latest + + services: + postgres: + image: postgres:15 + env: + POSTGRES_PASSWORD: postgres + POSTGRES_DB: physio_test + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432:5432 + + redis: + image: redis:7 + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 6379:6379 + + steps: + - uses: actions/checkout@v3 + + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version: '18' + cache: 'npm' + cache-dependency-path: | + backend/package-lock.json + frontend/package-lock.json + + - name: Install backend dependencies + run: | + cd backend + npm ci + + - name: Install frontend dependencies + run: | + cd frontend + npm ci + + - name: Run backend tests + run: | + cd backend + npm run test + env: + DATABASE_URL: postgresql://postgres:postgres@localhost:5432/physio_test + REDIS_URL: redis://localhost:6379 + JWT_SECRET: test-secret + + - name: Run frontend tests + run: | + cd frontend + npm run test -- --coverage --watchAll=false + + - name: Run E2E tests + run: | + cd backend + npm start & + cd ../frontend + npm start & + sleep 30 + npm run test:e2e + + deploy: + needs: test + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + + steps: + - uses: actions/checkout@v3 + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v2 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.AWS_REGION }} + + - name: Login to Amazon ECR + id: login-ecr + uses: aws-actions/amazon-ecr-login@v1 + + - name: Build and push backend image + env: + ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} + IMAGE_TAG: ${{ github.sha }} + run: | + cd backend + docker build -t $ECR_REGISTRY/$ECR_REPOSITORY_BACKEND:$IMAGE_TAG . + docker push $ECR_REGISTRY/$ECR_REPOSITORY_BACKEND:$IMAGE_TAG + docker tag $ECR_REGISTRY/$ECR_REPOSITORY_BACKEND:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY_BACKEND:latest + docker push $ECR_REGISTRY/$ECR_REPOSITORY_BACKEND:latest + + - name: Build and push frontend image + env: + ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} + IMAGE_TAG: ${{ github.sha }} + run: | + cd frontend + docker build -t $ECR_REGISTRY/$ECR_REPOSITORY_FRONTEND:$IMAGE_TAG . + docker push $ECR_REGISTRY/$ECR_REPOSITORY_FRONTEND:$IMAGE_TAG + docker tag $ECR_REGISTRY/$ECR_REPOSITORY_FRONTEND:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY_FRONTEND:latest + docker push $ECR_REGISTRY/$ECR_REPOSITORY_FRONTEND:latest + + - name: Deploy to ECS + run: | + aws ecs update-service --cluster $ECS_CLUSTER --service $ECS_SERVICE_BACKEND --force-new-deployment + aws ecs update-service --cluster $ECS_CLUSTER --service $ECS_SERVICE_FRONTEND --force-new-deployment + + - name: Wait for deployment + run: | + aws ecs wait services-stable --cluster $ECS_CLUSTER --services $ECS_SERVICE_BACKEND $ECS_SERVICE_FRONTEND + + - name: Run database migrations + run: | + # Run migrations using ECS task + aws ecs run-task \ + --cluster $ECS_CLUSTER \ + --task-definition physio-backend \ + --overrides '{ + "containerOverrides": [ + { + "name": "backend", + "command": ["npm", "run", "migrate"] + } + ] + }' +``` + +## Monitoring and Logging + +### CloudWatch Configuration +```yaml +# cloudwatch-config.yml +Resources: + LogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: /ecs/physio-management + RetentionInDays: 30 + + MetricFilter: + Type: AWS::Logs::MetricFilter + Properties: + LogGroupName: !Ref LogGroup + FilterPattern: "[timestamp, request_id, level=\"ERROR\", ...]" + MetricTransformations: + - MetricNamespace: PhysioManagement + MetricName: ErrorCount + MetricValue: "1" + + ErrorAlarm: + Type: AWS::CloudWatch::Alarm + Properties: + AlarmName: PhysioManagement-ErrorRate + AlarmDescription: High error rate detected + MetricName: ErrorCount + Namespace: PhysioManagement + Statistic: Sum + Period: 300 + EvaluationPeriods: 2 + Threshold: 10 + ComparisonOperator: GreaterThanThreshold + AlarmActions: + - !Ref SNSTopicArn +``` + +### Health Checks +Create `backend/routes/health.js`: +```javascript +const express = require('express'); +const router = express.Router(); +const { Pool } = require('pg'); +const redis = require('redis'); + +router.get('/health', async (req, res) => { + const health = { + status: 'ok', + timestamp: new Date().toISOString(), + services: {} + }; + + try { + // Check database connection + const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + await pool.query('SELECT 1'); + health.services.database = 'ok'; + await pool.end(); + } catch (error) { + health.services.database = 'error'; + health.status = 'error'; + } + + try { + // Check Redis connection + const client = redis.createClient({ url: process.env.REDIS_URL }); + await client.connect(); + await client.ping(); + health.services.redis = 'ok'; + await client.quit(); + } catch (error) { + health.services.redis = 'error'; + health.status = 'error'; + } + + const statusCode = health.status === 'ok' ? 200 : 503; + res.status(statusCode).json(health); +}); + +module.exports = router; +``` + +## Security Configuration + +### SSL/TLS Setup +```bash +# Install Certbot for Let's Encrypt +sudo apt-get update +sudo apt-get install certbot python3-certbot-nginx + +# Obtain SSL certificate +sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com + +# Auto-renewal cron job +echo "0 12 * * * /usr/bin/certbot renew --quiet" | sudo crontab - +``` + +### Security Headers +```nginx +# Add to nginx configuration +add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; +add_header X-Frame-Options "SAMEORIGIN" always; +add_header X-Content-Type-Options "nosniff" always; +add_header X-XSS-Protection "1; mode=block" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; +add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://js.stripe.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https:; connect-src 'self' https://api.stripe.com;" always; +``` + +## Backup and Recovery + +### Database Backup Script +Create `scripts/backup.sh`: +```bash +#!/bin/bash + +# Configuration +DB_HOST="your-rds-endpoint" +DB_NAME="physio_prod" +DB_USER="your-username" +BACKUP_DIR="/backups" +S3_BUCKET="physio-backups" +DATE=$(date +%Y%m%d_%H%M%S) + +# Create backup +pg_dump -h $DB_HOST -U $DB_USER -d $DB_NAME > $BACKUP_DIR/physio_backup_$DATE.sql + +# Compress backup +gzip $BACKUP_DIR/physio_backup_$DATE.sql + +# Upload to S3 +aws s3 cp $BACKUP_DIR/physio_backup_$DATE.sql.gz s3://$S3_BUCKET/ + +# Clean up local backups older than 7 days +find $BACKUP_DIR -name "physio_backup_*.sql.gz" -mtime +7 -delete + +echo "Backup completed: physio_backup_$DATE.sql.gz" +``` + +### Recovery Procedure +```bash +#!/bin/bash + +# Download backup from S3 +aws s3 cp s3://physio-backups/physio_backup_YYYYMMDD_HHMMSS.sql.gz ./ + +# Decompress +gunzip physio_backup_YYYYMMDD_HHMMSS.sql.gz + +# Restore database +psql -h $DB_HOST -U $DB_USER -d $DB_NAME < physio_backup_YYYYMMDD_HHMMSS.sql +``` + +## Performance Optimization + +### CDN Configuration +```javascript +// CloudFront cache behaviors +const cacheBehaviors = [ + { + pathPattern: '/api/*', + cachePolicyId: '4135ea2d-6df8-44a3-9df3-4b5a84be39ad', // CachingDisabled + originRequestPolicyId: '88a5eaf4-2fd4-4709-b370-b4c650ea3fcf', // CORS-S3Origin + }, + { + pathPattern: '/static/*', + cachePolicyId: '658327ea-f89d-4fab-a63d-7e88639e58f6', // CachingOptimized + compress: true, + }, + { + pathPattern: '/videos/*', + cachePolicyId: '4135ea2d-6df8-44a3-9df3-4b5a84be39ad', // CachingDisabled (for authenticated content) + } +]; +``` + +### Database Optimization +```sql +-- Create indexes for performance +CREATE INDEX CONCURRENTLY idx_appointments_date_therapist ON appointments(appointment_date, physiotherapist_id); +CREATE INDEX CONCURRENTLY idx_sessions_patient_date ON sessions(patient_id, session_date DESC); +CREATE INDEX CONCURRENTLY idx_invoices_patient_status ON invoices(patient_id, status); +CREATE INDEX CONCURRENTLY idx_videos_patient_type ON videos(patient_id, video_type); + +-- Analyze tables for query optimization +ANALYZE appointments; +ANALYZE sessions; +ANALYZE invoices; +ANALYZE videos; +``` + +## Troubleshooting + +### Common Issues + +#### 1. Database Connection Issues +```bash +# Check RDS connectivity +telnet your-rds-endpoint 5432 + +# Check security groups +aws ec2 describe-security-groups --group-ids sg-xxxxx + +# Test database connection +psql -h your-rds-endpoint -U username -d physio_prod +``` + +#### 2. ECS Service Issues +```bash +# Check service status +aws ecs describe-services --cluster physio-cluster --services physio-backend + +# Check task logs +aws logs get-log-events --log-group-name /ecs/physio-backend --log-stream-name ecs/backend/task-id + +# Force new deployment +aws ecs update-service --cluster physio-cluster --service physio-backend --force-new-deployment +``` + +#### 3. Load Balancer Issues +```bash +# Check target health +aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:... + +# Check ALB logs +aws s3 ls s3://your-alb-logs-bucket/ +``` + +### Rollback Procedure +```bash +#!/bin/bash + +# Rollback to previous task definition +PREVIOUS_TASK_DEF=$(aws ecs list-task-definitions --family-prefix physio-backend --status ACTIVE --sort DESC --max-items 2 --query 'taskDefinitionArns[1]' --output text) + +aws ecs update-service \ + --cluster physio-cluster \ + --service physio-backend \ + --task-definition $PREVIOUS_TASK_DEF + +# Wait for rollback to complete +aws ecs wait services-stable --cluster physio-cluster --services physio-backend +``` + +This comprehensive deployment guide provides everything needed to deploy the physiotherapy management system from development to production, including infrastructure setup, CI/CD pipelines, monitoring, security, and troubleshooting procedures. \ No newline at end of file diff --git a/development-roadmap.md b/development-roadmap.md new file mode 100644 index 00000000..b0f61176 --- /dev/null +++ b/development-roadmap.md @@ -0,0 +1,951 @@ +# Physiotherapy Management System - Development Roadmap + +## Project Overview + +This roadmap outlines the complete development lifecycle for the physiotherapy patient management system, from initial setup to full deployment across web, iOS, and Android platforms. + +**Total Estimated Timeline: 24 weeks (6 months)** +**Estimated Budget: $251,200 - $369,600** + +## Team Structure + +### Core Team (Recommended) +- **1 Project Manager** (0.5 FTE) - $70-100/hour +- **1 Backend Developer** (1.0 FTE) - $80-120/hour +- **1 Frontend Developer** (1.0 FTE) - $70-100/hour +- **1 Mobile Developer** (0.8 FTE) - $80-120/hour +- **1 UI/UX Designer** (0.4 FTE) - $60-90/hour +- **1 DevOps Engineer** (0.2 FTE) - $90-130/hour +- **1 QA Engineer** (0.3 FTE) - $50-80/hour + +### Alternative Lean Team +- **1 Full-Stack Developer** (1.0 FTE) - $90-130/hour +- **1 Mobile Developer** (1.0 FTE) - $80-120/hour +- **1 UI/UX Designer** (0.5 FTE) - $60-90/hour +- **1 Project Manager/DevOps** (0.3 FTE) - $80-120/hour + +## Phase 1: Foundation & Core Setup (Weeks 1-4) + +### Week 1: Project Setup & Planning +**Goals:** Establish development environment and project structure + +#### Tasks: +- [ ] **Project Setup** (2 days) + - Set up Git repository and branching strategy + - Configure development environments + - Set up project management tools (Jira/Linear/Asana) + - Create communication channels (Slack/Discord) + +- [ ] **Technical Architecture** (2 days) + - Finalize technology stack decisions + - Set up database schema and migrations + - Configure CI/CD pipeline basics + - Set up code quality tools (ESLint, Prettier, SonarQube) + +- [ ] **Design System** (1 day) + - Create design tokens and color palette + - Define typography and spacing scales + - Set up component library structure + +**Deliverables:** +- Development environment setup +- Git repository with initial structure +- Database schema implementation +- Basic CI/CD pipeline +- Design system foundations + +### Week 2: Authentication & User Management +**Goals:** Implement secure user authentication system + +#### Backend Tasks: +- [ ] **User Authentication API** (3 days) + - JWT-based authentication system + - Password hashing and validation + - Email verification system + - Password reset functionality + - Role-based access control (RBAC) + +- [ ] **User Management API** (2 days) + - User profile CRUD operations + - Patient and physiotherapist profile extensions + - File upload for profile pictures + +#### Frontend Tasks: +- [ ] **Authentication UI** (3 days) + - Login/Register forms + - Password reset flow + - Email verification pages + - Protected route implementation + +- [ ] **User Profile Management** (2 days) + - Profile view and edit forms + - Avatar upload functionality + - Account settings page + +**Deliverables:** +- Complete authentication system +- User profile management +- Protected routing implementation +- Basic responsive design + +### Week 3: Core Data Models & APIs +**Goals:** Implement core business logic and data models + +#### Backend Tasks: +- [ ] **Patient Management API** (2 days) + - Patient CRUD operations + - Medical history management + - Insurance information handling + - Emergency contact management + +- [ ] **Physiotherapist Management API** (2 days) + - Therapist profile management + - Specialization and certification handling + - Availability schedule management + - Rating and review system + +- [ ] **Basic Appointment API** (1 day) + - Appointment creation and retrieval + - Basic validation rules + - Status management + +#### Database & Infrastructure: +- [ ] **Database Optimization** (1 day) + - Index creation for performance + - Query optimization + - Database backup setup + +**Deliverables:** +- Core API endpoints for patients and therapists +- Database with proper indexing +- Basic appointment functionality +- API documentation (Swagger/OpenAPI) + +### Week 4: Basic Frontend Implementation +**Goals:** Create core user interfaces and connect to APIs + +#### Frontend Tasks: +- [ ] **Dashboard Implementation** (2 days) + - Patient dashboard with overview + - Therapist dashboard with patient list + - Basic navigation and layout + +- [ ] **Patient Management UI** (2 days) + - Patient list and search functionality + - Patient detail view + - Patient profile editing + +- [ ] **Therapist Management UI** (1 day) + - Therapist list and profiles + - Specialization filtering + - Rating display + +**Testing & Quality Assurance:** +- [ ] **Testing Setup** (1 day) + - Unit test framework setup + - Integration test examples + - E2E test framework configuration + +**Deliverables:** +- Functional web application MVP +- Basic patient and therapist management +- Test framework implementation +- Responsive design implementation + +## Phase 2: Appointment & Session Management (Weeks 5-8) + +### Week 5: Advanced Appointment System +**Goals:** Complete appointment booking and management system + +#### Backend Tasks: +- [ ] **Advanced Appointment API** (3 days) + - Availability checking algorithm + - Conflict detection and resolution + - Recurring appointment support + - Appointment reminders system + +- [ ] **Calendar Integration** (2 days) + - Calendar view API endpoints + - Time zone handling + - Business hours configuration + - Holiday and break management + +#### Frontend Tasks: +- [ ] **Appointment Booking UI** (3 days) + - Calendar component implementation + - Time slot selection interface + - Appointment form with validation + - Confirmation and cancellation flows + +- [ ] **Calendar Views** (2 days) + - Monthly/weekly/daily calendar views + - Drag-and-drop rescheduling + - Color-coded appointment status + - Quick appointment creation + +**Deliverables:** +- Complete appointment booking system +- Interactive calendar interface +- Appointment conflict resolution +- Automated reminder system + +### Week 6: Session Recording & Management +**Goals:** Implement session tracking and documentation system + +#### Backend Tasks: +- [ ] **Session Management API** (3 days) + - Session creation from appointments + - SOAP notes (Subjective, Objective, Assessment, Plan) structure + - Progress tracking and measurements + - Treatment history management + +- [ ] **Exercise Library API** (2 days) + - Exercise database management + - Exercise assignment to patients + - Progress tracking for exercises + - Custom exercise creation + +#### Frontend Tasks: +- [ ] **Session Documentation UI** (3 days) + - SOAP notes form interface + - Progress tracking charts + - Treatment history timeline + - Session completion workflow + +- [ ] **Exercise Management UI** (2 days) + - Exercise library browser + - Exercise assignment interface + - Patient exercise tracking + - Progress visualization + +**Deliverables:** +- Complete session documentation system +- Exercise library and assignment +- Progress tracking capabilities +- Treatment history visualization + +### Week 7: Patient Portal Development +**Goals:** Create comprehensive patient-facing features + +#### Frontend Tasks: +- [ ] **Patient Appointment Management** (2 days) + - Appointment booking interface + - Appointment history and upcoming appointments + - Cancellation and rescheduling options + - Appointment reminders + +- [ ] **Patient Session History** (2 days) + - Session history timeline + - Progress charts and metrics + - Treatment plan viewing + - Exercise assignment display + +- [ ] **Patient Exercise Portal** (1 day) + - Assigned exercise list + - Exercise completion tracking + - Progress reporting + - Exercise video viewing + +**Mobile Preparation:** +- [ ] **Responsive Design Optimization** (1 day) + - Mobile-first responsive design + - Touch-friendly interface elements + - Performance optimization for mobile + +**Deliverables:** +- Complete patient portal functionality +- Mobile-optimized web interface +- Patient self-service capabilities +- Exercise tracking system + +### Week 8: Testing & Refinement +**Goals:** Comprehensive testing and bug fixes + +#### Testing Tasks: +- [ ] **Comprehensive Testing** (3 days) + - Unit test coverage improvement (>80%) + - Integration test implementation + - End-to-end test scenarios + - Performance testing + +- [ ] **User Acceptance Testing** (2 days) + - UAT scenario creation + - Stakeholder testing sessions + - Feedback collection and analysis + - Priority bug identification + +**Bug Fixes & Optimization:** +- [ ] **Bug Resolution** (2 days) + - Critical bug fixes + - Performance optimization + - UI/UX improvements + - Security vulnerability assessment + +**Deliverables:** +- Thoroughly tested application +- Performance optimizations +- Bug-free core functionality +- UAT completion report + +## Phase 3: Billing & Payment Integration (Weeks 9-12) + +### Week 9: Billing System Implementation +**Goals:** Create comprehensive billing and invoice management + +#### Backend Tasks: +- [ ] **Billing API Development** (3 days) + - Invoice generation system + - Pricing and tax calculation + - Payment tracking + - Billing history management + +- [ ] **Payment Gateway Integration** (2 days) + - Stripe payment integration + - Payment method management + - Webhook handling for payment events + - Refund and dispute management + +#### Frontend Tasks: +- [ ] **Billing Management UI** (3 days) + - Invoice creation and editing + - Billing dashboard for therapists + - Payment history visualization + - Revenue reporting interface + +- [ ] **Payment Processing UI** (2 days) + - Secure payment forms + - Payment method management + - Payment confirmation flows + - Receipt generation and viewing + +**Deliverables:** +- Complete billing system +- Secure payment processing +- Invoice management +- Revenue tracking capabilities + +### Week 10: Financial Reporting & Analytics +**Goals:** Implement comprehensive reporting and analytics + +#### Backend Tasks: +- [ ] **Analytics API** (2 days) + - Revenue analytics endpoints + - Patient analytics and metrics + - Session statistics and trends + - Performance indicators calculation + +- [ ] **Reporting System** (2 days) + - Automated report generation + - Custom report builder + - Data export functionality + - Scheduled report delivery + +#### Frontend Tasks: +- [ ] **Analytics Dashboard** (3 days) + - Revenue charts and graphs + - Patient metrics visualization + - Session analytics display + - Key performance indicators (KPIs) + +- [ ] **Reporting Interface** (1 day) + - Report generation forms + - Report viewing and download + - Custom report builder UI + - Scheduled report management + +**Deliverables:** +- Comprehensive analytics system +- Financial reporting capabilities +- Data visualization dashboards +- Custom report generation + +### Week 11: Mobile App Development Start +**Goals:** Begin native mobile app development + +#### Mobile Development Setup: +- [ ] **Development Environment** (1 day) + - React Native setup (or native iOS/Android) + - Development tools configuration + - Emulator/simulator setup + - Code sharing strategy implementation + +#### Core Mobile Features: +- [ ] **Authentication & Navigation** (2 days) + - Mobile authentication flow + - Navigation structure + - Biometric authentication (Face ID/Touch ID) + - Secure token storage + +- [ ] **Core UI Components** (2 days) + - Design system implementation + - Reusable component library + - Platform-specific adaptations + - Accessibility features + +**API Integration:** +- [ ] **Mobile API Client** (1 day) + - HTTP client configuration + - Error handling and retry logic + - Offline capability planning + - Push notification setup + +**Deliverables:** +- Mobile development environment +- Core mobile authentication +- Basic navigation structure +- API integration foundation + +### Week 12: Mobile Core Features +**Goals:** Implement core mobile functionality + +#### Mobile Features Implementation: +- [ ] **Appointment Management** (2 days) + - Mobile appointment booking + - Calendar integration + - Push notifications for appointments + - Offline appointment viewing + +- [ ] **Patient Features** (2 days) + - Patient profile management + - Session history viewing + - Exercise tracking + - Progress visualization + +- [ ] **Therapist Features** (1 day) + - Patient list and management + - Quick session notes + - Appointment management + - Basic reporting + +**Testing & Optimization:** +- [ ] **Mobile Testing** (1 day) + - Device testing on multiple platforms + - Performance optimization + - Memory usage optimization + - Battery usage testing + +**Deliverables:** +- Core mobile app functionality +- Cross-platform compatibility +- Performance-optimized mobile app +- Push notification system + +## Phase 4: Video Features & Advanced Functionality (Weeks 13-16) + +### Week 13: Video Infrastructure Setup +**Goals:** Implement video upload, storage, and streaming + +#### Backend Tasks: +- [ ] **Video Storage System** (3 days) + - AWS S3/Google Cloud Storage integration + - Video upload API with chunking + - Video processing pipeline + - Thumbnail generation + +- [ ] **Video Streaming API** (2 days) + - Secure video streaming endpoints + - Access control for video content + - Video quality adaptation + - CDN integration for performance + +#### Frontend Tasks: +- [ ] **Video Upload Interface** (2 days) + - Drag-and-drop video upload + - Upload progress tracking + - Video preview functionality + - Batch upload support + +- [ ] **Video Player Implementation** (1 day) + - Custom video player + - Playback controls + - Quality selection + - Fullscreen support + +**Deliverables:** +- Video upload and storage system +- Secure video streaming +- Professional video player +- CDN-optimized delivery + +### Week 14: Video Management Features +**Goals:** Complete video management and organization system + +#### Backend Tasks: +- [ ] **Video Management API** (2 days) + - Video categorization and tagging + - Video sharing and permissions + - Video analytics and tracking + - Video library organization + +- [ ] **Video Processing** (2 days) + - Automatic video transcoding + - Multiple quality generation + - Video compression optimization + - Metadata extraction + +#### Frontend Tasks: +- [ ] **Video Library Interface** (2 days) + - Video library browser + - Search and filter functionality + - Video organization tools + - Sharing and permission management + +- [ ] **Video Analytics Dashboard** (1 day) + - Video view statistics + - Engagement metrics + - Popular content identification + - Usage analytics + +**Mobile Video Features:** +- [ ] **Mobile Video Implementation** (1 day) + - Mobile video upload + - Native video player integration + - Offline video caching + - Mobile-optimized streaming + +**Deliverables:** +- Complete video management system +- Video analytics and insights +- Mobile video capabilities +- Optimized video delivery + +### Week 15: Communication & Collaboration Features +**Goals:** Implement messaging and collaboration tools + +#### Backend Tasks: +- [ ] **Messaging System API** (2 days) + - Real-time messaging with WebSocket + - Message threading and conversations + - File attachment support + - Message history and search + +- [ ] **Notification System** (2 days) + - Push notification service + - Email notification system + - SMS notification integration + - Notification preferences management + +#### Frontend Tasks: +- [ ] **Messaging Interface** (2 days) + - Real-time chat interface + - Message composition and sending + - File sharing capabilities + - Conversation management + +- [ ] **Notification Management** (1 day) + - Notification center + - Notification preferences + - Real-time notification display + - Notification history + +**Mobile Communication:** +- [ ] **Mobile Messaging** (1 day) + - Native messaging interface + - Push notification handling + - Background message sync + - Offline message queue + +**Deliverables:** +- Real-time messaging system +- Comprehensive notification system +- Mobile communication features +- File sharing capabilities + +### Week 16: Advanced Features & Integration +**Goals:** Implement advanced features and third-party integrations + +#### Advanced Features: +- [ ] **Advanced Analytics** (2 days) + - Machine learning insights + - Predictive analytics for patient outcomes + - Treatment effectiveness analysis + - Automated reporting + +- [ ] **Integration Features** (2 days) + - Calendar integration (Google Calendar, Outlook) + - Electronic Health Records (EHR) integration + - Insurance verification API integration + - Telehealth platform integration + +#### Performance & Security: +- [ ] **Performance Optimization** (1 day) + - Database query optimization + - Caching implementation + - CDN optimization + - Load testing and optimization + +- [ ] **Security Enhancements** (1 day) + - Security audit and penetration testing + - HIPAA compliance verification + - Data encryption improvements + - Access control refinements + +**Deliverables:** +- Advanced analytics capabilities +- Third-party integrations +- Performance-optimized system +- Enhanced security measures + +## Phase 5: Polish & Advanced Features (Weeks 17-20) + +### Week 17: User Experience Enhancement +**Goals:** Polish user interface and improve user experience + +#### UI/UX Improvements: +- [ ] **Design System Refinement** (2 days) + - Component library completion + - Accessibility improvements (WCAG 2.1 AA) + - Dark mode implementation + - Animation and micro-interactions + +- [ ] **User Experience Optimization** (2 days) + - User journey optimization + - Loading state improvements + - Error handling enhancement + - Onboarding flow creation + +#### Mobile UX: +- [ ] **Mobile Experience Polish** (2 days) + - Native platform design guidelines + - Gesture navigation implementation + - Haptic feedback integration + - App icon and splash screen design + +**Performance Monitoring:** +- [ ] **Monitoring Implementation** (1 day) + - Application performance monitoring + - Error tracking and logging + - User behavior analytics + - Performance metrics dashboard + +**Deliverables:** +- Polished user interface +- Improved accessibility +- Enhanced mobile experience +- Comprehensive monitoring + +### Week 18: Advanced Reporting & Analytics +**Goals:** Implement sophisticated reporting and business intelligence + +#### Advanced Reporting: +- [ ] **Business Intelligence Dashboard** (3 days) + - Executive dashboard with KPIs + - Predictive analytics for patient retention + - Revenue forecasting + - Treatment outcome analysis + +- [ ] **Custom Report Builder** (2 days) + - Drag-and-drop report builder + - Custom chart and graph creation + - Automated report scheduling + - Report sharing and collaboration + +#### Data Export & Integration: +- [ ] **Data Export Features** (1 day) + - Multiple export formats (PDF, Excel, CSV) + - Automated data backups + - Data archiving system + - Compliance reporting + +**API Enhancements:** +- [ ] **API Documentation & SDK** (1 day) + - Comprehensive API documentation + - SDK development for integrations + - Webhook system enhancement + - Rate limiting and monitoring + +**Deliverables:** +- Advanced business intelligence +- Custom reporting capabilities +- Data export and integration +- Enhanced API ecosystem + +### Week 19: Mobile App Completion +**Goals:** Complete mobile app development and prepare for app store submission + +#### Mobile App Finalization: +- [ ] **Feature Completion** (2 days) + - All web features ported to mobile + - Platform-specific optimizations + - Offline functionality implementation + - Background sync capabilities + +- [ ] **App Store Preparation** (2 days) + - App store listing creation + - Screenshot and video creation + - App store optimization (ASO) + - Compliance and privacy policy + +#### Mobile Testing: +- [ ] **Comprehensive Mobile Testing** (2 days) + - Device testing across multiple models + - Performance testing and optimization + - Battery usage optimization + - Memory leak detection and fixes + +**Beta Testing:** +- [ ] **Beta Release** (1 day) + - TestFlight/Google Play Console setup + - Beta tester recruitment + - Feedback collection system + - Bug tracking and resolution + +**Deliverables:** +- Complete mobile applications +- App store ready submissions +- Beta testing program +- Performance-optimized mobile apps + +### Week 20: Integration Testing & Optimization +**Goals:** Final integration testing and system optimization + +#### System Integration Testing: +- [ ] **End-to-End Testing** (2 days) + - Complete user journey testing + - Cross-platform compatibility testing + - Integration testing with third-party services + - Load testing and stress testing + +- [ ] **Security Testing** (1 day) + - Penetration testing + - Vulnerability assessment + - HIPAA compliance audit + - Data protection verification + +#### Performance Optimization: +- [ ] **System Optimization** (2 days) + - Database performance tuning + - API response time optimization + - Frontend bundle optimization + - CDN configuration optimization + +**Documentation:** +- [ ] **Documentation Completion** (1 day) + - User documentation and help guides + - Administrator documentation + - API documentation finalization + - Deployment and maintenance guides + +**Deliverables:** +- Fully tested and optimized system +- Complete security audit +- Performance-tuned application +- Comprehensive documentation + +## Phase 6: Deployment & Launch (Weeks 21-24) + +### Week 21: Production Deployment Setup +**Goals:** Set up production infrastructure and deploy applications + +#### Infrastructure Deployment: +- [ ] **Production Infrastructure** (3 days) + - AWS/GCP production environment setup + - Database migration and optimization + - CDN configuration and testing + - SSL certificate installation + +- [ ] **CI/CD Pipeline** (2 days) + - Production deployment pipeline + - Automated testing integration + - Rollback procedures + - Monitoring and alerting setup + +#### Security & Compliance: +- [ ] **Security Implementation** (2 days) + - Production security configuration + - HIPAA compliance implementation + - Data encryption at rest and in transit + - Access control and audit logging + +**Deliverables:** +- Production-ready infrastructure +- Automated deployment pipeline +- Security and compliance implementation +- Monitoring and alerting system + +### Week 22: Data Migration & System Testing +**Goals:** Migrate data and perform comprehensive system testing + +#### Data Migration: +- [ ] **Data Migration** (2 days) + - Legacy data analysis and mapping + - Data migration scripts development + - Data validation and verification + - Backup and recovery testing + +#### System Testing: +- [ ] **Production Testing** (2 days) + - Production environment testing + - Performance testing under load + - Disaster recovery testing + - User acceptance testing in production + +#### Mobile App Submission: +- [ ] **App Store Submission** (1 day) + - iOS App Store submission + - Google Play Store submission + - App review process monitoring + - App store optimization + +**Final Preparations:** +- [ ] **Launch Preparations** (1 day) + - Launch checklist completion + - Support documentation preparation + - Training material creation + - Communication plan execution + +**Deliverables:** +- Migrated and validated data +- Production-tested system +- Submitted mobile applications +- Launch-ready platform + +### Week 23: User Training & Soft Launch +**Goals:** Train users and conduct soft launch with limited users + +#### User Training: +- [ ] **Training Program** (2 days) + - Administrator training sessions + - Physiotherapist training workshops + - Patient onboarding materials + - Support staff training + +- [ ] **Documentation & Support** (1 day) + - User manual completion + - FAQ and troubleshooting guides + - Video tutorial creation + - Help desk setup + +#### Soft Launch: +- [ ] **Limited User Launch** (2 days) + - Gradual user onboarding + - Real-world usage monitoring + - Feedback collection and analysis + - Issue identification and resolution + +**Quality Assurance:** +- [ ] **Final Quality Checks** (1 day) + - Final bug fixes and optimizations + - Performance monitoring and tuning + - User experience refinements + - Security final verification + +**Deliverables:** +- Trained user base +- Comprehensive support materials +- Soft launch completion +- Refined and optimized system + +### Week 24: Full Launch & Post-Launch Support +**Goals:** Execute full launch and establish ongoing support + +#### Full Launch: +- [ ] **Production Launch** (2 days) + - Full user base migration + - Marketing and communication campaign + - Launch monitoring and support + - Issue resolution and hotfixes + +- [ ] **Mobile App Launch** (1 day) + - App store approval and launch + - App marketing and promotion + - User acquisition campaigns + - App performance monitoring + +#### Post-Launch Activities: +- [ ] **Support & Monitoring** (2 days) + - 24/7 monitoring setup + - Support ticket system implementation + - Performance metrics tracking + - User feedback collection + +**Project Closure:** +- [ ] **Project Handover** (1 day) + - Technical documentation handover + - Knowledge transfer sessions + - Maintenance plan establishment + - Future enhancement roadmap + +**Deliverables:** +- Successfully launched platform +- Active mobile applications +- Established support system +- Project closure documentation + +## Success Metrics & KPIs + +### Technical Metrics +- **System Uptime**: >99.9% +- **API Response Time**: <200ms average +- **Mobile App Performance**: <3 second load times +- **Database Query Performance**: <100ms average +- **Video Upload Success Rate**: >95% + +### Business Metrics +- **User Adoption Rate**: Target 80% of existing patients within 3 months +- **Appointment Show Rate**: Improve by 15% within 6 months +- **Payment Processing Success**: >98% success rate +- **Customer Satisfaction**: >4.5/5 rating +- **Revenue Impact**: 20% increase in practice efficiency + +### User Experience Metrics +- **Mobile App Store Rating**: >4.0 stars +- **User Session Duration**: Track engagement levels +- **Feature Adoption Rate**: Monitor feature usage +- **Support Ticket Volume**: <5% of active users per month + +## Risk Mitigation Strategies + +### Technical Risks +1. **Scalability Issues** + - Implement horizontal scaling from day one + - Use cloud-native services (AWS/GCP) + - Regular load testing and performance monitoring + +2. **Data Security Breaches** + - Implement end-to-end encryption + - Regular security audits and penetration testing + - HIPAA compliance from the beginning + +3. **Third-Party Integration Failures** + - Build fallback mechanisms + - Maintain service level agreements (SLAs) + - Regular integration testing + +### Business Risks +1. **User Adoption Challenges** + - Comprehensive training programs + - Gradual rollout with feedback loops + - Strong change management process + +2. **Regulatory Compliance Issues** + - Legal consultation throughout development + - Regular compliance audits + - Documentation of all compliance measures + +3. **Budget Overruns** + - Detailed project tracking and reporting + - Regular budget reviews and adjustments + - Scope management and change control + +## Post-Launch Roadmap (Months 7-12) + +### Month 7-8: Optimization & Enhancement +- Performance optimization based on real usage data +- User feedback implementation +- Mobile app updates and improvements +- Advanced analytics features + +### Month 9-10: Advanced Features +- AI-powered treatment recommendations +- Telehealth integration +- Advanced reporting and business intelligence +- Integration with wearable devices + +### Month 11-12: Expansion & Scaling +- Multi-location support +- Advanced role management +- API marketplace for third-party integrations +- White-label solution development + +This comprehensive roadmap provides a structured approach to developing the physiotherapy management system while maintaining quality, security, and user experience throughout the development process. \ No newline at end of file diff --git a/physiotherapy-management-system-specification.md b/physiotherapy-management-system-specification.md new file mode 100644 index 00000000..cc798064 --- /dev/null +++ b/physiotherapy-management-system-specification.md @@ -0,0 +1,438 @@ +# Physiotherapy Patient Management System - Technical Specification + +## Executive Summary + +This document outlines the technical specifications for a comprehensive physiotherapy patient management system that enables patients to book appointments, manage payments, and share videos, while providing physiotherapists with complete session tracking, patient records, and content management capabilities. + +## System Overview + +### Core Features + +#### Patient Portal +- **Appointment Booking**: Schedule sessions with available physiotherapists +- **Payment Management**: Pay bills online with multiple payment options +- **Video Sharing**: Upload initial assessment videos and receive treatment videos +- **Session History**: View past sessions and treatment progress +- **Profile Management**: Update personal information and medical history + +#### Physiotherapist Dashboard +- **Patient Management**: Complete patient records and medical history +- **Session Tracking**: Record session details, treatments, and progress notes +- **Appointment Management**: View, confirm, and reschedule appointments +- **Billing System**: Generate invoices and track payments +- **Video Management**: Upload treatment videos and view patient submissions +- **Analytics**: Session statistics, patient progress, and revenue reports + +#### Administrative Features +- **Multi-therapist Support**: Manage multiple physiotherapists and their schedules +- **Reporting**: Generate comprehensive reports on sessions, revenue, and patient outcomes +- **Content Library**: Organize and categorize treatment videos +- **Communication**: In-app messaging between patients and therapists + +## Technical Architecture + +### Platform Strategy +- **Web Application**: React.js with responsive design +- **iOS App**: Native Swift development or React Native +- **Android App**: Native Kotlin development or React Native +- **Backend API**: Node.js with Express.js or Python with FastAPI +- **Database**: PostgreSQL with Redis for caching +- **File Storage**: AWS S3 or Google Cloud Storage for videos +- **Real-time Features**: WebSocket connections for notifications + +### Technology Stack + +#### Frontend +- **Web**: React.js 18+, TypeScript, Tailwind CSS, React Query +- **Mobile**: React Native or Native development (Swift/Kotlin) +- **State Management**: Redux Toolkit or Zustand +- **UI Components**: Material-UI or Chakra UI +- **Video Player**: Video.js or React Player + +#### Backend +- **Runtime**: Node.js 18+ or Python 3.11+ +- **Framework**: Express.js or FastAPI +- **Authentication**: JWT with refresh tokens +- **File Upload**: Multer (Node.js) or FastAPI File Upload +- **Email Service**: SendGrid or AWS SES +- **Push Notifications**: Firebase Cloud Messaging + +#### Database & Storage +- **Primary Database**: PostgreSQL 15+ +- **Caching**: Redis 7+ +- **File Storage**: AWS S3 or Google Cloud Storage +- **CDN**: CloudFlare or AWS CloudFront +- **Backup**: Automated daily backups + +#### Infrastructure +- **Hosting**: AWS, Google Cloud, or DigitalOcean +- **Containerization**: Docker with Docker Compose +- **CI/CD**: GitHub Actions or GitLab CI +- **Monitoring**: Sentry for error tracking, DataDog for performance +- **SSL**: Let's Encrypt or CloudFlare SSL + +## Database Schema + +### Core Tables + +#### Users +```sql +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(255) UNIQUE NOT NULL, + password_hash VARCHAR(255) NOT NULL, + role ENUM('patient', 'physiotherapist', 'admin') NOT NULL, + first_name VARCHAR(100) NOT NULL, + last_name VARCHAR(100) NOT NULL, + phone VARCHAR(20), + date_of_birth DATE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +#### Patients +```sql +CREATE TABLE patients ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + medical_history TEXT, + emergency_contact_name VARCHAR(100), + emergency_contact_phone VARCHAR(20), + insurance_provider VARCHAR(100), + insurance_policy_number VARCHAR(50), + address TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +#### Physiotherapists +```sql +CREATE TABLE physiotherapists ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + license_number VARCHAR(50) UNIQUE NOT NULL, + specializations TEXT[], + bio TEXT, + hourly_rate DECIMAL(10,2), + availability_schedule JSONB, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +#### Appointments +```sql +CREATE TABLE appointments ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + patient_id UUID REFERENCES patients(id) ON DELETE CASCADE, + physiotherapist_id UUID REFERENCES physiotherapists(id) ON DELETE CASCADE, + appointment_date TIMESTAMP NOT NULL, + duration_minutes INTEGER DEFAULT 60, + status ENUM('scheduled', 'confirmed', 'completed', 'cancelled', 'no_show') DEFAULT 'scheduled', + notes TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +#### Sessions +```sql +CREATE TABLE sessions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + appointment_id UUID REFERENCES appointments(id) ON DELETE CASCADE, + patient_id UUID REFERENCES patients(id) ON DELETE CASCADE, + physiotherapist_id UUID REFERENCES physiotherapists(id) ON DELETE CASCADE, + session_date TIMESTAMP NOT NULL, + duration_minutes INTEGER NOT NULL, + treatment_notes TEXT, + exercises_prescribed TEXT, + progress_notes TEXT, + next_session_recommendations TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +#### Billing +```sql +CREATE TABLE invoices ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + patient_id UUID REFERENCES patients(id) ON DELETE CASCADE, + session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, + amount DECIMAL(10,2) NOT NULL, + tax_amount DECIMAL(10,2) DEFAULT 0, + total_amount DECIMAL(10,2) NOT NULL, + status ENUM('pending', 'paid', 'overdue', 'cancelled') DEFAULT 'pending', + due_date DATE NOT NULL, + paid_at TIMESTAMP, + payment_method VARCHAR(50), + transaction_id VARCHAR(100), + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +#### Videos +```sql +CREATE TABLE videos ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + uploader_id UUID REFERENCES users(id) ON DELETE CASCADE, + patient_id UUID REFERENCES patients(id) ON DELETE CASCADE, + title VARCHAR(255) NOT NULL, + description TEXT, + file_url VARCHAR(500) NOT NULL, + thumbnail_url VARCHAR(500), + file_size BIGINT, + duration_seconds INTEGER, + video_type ENUM('initial_assessment', 'treatment', 'exercise', 'progress') NOT NULL, + is_public BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +## API Endpoints + +### Authentication +- `POST /api/auth/register` - User registration +- `POST /api/auth/login` - User login +- `POST /api/auth/refresh` - Refresh JWT token +- `POST /api/auth/logout` - User logout +- `POST /api/auth/forgot-password` - Password reset request +- `POST /api/auth/reset-password` - Password reset confirmation + +### Patient Management +- `GET /api/patients` - List all patients (therapist/admin only) +- `GET /api/patients/:id` - Get patient details +- `PUT /api/patients/:id` - Update patient information +- `GET /api/patients/:id/sessions` - Get patient session history +- `GET /api/patients/:id/invoices` - Get patient billing history + +### Appointment Management +- `GET /api/appointments` - List appointments (filtered by user role) +- `POST /api/appointments` - Create new appointment +- `GET /api/appointments/:id` - Get appointment details +- `PUT /api/appointments/:id` - Update appointment +- `DELETE /api/appointments/:id` - Cancel appointment +- `GET /api/availability/:therapistId` - Get therapist availability + +### Session Management +- `GET /api/sessions` - List sessions +- `POST /api/sessions` - Create session record +- `GET /api/sessions/:id` - Get session details +- `PUT /api/sessions/:id` - Update session notes +- `GET /api/sessions/stats` - Get session statistics + +### Billing & Payments +- `GET /api/invoices` - List invoices +- `POST /api/invoices` - Create invoice +- `GET /api/invoices/:id` - Get invoice details +- `POST /api/payments` - Process payment +- `GET /api/payments/:id` - Get payment details + +### Video Management +- `GET /api/videos` - List videos (filtered by permissions) +- `POST /api/videos/upload` - Upload video file +- `GET /api/videos/:id` - Get video details +- `PUT /api/videos/:id` - Update video metadata +- `DELETE /api/videos/:id` - Delete video +- `GET /api/videos/:id/stream` - Stream video content + +### Notifications +- `GET /api/notifications` - Get user notifications +- `PUT /api/notifications/:id/read` - Mark notification as read +- `POST /api/notifications/preferences` - Update notification preferences + +## Security Considerations + +### Authentication & Authorization +- JWT-based authentication with refresh tokens +- Role-based access control (RBAC) +- Multi-factor authentication (MFA) for therapists +- Session timeout and automatic logout +- Password complexity requirements + +### Data Protection +- HIPAA compliance for patient data +- End-to-end encryption for sensitive data +- Secure file upload with virus scanning +- Data anonymization for analytics +- Regular security audits and penetration testing + +### Privacy & Compliance +- GDPR compliance for EU users +- Patient consent management +- Data retention policies +- Audit logs for all data access +- Secure data deletion procedures + +## Mobile App Features + +### iOS App (Swift/SwiftUI) +- Native iOS design patterns +- HealthKit integration for patient data +- Push notifications for appointments +- Biometric authentication (Face ID/Touch ID) +- Offline mode for viewing session history +- Camera integration for video uploads + +### Android App (Kotlin/Jetpack Compose) +- Material Design 3 components +- Google Fit integration +- Firebase Cloud Messaging +- Biometric authentication +- Background sync capabilities +- Camera and gallery integration + +### Cross-Platform Considerations +- Shared business logic through API +- Consistent UI/UX across platforms +- Platform-specific optimizations +- Native performance for video playback +- Offline data synchronization + +## Development Phases + +### Phase 1: Core Foundation (Weeks 1-4) +- User authentication and registration +- Basic patient and therapist profiles +- Simple appointment booking system +- Database setup and basic API endpoints +- Web application MVP + +### Phase 2: Session Management (Weeks 5-8) +- Session recording and note-taking +- Basic billing and invoice generation +- Patient session history +- Therapist dashboard improvements +- Mobile app development start + +### Phase 3: Payment Integration (Weeks 9-12) +- Payment gateway integration (Stripe/PayPal) +- Invoice management system +- Payment history and receipts +- Automated billing workflows +- Mobile app core features + +### Phase 4: Video Features (Weeks 13-16) +- Video upload and storage +- Video streaming and playback +- Video categorization and tagging +- Patient video submissions +- Mobile app video features + +### Phase 5: Advanced Features (Weeks 17-20) +- Advanced analytics and reporting +- Communication system (messaging) +- Notification system +- Mobile app completion +- Performance optimization + +### Phase 6: Testing & Deployment (Weeks 21-24) +- Comprehensive testing (unit, integration, E2E) +- Security testing and compliance review +- Performance testing and optimization +- App store submissions +- Production deployment and monitoring + +## Deployment Architecture + +### Production Environment +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Load Balancer β”‚ β”‚ Web Server β”‚ β”‚ API Server β”‚ +β”‚ (Nginx/HAProxy│────│ (React SPA) │────│ (Node.js/API) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ File Storage β”‚ β”‚ Database β”‚ + β”‚ (AWS S3/GCS) β”‚ β”‚ (PostgreSQL) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Cache Layer β”‚ + β”‚ (Redis) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +### Monitoring & Logging +- Application Performance Monitoring (APM) +- Error tracking and alerting +- Database performance monitoring +- User analytics and behavior tracking +- System health checks and uptime monitoring + +## Cost Estimation + +### Development Costs (24 weeks) +- **Backend Developer**: $80-120/hour Γ— 960 hours = $76,800 - $115,200 +- **Frontend Developer**: $70-100/hour Γ— 800 hours = $56,000 - $80,000 +- **Mobile Developer**: $80-120/hour Γ— 640 hours = $51,200 - $76,800 +- **UI/UX Designer**: $60-90/hour Γ— 320 hours = $19,200 - $28,800 +- **DevOps Engineer**: $90-130/hour Γ— 160 hours = $14,400 - $20,800 +- **Project Manager**: $70-100/hour Γ— 480 hours = $33,600 - $48,000 + +**Total Development**: $251,200 - $369,600 + +### Infrastructure Costs (Monthly) +- **Cloud Hosting**: $200-500/month +- **Database**: $100-300/month +- **File Storage & CDN**: $50-200/month +- **Third-party Services**: $100-300/month +- **Monitoring & Security**: $50-150/month + +**Total Monthly Infrastructure**: $500-1,450 + +### Third-party Services +- **Payment Processing**: 2.9% + $0.30 per transaction +- **Video Storage**: $0.02-0.05 per GB/month +- **SMS/Email Services**: $0.01-0.10 per message +- **Push Notifications**: Free tier available, then $1/1000 notifications + +## Risk Assessment & Mitigation + +### Technical Risks +- **Video Storage Costs**: Implement compression and CDN optimization +- **Scalability Issues**: Use microservices architecture and horizontal scaling +- **Data Security**: Regular security audits and compliance reviews +- **Mobile App Approval**: Follow platform guidelines and prepare for review process + +### Business Risks +- **HIPAA Compliance**: Work with legal experts and compliance consultants +- **Payment Processing**: Use established providers with healthcare experience +- **User Adoption**: Implement comprehensive onboarding and training +- **Competition**: Focus on unique features and excellent user experience + +## Success Metrics + +### Technical KPIs +- **System Uptime**: >99.9% +- **API Response Time**: <200ms average +- **Mobile App Performance**: <3 second load times +- **Video Upload Success Rate**: >95% + +### Business KPIs +- **User Adoption Rate**: Track monthly active users +- **Session Completion Rate**: Monitor appointment show rates +- **Payment Success Rate**: Track billing and payment completion +- **Customer Satisfaction**: Regular surveys and feedback collection + +## Conclusion + +This physiotherapy management system will provide a comprehensive solution for patient management, appointment booking, billing, and video sharing across web and mobile platforms. The phased development approach ensures steady progress while allowing for feedback and iterations throughout the development process. + +The system is designed to be scalable, secure, and compliant with healthcare regulations while providing an excellent user experience for both patients and physiotherapists. + +## Next Steps + +1. **Stakeholder Review**: Present this specification to your physiotherapist friend for feedback +2. **Technical Team Assembly**: Recruit developers, designers, and project managers +3. **Detailed Planning**: Create detailed user stories and technical requirements +4. **Prototype Development**: Build a minimal viable product (MVP) for validation +5. **Iterative Development**: Follow the phased approach with regular feedback cycles + +--- + +*This document serves as a comprehensive guide for developing the physiotherapy management system. Regular updates and revisions should be made based on stakeholder feedback and changing requirements.* \ No newline at end of file