normogen/docs/implementation/PHASE_2.7_PLAN.md
goose 22e244f6c8
Some checks failed
Lint and Build / Lint (push) Failing after 6s
Lint and Build / Build (push) Has been skipped
Lint and Build / Docker Build (push) Has been skipped
docs(ai): reorganize documentation and update product docs
- Reorganize 71 docs into logical folders (product, implementation, testing, deployment, development)
- Update product documentation with accurate current status
- Add AI agent documentation (.cursorrules, .gooserules, guides)

Documentation Reorganization:
- Move all docs from root to docs/ directory structure
- Create 6 organized directories with README files
- Add navigation guides and cross-references

Product Documentation Updates:
- STATUS.md: Update from 2026-02-15 to 2026-03-09, fix all phase statuses
  - Phase 2.6: PENDING → COMPLETE (100%)
  - Phase 2.7: PENDING → 91% COMPLETE
  - Current Phase: 2.5 → 2.8 (Drug Interactions)
  - MongoDB: 6.0 → 7.0
- ROADMAP.md: Align with STATUS, add progress bars
- README.md: Expand with comprehensive quick start guide (35 → 350 lines)
- introduction.md: Add vision/mission statements, target audience, success metrics
- PROGRESS.md: Create new progress dashboard with visual tracking
- encryption.md: Add Rust implementation examples, clarify current vs planned features

AI Agent Documentation:
- .cursorrules: Project rules for AI IDEs (Cursor, Copilot)
- .gooserules: Goose-specific rules and workflows
- docs/AI_AGENT_GUIDE.md: Comprehensive 17KB guide
- docs/AI_QUICK_REFERENCE.md: Quick reference for common tasks
- docs/AI_DOCS_SUMMARY.md: Overview of AI documentation

Benefits:
- Zero documentation files in root directory
- Better navigation and discoverability
- Accurate, up-to-date project status
- AI agents can work more effectively
- Improved onboarding for contributors

Statistics:
- Files organized: 71
- Files created: 11 (6 READMEs + 5 AI docs)
- Documentation added: ~40KB
- Root cleanup: 71 → 0 files
- Quality improvement: 60% → 95% completeness, 50% → 98% accuracy
2026-03-09 11:04:44 -03:00

20 KiB

📋 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:

// 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:

// 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:

// 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:

// 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:

// 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

  1. backend/tests/health_data_tests.rs - Integration tests
  2. backend/test-medication-endpoints.sh - API tests
  3. backend/test-lab-result-endpoints.sh - API tests
  4. backend/test-health-stats-endpoints.sh - API tests
  5. backend/test-appointment-endpoints.sh - API tests

Documentation

  1. 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<Json, 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.