refactor: Migrate from monolithic to modular architecture

- Restructure project into domain-specific modules (core, masterdata, members, horses, events, infrastructure)
- Create shared client components in common-ui module
- Implement CI/CD workflows with GitHub Actions
- Consolidate documentation in docs directory
- Remove deprecated modules and documentation files
- Add cleanup and migration scripts for transition
- Update README with new project structure and setup instructions
This commit is contained in:
stefan
2025-07-22 18:44:18 +02:00
parent 8229e8e571
commit a256622f37
314 changed files with 5930 additions and 19817 deletions
@@ -0,0 +1,37 @@
package at.mocode.client.web
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import at.mocode.client.common.BaseApp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun App() {
BaseApp {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Meldestelle - Reitersport Management") }
)
}
) { paddingValues ->
Column(
modifier = Modifier.padding(paddingValues).fillMaxSize(),
verticalArrangement = Arrangement.Center
) {
// Placeholder content
Text("Welcome to Meldestelle - Reitersport Management")
Text("This is a desktop application for managing equestrian events")
}
}
}
}
@@ -0,0 +1,35 @@
package at.mocode.client.web.di
import at.mocode.client.common.api.ApiClient
import at.mocode.client.common.repository.ClientEventRepository
import at.mocode.client.common.repository.ClientPersonRepository
import at.mocode.client.common.repository.EventRepository
import at.mocode.client.common.repository.PersonRepository
import at.mocode.client.web.viewmodel.CreatePersonViewModel
import at.mocode.client.web.viewmodel.PersonListViewModel
/**
* Simple dependency injection container for the application.
* In a real application, you might want to use a proper DI framework like Koin.
*/
object AppDependencies {
// Repository instances
private val personRepository: PersonRepository by lazy { ClientPersonRepository() }
private val eventRepository: EventRepository by lazy { ClientEventRepository() }
// ViewModel factory methods
fun createPersonViewModel(): CreatePersonViewModel {
return CreatePersonViewModel(personRepository)
}
fun personListViewModel(): PersonListViewModel {
return PersonListViewModel(personRepository)
}
// Helper method to initialize dependencies
fun initialize() {
// Initialize ApiClient if needed
println("AppDependencies initialized")
}
}
@@ -0,0 +1,148 @@
package at.mocode.client.web.di
import at.mocode.members.application.usecase.CreatePersonUseCase
import at.mocode.members.domain.repository.PersonRepository
import at.mocode.members.domain.repository.VereinRepository
import at.mocode.members.domain.service.MasterDataService
import at.mocode.client.web.viewmodel.CreatePersonViewModel
import at.mocode.client.web.viewmodel.PersonListViewModel
/**
* Simple dependency injection container for the application.
* In a real application, you might want to use a proper DI framework like Koin.
*/
object AppDependencies {
// Mock implementations for demonstration
// In a real application, these would be proper implementations
private val mockPersonRepository = object : PersonRepository {
override suspend fun save(person: at.mocode.members.domain.model.DomPerson): at.mocode.members.domain.model.DomPerson {
// Mock implementation - just return the person with an ID
return person.copy(personId = com.benasher44.uuid.uuid4())
}
override suspend fun findById(id: com.benasher44.uuid.Uuid): at.mocode.members.domain.model.DomPerson? {
return null // Mock implementation
}
override suspend fun findByOepsSatzNr(oepsSatzNr: String): at.mocode.members.domain.model.DomPerson? {
return null // Mock implementation
}
override suspend fun findByStammVereinId(vereinId: com.benasher44.uuid.Uuid): List<at.mocode.members.domain.model.DomPerson> {
return emptyList() // Mock implementation
}
override suspend fun findByName(searchTerm: String, limit: Int): List<at.mocode.members.domain.model.DomPerson> {
return emptyList() // Mock implementation
}
override suspend fun findAllActive(limit: Int, offset: Int): List<at.mocode.members.domain.model.DomPerson> {
return emptyList() // Mock implementation
}
override suspend fun countActive(): Long {
return 0L // Mock implementation
}
override suspend fun existsByOepsSatzNr(oepsSatzNr: String): Boolean {
return false // Mock implementation - no duplicates for demo
}
override suspend fun delete(id: com.benasher44.uuid.Uuid): Boolean {
return true // Mock implementation
}
}
private val mockVereinRepository = object : VereinRepository {
override suspend fun findById(id: com.benasher44.uuid.Uuid): at.mocode.members.domain.model.DomVerein? {
return null // Mock implementation
}
override suspend fun findByOepsVereinsNr(oepsVereinsNr: String): at.mocode.members.domain.model.DomVerein? {
return null // Mock implementation
}
override suspend fun findByName(searchTerm: String, limit: Int): List<at.mocode.members.domain.model.DomVerein> {
return emptyList() // Mock implementation
}
override suspend fun findByBundeslandId(bundeslandId: com.benasher44.uuid.Uuid): List<at.mocode.members.domain.model.DomVerein> {
return emptyList() // Mock implementation
}
override suspend fun findByLandId(landId: com.benasher44.uuid.Uuid): List<at.mocode.members.domain.model.DomVerein> {
return emptyList() // Mock implementation
}
override suspend fun findAllActive(limit: Int, offset: Int): List<at.mocode.members.domain.model.DomVerein> {
return emptyList() // Mock implementation
}
override suspend fun findByLocation(searchTerm: String, limit: Int): List<at.mocode.members.domain.model.DomVerein> {
return emptyList() // Mock implementation
}
override suspend fun save(verein: at.mocode.members.domain.model.DomVerein): at.mocode.members.domain.model.DomVerein {
return verein.copy(vereinId = com.benasher44.uuid.uuid4()) // Mock implementation
}
override suspend fun delete(id: com.benasher44.uuid.Uuid): Boolean {
return true // Mock implementation
}
override suspend fun existsByOepsVereinsNr(oepsVereinsNr: String): Boolean {
return false // Mock implementation
}
override suspend fun countActive(): Long {
return 0L // Mock implementation
}
override suspend fun countActiveByBundeslandId(bundeslandId: com.benasher44.uuid.Uuid): Long {
return 0L // Mock implementation
}
}
private val mockMasterDataService = object : MasterDataService {
override suspend fun countryExists(countryId: com.benasher44.uuid.Uuid): Boolean {
return true // Mock implementation - assume all countries exist
}
override suspend fun stateExists(stateId: com.benasher44.uuid.Uuid): Boolean {
return true // Mock implementation - assume all states exist
}
override suspend fun getCountryById(countryId: com.benasher44.uuid.Uuid): MasterDataService.CountryInfo? {
return null // Mock implementation
}
override suspend fun getStateById(stateId: com.benasher44.uuid.Uuid): MasterDataService.StateInfo? {
return null // Mock implementation
}
override suspend fun getAllCountries(): List<MasterDataService.CountryInfo> {
return emptyList() // Mock implementation
}
override suspend fun getStatesByCountry(countryId: com.benasher44.uuid.Uuid): List<MasterDataService.StateInfo> {
return emptyList() // Mock implementation
}
}
// Use case instances
private val createPersonUseCase = CreatePersonUseCase(
personRepository = mockPersonRepository,
vereinRepository = mockVereinRepository,
masterDataService = mockMasterDataService
)
// ViewModel factory methods
fun createPersonViewModel(): CreatePersonViewModel {
return CreatePersonViewModel(createPersonUseCase)
}
fun personListViewModel(): PersonListViewModel {
return PersonListViewModel(mockPersonRepository)
}
}
@@ -0,0 +1,14 @@
package at.mocode.client.web
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
fun main() = application {
Window(
title = "Meldestelle - Reitersport Management",
onCloseRequest = ::exitApplication
) {
App()
}
}
@@ -0,0 +1,275 @@
package at.mocode.client.web.screens
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import at.mocode.client.web.viewmodel.CreatePersonViewModel
/**
* Screen for creating a new person.
* This is a simplified version that uses the simplified CreatePersonViewModel.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreatePersonScreen(
viewModel: CreatePersonViewModel,
onNavigateBack: () -> Unit
) {
// Handle success navigation
LaunchedEffect(viewModel.isSuccess) {
if (viewModel.isSuccess) {
onNavigateBack()
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("Person erstellen") },
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Zurück")
}
}
)
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Error message
viewModel.errorMessage?.let { error ->
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer
)
) {
Text(
text = error,
modifier = Modifier.padding(16.dp),
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
// Basic Information Section
Text(
text = "Grunddaten",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.nachname,
onValueChange = viewModel::updateNachname,
label = { Text("Nachname *") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
OutlinedTextField(
value = viewModel.vorname,
onValueChange = viewModel::updateVorname,
label = { Text("Vorname *") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
OutlinedTextField(
value = viewModel.titel,
onValueChange = viewModel::updateTitel,
label = { Text("Titel") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
placeholder = { Text("z.B. Dr., Ing.") }
)
OutlinedTextField(
value = viewModel.oepsSatzNr,
onValueChange = viewModel::updateOepsSatzNr,
label = { Text("OEPS Satznummer") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
placeholder = { Text("6-stellige Nummer") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
OutlinedTextField(
value = viewModel.geburtsdatum,
onValueChange = viewModel::updateGeburtsdatum,
label = { Text("Geburtsdatum") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
placeholder = { Text("YYYY-MM-DD") }
)
// Contact Information Section
Text(
text = "Kontaktdaten",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.telefon,
onValueChange = viewModel::updateTelefon,
label = { Text("Telefon") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone)
)
OutlinedTextField(
value = viewModel.email,
onValueChange = viewModel::updateEmail,
label = { Text("E-Mail") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)
)
// Address Section
Text(
text = "Adresse",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.strasse,
onValueChange = viewModel::updateStrasse,
label = { Text("Straße und Hausnummer") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = viewModel.plz,
onValueChange = viewModel::updatePlz,
label = { Text("PLZ") },
modifier = Modifier.weight(1f),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
OutlinedTextField(
value = viewModel.ort,
onValueChange = viewModel::updateOrt,
label = { Text("Ort") },
modifier = Modifier.weight(2f),
singleLine = true
)
}
OutlinedTextField(
value = viewModel.adresszusatz,
onValueChange = viewModel::updateAdresszusatz,
label = { Text("Adresszusatz") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
// Additional Information Section
Text(
text = "Weitere Informationen",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.feiId,
onValueChange = viewModel::updateFeiId,
label = { Text("FEI ID") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
OutlinedTextField(
value = viewModel.mitgliedsNummer,
onValueChange = viewModel::updateMitgliedsNummer,
label = { Text("Mitgliedsnummer beim Stammverein") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = viewModel.istGesperrt,
onCheckedChange = viewModel::updateIstGesperrt
)
Spacer(modifier = Modifier.width(8.dp))
Text("Person ist gesperrt")
}
if (viewModel.istGesperrt) {
OutlinedTextField(
value = viewModel.sperrGrund,
onValueChange = viewModel::updateSperrGrund,
label = { Text("Sperrgrund") },
modifier = Modifier.fillMaxWidth(),
maxLines = 3
)
}
OutlinedTextField(
value = viewModel.notizen,
onValueChange = viewModel::updateNotizen,
label = { Text("Interne Notizen") },
modifier = Modifier.fillMaxWidth(),
maxLines = 4
)
// Action Buttons
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedButton(
onClick = onNavigateBack,
modifier = Modifier.weight(1f),
enabled = !viewModel.isLoading
) {
Text("Abbrechen")
}
Button(
onClick = {
viewModel.createPerson()
},
modifier = Modifier.weight(1f),
enabled = !viewModel.isLoading
) {
if (viewModel.isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
strokeWidth = 2.dp
)
} else {
Text("Erstellen")
}
}
}
}
}
}
@@ -0,0 +1,166 @@
package at.mocode.client.web.screens
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import at.mocode.client.web.viewmodel.PersonListViewModel
import at.mocode.client.web.viewmodel.PersonUiModel
/**
* Screen for displaying a list of persons.
* This is a simplified version that uses the simplified PersonListViewModel.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PersonListScreen(
viewModel: PersonListViewModel,
onNavigateToCreatePerson: () -> Unit
) {
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = onNavigateToCreatePerson
) {
Icon(Icons.Default.Add, contentDescription = "Person hinzufügen")
}
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp)
) {
Text(
text = "Personen",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(bottom = 16.dp)
)
// Error handling
viewModel.errorMessage?.let { error ->
Card(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer
)
) {
Row(
modifier = Modifier.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = error,
color = MaterialTheme.colorScheme.onErrorContainer,
modifier = Modifier.weight(1f)
)
TextButton(
onClick = { viewModel.clearError() }
) {
Text("OK")
}
}
}
}
// Loading indicator
if (viewModel.isLoading) {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
if (!viewModel.isLoading && viewModel.persons.isEmpty()) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
Icons.Default.Person,
contentDescription = null,
modifier = Modifier.size(64.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Keine Personen vorhanden",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
} else {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(viewModel.persons) { person ->
PersonCard(person = person)
}
}
}
}
}
}
@Composable
private fun PersonCard(person: PersonUiModel) {
Card(
modifier = Modifier.fillMaxWidth(),
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(
text = person.name,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
person.email?.let { email ->
Text(
text = "📧 $email",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
person.phone?.let { phone ->
Text(
text = "📞 $phone",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
person.address?.let { address ->
Text(
text = "📍 $address",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
@@ -0,0 +1,319 @@
package at.mocode.client.web.screens
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import at.mocode.core.domain.model.GeschlechtE
import at.mocode.client.web.viewmodel.CreatePersonViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreatePersonScreen(
viewModel: CreatePersonViewModel,
onNavigateBack: () -> Unit
) {
var showGeschlechtDropdown by remember { mutableStateOf(false) }
// Handle success navigation
LaunchedEffect(viewModel.isSuccess) {
if (viewModel.isSuccess) {
onNavigateBack()
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("Person erstellen") },
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Zurück")
}
}
)
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Error message
viewModel.errorMessage?.let { error ->
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer
)
) {
Text(
text = error,
modifier = Modifier.padding(16.dp),
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
// Basic Information Section
Text(
text = "Grunddaten",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.nachname,
onValueChange = viewModel::updateNachname,
label = { Text("Nachname *") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
OutlinedTextField(
value = viewModel.vorname,
onValueChange = viewModel::updateVorname,
label = { Text("Vorname *") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
OutlinedTextField(
value = viewModel.titel,
onValueChange = viewModel::updateTitel,
label = { Text("Titel") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
placeholder = { Text("z.B. Dr., Ing.") }
)
OutlinedTextField(
value = viewModel.oepsSatzNr,
onValueChange = viewModel::updateOepsSatzNr,
label = { Text("OEPS Satznummer") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
placeholder = { Text("6-stellige Nummer") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
OutlinedTextField(
value = viewModel.geburtsdatum,
onValueChange = viewModel::updateGeburtsdatum,
label = { Text("Geburtsdatum") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
placeholder = { Text("YYYY-MM-DD") }
)
// Gender Dropdown
ExposedDropdownMenuBox(
expanded = showGeschlechtDropdown,
onExpandedChange = { showGeschlechtDropdown = !showGeschlechtDropdown }
) {
OutlinedTextField(
value = viewModel.geschlecht?.let {
when(it) {
GeschlechtE.M -> "Männlich"
GeschlechtE.W -> "Weiblich"
GeschlechtE.D -> "Divers"
GeschlechtE.UNBEKANNT -> "Unbekannt"
}
} ?: "",
onValueChange = { },
readOnly = true,
label = { Text("Geschlecht") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = showGeschlechtDropdown) },
modifier = Modifier
.fillMaxWidth()
)
ExposedDropdownMenu(
expanded = showGeschlechtDropdown,
onDismissRequest = { showGeschlechtDropdown = false }
) {
GeschlechtE.entries.forEach { option ->
DropdownMenuItem(
text = {
Text(when(option) {
GeschlechtE.M -> "Männlich"
GeschlechtE.W -> "Weiblich"
GeschlechtE.D -> "Divers"
GeschlechtE.UNBEKANNT -> "Unbekannt"
})
},
onClick = {
viewModel.updateGeschlecht(option)
showGeschlechtDropdown = false
}
)
}
}
}
// Contact Information Section
Text(
text = "Kontaktdaten",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.telefon,
onValueChange = viewModel::updateTelefon,
label = { Text("Telefon") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone)
)
OutlinedTextField(
value = viewModel.email,
onValueChange = viewModel::updateEmail,
label = { Text("E-Mail") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)
)
// Address Section
Text(
text = "Adresse",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.strasse,
onValueChange = viewModel::updateStrasse,
label = { Text("Straße und Hausnummer") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = viewModel.plz,
onValueChange = viewModel::updatePlz,
label = { Text("PLZ") },
modifier = Modifier.weight(1f),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
OutlinedTextField(
value = viewModel.ort,
onValueChange = viewModel::updateOrt,
label = { Text("Ort") },
modifier = Modifier.weight(2f),
singleLine = true
)
}
OutlinedTextField(
value = viewModel.adresszusatz,
onValueChange = viewModel::updateAdresszusatz,
label = { Text("Adresszusatz") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
// Additional Information Section
Text(
text = "Weitere Informationen",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = viewModel.feiId,
onValueChange = viewModel::updateFeiId,
label = { Text("FEI ID") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
OutlinedTextField(
value = viewModel.mitgliedsNummer,
onValueChange = viewModel::updateMitgliedsNummer,
label = { Text("Mitgliedsnummer beim Stammverein") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = viewModel.istGesperrt,
onCheckedChange = viewModel::updateIstGesperrt
)
Spacer(modifier = Modifier.width(8.dp))
Text("Person ist gesperrt")
}
if (viewModel.istGesperrt) {
OutlinedTextField(
value = viewModel.sperrGrund,
onValueChange = viewModel::updateSperrGrund,
label = { Text("Sperrgrund") },
modifier = Modifier.fillMaxWidth(),
maxLines = 3
)
}
OutlinedTextField(
value = viewModel.notizen,
onValueChange = viewModel::updateNotizen,
label = { Text("Interne Notizen") },
modifier = Modifier.fillMaxWidth(),
maxLines = 4
)
// Action Buttons
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedButton(
onClick = onNavigateBack,
modifier = Modifier.weight(1f),
enabled = !viewModel.isLoading
) {
Text("Abbrechen")
}
Button(
onClick = {
viewModel.createPerson()
},
modifier = Modifier.weight(1f),
enabled = !viewModel.isLoading
) {
if (viewModel.isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
strokeWidth = 2.dp
)
} else {
Text("Erstellen")
}
}
}
}
}
}
@@ -0,0 +1,212 @@
package at.mocode.client.web.screens
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import at.mocode.members.domain.model.DomPerson
import at.mocode.core.domain.model.GeschlechtE
import at.mocode.core.domain.model.DatenQuelleE
import at.mocode.client.web.viewmodel.PersonListViewModel
import kotlinx.datetime.LocalDate
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PersonListScreen(
viewModel: PersonListViewModel,
onNavigateToCreatePerson: () -> Unit
) {
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = onNavigateToCreatePerson
) {
Icon(Icons.Default.Add, contentDescription = "Person hinzufügen")
}
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp)
) {
Text(
text = "Personen",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(bottom = 16.dp)
)
// Error handling
viewModel.errorMessage?.let { error ->
Card(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer
)
) {
Row(
modifier = Modifier.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = error,
color = MaterialTheme.colorScheme.onErrorContainer,
modifier = Modifier.weight(1f)
)
TextButton(
onClick = { viewModel.clearError() }
) {
Text("OK")
}
}
}
}
// Loading indicator
if (viewModel.isLoading) {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
if (!viewModel.isLoading && viewModel.persons.isEmpty()) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
Icons.Default.Person,
contentDescription = null,
modifier = Modifier.size(64.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Keine Personen vorhanden",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
} else {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(viewModel.persons) { person ->
PersonCard(person = person)
}
}
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun PersonCard(person: DomPerson) {
Card(
modifier = Modifier.fillMaxWidth(),
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.Top
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "${person.titel?.let { "$it " } ?: ""}${person.vorname} ${person.nachname}",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
person.oepsSatzNr?.let { oepsNr ->
Text(
text = "OEPS: $oepsNr",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary
)
}
person.geburtsdatum?.let { birthDate ->
Text(
text = "Geboren: $birthDate",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Surface(
color = when (person.datenQuelle) {
DatenQuelleE.OEPS_ZNS -> MaterialTheme.colorScheme.primaryContainer
DatenQuelleE.MANUELL -> MaterialTheme.colorScheme.secondaryContainer
},
shape = MaterialTheme.shapes.small
) {
Text(
text = when (person.datenQuelle) {
DatenQuelleE.OEPS_ZNS -> "OEPS"
DatenQuelleE.MANUELL -> "Manuell"
},
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
style = MaterialTheme.typography.labelSmall,
color = when (person.datenQuelle) {
DatenQuelleE.OEPS_ZNS -> MaterialTheme.colorScheme.onPrimaryContainer
DatenQuelleE.MANUELL -> MaterialTheme.colorScheme.onSecondaryContainer
}
)
}
}
Spacer(modifier = Modifier.height(8.dp))
person.email?.let { email ->
Text(
text = "📧 $email",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
person.telefon?.let { phone ->
Text(
text = "📞 $phone",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (person.strasse != null && person.plz != null && person.ort != null) {
Text(
text = "📍 ${person.strasse}, ${person.plz} ${person.ort}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
@@ -0,0 +1,181 @@
package at.mocode.client.web.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import at.mocode.client.common.repository.Person
import at.mocode.client.common.repository.PersonRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.datetime.LocalDate
/**
* ViewModel for creating a person.
* This is a simplified version that doesn't depend on androidx.lifecycle.
* It uses Compose for Desktop's own state management.
*/
class CreatePersonViewModel(
private val personRepository: PersonRepository
) {
// Coroutine scope for launching background tasks
private val coroutineScope = CoroutineScope(Dispatchers.Default)
// Form state
var nachname by mutableStateOf("")
private set
var vorname by mutableStateOf("")
private set
var titel by mutableStateOf("")
private set
var oepsSatzNr by mutableStateOf("")
private set
var geburtsdatum by mutableStateOf("")
private set
var telefon by mutableStateOf("")
private set
var email by mutableStateOf("")
private set
var strasse by mutableStateOf("")
private set
var plz by mutableStateOf("")
private set
var ort by mutableStateOf("")
private set
var adresszusatz by mutableStateOf("")
private set
var feiId by mutableStateOf("")
private set
var mitgliedsNummer by mutableStateOf("")
private set
var notizen by mutableStateOf("")
private set
var istGesperrt by mutableStateOf(false)
private set
var sperrGrund by mutableStateOf("")
private set
// UI state
var isLoading by mutableStateOf(false)
private set
var errorMessage by mutableStateOf<String?>(null)
private set
var isSuccess by mutableStateOf(false)
private set
// Update methods
fun updateNachname(value: String) { nachname = value }
fun updateVorname(value: String) { vorname = value }
fun updateTitel(value: String) { titel = value }
fun updateOepsSatzNr(value: String) { oepsSatzNr = value }
fun updateGeburtsdatum(value: String) { geburtsdatum = value }
fun updateTelefon(value: String) { telefon = value }
fun updateEmail(value: String) { email = value }
fun updateStrasse(value: String) { strasse = value }
fun updatePlz(value: String) { plz = value }
fun updateOrt(value: String) { ort = value }
fun updateAdresszusatz(value: String) { adresszusatz = value }
fun updateFeiId(value: String) { feiId = value }
fun updateMitgliedsNummer(value: String) { mitgliedsNummer = value }
fun updateNotizen(value: String) { notizen = value }
fun updateIstGesperrt(value: Boolean) { istGesperrt = value }
fun updateSperrGrund(value: String) { sperrGrund = value }
fun clearError() {
errorMessage = null
}
fun createPerson() {
// Basic validation
when {
nachname.isBlank() -> {
errorMessage = "Nachname ist erforderlich"
return
}
vorname.isBlank() -> {
errorMessage = "Vorname ist erforderlich"
return
}
}
coroutineScope.launch {
isLoading = true
errorMessage = null
try {
// Parse birthdate if provided
val parsedGeburtsdatum = if (geburtsdatum.isNotBlank()) {
try {
val parts = geburtsdatum.split("-")
if (parts.size == 3) {
LocalDate(parts[0].toInt(), parts[1].toInt(), parts[2].toInt())
} else {
errorMessage = "Ungültiges Datumsformat. Verwenden Sie YYYY-MM-DD"
isLoading = false
isSuccess = false
return@launch
}
} catch (_: Exception) {
errorMessage = "Ungültiges Datumsformat. Verwenden Sie YYYY-MM-DD"
isLoading = false
isSuccess = false
return@launch
}
} else null
// Create a Person object from form data
val person = Person(
nachname = nachname,
vorname = vorname,
titel = titel.takeIf { it.isNotBlank() },
oepsSatzNr = oepsSatzNr.takeIf { it.isNotBlank() },
geburtsdatum = parsedGeburtsdatum,
telefon = telefon.takeIf { it.isNotBlank() },
email = email.takeIf { it.isNotBlank() },
strasse = strasse.takeIf { it.isNotBlank() },
plz = plz.takeIf { it.isNotBlank() },
ort = ort.takeIf { it.isNotBlank() },
adresszusatz = adresszusatz.takeIf { it.isNotBlank() },
feiId = feiId.takeIf { it.isNotBlank() },
mitgliedsNummer = mitgliedsNummer.takeIf { it.isNotBlank() },
notizen = notizen.takeIf { it.isNotBlank() },
istGesperrt = istGesperrt,
sperrGrund = sperrGrund.takeIf { it.isNotBlank() },
datenQuelle = "MANUELL"
)
// Save the person using the repository
personRepository.save(person)
// Set success state
isSuccess = true
} catch (e: Exception) {
errorMessage = "Fehler beim Erstellen der Person: ${e.message}"
} finally {
isLoading = false
}
}
}
fun resetForm() {
nachname = ""
vorname = ""
titel = ""
oepsSatzNr = ""
geburtsdatum = ""
telefon = ""
email = ""
strasse = ""
plz = ""
ort = ""
adresszusatz = ""
feiId = ""
mitgliedsNummer = ""
notizen = ""
istGesperrt = false
sperrGrund = ""
isLoading = false
errorMessage = null
isSuccess = false
}
}
@@ -0,0 +1,86 @@
package at.mocode.client.web.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import at.mocode.client.common.repository.Person
import at.mocode.client.common.repository.PersonRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* ViewModel for displaying a list of persons.
* This is a simplified version that doesn't depend on androidx.lifecycle.
* It uses Compose for Desktop's own state management.
*/
class PersonListViewModel(
private val personRepository: PersonRepository
) {
// Coroutine scope for launching background tasks
private val coroutineScope = CoroutineScope(Dispatchers.Default)
// UI state
var persons by mutableStateOf<List<PersonUiModel>>(emptyList())
private set
var isLoading by mutableStateOf(false)
private set
var errorMessage by mutableStateOf<String?>(null)
private set
init {
loadPersons()
}
fun loadPersons() {
coroutineScope.launch {
isLoading = true
errorMessage = null
try {
// Load persons from the repository
val personList = personRepository.findAllActive(limit = 100, offset = 0)
// Map domain models to UI models
persons = personList.map { it.toUiModel() }
} catch (e: Exception) {
errorMessage = "Fehler beim Laden der Personen: ${e.message}"
} finally {
isLoading = false
}
}
}
fun clearError() {
errorMessage = null
}
fun refreshPersons() {
loadPersons()
}
/**
* Maps a domain Person to a UI PersonUiModel
*/
private fun Person.toUiModel(): PersonUiModel {
return PersonUiModel(
id = this.id,
name = this.getFullName(),
email = this.email,
phone = this.telefon,
address = this.getFormattedAddress()
)
}
}
/**
* UI model for a person.
* This is a simplified version that doesn't depend on domain models.
*/
data class PersonUiModel(
val id: String,
val name: String,
val email: String? = null,
val phone: String? = null,
val address: String? = null
)
@@ -0,0 +1,432 @@
package at.mocode.client.web.viewmodel
import at.mocode.core.domain.model.GeschlechtE
import at.mocode.members.application.usecase.CreatePersonUseCase
import at.mocode.members.domain.model.DomPerson
import at.mocode.members.domain.repository.PersonRepository
import at.mocode.members.domain.repository.VereinRepository
import at.mocode.members.domain.service.MasterDataService
import com.benasher44.uuid.uuid4
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import kotlin.test.*
/**
* Comprehensive test suite for the CreatePersonViewModel.
*
* Tests cover:
* - Initial state verification
* - Field update operations
* - Form validation
* - Person creation with various inputs
* - Form reset functionality
* - Error handling
*/
@OptIn(ExperimentalCoroutinesApi::class)
class CreatePersonViewModelTest {
private lateinit var mockPersonRepository: PersonRepository
private lateinit var mockVereinRepository: VereinRepository
private lateinit var mockMasterDataService: MasterDataService
private lateinit var createPersonUseCase: CreatePersonUseCase
private lateinit var viewModel: CreatePersonViewModel
private val testDispatcher = StandardTestDispatcher()
@BeforeTest
fun setup() {
Dispatchers.setMain(testDispatcher)
// Initialize mock repositories and services
setupMockRepositories()
// Create the use case with mocks
createPersonUseCase = CreatePersonUseCase(
personRepository = mockPersonRepository,
vereinRepository = mockVereinRepository,
masterDataService = mockMasterDataService
)
// Initialize the view model
viewModel = CreatePersonViewModel(createPersonUseCase)
}
/**
* Sets up all mock repositories and services needed for testing
*/
private fun setupMockRepositories() {
// Mock person repository with in-memory storage
mockPersonRepository = object : PersonRepository {
private val persons = mutableListOf<DomPerson>()
override suspend fun save(person: DomPerson): DomPerson {
val savedPerson = person.copy(personId = uuid4())
persons.add(savedPerson)
return savedPerson
}
override suspend fun findById(id: com.benasher44.uuid.Uuid): DomPerson? {
return persons.find { it.personId == id }
}
override suspend fun findByOepsSatzNr(oepsSatzNr: String): DomPerson? {
return persons.find { it.oepsSatzNr == oepsSatzNr }
}
override suspend fun findByStammVereinId(vereinId: com.benasher44.uuid.Uuid): List<DomPerson> {
return persons.filter { it.stammVereinId == vereinId }
}
override suspend fun findByName(searchTerm: String, limit: Int): List<DomPerson> {
return persons.filter {
it.vorname.contains(searchTerm, ignoreCase = true) ||
it.nachname.contains(searchTerm, ignoreCase = true)
}.take(limit)
}
override suspend fun findAllActive(limit: Int, offset: Int): List<DomPerson> {
return persons.filter { !it.istGesperrt }.drop(offset).take(limit)
}
override suspend fun existsByOepsSatzNr(oepsSatzNr: String): Boolean {
return persons.any { it.oepsSatzNr == oepsSatzNr }
}
override suspend fun countActive(): Long {
return persons.count { !it.istGesperrt }.toLong()
}
override suspend fun delete(id: com.benasher44.uuid.Uuid): Boolean {
return persons.removeAll { it.personId == id }
}
}
// Mock verein repository (minimal implementation)
mockVereinRepository = object : VereinRepository {
override suspend fun findById(id: com.benasher44.uuid.Uuid): at.mocode.members.domain.model.DomVerein? {
return null
}
override suspend fun findByOepsVereinsNr(oepsVereinsNr: String): at.mocode.members.domain.model.DomVerein? {
return null
}
override suspend fun findByName(searchTerm: String, limit: Int): List<at.mocode.members.domain.model.DomVerein> {
return emptyList()
}
override suspend fun findByBundeslandId(bundeslandId: com.benasher44.uuid.Uuid): List<at.mocode.members.domain.model.DomVerein> {
return emptyList()
}
override suspend fun findByLandId(landId: com.benasher44.uuid.Uuid): List<at.mocode.members.domain.model.DomVerein> {
return emptyList()
}
override suspend fun findAllActive(limit: Int, offset: Int): List<at.mocode.members.domain.model.DomVerein> {
return emptyList()
}
override suspend fun findByLocation(searchTerm: String, limit: Int): List<at.mocode.members.domain.model.DomVerein> {
return emptyList()
}
override suspend fun save(verein: at.mocode.members.domain.model.DomVerein): at.mocode.members.domain.model.DomVerein {
return verein
}
override suspend fun delete(id: com.benasher44.uuid.Uuid): Boolean {
return true
}
override suspend fun existsByOepsVereinsNr(oepsVereinsNr: String): Boolean {
return false
}
override suspend fun countActive(): Long {
return 0L
}
override suspend fun countActiveByBundeslandId(bundeslandId: com.benasher44.uuid.Uuid): Long {
return 0L
}
}
// Mock master data service (minimal implementation)
mockMasterDataService = object : MasterDataService {
override suspend fun countryExists(countryId: com.benasher44.uuid.Uuid): Boolean {
return true
}
override suspend fun stateExists(stateId: com.benasher44.uuid.Uuid): Boolean {
return true
}
override suspend fun getCountryById(countryId: com.benasher44.uuid.Uuid): MasterDataService.CountryInfo? {
return null
}
override suspend fun getStateById(stateId: com.benasher44.uuid.Uuid): MasterDataService.StateInfo? {
return null
}
override suspend fun getAllCountries(): List<MasterDataService.CountryInfo> {
return emptyList()
}
override suspend fun getStatesByCountry(countryId: com.benasher44.uuid.Uuid): List<MasterDataService.StateInfo> {
return emptyList()
}
}
}
@AfterTest
fun tearDown() {
Dispatchers.resetMain()
}
//region Initial State Tests
@Test
fun `initial state should be correct`() {
// Verify all fields are initialized to empty values
assertEquals("", viewModel.nachname, "Nachname should be empty initially")
assertEquals("", viewModel.vorname, "Vorname should be empty initially")
assertEquals("", viewModel.titel, "Titel should be empty initially")
assertEquals("", viewModel.oepsSatzNr, "OepsSatzNr should be empty initially")
assertEquals("", viewModel.geburtsdatum, "Geburtsdatum should be empty initially")
assertNull(viewModel.geschlecht, "Geschlecht should be null initially")
assertEquals("", viewModel.telefon, "Telefon should be empty initially")
assertEquals("", viewModel.email, "Email should be empty initially")
assertEquals("", viewModel.strasse, "Strasse should be empty initially")
assertEquals("", viewModel.plz, "PLZ should be empty initially")
assertEquals("", viewModel.ort, "Ort should be empty initially")
assertEquals("", viewModel.adresszusatz, "Adresszusatz should be empty initially")
assertEquals("", viewModel.feiId, "FeiId should be empty initially")
assertEquals("", viewModel.mitgliedsNummer, "MitgliedsNummer should be empty initially")
assertEquals("", viewModel.notizen, "Notizen should be empty initially")
// Verify flags are initialized correctly
assertFalse(viewModel.istGesperrt, "IstGesperrt should be false initially")
assertEquals("", viewModel.sperrGrund, "SperrGrund should be empty initially")
assertFalse(viewModel.isLoading, "IsLoading should be false initially")
assertNull(viewModel.errorMessage, "ErrorMessage should be null initially")
assertFalse(viewModel.isSuccess, "IsSuccess should be false initially")
}
//endregion
//region Update Method Tests
@Test
fun `update methods should change state correctly`() {
// When - update multiple fields
viewModel.updateNachname("Mustermann")
viewModel.updateVorname("Max")
viewModel.updateTitel("Dr.")
viewModel.updateGeschlecht(GeschlechtE.M)
viewModel.updateEmail("max@example.com")
viewModel.updateIstGesperrt(true)
viewModel.updateSperrGrund("Test Sperrgrund")
// Then - verify all fields were updated correctly
assertEquals("Mustermann", viewModel.nachname, "Nachname should be updated")
assertEquals("Max", viewModel.vorname, "Vorname should be updated")
assertEquals("Dr.", viewModel.titel, "Titel should be updated")
assertEquals(GeschlechtE.M, viewModel.geschlecht, "Geschlecht should be updated")
assertEquals("max@example.com", viewModel.email, "Email should be updated")
assertTrue(viewModel.istGesperrt, "IstGesperrt should be updated")
assertEquals("Test Sperrgrund", viewModel.sperrGrund, "SperrGrund should be updated")
}
@Test
fun `update methods should handle special characters`() {
// When - update with special characters
val nameWithSpecialChars = "Müller-Höß"
viewModel.updateNachname(nameWithSpecialChars)
// Then - verify special characters are preserved
assertEquals(nameWithSpecialChars, viewModel.nachname, "Special characters should be preserved")
}
@Test
fun `update methods should handle very long inputs`() {
// When - update with very long input
val longText = "A".repeat(500)
viewModel.updateNotizen(longText)
// Then - verify long text is preserved
assertEquals(longText, viewModel.notizen, "Long text should be preserved")
}
//endregion
//region Validation Tests
@Test
fun `createPerson should fail with empty nachname`() = runTest {
// Given - empty nachname
viewModel.updateVorname("Max")
// When
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then
assertEquals("Nachname ist erforderlich", viewModel.errorMessage, "Should show error for empty nachname")
assertFalse(viewModel.isSuccess, "Should not be successful with validation error")
assertFalse(viewModel.isLoading, "Loading state should be reset after validation")
}
@Test
fun `createPerson should fail with empty vorname`() = runTest {
// Given - empty vorname
viewModel.updateNachname("Mustermann")
// When
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then
assertEquals("Vorname ist erforderlich", viewModel.errorMessage, "Should show error for empty vorname")
assertFalse(viewModel.isSuccess, "Should not be successful with validation error")
assertFalse(viewModel.isLoading, "Loading state should be reset after validation")
}
@Test
fun `createPerson should handle invalid date format`() = runTest {
// Given - invalid date format
viewModel.updateNachname("Mustermann")
viewModel.updateVorname("Max")
viewModel.updateGeburtsdatum("invalid-date")
// When
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then
assertEquals("Ungültiges Datumsformat. Verwenden Sie YYYY-MM-DD", viewModel.errorMessage,
"Should show error for invalid date format")
assertFalse(viewModel.isSuccess, "Should not be successful with validation error")
assertFalse(viewModel.isLoading, "Loading state should be reset after validation")
}
//endregion
//region Success Tests
@Test
fun `createPerson should succeed with valid data`() = runTest {
// Given - valid data
viewModel.updateNachname("Mustermann")
viewModel.updateVorname("Max")
viewModel.updateGeschlecht(GeschlechtE.M)
viewModel.updateEmail("max@example.com")
// When
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then
assertTrue(viewModel.isSuccess, "Should be successful with valid data")
assertNull(viewModel.errorMessage, "Should not have error message")
assertFalse(viewModel.isLoading, "Loading state should be reset after success")
}
@Test
fun `createPerson should handle valid date format`() = runTest {
// Given - valid date format
viewModel.updateNachname("Mustermann")
viewModel.updateVorname("Max")
viewModel.updateGeburtsdatum("1990-05-15")
// When
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then
assertTrue(viewModel.isSuccess, "Should be successful with valid date")
assertNull(viewModel.errorMessage, "Should not have error message")
assertFalse(viewModel.isLoading, "Loading state should be reset after success")
}
@Test
fun `createPerson should succeed with minimal required data`() = runTest {
// Given - only required fields
viewModel.updateNachname("Mustermann")
viewModel.updateVorname("Max")
// When
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then
assertTrue(viewModel.isSuccess, "Should be successful with minimal required data")
assertNull(viewModel.errorMessage, "Should not have error message")
assertFalse(viewModel.isLoading, "Loading state should be reset after success")
}
//endregion
//region Form Management Tests
@Test
fun `resetForm should clear all fields`() {
// Given - set some values
viewModel.updateNachname("Mustermann")
viewModel.updateVorname("Max")
viewModel.updateEmail("max@example.com")
viewModel.updateIstGesperrt(true)
viewModel.updateSperrGrund("Test Sperrgrund")
// When
viewModel.resetForm()
// Then - verify all fields are reset
assertEquals("", viewModel.nachname, "Nachname should be reset")
assertEquals("", viewModel.vorname, "Vorname should be reset")
assertEquals("", viewModel.email, "Email should be reset")
assertFalse(viewModel.istGesperrt, "IstGesperrt should be reset")
assertEquals("", viewModel.sperrGrund, "SperrGrund should be reset")
// Verify state flags are reset
assertFalse(viewModel.isLoading, "IsLoading should be reset")
assertNull(viewModel.errorMessage, "ErrorMessage should be reset")
assertFalse(viewModel.isSuccess, "IsSuccess should be reset")
}
@Test
fun `clearError should reset error message`() = runTest {
// Given - simulate an error
viewModel.updateNachname("") // This will cause validation error
viewModel.updateVorname("Max")
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then - verify error message exists
assertNotNull(viewModel.errorMessage, "Should have error message")
// When - clear the error
viewModel.clearError()
// Then - verify error message is cleared
assertNull(viewModel.errorMessage, "Error message should be cleared")
}
@Test
fun `loading state should be reset after createPerson completes`() = runTest {
// Given
viewModel.updateNachname("Mustermann")
viewModel.updateVorname("Max")
// When - start creation and complete the operation
viewModel.createPerson()
testDispatcher.scheduler.advanceUntilIdle()
// Then - verify loading state is reset after completion
assertFalse(viewModel.isLoading, "Loading state should be reset after operation completes")
assertTrue(viewModel.isSuccess, "Operation should complete successfully")
}
//endregion
}
@@ -0,0 +1,296 @@
package at.mocode.client.web.viewmodel
import at.mocode.members.domain.model.DomPerson
import at.mocode.members.domain.repository.PersonRepository
import at.mocode.core.domain.model.GeschlechtE
import at.mocode.core.domain.model.DatenQuelleE
import com.benasher44.uuid.Uuid
import com.benasher44.uuid.uuid4
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import kotlin.test.*
/**
* Comprehensive test suite for the PersonListViewModel.
*
* Tests cover:
* - Initial state verification
* - Loading and refreshing person data
* - Error handling
* - Loading state management
*/
@OptIn(ExperimentalCoroutinesApi::class)
class PersonListViewModelTest {
private lateinit var mockPersonRepository: PersonRepository
private lateinit var viewModel: PersonListViewModel
private val testDispatcher = StandardTestDispatcher()
@BeforeTest
fun setup() {
Dispatchers.setMain(testDispatcher)
setupMockRepository()
}
/**
* Sets up the mock repository with test data
*/
private fun setupMockRepository() {
val persons = mutableListOf<DomPerson>()
mockPersonRepository = object : PersonRepository {
override suspend fun save(person: DomPerson): DomPerson {
val savedPerson = person.copy(personId = uuid4())
// Remove existing person with same OEPS number if exists
val existingIndex = persons.indexOfFirst { it.oepsSatzNr == person.oepsSatzNr }
if (existingIndex >= 0) {
persons.removeAt(existingIndex)
}
persons.add(savedPerson)
return savedPerson
}
override suspend fun findById(id: Uuid): DomPerson? {
return persons.find { it.personId == id }
}
override suspend fun findByOepsSatzNr(oepsSatzNr: String): DomPerson? {
return persons.find { it.oepsSatzNr == oepsSatzNr }
}
override suspend fun findByStammVereinId(vereinId: Uuid): List<DomPerson> {
return persons.filter { it.stammVereinId == vereinId }
}
override suspend fun findByName(searchTerm: String, limit: Int): List<DomPerson> {
return persons.filter {
it.nachname.contains(searchTerm, ignoreCase = true) ||
it.vorname.contains(searchTerm, ignoreCase = true)
}.take(limit)
}
override suspend fun findAllActive(limit: Int, offset: Int): List<DomPerson> {
return persons.filter { it.istAktiv }.drop(offset).take(limit)
}
override suspend fun countActive(): Long {
return persons.count { it.istAktiv }.toLong()
}
override suspend fun existsByOepsSatzNr(oepsSatzNr: String): Boolean {
return persons.any { it.oepsSatzNr == oepsSatzNr }
}
override suspend fun delete(id: Uuid): Boolean {
val initialSize = persons.size
persons.removeAll { it.personId == id }
return persons.size < initialSize
}
}
}
/**
* Adds test persons to the repository
*/
private suspend fun addTestPersons() {
// Create and add test persons
val testPersons = listOf(
createTestPerson("123456", "Müller", "Hans", GeschlechtE.M),
createTestPerson("234567", "Schmidt", "Anna", GeschlechtE.W),
createTestPerson("345678", "Weber", "Thomas", GeschlechtE.M)
)
testPersons.forEach { mockPersonRepository.save(it) }
}
/**
* Creates a test person with the given data
*/
private fun createTestPerson(
oepsSatzNr: String,
nachname: String,
vorname: String,
geschlecht: GeschlechtE,
isActive: Boolean = true
): DomPerson {
return DomPerson(
personId = uuid4(), // Generate a new UUID
oepsSatzNr = oepsSatzNr,
nachname = nachname,
vorname = vorname,
geschlechtE = geschlecht,
datenQuelle = DatenQuelleE.MANUELL,
istAktiv = isActive
)
}
@AfterTest
fun tearDown() {
Dispatchers.resetMain()
}
//region Initial State Tests
@Test
fun `initial state should be correct`() {
// When - create view model with empty repository
viewModel = PersonListViewModel(mockPersonRepository)
// Then - verify initial state
assertTrue(viewModel.persons.isEmpty(), "Persons list should be empty initially")
assertFalse(viewModel.isLoading, "Loading state should be false initially")
assertNull(viewModel.errorMessage, "Error message should be null initially")
}
//endregion
//region Data Loading Tests
@Test
fun `loadPersons should update persons list`() = runTest {
// Given - repository with test data
addTestPersons()
// When - initialize view model (which triggers loadPersons)
viewModel = PersonListViewModel(mockPersonRepository)
testDispatcher.scheduler.advanceUntilIdle()
// Then - verify persons list is populated
assertEquals(3, viewModel.persons.size, "Should load all test persons")
assertTrue(
viewModel.persons.any { it.nachname == "Müller" && it.vorname == "Hans" },
"Should contain person Müller Hans"
)
assertTrue(
viewModel.persons.any { it.nachname == "Schmidt" && it.vorname == "Anna" },
"Should contain person Schmidt Anna"
)
assertTrue(
viewModel.persons.any { it.nachname == "Weber" && it.vorname == "Thomas" },
"Should contain person Weber Thomas"
)
assertFalse(viewModel.isLoading, "Loading state should be reset after loading")
assertNull(viewModel.errorMessage, "Should not have error message after successful loading")
}
@Test
fun `refreshPersons should reload data`() = runTest {
// Given - view model with initial data loaded
addTestPersons()
viewModel = PersonListViewModel(mockPersonRepository)
testDispatcher.scheduler.advanceUntilIdle()
val initialCount = viewModel.persons.size
// When - add a new person and refresh
val newPerson = createTestPerson(
"999999",
"New",
"Person",
GeschlechtE.D
)
mockPersonRepository.save(newPerson)
viewModel.refreshPersons()
testDispatcher.scheduler.advanceUntilIdle()
// Then - verify new person is included
assertEquals(initialCount + 1, viewModel.persons.size, "Should have one more person after refresh")
assertTrue(
viewModel.persons.any { it.nachname == "New" && it.vorname == "Person" },
"Should contain newly added person after refresh"
)
assertFalse(viewModel.isLoading, "Loading state should be reset after refresh")
}
@Test
fun `loadPersons should handle empty repository`() = runTest {
// Given - empty repository (already set up in setup())
// When - initialize view model
viewModel = PersonListViewModel(mockPersonRepository)
testDispatcher.scheduler.advanceUntilIdle()
// Then - verify empty list is handled correctly
assertTrue(viewModel.persons.isEmpty(), "Persons list should be empty with empty repository")
assertFalse(viewModel.isLoading, "Loading state should be reset even with empty result")
assertNull(viewModel.errorMessage, "Should not have error with empty repository")
}
@Test
fun `loading state should be reset after operations complete`() = runTest {
// Given
viewModel = PersonListViewModel(mockPersonRepository)
// Add some test data to verify operation works
addTestPersons()
// When - refresh and complete the operation
viewModel.refreshPersons()
testDispatcher.scheduler.advanceUntilIdle()
// Then - verify loading state is reset after completion
assertFalse(viewModel.isLoading, "Loading state should be reset after operation completes")
assertTrue(viewModel.persons.isNotEmpty(), "Persons list should be populated after successful refresh")
}
//endregion
//region Error Handling Tests
@Test
fun `clearError should reset error message`() {
// Given - view model
viewModel = PersonListViewModel(mockPersonRepository)
// When - clear error (even when no error exists)
viewModel.clearError()
// Then - verify no error message
assertNull(viewModel.errorMessage, "Error message should be null after clearError")
}
@Test
fun `error handling should be robust`() = runTest {
// Given - view model with initial data loaded
addTestPersons()
viewModel = PersonListViewModel(mockPersonRepository)
testDispatcher.scheduler.advanceUntilIdle()
// Capture initial state
val initialPersons = viewModel.persons.toList()
// When - simulate a refresh operation that might cause errors
viewModel.refreshPersons()
testDispatcher.scheduler.advanceUntilIdle()
// Then - verify data is still intact regardless of potential errors
assertEquals(initialPersons.size, viewModel.persons.size,
"Person list size should be maintained even with potential errors")
// And error handling mechanism works
viewModel.clearError()
assertNull(viewModel.errorMessage, "Should be able to clear any potential errors")
}
//endregion
//region Search Tests
@Test
fun `repository search should work correctly`() = runTest {
// Given - repository with test data
addTestPersons()
// When - search for a specific person
val searchResults = mockPersonRepository.findByName("Müller", 10)
// Then - verify correct results
assertEquals(1, searchResults.size, "Should find one person with name Müller")
assertEquals("Müller", searchResults.first().nachname, "Should find person with correct last name")
assertEquals("Hans", searchResults.first().vorname, "Should find person with correct first name")
}
//endregion
}