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

Handle missing tasks in careplans #94

Merged
merged 7 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions android/engine/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ dependencies {
api("com.squareup.retrofit2:retrofit-mock:$retrofitVersion")
api("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0")

implementation("ca.uhn.hapi.fhir:hapi-fhir-client-okhttp:${Dependencies.Versions.hapiFhir}")

val okhttpVersion = "4.12.0"
api("com.squareup.okhttp3:okhttp:$okhttpVersion")
api("com.squareup.okhttp3:logging-interceptor:$okhttpVersion")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import org.smartregister.fhircore.engine.configuration.ConfigurationRegistry
import org.smartregister.fhircore.engine.data.domain.Guardian
import org.smartregister.fhircore.engine.data.domain.PregnancyStatus
import org.smartregister.fhircore.engine.data.local.DefaultRepository
import org.smartregister.fhircore.engine.domain.model.CarePlanTask
import org.smartregister.fhircore.engine.domain.model.HealthStatus
import org.smartregister.fhircore.engine.domain.model.ProfileData
import org.smartregister.fhircore.engine.domain.model.RegisterData
Expand Down Expand Up @@ -245,7 +246,7 @@ constructor(
fhirEngine.withTransaction {
val patient = defaultRepository.loadResource<Patient>(resourceId)!!
val carePlan = patient.activeCarePlans(fhirEngine).firstOrNull()

val (exists, activities) = fetchCarePlanActivities(carePlan)
profileData =
ProfileData.HivProfileData(
logicalId = patient.logicalId,
Expand All @@ -265,7 +266,8 @@ constructor(
showIdentifierInProfile = true,
currentCarePlan = carePlan,
healthStatus = patient.extractHealthStatusFromMeta(patientTypeMetaTagCodingSystem),
tasks = fetchCarePlanActivities(carePlan),
tasks = activities,
hasMissingTasks = exists,
conditions = defaultRepository.activePatientConditions(patient.logicalId),
otherPatients = patient.otherChildren(),
guardians = patient.guardians(),
Expand Down Expand Up @@ -512,33 +514,49 @@ constructor(

private suspend fun fetchCarePlanActivities(
carePlan: CarePlan?,
): List<CarePlan.CarePlanActivityComponent> {
if (carePlan == null) return emptyList()
val activityOnList = mutableMapOf<String, CarePlan.CarePlanActivityComponent>()
val tasksToFetch = mutableListOf<String>()
for (planActivity in carePlan.activity) {
if (!planActivity.shouldShowOnProfile()) {
continue
}
val taskId = planActivity.outcomeReference.firstOrNull()?.extractId()
if (taskId != null) {
tasksToFetch.add(taskId)
activityOnList[taskId] = planActivity
): Pair<Boolean, List<CarePlanTask>> {
if (carePlan == null) return Pair(false, emptyList())

val activityOnList = mutableMapOf<String, CarePlanTask>()
val tasksToFetch =
carePlan.activity.mapNotNull { planActivity ->
if (planActivity.shouldShowOnProfile()) {
planActivity.outcomeReference.firstOrNull()?.extractId()?.also { taskId ->
activityOnList[taskId] = CarePlanTask(planActivity, false)
}
} else {
null
}
}
}
if (tasksToFetch.isNotEmpty()) {
val tasks = fhirEngine.getResourcesByIds<Task>(tasksToFetch)
tasks.forEach { task ->
val planActivity: CarePlan.CarePlanActivityComponent? = activityOnList[task.logicalId]
if (planActivity != null) {
planActivity.detail?.status = task.taskStatusToCarePlanActivityStatus()
activityOnList[task.logicalId] = planActivity

var hasMissingTask = false
val items: List<CarePlanTask> =
if (tasksToFetch.isNotEmpty()) {
val tasks = fhirEngine.getResourcesByIds<Task>(tasksToFetch).associateBy { it.logicalId }
activityOnList.map { (taskId, carePlanTask) ->
println(taskId)
tasks[taskId]?.let { task ->
val updatedTask =
carePlanTask.task.apply { detail?.status = task.taskStatusToCarePlanActivityStatus() }
carePlanTask.copy(task = updatedTask, taskExists = true)
}
?: run {
if (carePlanTask.task.detail?.status != CarePlan.CarePlanActivityStatus.SCHEDULED) {
hasMissingTask = true
}
carePlanTask.copy(taskExists = false)
}
}
} else {
activityOnList.values.toList()
}
}
return activityOnList.values.sortedWith(
compareBy(nullsLast()) { it.detail?.code?.text?.toBigIntegerOrNull() },
)

val sortedItems =
items.sortedWith(
compareBy(nullsLast()) { it.task.detail?.code?.text?.toBigIntegerOrNull() },
)

return Pair(hasMissingTask, sortedItems)
}

object ResourceValue {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
/*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.smartregister.fhircore.engine.data.remote.fhir.resource

import ca.uhn.fhir.rest.client.api.IGenericClient
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.datacapture.extensions.logicalId
import com.google.android.fhir.get
import java.util.Date
import javax.inject.Inject
import org.hl7.fhir.r4.model.Bundle
import org.hl7.fhir.r4.model.CarePlan
import org.hl7.fhir.r4.model.CarePlan.CarePlanActivityComponent
import org.hl7.fhir.r4.model.Coding
import org.hl7.fhir.r4.model.Meta
import org.hl7.fhir.r4.model.Period
import org.hl7.fhir.r4.model.Reference
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
import org.hl7.fhir.r4.model.Task
import org.smartregister.fhircore.engine.util.SharedPreferenceKey
import org.smartregister.fhircore.engine.util.SharedPreferencesHelper
import org.smartregister.fhircore.engine.util.SystemConstants.CARE_PLAN_REFERENCE_SYSTEM
import org.smartregister.fhircore.engine.util.SystemConstants.QUESTIONNAIRE_REFERENCE_SYSTEM
import org.smartregister.fhircore.engine.util.SystemConstants.RESOURCE_CREATED_ON_TAG_SYSTEM
import org.smartregister.fhircore.engine.util.extension.extractId
import org.smartregister.fhircore.engine.util.extension.generateCreatedOn
import org.smartregister.fhircore.engine.util.extension.getResourcesByIds
import org.smartregister.fhircore.engine.util.extension.shouldShowOnProfile
import org.smartregister.fhircore.engine.util.extension.toTaskStatus
import timber.log.Timber

class ResourceFixerService
@Inject
constructor(
private val fhirClient: IGenericClient,
private val fhirEngine: FhirEngine,
private val sharedPreferences: SharedPreferencesHelper,
) {
suspend fun fixCurrentCarePlan(patientId: String, carePlanId: String) {
val carePlan: CarePlan = fhirEngine.get(carePlanId)
val tasks = getMissingTasks(carePlan)
if (tasks.isEmpty()) {
return
}
Timber.i("Found missing tasks: ${tasks.size}")
val isOffline = sharedPreferences.read(SharedPreferenceKey.PATIENT_FIX_TYPE.name, false)
handleMissingTasks(patientId, carePlan, tasks, recreateAll = isOffline)
return
}

private suspend fun getMissingTasks(carePlan: CarePlan): List<CarePlanActivityComponent> {
val activityOnList = mutableMapOf<String, CarePlanActivityComponent>()
val missingTasks = mutableListOf<CarePlanActivityComponent>()
val tasksToFetch =
carePlan.activity.mapNotNull { planActivity ->
if (planActivity.shouldShowOnProfile()) {
planActivity.outcomeReference.firstOrNull()?.extractId()?.also { taskId ->
activityOnList[taskId] = planActivity
}
} else {
null
}
}
val tasks = fhirEngine.getResourcesByIds<Task>(tasksToFetch).associateBy { it.logicalId }
activityOnList.forEach { (taskId, activity) ->
if (activity.detail?.status != CarePlan.CarePlanActivityStatus.SCHEDULED) {
if (!tasks.containsKey(taskId)) {
missingTasks.add(activity)
}
}
}
return missingTasks
}

private suspend fun handleMissingTasks(
patientId: String,
carePlan: CarePlan,
tasks: List<CarePlanActivityComponent>,
recreateAll: Boolean,
) {
val resourceToSave = mutableListOf<Resource>()

if (recreateAll) {
resourceToSave.addAll(
tasks.map {
createGenericTask(
patientId = patientId,
activity = it,
carePlan = carePlan,
)
},
)
Timber.e("Recreating tasks: ${resourceToSave.size}")
} else {
val bundle = Bundle()
bundle.setType(Bundle.BundleType.TRANSACTION)
bundle.entry.addAll(
tasks.map { task ->
val taskId = task.outcomeReference.firstOrNull()?.extractId()
Bundle.BundleEntryComponent().apply {
request =
Bundle.BundleEntryRequestComponent().apply {
method = Bundle.HTTPVerb.GET
url = "${ResourceType.Task.name}/$taskId"
}
}
},
)

val tasksToRecreate = mutableListOf<CarePlanActivityComponent>()
val existingTasks = mutableListOf<Task>()

val resBundle = fhirClient.transaction().withBundle(bundle).execute()
for ((index, entry) in resBundle.entry.withIndex()) {
if (entry.hasResource()) {
existingTasks.add(entry.resource as Task)
} else {
tasksToRecreate.add(tasks[index])
}
}
resourceToSave.addAll(existingTasks)
if (tasksToRecreate.isNotEmpty()) {
resourceToSave.addAll(
tasksToRecreate.map {
createGenericTask(
patientId = patientId,
activity = it,
carePlan = carePlan,
)
},
)
}
Timber.e("Task on server: ${existingTasks.size}, Tasks to recreate: ${tasksToRecreate.size}")
}

fhirEngine.create(*resourceToSave.toTypedArray())
}

private fun createGenericTask(
patientId: String,
activity: CarePlanActivityComponent,
carePlan: CarePlan,
): Task {
val questId = activity.detail.code.coding.firstOrNull()?.code
val patientReference = Reference().apply { reference = "Patient/$patientId" }
val questRef = Reference().apply { reference = questId }

val period =
Period().apply {
start = Date()
end = Date()
}

val task =
Task().apply {
id = activity.outcomeReference.firstOrNull()?.extractId()
status = activity.detail.status.toTaskStatus()
intent = Task.TaskIntent.PLAN
priority = Task.TaskPriority.ROUTINE
description = activity.detail.description
authoredOn = Date()
lastModified = Date()
`for` = patientReference
executionPeriod = period
requester = carePlan.author
owner = carePlan.author
reasonReference = questRef
}

val meta =
Meta().apply {
tag =
carePlan.meta.tag
.filter {
it.system != RESOURCE_CREATED_ON_TAG_SYSTEM && it.system != CARE_PLAN_REFERENCE_SYSTEM
}
.toMutableList()
tag.add(
Coding().apply {
system = CARE_PLAN_REFERENCE_SYSTEM
code = "CarePlan/${carePlan.id}"
display = carePlan.title
},
)
tag.add(
Coding().apply {
system = QUESTIONNAIRE_REFERENCE_SYSTEM
code = questId
},
)
}

task.meta = meta
task.generateCreatedOn()
return task
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
package org.smartregister.fhircore.engine.di

import ca.uhn.fhir.context.FhirContext
import ca.uhn.fhir.okhttp.client.OkHttpRestfulClientFactory
import ca.uhn.fhir.parser.IParser
import ca.uhn.fhir.rest.client.api.IGenericClient
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
Expand Down Expand Up @@ -166,6 +168,19 @@ class NetworkModule {
fun provideFhirResourceService(@RegularRetrofit retrofit: Retrofit): FhirResourceService =
retrofit.create(FhirResourceService::class.java)

@Provides
fun providesGenericFhirClient(
@WithAuthorizationOkHttpClientQualifier okHttpClient: OkHttpClient,
configService: ConfigService,
): IGenericClient {
val factory = OkHttpRestfulClientFactory()
val ctx = FhirContext.forR4()
factory.fhirContext = ctx
factory.setHttpClient(okHttpClient)
ctx.restfulClientFactory = factory
return ctx.newRestfulGenericClient(configService.provideAuthConfiguration().fhirServerBaseUrl)
}

companion object {
const val TIMEOUT_DURATION = 120L
const val AUTHORIZATION = "Authorization"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.smartregister.fhircore.engine.domain.model

import org.hl7.fhir.r4.model.CarePlan

data class CarePlanTask(
val task: CarePlan.CarePlanActivityComponent,
val taskExists: Boolean,
)
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ sealed class ProfileData(open val logicalId: String, open val name: String) {
val addressDistrict: String = "",
val addressTracingCatchment: String = "",
val addressPhysicalLocator: String = "",
val tasks: List<CarePlan.CarePlanActivityComponent> = listOf(),
val hasMissingTasks: Boolean = false,
val tasks: List<CarePlanTask> = listOf(),
val chwAssigned: Reference,
val healthStatus: HealthStatus,
val phoneContacts: List<String> = listOf(),
Expand Down
Loading
Loading