Skip to content

Commit

Permalink
Fix data refresh
Browse files Browse the repository at this point in the history
Signed-off-by: Elly Kitoto <[email protected]>
  • Loading branch information
ellykits committed Jun 11, 2024
1 parent aaa1d5c commit d425b90
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 97 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ import org.smartregister.fhircore.quest.ui.shared.models.QuestionnaireSubmission
sealed class AppEvent {
data class OnSubmitQuestionnaire(val questionnaireSubmission: QuestionnaireSubmission) :
AppEvent()

data object RefreshRegisterData : AppEvent()
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import java.time.Instant
import javax.inject.Inject
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.hl7.fhir.r4.model.IdType
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.smartregister.fhircore.engine.configuration.QuestionnaireConfig
Expand Down Expand Up @@ -132,28 +133,26 @@ open class AppMainActivity : BaseMultiLanguageActivity(), QuestionnaireHandler,

// Setup the drawer and schedule jobs
appMainViewModel.run {
lifecycleScope.launch {
retrieveAppMainUiState()
if (isDeviceOnline()) {
// Do not schedule sync until location selected when strategy is RelatedEntityLocation
// Use applicationConfiguration.usePractitionerAssignedLocationOnSync to identify
// if we need to trigger sync based on assigned locations or not
if (applicationConfiguration.syncStrategy.contains(SyncStrategy.RelatedEntityLocation)) {
if (
applicationConfiguration.usePractitionerAssignedLocationOnSync ||
syncLocationIdsProtoStore.data.firstOrNull()?.isNotEmpty() == true
) {
triggerSync()
}
} else {
retrieveAppMainUiState()
if (isDeviceOnline()) {
// Do not schedule sync until location selected when strategy is RelatedEntityLocation
// Use applicationConfiguration.usePractitionerAssignedLocationOnSync to identify
// if we need to trigger sync based on assigned locations or not
if (applicationConfiguration.syncStrategy.contains(SyncStrategy.RelatedEntityLocation)) {
if (
applicationConfiguration.usePractitionerAssignedLocationOnSync ||
runBlocking { syncLocationIdsProtoStore.data.firstOrNull() }?.isNotEmpty() == true
) {
triggerSync()
}
} else {
showToast(
getString(org.smartregister.fhircore.engine.R.string.sync_failed),
Toast.LENGTH_LONG,
)
triggerSync()
}
} else {
showToast(
getString(org.smartregister.fhircore.engine.R.string.sync_failed),
Toast.LENGTH_LONG,
)
}
schedulePeriodicJobs()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

package org.smartregister.fhircore.quest.ui.main

import android.content.Context
import android.widget.Toast
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateMapOf
Expand All @@ -25,7 +24,6 @@ import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.google.android.fhir.sync.CurrentSyncJobStatus
Expand All @@ -39,24 +37,18 @@ import javax.inject.Inject
import kotlin.time.Duration
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.hl7.fhir.r4.model.Enumerations
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.hl7.fhir.r4.model.ResourceType
import org.hl7.fhir.r4.model.Task
import org.smartregister.fhircore.engine.R
import org.smartregister.fhircore.engine.configuration.ConfigType
import org.smartregister.fhircore.engine.configuration.ConfigurationRegistry
import org.smartregister.fhircore.engine.configuration.QuestionnaireConfig
import org.smartregister.fhircore.engine.configuration.app.ApplicationConfiguration
import org.smartregister.fhircore.engine.configuration.geowidget.GeoWidgetConfiguration
import org.smartregister.fhircore.engine.configuration.navigation.ICON_TYPE_REMOTE
import org.smartregister.fhircore.engine.configuration.navigation.NavigationConfiguration
import org.smartregister.fhircore.engine.configuration.navigation.NavigationMenuConfig
import org.smartregister.fhircore.engine.configuration.report.measure.MeasureReportConfiguration
import org.smartregister.fhircore.engine.configuration.workflow.ActionTrigger
import org.smartregister.fhircore.engine.data.local.register.RegisterRepository
import org.smartregister.fhircore.engine.domain.model.ActionParameter
import org.smartregister.fhircore.engine.domain.model.ActionParameterType
import org.smartregister.fhircore.engine.sync.SyncBroadcaster
import org.smartregister.fhircore.engine.task.FhirCarePlanGenerator
import org.smartregister.fhircore.engine.task.FhirCompleteCarePlanWorker
Expand All @@ -78,7 +70,6 @@ import org.smartregister.fhircore.engine.util.extension.tryParse
import org.smartregister.fhircore.quest.navigation.MainNavigationScreen
import org.smartregister.fhircore.quest.navigation.NavigationArg
import org.smartregister.fhircore.quest.ui.report.measure.worker.MeasureReportMonthPeriodWorker
import org.smartregister.fhircore.quest.ui.shared.QuestionnaireHandler
import org.smartregister.fhircore.quest.ui.shared.models.QuestionnaireSubmission
import org.smartregister.fhircore.quest.util.extensions.decodeBinaryResourcesToBitmap
import org.smartregister.fhircore.quest.util.extensions.handleClickEvent
Expand Down Expand Up @@ -107,9 +98,6 @@ constructor(
),
)

private val simpleDateFormat = SimpleDateFormat(SYNC_TIMESTAMP_OUTPUT_FORMAT, Locale.getDefault())
private val registerCountMap: SnapshotStateMap<String, Long> = mutableStateMapOf()

val applicationConfiguration: ApplicationConfiguration by lazy {
configurationRegistry.retrieveConfiguration(ConfigType.Application, paramsMap = emptyMap())
}
Expand All @@ -121,6 +109,8 @@ constructor(
private val measureReportConfigurations: List<MeasureReportConfiguration> by lazy {
configurationRegistry.retrieveConfigurations(ConfigType.MeasureReport)
}
private val simpleDateFormat = SimpleDateFormat(SYNC_TIMESTAMP_OUTPUT_FORMAT, Locale.getDefault())
private val registerCountMap: SnapshotStateMap<String, Long> = mutableStateMapOf()

fun retrieveIconsAsBitmap() {
navigationConfiguration.clientRegisters
Expand All @@ -133,7 +123,7 @@ constructor(
.decodeBinaryResourcesToBitmap(viewModelScope, registerRepository)
}

suspend fun retrieveAppMainUiState(refreshAll: Boolean = true) {
fun retrieveAppMainUiState(refreshAll: Boolean = true) {
if (refreshAll) {
appMainUiState.value =
appMainUiStateOf(
Expand All @@ -147,7 +137,10 @@ constructor(
)
}

// Count data for configured registers by populating the register count map
countRegisterData()
}

fun countRegisterData() {
viewModelScope.launch {
navigationConfiguration.run {
clientRegisters.countRegisterData()
Expand Down Expand Up @@ -179,7 +172,7 @@ constructor(
SharedPreferenceKey.LAST_SYNC_TIMESTAMP.name,
formatLastSyncTimestamp(event.state.timestamp),
)
viewModelScope.launch { retrieveAppMainUiState() }
retrieveAppMainUiState()
}
}
is AppMainEvent.TriggerWorkflow ->
Expand Down Expand Up @@ -214,31 +207,6 @@ constructor(
}
}

fun launchFamilyRegistrationWithLocationId(
context: Context,
locationId: String,
questionnaireConfig: QuestionnaireConfig,
) {
viewModelScope.launch {
val prePopulateLocationIdParameter =
ActionParameter(
key = "locationId",
paramType = ActionParameterType.PREPOPULATE,
dataType = Enumerations.DataType.STRING,
resourceType = ResourceType.Location,
value = locationId,
linkId = "household-location-reference",
)
if (context is QuestionnaireHandler) {
context.launchQuestionnaire(
context = context,
questionnaireConfig = questionnaireConfig,
actionParams = listOf(prePopulateLocationIdParameter),
)
}
}
}

private suspend fun List<NavigationMenuConfig>.countRegisterData() {
// Set count for registerId against its value. Use action Id; otherwise default to menu id
return this.filter { it.showCount }
Expand Down Expand Up @@ -271,26 +239,6 @@ constructor(
fun retrieveLastSyncTimestamp(): String? =
sharedPreferencesHelper.read(SharedPreferenceKey.LAST_SYNC_TIMESTAMP.name, null)

fun launchProfileFromGeoWidget(
navController: NavController,
geoWidgetConfigId: String,
resourceId: String,
) {
val geoWidgetConfiguration =
configurationRegistry.retrieveConfiguration<GeoWidgetConfiguration>(
ConfigType.GeoWidget,
geoWidgetConfigId,
)
onEvent(
AppMainEvent.OpenProfile(
navController = navController,
profileId = geoWidgetConfiguration.profileId,
resourceId = resourceId,
resourceConfig = geoWidgetConfiguration.resourceConfig,
),
)
}

/** This function is used to schedule tasks that are intended to run periodically */
fun schedulePeriodicJobs() {
workManager.run {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,43 +25,52 @@ import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.navArgs
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.launch
import org.smartregister.fhircore.engine.ui.theme.AppTheme
import org.smartregister.fhircore.engine.util.extension.isDeviceOnline
import org.smartregister.fhircore.engine.util.extension.showToast
import org.smartregister.fhircore.quest.event.AppEvent
import org.smartregister.fhircore.quest.event.EventBus
import org.smartregister.fhircore.quest.ui.main.AppMainViewModel

@AndroidEntryPoint
class MultiSelectBottomSheetFragment() : BottomSheetDialogFragment() {

@Inject lateinit var eventBus: EventBus
val bottomSheetArgs by navArgs<MultiSelectBottomSheetFragmentArgs>()
val multiSelectViewModel by viewModels<MultiSelectViewModel>()
private val appMainViewModel by activityViewModels<AppMainViewModel>()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
isCancelable = false
val multiSelectViewConfig = bottomSheetArgs.multiSelectViewConfig
val multiSelectViewConfig = bottomSheetArgs?.multiSelectViewConfig
if (multiSelectViewConfig != null) {
multiSelectViewModel.populateLookupMap(requireContext(), multiSelectViewConfig)
}
}

private fun onSelectionDone() {
multiSelectViewModel.saveSelectedLocations(requireContext())
appMainViewModel.run {
if (requireContext().isDeviceOnline()) {
triggerSync()
} else {
requireContext()
.showToast(
getString(org.smartregister.fhircore.engine.R.string.sync_failed),
Toast.LENGTH_LONG,
)
lifecycleScope.launch {
multiSelectViewModel.saveSelectedLocations(requireContext())
appMainViewModel.run {
if (requireContext().isDeviceOnline()) {
triggerSync()
} else {
requireContext()
.showToast(
getString(org.smartregister.fhircore.engine.R.string.sync_failed),
Toast.LENGTH_LONG,
)
eventBus.triggerEvent(AppEvent.RefreshRegisterData)
}
}
dismiss()
}
dismiss()
}

override fun onCreateView(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,9 @@ constructor(
}
}

fun saveSelectedLocations(context: Context) {
viewModelScope.launch {
context.syncLocationIdsProtoStore.updateData {
selectedNodes.map { SyncLocationToggleableState(it.key, it.value) }
}
suspend fun saveSelectedLocations(context: Context) {
context.syncLocationIdsProtoStore.updateData {
selectedNodes.map { SyncLocationToggleableState(it.key, it.value) }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,13 @@ class RegisterFragment : Fragment(), OnSyncListener {
eventBus.events
.getFor(MainNavigationScreen.Home.eventId(registerFragmentArgs.registerId))
.onEach { appEvent ->
if (appEvent is AppEvent.OnSubmitQuestionnaire) {
handleQuestionnaireSubmission(appEvent.questionnaireSubmission)
when (appEvent) {
is AppEvent.OnSubmitQuestionnaire ->
handleQuestionnaireSubmission(appEvent.questionnaireSubmission)
is AppEvent.RefreshRegisterData -> {
appMainViewModel.countRegisterData()
refreshRegisterData()
}
}
}
.launchIn(lifecycleScope)
Expand Down

0 comments on commit d425b90

Please sign in to comment.