package com.cottondb.android.ui.day.people import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.material3.Text import androidx.compose.ui.test.hasContentDescription import androidx.compose.ui.test.hasText import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.performTextReplacement import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.onRoot import androidx.compose.ui.graphics.asAndroidBitmap import com.cottondb.android.ScreenEvidence import com.cottondb.android.design.CottonTheme import com.cottondb.android.ui.media.CottonAvatar import com.cottondb.android.media.* import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextClearance import androidx.compose.ui.test.performTextInput import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.day.people.PeopleRead import com.cottondb.android.day.people.PeopleRepository import com.cottondb.android.day.people.PeopleState import com.cottondb.android.day.people.PersonDetailModel import com.cottondb.android.day.people.PersonListing import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import org.junit.Assert.assertEquals import org.junit.After import kotlinx.coroutines.cancel import org.junit.Rule import org.junit.runner.RunWith import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test @RunWith(AndroidJUnit4::class) class PeopleScreensTest { @get:Rule val compose = createComposeRule() private val fixtures = mutableListOf() @After fun closeScopes() { fixtures.forEach { it.writerScope.cancel() } } @Test fun directorySearchesTheCompleteReadAndNavigatesToTheSelectedPerson() { var route: String? = null compose.setContent { PeopleDirectoryScreen( state = PeopleState.Data(PeopleRead(2, 0, false, listOf(person("a", "Asha", "Studio"), person("b", "Bela", "Elsewhere")))), query = "studio", layout = PeopleLayout.List, onQueryChange = {}, onLayoutChange = {}, onRefresh = {}, onOpenPerson = { route = "/people/person/$it" }, ) } ScreenEvidence.capture("people-directory") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.onNodeWithText("Bela").assertDoesNotExist() compose.onNodeWithText("Asha").performClick() assertEquals("/people/person/a", route) } @Test fun emptyDirectoryOffersTheContactImportFlow() { var imports = 0 compose.setContent { PeopleDirectoryScreen( state = PeopleState.Data(PeopleRead(0, 0, false, emptyList())), query = "", layout = PeopleLayout.Grid, onQueryChange = {}, onLayoutChange = {}, onRefresh = {}, onOpenPerson = {}, onImport = { imports += 1 }, ) } compose.onNodeWithText("Import contacts").assertExists().performClick() assertEquals(1, imports) } @Test fun invalidBirthdayPreventsSaveAndAChosenTimezoneEnablesIt() { val fixture = DetailFixture().also(fixtures::add) compose.setContent { fixture.screen() } compose.waitUntil(5_000) { fixture.model.editor.value != null } ScreenEvidence.capture("person-detail") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.onNodeWithContentDescription("Edit person").performClick() input("Month", "2") input("Day", "30") compose.onNodeWithText("That day is not in this birthday month.").assertExists() compose.onNodeWithText("Save").assertIsNotEnabled() input("Day", "29") input("Timezone", "Berlin") compose.onNodeWithText("Europe/Berlin").performClick() compose.onNodeWithText("Save").assertIsEnabled() } @Test fun partialSaveFailureStaysInTheEditorAndArchiveNeedsConfirmation() { val fixture = DetailFixture(summaryFails = true).also(fixtures::add) compose.setContent { fixture.screen() } compose.waitUntil(5_000) { fixture.model.editor.value != null } ScreenEvidence.capture("person-detail") { compose.onRoot().captureToImage().asAndroidBitmap() } compose.onNodeWithContentDescription("Edit person").performClick() input("City", "Berlin") input("Summary", "A new summary") compose.onNodeWithText("Save").performClick() compose.waitUntil(5_000) { fixture.core.summaryWrites == 1 } compose.onNodeWithTag("person-edit-fields").performScrollToNode(hasText("Summary could not be saved")) compose.onNodeWithText("Summary could not be saved").assertExists() compose.onNodeWithText("Edit person").assertExists() compose.onNodeWithText("Cancel").performClick() compose.onNodeWithContentDescription("Archive person").performClick() compose.onNodeWithText("Archive Asha?").assertExists() assertEquals(0, fixture.core.archives) compose.onNodeWithTag("person-archive-confirm").performClick() compose.waitUntil(5_000) { fixture.core.archives == 1 } } private fun input(label: String, value: String) { compose.onNodeWithTag("person-edit-fields").performScrollToNode(hasContentDescription(label)) compose.onNodeWithContentDescription(label).performTextReplacement(value) } private fun person(id: String, name: String, org: String) = PersonListing( id = id, name = name, phones = emptyList(), emails = emptyList(), org = org, roleTitle = null, city = null, timezone = null, avatarKey = null, avatarUrl = null, ) private class DetailFixture(summaryFails: Boolean = false) { val core = PersonCore(summaryFails) val model = PersonDetailModel(PeopleRepository(core), "person-a") val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) @androidx.compose.runtime.Composable fun screen() = CottonTheme { PersonDetailScreen( model = model, writerScope = writerScope, dataRevision = 0, avatar = { id, name, key, size -> CottonAvatar(id, name, key, media, 0, size) }, onBack = {}, onNavigate = {}, onOpenUri = {}, clock = java.time.Clock.fixed(java.time.Instant.parse("2026-01-01T12:00:00Z"), java.time.ZoneOffset.UTC), zoneId = java.time.ZoneOffset.UTC, ) } private val media = object : LocalMediaSource { override suspend fun local(key: String, tier: MediaPathTier) = LocalMedia.Absent } } private class PersonCore(private val summaryFails: Boolean) : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() var summaryWrites = 0 var archives = 0 override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) { "read.person" -> detailJson() "write" -> when ((request["tool"] as JsonPrimitive).content) { "update_person" -> buildJsonObject { } "update_summary" -> { summaryWrites += 1 if (summaryFails) error("Summary could not be saved") else buildJsonObject { } } "archive_person" -> { archives += 1 buildJsonObject { } } else -> error("unexpected person write") } else -> error("unexpected method $method") } override suspend fun close() = Unit } private companion object { fun detailJson() = buildJsonObject { put("person", buildJsonObject { put("id", "person-a"); put("workspaceId", "workspace"); put("fullName", "Asha") put("phones", buildJsonArray { add(JsonPrimitive("+49 123 4567890")) }) put("emails", buildJsonArray { add(JsonPrimitive("asha@example.test")) }) put("org", "Studio"); put("roleTitle", "Designer"); put("city", "Hamburg") put("summary", kotlinx.serialization.json.JsonNull); put("summaryBy", kotlinx.serialization.json.JsonNull); put("summaryUpdatedAt", kotlinx.serialization.json.JsonNull) put("contactSource", kotlinx.serialization.json.JsonNull); put("deviceContactId", kotlinx.serialization.json.JsonNull); put("birthday", kotlinx.serialization.json.JsonNull) put("timezone", "Europe/Berlin"); put("avatarKey", kotlinx.serialization.json.JsonNull); put("avatarUrl", kotlinx.serialization.json.JsonNull) put("archivedAt", kotlinx.serialization.json.JsonNull); put("createdAt", kotlinx.serialization.json.JsonNull); put("updatedAt", kotlinx.serialization.json.JsonNull) }) put("thread", kotlinx.serialization.json.JsonNull) put("projects", buildJsonArray { }) put("projectLinks", buildJsonArray { }) // Strict `parsePersonSections` consumes these families from the same read. put("personNotes", buildJsonArray { }) put("links", buildJsonArray { }) put("linkedRecordFacts", buildJsonObject { }) put("todos", buildJsonArray { }) put("calls", buildJsonArray { }) put("faceSuggestions", buildJsonArray { }) put("faceSuggestionPhotos", buildJsonArray { }) put("money", buildJsonArray { }) put("summary", buildJsonObject { put("summary", buildJsonObject { put("text", kotlinx.serialization.json.JsonNull); put("by", kotlinx.serialization.json.JsonNull); put("updatedAt", kotlinx.serialization.json.JsonNull) }) }) } } }