Kulcare Docs
DeveloperCare plansBackend

LHR Implementation Progress & Testing Plan

Overview

This document tracks the implementation progress of the Longitudinal Health Records (LHR) feature and provides a systematic testing plan.

1. Changes Made in enh-health-record Branch

Backend Changes

New Controllers Created

  • backend/parts/clinic/controllers/clinic_patients_lhr_controller.rb - Main LHR API endpoints for clinic-based access

New Interactors Created

  1. Clinic-Side Interactors (in parts/clinic/interactors/clinic_patients/)

    • get_longitudinal_health_record.rb - Main LHR data aggregation
    • create_patient_problem.rb - Create new patient problems
    • delete_patient_problem.rb - Delete patient problems
    • get_clinical_assessments.rb - Fetch clinical assessments
    • get_encounter_details.rb - Get specific encounter details
    • get_medication_details.rb - Get medication details
    • get_medication_timeline.rb - Medication history timeline
    • get_patient_problems.rb - Fetch patient problems
    • get_vitals_trends.rb - Vitals trends (delegates to patient-side)
    • link_problem_medications.rb - Link medications to problems
    • resolve_patient_problem.rb - Mark problems as resolved
    • schedule_follow_up_appointment.rb - Schedule follow-ups
    • update_medication_status.rb - Update medication status
    • update_patient_problem.rb - Update existing problems
  2. Patient-Side Interactors (in parts/patient/interactors/)

    • patients/get_longitudinal_health_record.rb - Core LHR logic
    • patients/get_vitals_trends.rb - Vitals trend analysis
    • patient_problems/create.rb - Create patient problem
    • patient_problems/delete.rb - Delete patient problem
    • patient_problems/link_medications.rb - Link medications
    • patient_problems/resolve.rb - Resolve problem
    • patient_problems/update.rb - Update problem
    • patients/get_vitals_trends.rb - Get vitals trends
  3. Doctor-Side Interactors

    • prescriptions/sync_to_lhr.rb - Sync finalized prescriptions to LHR tables

New Policies Created

  • backend/parts/clinic/policies/clinic_patients_lhr_controller_policy.rb - Authorization for LHR operations

Routes Added

  • Added comprehensive LHR routes in parts/clinic/routes.rb (lines 154-174)
  • Problem management CRUD endpoints
  • Medication management endpoints
  • Encounter management endpoints

Database Models Used

  • PatientProblem - For storing patient problems/conditions
  • PatientMedicine - For medication records (already existed)
  • ClinicalImpression - For clinical assessments
  • MedicationRequest - For medication requests
  • ServiceRequest - For lab/test orders
  • PatientVital - For vitals data
  • Appointment - Used as encounter records

Frontend Changes

New API Service

  • frontend/apps/cms/src/services/longitudinalHealthRecordApi.ts - Complete API client with all CRUD operations

New Components Created

  • PatientSummaryDashboard.tsx - Updated to use real vitals data with empty states
  • VitalsTrendChart.tsx - Updated to use real API data with empty states

Updated Components

  • LongitudinalHealthRecord.tsx - Integrated all CRUD operations with real API calls
  • Replaced all console.log placeholders with actual API interactions

New Hooks

  • useLongitudinalHealthRecord.ts - React Query hooks for LHR data fetching

Routes Added

  • /cms/careplan/patient/:clinic_patient_id - LHR view route

2. System Design Comparison

✅ Implemented Features

Core LHR Functionality

  • Patient summary dashboard with vitals, problems, medications
  • Problem list management (CRUD operations)
  • Medication timeline and management
  • Clinical assessments view
  • Vitals trends visualization
  • Encounter history
  • Empty state handling for all data types

API Architecture

  • Clinic-based API structure (/clinics/:clinic_id/patients/:id/longitudinal_health_record)
  • Proper authorization with Pundit policies
  • Error handling and validation
  • JSON API responses with proper serialization

Data Models

  • PatientProblem for conditions/problems
  • PatientMedicine for medications (reused existing)
  • PatientVital for vitals data (reused existing)
  • Appointment as encounter records
  • ClinicalImpression for assessments
  • MedicationRequest for medication orders
  • ServiceRequest for lab orders

❌ Missing/Incomplete Features

PDF Generation

  • ClinicalImpression PDFs
  • MedicationRequest PDFs
  • ServiceRequest PDFs
  • PatientProblem summaries
  • CarePlan PDFs
  • DiagnosticReport PDFs

FHIR Document Generation

  • FHIR ClinicalImpression resources
  • FHIR MedicationRequest resources
  • FHIR ServiceRequest resources
  • FHIR Observation resources
  • FHIR DiagnosticReport resources
  • FHIR CarePlan resources

Advanced Features

  • Problem-medication linking UI
  • Medication interaction checking
  • Allergy management
  • Care plan templates
  • Timeline view of all events
  • Export functionality

Integration Points

  • Integration with prescription finalization workflow
  • Integration with appointment completion
  • Integration with vitals capture during appointments
  • Automatic problem resolution workflows

3. Manual Testing Plan

Phase 1: Careplan Creation Testing

URL: http://localhost:3001/cms/prescription/29/21/queue?did=8

Test Cases:

  1. Basic Navigation

    • Page loads without errors
    • All tabs are accessible (Vitals, Observations, Medications, Investigations, Advice)
    • No console errors in browser
  2. Tab Functionality

    • Vitals tab: Can add/edit vitals
    • Observations tab: Can add clinical notes
    • Medications tab: Can add/edit medications
    • Investigations tab: Can order tests
    • Advice tab: Can add advice/instructions
  3. Data Persistence

    • Changes are saved properly
    • Auto-save functionality works
    • No data loss on tab switching

Phase 2: Careplan Finalization Testing

Test Cases:

  1. Finalization Process

    • Careplan can be finalized without errors
    • Proper validation messages shown
    • Success confirmation displayed
  2. LHR Data Sync (Backend)

    • PatientProblem records created from diagnosis
    • PatientMedicine records created (via existing GenerateMedicines)
    • ClinicalImpression records created
    • MedicationRequest records created
    • ServiceRequest records created
  3. PDF Generation (If Implemented)

    • ClinicalImpression PDF generated
    • MedicationRequest PDF generated
    • ServiceRequest PDF generated
    • CarePlan PDF generated
  4. FHIR Generation (If Implemented)

    • FHIR resources created for each entity
    • Proper FHIR format validation
    • FHIR documents stored/accessible

Phase 3: LHR View Testing

URL: http://localhost:3001/cms/careplan/patient/23060

Test Cases:

  1. Page Load

    • LHR page loads without errors
    • Patient information displayed correctly
    • All tabs visible and functional
  2. Problems Tab

    • Problems list displays (or proper empty state)
    • Can create new problems
    • Can edit existing problems
    • Can resolve problems
    • Can delete problems
    • Proper validation and error handling
  3. Medications Tab

    • Medications list displays (or proper empty state)
    • Can view medication details
    • Can update medication status
    • Timeline view works
  4. Encounters Tab

    • Encounter history displays
    • Can view encounter details
    • Proper chronological ordering
  5. Vitals Tab

    • Vitals trends display (or proper empty state)
    • Chart visualization works
    • Different time ranges work
    • Different vital types selectable
  6. Clinical Assessments Tab

    • Assessments display (or proper empty state)
    • Assessment details accessible
    • Proper chronological ordering

4. Code Review Checklist

Backend Files to Review

  • clinic_patients_lhr_controller.rb - API endpoints
  • All clinic interactors in clinic_patients/ - Business logic
  • All patient interactors - Core functionality
  • sync_to_lhr.rb - Prescription sync logic
  • Policy file - Authorization rules
  • Routes configuration - API structure

Frontend Files to Review

  • longitudinalHealthRecordApi.ts - API client
  • LongitudinalHealthRecord.tsx - Main component
  • PatientSummaryDashboard.tsx - Dashboard component
  • VitalsTrendChart.tsx - Chart component
  • Hook files - Data fetching logic

Review Criteria

  • Code follows existing patterns and conventions
  • Proper error handling implemented
  • Security considerations addressed
  • Performance optimizations applied
  • Comprehensive input validation
  • Consistent naming conventions
  • Adequate comments and documentation

5. RSpec Test Cases Plan

Controller Tests

  • ClinicPatientsLhrController spec
  • Authorization tests for all endpoints
  • Parameter validation tests
  • Response format tests

Interactor Tests (45 examples, 0 failures)

  • ClinicPatients::GetFamilyHistory - valid params, relationship/conditions filtering, summary data, clinic/patient validation
  • ClinicPatients::GetGoals - valid params, status/category filtering, summary data, clinic validation
  • ClinicPatients::GetSocialHistory - valid params, category/current filtering, summary data, clinic validation
  • ClinicPatients::GetImagingStudies - valid params, modality/body_site filtering, summary data, error handling
  • ClinicPatients::CreateFamilyHistory - valid params, record creation, attribute validation, error handling
  • ClinicPatients::CreateGoal - valid params, record creation, doctor association, error handling
  • ClinicPatients::CreateSocialHistory - valid params, creation with traits, error handling
  • ClinicPatients::CreateImagingStudy - valid params, DICOM info, record creation, error handling
  • All patient-side interactors (Family History, Goals, Social History, Imaging Studies)
  • SyncToLhr interactor
  • Edge case handling
  • Error condition tests

Model Tests (Phase 2 Models - COMPLETED)

  • FamilyMemberHistory - associations, validations, scopes
  • Goal - associations, validations, scopes (active, completed, by_priority), methods (active?, achieved?, update_achievement_status!)
  • SocialHistory - associations, validations, scopes (current, by_category, practice_viewable), methods (current?, display_category), current_summary
  • ImagingStudy - associations, validations, scopes (available, by_modality, interpreted, pending_interpretation), methods (modality_display_name, interpreted?, has_report?)

Total: 83 examples, 0 failures (Dec 26, 2024)

Clinical Data Backbone Tests (NEW - COMPLETED)

  • EpisodeOfCare model spec - 138 examples, 0 failures
    • Constants (STATUSES, EPISODE_TYPES, FREQUENCIES, REFERRAL_SOURCES, DISCHARGE_DISPOSITIONS)
    • Associations (patient, clinic, providers, encounters, care_plans, treatment_goals, progress_notes)
    • Validations (episode_type, status presence and inclusion)
    • Scopes (active, current, finished, for_patient, for_clinic, by_type, by_status, with_open_sessions, overdue)
    • Methods (progress_percentage, active?, on_hold?, complete?, sessions_complete?, remaining_sessions, overdue?, duration_days)
    • State transitions (activate!, put_on_hold!, resume!, finish!, cancel!, increment_session!)
  • EpisodesOfCareController request spec - 17 examples, 0 failures
    • POST /patients/:patient_id/episodes_of_care (create with condition anchoring)
    • GET /patients/:patient_id/episodes_of_care (index with filtering)
    • GET /episodes_of_care/:id (show)
    • POST /episodes_of_care/:id/activate
    • POST /episodes_of_care/:id/put_on_hold
    • POST /episodes_of_care/:id/resume
    • POST /episodes_of_care/:id/discharge
    • POST /episodes_of_care/:id/cancel
    • PUT /episodes_of_care/:id (update)
    • POST /episodes_of_care/:id/increment_session
  • EncounterDocumentsController request spec - 11 examples, 0 failures
    • POST /encounters/:encounter_id/documents (create)
    • GET /encounters/:encounter_id/documents (index)
    • GET /encounter_documents/:id (show)
    • PUT /encounter_documents/:id (update)
    • POST /encounter_documents/:id/sign (sign)
    • POST /encounter_documents/:id/lock (lock)
    • POST /encounter_documents/:id/amend (amend)
    • GET /encounter_documents/:id/amendment_chain (not found case)

Clinical Data Backbone Total: 250 examples, 0 failures (Dec 26, 2024)

Integration Tests

  • End-to-end LHR workflow
  • Prescription to LHR sync
  • Multi-user scenarios
  • Data consistency tests

6. Current Status

✅ Completed

  • Backend API structure complete
  • Frontend integration complete
  • Basic CRUD operations working
  • Empty state handling implemented
  • Route configuration complete
  • Authorization framework in place
  • Phase 1 endpoints (allergies, procedures, immunizations, lab_results, care_plans, referrals)
  • Phase 2 models (FamilyMemberHistory, Goal, SocialHistory, ImagingStudy)
  • Phase 2 model specs (73 examples, 0 failures)
  • Phase 2 interactor specs (45 examples, 0 failures) - All Get/Create operations covered
  • Phase 2 factories with comprehensive traits
  • Clinical Data Backbone - Core Models (NEW):
    • EpisodeOfCare model with full FHIR-aligned lifecycle (planned/active/onhold/finished/cancelled)
    • EncounterDocument model with document workflow (draft/signed/locked/amended)
    • TreatmentGoal model for episode-level goals
    • ProgressNote model for episode progress tracking
    • EpisodeCondition join model linking episodes to patient problems
    • CarePlan model (FHIR-aligned planning resource)
  • Clinical Data Backbone - Controllers & Routes (NEW):
    • EpisodesOfCareController with full CRUD and lifecycle actions
    • EncounterDocumentsController with document workflow actions
    • Nested routes under patients and standalone routes by ID
  • Clinical Data Backbone - Tests (NEW):
    • EpisodeOfCare model spec - 74 examples, 0 failures
    • Encounter model spec - 15 examples, 0 failures
    • EncounterDocument model spec - 64 examples, 0 failures
    • EncounterParticipant model spec - 69 examples, 0 failures
    • EpisodesOfCareController request spec - 17 examples, 0 failures
    • EncounterDocumentsController request spec - 11 examples, 0 failures
  • EncounterParticipant Model (NEW) - Multi-provider encounter support:
    • Migration with roles, practitioner_type, permissions (can_view_private_notes, can_sign, can_edit)
    • Model with validations, scopes, and instance methods
    • Factory with traits for all roles (primary, assistant, supervisor, scribe, consultant, observer)
    • Comprehensive model spec (69 examples)
  • Nested Participants Attributes (NEW) - Encounter interactor integration:
    • accepts_nested_attributes_for :encounter_participants on Encounter model
    • EncounterActions::Create interactor handles participants_attributes
    • EncounterActions::Update interactor handles add/update/remove of participants
    • EncounterActions::Update spec - 9 examples, 0 failures
  • Architecture Documentation (NEW):
    • docs/care-plan/architecture/clinical-data-hierarchy.md - Comprehensive LHR/Episode/Encounter hierarchy
    • docs/care-plan/architecture/multi-practitioner-encounter-types.md - Document types by practitioner

🚧 In Progress

  • Manual testing phase
  • Code review phase
  • Controller tests for LHR endpoints

⏳ Pending

  • Controller tests for LHR endpoints
  • Integration tests (end-to-end workflows)
  • PDF generation implementation
  • FHIR document generation
  • Advanced UI features (Episode management UI in frontend)
  • LHR Episode Integration (frontend):
    • Update EncounterHistory to group by episode
    • Add Active Episodes card to PatientSummaryDashboard
    • Add episode filter to VitalsTrendChart
    • Enable problem-to-episode linking
  • Performance optimizations

7. Next Steps

  1. Immediate

    • Add controller tests for LHR endpoints
    • Manual testing of Phase 2 features (family history, goals, social history, imaging studies)
    • Add patient-side interactor tests (Index/Create for Phase 2 models)
    • Fix EncounterActions::Create spec (pre-existing ClinicPatient/ClinicSettings test setup issue)
  2. Short Term

    • Integration tests for end-to-end workflows
    • Code review of all Phase 2 implementations
    • Fix any bugs found during testing
    • EpisodeOfCare interactor specs (Create, Index, Show, Activate, Discharge)
  3. Medium Term

    • Implement PDF generation for clinical documents
    • Implement FHIR document generation
    • Add advanced UI features (timeline views, charts)
    • Performance optimization for large datasets
    • Frontend Episode Management UI:
      • EpisodeList component
      • EpisodeDetail component with progress tracking
      • EpisodeCreate dialog
      • TreatmentGoalManager component
    • LHR Episode Integration:
      • Group encounters by episode in EncounterHistory
      • Add Active Episodes card to PatientSummaryDashboard
      • Enable problem-to-episode linking in ProblemListManager

8. Known Issues

Current Warnings

  • sync_to_lhr.rb:49 - Unused variable appointment_id (needs cleanup)

Potential Issues to Test

  • Authorization edge cases
  • Data validation boundaries
  • Performance with large datasets
  • Concurrent user scenarios
  • Error recovery mechanisms

Document Status: Living document, updated as progress is made Last Updated: Dec 26, 2024 - Nested participants_attributes support complete Next Review: After controller tests for LHR endpoints

Test Summary

CategoryExamplesFailures
Phase 2 Models730
Phase 2 Interactors450
Clinical Data Backbone Models2220
- EpisodeOfCare740
- Encounter150
- EncounterDocument640
- EncounterParticipant690
Clinical Data Backbone Requests280
- EpisodesOfCareController170
- EncounterDocumentsController110
Encounter Interactors90
- EncounterActions::Update90
Total3770

On this page