Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Health Summary Updates #199

Merged
merged 13 commits into from
Jan 15, 2025
Prev Previous commit
Next Next commit
updatee
pauljohanneskraft committed Jan 7, 2025
commit f52f71eb5ede46ab6c766896b50b47cdab480cf9
14 changes: 9 additions & 5 deletions functions/models/src/codes/quantityUnit.ts
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@
//

import { type FHIRQuantity } from '../fhir/baseTypes/fhirQuantity.js'
import { Observation } from '../types/observation.js'

Check warning on line 10 in functions/models/src/codes/quantityUnit.ts

GitHub Actions / Lint

All imports in the declaration are only used as types. Use `import type`

export class QuantityUnit {
// Static Properties
@@ -72,14 +73,17 @@
)
}

convert(value: number, target: QuantityUnit): number | undefined {
return QuantityUnitConverter.allValues
convert(observation: Observation): Observation | undefined {
const value = QuantityUnitConverter.allValues
.find(
(converter) =>
converter.sourceUnit.equals(this) &&
converter.targetUnit.equals(target),
converter.sourceUnit.equals(observation.unit) &&
converter.targetUnit.equals(this),
)
?.convert(value)
?.convert(observation.value)
return value !== undefined ?
{ ...observation, value, unit: this }
: undefined
}

fhirQuantity(value: number): FHIRQuantity {
119 changes: 39 additions & 80 deletions functions/src/healthSummary/generate+localizations.ts
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ import {
SymptomScore,
UserMedicationRecommendationType,
} from '@stanfordbdhg/engagehf-models'
import { HealthSummaryData } from '../models/healthSummaryData'
import { HealthSummaryKeyPointMessage } from '../models/healthSummaryData.js'

export function healthSummaryLocalizations(languages: string[]) {
function localize(strings: Record<string, string>): string {
@@ -53,86 +53,45 @@ export function healthSummaryLocalizations(languages: string[]) {
title: localize({
en: 'KEY POINTS',
}),
messageTexts: {
optimizationsAvailable: localize({
en: 'There are possible options to improve your heart medicines. See the list of "Potential Med Changes" below to discuss these options with your care team. These meds can help you feel better and strengthen your heart.',
}),
missingHeartObservations: localize({
en: 'We are missing blood pressure and heart rate checks in the last two weeks. Try to check your blood pressure and heart rate multiple times a week to understand if your medications can be adjusted to help you feel better and strengthen your heart.',
}),
onTargetDose: localize({
en: 'Great news! You are on the target dose for your heart medicines at this time. Your symptoms are stable, and your weight is not rising. Make sure to keep taking your heart meds to help you feel better and strengthen your heart.',
}),
symptomsWorsened: localize({
en: 'Your heart symptoms worsened (see symptom report). Discuss with your care team how adjusting your medications can help you feel better.',
}),
weightIncreased: localize({
en: 'Your weight is increasing. This is a sign that you may be retaining fluid. Discuss with your care team and watch the weight educational video. Changing your heart medicines can lower your risk of having fluid gain in the future by strengthening your heart.',
}),
dizzinessIncreased: localize({
en: 'Your dizziness is more bothersome. Discuss with your care team options to improve your dizziness, and watch the dizziness educational video.',
}),
missingAllObservations: localize({
en: 'Check your blood pressure, heart rate, and weight more frequently and discuss with your care team how adjusting your medicines can help you feel better.',
}),
},
messages(data: HealthSummaryData): string[] {
const currentScore = data.symptomScores.at(0)
const previousScore = data.symptomScores.at(1)
const scoreAbove90 =
currentScore !== undefined ?
currentScore.overallScore >= 90
: undefined
const scoreDecreased =
currentScore !== undefined && previousScore !== undefined ?
currentScore.overallScore - previousScore.overallScore < -10
: undefined
const dizzinessScoreIncreased =
currentScore !== undefined && previousScore !== undefined ?
currentScore.dizzinessScore - previousScore.dizzinessScore > 1
: undefined

const optimizingRecommendations = data.recommendations.filter(
(recommendation) =>
[
UserMedicationRecommendationType.notStarted,
UserMedicationRecommendationType.improvementAvailable,
].includes(recommendation.displayInformation.type),
)
const observationsRequiredRecommendations = data.recommendations.filter(
(recommendation) =>
[
UserMedicationRecommendationType.moreLabObservationsRequired,
UserMedicationRecommendationType.morePatientObservationsRequired,
].includes(recommendation.displayInformation.type),
)
const recommendationsAtTargetDose = data.recommendations.filter(
(recommendation) =>
recommendation.displayInformation.type ===
UserMedicationRecommendationType.targetDoseReached,
)

const result: string[] = []

if (optimizingRecommendations.length > 0) {
result.push(this.messageTexts.optimizationsAvailable)
} else if (observationsRequiredRecommendations.length > 0) {
result.push(this.messageTexts.missingHeartObservations)
}

if (scoreDecreased === true) {
result.push(this.messageTexts.symptomsWorsened)
} else if (scoreDecreased === false && scoreAbove90 === true) {
result.push(this.messageTexts.weightIncreased)
} else if (scoreDecreased === false && scoreAbove90 === false) {
result.push(this.messageTexts.onTargetDose)
}

if (result.length === 0) {
result.push(this.messageTexts.onTargetDose)
}
text(keyPoints: HealthSummaryKeyPointMessage[]): string {
const messages = keyPoints.map((keyPoint) => {
switch (keyPoint) {
case HealthSummaryKeyPointMessage.OPTIMIZATIONS_AVAILABLE:
return localize({
en: 'There are possible options to improve your heart medicines. See the list of "Potential Med Changes" below to discuss these options with your care team. These meds can help you feel better and strengthen your heart.',
})
case HealthSummaryKeyPointMessage.MISSING_HEART_OBSERVATIONS:
return localize({
en: 'We are missing blood pressure and heart rate checks in the last two weeks. Try to check your blood pressure and heart rate multiple times a week to understand if your medications can be adjusted to help you feel better and strengthen your heart.',
})
case HealthSummaryKeyPointMessage.ON_TARGET_DOSE:
return localize({
en: 'Great news! You are on the target dose for your heart medicines at this time. Your symptoms are stable, and your weight is not rising. Make sure to keep taking your heart meds to help you feel better and strengthen your heart.',
})
case HealthSummaryKeyPointMessage.SYMPTOMS_WORSENED:
return localize({
en: 'Your heart symptoms worsened (see symptom report). Discuss with your care team how adjusting your medications can help you feel better.',
})
case HealthSummaryKeyPointMessage.WEIGHT_INCREASED:
return localize({
en: 'Your weight is increasing. This is a sign that you may be retaining fluid. Discuss with your care team and watch the weight educational video. Changing your heart medicines can lower your risk of having fluid gain in the future by strengthening your heart.',
})
case HealthSummaryKeyPointMessage.DIZZINESS_WORSENED:
return localize({
en: 'Your dizziness is more bothersome. Discuss with your care team options to improve your dizziness, and watch the dizziness educational video.',
})
case HealthSummaryKeyPointMessage.MISSING_ALL_OBSERVATIONS:
return localize({
en: 'Check your blood pressure, heart rate, and weight more frequently and discuss with your care team how adjusting your medicines can help you feel better.',
})
}
})

return []
return messages.length > 1 ?
messages
.map((message, index) => ` ${index + 1}. ${message}`)
.join('\n')
: messages.join('\n')
},
},
currentMedicationsSection: {
72 changes: 71 additions & 1 deletion functions/src/healthSummary/generate.test.ts
Original file line number Diff line number Diff line change
@@ -9,9 +9,13 @@
import fs from 'fs'
import { assert, expect } from 'chai'
import { generateHealthSummary } from './generate.js'
import { type HealthSummaryData } from '../models/healthSummaryData.js'
import {
HealthSummaryKeyPointMessage,
type HealthSummaryData,
} from '../models/healthSummaryData.js'
import { mockHealthSummaryData } from '../tests/mocks/healthSummaryData.js'
import { TestFlags } from '../tests/testFlags.js'
import { readCsv } from '../tests/helpers/csv.js'

describe('generateHealthSummary', () => {
function comparePdf(actual: Buffer, expected: Buffer): boolean {
@@ -78,4 +82,70 @@ describe('generateHealthSummary', () => {
comparePdf(actualData, expectedData)
}
})

it('should generate the correct key point messages', () => {
const allMessages = new Set<string>()
readCsv('src/tests/resources/keyPointMessages.csv', 55, (line, index) => {
if (index === 0) return

switch (line[0]) {
case 'Eligible meds for optimization':
break
case 'No eligible meds at optimization; measure BP':
break
case 'No eligible meds at optimization; at target doses':
break
default:
console.log('Unknown item at 0:', line[0])
}

switch (line[1]) {
case 'Change >-10 and KCCQ<90':
break
case 'Change >-10 and KCCQ>=90':
break
case 'Change <-10':
break
default:
console.log('Unknown item at 1:', line[1])
}

switch (line[2]) {
case 'No decrease <-25':
break
case 'Decrease <-25':
break
default:
console.log('Unknown item at 2:', line[2])
}

switch (line[3]) {
case 'No weight gain but weight measured':
break
case 'Weight increase':
break
case 'No weight measured':
break
default:
console.log('Unknown item at 3:', line[3])
}

const newMessages = separateKeyPointMessages(line[4])
for (const newMessage of newMessages) {
allMessages.add(newMessage)
}
// console.log(line)
})
console.log(Array.from(allMessages.values()).sort())
})
})

function separateKeyPointMessages(string: string): string[] {
return string
.split('\n')
.map((line) =>
(line.match(/[0-9]\.\) .*/g) ? line.substring(4) : line)
.replace(/\s+/g, ' ')
.trim(),
)
}
15 changes: 6 additions & 9 deletions functions/src/healthSummary/generate.ts
Original file line number Diff line number Diff line change
@@ -13,6 +13,7 @@ import {
presortedPercentile,
type Observation,
UserMedicationRecommendationType,
QuantityUnit,
} from '@stanfordbdhg/engagehf-models'
import { logger } from 'firebase-functions'
import 'jspdf-autotable' /* eslint-disable-line */
@@ -119,10 +120,8 @@ class HealthSummaryPdfGenerator extends PdfGenerator {
addKeyPointsSection() {
this.addSectionTitle(this.texts.keyPointsSection.title)

const messages = this.texts.keyPointsSection.messages(this.data)
messages.forEach((message, index) => {
this.addText(` ${index + 1}. ${message}`, this.textStyles.bodyColored)
})
const text = this.texts.keyPointsSection.text(this.data.keyPointMessages)
this.addText(text, this.textStyles.bodyColored)
}

addCurrentMedicationSection() {
@@ -334,12 +333,10 @@ class HealthSummaryPdfGenerator extends PdfGenerator {
].map((title) => this.cell(title)),
[
this.texts.vitalsSection.bodyWeightTable.rowTitle,
this.data.vitals.bodyWeight.at(0)?.value.toFixed(0) ?? '---',
avgWeight?.toFixed(0) ?? '---',
this.data.latestBodyWeight?.toFixed(0) ?? '---',
this.data.averageBodyWeight?.toFixed(0) ?? '---',
'-',
isFinite(maxWeight) && isFinite(minWeight) ?
(maxWeight - minWeight).toFixed(0)
: '---',
this.data.bodyWeightRange?.toFixed(0) ?? '---',
].map((title) => this.cell(title)),
],
columnWidth,
82 changes: 61 additions & 21 deletions functions/src/models/healthSummaryData.ts
Original file line number Diff line number Diff line change
@@ -8,8 +8,6 @@

import {
average,
compactMap,
QuantityUnit,
UserMedicationRecommendationType,
type FHIRAppointment,
type Observation,
@@ -42,7 +40,17 @@ export enum HealthSummaryMedicationRecommendationCategory {
export enum HealthSummaryWeightCategory {
INCREASING,
MISSING,
STABLE,
STABLE_OR_DECREASING,
}

export enum HealthSummaryKeyPointMessage {
OPTIMIZATIONS_AVAILABLE,
MISSING_HEART_OBSERVATIONS,
ON_TARGET_DOSE,
SYMPTOMS_WORSENED,
WEIGHT_INCREASED,
DIZZINESS_WORSENED,
MISSING_ALL_OBSERVATIONS,
}

export class HealthSummaryData {
@@ -56,7 +64,48 @@ export class HealthSummaryData {
vitals: HealthSummaryVitals
symptomScores: SymptomScore[]

// Computed Properties
// Computed Properties - Key Points

get keyPointMessages(): HealthSummaryKeyPointMessage[] {
return []
}

// Computed Properties - Body Weight

get latestBodyWeight(): number | null {
return this.vitals.bodyWeight.at(0)?.value ?? null
}

get averageBodyWeight(): number | null {
return (
average(this.vitals.bodyWeight.map((observation) => observation.value)) ??
null
)
}

get bodyWeightRange(): number | null {
const bodyWeightValues = this.vitals.bodyWeight.map(
(observation) => observation.value,
)
const minWeight = Math.min(...bodyWeightValues)
const maxWeight = Math.max(...bodyWeightValues)
return isFinite(minWeight) && isFinite(maxWeight) ?
maxWeight - minWeight
: null
}

get weightCategory(): HealthSummaryWeightCategory {
const averageWeight = this.averageBodyWeight
const latestWeight = this.latestBodyWeight
if (averageWeight === null || latestWeight === null)
return HealthSummaryWeightCategory.MISSING

return latestWeight - averageWeight > 1 ?
HealthSummaryWeightCategory.INCREASING
: HealthSummaryWeightCategory.STABLE_OR_DECREASING
}

// Computed Properties - Symptom Scores

get latestSymptomScore(): SymptomScore | null {
return this.symptomScores.at(0) ?? null
@@ -85,17 +134,17 @@ export class HealthSummaryData {
}
}

get weightCategory(): HealthSummaryWeightCategory {
const weight = average(
compactMap(this.vitals.bodyWeight, (observation) =>
observation.unit.convert(observation.value, QuantityUnit.lbs),
),
)
if (weight.length < 2) return HealthSummaryWeightCategory.MISSING
get dizzinessWorsened(): boolean {
const latestScore = this.latestSymptomScore?.dizzinessScore
const secondLatestScore = this.secondLatestSymptomScore?.dizzinessScore

return true
return latestScore !== undefined && secondLatestScore !== undefined ?
latestScore - secondLatestScore < -1
: false
}

// Computed Properties - Medication Recommendations

get recommendationCategory(): HealthSummaryMedicationRecommendationCategory {
const hasOptimizations = this.recommendations.some((recommendation) =>
[
@@ -119,15 +168,6 @@ export class HealthSummaryData {
return HealthSummaryMedicationRecommendationCategory.AT_TARGET
}

get dizzinessWorsened(): boolean {
const latestScore = this.latestSymptomScore?.dizzinessScore
const secondLatestScore = this.secondLatestSymptomScore?.dizzinessScore

return latestScore !== undefined && secondLatestScore !== undefined ?
latestScore - secondLatestScore < -1
: false
}

// Initialization

constructor(input: {
18 changes: 15 additions & 3 deletions functions/src/tests/helpers/csv.ts
Original file line number Diff line number Diff line change
@@ -16,15 +16,27 @@ export function readCsv(
) {
const fileContent = fs.readFileSync(path, 'utf8')
const lines = fileContent
.replace(/"(.*?)"/g, (str) =>
str.slice(1, -1).split(',').join('###COMMA###'),
.replace(/"([\s\S]*?)"/g, (str) =>
str
.slice(1, -1)
.split(',')
.join('###COMMA###')
.split('\n')
.join('###NEWLINE###'),
)
.split('\n')
expect(lines).to.have.length(expectedLines)
lines.forEach((line, index) => {
const values = line
.split(',')
.map((x) => x.split('###COMMA###').join(',').trim())
.map((x) =>
x
.split('###COMMA###')
.join(',')
.split('###NEWLINE###')
.join('\n')
.trim(),
)
perform(values, index)
})
}
116 changes: 116 additions & 0 deletions functions/src/tests/resources/keyPointMessages.csv

Large diffs are not rendered by default.