Přizpůsobení mobilního klienta změnám backendu

This commit is contained in:
pilnas committed 2026-11-19 16:03:00 +01:00
1 parent a1bf12ba72
commit c4fe447d9d
17 files changed
+589 -49

No files matched your search

@@ -0,0 +1,77 @@
package cz.ntbug.mobile
import android.content.Context
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import cz.ntbug.mobile.ui.AccountScreen
import cz.ntbug.mobile.ui.AppState
import cz.ntbug.mobile.ui.AppViewModel
import cz.ntbug.mobile.ui.AuthOutcome
import cz.ntbug.mobile.ui.NTBugTheme
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExternalResource
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
/** Auth navigation stays usable without SMTP and never submits credentials automatically. */
@RunWith(AndroidJUnit4::class)
class AuthFlowUiTest {
private val compose = createAndroidComposeRule<MainActivity>()
private val cleanSession = object : ExternalResource() {
override fun before() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
check(context.getSharedPreferences("ntbug_session", Context.MODE_PRIVATE).edit().clear().commit())
}
}
@get:Rule val rules: RuleChain = RuleChain.outerRule(cleanSession).around(compose)
@Test fun verificationScreenOffersExplicitRegistrationRetry() {
awaitLogin()
compose.onNodeWithText("Ověřit e-mail").performScrollTo().performClick()
compose.onNodeWithText("Poslat ověřovací e-mail znovu").performScrollTo().performClick()
compose.onNodeWithText("Vytvořit účet").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Pokud už máte neověřený účet", substring = true).assertIsDisplayed()
compose.onNodeWithText("Jméno").assertExists()
compose.onNodeWithText("Heslo znovu").assertExists()
}
@Test fun leavingRegistrationClearsPasswordBeforeReturningToLogin() {
awaitLogin()
compose.onNodeWithText("Ještě nemám účet").performScrollTo().performClick()
val password = compose.onNode(hasSetTextAction() and hasText("Heslo"))
password.performScrollTo().performTextInput("LocalTestPassword123")
compose.onNodeWithText("Zpět na přihlášení").performScrollTo().performClick()
val loginPassword = compose.onNode(hasSetTextAction() and hasText("Heslo"))
assertEquals("", loginPassword.fetchSemanticsNode().config[SemanticsProperties.EditableText].text)
}
private fun awaitLogin() {
compose.waitUntil(15_000) { compose.onAllNodesWithText("Prohlédnout ukázku").fetchSemanticsNodes().isNotEmpty() }
}
}
@RunWith(AndroidJUnit4::class)
class RestoredAuthOutcomeUiTest {
@get:Rule val compose = createComposeRule()
@Test fun registrationFinishedBeforeScreenCreationStillOpensVerificationAndKeepsItsMessage() {
compose.setContent {
val vm: AppViewModel = viewModel()
NTBugTheme {
AccountScreen(AppState(booting = false, authOutcome = AuthOutcome.REGISTERED,
authMessage = "Registrace je hotová. Ověřte e-mail."), vm)
}
}
compose.onNodeWithText("Vložte ověřovací odkaz nebo token z registračního e-mailu.").assertIsDisplayed()
compose.onNodeWithText("Registrace je hotová. Ověřte e-mail.").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Poslat ověřovací e-mail znovu").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Heslo znovu").assertDoesNotExist()
}
}
@@ -0,0 +1,76 @@
package cz.ntbug.mobile
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.text.AnnotatedString
import androidx.test.ext.junit.runners.AndroidJUnit4
import cz.ntbug.mobile.data.*
import cz.ntbug.mobile.ui.NTBugTheme
import cz.ntbug.mobile.ui.features.EditIssueScreen
import cz.ntbug.mobile.ui.features.NewProposalScreen
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CatalogFormTest {
@get:Rule val compose = createComposeRule()
@Test fun catalogRefreshKeepsEditedTitleAndOriginalInactiveReferences() {
val original = Issue(7, "Původní název", "Popis závady", "RECEIVED", 9, "Původní kategorie",
buildingId = 20, buildingName = "Původní budova", reporterId = 1, reporterName = "Jana", createdAt = "2026-11-19T10:00:00Z")
val catalogs = mutableStateOf(Catalogs(listOf(Building(20, "", "Původní budova")), listOf(Category(9, "Původní kategorie")), emptyList()))
var submitted: NewIssue? = null
var clearFocus: () -> Unit = {}
compose.setContent {
val focus = LocalFocusManager.current
val keyboard = LocalSoftwareKeyboardController.current
SideEffect { clearFocus = { keyboard?.hide(); focus.clearFocus() } }
NTBugTheme { EditIssueScreen(original, catalogs.value, busy = false) { submitted = it } }
}
val title = compose.onNode(hasSetTextAction() and hasText("Název závady *"))
title.performScrollTo().performTextReplacement("Rozepsaná změna názvu")
compose.runOnIdle { clearFocus(); catalogs.value = Catalogs(emptyList(), emptyList(), emptyList()) }
title.assert(SemanticsMatcher.expectValue(SemanticsProperties.EditableText, AnnotatedString("Rozepsaná změna názvu")))
compose.onNodeWithText("Původní kategorie (již není v nabídce)").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Původní budova (již není v nabídce)").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Uložit změny").performScrollTo().assertIsEnabled().performClick()
compose.runOnIdle {
val sent = requireNotNull(submitted)
assertEquals("Rozepsaná změna názvu", sent.title)
assertEquals(9, sent.categoryId)
assertEquals(20, sent.buildingId)
}
}
@Test fun deactivatedProposalCategoryIsRemovedWithoutLosingTheDraft() {
val catalogs = mutableStateOf(Catalogs(emptyList(), emptyList(), listOf(Category(2, "Studovna"))))
var submitted: NewProposal? = null
var clearFocus: () -> Unit = {}
compose.setContent {
val focus = LocalFocusManager.current
val keyboard = LocalSoftwareKeyboardController.current
SideEffect { clearFocus = { keyboard?.hide(); focus.clearFocus() } }
NTBugTheme { NewProposalScreen(catalogs.value, busy = false) { submitted = it } }
}
compose.onNodeWithText("Oblast *").performScrollTo().performClick()
compose.onNodeWithText("Studovna").performClick()
val title = compose.onNode(hasSetTextAction() and hasText("Název návrhu *"))
title.performScrollTo().performTextReplacement("Další zásuvky")
compose.onNode(hasSetTextAction() and hasText("Popis a přínos *")).performScrollTo().performTextReplacement("Více míst pro studium.")
compose.runOnIdle {
clearFocus()
catalogs.value = catalogs.value.copy(proposalCategories = listOf(Category(2, "Studovna", isActive = false)))
}
title.performScrollTo().assert(SemanticsMatcher.expectValue(SemanticsProperties.EditableText, AnnotatedString("Další zásuvky")))
compose.onNodeWithText("Vybraná oblast už není v nabídce. Vyberte jinou.").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Odeslat návrh").performScrollTo().assertIsNotEnabled()
compose.runOnIdle { assertNull(submitted) }
}
}
@@ -52,7 +52,7 @@ class DemoRepository : HelpdeskRepository {
user = user.copy(firstName = update.firstName.trim(), lastName = update.lastName.trim(), phone = update.phone?.trim()?.takeIf(String::isNotBlank), emailNotificationsEnabled = update.emailNotificationsEnabled)
return user
}
override suspend fun catalogs(): Catalogs = catalog
override suspend fun catalogs(refresh: Boolean): Catalogs = catalog
override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> = paginate(
issueItems.filter { (status == null || it.status == status) && (it.title.contains(query, true) || it.description.contains(query, true)) && !assigned }, page,
)
@@ -88,7 +88,7 @@ interface HelpdeskRepository {
suspend fun restoreUser(): User?
suspend fun logout(allDevices: Boolean = false)
suspend fun updateProfile(update: ProfileUpdate): User
suspend fun catalogs(): Catalogs
suspend fun catalogs(refresh: Boolean = false): Catalogs
suspend fun issues(page: Int = 1, query: String = "", status: String? = null, assigned: Boolean = false): Page<Issue>
suspend fun issue(id: Int): Issue
suspend fun createIssue(issue: NewIssue): Issue
@@ -120,8 +120,10 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
return user
}
override suspend fun catalogs(): Catalogs = catalogLock.withLock {
catalogCache ?: Catalogs(
override suspend fun catalogs(refresh: Boolean): Catalogs = catalogLock.withLock {
// Administrators can rename/deactivate catalog entries while this session is open.
// Publish a replacement only when all three requests have completed successfully.
catalogCache?.takeUnless { refresh } ?: Catalogs(
authorized { api.buildings(it) }, authorized { api.issueCategories(it) }, authorized { api.proposalCategories(it) },
).also { catalogCache = it }
}
@@ -286,6 +288,7 @@ class RemoteRepository(baseUrl: String, private val store: SessionPersistence) :
409 -> "Záznam se mezitím změnil. Obnovte jej a zkuste akci znovu."
413 -> "Přílohy jsou příliš velké. Limit je 10 MB na soubor."
429 -> "Příliš mnoho požadavků. Zkuste to za chvíli."
503 -> "Služba je dočasně nedostupná. Zkuste požadavek později."
else -> "Server je dočasně nedostupný (${error.code()}). Zkuste to později."
}
val body = runCatching { error.response()?.errorBody()?.string() }.getOrNull()
@@ -42,8 +42,14 @@ fun AccountScreen(s: AppState, vm: AppViewModel) {
var token by remember { mutableStateOf("") }
var validation by remember { mutableStateOf<String?>(null) }
var serverDialog by remember { mutableStateOf(false) }
fun change(value: AuthMode) {
mode = value; password = ""; repeat = ""; token = ""; validation = null; vm.clearFeedback()
fun complete(value: AuthMode) {
mode = value; password = ""; repeat = ""; token = ""; validation = null
}
fun change(value: AuthMode) { complete(value); vm.clearFeedback() }
LaunchedEffect(s.authOutcome) {
val outcome = s.authOutcome ?: return@LaunchedEffect
complete(if (outcome == AuthOutcome.REGISTERED) AuthMode.CONFIRM else AuthMode.LOGIN)
vm.consumeAuthOutcome(outcome)
}
Column(
@@ -63,8 +69,8 @@ fun AccountScreen(s: AppState, vm: AppViewModel) {
Text(mode.title, style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold)
Text(when (mode) {
AuthMode.LOGIN -> "Lepší univerzita začíná u vás. Nahlaste závadu, sledujte řešení a podpořte dobré nápady."
AuthMode.REGISTER -> "Použijte univerzitní e-mail. Studentský nebo vyučující účet se určí automaticky."
AuthMode.FORGOT -> "Na univerzitní e-mail vám pošleme odkaz pro nastavení nového hesla."
AuthMode.REGISTER -> "Použijte univerzitní e-mail. Studentský nebo vyučující účet se určí automaticky. Pokud už máte neověřený účet, stejné registrační údaje znovu odešlou ověřovací e-mail."
AuthMode.FORGOT -> "Požádejte o odkaz pro nastavení nového hesla. Pokud vám zpráva nepřijde, zkontrolujte také složku Spam."
AuthMode.CONFIRM -> "Vložte ověřovací odkaz nebo token z registračního e-mailu."
AuthMode.RESET -> "Vložte odkaz z e-mailu a zvolte nové heslo o délce 8 až 64 znaků."
}, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -121,7 +127,12 @@ fun AccountScreen(s: AppState, vm: AppViewModel) {
TextButton(onClick = { change(AuthMode.CONFIRM) }, enabled = !s.busy) { Text("Ověřit e-mail") }
TextButton(onClick = { change(AuthMode.RESET) }, enabled = !s.busy) { Text("Mám odkaz na reset") }
}
} else TextButton(onClick = { change(AuthMode.LOGIN) }, enabled = !s.busy) { Text("Zpět na přihlášení") }
} else {
if (mode == AuthMode.CONFIRM) TextButton(onClick = { change(AuthMode.REGISTER) }, enabled = !s.busy, modifier = Modifier.fillMaxWidth()) {
Text("Poslat ověřovací e-mail znovu")
}
TextButton(onClick = { change(AuthMode.LOGIN) }, enabled = !s.busy) { Text("Zpět na přihlášení") }
}
TextButton(onClick = { serverDialog = true }, enabled = !s.busy, modifier = Modifier.align(Alignment.CenterHorizontally)) {
Icon(Icons.Outlined.Dns, null, modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text("Nastavení serveru")
}
@@ -199,7 +210,7 @@ private fun ServerDialog(current: String, onDismiss: () -> Unit, onSave: (String
var value by remember { mutableStateOf(current) }
AlertDialog(onDismissRequest = onDismiss, title = { Text("Server NTBug") },
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("Pro emulátor použijte http://10.0.2.2:8080/. Na telefonu zadejte adresu počítače ve stejné Wi-Fi síti. Mimo místní vývoj použijte HTTPS.")
Text("Pro emulátor použijte http://10.0.2.2:8080/. Na telefonu zadejte adresu počítače ve stejné Wi-Fi síti. Server musí povolovat připojení z místní sítě. Mimo místní vývoj použijte HTTPS.")
AccountField(value, { value = it }, "Adresa serveru", KeyboardType.Uri)
} }, confirmButton = { TextButton(onClick = { onSave(value) }) { Text("Uložit") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Zrušit") } })
}
@@ -15,6 +15,8 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
enum class AuthOutcome { REGISTERED, EMAIL_CONFIRMED, PASSWORD_RESET }
data class AppState(
val booting: Boolean = true,
val user: User? = null,
@@ -25,6 +27,7 @@ data class AppState(
val error: String? = null,
val message: String? = null,
val authMessage: String? = null,
val authOutcome: AuthOutcome? = null,
val catalogs: Catalogs = Catalogs(emptyList(), emptyList(), emptyList()),
val issues: List<Issue> = emptyList(),
val proposals: List<Proposal> = emptyList(),
@@ -100,26 +103,36 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
}
fun register(email: String, password: String, firstName: String, lastName: String) = operation {
repository.register(email.trim(), password, firstName.trim(), lastName.trim())
state.update { it.copy(authMessage = "Registrace je hotová. Ověřte e-mail odkazem ze zprávy a pak se přihlaste.") }
try {
repository.register(email.trim(), password, firstName.trim(), lastName.trim())
} catch (error: ApiException) {
// Main saves an unconfirmed account before sending its verification email.
// A manual retry with the same credentials resends the email instead of duplicating it.
if (error.status == 503) throw ApiException(503, "${error.message}\nZkuste registraci znovu se stejným e-mailem a heslem.")
throw error
}
state.update { it.copy(authMessage = "Registrace je hotová. Ověřte e-mail odkazem ze zprávy a pak se přihlaste.", authOutcome = AuthOutcome.REGISTERED) }
}
fun forgotPassword(email: String) = operation {
repository.forgotPassword(email.trim())
state.update { it.copy(authMessage = "Pokud účet existuje, obdržíte e-mail s odkazem pro obnovu hesla.") }
state.update { it.copy(authMessage = "Požadavek byl přijat. Pokud účet existuje a e-mail se podaří doručit, obdržíte odkaz pro obnovu hesla.") }
}
fun confirmEmail(token: String) = operation {
repository.confirmEmail(extractToken(token))
state.update { it.copy(authMessage = "E-mail je ověřený. Nyní se můžete přihlásit.") }
repository.confirmEmail(extractEmailActionToken(token, EmailAction.CONFIRM))
state.update { it.copy(authMessage = "E-mail je ověřený. Nyní se můžete přihlásit.", authOutcome = AuthOutcome.EMAIL_CONFIRMED) }
}
fun resetPassword(token: String, password: String) = operation {
repository.resetPassword(extractToken(token), password)
state.update { it.copy(authMessage = "Heslo bylo změněno. Přihlaste se novým heslem.") }
repository.resetPassword(extractEmailActionToken(token, EmailAction.RESET), password)
state.update { it.copy(authMessage = "Heslo bylo změněno. Přihlaste se novým heslem.", authOutcome = AuthOutcome.PASSWORD_RESET) }
}
fun clearFeedback() { state.update { it.copy(error = null, message = null, authMessage = null) } }
fun consumeAuthOutcome(outcome: AuthOutcome) {
state.update { if (it.authOutcome == outcome) it.copy(authOutcome = null) else it }
}
fun clearFeedback() { state.update { it.copy(error = null, message = null, authMessage = null, authOutcome = null) } }
fun dismissMessage() { state.update { it.copy(message = null) } }
fun logout(allDevices: Boolean) {
@@ -145,7 +158,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
state.update { it.copy(user = user, message = "Profil byl uložen.") }
}
fun load(route: String) {
fun load(route: String, refreshCatalogs: Boolean = false) {
currentRoute = route
loadJob?.cancel()
val sequence = ++loadSequence
@@ -153,6 +166,15 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
val stamp = generation
state.update { it.copy(loading = true, error = null) }
try {
val form = route == "new-issue" || route == "new-proposal" || route.startsWith("edit-issue/")
val usesCatalogs = form || route in listOf("home", "issues", "proposals") || route.startsWith("issue/") || route.startsWith("proposal/")
if (form || refreshCatalogs && usesCatalogs) {
// Categories can be renamed/deactivated by administrators during a session.
// Reload before forms and explicit refresh, then share the snapshot with mappers.
if (form) state.update { it.copy(catalogs = Catalogs(emptyList(), emptyList(), emptyList())) }
val latest = repository.catalogs(refresh = true)
state.update { it.copy(catalogs = latest) }
}
when {
route == "home" -> loadHome()
route == "issues" -> loadIssues(false)
@@ -187,7 +209,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
}
}
fun retry() = load(currentRoute)
fun retry() = load(currentRoute, refreshCatalogs = true)
private suspend fun loadHome() = coroutineScope {
// Keep usable sections visible when another request temporarily fails.
@@ -373,7 +395,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
state.update { it.copy(loading = false) }
}
viewModelScope.launch {
state.update { it.copy(busy = true, error = null, message = null, authMessage = null) }
state.update { it.copy(busy = true, error = null, message = null, authMessage = null, authOutcome = null) }
try { block() }
catch (e: Exception) { if (e is CancellationException) throw e; failure(e) }
finally { state.update { it.copy(busy = false) } }
@@ -381,13 +403,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
}
}
private fun extractToken(value: String): String {
val trimmed = value.trim()
return if (trimmed.startsWith("https://") || trimmed.startsWith("http://")) {
android.net.Uri.parse(trimmed).getQueryParameter("token") ?: throw IllegalArgumentException("Odkaz neobsahuje ověřovací token.")
} else trimmed
}
private fun <T> Result<T>.getOrThrowCancellation(): Result<T> {
(exceptionOrNull() as? CancellationException)?.let { throw it }
return this
@@ -0,0 +1,42 @@
package cz.ntbug.mobile.ui
import java.net.URI
import java.net.URLDecoder
enum class EmailAction(val path: String) {
CONFIRM("confirm-email"),
RESET("reset-password"),
}
/** WebBaseUrl may differ from the API origin; validate purpose and ambiguity, not its host. */
fun extractEmailActionToken(value: String, action: EmailAction): String {
val trimmed = value.trim()
require(trimmed.isNotEmpty()) { "Vložte token nebo odkaz z e-mailu." }
val uri = try { URI(trimmed) } catch (_: Exception) {
throw IllegalArgumentException("Vložte platný token nebo úplný odkaz z e-mailu.")
}
if (uri.scheme == null) {
require(trimmed.none(Char::isWhitespace)) { "Token nesmí obsahovat mezery ani konce řádků." }
return trimmed
}
require(uri.scheme.lowercase() in setOf("http", "https") && !uri.host.isNullOrBlank() &&
uri.rawUserInfo == null && uri.rawFragment == null) {
"Vložte úplný odkaz HTTP nebo HTTPS z e-mailu."
}
require(uri.path.trimEnd('/').substringAfterLast('/') == action.path) {
if (action == EmailAction.CONFIRM) "Tento odkaz není určený k ověření e-mailu."
else "Tento odkaz není určený k obnově hesla."
}
val tokens = try {
uri.rawQuery.orEmpty().split('&').map { entry ->
val parts = entry.split('=', limit = 2)
URLDecoder.decode(parts[0], "UTF-8") to URLDecoder.decode(parts.getOrElse(1) { "" }, "UTF-8")
}.filter { it.first == "token" }.map { it.second }
} catch (_: Exception) {
throw IllegalArgumentException("Odkaz obsahuje neplatně zapsaný token.")
}
require(tokens.size == 1 && tokens.single().isNotBlank() && tokens.single().none(Char::isWhitespace)) {
"Odkaz musí obsahovat právě jeden neprázdný token."
}
return tokens.single()
}
@@ -107,11 +107,11 @@ private fun SignedInApp(s: AppState, vm: AppViewModel) {
composable("issues") { IssuesScreen(s.issues, s.issueQuery, s.issueStatus, s.assigned, user.role in listOf("FACILITY_MANAGER", "MANAGEMENT"),
{ vm.issueFilters(query = it) }, { vm.issueFilters(status = it) }, { vm.issueFilters(assigned = it) }, { open("issue/$it") }, { open("new-issue") }, { vm.more("issues") }, s.moreIssues) }
composable("new-issue") { NewIssueScreen(s.catalogs, s.busy || s.loading) { request, files -> vm.createIssue(request, files) { created -> nav.navigate("issue/$created") { popUpTo("new-issue") { inclusive = true } } } } }
composable("issue/{id}") { s.issue?.let { issue -> IssueDetailScreen(issue, s.busy, { text, onSaved -> vm.comment(issue.id, text, onSaved) }, { action, reason -> vm.issueAction(issue.id, action, reason) }, { files, onSaved -> vm.attachments(issue.id, files, onSaved) }, { open("edit-issue/${issue.id}") }, { vm.openAttachment(it.id) }) } }
composable("issue/{id}") { s.issue?.let { issue -> IssueDetailScreen(issue, s.busy || s.loading, { text, onSaved -> vm.comment(issue.id, text, onSaved) }, { action, reason -> vm.issueAction(issue.id, action, reason) }, { files, onSaved -> vm.attachments(issue.id, files, onSaved) }, { open("edit-issue/${issue.id}") }, { vm.openAttachment(it.id) }) } }
composable("edit-issue/{id}") { s.issue?.let { issue -> EditIssueScreen(issue, s.catalogs, s.busy || s.loading) { request -> vm.updateIssue(issue.id, request) { nav.popBackStack() } } } }
composable("proposals") { ProposalsScreen(s.proposals, user.id, s.proposalQuery, s.proposalSort, { vm.proposalFilters(query = it) }, { vm.proposalFilters(sort = it) }, { open("proposal/$it") }, vm::vote, { open("new-proposal") }, { vm.more("proposals") }, s.moreProposals) }
composable("new-proposal") { NewProposalScreen(s.catalogs, s.busy || s.loading) { request -> vm.createProposal(request) { created -> nav.navigate("proposal/$created") { popUpTo("new-proposal") { inclusive = true } } } } }
composable("proposal/{id}") { s.proposal?.let { proposal -> ProposalDetailScreen(proposal, user.id, s.busy) { vm.vote(proposal.id, it) } } }
composable("proposal/{id}") { s.proposal?.let { proposal -> ProposalDetailScreen(proposal, user.id, s.busy || s.loading) { vm.vote(proposal.id, it) } } }
composable("notices") { NoticesScreen(s.notices, { notice -> vm.readNotice(notice) { when { notice.issueId != null -> nav.navigate("issue/${notice.issueId}"); notice.proposalId != null -> nav.navigate("proposal/${notice.proposalId}") } } }, vm::readAll, { vm.more("notices") }, s.moreNotices, unreadCount = s.unreadCount) }
composable("profile") { ProfileScreen(user, s, vm) }
}
@@ -0,0 +1,34 @@
package cz.ntbug.mobile.ui.features
import cz.ntbug.mobile.data.Building
import cz.ntbug.mobile.data.Catalogs
import cz.ntbug.mobile.data.Category
import cz.ntbug.mobile.data.Issue
/** The server permits keeping an issue's original category even after deactivation. */
internal fun issueCategoryOptions(catalogs: Catalogs, initial: Issue?): List<Category> {
val active = catalogs.issueCategories.filter { it.isActive }
if (initial == null || active.any { it.id == initial.categoryId }) return active
val original = catalogs.issueCategories.firstOrNull { it.id == initial.categoryId }
?: Category(initial.categoryId, initial.categoryName.ifBlank { "Kategorie #${initial.categoryId}" }, isActive = false)
return active + original.copy(isActive = false)
}
/** Missing historical buildings stay selectable only on the issue they already belong to. */
internal fun issueBuildingOptions(catalogs: Catalogs, initial: Issue?): List<Building> {
val active = listOf(Building(-1, "", "Bez vazby na budovu")) + catalogs.buildings.filter { it.isActive }
val originalId = initial?.buildingId ?: return active
if (active.any { it.id == originalId }) return active
val original = catalogs.buildings.firstOrNull { it.id == originalId }
?: Building(originalId, "", initial.buildingName?.takeIf(String::isNotBlank) ?: "Budova #$originalId", isActive = false)
return active + original.copy(isActive = false)
}
internal fun proposalCategoryOptions(catalogs: Catalogs): List<Category> = catalogs.proposalCategories.filter { it.isActive }
internal fun categoryOptionLabel(category: Category): String = category.name + if (category.isActive) "" else " (již není v nabídce)"
internal fun buildingOptionLabel(building: Building): String {
val name = if (building.code.isBlank()) building.name else "${building.code} · ${building.name}"
return name + if (building.isActive) "" else " (již není v nabídce)"
}
@@ -42,10 +42,12 @@ private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubm
val draft: DraftAttachmentsViewModel = viewModel()
val files = draft.files
var readingFiles by remember { mutableStateOf(false) }
val category = catalogs.issueCategories.find { it.id == categoryId }
val buildings = listOf(Building(-1, "", "Bez vazby na budovu", null, true)) + catalogs.buildings.filter { it.isActive }
val categories = issueCategoryOptions(catalogs, initial)
val category = categories.find { it.id == categoryId }
val buildings = issueBuildingOptions(catalogs, initial)
val building = buildings.find { it.id == buildingId }
val valid = title.isNotBlank() && description.isNotBlank() && category != null
val valid = title.isNotBlank() && description.isNotBlank() &&
category?.let { it.isActive || it.id == initial?.categoryId } == true && building != null
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize().imePadding()) {
item {
Text(if (initial == null) "Co je potřeba opravit?" else "Upravit hlášení", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
@@ -53,8 +55,10 @@ private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubm
Text(if (initial == null) "Stačí pár údajů. O průběhu řešení vás budeme informovat." else "Upřesněte údaje, aby se závada vyřešila rychleji.", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
item { OutlinedTextField(value = title, onValueChange = { title = it.take(200) }, modifier = Modifier.fillMaxWidth(), label = { Text("Název závady *") }, placeholder = { Text("Např. Nefunkční projektor") }, singleLine = true, isError = showErrors && title.isBlank(), keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), supportingText = { Text("${title.length}/200") }) }
item { SelectionField(label = "Kategorie *", selected = category, items = catalogs.issueCategories, itemLabel = { it.name }, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
item { SelectionField(label = "Budova", selected = building, items = buildings, itemLabel = { if (it.code.isBlank()) it.name else "${it.code} · ${it.name}" }, onSelect = { buildingId = it.id }, modifier = Modifier.fillMaxWidth()) }
item { SelectionField(label = "Kategorie *", selected = category, items = categories, itemLabel = ::categoryOptionLabel, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
if (!busy && categoryId > 0 && category == null) item { Text("Vybraná kategorie už není v nabídce. Vyberte jinou.", color = MaterialTheme.colorScheme.error) }
item { SelectionField(label = "Budova", selected = building, items = buildings, itemLabel = ::buildingOptionLabel, onSelect = { buildingId = it.id }, modifier = Modifier.fillMaxWidth()) }
if (!busy && buildingId > 0 && building == null) item { Text("Vybraná budova už není v nabídce. Vyberte jinou nebo možnost Bez vazby na budovu.", color = MaterialTheme.colorScheme.error) }
item { OutlinedTextField(value = location, onValueChange = { location = it.take(255) }, modifier = Modifier.fillMaxWidth(), label = { Text("Upřesnění místa") }, placeholder = { Text("Učebna, patro nebo jiné místo") }, singleLine = true, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)) }
item { OutlinedTextField(value = description, onValueChange = { description = it.take(10_000) }, modifier = Modifier.fillMaxWidth(), label = { Text("Co se stalo? *") }, placeholder = { Text("Popište problém a okolnosti, které nám pomohou.") }, minLines = 4, maxLines = 10, isError = showErrors && description.isBlank(), keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)) }
if (initial == null) item {
@@ -64,10 +68,10 @@ private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubm
if (draft.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
draft.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
}
if (catalogs.issueCategories.isEmpty()) item { Text("Kategorie se nepodařilo načíst. Vraťte se zpět a obnovte data.", color = MaterialTheme.colorScheme.error) }
if (showErrors && !valid) item { Text("Vyplňte název, popis a vyberte kategorii závady.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
if (categories.isEmpty()) item { Text("Není dostupná žádná aktivní kategorie závad. Zkuste obnovit data nebo kontaktujte správce.", color = MaterialTheme.colorScheme.error) }
if (showErrors && !valid) item { Text("Vyplňte název, popis a vyberte kategorii i budovu, případně možnost Bez vazby na budovu.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
item {
Button(onClick = { showErrors = true; if (valid) onSubmit(NewIssue(title.trim(), description.trim(), categoryId, buildingId.takeIf { it >= 0 }, location.trim()), files) }, enabled = !busy && !readingFiles && !draft.busy && catalogs.issueCategories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
Button(onClick = { showErrors = true; if (valid) onSubmit(NewIssue(title.trim(), description.trim(), categoryId, buildingId.takeIf { it >= 0 }, location.trim()), files) }, enabled = !busy && !readingFiles && !draft.busy && categories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
if (busy) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Icon(Icons.AutoMirrored.Rounded.Send, null)
Spacer(Modifier.width(8.dp)); Text(if (busy) "Ukládání…" else if (initial == null) "Odeslat hlášení" else "Uložit změny")
}
@@ -127,25 +127,27 @@ fun NewProposalScreen(catalogs: Catalogs, busy: Boolean, onSubmit: (NewProposal)
var description by rememberSaveable { mutableStateOf("") }
var categoryId by rememberSaveable { mutableIntStateOf(-1) }
var showErrors by rememberSaveable { mutableStateOf(false) }
val category = catalogs.proposalCategories.find { it.id == categoryId }
val valid = title.isNotBlank() && description.isNotBlank() && category != null
val categories = proposalCategoryOptions(catalogs)
val category = categories.find { it.id == categoryId }
val valid = title.isNotBlank() && description.isNotBlank() && category?.isActive == true
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize().imePadding()) {
item {
Text("Máte nápad?", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
Spacer(Modifier.height(8.dp))
Text("Popište, co byste chtěli změnit a komu to pomůže. Ostatní mohou návrh podpořit.", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
item { SelectionField(label = "Oblast *", selected = category, items = catalogs.proposalCategories, itemLabel = { it.name }, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
item { SelectionField(label = "Oblast *", selected = category, items = categories, itemLabel = ::categoryOptionLabel, onSelect = { categoryId = it.id }, modifier = Modifier.fillMaxWidth()) }
if (!busy && categoryId > 0 && category == null) item { Text("Vybraná oblast už není v nabídce. Vyberte jinou.", color = MaterialTheme.colorScheme.error) }
item {
OutlinedTextField(value = title, onValueChange = { title = it.take(200) }, modifier = Modifier.fillMaxWidth(), label = { Text("Název návrhu *") }, placeholder = { Text("Např. Více zásuvek ve studovně") }, isError = showErrors && title.isBlank(), singleLine = true, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), supportingText = { Text("${title.length}/200") })
}
item {
OutlinedTextField(value = description, onValueChange = { description = it.take(10_000) }, modifier = Modifier.fillMaxWidth(), label = { Text("Popis a přínos *") }, placeholder = { Text("Co by se mělo změnit a proč?") }, minLines = 5, maxLines = 12, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), isError = showErrors && description.isBlank())
}
if (catalogs.proposalCategories.isEmpty()) item { Text("Oblasti se nepodařilo načíst. Vraťte se zpět a obnovte data.", color = MaterialTheme.colorScheme.error) }
if (categories.isEmpty()) item { Text("Není dostupná žádná aktivní oblast návrhů. Zkuste obnovit data nebo kontaktujte správce.", color = MaterialTheme.colorScheme.error) }
if (showErrors && !valid) item { Text("Vyplňte název, popis a vyberte oblast návrhu.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
item {
Button(onClick = { showErrors = true; if (valid) onSubmit(NewProposal(title.trim(), description.trim(), categoryId)) }, enabled = !busy && catalogs.proposalCategories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
Button(onClick = { showErrors = true; if (valid) onSubmit(NewProposal(title.trim(), description.trim(), categoryId)) }, enabled = !busy && categories.isNotEmpty(), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
if (busy) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Icon(Icons.Rounded.Lightbulb, null)
Spacer(Modifier.width(8.dp)); Text(if (busy) "Odesílání…" else "Odeslat návrh")
}
@@ -0,0 +1,91 @@
package cz.ntbug.mobile.data
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
class MutableCatalogContractTest {
private lateinit var server: MockWebServer
private lateinit var repository: RemoteRepository
@Before fun setup() {
server = MockWebServer().apply { start() }
repository = RemoteRepository(server.url("/").toString(), object : SessionPersistence {
private var session: AuthSession? = AuthSession("access", "2099-01-01T00:00:00Z", "refresh", "2099-02-01T00:00:00Z",
User(1, "[email protected]", "Jana", "Nováková", role = "STUDENT"))
override fun read() = session
override fun write(session: AuthSession) { this.session = session }
override fun clear() { session = null }
})
}
@After fun teardown() { server.shutdown() }
@Test fun `explicit refresh picks up renamed new and deactivated categories without reloading per row`() = runBlocking {
val revision = AtomicInteger()
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
assertEquals("Bearer access", request.getHeader("Authorization"))
// Ordinary catalog access must not request administrator-only inactive rows.
assertNull(request.requestUrl!!.queryParameter("includeInactive"))
return when (request.requestUrl!!.encodedPath) {
"/api/buildings" -> json(buildings(if (revision.get() == 0) "Budova A" else "Hlavní budova"))
"/api/issue-categories" -> json(if (revision.get() == 0)
"""[{"id":1,"name":"Technika","isActive":true},{"id":2,"name":"Stará kategorie","isActive":true}]"""
else """[{"id":1,"name":"Technické vybavení","isActive":true},{"id":5,"name":"Nová kategorie","isActive":true}]""")
"/api/proposal-categories" -> json(if (revision.get() == 0)
"""[{"id":3,"name":"Prostředí","isActive":true}]"""
else """[{"id":4,"name":"Výuka","isActive":true}]""")
else -> MockResponse().setResponseCode(404)
}
}
}
val original = repository.catalogs()
revision.set(1)
assertSame(original, repository.catalogs())
assertEquals(3, server.requestCount)
val updated = repository.catalogs(refresh = true)
assertEquals("Hlavní budova", updated.buildings.single().name)
assertEquals("Technické vybavení", updated.issueCategories.first { it.id == 1 }.name)
assertEquals(setOf(1, 5), updated.issueCategories.map { it.id }.toSet())
assertEquals(listOf(4), updated.proposalCategories.map { it.id })
assertSame(updated, repository.catalogs())
assertEquals(6, server.requestCount)
}
@Test fun `failed refresh does not replace any part of the previously complete catalog`() = runBlocking {
val failing = AtomicBoolean(false)
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse = when (request.requestUrl!!.encodedPath) {
"/api/buildings" -> json(buildings(if (failing.get()) "Nový název" else "Budova A"))
"/api/issue-categories" -> if (failing.get()) MockResponse().setResponseCode(503)
else json("""[{"id":1,"name":"Technika","isActive":true}]""")
"/api/proposal-categories" -> json("""[{"id":3,"name":"Prostředí","isActive":true}]""")
else -> MockResponse().setResponseCode(404)
}
}
val original = repository.catalogs()
failing.set(true)
try {
repository.catalogs(refresh = true)
fail("Expected service failure")
} catch (error: ApiException) { assertEquals(503, error.status) }
val cached = repository.catalogs()
assertSame(original, cached)
assertEquals("Budova A", cached.buildings.single().name)
assertEquals("Technika", cached.issueCategories.single().name)
assertEquals(5, server.requestCount)
}
private fun buildings(name: String) = """[{"id":1,"code":"A","name":"$name","isActive":true}]"""
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
}
@@ -0,0 +1,69 @@
package cz.ntbug.mobile.data
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.util.concurrent.TimeUnit
class RegistrationDeliveryContractTest {
private lateinit var server: MockWebServer
private lateinit var repository: RemoteRepository
private var session: AuthSession? = null
@Before fun setup() {
server = MockWebServer().apply { start() }
repository = RemoteRepository(server.url("/").toString(), object : SessionPersistence {
override fun read() = session
override fun write(session: AuthSession) { this@RegistrationDeliveryContractTest.session = session }
override fun clear() { session = null }
})
}
@After fun teardown() { server.shutdown() }
@Test fun `failed email delivery is shown without retry and same registration can be manually resent`() = runBlocking {
val message = "E-mail se nepodařilo odeslat. Zkuste požadavek později."
server.enqueue(json("""{"status":503,"title":"$message"}""").setResponseCode(503))
try {
register()
fail("Expected email delivery failure")
} catch (error: ApiException) {
assertEquals(503, error.status)
assertEquals(message, error.message)
}
val failed = server.takeRequest()
assertEquals("/api/auth/register", failed.path)
assertEquals("POST", failed.method)
val failedBody = failed.body.readUtf8()
assertNull(server.takeRequest(100, TimeUnit.MILLISECONDS))
assertNull(session)
server.enqueue(json("""{"id":1,"email":"[email protected]","firstName":"Jana","lastName":"Nováková","role":"STUDENT","emailNotificationsEnabled":true}""").setResponseCode(201))
register()
val repeated = server.takeRequest()
assertEquals("/api/auth/register", repeated.path)
assertEquals(failedBody, repeated.body.readUtf8())
assertEquals(2, server.requestCount)
assertNull("Registration must not sign in an unverified account", session)
}
@Test fun `service failure without problem details has a Czech fallback`() = runBlocking {
server.enqueue(MockResponse().setResponseCode(503))
try {
register()
fail("Expected service failure")
} catch (error: ApiException) {
assertEquals(503, error.status)
assertEquals("Služba je dočasně nedostupná. Zkuste požadavek později.", error.message)
}
assertEquals(1, server.requestCount)
assertNull(session)
}
private suspend fun register() = repository.register("[email protected]", "test-password", "Jana", "Nováková")
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
}
@@ -0,0 +1,47 @@
package cz.ntbug.mobile.ui
import org.junit.Assert.*
import org.junit.Test
class EmailActionTokenTest {
@Test fun acceptsRawTokenWithoutChangingItsContents() {
assertEquals("header.payload.signature", extractEmailActionToken(" header.payload.signature ", EmailAction.CONFIRM))
assertEquals("opaque-token_123", extractEmailActionToken("opaque-token_123", EmailAction.RESET))
}
@Test fun acceptsConfiguredWebHostAndPrefixRatherThanRequiringTheApiHost() {
assertEquals("token.value", extractEmailActionToken("HTTPS://portal.univerzita.cz/helpdesk/confirm-email?token=token%2Evalue", EmailAction.CONFIRM))
assertEquals("reset-token", extractEmailActionToken("https://portal.univerzita.cz/reset-password/?source=mail&token=reset-token", EmailAction.RESET))
}
@Test fun rejectsLinkForAnotherActionBeforeSubmittingItsSingleUseToken() {
rejects("https://portal.univerzita.cz/reset-password?token=secret", EmailAction.CONFIRM)
rejects("https://portal.univerzita.cz/confirm-email?token=secret", EmailAction.RESET)
rejects("https://portal.univerzita.cz/other?token=secret")
}
@Test fun rejectsMissingEmptyDuplicateAndWhitespaceTokens() {
listOf(
"https://portal.univerzita.cz/confirm-email",
"https://portal.univerzita.cz/confirm-email?token=",
"https://portal.univerzita.cz/confirm-email?token=one&token=two",
"https://portal.univerzita.cz/confirm-email?token=one&%74oken=two",
"https://portal.univerzita.cz/confirm-email?token=bad%20token",
" ", "header. payload.signature",
).forEach { rejects(it) }
}
@Test fun rejectsNonWebAmbiguousAndMalformedLinks() {
listOf(
"ftp://portal.univerzita.cz/confirm-email?token=secret",
"https://[email protected]/confirm-email?token=secret",
"https://portal.univerzita.cz/confirm-email?token=secret#another-token",
"https://portal.univerzita.cz/confirm-email?token=%XX",
"https:/confirm-email?token=secret",
).forEach { rejects(it) }
}
private fun rejects(value: String, action: EmailAction = EmailAction.CONFIRM) {
assertThrows(IllegalArgumentException::class.java) { extractEmailActionToken(value, action) }
}
}
@@ -0,0 +1,63 @@
package cz.ntbug.mobile.ui.features
import cz.ntbug.mobile.data.Building
import cz.ntbug.mobile.data.Catalogs
import cz.ntbug.mobile.data.Category
import cz.ntbug.mobile.data.Issue
import org.junit.Assert.*
import org.junit.Test
class CatalogSelectionTest {
private val issue = Issue(7, "Závada", "Popis", "RECEIVED", 9, "Původní kategorie",
buildingId = 20, buildingName = "Původní budova", reporterId = 1, reporterName = "Jana Nováková", createdAt = "2026-11-19T10:00:00Z")
private val catalogs = Catalogs(
buildings = listOf(Building(20, "A", "Přejmenovaná budova", isActive = false), Building(21, "B", "Aktivní budova"), Building(22, "C", "Jiná neaktivní budova", isActive = false)),
issueCategories = listOf(Category(1, "Aktivní kategorie"), Category(9, "Přejmenovaná kategorie", isActive = false), Category(10, "Jiná neaktivní kategorie", isActive = false)),
proposalCategories = listOf(Category(2, "Aktivní oblast"), Category(3, "Neaktivní oblast", isActive = false)),
)
@Test fun `new reports and proposals can select only active catalog entries`() {
assertEquals(listOf(1), issueCategoryOptions(catalogs, null).map { it.id })
assertEquals(listOf(-1, 21), issueBuildingOptions(catalogs, null).map { it.id })
assertEquals(listOf(2), proposalCategoryOptions(catalogs).map { it.id })
}
@Test fun `edit retains only its own inactive references and their current catalog names`() {
val categories = issueCategoryOptions(catalogs, issue)
assertEquals(listOf(1, 9), categories.map { it.id })
assertEquals("Přejmenovaná kategorie (již není v nabídce)", categoryOptionLabel(categories.last()))
val buildings = issueBuildingOptions(catalogs, issue)
assertEquals(listOf(-1, 21, 20), buildings.map { it.id })
assertEquals("A · Přejmenovaná budova (již není v nabídce)", buildingOptionLabel(buildings.last()))
}
@Test fun `edit preserves IDs and names when historical references are absent from the response`() {
val empty = Catalogs(emptyList(), emptyList(), emptyList())
val category = issueCategoryOptions(empty, issue).single()
assertEquals(9, category.id)
assertEquals("Původní kategorie", category.name)
assertFalse(category.isActive)
val building = issueBuildingOptions(empty, issue).last()
assertEquals(20, building.id)
assertEquals("Původní budova", building.name)
assertFalse(building.isActive)
}
@Test fun `active original references use fresh catalog names without duplicate choices`() {
val fresh = catalogs.copy(
issueCategories = listOf(Category(9, "Aktuální název")),
buildings = listOf(Building(20, "A", "Aktuální budova")),
)
assertEquals("Aktuální název", categoryOptionLabel(issueCategoryOptions(fresh, issue).single()))
assertEquals(listOf(-1, 20), issueBuildingOptions(fresh, issue).map { it.id })
assertEquals("A · Aktuální budova", buildingOptionLabel(issueBuildingOptions(fresh, issue).last()))
}
@Test fun `missing historical names use readable IDs and no original building stays optional`() {
val empty = Catalogs(emptyList(), emptyList(), emptyList())
val unnamed = issue.copy(categoryName = "", buildingName = null)
assertEquals("Kategorie #9 (již není v nabídce)", categoryOptionLabel(issueCategoryOptions(empty, unnamed).single()))
assertEquals("Budova #20 (již není v nabídce)", buildingOptionLabel(issueBuildingOptions(empty, unnamed).last()))
assertEquals(listOf(-1), issueBuildingOptions(empty, unnamed.copy(buildingId = null)).map { it.id })
}
}