# ๐Ÿ“‹ Phase 2.7 Plan: Health Data Features ## Overview **Phase:** 2.7 - Health Data Features **Status:** โณ Not Started **Estimated Duration:** 2-3 weeks **Dependencies:** Phase 2.6 โœ… Complete **Priority:** HIGH - Core feature for user value --- ## ๐ŸŽฏ Phase Objectives Implement the core health data tracking features that define the Normogen platform's value proposition. This phase enables users to store, manage, and analyze their personal health information. ### Primary Goals 1. โœ… Store and retrieve lab results 2. โœ… Track medications and adherence 3. โœ… Record health statistics 4. โœ… Manage appointments 5. โœ… Implement data sharing capabilities --- ## ๐Ÿ“Š Data Models (Already Created!) Good news! **All data models are already implemented** from Phase 2.2. We just need to create the handlers and business logic. ### Existing Models #### 1. **Medication** ๐Ÿ’Š - **File:** `backend/src/models/medication.rs` - **Fields:** - `name`: String - Medication name - `dosage`: String - Dosage amount - `frequency`: String - How often to take - `start_date`: DateTime - When to start - `end_date`: Option - When to stop (nullable) - `notes`: Option - Additional notes - `user_id`: ObjectId - Owner - `profile_id`: ObjectId - Associated profile #### 2. **LabResult** ๐Ÿงช - **File:** `backend/src/models/lab_result.rs` - **Fields:** - `test_name`: String - Name of the test - `test_date`: DateTime - When the test was performed - `result_value`: String - The result - `unit`: String - Unit of measurement - `reference_range`: String - Normal range - `notes`: Option - Additional notes - `user_id`: ObjectId - Owner - `profile_id`: ObjectId - Associated profile #### 3. **HealthStatistics** ๐Ÿ“ˆ - **File:** `backend/src/models/health_stats.rs` - **Fields:** - `stat_type`: String - Type of statistic (weight, blood_pressure, etc.) - `value`: String - The value - `unit`: String - Unit of measurement - `measured_at`: DateTime - When measured - `notes`: Option - Additional notes - `user_id`: ObjectId - Owner - `profile_id`: ObjectId - Associated profile #### 4. **Appointment** ๐Ÿ“… - **File:** `backend/src/models/appointment.rs` - **Fields:** - `title`: String - Appointment title - `description`: Option - Description - `appointment_date`: DateTime - When the appointment is - `location`: Option - Location - `provider_name`: Option - Healthcare provider - `appointment_type`: String - Type of appointment - `status`: String - scheduled, completed, cancelled - `notes`: Option - Additional notes - `reminder_enabled`: bool - Whether to send reminders - `user_id`: ObjectId - Owner - `profile_id`: ObjectId - Associated profile #### 5. **HealthDocument** ๐Ÿ“„ - **File:** `backend/src/models/health_document.rs` - **Fields:** - `document_name`: String - Document name - `document_type`: String - Type of document - `document_url`: String - URL to stored file - `upload_date`: DateTime - When uploaded - `file_size`: i64 - File size in bytes - `mime_type`: String - File MIME type - `notes`: Option - Additional notes - `user_id`: ObjectId - Owner - `profile_id`: ObjectId - Associated profile --- ## ๐Ÿš€ Implementation Plan ### Task 1: Medication Management ๐Ÿ’Š **Priority:** HIGH **Estimated Time:** 3-4 days #### 1.1 Create Medication Handlers **File:** `backend/src/handlers/medications.rs` **Endpoints to Implement:** ```rust // Create a new medication POST /api/medications Request Body: { "name": "Aspirin", "dosage": "81mg", "frequency": "Once daily", "start_date": "2026-03-05T00:00:00Z", "end_date": null, "notes": "Take with food", "profile_id": "profile_id_here" } Response: 201 Created + Medication object // Get all medications for user GET /api/medications Query Params: - profile_id: Optional (filter by profile) Response: 200 OK + Array of medications // Get specific medication GET /api/medications/:id Response: 200 OK + Medication object // Update medication PUT /api/medications/:id Request Body: Same as create Response: 200 OK + Updated medication // Delete medication DELETE /api/medications/:id Response: 204 No Content // Get current medications (active) GET /api/medications/current Response: 200 OK + Array of active medications ``` #### 1.2 Features to Implement - โœ… CRUD operations - โœ… Filter by profile - โœ… Date-based queries (current vs past) - โœ… Validation (dates, required fields) - โœ… Authorization (user can only access their data) - โœ… Audit logging #### 1.3 Testing ``bash # Test creating medication curl -X POST http://localhost:8000/api/medications \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Aspirin", "dosage": "81mg", "frequency": "Once daily", "start_date": "2026-03-05T00:00:00Z", "profile_id": "PROFILE_ID" }' `` --- ### Task 2: Lab Results Management ๐Ÿงช **Priority:** HIGH **Estimated Time:** 3-4 days #### 2.1 Create Lab Result Handlers **File:** `backend/src/handlers/lab_results.rs` **Endpoints to Implement:** ```rust // Create lab result POST /api/lab-results Request Body: { "test_name": "Complete Blood Count", "test_date": "2026-03-05T10:30:00Z", "result_value": "13.5", "unit": "g/dL", "reference_range": "12.0-16.0", "notes": "Normal range", "profile_id": "profile_id_here" } Response: 201 Created + LabResult object // Get all lab results GET /api/lab-results Query Params: - profile_id: Optional (filter by profile) - test_name: Optional (filter by test type) - start_date: Optional (filter by date range) - end_date: Optional (filter by date range) Response: 200 OK + Array of lab results // Get specific lab result GET /api/lab-results/:id Response: 200 OK + LabResult object // Update lab result PUT /api/lab-results/:id Request Body: Same as create Response: 200 OK + Updated lab result // Delete lab result DELETE /api/lab-results/:id Response: 204 No Content // Get lab results by test type GET /api/lab-results/test/:test_name Response: 200 OK + Array of lab results // Get lab results trend (same test over time) GET /api/lab-results/trend/:test_name Response: 200 OK + Array of results with dates ``` #### 2.2 Features to Implement - โœ… CRUD operations - โœ… Filter by profile, test name, date range - โœ… Trend analysis (same test over time) - โœ… Abnormal result highlighting (outside reference range) - โœ… Validation - โœ… Authorization - โœ… Audit logging --- ### Task 3: Health Statistics Tracking ๐Ÿ“ˆ **Priority:** HIGH **Estimated Time:** 3-4 days #### 3.1 Create Health Statistics Handlers **File:** `backend/src/handlers/health_stats.rs` **Endpoints to Implement:** ```rust // Create health statistic POST /api/health-stats Request Body: { "stat_type": "weight", "value": "165", "unit": "lbs", "measured_at": "2026-03-05T08:00:00Z", "notes": "Morning weight", "profile_id": "profile_id_here" } Response: 201 Created + HealthStatistic object // Get all health statistics GET /api/health-stats Query Params: - profile_id: Optional (filter by profile) - stat_type: Optional (filter by type) - start_date: Optional (filter by date range) - end_date: Optional (filter by date range) Response: 200 OK + Array of statistics // Get specific health statistic GET /api/health-stats/:id Response: 200 OK + HealthStatistic object // Update health statistic PUT /api/health-stats/:id Request Body: Same as create Response: 200 OK + Updated statistic // Delete health statistic DELETE /api/health-stats/:id Response: 204 No Content // Get statistics by type GET /api/health-stats/type/:stat_type Query Params: - start_date: Optional - end_date: Optional Response: 200 OK + Array of statistics // Get statistics trend GET /api/health-stats/trend/:stat_type Query Params: - start_date: Optional - end_date: Optional Response: 200 OK + Array with calculated trends // Get latest statistics GET /api/health-stats/latest Response: 200 OK + Latest entry for each stat type ``` #### 3.2 Features to Implement - โœ… CRUD operations - โœ… Multiple filtering options - โœ… Trend analysis - โœ… Latest values - โœ… Data aggregation (min, max, average) - โœ… Validation - โœ… Authorization - โœ… Audit logging --- ### Task 4: Appointment Management ๐Ÿ“… **Priority:** MEDIUM **Estimated Time:** 2-3 days #### 4.1 Create Appointment Handlers **File:** `backend/src/handlers/appointments.rs` **Endpoints to Implement:** ```rust // Create appointment POST /api/appointments Request Body: { "title": "Annual Physical", "description": "Yearly checkup", "appointment_date": "2026-04-15T10:00:00Z", "location": "123 Main St", "provider_name": "Dr. Smith", "appointment_type": "checkup", "status": "scheduled", "notes": "Bring insurance card", "reminder_enabled": true, "profile_id": "profile_id_here" } Response: 201 Created + Appointment object // Get all appointments GET /api/appointments Query Params: - profile_id: Optional - status: Optional (scheduled, completed, cancelled) - start_date: Optional - end_date: Optional Response: 200 OK + Array of appointments // Get specific appointment GET /api/appointments/:id Response: 200 OK + Appointment object // Update appointment PUT /api/appointments/:id Request Body: Same as create Response: 200 OK + Updated appointment // Delete appointment DELETE /api/appointments/:id Response: 204 No Content // Get upcoming appointments GET /api/appointments/upcoming Response: 200 OK + Array of future appointments // Get past appointments GET /api/appointments/past Response: 200 OK + Array of past appointments // Update appointment status PATCH /api/appointments/:id/status Request Body: { "status": "completed" } Response: 200 OK + Updated appointment ``` #### 4.2 Features to Implement - โœ… CRUD operations - โœ… Status management (scheduled, completed, cancelled) - โœ… Upcoming vs past filtering - โœ… Reminder settings - โœ… Validation (dates in future for scheduled) - โœ… Authorization - โœ… Audit logging --- ### Task 5: Health Document Management ๐Ÿ“„ **Priority:** MEDIUM **Estimated Time:** 3-4 days #### 5.1 Create Health Document Handlers **File:** `backend/src/handlers/health_documents.rs` **Endpoints to Implement:** ```rust // Upload health document POST /api/health-documents Request: multipart/form-data - file: The file to upload - document_name: Document name - document_type: Document type - profile_id: Associated profile - notes: Optional notes Response: 201 Created + Document metadata // Get all documents GET /api/health-documents Query Params: - profile_id: Optional - document_type: Optional Response: 200 OK + Array of documents // Get specific document GET /api/health-documents/:id Response: 200 OK + Document object // Download document GET /api/health-documents/:id/download Response: 200 OK + File content // Update document metadata PUT /api/health-documents/:id Request Body: { "document_name": "Updated name", "notes": "Updated notes" } Response: 200 OK + Updated document // Delete document DELETE /api/health-documents/:id Response: 204 No Content // Get documents by type GET /api/health-documents/type/:document_type Response: 200 OK + Array of documents ``` #### 5.2 Features to Implement - โœ… File upload handling - โœ… File storage (local or S3) - โœ… Document metadata - โœ… Download functionality - โœ… File size limits - โœ… MIME type validation - โœ… Authorization - โœ… Audit logging **Note:** This task requires: - File storage backend (decide between local filesystem or S3-compatible storage) - Multipart form data handling - File cleanup on deletion --- ## ๐Ÿ”’ Security & Authorization ### Authorization Rules All health data endpoints must enforce: 1. **User Isolation** - Users can only access their own data - Profile-based filtering (user must own profile) - No cross-user data access 2. **Permission Checks** - Use existing permission middleware - Check `Read` permission for GET requests - Check `Write` permission for POST/PUT/DELETE 3. **Audit Logging** - Log all data creation (AUDIT_EVENT_HEALTH_DATA_CREATED) - Log all data updates (AUDIT_EVENT_HEALTH_DATA_UPDATED) - Log all data deletions (AUDIT_EVENT_HEALTH_DATA_DELETED) - Log all data access (AUDIT_EVENT_HEALTH_DATA_ACCESSED) 4. **Input Validation** - Validate all required fields - Sanitize user input - Validate date ranges - Validate file types and sizes --- ## ๐Ÿงช Testing Strategy ### Unit Tests For each handler, write tests for: - โœ… Successful operations - โœ… Authorization failures - โœ… Invalid input - โœ… Edge cases (empty results, dates, etc.) ### Integration Tests ``rust // backend/tests/health_data_tests.rs #[tokio::test] async fn test_create_medication() { // Test medication creation } #[tokio::test] async fn test_create_lab_result() { // Test lab result creation } #[tokio::test] async fn test_health_statistics_trend() { // Test trend calculation } #[tokio::test] async fn test_unauthorized_access() { // Test that users can't access others' data } `` ### API Tests ``bash # Test medication endpoints ./backend/test-medication-endpoints.sh # Test lab result endpoints ./backend/test-lab-result-endpoints.sh # Test health stats endpoints ./backend/test-health-stats-endpoints.sh # Test appointment endpoints ./backend/test-appointment-endpoints.sh `` --- ## ๐Ÿ“… Timeline ### Week 1: Medication & Lab Results - Day 1-2: Medication handlers and testing - Day 3-4: Lab result handlers and testing - Day 5: Integration and documentation ### Week 2: Health Statistics & Appointments - Day 1-2: Health statistics handlers and testing - Day 3-4: Appointment handlers and testing - Day 5: Integration and documentation ### Week 3: Documents & Integration - Day 1-3: Health document handlers and testing - Day 4: Comprehensive integration testing - Day 5: Documentation and deployment --- ## ๐Ÿ“ New Files to Create ### Handler Files 1. `backend/src/handlers/medications.rs` - Medication CRUD 2. `backend/src/handlers/lab_results.rs` - Lab result CRUD 3. `backend/src/handlers/health_stats.rs` - Health statistics CRUD 4. `backend/src/handlers/appointments.rs` - Appointment CRUD 5. `backend/src/handlers/health_documents.rs` - Document CRUD ### Test Files 6. `backend/tests/health_data_tests.rs` - Integration tests 7. `backend/test-medication-endpoints.sh` - API tests 8. `backend/test-lab-result-endpoints.sh` - API tests 9. `backend/test-health-stats-endpoints.sh` - API tests 10. `backend/test-appointment-endpoints.sh` - API tests ### Documentation 11. `PHASE_2.7_COMPLETION.md` - Completion report --- ## ๐Ÿ”„ Existing Files to Modify ### 1. `backend/src/handlers/mod.rs` Add handler modules: ``rust pub mod medications; pub mod lab_results; pub mod health_stats; pub mod appointments; pub mod health_documents; `` ### 2. `backend/src/main.rs` Add routes: ``rust // Medication routes .route("/api/medications", post(handlers::medications::create_medication)) .route("/api/medications", get(handlers::medications::get_medications)) .route("/api/medications/:id", get(handlers::medications::get_medication)) .route("/api/medications/:id", put(handlers::medications::update_medication)) .route("/api/medications/:id", delete(handlers::medications::delete_medication)) .route("/api/medications/current", get(handlers::medications::get_current_medications)) // Lab result routes .route("/api/lab-results", post(handlers::lab_results::create_lab_result)) .route("/api/lab-results", get(handlers::lab_results::get_lab_results)) // ... (and so on for all endpoints) `` ### 3. File Storage (if using local filesystem) Add storage configuration to `backend/src/config/mod.rs`: ``rust pub struct StorageConfig { pub upload_path: String, pub max_file_size: usize, } `` --- ## ๐ŸŽฏ Success Criteria ### Functional Requirements - โœ… All CRUD operations work for all health data types - โœ… Filtering and querying work correctly - โœ… Authorization enforced (users can't access others' data) - โœ… Audit logging on all mutations - โœ… Input validation prevents invalid data - โœ… File uploads work for documents ### Non-Functional Requirements - โœ… All endpoints respond in < 500ms - โœ… Unit tests cover 80%+ of code - โœ… Integration tests pass - โœ… API tests pass - โœ… No memory leaks - โœ… Proper error handling ### Documentation Requirements - โœ… All endpoints documented in API docs - โœ… Code is well-commented - โœ… Completion report written --- ## ๐Ÿ“Š Metrics to Track ### Development Metrics - Number of handlers implemented - Test coverage percentage - Number of API endpoints working - Code quality metrics ### Performance Metrics - API response times - Database query times - File upload speeds ### Quality Metrics - Number of bugs found in testing - Number of security issues - Code review feedback --- ## ๐Ÿšฆ Getting Started ### Step 1: Setup ``bash # Create branch for Phase 2.7 git checkout -b phase-2.7-health-data # Create handler files touch backend/src/handlers/medications.rs touch backend/src/handlers/lab_results.rs touch backend/src/handlers/health_stats.rs touch backend/src/handlers/appointments.rs touch backend/src/handlers/health_documents.rs `` ### Step 2: Implement Handlers (in order) 1. Start with medications (simplest) 2. Then lab results (similar to medications) 3. Then health statistics (adds trend analysis) 4. Then appointments (adds status management) 5. Finally documents (adds file handling) ### Step 3: Add Routes Update `backend/src/main.rs` to add routes for each handler. ### Step 4: Test Write and run tests for each handler. ### Step 5: Deploy Deploy to Solaria and run integration tests. --- ## ๐ŸŽ“ Key Learning Points ### MongoDB Query Patterns ``rust // Find by user and profile collection.find_one(doc! { "user_id": user_id, "profile_id": profile_id }) // Find with date range collection.find(doc! { "user_id": user_id, "test_date": doc! { "$gte": start_date, "$lte": end_date } }) // Aggregate for trends collection.aggregate(vec![ doc! { "$match": doc! { "user_id": user_id } }, doc! { "$sort": doc! { "measured_at": 1 } }, doc! { "$group": doc! { "_id": "$stat_type", "values": doc! { "$push": "$$ROOT" } }} ]) `` ### Authorization Pattern ``rust // In handler async fn create_medication( State(state): State, claims: JwtClaims, // From auth middleware Json(payload): Json, ) -> Result, StatusCode> { // Verify user owns the profile verify_profile_ownership(&state, &claims.user_id, &payload.profile_id)?; // Create medication let medication = create_medication_db(&state, payload).await?; // Log audit event state.audit_logger.log( AUDIT_EVENT_HEALTH_DATA_CREATED, &claims.user_id, "medication", &medication.id ).await; Ok(Json(medication)) } `` --- ## ๐Ÿ“ž Next Steps After Phase 2.7 ### Phase 2.8: Data Analysis & Insights - Statistical analysis of health data - Trend visualization endpoints - Health insights and recommendations - Data export functionality ### Phase 2.9: Notifications & Reminders - Email notifications for appointments - Medication reminders - Lab result alerts - In-app notifications ### Phase 2.10: API Documentation - OpenAPI/Swagger specification - Interactive API documentation - Client SDK generation --- ## โœจ Summary **Phase 2.7 is about bringing the health data models to life.** We already have excellent data models from Phase 2.2. Now we need to: 1. Create handlers to manage the data 2. Add routes to expose the endpoints 3. Implement proper authorization 4. Add comprehensive testing 5. Deploy and verify **The focus is on:** CRUD operations, filtering, querying, authorization, and audit logging. **Estimated time:** 2-3 weeks **Difficulty:** Medium (models are done, just need business logic) **Priority:** HIGH (core user value) **Ready to start?** Begin with Task 1 (Medication Management) - it's the simplest and will establish the pattern for the other handlers.