package com.cottondb.android import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.navigation.Route import com.cottondb.android.work.money.MoneyReadState import java.time.Clock import java.time.Instant import java.time.ZoneId import java.time.ZoneOffset import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotSame import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith /** Retained Account hosts keep native reads local to the routes that requested them. */ @RunWith(AndroidJUnit4::class) class MoneyModelsTest { private val fixtures = CopyOnWriteArrayList() @After fun closeModels() = onMain { fixtures.forEach(Fixture::close) fixtures.clear() } @Test fun typedVisitsUseInjectedLocalDayAndExactReadMethods() { val fixture = onMain { fixture() } val overview = onMain { fixture.models.overview() } val account = onMain { fixture.models.account("account-1") } val statement = onMain { fixture.models.statement("statement-1") } val transaction = onMain { fixture.models.transaction("transaction-1") } runBlocking { overview.refresh().join() account.refresh().join() statement.refresh().join() transaction.refresh().join() } InstrumentationRegistry.getInstrumentation().waitForIdleSync() assertEquals("2026-09-23", fixture.request("read.money")["today"]!!.jsonPrimitive.content) assertEquals("2026-09-23", fixture.request("read.moneyAccount")["today"]!!.jsonPrimitive.content) assertEquals("account-1", fixture.request("read.moneyAccount")["accountId"]!!.jsonPrimitive.content) assertEquals("statement-1", fixture.request("read.statement")["id"]!!.jsonPrimitive.content) assertEquals("transaction-1", fixture.request("read.transaction")["id"]!!.jsonPrimitive.content) assertTrue(overview.state.value is MoneyReadState.Data) assertTrue(account.state.value is MoneyReadState.Data) assertTrue(statement.state.value is MoneyReadState.Data) assertTrue(transaction.state.value is MoneyReadState.Data) } @Test fun retainedStackKeepsTypedVisitIdentityAndPoppedVisitRefusesFutureRefresh() = onMain { val fixture = fixture() val overview = fixture.models.overview() val account = fixture.models.account("account-1") val statement = fixture.models.statement("statement-1") val transaction = fixture.models.transaction("transaction-1") fixture.models.retain(listOf(Route.Money, Route.MoneyAccount("account-1"), Route.MoneyStatement("statement-1"), Route.MoneyTransaction("transaction-1"))) assertSame(overview, fixture.models.overview()) assertSame(account, fixture.models.account("account-1")) assertSame(statement, fixture.models.statement("statement-1")) assertSame(transaction, fixture.models.transaction("transaction-1")) fixture.models.retain(listOf(Route.Money)) runBlocking { account.refresh().join() } assertFalse(fixture.core.methods.contains("read.moneyAccount")) assertNotSame(account, fixture.models.account("account-1")) assertNotSame(statement, fixture.models.statement("statement-1")) assertNotSame(transaction, fixture.models.transaction("transaction-1")) } @Test fun blankRouteIdsAreVisibleErrorsAndNeverReachNative() = onMain { val fixture = fixture() val account = fixture.models.account(" ") val statement = fixture.models.statement("\t") val transaction = fixture.models.transaction("") runBlocking { account.refresh().join() statement.refresh().join() transaction.refresh().join() } assertEquals("This account could not be opened.", (account.state.value as MoneyReadState.Error).message) assertEquals("This statement could not be opened.", (statement.state.value as MoneyReadState.Error).message) assertEquals("This transaction could not be opened.", (transaction.state.value as MoneyReadState.Error).message) assertTrue(fixture.core.methods.isEmpty()) } @Test fun failureRemainsVisibleWithNoSyntheticData() { val fixture = onMain { fixture(failStatement = true) } val statement = onMain { fixture.models.statement("statement-1") } runBlocking { statement.refresh().join() } InstrumentationRegistry.getInstrumentation().waitForIdleSync() val failure = statement.state.value as MoneyReadState.Error assertEquals("Synthetic statement failure", failure.message) assertEquals(null, failure.last) } @Test fun retirementCancelsOwnedReadAndLateNativeAnswerCannotUpdateRetiredVisit() { val fixture = onMain { fixture(blockAccount = true) } val retired = onMain { fixture.models.account("account-1") } onMain { retired.refresh() } assertTrue(fixture.core.accountEntered.await(3, TimeUnit.SECONDS)) onMain { fixture.models.retain(emptyList()) } fixture.core.releaseAccount() InstrumentationRegistry.getInstrumentation().waitForIdleSync() assertTrue(retired.state.value is MoneyReadState.Loading) assertNotSame(retired, onMain { fixture.models.account("account-1") }) } private fun fixture(failStatement: Boolean = false, blockAccount: Boolean = false) = Fixture(failStatement, blockAccount).also(fixtures::add) private fun onMain(block: () -> T): T { var result: Result? = null InstrumentationRegistry.getInstrumentation().runOnMainSync { result = runCatching(block) } return requireNotNull(result).getOrThrow() } private class Fixture(failStatement: Boolean, blockAccount: Boolean) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) val core = MoneyCore(failStatement, blockAccount) val models = MoneyModels( core = core, clock = Clock.fixed(Instant.parse("2026-09-22T23:30:00Z"), ZoneOffset.UTC), zone = ZoneId.of("Asia/Kolkata"), scope = scope, ) fun request(method: String): JsonObject = core.requests.single { it.first == method }.second fun close() = scope.cancel() } private class MoneyCore( private val failStatement: Boolean, private val blockAccount: Boolean, ) : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val methods = CopyOnWriteArrayList() val requests = CopyOnWriteArrayList>() val accountEntered = CountDownLatch(1) private val accountReply = CompletableDeferred() override suspend fun call(method: String, request: JsonObject): JsonElement { methods += method requests += method to request return when (method) { "read.money" -> json(MONEY) "read.moneyAccount" -> if (blockAccount) { accountEntered.countDown() withContext(NonCancellable) { accountReply.await() } } else json(ACCOUNT) "read.statement" -> if (failStatement) error("Synthetic statement failure") else json(STATEMENT) "read.transaction" -> json(TRANSACTION) else -> error("Unexpected core method: $method") } } override suspend fun close() = Unit fun releaseAccount() { accountReply.complete(json(ACCOUNT)) } } private companion object { fun json(raw: String): JsonElement = Json.parseToJsonElement(raw) const val MONEY = """{"currency":"INR","accounts":[],"month":{"key":"2026-09","spentMinor":0,"receivedMinor":0,"unaccountedMinor":0}}""" const val ACCOUNT = """{"account":{"id":"account-1","name":"Synthetic account","kind":"asset","subtype":"bank","currency":"INR","institution":null,"numberMask":null},"liveBalanceMinor":0,"rows":[],"statements":[],"gaps":[]}""" const val TRANSACTION = """{"transaction":{"id":"transaction-1","occurredOn":"2026-09-22","description":"Synthetic transaction","personId":null,"status":null,"source":null,"notes":null,"dueDate":null,"settlesTransactionId":null,"classifiedBy":null,"classifiedByLabel":null,"confidenceBps":null,"payeeText":null,"period":null},"lines":[],"evidence":[],"categories":[],"people":[]}""" const val STATEMENT = """{"id":"statement-1","documentId":"document-1","accountId":"account-1","kind":"bank","period":{"from":"2026-09-01","to":"2026-09-30"},"openingBalanceMinor":0,"closingBalanceMinor":0,"currency":"INR","readStatus":"read","readError":null,"readBy":null,"readAt":null,"balanceCheck":"ok","lineCount":0,"sumInMinor":0,"sumOutMinor":0,"account":{"id":"account-1","name":"Synthetic account","kind":"asset","subtype":"bank","currency":"INR","institution":null,"numberMask":null},"lines":[]}""" } }