diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index e2f3e2ed1b..1e9704e869 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -186,7 +186,7 @@ complexity: ignoreArgumentsMatchingNames: false NestedBlockDepth: active: true - threshold: 5 + threshold: 6 NestedScopeFunctions: active: false threshold: 1 diff --git a/core/data/src/main/java/com/mifos/core/data/pagingSource/CenterListPagingSource.kt b/core/data/src/main/java/com/mifos/core/data/pagingSource/CenterListPagingSource.kt index 196562690a..a4a5d3bbaf 100644 --- a/core/data/src/main/java/com/mifos/core/data/pagingSource/CenterListPagingSource.kt +++ b/core/data/src/main/java/com/mifos/core/data/pagingSource/CenterListPagingSource.kt @@ -9,17 +9,13 @@ */ package com.mifos.core.data.pagingSource +import android.graphics.pdf.LoadParams import androidx.paging.PagingSource import androidx.paging.PagingState -import com.mifos.core.entity.group.Center import com.mifos.core.network.datamanager.DataManagerCenter -import com.mifos.core.objects.clients.Page -import rx.Subscriber -import rx.android.schedulers.AndroidSchedulers -import rx.schedulers.Schedulers -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException -import kotlin.coroutines.suspendCoroutine +import com.mifos.room.entities.group.Center +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map class CenterListPagingSource(private val dataManagerCenter: DataManagerCenter) : PagingSource() { @@ -55,26 +51,10 @@ class CenterListPagingSource(private val dataManagerCenter: DataManagerCenter) : return Pair(pagedClient.pageItems, pagedClient.totalFilteredRecords) } - private suspend fun getCenterDbList(): List
= suspendCoroutine { continuation -> - try { - dataManagerCenter.allDatabaseCenters - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe(object : Subscriber>() { - override fun onCompleted() { - } - - override fun onError(error: Throwable) { - continuation.resumeWithException(error) - } - - override fun onNext(centers: Page
) { - continuation.resume(centers.pageItems) - } - }) - } catch (exception: Exception) { - continuation.resumeWithException(exception) - } + private suspend fun getCenterDbList(): List
{ + return dataManagerCenter.allDatabaseCenters + .map { it.pageItems } + .first() } private fun getCenterListWithSync( @@ -82,11 +62,11 @@ class CenterListPagingSource(private val dataManagerCenter: DataManagerCenter) : centerDbList: List
, ): List
{ if (centerDbList.isNotEmpty()) { - centerList.forEach { center -> - centerDbList.forEach { centerDb -> - if (center.id == centerDb.id) { - center.sync = true - } + return centerList.map { center -> + if (centerDbList.any { it.id == center.id }) { + center.copy(sync = true) + } else { + center } } } diff --git a/core/data/src/main/java/com/mifos/core/data/repository/CenterListRepository.kt b/core/data/src/main/java/com/mifos/core/data/repository/CenterListRepository.kt index 4643d33b6c..1364826add 100644 --- a/core/data/src/main/java/com/mifos/core/data/repository/CenterListRepository.kt +++ b/core/data/src/main/java/com/mifos/core/data/repository/CenterListRepository.kt @@ -10,11 +10,10 @@ package com.mifos.core.data.repository import androidx.paging.PagingData -import com.mifos.core.entity.group.Center -import com.mifos.core.objects.clients.Page +import com.mifos.core.model.objects.clients.Page +import com.mifos.room.entities.group.Center import com.mifos.room.entities.group.CenterWithAssociations import kotlinx.coroutines.flow.Flow -import rx.Observable /** * Created by Aditya Gupta on 06/08/23. @@ -25,5 +24,5 @@ interface CenterListRepository { suspend fun getCentersGroupAndMeeting(id: Int): CenterWithAssociations - fun allDatabaseCenters(): Observable> + fun allDatabaseCenters(): Flow> } diff --git a/core/data/src/main/java/com/mifos/core/data/repository/CreateNewCenterRepository.kt b/core/data/src/main/java/com/mifos/core/data/repository/CreateNewCenterRepository.kt index a260516604..f0a35af3ca 100644 --- a/core/data/src/main/java/com/mifos/core/data/repository/CreateNewCenterRepository.kt +++ b/core/data/src/main/java/com/mifos/core/data/repository/CreateNewCenterRepository.kt @@ -9,13 +9,11 @@ */ package com.mifos.core.data.repository -import com.mifos.core.entity.center.CenterPayload -import com.mifos.core.objects.responses.SaveResponse -import rx.Observable +import com.mifos.room.entities.center.CenterPayload /** * Created by Aditya Gupta on 10/08/23. */ interface CreateNewCenterRepository { - fun createCenter(centerPayload: CenterPayload): Observable + suspend fun createCenter(centerPayload: CenterPayload) } diff --git a/core/data/src/main/java/com/mifos/core/data/repository/OfflineDashboardRepository.kt b/core/data/src/main/java/com/mifos/core/data/repository/OfflineDashboardRepository.kt index 7a48df1c5c..8d0822b412 100644 --- a/core/data/src/main/java/com/mifos/core/data/repository/OfflineDashboardRepository.kt +++ b/core/data/src/main/java/com/mifos/core/data/repository/OfflineDashboardRepository.kt @@ -10,9 +10,9 @@ package com.mifos.core.data.repository import com.mifos.core.entity.accounts.savings.SavingsAccountTransactionRequest -import com.mifos.core.entity.center.CenterPayload import com.mifos.core.entity.client.ClientPayload import com.mifos.room.entities.accounts.loans.LoanRepaymentRequest +import com.mifos.room.entities.center.CenterPayload import com.mifos.room.entities.group.GroupPayload import kotlinx.coroutines.flow.Flow import rx.Observable @@ -26,7 +26,7 @@ interface OfflineDashboardRepository { fun allDatabaseGroupPayload(): Flow> - fun allDatabaseCenterPayload(): Observable> + fun allDatabaseCenterPayload(): Flow> fun databaseLoanRepayments(): Flow> diff --git a/core/data/src/main/java/com/mifos/core/data/repository/SyncCenterPayloadsRepository.kt b/core/data/src/main/java/com/mifos/core/data/repository/SyncCenterPayloadsRepository.kt index 266306fad7..8a911fb08c 100644 --- a/core/data/src/main/java/com/mifos/core/data/repository/SyncCenterPayloadsRepository.kt +++ b/core/data/src/main/java/com/mifos/core/data/repository/SyncCenterPayloadsRepository.kt @@ -9,20 +9,19 @@ */ package com.mifos.core.data.repository -import com.mifos.core.entity.center.CenterPayload -import com.mifos.core.objects.responses.SaveResponse -import rx.Observable +import com.mifos.room.entities.center.CenterPayload +import kotlinx.coroutines.flow.Flow /** * Created by Aditya Gupta on 16/08/23. */ interface SyncCenterPayloadsRepository { - fun allDatabaseCenterPayload(): Observable> + fun allDatabaseCenterPayload(): Flow> - fun createCenter(centerPayload: CenterPayload): Observable + suspend fun createCenter(centerPayload: CenterPayload?) - fun deleteAndUpdateCenterPayloads(id: Int): Observable> + fun deleteAndUpdateCenterPayloads(id: Int): Flow> - fun updateCenterPayload(centerPayload: CenterPayload): Observable + suspend fun updateCenterPayload(centerPayload: CenterPayload) } diff --git a/core/data/src/main/java/com/mifos/core/data/repository/SyncCentersDialogRepository.kt b/core/data/src/main/java/com/mifos/core/data/repository/SyncCentersDialogRepository.kt index c627c009d8..832174bbeb 100644 --- a/core/data/src/main/java/com/mifos/core/data/repository/SyncCentersDialogRepository.kt +++ b/core/data/src/main/java/com/mifos/core/data/repository/SyncCentersDialogRepository.kt @@ -11,12 +11,12 @@ package com.mifos.core.data.repository import com.mifos.core.entity.accounts.savings.SavingsAccountWithAssociations import com.mifos.core.entity.client.Client -import com.mifos.core.entity.group.Center import com.mifos.core.entity.templates.savings.SavingsAccountTransactionTemplate import com.mifos.room.entities.accounts.CenterAccounts import com.mifos.room.entities.accounts.ClientAccounts import com.mifos.room.entities.accounts.GroupAccounts import com.mifos.room.entities.accounts.loans.LoanWithAssociations +import com.mifos.room.entities.group.Center import com.mifos.room.entities.group.CenterWithAssociations import com.mifos.room.entities.group.Group import com.mifos.room.entities.group.GroupWithAssociations @@ -29,13 +29,13 @@ import rx.Observable */ interface SyncCentersDialogRepository { - fun syncCenterAccounts(centerId: Int): Observable + fun syncCenterAccounts(centerId: Int): Flow fun syncLoanById(loanId: Int): Flow fun syncLoanRepaymentTemplate(loanId: Int): Flow - fun getCenterWithAssociations(centerId: Int): Observable + fun getCenterWithAssociations(centerId: Int): Flow fun getGroupWithAssociations(groupId: Int): Observable @@ -47,7 +47,7 @@ interface SyncCentersDialogRepository { fun syncClientInDatabase(client: Client): Observable - fun syncCenterInDatabase(center: Center): Observable
+ suspend fun syncCenterInDatabase(center: Center) fun syncSavingsAccount( type: String?, diff --git a/core/data/src/main/java/com/mifos/core/data/repositoryImp/CenterListRepositoryImp.kt b/core/data/src/main/java/com/mifos/core/data/repositoryImp/CenterListRepositoryImp.kt index c855f4af2e..aaf3c18516 100644 --- a/core/data/src/main/java/com/mifos/core/data/repositoryImp/CenterListRepositoryImp.kt +++ b/core/data/src/main/java/com/mifos/core/data/repositoryImp/CenterListRepositoryImp.kt @@ -14,12 +14,11 @@ import androidx.paging.PagingConfig import androidx.paging.PagingData import com.mifos.core.data.pagingSource.CenterListPagingSource import com.mifos.core.data.repository.CenterListRepository -import com.mifos.core.entity.group.Center +import com.mifos.core.model.objects.clients.Page import com.mifos.core.network.datamanager.DataManagerCenter -import com.mifos.core.objects.clients.Page +import com.mifos.room.entities.group.Center import com.mifos.room.entities.group.CenterWithAssociations import kotlinx.coroutines.flow.Flow -import rx.Observable import javax.inject.Inject /** @@ -43,7 +42,7 @@ class CenterListRepositoryImp @Inject constructor(private val dataManagerCenter: return dataManagerCenter.getCentersGroupAndMeeting(id) } - override fun allDatabaseCenters(): Observable> { + override fun allDatabaseCenters(): Flow> { return dataManagerCenter.allDatabaseCenters } } diff --git a/core/data/src/main/java/com/mifos/core/data/repositoryImp/CreateNewCenterRepositoryImp.kt b/core/data/src/main/java/com/mifos/core/data/repositoryImp/CreateNewCenterRepositoryImp.kt index 69792f571a..80a3e4878f 100644 --- a/core/data/src/main/java/com/mifos/core/data/repositoryImp/CreateNewCenterRepositoryImp.kt +++ b/core/data/src/main/java/com/mifos/core/data/repositoryImp/CreateNewCenterRepositoryImp.kt @@ -10,10 +10,8 @@ package com.mifos.core.data.repositoryImp import com.mifos.core.data.repository.CreateNewCenterRepository -import com.mifos.core.entity.center.CenterPayload import com.mifos.core.network.datamanager.DataManagerCenter -import com.mifos.core.objects.responses.SaveResponse -import rx.Observable +import com.mifos.room.entities.center.CenterPayload import javax.inject.Inject /** @@ -22,7 +20,7 @@ import javax.inject.Inject class CreateNewCenterRepositoryImp @Inject constructor(private val dataManagerCenter: DataManagerCenter) : CreateNewCenterRepository { - override fun createCenter(centerPayload: CenterPayload): Observable { - return dataManagerCenter.createCenter(centerPayload) + override suspend fun createCenter(centerPayload: CenterPayload) { + dataManagerCenter.createCenter(centerPayload) } } diff --git a/core/data/src/main/java/com/mifos/core/data/repositoryImp/OfflineDashboardRepositoryImp.kt b/core/data/src/main/java/com/mifos/core/data/repositoryImp/OfflineDashboardRepositoryImp.kt index dad02a980d..0aa6f6c9bc 100644 --- a/core/data/src/main/java/com/mifos/core/data/repositoryImp/OfflineDashboardRepositoryImp.kt +++ b/core/data/src/main/java/com/mifos/core/data/repositoryImp/OfflineDashboardRepositoryImp.kt @@ -11,7 +11,6 @@ package com.mifos.core.data.repositoryImp import com.mifos.core.data.repository.OfflineDashboardRepository import com.mifos.core.entity.accounts.savings.SavingsAccountTransactionRequest -import com.mifos.core.entity.center.CenterPayload import com.mifos.core.entity.client.ClientPayload import com.mifos.core.network.datamanager.DataManagerCenter import com.mifos.core.network.datamanager.DataManagerClient @@ -19,6 +18,7 @@ import com.mifos.core.network.datamanager.DataManagerGroups import com.mifos.core.network.datamanager.DataManagerLoan import com.mifos.core.network.datamanager.DataManagerSavings import com.mifos.room.entities.accounts.loans.LoanRepaymentRequest +import com.mifos.room.entities.center.CenterPayload import com.mifos.room.entities.group.GroupPayload import kotlinx.coroutines.flow.Flow import rx.Observable @@ -43,7 +43,7 @@ class OfflineDashboardRepositoryImp @Inject constructor( return dataManagerGroups.allDatabaseGroupPayload } - override fun allDatabaseCenterPayload(): Observable> { + override fun allDatabaseCenterPayload(): Flow> { return dataManagerCenter.allDatabaseCenterPayload } diff --git a/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCenterPayloadsRepositoryImp.kt b/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCenterPayloadsRepositoryImp.kt index 39645fed20..062a3b20ec 100644 --- a/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCenterPayloadsRepositoryImp.kt +++ b/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCenterPayloadsRepositoryImp.kt @@ -10,10 +10,9 @@ package com.mifos.core.data.repositoryImp import com.mifos.core.data.repository.SyncCenterPayloadsRepository -import com.mifos.core.entity.center.CenterPayload import com.mifos.core.network.datamanager.DataManagerCenter -import com.mifos.core.objects.responses.SaveResponse -import rx.Observable +import com.mifos.room.entities.center.CenterPayload +import kotlinx.coroutines.flow.Flow import javax.inject.Inject /** @@ -22,19 +21,19 @@ import javax.inject.Inject class SyncCenterPayloadsRepositoryImp @Inject constructor(private val dataManagerCenter: DataManagerCenter) : SyncCenterPayloadsRepository { - override fun allDatabaseCenterPayload(): Observable> { + override fun allDatabaseCenterPayload(): Flow> { return dataManagerCenter.allDatabaseCenterPayload } - override fun createCenter(centerPayload: CenterPayload): Observable { - return dataManagerCenter.createCenter(centerPayload) + override suspend fun createCenter(centerPayload: CenterPayload?) { + dataManagerCenter.createCenter(centerPayload) } - override fun deleteAndUpdateCenterPayloads(id: Int): Observable> { + override fun deleteAndUpdateCenterPayloads(id: Int): Flow> { return dataManagerCenter.deleteAndUpdateCenterPayloads(id) } - override fun updateCenterPayload(centerPayload: CenterPayload): Observable { - return dataManagerCenter.updateCenterPayload(centerPayload) + override suspend fun updateCenterPayload(centerPayload: CenterPayload) { + dataManagerCenter.updateCenterPayload(centerPayload) } } diff --git a/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCentersDialogRepositoryImp.kt b/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCentersDialogRepositoryImp.kt index 77b1e5f8ce..3ad508feb9 100644 --- a/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCentersDialogRepositoryImp.kt +++ b/core/data/src/main/java/com/mifos/core/data/repositoryImp/SyncCentersDialogRepositoryImp.kt @@ -12,7 +12,6 @@ package com.mifos.core.data.repositoryImp import com.mifos.core.data.repository.SyncCentersDialogRepository import com.mifos.core.entity.accounts.savings.SavingsAccountWithAssociations import com.mifos.core.entity.client.Client -import com.mifos.core.entity.group.Center import com.mifos.core.entity.templates.savings.SavingsAccountTransactionTemplate import com.mifos.core.network.datamanager.DataManagerCenter import com.mifos.core.network.datamanager.DataManagerClient @@ -23,6 +22,7 @@ import com.mifos.room.entities.accounts.CenterAccounts import com.mifos.room.entities.accounts.ClientAccounts import com.mifos.room.entities.accounts.GroupAccounts import com.mifos.room.entities.accounts.loans.LoanWithAssociations +import com.mifos.room.entities.group.Center import com.mifos.room.entities.group.CenterWithAssociations import com.mifos.room.entities.group.Group import com.mifos.room.entities.group.GroupWithAssociations @@ -42,7 +42,7 @@ class SyncCentersDialogRepositoryImp @Inject constructor( private val dataManagerClient: DataManagerClient, ) : SyncCentersDialogRepository { - override fun syncCenterAccounts(centerId: Int): Observable { + override fun syncCenterAccounts(centerId: Int): Flow { return dataManagerCenter.syncCenterAccounts(centerId) } @@ -54,7 +54,7 @@ class SyncCentersDialogRepositoryImp @Inject constructor( return dataManagerLoan.syncLoanRepaymentTemplate(loanId) } - override fun getCenterWithAssociations(centerId: Int): Observable { + override fun getCenterWithAssociations(centerId: Int): Flow { return dataManagerCenter.getCenterWithAssociations(centerId) } @@ -78,8 +78,8 @@ class SyncCentersDialogRepositoryImp @Inject constructor( return dataManagerClient.syncClientInDatabase(client) } - override fun syncCenterInDatabase(center: Center): Observable
{ - return dataManagerCenter.syncCenterInDatabase(center) + override suspend fun syncCenterInDatabase(center: Center) { + dataManagerCenter.syncCenterInDatabase(center) } override fun syncSavingsAccount( diff --git a/core/database/src/main/java/com/mifos/core/databasehelper/DatabaseHelperCenter.kt b/core/database/src/main/java/com/mifos/core/databasehelper/DatabaseHelperCenter.kt index 13929a3c13..69175c526d 100644 --- a/core/database/src/main/java/com/mifos/core/databasehelper/DatabaseHelperCenter.kt +++ b/core/database/src/main/java/com/mifos/core/databasehelper/DatabaseHelperCenter.kt @@ -16,8 +16,8 @@ import com.mifos.core.entity.group.Center import com.mifos.core.entity.group.CenterDate import com.mifos.core.entity.group.Group import com.mifos.core.entity.group.Group_Table -import com.mifos.core.objects.clients.Page -import com.mifos.core.objects.responses.SaveResponse +import com.mifos.core.model.objects.clients.Page +import com.mifos.core.model.objects.responses.SaveResponse import com.mifos.room.entities.accounts.CenterAccounts import com.mifos.room.entities.group.CenterWithAssociations import com.raizlabs.android.dbflow.sql.language.Delete diff --git a/core/database/src/main/java/com/mifos/room/dao/CenterDao.kt b/core/database/src/main/java/com/mifos/room/dao/CenterDao.kt new file mode 100644 index 0000000000..660ddffa84 --- /dev/null +++ b/core/database/src/main/java/com/mifos/room/dao/CenterDao.kt @@ -0,0 +1,56 @@ +/* + * Copyright 2025 Mifos Initiative + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * See https://github.com/openMF/android-client/blob/master/LICENSE.md + */ +package com.mifos.room.dao + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import androidx.room.Update +import com.mifos.room.entities.accounts.loans.LoanAccount +import com.mifos.room.entities.accounts.savings.SavingsAccount +import com.mifos.room.entities.center.CenterPayload +import com.mifos.room.entities.group.Center +import com.mifos.room.entities.group.Group +import kotlinx.coroutines.flow.Flow + +@Dao +interface CenterDao { + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun saveCenter(center: Center) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun saveLoanAccount(loanAccount: LoanAccount) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun saveSavingsAccount(savingsAccount: SavingsAccount) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun saveMemberLoanAccount(loanAccount: LoanAccount) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun saveCenterPayload(centerPayload: CenterPayload?) + + @Update + suspend fun updateCenterPayload(centerPayload: CenterPayload?) + + @Query("DELETE FROM CenterPayload WHERE id = :id") + suspend fun deleteCenterPayloadById(id: Int) + + @Query("SELECT * FROM Center") + fun readAllCenters(): Flow> + + @Query("SELECT * FROM CenterPayload") + fun readAllCenterPayload(): Flow> + + @Query("SELECT * FROM GroupTable WHERE centerId = :centerId") + fun getCenterAssociateGroups(centerId: Int): Flow> +} diff --git a/core/database/src/main/java/com/mifos/room/db/MifosDatabase.kt b/core/database/src/main/java/com/mifos/room/db/MifosDatabase.kt index cb400813e4..5aa2b2a1b3 100644 --- a/core/database/src/main/java/com/mifos/room/db/MifosDatabase.kt +++ b/core/database/src/main/java/com/mifos/room/db/MifosDatabase.kt @@ -35,6 +35,7 @@ import com.mifos.room.entities.survey.QuestionDatas import com.mifos.room.entities.survey.ResponseDatas import com.mifos.room.entities.survey.Survey import com.mifos.room.entities.templates.loans.LoanRepaymentTemplate +import com.mifos.room.utils.typeconverters.CenterTypeConverters import com.mifos.room.utils.typeconverters.DueDateConverter import com.mifos.room.utils.typeconverters.ListTypeConverters import com.mifos.room.utils.typeconverters.LoanTypeConverters @@ -75,6 +76,7 @@ import com.mifos.room.utils.typeconverters.SurveyTypeConverters DueDateConverter::class, LoanTypeConverters::class, SurveyTypeConverters::class, + CenterTypeConverters::class, ) // ( TODO -> add type converters here ) diff --git a/core/database/src/main/java/com/mifos/room/entities/accounts/CenterAccounts.kt b/core/database/src/main/java/com/mifos/room/entities/accounts/CenterAccounts.kt index d556e320ba..ec189e6654 100644 --- a/core/database/src/main/java/com/mifos/room/entities/accounts/CenterAccounts.kt +++ b/core/database/src/main/java/com/mifos/room/entities/accounts/CenterAccounts.kt @@ -10,8 +10,8 @@ package com.mifos.room.entities.accounts import android.os.Parcelable -import com.mifos.core.entity.accounts.loan.LoanAccount -import com.mifos.core.entity.accounts.savings.SavingsAccount +import com.mifos.room.entities.accounts.loans.LoanAccount +import com.mifos.room.entities.accounts.savings.SavingsAccount import kotlinx.parcelize.Parcelize /** @@ -19,9 +19,9 @@ import kotlinx.parcelize.Parcelize */ @Parcelize data class CenterAccounts( - var loanAccounts: List = ArrayList(), + val loanAccounts: List = emptyList(), - var savingsAccounts: List = ArrayList(), + val savingsAccounts: List = emptyList(), - var memberLoanAccounts: List = ArrayList(), + val memberLoanAccounts: List = emptyList(), ) : Parcelable diff --git a/core/database/src/main/java/com/mifos/room/entities/accounts/ClientAccounts.kt b/core/database/src/main/java/com/mifos/room/entities/accounts/ClientAccounts.kt index 4ab9c8e4dd..c76b7b5efe 100644 --- a/core/database/src/main/java/com/mifos/room/entities/accounts/ClientAccounts.kt +++ b/core/database/src/main/java/com/mifos/room/entities/accounts/ClientAccounts.kt @@ -10,8 +10,8 @@ package com.mifos.room.entities.accounts import android.os.Parcelable -import com.mifos.core.entity.accounts.loan.LoanAccount -import com.mifos.core.entity.accounts.savings.SavingsAccount +import com.mifos.room.entities.accounts.loans.LoanAccount +import com.mifos.room.entities.accounts.savings.SavingsAccount import kotlinx.parcelize.Parcelize @Parcelize diff --git a/core/database/src/main/java/com/mifos/room/entities/accounts/loans/LoanWithAssociations.kt b/core/database/src/main/java/com/mifos/room/entities/accounts/loans/LoanWithAssociations.kt index ef97407944..636783c453 100644 --- a/core/database/src/main/java/com/mifos/room/entities/accounts/loans/LoanWithAssociations.kt +++ b/core/database/src/main/java/com/mifos/room/entities/accounts/loans/LoanWithAssociations.kt @@ -16,14 +16,7 @@ import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey import com.mifos.core.model.objects.account.loan.RepaymentFrequencyType -import com.mifos.core.objects.account.loan.AmortizationType -import com.mifos.core.objects.account.loan.Currency -import com.mifos.core.objects.account.loan.InterestCalculationPeriodType -import com.mifos.core.objects.account.loan.InterestRateFrequencyType -import com.mifos.core.objects.account.loan.InterestType -import com.mifos.core.objects.account.loan.RepaymentSchedule -import com.mifos.core.objects.account.loan.TermPeriodFrequencyType -import com.mifos.core.objects.account.loan.Transaction +import com.mifos.core.model.objects.account.loan.RepaymentSchedule import kotlinx.parcelize.Parcelize // @TypeConverters( diff --git a/core/database/src/main/java/com/mifos/room/entities/accounts/savings/DepositType.kt b/core/database/src/main/java/com/mifos/room/entities/accounts/savings/DepositType.kt index d167e184a6..3e434fdd57 100644 --- a/core/database/src/main/java/com/mifos/room/entities/accounts/savings/DepositType.kt +++ b/core/database/src/main/java/com/mifos/room/entities/accounts/savings/DepositType.kt @@ -20,13 +20,13 @@ import kotlinx.parcelize.Parcelize @Parcelize data class DepositType( @PrimaryKey - var id: Int? = null, + val id: Int? = null, @ColumnInfo(name = "code") - var code: String? = null, + val code: String? = null, @ColumnInfo(name = "value") - var value: String? = null, + val value: String? = null, ) : Parcelable { val isRecurring: Boolean diff --git a/core/database/src/main/java/com/mifos/room/entities/center/CenterPayload.kt b/core/database/src/main/java/com/mifos/room/entities/center/CenterPayload.kt index 42880410cb..620adf4b66 100644 --- a/core/database/src/main/java/com/mifos/room/entities/center/CenterPayload.kt +++ b/core/database/src/main/java/com/mifos/room/entities/center/CenterPayload.kt @@ -10,7 +10,6 @@ package com.mifos.room.entities.center import android.os.Parcelable -import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @@ -20,27 +19,20 @@ import kotlinx.parcelize.Parcelize data class CenterPayload( @PrimaryKey(autoGenerate = true) @Transient - var id: Int = 0, + val id: Int = 0, - @ColumnInfo(name = "errorMessage") @Transient - var errorMessage: String? = null, + val errorMessage: String? = null, - @ColumnInfo(name = "dateFormat") - var dateFormat: String? = null, + val dateFormat: String? = null, - @ColumnInfo(name = "locale") - var locale: String? = null, + val locale: String? = null, - @ColumnInfo(name = "name") - var name: String? = null, + val name: String? = null, - @ColumnInfo(name = "officeId") - var officeId: Int? = null, + val officeId: Int? = null, - @ColumnInfo(name = "active") - var active: Boolean = false, + val active: Boolean = false, - @ColumnInfo(name = "activationDate") - var activationDate: String? = null, + val activationDate: String? = null, ) : Parcelable diff --git a/core/database/src/main/java/com/mifos/room/entities/group/Center.kt b/core/database/src/main/java/com/mifos/room/entities/group/Center.kt index b66afc7689..c63cf8a102 100644 --- a/core/database/src/main/java/com/mifos/room/entities/group/Center.kt +++ b/core/database/src/main/java/com/mifos/room/entities/group/Center.kt @@ -10,10 +10,10 @@ package com.mifos.room.entities.group import android.os.Parcelable -import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey +import com.mifos.room.entities.accounts.loans.Timeline import com.mifos.room.entities.client.Status import kotlinx.parcelize.Parcelize @@ -31,50 +31,35 @@ import kotlinx.parcelize.Parcelize ) data class Center( @PrimaryKey - @ColumnInfo(name = "id") - var id: Int? = null, + val id: Int? = null, - @ColumnInfo(name = "sync") @Transient - var sync: Boolean = false, + val sync: Boolean = false, - @ColumnInfo(name = "accountNo") - var accountNo: String? = null, + val accountNo: String? = null, - @ColumnInfo(name = "name") - var name: String? = null, + val name: String? = null, - @ColumnInfo(name = "officeId") - var officeId: Int? = null, + val officeId: Int? = null, - @ColumnInfo(name = "officeName") - var officeName: String? = null, + val officeName: String? = null, - @ColumnInfo(name = "staffId") - var staffId: Int? = null, + val staffId: Int? = null, - @ColumnInfo(name = "staffName") - var staffName: String? = null, + val staffName: String? = null, - @ColumnInfo(name = "hierarchy") - var hierarchy: String? = null, + val hierarchy: String? = null, - @ColumnInfo(name = "status") - var status: Status? = null, + val status: Status? = null, - @ColumnInfo(name = "active") - var active: Boolean? = null, + val active: Boolean? = null, - @ColumnInfo(name = "centerDate") @Transient - var centerDate: CenterDate? = null, + val centerDate: CenterDate? = null, - @ColumnInfo(name = "activationDate") - var activationDate: String? = null, + val activationDate: List = emptyList(), - @ColumnInfo(name = "timeline") - var timeline: String? = null, + val timeline: Timeline? = null, - @ColumnInfo(name = "externalId") - var externalId: String? = null, + val externalId: String? = null, ) : Parcelable diff --git a/core/database/src/main/java/com/mifos/room/entities/group/CenterWithAssociations.kt b/core/database/src/main/java/com/mifos/room/entities/group/CenterWithAssociations.kt index 734ea32280..0904231fc8 100644 --- a/core/database/src/main/java/com/mifos/room/entities/group/CenterWithAssociations.kt +++ b/core/database/src/main/java/com/mifos/room/entities/group/CenterWithAssociations.kt @@ -11,7 +11,7 @@ package com.mifos.room.entities.group import android.os.Parcelable import com.mifos.core.entity.client.Status -import com.mifos.core.entity.group.Group +import com.mifos.core.model.objects.collectionsheets.CollectionMeetingCalendar import com.mifos.core.objects.collectionsheets.CollectionMeetingCalendar import com.mifos.room.entities.Timeline import kotlinx.parcelize.Parcelize diff --git a/core/database/src/main/java/com/mifos/room/helper/CenterDaoHelper.kt b/core/database/src/main/java/com/mifos/room/helper/CenterDaoHelper.kt new file mode 100644 index 0000000000..3dc05eb1ad --- /dev/null +++ b/core/database/src/main/java/com/mifos/room/helper/CenterDaoHelper.kt @@ -0,0 +1,143 @@ +/* + * Copyright 2025 Mifos Initiative + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * See https://github.com/openMF/android-client/blob/master/LICENSE.md + */ +package com.mifos.room.helper + +import com.mifos.core.model.objects.clients.Page +import com.mifos.room.dao.CenterDao +import com.mifos.room.entities.accounts.CenterAccounts +import com.mifos.room.entities.center.CenterPayload +import com.mifos.room.entities.group.Center +import com.mifos.room.entities.group.CenterDate +import com.mifos.room.entities.group.CenterWithAssociations +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map +import javax.inject.Inject + +/** + * Created by Pronay Sarker on 03/02/2025 (7:32 PM) + */ +class CenterDaoHelper @Inject constructor( + private val centerDatabase: CenterDao, +) { + /** + * Reading All Centers from table of Center and return the CenterList + * + * @return List Of Centers + */ + // (todo from old code) + // TODO Implement Observable Transaction to load Center List + fun readAllCenters(): Flow> { + return centerDatabase.readAllCenters().map { centers -> + Page
().apply { pageItems = centers } + } + } + + suspend fun saveCenterPayload(centerPayload: CenterPayload?) { + centerDatabase.saveCenterPayload(centerPayload) + } + + fun readAllCenterPayload(): Flow> { + return centerDatabase.readAllCenterPayload() + } + + /** + * This Method Fetch the Groups that are attached to the Center. + * @param centerId Center Id + * @return CenterWithAssociations + */ + fun getCenterAssociateGroups(centerId: Int): Flow { + return flow { + val groups = centerDatabase.getCenterAssociateGroups(centerId).first() + val centerWithAssociations = CenterWithAssociations() + centerWithAssociations.groupMembers = groups + emit(centerWithAssociations) + } + } + + /** + * This Method Saving the Single Center in the Database + * + * @param center + * @return Observable.just(Center) + */ + suspend fun saveCenter(center: Center) { + var updatedCenter: Center = center + + if (center.activationDate.isNotEmpty()) { + val centerDate = center.id?.let { + center.activationDate[0]?.let { it1 -> + center.activationDate[1]?.let { it2 -> + center.activationDate[2]?.let { it3 -> + CenterDate( + it.toLong(), + 0, + it1, + it2, + it3, + ) + } + } + } + } + updatedCenter = center.copy(centerDate = centerDate) + } + centerDatabase.saveCenter(updatedCenter) + } + + /** + * This Method for deleting the center payload from the Database according to Id and + * again fetch the center List from the Database CenterPayload_Table + * @param id is Id of the Center Payload in which reference center was saved into Database + * @return List> + */ + // todo recheck logic + fun deleteAndUpdateCenterPayloads(id: Int): Flow> { + return flow { + centerDatabase.deleteCenterPayloadById(id) + emitAll(centerDatabase.readAllCenterPayload()) + } + } + + suspend fun updateDatabaseCenterPayload(centerPayload: CenterPayload) { + centerDatabase.updateCenterPayload(centerPayload) + } + + /** + * This Method write the CenterAccounts in tho DB. According to Schema Defined in Model + * + * @param centerAccounts Model of List of LoanAccount and SavingAccount + * @param centerId Center Id + * @return CenterAccounts + */ + suspend fun saveCenterAccounts( + centerAccounts: CenterAccounts, + centerId: Int, + ) { + val loanAccounts = centerAccounts.loanAccounts + val savingsAccounts = centerAccounts.savingsAccounts + val memberLoanAccounts = centerAccounts.memberLoanAccounts + + for (loanAccount in loanAccounts) { + val updatedLoanAccount = loanAccount.copy(centerId = centerId.toLong()) + centerDatabase.saveLoanAccount(updatedLoanAccount) + } + for (savingsAccount in savingsAccounts) { + savingsAccount.centerId = centerId.toLong() + centerDatabase.saveSavingsAccount(savingsAccount) + } + for (memberLoanAccount in memberLoanAccounts) { + val updatedLoanAccount = memberLoanAccount.copy(centerId = centerId.toLong()) + centerDatabase.saveMemberLoanAccount(updatedLoanAccount) + } + } +} diff --git a/core/database/src/main/java/com/mifos/room/utils/typeconverters/CenterTypeConverters.kt b/core/database/src/main/java/com/mifos/room/utils/typeconverters/CenterTypeConverters.kt new file mode 100644 index 0000000000..b1057f07a7 --- /dev/null +++ b/core/database/src/main/java/com/mifos/room/utils/typeconverters/CenterTypeConverters.kt @@ -0,0 +1,50 @@ +/* + * Copyright 2025 Mifos Initiative + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * See https://github.com/openMF/android-client/blob/master/LICENSE.md + */ +package com.mifos.room.utils.typeconverters + +import androidx.room.TypeConverter +import com.mifos.room.entities.accounts.savings.DepositType +import com.mifos.room.entities.group.CenterDate +import com.mifos.room.entities.group.GroupDate +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json + +class CenterTypeConverters { + + @TypeConverter + fun fromCenterDate(centerDate: CenterDate?): String? { + return centerDate?.let { Json.encodeToString(it) } + } + + @TypeConverter + fun toCenterDate(json: String?): CenterDate? { + return json?.let { Json.decodeFromString(it) } + } + + @TypeConverter + fun fromDepositType(type: DepositType?): String? { + return type?.let { Json.encodeToString(it) } + } + + @TypeConverter + fun toDepositType(json: String?): DepositType? { + return json?.let { Json.decodeFromString(it) } + } + + @TypeConverter + fun fromGroupDate(groupDate: GroupDate?): String? { + return groupDate?.let { Json.encodeToString(it) } + } + + @TypeConverter + fun toGroupDate(json: String?): GroupDate? { + return json?.let { Json.decodeFromString(it) } + } +} diff --git a/core/domain/src/main/java/com/mifos/core/domain/useCases/AllDatabaseCenterPayloadUseCase.kt b/core/domain/src/main/java/com/mifos/core/domain/useCases/AllDatabaseCenterPayloadUseCase.kt deleted file mode 100644 index 0ef33a0206..0000000000 --- a/core/domain/src/main/java/com/mifos/core/domain/useCases/AllDatabaseCenterPayloadUseCase.kt +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2024 Mifos Initiative - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - * - * See https://github.com/openMF/android-client/blob/master/LICENSE.md - */ -package com.mifos.core.domain.useCases - -import com.mifos.core.common.utils.Resource -import com.mifos.core.data.repository.SyncCenterPayloadsRepository -import com.mifos.core.entity.center.CenterPayload -import kotlinx.coroutines.channels.awaitClose -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.callbackFlow -import rx.Subscriber -import rx.android.schedulers.AndroidSchedulers -import rx.schedulers.Schedulers -import javax.inject.Inject - -/** - * Created by Pronay Sarker on 08/08/2024 (2:22 PM) - */ -class AllDatabaseCenterPayloadUseCase @Inject constructor(private val repository: SyncCenterPayloadsRepository) { - - suspend operator fun invoke(): Flow>> = - callbackFlow { - try { - trySend(Resource.Loading()) - - repository.allDatabaseCenterPayload() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe(object : Subscriber>() { - override fun onCompleted() {} - - override fun onError(e: Throwable) { - trySend(Resource.Error(e.message.toString())) - } - - override fun onNext(centerPayloads: List) { - trySend(Resource.Success(centerPayloads)) - } - }) - - awaitClose { channel.close() } - } catch (e: Exception) { - trySend(Resource.Error(e.message.toString())) - } - } -} diff --git a/core/domain/src/main/java/com/mifos/core/domain/useCases/CreateCenterUseCase.kt b/core/domain/src/main/java/com/mifos/core/domain/useCases/CreateCenterUseCase.kt deleted file mode 100644 index 827eeeaa5f..0000000000 --- a/core/domain/src/main/java/com/mifos/core/domain/useCases/CreateCenterUseCase.kt +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2024 Mifos Initiative - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - * - * See https://github.com/openMF/android-client/blob/master/LICENSE.md - */ -package com.mifos.core.domain.useCases - -import com.mifos.core.common.utils.Resource -import com.mifos.core.data.repository.SyncCenterPayloadsRepository -import com.mifos.core.entity.center.CenterPayload -import com.mifos.core.objects.responses.SaveResponse -import kotlinx.coroutines.channels.awaitClose -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.callbackFlow -import rx.Subscriber -import rx.android.schedulers.AndroidSchedulers -import rx.schedulers.Schedulers -import javax.inject.Inject - -/** - * Created by Pronay Sarker on 08/08/2024 (2:08 PM) - */ -class CreateCenterUseCase @Inject constructor(private val repository: SyncCenterPayloadsRepository) { - - suspend operator fun invoke(centerPayload: CenterPayload): Flow> = - callbackFlow { - try { - trySend(Resource.Loading()) - - repository.createCenter(centerPayload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe(object : Subscriber() { - override fun onCompleted() {} - - override fun onError(e: Throwable) { - trySend(Resource.Error(e.message.toString())) - } - - override fun onNext(center: SaveResponse?) { - trySend(Resource.Success(center)) - } - }) - - awaitClose { channel.close() } - } catch (e: Exception) { - trySend(Resource.Error(e.message.toString())) - } - } -} diff --git a/core/domain/src/main/java/com/mifos/core/domain/useCases/DeleteAndUpdateCenterPayloadsUseCase.kt b/core/domain/src/main/java/com/mifos/core/domain/useCases/DeleteAndUpdateCenterPayloadsUseCase.kt deleted file mode 100644 index eaf96886ac..0000000000 --- a/core/domain/src/main/java/com/mifos/core/domain/useCases/DeleteAndUpdateCenterPayloadsUseCase.kt +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2024 Mifos Initiative - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - * - * See https://github.com/openMF/android-client/blob/master/LICENSE.md - */ -package com.mifos.core.domain.useCases - -import com.mifos.core.common.utils.Resource -import com.mifos.core.data.repository.SyncCenterPayloadsRepository -import com.mifos.core.entity.center.CenterPayload -import kotlinx.coroutines.channels.awaitClose -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.callbackFlow -import rx.Subscriber -import rx.android.schedulers.AndroidSchedulers -import rx.schedulers.Schedulers -import javax.inject.Inject - -/** - * Created by Pronay Sarker on 08/08/2024 (1:37 PM) - */ -class DeleteAndUpdateCenterPayloadsUseCase @Inject constructor(private val repository: SyncCenterPayloadsRepository) { - - suspend operator fun invoke(id: Int): Flow>> = - callbackFlow { - try { - trySend(Resource.Loading()) - - repository.deleteAndUpdateCenterPayloads(id) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe(object : Subscriber>() { - override fun onCompleted() {} - - override fun onError(e: Throwable) { - trySend(Resource.Error(e.message.toString())) - } - - override fun onNext(centerPayloads: List) { - trySend(Resource.Success(centerPayloads)) - } - }) - - awaitClose { channel.close() } - } catch (e: Exception) { - trySend(Resource.Error(e.message.toString())) - } - } -} diff --git a/core/domain/src/main/java/com/mifos/core/domain/useCases/UpdateCenterPayloadUseCase.kt b/core/domain/src/main/java/com/mifos/core/domain/useCases/UpdateCenterPayloadUseCase.kt deleted file mode 100644 index aa127b52d4..0000000000 --- a/core/domain/src/main/java/com/mifos/core/domain/useCases/UpdateCenterPayloadUseCase.kt +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2024 Mifos Initiative - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - * - * See https://github.com/openMF/android-client/blob/master/LICENSE.md - */ -package com.mifos.core.domain.useCases - -import com.mifos.core.common.utils.Resource -import com.mifos.core.data.repository.SyncCenterPayloadsRepository -import com.mifos.core.entity.center.CenterPayload -import kotlinx.coroutines.channels.awaitClose -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.callbackFlow -import rx.Subscriber -import rx.android.schedulers.AndroidSchedulers -import rx.schedulers.Schedulers -import javax.inject.Inject - -/** - * Created by Pronay Sarker on 08/08/2024 (1:43 PM) - */ -class UpdateCenterPayloadUseCase @Inject constructor(private val repository: SyncCenterPayloadsRepository) { - - suspend operator fun invoke(centerPayload: CenterPayload): Flow> = - callbackFlow { - try { - trySend(Resource.Loading()) - - repository.updateCenterPayload(centerPayload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe(object : Subscriber() { - override fun onCompleted() {} - - override fun onError(e: Throwable) { - trySend(Resource.Error(e.message.toString())) - } - - override fun onNext(centerPayload: CenterPayload) { - trySend(Resource.Success(centerPayload)) - } - }) - - awaitClose { channel.close() } - } catch (e: Exception) { - trySend(Resource.Error(e.message.toString())) - } - } -} diff --git a/core/network/src/main/java/com/mifos/core/network/datamanager/DataManagerCenter.kt b/core/network/src/main/java/com/mifos/core/network/datamanager/DataManagerCenter.kt index 3fc515a617..84a4109412 100644 --- a/core/network/src/main/java/com/mifos/core/network/datamanager/DataManagerCenter.kt +++ b/core/network/src/main/java/com/mifos/core/network/datamanager/DataManagerCenter.kt @@ -9,21 +9,21 @@ */ package com.mifos.core.network.datamanager -import com.mifos.core.databasehelper.DatabaseHelperCenter -import com.mifos.core.entity.center.CenterPayload -import com.mifos.core.entity.group.Center import com.mifos.core.entity.organisation.Office +import com.mifos.core.model.objects.clients.ActivatePayload +import com.mifos.core.model.objects.clients.Page import com.mifos.core.network.BaseApiManager import com.mifos.core.network.mappers.centers.GetCentersResponseMapper import com.mifos.core.network.mappers.offices.GetOfficeResponseMapper -import com.mifos.core.objects.clients.ActivatePayload -import com.mifos.core.objects.clients.Page -import com.mifos.core.objects.responses.SaveResponse import com.mifos.room.entities.accounts.CenterAccounts +import com.mifos.room.entities.center.CenterPayload +import com.mifos.room.entities.group.Center import com.mifos.room.entities.group.CenterWithAssociations +import com.mifos.room.helper.CenterDaoHelper +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow import org.openapitools.client.models.PostCentersCenterIdRequest import org.openapitools.client.models.PostCentersCenterIdResponse -import rx.Observable import javax.inject.Inject import javax.inject.Singleton @@ -36,7 +36,7 @@ import javax.inject.Singleton @Singleton class DataManagerCenter @Inject constructor( val mBaseApiManager: BaseApiManager, - private val mDatabaseHelperCenter: DatabaseHelperCenter, + private val centerDatabaseHelper: CenterDaoHelper, private val baseApiManager: org.mifos.core.apimanager.BaseApiManager, private val prefManager: com.mifos.core.datastore.PrefManager, ) { @@ -88,8 +88,8 @@ class DataManagerCenter @Inject constructor( * @param center Center * @return Center */ - fun syncCenterInDatabase(center: Center): Observable
{ - return mDatabaseHelperCenter.saveCenter(center) + suspend fun syncCenterInDatabase(center: Center) { + return centerDatabaseHelper.saveCenter(center) } /** @@ -99,14 +99,13 @@ class DataManagerCenter @Inject constructor( * @param centerId Center Id * @return CenterAccounts */ - fun syncCenterAccounts(centerId: Int): Observable { - return mBaseApiManager.centerApi.getCenterAccounts(centerId) - .concatMap { centerAccounts -> - mDatabaseHelperCenter.saveCenterAccounts( - centerAccounts, - centerId, - ) + fun syncCenterAccounts(centerId: Int): Flow { + return flow { + val centerAccounts = mBaseApiManager.centerApi.getCenterAccounts(centerId).also { + centerDatabaseHelper.saveCenterAccounts(it, centerId) } + emit(centerAccounts) + } } /** @@ -123,14 +122,14 @@ class DataManagerCenter @Inject constructor( .getCenterWithGroupMembersAndCollectionMeetingCalendar(id) } - fun createCenter(centerPayload: CenterPayload): Observable { - return when (prefManager.userStatus) { + suspend fun createCenter(centerPayload: CenterPayload?) { + when (prefManager.userStatus) { false -> mBaseApiManager.centerApi.createCenter(centerPayload) true -> /** * Save CenterPayload in Database table. */ - mDatabaseHelperCenter.saveCenterPayload(centerPayload) + centerDatabaseHelper.saveCenterPayload(centerPayload) } } @@ -139,14 +138,16 @@ class DataManagerCenter @Inject constructor( * @param centerId Center Id * @return CenterWithAssociations */ - fun getCenterWithAssociations(centerId: Int): Observable { - return when (prefManager.userStatus) { - false -> mBaseApiManager.centerApi.getAllGroupsForCenter(centerId) - true -> - /** - * Return Groups from DatabaseHelperGroups. - */ - mDatabaseHelperCenter.getCenterAssociateGroups(centerId) + fun getCenterWithAssociations(centerId: Int): Flow { + return flow { + when (prefManager.userStatus) { + false -> mBaseApiManager.centerApi.getAllGroupsForCenter(centerId) + true -> + /** + * Return Groups from DatabaseHelperGroups. + */ + centerDatabaseHelper.getCenterAssociateGroups(centerId) + } } } @@ -156,8 +157,8 @@ class DataManagerCenter @Inject constructor( * * @return Page of Center List */ - val allDatabaseCenters: Observable> - get() = mDatabaseHelperCenter.readAllCenters() + val allDatabaseCenters: Flow> + get() = centerDatabaseHelper.readAllCenters() suspend fun offices(): List { return baseApiManager.getOfficeApi().retrieveOffices(null, null, null) @@ -169,8 +170,8 @@ class DataManagerCenter @Inject constructor( * * @return List */ - val allDatabaseCenterPayload: Observable> - get() = mDatabaseHelperCenter.readAllCenterPayload() + val allDatabaseCenterPayload: Flow> + get() = centerDatabaseHelper.readAllCenterPayload() /** * This method will called when user is syncing the Database center. @@ -180,8 +181,8 @@ class DataManagerCenter @Inject constructor( * @param id of the centerPayload in Database * @return List> */ - fun deleteAndUpdateCenterPayloads(id: Int): Observable> { - return mDatabaseHelperCenter.deleteAndUpdateCenterPayloads(id) + fun deleteAndUpdateCenterPayloads(id: Int): Flow> { + return centerDatabaseHelper.deleteAndUpdateCenterPayloads(id) } /** @@ -190,8 +191,8 @@ class DataManagerCenter @Inject constructor( * @param centerPayload CenterPayload * @return CenterPayload */ - fun updateCenterPayload(centerPayload: CenterPayload): Observable { - return mDatabaseHelperCenter.updateDatabaseCenterPayload(centerPayload) + suspend fun updateCenterPayload(centerPayload: CenterPayload) { + return centerDatabaseHelper.updateDatabaseCenterPayload(centerPayload) } /** diff --git a/core/network/src/main/java/com/mifos/core/network/services/CenterService.kt b/core/network/src/main/java/com/mifos/core/network/services/CenterService.kt index 36b6d55eb6..14f69d1797 100644 --- a/core/network/src/main/java/com/mifos/core/network/services/CenterService.kt +++ b/core/network/src/main/java/com/mifos/core/network/services/CenterService.kt @@ -9,18 +9,18 @@ */ package com.mifos.core.network.services -import com.mifos.core.entity.center.CenterPayload import com.mifos.core.entity.group.Center +import com.mifos.core.model.objects.clients.ActivatePayload +import com.mifos.core.model.objects.clients.Page +import com.mifos.core.model.objects.databaseobjects.CollectionSheet +import com.mifos.core.model.objects.databaseobjects.OfflineCenter +import com.mifos.core.model.objects.responses.SaveResponse import com.mifos.core.network.GenericResponse import com.mifos.core.network.model.CollectionSheetPayload import com.mifos.core.network.model.Payload -import com.mifos.core.objects.clients.ActivatePayload -import com.mifos.core.objects.clients.Page -import com.mifos.core.objects.databaseobjects.CollectionSheet -import com.mifos.core.objects.databaseobjects.OfflineCenter -import com.mifos.core.objects.responses.SaveResponse import com.mifos.room.basemodel.APIEndPoint import com.mifos.room.entities.accounts.CenterAccounts +import com.mifos.room.entities.center.CenterPayload import com.mifos.room.entities.group.CenterWithAssociations import retrofit2.http.Body import retrofit2.http.GET @@ -42,7 +42,7 @@ interface CenterService { ): Observable> @GET(APIEndPoint.CENTERS + "/{centerId}/accounts") - fun getCenterAccounts(@Path("centerId") centerId: Int): Observable + suspend fun getCenterAccounts(@Path("centerId") centerId: Int): CenterAccounts @GET(APIEndPoint.CENTERS + "/{centerId}?associations=groupMembers,collectionMeetingCalendar") suspend fun getCenterWithGroupMembersAndCollectionMeetingCalendar(@Path("centerId") centerId: Int): CenterWithAssociations @@ -54,7 +54,7 @@ interface CenterService { ): List
@GET(APIEndPoint.CENTERS + "/{centerId}?associations=groupMembers") - fun getAllGroupsForCenter(@Path("centerId") centerId: Int): Observable + suspend fun getAllGroupsForCenter(@Path("centerId") centerId: Int): CenterWithAssociations @POST(APIEndPoint.CENTERS + "/{centerId}?command=generateCollectionSheet") fun getCollectionSheet( @@ -77,7 +77,7 @@ interface CenterService { /*@POST(APIEndPoint.CLIENTS + "") void uploadNewClientDetails();*/ @POST(APIEndPoint.CENTERS) - fun createCenter(@Body centerPayload: CenterPayload?): Observable + suspend fun createCenter(@Body centerPayload: CenterPayload?) @GET(APIEndPoint.CENTERS) fun getCenterList( diff --git a/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListUiState.kt b/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListUiState.kt index b23e7bf779..0b2fea4bfc 100644 --- a/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListUiState.kt +++ b/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListUiState.kt @@ -10,7 +10,7 @@ package com.mifos.feature.center.centerList.ui import androidx.paging.PagingData -import com.mifos.core.entity.group.Center +import com.mifos.room.entities.group.Center import kotlinx.coroutines.flow.Flow /** diff --git a/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListViewModel.kt b/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListViewModel.kt index 3af23f94de..abe20c64db 100644 --- a/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListViewModel.kt +++ b/feature/center/src/main/java/com/mifos/feature/center/centerList/ui/CenterListViewModel.kt @@ -11,15 +11,14 @@ package com.mifos.feature.center.centerList.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope -import com.mifos.core.common.utils.Resource import com.mifos.core.data.repository.CenterListRepository import com.mifos.core.datastore.PrefManager -import com.mifos.core.domain.useCases.GetCenterListDbUseCase import com.mifos.feature.center.R import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import javax.inject.Inject @@ -27,7 +26,6 @@ import javax.inject.Inject class CenterListViewModel @Inject constructor( private val prefManager: PrefManager, private val repository: CenterListRepository, - private val getCenterListDbUseCase: GetCenterListDbUseCase, ) : ViewModel() { // for refresh feature @@ -56,19 +54,18 @@ class CenterListViewModel @Inject constructor( _centerListUiState.value = CenterListUiState.CenterList(response) } - private fun loadCentersFromDb() = viewModelScope.launch(Dispatchers.IO) { - getCenterListDbUseCase().collect { result -> - when (result) { - is Resource.Error -> + private fun loadCentersFromDb() { + viewModelScope.launch(Dispatchers.IO) { + _centerListUiState.value = CenterListUiState.Loading + + repository.allDatabaseCenters() + .catch { _centerListUiState.value = CenterListUiState.Error(R.string.feature_center_failed_to_load_db_centers) - - is Resource.Loading -> _centerListUiState.value = CenterListUiState.Loading - - is Resource.Success -> + }.collect { _centerListUiState.value = - CenterListUiState.CenterListDb(result.data ?: emptyList()) - } + CenterListUiState.CenterListDb(it.pageItems) + } } } } diff --git a/feature/center/src/main/java/com/mifos/feature/center/createCenter/CreateNewCenterViewModel.kt b/feature/center/src/main/java/com/mifos/feature/center/createCenter/CreateNewCenterViewModel.kt index a3583d40f5..15ea21ce2c 100644 --- a/feature/center/src/main/java/com/mifos/feature/center/createCenter/CreateNewCenterViewModel.kt +++ b/feature/center/src/main/java/com/mifos/feature/center/createCenter/CreateNewCenterViewModel.kt @@ -12,10 +12,10 @@ package com.mifos.feature.center.createCenter import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mifos.core.common.utils.Resource -import com.mifos.core.domain.useCases.CreateNewCenterUseCase +import com.mifos.core.data.repository.CreateNewCenterRepository import com.mifos.core.domain.useCases.GetOfficeListUseCase -import com.mifos.core.entity.center.CenterPayload import com.mifos.feature.center.R +import com.mifos.room.entities.center.CenterPayload import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow @@ -26,7 +26,8 @@ import javax.inject.Inject @HiltViewModel class CreateNewCenterViewModel @Inject constructor( private val getOfficeListUseCase: GetOfficeListUseCase, - private val createNewCenterUseCase: CreateNewCenterUseCase, +// private val createNewCenterUseCase: CreateNewCenterUseCase, + private val repository: CreateNewCenterRepository, ) : ViewModel() { private val _createNewCenterUiState = @@ -51,20 +52,16 @@ class CreateNewCenterViewModel @Inject constructor( } } - fun createNewCenter(centerPayload: CenterPayload) = viewModelScope.launch(Dispatchers.IO) { - createNewCenterUseCase(centerPayload).collect { result -> - when (result) { - is Resource.Error -> - _createNewCenterUiState.value = - CreateNewCenterUiState.Error(R.string.feature_center_failed_to_create_center) - - is Resource.Loading -> - _createNewCenterUiState.value = - CreateNewCenterUiState.Loading - - is Resource.Success -> - _createNewCenterUiState.value = - CreateNewCenterUiState.CenterCreatedSuccessfully + fun createNewCenter(centerPayload: CenterPayload) { + viewModelScope.launch { + _createNewCenterUiState.value = CreateNewCenterUiState.Loading + try { + repository.createCenter(centerPayload) + _createNewCenterUiState.value = + CreateNewCenterUiState.CenterCreatedSuccessfully + } catch (e: Exception) { + _createNewCenterUiState.value = + CreateNewCenterUiState.Error(R.string.feature_center_failed_to_create_center) } } } diff --git a/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogUiState.kt b/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogUiState.kt index 6931a0d3de..0eb94bf2ac 100644 --- a/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogUiState.kt +++ b/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogUiState.kt @@ -10,7 +10,7 @@ package com.mifos.feature.center.syncCentersDialog import androidx.compose.ui.graphics.vector.ImageVector -import com.mifos.core.entity.group.Center +import com.mifos.room.entities.group.Center /** * Created by Aditya Gupta on 16/08/23. diff --git a/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogViewModel.kt b/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogViewModel.kt index 9c3583b6ac..fdfb798f88 100644 --- a/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogViewModel.kt +++ b/feature/center/src/main/java/com/mifos/feature/center/syncCentersDialog/SyncCentersDialogViewModel.kt @@ -9,6 +9,7 @@ */ package com.mifos.feature.center.syncCentersDialog +import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mifos.core.common.utils.Constants @@ -17,12 +18,10 @@ import com.mifos.core.data.repository.SyncCentersDialogRepository import com.mifos.core.datastore.PrefManager import com.mifos.core.designsystem.icon.MifosIcons import com.mifos.core.entity.client.Client -import com.mifos.core.entity.group.Center import com.mifos.feature.center.R -import com.mifos.room.entities.accounts.CenterAccounts import com.mifos.room.entities.accounts.loans.LoanAccount import com.mifos.room.entities.accounts.savings.SavingsAccount -import com.mifos.room.entities.group.CenterWithAssociations +import com.mifos.room.entities.group.Center import com.mifos.room.entities.group.Group import com.mifos.room.entities.group.GroupWithAssociations import com.mifos.room.entities.zipmodels.LoanAndLoanRepayment @@ -34,6 +33,9 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.observeOn +import kotlinx.coroutines.flow.subscribe +import kotlinx.coroutines.flow.subscribeOn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import retrofit2.HttpException @@ -154,38 +156,31 @@ class SyncCentersDialogViewModel @Inject constructor( * @param centerId Center Id */ private fun syncCenterAccounts(centerId: Int) { - repository.syncCenterAccounts(centerId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe( - object : Subscriber() { - override fun onCompleted() {} - override fun onError(e: Throwable) { - onAccountSyncFailed(e) - } - - override fun onNext(centerAccounts: CenterAccounts) { - mLoanAccountList = getActiveLoanAccounts( - centerAccounts - .loanAccounts, - ) - mSavingsAccountList = getActiveSavingsAccounts( - centerAccounts - .savingsAccounts, - ) - mMemberLoanAccountsList = getActiveLoanAccounts( - centerAccounts - .memberLoanAccounts, + viewModelScope.launch { + repository.syncCenterAccounts(centerId) + .catch { e -> + onAccountSyncFailed(e) + }.collect { centerAccounts -> + mLoanAccountList = getActiveLoanAccounts( + centerAccounts + .loanAccounts, + ) + mSavingsAccountList = getActiveSavingsAccounts( + centerAccounts + .savingsAccounts, + ) + mMemberLoanAccountsList = getActiveLoanAccounts( + centerAccounts + .memberLoanAccounts, + ) + // Updating UI + maxSingleSyncCenterProgressBar = ( + mLoanAccountList.size + + mSavingsAccountList.size + mMemberLoanAccountsList.size ) - // Updating UI - maxSingleSyncCenterProgressBar = ( - mLoanAccountList.size + - mSavingsAccountList.size + mMemberLoanAccountsList.size - ) - checkAccountsSyncStatusAndSyncAccounts() - } - }, - ) + checkAccountsSyncStatusAndSyncAccounts() + } + } } /** @@ -336,17 +331,22 @@ class SyncCentersDialogViewModel @Inject constructor( * @param center Center */ private fun syncCenter(center: Center) { - center.id = mCenterList[mCenterSyncIndex].id - center.sync = true - repository.syncCenterInDatabase(center) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe { + val updatedCenter = center.copy( + id = mCenterList[mCenterSyncIndex].id, + sync = true, + ) + viewModelScope.launch { + try { + repository.syncCenterInDatabase(updatedCenter) + val singleSyncCenterMax = maxSingleSyncCenterProgressBar _syncCenterData.update { it.copy(singleSyncCount = singleSyncCenterMax) } mCenterSyncIndex += 1 syncCenter() + } catch (e: Exception) { + Log.d("TAG", "syncCenter: ${e.message}") } + } } /** @@ -405,30 +405,24 @@ class SyncCentersDialogViewModel @Inject constructor( * @param centerId Center Id */ private fun loadCenterAssociateGroups(centerId: Int) { - _syncCentersDialogUiState.value = SyncCentersDialogUiState.Loading - repository.getCenterWithAssociations(centerId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe( - object : Subscriber() { - override fun onCompleted() {} - override fun onError(e: Throwable) { - onAccountSyncFailed(e) - } + viewModelScope.launch { + _syncCentersDialogUiState.value = SyncCentersDialogUiState.Loading - override fun onNext(centerWithAssociations: CenterWithAssociations) { - mGroups = centerWithAssociations.groupMembers - mGroupSyncIndex = 0 - resetIndexes() - if (mGroups.isNotEmpty()) { - _syncCenterData.update { it.copy(totalGroupsSyncCount = mGroups.size) } - mGroups[mGroupSyncIndex].id?.let { syncGroupAccounts(it) } - } else { - syncCenter(mCenterList[mCenterSyncIndex]) - } + repository.getCenterWithAssociations(centerId) + .catch { + onAccountSyncFailed(it) + }.collect { centerWithAssociations -> + mGroups = centerWithAssociations.groupMembers + mGroupSyncIndex = 0 + resetIndexes() + if (mGroups.isNotEmpty()) { + _syncCenterData.update { it.copy(totalGroupsSyncCount = mGroups.size) } + mGroups[mGroupSyncIndex].id?.let { syncGroupAccounts(it) } + } else { + syncCenter(mCenterList[mCenterSyncIndex]) } - }, - ) + } + } } /** diff --git a/feature/offline/src/main/java/com/mifos/feature/offline/dashboard/OfflineDashboardViewModel.kt b/feature/offline/src/main/java/com/mifos/feature/offline/dashboard/OfflineDashboardViewModel.kt index 2a1157f601..1b8dbe0163 100644 --- a/feature/offline/src/main/java/com/mifos/feature/offline/dashboard/OfflineDashboardViewModel.kt +++ b/feature/offline/src/main/java/com/mifos/feature/offline/dashboard/OfflineDashboardViewModel.kt @@ -13,7 +13,6 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mifos.core.data.repository.OfflineDashboardRepository import com.mifos.core.entity.accounts.savings.SavingsAccountTransactionRequest -import com.mifos.core.entity.center.CenterPayload import com.mifos.core.entity.client.ClientPayload import com.mifos.feature.offline.R import dagger.hilt.android.lifecycle.HiltViewModel @@ -68,21 +67,14 @@ class OfflineDashboardViewModel @Inject constructor( } fun loadDatabaseCenterPayload() { - repository.allDatabaseCenterPayload() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribe( - object : Subscriber>() { - override fun onCompleted() {} - override fun onError(e: Throwable) { - setError(Type.SYNC_CENTERS, e.message.toString()) - } - - override fun onNext(centerPayloads: List) { - setCountOfSyncData(Type.SYNC_CENTERS, centerPayloads.size) - } - }, - ) + viewModelScope.launch { + repository.allDatabaseCenterPayload() + .catch { + setError(Type.SYNC_CENTERS, it.message.toString()) + }.collect { centerPayloads -> + setCountOfSyncData(Type.SYNC_CENTERS, centerPayloads.size) + } + } } fun loadDatabaseLoanRepaymentTransactions() { diff --git a/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsUiState.kt b/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsUiState.kt index b4723f445e..a9118bff9a 100644 --- a/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsUiState.kt +++ b/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsUiState.kt @@ -9,7 +9,7 @@ */ package com.mifos.feature.offline.syncCenterPayloads -import com.mifos.core.entity.center.CenterPayload +import com.mifos.room.entities.center.CenterPayload /** * Created by Aditya Gupta on 16/08/23. diff --git a/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsViewModel.kt b/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsViewModel.kt index e0616528b6..d63423d522 100644 --- a/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsViewModel.kt +++ b/feature/offline/src/main/java/com/mifos/feature/offline/syncCenterPayloads/SyncCenterPayloadsViewModel.kt @@ -13,18 +13,15 @@ import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mifos.core.common.utils.FileUtils.LOG_TAG -import com.mifos.core.common.utils.Resource +import com.mifos.core.data.repository.SyncCenterPayloadsRepository import com.mifos.core.datastore.PrefManager -import com.mifos.core.domain.useCases.AllDatabaseCenterPayloadUseCase -import com.mifos.core.domain.useCases.CreateCenterUseCase -import com.mifos.core.domain.useCases.DeleteAndUpdateCenterPayloadsUseCase -import com.mifos.core.domain.useCases.UpdateCenterPayloadUseCase -import com.mifos.core.entity.center.CenterPayload +import com.mifos.room.entities.center.CenterPayload import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import javax.inject.Inject @@ -33,11 +30,8 @@ import javax.inject.Inject */ @HiltViewModel class SyncCenterPayloadsViewModel @Inject constructor( - private val deleteAndUpdateCenterPayloadsUseCase: DeleteAndUpdateCenterPayloadsUseCase, - private val updateCenterPayloadUseCase: UpdateCenterPayloadUseCase, - private val createCenterUseCase: CreateCenterUseCase, - private val allDatabaseCenterPayloadUseCase: AllDatabaseCenterPayloadUseCase, private val prefManager: PrefManager, + private val repository: SyncCenterPayloadsRepository, ) : ViewModel() { private val _syncCenterPayloadsUiState = MutableStateFlow( @@ -61,99 +55,77 @@ class SyncCenterPayloadsViewModel @Inject constructor( _isRefreshing.value = false } - fun loadDatabaseCenterPayload() = viewModelScope.launch(Dispatchers.IO) { - allDatabaseCenterPayloadUseCase().collect { result -> - when (result) { - is Resource.Error -> + fun loadDatabaseCenterPayload() { + viewModelScope.launch(Dispatchers.IO) { + repository.allDatabaseCenterPayload() + .catch { _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowError(result.message.toString()) - - is Resource.Loading -> Unit - - is Resource.Success -> { - mCenterPayloads = result.data?.toMutableList() ?: mutableListOf() + SyncCenterPayloadsUiState.ShowError(it.message.toString()) + }.collect { mCenterPayloads -> _syncCenterPayloadsUiState.value = SyncCenterPayloadsUiState.ShowCenters(mCenterPayloads) } - } } } private fun syncCenterPayload(centerPayload: CenterPayload?) { - if (centerPayload != null) { - viewModelScope.launch(Dispatchers.IO) { - createCenterUseCase(centerPayload).collect { result -> - when (result) { - is Resource.Error -> { - _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowError(result.message.toString()) - updateCenterPayload(centerPayload) - } - - is Resource.Loading -> - _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowProgressbar - - is Resource.Success -> { - deleteAndUpdateCenterPayload( - mCenterPayloads[centerSyncIndex].id, - ) - } - } - } + viewModelScope.launch { + _syncCenterPayloadsUiState.value = + SyncCenterPayloadsUiState.ShowProgressbar + try { + repository.createCenter(centerPayload) + + deleteAndUpdateCenterPayload( + mCenterPayloads[centerSyncIndex].id, + ) + } catch (e: Exception) { + _syncCenterPayloadsUiState.value = + SyncCenterPayloadsUiState.ShowError(e.message.toString()) + updateCenterPayload(centerPayload) } } } - private fun deleteAndUpdateCenterPayload(id: Int) = - viewModelScope.launch(Dispatchers.IO) { - deleteAndUpdateCenterPayloadsUseCase(id).collect { result -> - when (result) { - is Resource.Error -> - _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowError(result.message.toString()) - - is Resource.Loading -> - _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowProgressbar + private fun deleteAndUpdateCenterPayload(id: Int) { + viewModelScope.launch { + _syncCenterPayloadsUiState.value = + SyncCenterPayloadsUiState.ShowProgressbar - is Resource.Success -> { - centerSyncIndex = 0 - mCenterPayloads = result.data?.toMutableList() ?: mutableListOf() - _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowCenters(mCenterPayloads) - if (mCenterPayloads.isNotEmpty()) { - syncCenterPayload() - } + repository.deleteAndUpdateCenterPayloads(id) + .catch { + _syncCenterPayloadsUiState.value = + SyncCenterPayloadsUiState.ShowError(it.message.toString()) + }.collect { + centerSyncIndex = 0 + mCenterPayloads = it.toMutableList() + _syncCenterPayloadsUiState.value = + SyncCenterPayloadsUiState.ShowCenters(mCenterPayloads) + if (mCenterPayloads.isNotEmpty()) { + syncCenterPayload() } } - } } + } private fun updateCenterPayload(centerPayload: CenterPayload?) { deleteAndUpdateCenterPayload( mCenterPayloads[centerSyncIndex].id, ) if (centerPayload != null) { - viewModelScope.launch(Dispatchers.IO) { - updateCenterPayloadUseCase(centerPayload).collect { result -> - when (result) { - is Resource.Error -> - _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowError(result.message.toString()) - - is Resource.Loading -> Unit + viewModelScope.launch { + try { + repository.updateCenterPayload(centerPayload) - is Resource.Success -> { - mCenterPayloads[centerSyncIndex] = result.data ?: CenterPayload() - _syncCenterPayloadsUiState.value = - SyncCenterPayloadsUiState.ShowCenters(mCenterPayloads) - centerSyncIndex += 1 - if (mCenterPayloads.size != centerSyncIndex) { - syncCenterPayload() - } - } + mCenterPayloads[centerSyncIndex] = centerPayload + _syncCenterPayloadsUiState.value = + SyncCenterPayloadsUiState.ShowCenters(mCenterPayloads) + centerSyncIndex += 1 + if (mCenterPayloads.size != centerSyncIndex) { + syncCenterPayload() } + } catch (e: Exception) { + _syncCenterPayloadsUiState.value = + SyncCenterPayloadsUiState.ShowError(e.message.toString()) } } }