Compare commits
19 Commits
aa10114767
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
463e1a013f
|
|||
|
69e0344261
|
|||
|
25d1038c9d
|
|||
|
ea6349c85c
|
|||
|
4104930ea5
|
|||
|
3d789c0352
|
|||
|
37d8e8cc74
|
|||
|
f3f83b7ca9
|
|||
|
552f604200
|
|||
|
f01357987c
|
|||
|
b4229c29c4
|
|||
|
d05d93a0d7
|
|||
|
37e125945b
|
|||
|
463e9b6258
|
|||
|
e99e951232
|
|||
|
ca1ad57f7e
|
|||
|
8ad212ee76
|
|||
|
dc9f4121e0
|
|||
|
d94b3f74de
|
43
.gitignore
vendored
43
.gitignore
vendored
@@ -1,11 +1,36 @@
|
||||
# Build artifacts
|
||||
bin/
|
||||
gen/
|
||||
out/
|
||||
build/
|
||||
app/build/
|
||||
|
||||
# Kotlin / Java
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
.gradle/
|
||||
local.properties
|
||||
/app/build
|
||||
|
||||
# Android Studio
|
||||
captures/
|
||||
.externalNativeBuild/
|
||||
.cxx/
|
||||
.navigation/
|
||||
|
||||
# Keys & Secrets
|
||||
*.jks
|
||||
*.keystore
|
||||
*.p12
|
||||
google-services.json
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Log files
|
||||
*.log
|
||||
|
||||
# Bundle/Release
|
||||
/app/release/
|
||||
|
||||
20
README.md
Normal file
20
README.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# ShAp-Planner
|
||||
|
||||
ShAp-Planner is a **self-hosted app** for managing finances, tasks, and data within shared households.
|
||||
The app is fully open source, lightweight, and can run on small devices like Raspberry Pi or older computers.
|
||||
|
||||
**[Backend](https://git.miaurizius.de/MiauRizius/shap-planner-backend):** Go
|
||||
**[Frontend](https://git.miaurizius.de/MiauRizius/shap-planner-android):** Android (Kotlin)
|
||||
**[License](https://git.miaurizius.de/MiauRizius/shap-planner-android/src/branch/main/LICENSE):** [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/)
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
You can either build the app from source or download the apk _(will be available soon)_
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
This work is marked <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0 1.0</a>
|
||||
@@ -61,6 +61,7 @@ dependencies {
|
||||
|
||||
//Manually added
|
||||
implementation("androidx.datastore:datastore-preferences:1.2.0")
|
||||
implementation("androidx.compose.material:material-icons-extended:1.6.0")
|
||||
|
||||
val room_version = "2.8.4"
|
||||
implementation("androidx.room:room-runtime:$room_version")
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
@@ -12,19 +9,16 @@
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@style/Theme.ShapPlanner">
|
||||
<activity
|
||||
android:name=".activities.MainActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.ShapPlanner">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -12,13 +12,14 @@ class TokenStorage(context: Context) {
|
||||
|
||||
private val prefs = EncryptedSharedPreferences.create(
|
||||
context,
|
||||
"wg_token_prefs",
|
||||
"wg_token_prefs2",
|
||||
masterKey,
|
||||
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
|
||||
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
|
||||
)
|
||||
|
||||
fun saveTokens(accountId: String, accessToken: String, refreshToken: String) {
|
||||
// println("Account ID: ${accountId}\nAToken: ${accessToken}\nRToken: ${refreshToken}")
|
||||
prefs.edit()
|
||||
.putString("access_$accountId", accessToken)
|
||||
.putString("refresh_$accountId", refreshToken)
|
||||
|
||||
@@ -2,212 +2,85 @@ package de.miaurizius.shap_planner.activities
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.miaurizius.shap_planner.TokenStorage
|
||||
import de.miaurizius.shap_planner.UserPreferences
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.room.AppDatabase
|
||||
import de.miaurizius.shap_planner.ui.AppContent
|
||||
import de.miaurizius.shap_planner.ui.theme.ShapPlannerTheme
|
||||
import de.miaurizius.shap_planner.viewmodels.ExpenseCreationViewModel
|
||||
import de.miaurizius.shap_planner.viewmodels.ExpenseDetailViewModel
|
||||
import de.miaurizius.shap_planner.viewmodels.LoginViewModel
|
||||
import de.miaurizius.shap_planner.viewmodels.MainViewModel
|
||||
import java.util.UUID
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
// enableEdgeToEdge()
|
||||
|
||||
val prefs = UserPreferences(this)
|
||||
val loginViewModel = LoginViewModel(prefs, applicationContext)
|
||||
|
||||
val database = AppDatabase.getDatabase(applicationContext)
|
||||
val dao = database.accountDao()
|
||||
val mainViewModel = MainViewModel(dao)
|
||||
val accountDao = database.accountDao()
|
||||
val expenseDao = database.expenseDao()
|
||||
val tokenStorage = TokenStorage(applicationContext)
|
||||
val mainViewModel = MainViewModel(
|
||||
accountDao,
|
||||
expenseDao,
|
||||
tokenStorage
|
||||
)
|
||||
val detailViewModel = ExpenseDetailViewModel(
|
||||
database.expenseDao(),
|
||||
database.expenseShareDao(),
|
||||
database.userDao(),
|
||||
tokenStorage
|
||||
)
|
||||
val creationViewModel = ExpenseCreationViewModel(
|
||||
database.userDao(),
|
||||
database.expenseDao(),
|
||||
database.expenseShareDao(),
|
||||
tokenStorage
|
||||
)
|
||||
|
||||
|
||||
setContent {
|
||||
ShapPlannerTheme {
|
||||
val isLoggedIn by loginViewModel.isLoggedIn.collectAsState()
|
||||
val accountList by mainViewModel.accounts.collectAsState()
|
||||
val selectedAccount = mainViewModel.selectedAccount
|
||||
val showLoginForNewAccount = remember { mutableStateOf(false) }
|
||||
|
||||
when {
|
||||
!isLoggedIn || accountList.isEmpty() -> {
|
||||
LoginScreen { serverUrl, username, password -> loginViewModel.login(serverUrl, username, password, mainViewModel) }
|
||||
BackHandler(enabled = showLoginForNewAccount.value && accountList.isNotEmpty()) {
|
||||
showLoginForNewAccount.value = false
|
||||
}
|
||||
|
||||
selectedAccount != null -> {
|
||||
DashboardScreen(
|
||||
account = selectedAccount,
|
||||
onBack = { mainViewModel.logoutFromAccount() }
|
||||
)
|
||||
}
|
||||
|
||||
else -> {
|
||||
AccountSelectionScreen(
|
||||
accounts = accountList,
|
||||
onAccountClick = { account ->
|
||||
mainViewModel.selectAccount(account)
|
||||
AppContent(
|
||||
accountList = accountList,
|
||||
selectedAccount = selectedAccount,
|
||||
showLoginForNewAccount = showLoginForNewAccount.value,
|
||||
onLogin = { server, user, pass ->
|
||||
loginViewModel.login(server, user, pass, mainViewModel)
|
||||
showLoginForNewAccount.value = false
|
||||
},
|
||||
onAddAccountClick = {
|
||||
loginViewModel.logout()
|
||||
}
|
||||
onSelectAccount = { mainViewModel.selectAccount(it) },
|
||||
onLogoutAccount = { mainViewModel.logoutFromAccount() },
|
||||
onAddAccountClick = { showLoginForNewAccount.value = true },
|
||||
onDeleteAccount = { mainViewModel.deleteAccount(selectedAccount!!) },
|
||||
sessionState = mainViewModel.sessionState,
|
||||
onValidateSession = { mainViewModel.validateSession(selectedAccount!!) },
|
||||
onSessionInvalid = { mainViewModel.logoutFromAccount() },
|
||||
onExpenseClick = { expense -> println("Clicked: ${expense.title}") },
|
||||
viewModel = mainViewModel,
|
||||
detailViewModel = detailViewModel,
|
||||
creationViewModel = creationViewModel,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AccountSelectionScreen(accounts: List<Account>, onAccountClick: (Account) -> Unit, onAddAccountClick: () -> Unit) {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp)
|
||||
.statusBarsPadding()
|
||||
.navigationBarsPadding(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
item {
|
||||
Text("Wähle einen Account", style = MaterialTheme.typography.headlineSmall)
|
||||
}
|
||||
|
||||
items(accounts) { account ->
|
||||
Card(modifier = Modifier.fillMaxWidth().clickable{ onAccountClick(account) }) {
|
||||
Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(modifier = Modifier.size(40.dp).background(Color.Gray, shape = CircleShape))
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
Column {
|
||||
Text(text = account.name, fontWeight = FontWeight.Bold)
|
||||
Text(text = account.wgName, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Button(
|
||||
onClick = onAddAccountClick,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text("Anderen Account hinzufügen")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun LoginScreen(onLogin: (String, String, String) -> Unit) {
|
||||
var serverUrl by remember { mutableStateOf("") }
|
||||
var username by remember { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
|
||||
Column(modifier = Modifier.padding(16.dp).statusBarsPadding().navigationBarsPadding()) {
|
||||
Text("Bitte anmelden")
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
//Home-Server
|
||||
TextField(
|
||||
value = serverUrl,
|
||||
onValueChange = { serverUrl = it },
|
||||
label = { Text("Server-URL") }
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
//Username
|
||||
TextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
label = { Text("Nutzername") }
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
//Password
|
||||
TextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("Passwort") }
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Button(onClick = { if(serverUrl.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty()) onLogin(
|
||||
serverUrl,
|
||||
username,
|
||||
password
|
||||
) }) {
|
||||
Text("Login")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun DashboardScreen(account: Account, onBack: () -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp)
|
||||
.statusBarsPadding()
|
||||
.navigationBarsPadding()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text(text = "Hallo, ${account.name}!", style = MaterialTheme.typography.headlineMedium)
|
||||
Text(text = "WG: ${account.wgName}", style = MaterialTheme.typography.bodyLarge, color = Color.Gray)
|
||||
}
|
||||
Button(onClick = onBack) {
|
||||
Text("Wechseln")
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.medium),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text("Hier kommen bald deine WG-Kosten hin 🚀")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ interface AccountDao {
|
||||
@Query("SELECT * FROM accounts")
|
||||
fun getAllAccounts(): Flow<List<Account>>
|
||||
|
||||
@Query("SELECT * FROM accounts WHERE id = :userId")
|
||||
fun getAccountById(userId: UUID): Flow<Account?>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAccount(account: Account)
|
||||
|
||||
|
||||
@@ -5,18 +5,21 @@ import androidx.room.Delete
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import java.util.UUID
|
||||
|
||||
@Entity(tableName = "expenses")
|
||||
data class Expense (
|
||||
val id: UUID,
|
||||
val amt: Double,
|
||||
val desc: String,
|
||||
|
||||
val payerId: UUID,
|
||||
val debtors: List<User>
|
||||
@PrimaryKey val id: UUID,
|
||||
val payer_id: UUID,
|
||||
val amount: Int,
|
||||
val title: String,
|
||||
val description: String,
|
||||
val attachments: List<String>?,
|
||||
val created_at: Int,
|
||||
val last_updated_at: Int
|
||||
)
|
||||
|
||||
@Dao
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package de.miaurizius.shap_planner.entities
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import java.util.UUID
|
||||
|
||||
@Entity(tableName = "expense_shares")
|
||||
data class ExpenseShare(
|
||||
@PrimaryKey val id: UUID,
|
||||
val expense_id: UUID,
|
||||
val user_id: UUID,
|
||||
val share_cents: Int
|
||||
)
|
||||
|
||||
@Dao
|
||||
interface ExpenseShareDao {
|
||||
@Query("SELECT * FROM expense_shares")
|
||||
fun getAllShares(): Flow<List<ExpenseShare>>
|
||||
|
||||
@Query("SELECT * FROM expense_shares WHERE id = :shareId")
|
||||
fun getShareById(shareId: UUID): Flow<ExpenseShare?>
|
||||
|
||||
@Query("SELECT * FROM expense_shares WHERE expense_id = :expense_id")
|
||||
fun getSharesByExpense(expense_id: UUID): Flow<List<ExpenseShare>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertShare(share: ExpenseShare)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteShare(share: ExpenseShare)
|
||||
}
|
||||
@@ -5,14 +5,16 @@ import androidx.room.Delete
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import java.util.UUID
|
||||
|
||||
@Entity(tableName = "users")
|
||||
data class User (
|
||||
val id: UUID,
|
||||
@PrimaryKey val id: UUID,
|
||||
val name: String,
|
||||
val avatar_url: String?
|
||||
)
|
||||
|
||||
@Dao
|
||||
@@ -20,6 +22,9 @@ interface UserDao {
|
||||
@Query("SELECT * FROM users")
|
||||
fun getAllUsers(): Flow<List<User>>
|
||||
|
||||
@Query("SELECT * FROM users WHERE id = :userId")
|
||||
fun getUserById(userId: UUID): Flow<User?>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertUser(user: User)
|
||||
|
||||
|
||||
@@ -1,17 +1,54 @@
|
||||
package de.miaurizius.shap_planner.network
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
import de.miaurizius.shap_planner.entities.User
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.DELETE
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Header
|
||||
import retrofit2.http.POST
|
||||
|
||||
data class LoginRequest(val username: String, val password: String)
|
||||
data class LoginUser(val id: String, val username: String, val role: String, val avatarUrl: String?)
|
||||
data class LoginResponse(val access_token: String, val refresh_token: String, val user: LoginUser, val wgName: String)
|
||||
import retrofit2.http.PUT
|
||||
import retrofit2.http.Query
|
||||
import java.util.UUID
|
||||
|
||||
interface APIService {
|
||||
// Account
|
||||
@POST("api/login")
|
||||
suspend fun login(@Body req: LoginRequest): Response<LoginResponse>
|
||||
|
||||
@POST("api/refresh")
|
||||
suspend fun refresh(@Body req: Map<String, String>): Response<Map<String, String>>
|
||||
suspend fun refresh(@Body req: RefreshRequest): Response<RefreshResponse>
|
||||
@GET("api/ping")
|
||||
suspend fun ping(@Header("Authorization") token: String): Response<Map<String, String>>
|
||||
|
||||
// Expenses
|
||||
@GET("api/expenses")
|
||||
suspend fun expensesGet(@Header("Authorization") token: String): Response<ExpensesResponse>
|
||||
@POST("api/expenses")
|
||||
suspend fun expenseCreate(@Header("Authorization") token: String, @Body req: ExpenseCreationRequest): Response<ExpenseCreationResponse>
|
||||
@PUT("api/expenses")
|
||||
suspend fun expenseUpdate(@Header("Authorization") token: String)
|
||||
@DELETE("api/expenses")
|
||||
suspend fun expenseDelete(@Header("Authorization") token: String)
|
||||
|
||||
// Shares
|
||||
@GET("api/shares")
|
||||
suspend fun sharesGet(@Header("Authorization") token: String): Response<ExpenseSharesResponse>
|
||||
@GET("api/shares")
|
||||
suspend fun shareGet(@Header("Authorization") token: String, @Query("id") shareId: UUID): Response<ExpenseShareResponse>
|
||||
@GET("api/shares")
|
||||
suspend fun shareGet(@Header("Authorization") token: String, @Query("id") expenseId: UUID, @Query("idType") idType: IDType): Response<ExpenseSharesResponse>
|
||||
|
||||
// User
|
||||
@GET("api/userinfo")
|
||||
suspend fun userinfo(@Header("Authorization") token: String, @Query("id") userId: UUID): Response<User>
|
||||
}
|
||||
|
||||
enum class IDType {
|
||||
@SerializedName("share")
|
||||
Share,
|
||||
@SerializedName("expense")
|
||||
Expense,
|
||||
@SerializedName("user")
|
||||
User,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package de.miaurizius.shap_planner.network
|
||||
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShare
|
||||
|
||||
// Login
|
||||
data class LoginRequest(val username: String, val password: String)
|
||||
data class LoginUser(val id: String, val username: String, val role: String, val avatarUrl: String?)
|
||||
data class LoginResponse(val access_token: String, val refresh_token: String, val user: LoginUser, val wgName: String)
|
||||
|
||||
// Refresh-Tokens
|
||||
data class RefreshRequest(val refresh_token: String)
|
||||
data class RefreshResponse(val access_token: String, val refresh_token: String)
|
||||
|
||||
// Expenses
|
||||
data class ExpensesResponse(val expenses: List<Expense>)
|
||||
data class ExpenseCreationRequest(val expense: Expense, val shares: List<ExpenseShare>)
|
||||
data class ExpenseCreationResponse(val expense: Expense, val shares: List<ExpenseShare>)
|
||||
|
||||
// ExpenseShares
|
||||
data class ExpenseSharesResponse(val shares: List<ExpenseShare>)
|
||||
data class ExpenseShareResponse(val share: ExpenseShare)
|
||||
@@ -8,7 +8,7 @@ import retrofit2.converter.gson.GsonConverterFactory
|
||||
object RetrofitProvider {
|
||||
|
||||
fun create(serverUrl: String): APIService {
|
||||
val base = if (serverUrl.endsWith("/")) serverUrl else "$serverUrl/"
|
||||
val base = if (serverUrl.endsWith("/")) "https://$serverUrl" else "https://$serverUrl/"
|
||||
|
||||
val logger = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BASIC }
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package de.miaurizius.shap_planner.network
|
||||
|
||||
sealed class SessionState {
|
||||
object Loading : SessionState()
|
||||
object Valid : SessionState()
|
||||
object Invalid : SessionState()
|
||||
data class Error(val message: String) : SessionState()
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package de.miaurizius.shap_planner.repository
|
||||
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.entities.ExpenseDao
|
||||
import de.miaurizius.shap_planner.network.APIService
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
class ExpenseRepository(
|
||||
private val dao: ExpenseDao,
|
||||
private val api: APIService
|
||||
) {
|
||||
fun getExpenses(token: String, forceRefresh: Boolean = false): Flow<Resource<List<Expense>>> = flow {
|
||||
val cachedExpense = dao.getAllExpenses().first()
|
||||
emit(Resource.Loading(cachedExpense))
|
||||
|
||||
if(cachedExpense.isEmpty() || forceRefresh) {
|
||||
try {
|
||||
val response = api.expensesGet("Bearer $token")
|
||||
if(response.isSuccessful) {
|
||||
val remoteExpense = response.body()?.expenses ?: emptyList()
|
||||
remoteExpense.forEach {
|
||||
dao.insertExpense(it)
|
||||
}
|
||||
}
|
||||
} catch(e: Exception) {
|
||||
emit(Resource.Error("Network Error: ${e.localizedMessage}", cachedExpense))
|
||||
}
|
||||
}
|
||||
dao.getAllExpenses().collect { emit(Resource.Success(it)) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package de.miaurizius.shap_planner.repository
|
||||
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShare
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShareDao
|
||||
import de.miaurizius.shap_planner.network.APIService
|
||||
import de.miaurizius.shap_planner.network.IDType
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import java.util.UUID
|
||||
|
||||
class ExpenseShareRepository(
|
||||
private val dao: ExpenseShareDao,
|
||||
private val api: APIService
|
||||
) {
|
||||
fun getShares(token: String, forceRefresh: Boolean = false): Flow<Resource<List<ExpenseShare>>> = flow {
|
||||
val cachedData = dao.getAllShares().first()
|
||||
emit(Resource.Loading(cachedData))
|
||||
|
||||
if(cachedData.isEmpty() || forceRefresh) {
|
||||
try {
|
||||
val response = api.sharesGet("Bearer $token")
|
||||
if(response.isSuccessful) {
|
||||
val remoteShare = response.body()?.shares ?: emptyList()
|
||||
remoteShare.forEach {
|
||||
dao.insertShare(it)
|
||||
}
|
||||
}
|
||||
} catch(e: Exception) {
|
||||
emit(Resource.Error("Network Error: ${e.localizedMessage}", cachedData))
|
||||
}
|
||||
}
|
||||
dao.getAllShares().collect { emit(Resource.Success(it)) }
|
||||
}
|
||||
|
||||
fun getShareById(token: String, shareId: UUID, forceRefresh: Boolean = false): Flow<Resource<ExpenseShare>> = flow {
|
||||
val cached = dao.getShareById(shareId).first()
|
||||
emit(Resource.Loading(cached))
|
||||
if(cached == null || forceRefresh) {
|
||||
try {
|
||||
val response = api.shareGet("Bearer $token", shareId)
|
||||
if(response.isSuccessful) {
|
||||
response.body()?.share?.let { remoteShare -> dao.insertShare(remoteShare) }
|
||||
}
|
||||
} catch(e: Exception) {
|
||||
emit(Resource.Error("Network-Error: ${e.localizedMessage}", cached))
|
||||
}
|
||||
}
|
||||
dao.getShareById(shareId).collect { share ->
|
||||
if(share != null) emit(Resource.Success(share))
|
||||
else emit(Resource.Error("Share nicht gefunden", null))
|
||||
}
|
||||
}
|
||||
|
||||
fun getSharesByExpenseId(token: String, expenseId: UUID, forceRefresh: Boolean = false): Flow<Resource<List<ExpenseShare>>> = flow {
|
||||
val cached = dao.getSharesByExpense(expenseId).first()
|
||||
emit(Resource.Loading(cached))
|
||||
if(cached.isEmpty() || forceRefresh) {
|
||||
try {
|
||||
val response = api.shareGet("Bearer $token", expenseId, IDType.Expense)
|
||||
if(response.isSuccessful) {
|
||||
println("Body: ${response.body()}")
|
||||
val remoteShare = response.body()?.shares ?: emptyList()
|
||||
remoteShare.forEach { dao.insertShare(it) }
|
||||
}
|
||||
} catch(e: Exception) {
|
||||
emit(Resource.Error("Network Error: ${e.localizedMessage}", cached))
|
||||
}
|
||||
}
|
||||
dao.getSharesByExpense(expenseId).collect { emit(Resource.Success(it)) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.miaurizius.shap_planner.repository
|
||||
|
||||
sealed class Resource<T>(val data: T? = null, val message: String? = null) {
|
||||
class Success<T>(data: T): Resource<T>(data)
|
||||
class Loading<T>(data: T? = null): Resource<T>(data)
|
||||
class Error<T>(message: String, data: T? = null): Resource<T>(data, message)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package de.miaurizius.shap_planner.repository
|
||||
|
||||
import de.miaurizius.shap_planner.entities.User
|
||||
import de.miaurizius.shap_planner.entities.UserDao
|
||||
import de.miaurizius.shap_planner.network.APIService
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import java.util.UUID
|
||||
|
||||
class UserRepository(
|
||||
private val dao: UserDao,
|
||||
private val api: APIService
|
||||
) {
|
||||
fun getUser(token: String, userId: UUID, forceRefresh: Boolean = false): Flow<Resource<User>> = flow {
|
||||
val cached = dao.getUserById(userId).first()
|
||||
emit(Resource.Loading(cached))
|
||||
if(cached == null || forceRefresh) {
|
||||
try {
|
||||
val response = api.userinfo("Bearer $token", userId)
|
||||
if(response.isSuccessful) {
|
||||
println("Body: ${response.body()}")
|
||||
response.body()?.let { remoteUser -> dao.insertUser(remoteUser) }
|
||||
}
|
||||
} catch(e: Exception) {
|
||||
emit(Resource.Error("Network-Error: ${e.localizedMessage}", cached))
|
||||
}
|
||||
}
|
||||
dao.getUserById(userId).collect { user -> if(user != null) emit(Resource.Success(user)) else emit(
|
||||
Resource.Error("User nicht gefunden", null)) }
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,31 @@ import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverter
|
||||
import androidx.room.TypeConverters
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.entities.AccountDao
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.entities.ExpenseDao
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShare
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShareDao
|
||||
import de.miaurizius.shap_planner.entities.User
|
||||
import de.miaurizius.shap_planner.entities.UserDao
|
||||
|
||||
@Database(entities = [Account::class], version = 2)
|
||||
class Converters {
|
||||
@TypeConverter
|
||||
fun fromList(list: List<String>?): String? = list?.joinToString(",")
|
||||
@TypeConverter
|
||||
fun toList(data: String?): List<String>? = data?.split(",")?.map { it.trim() }
|
||||
}
|
||||
|
||||
@Database(entities = [Account::class, Expense::class, ExpenseShare::class, User::class], version = 6)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun accountDao(): AccountDao
|
||||
abstract fun expenseDao(): ExpenseDao
|
||||
abstract fun expenseShareDao(): ExpenseShareDao
|
||||
abstract fun userDao(): UserDao
|
||||
companion object {
|
||||
@Volatile
|
||||
private var INSTANCE: AppDatabase? = null
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package de.miaurizius.shap_planner.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.network.SessionState
|
||||
import de.miaurizius.shap_planner.ui.screens.AccountSelectionScreen
|
||||
import de.miaurizius.shap_planner.ui.screens.DashboardScreen
|
||||
import de.miaurizius.shap_planner.ui.screens.ExpenseCreationScreen
|
||||
import de.miaurizius.shap_planner.ui.screens.ExpenseDetailScreen
|
||||
import de.miaurizius.shap_planner.ui.screens.LoginScreen
|
||||
import de.miaurizius.shap_planner.viewmodels.ExpenseCreationViewModel
|
||||
import de.miaurizius.shap_planner.viewmodels.ExpenseDetailViewModel
|
||||
import de.miaurizius.shap_planner.viewmodels.MainViewModel
|
||||
|
||||
@Composable
|
||||
fun AppContent(
|
||||
// Login
|
||||
accountList: List<Account>,
|
||||
selectedAccount: Account?,
|
||||
showLoginForNewAccount: Boolean,
|
||||
onLogin: (String, String, String) -> Unit,
|
||||
|
||||
// Expenses
|
||||
onExpenseClick: (Expense) -> Unit,
|
||||
|
||||
// Account
|
||||
onSelectAccount: (Account) -> Unit,
|
||||
onLogoutAccount: () -> Unit,
|
||||
onAddAccountClick: () -> Unit,
|
||||
onDeleteAccount: () -> Unit,
|
||||
|
||||
// Session
|
||||
sessionState: SessionState,
|
||||
onValidateSession: () -> Unit,
|
||||
onSessionInvalid: () -> Unit,
|
||||
|
||||
//Important
|
||||
viewModel: MainViewModel,
|
||||
detailViewModel: ExpenseDetailViewModel,
|
||||
creationViewModel: ExpenseCreationViewModel
|
||||
) {
|
||||
var selectedExpense by remember { mutableStateOf<Expense?>(null) }
|
||||
var showAddExpenseScreen by remember { mutableStateOf(false) }
|
||||
|
||||
when {
|
||||
showAddExpenseScreen -> {
|
||||
ExpenseCreationScreen(
|
||||
account = selectedAccount!!,
|
||||
viewModel = creationViewModel,
|
||||
onBack = { showAddExpenseScreen = false },
|
||||
onSaved = { showAddExpenseScreen = false },
|
||||
)
|
||||
}
|
||||
selectedExpense != null -> {
|
||||
ExpenseDetailScreen(
|
||||
expense = selectedExpense!!,
|
||||
account = selectedAccount!!,
|
||||
viewModel = detailViewModel,
|
||||
onBack = { selectedExpense = null }
|
||||
)
|
||||
}
|
||||
showLoginForNewAccount -> LoginScreen(onLogin)
|
||||
accountList.isEmpty() -> LoginScreen(onLogin)
|
||||
selectedAccount != null -> DashboardScreen(
|
||||
// Data and regarding Methods
|
||||
account = selectedAccount,
|
||||
onExpenseClick = { selectedExpense = it },
|
||||
|
||||
// Default Methods
|
||||
mainViewModel = viewModel,
|
||||
onBack = onLogoutAccount,
|
||||
onDelete = onDeleteAccount,
|
||||
sessionState = sessionState,
|
||||
onValidate = onValidateSession,
|
||||
onSessionInvalid = onSessionInvalid,
|
||||
onAddExpenseClick = { showAddExpenseScreen = true },
|
||||
)
|
||||
else -> AccountSelectionScreen(
|
||||
accounts = accountList,
|
||||
onAccountClick = onSelectAccount,
|
||||
onAddAccountClick = onAddAccountClick
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package de.miaurizius.shap_planner.ui.screens
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Home
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AccountSelectionScreen(
|
||||
accounts: List<Account>,
|
||||
onAccountClick: (Account) -> Unit,
|
||||
onAddAccountClick: () -> Unit
|
||||
) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
CenterAlignedTopAppBar(
|
||||
title = { Text("ShAp-Planner", fontWeight = FontWeight.Black) }
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
tonalElevation = 2.dp
|
||||
) {
|
||||
Button(
|
||||
onClick = onAddAccountClick,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp)
|
||||
.navigationBarsPadding()
|
||||
.height(56.dp),
|
||||
shape = MaterialTheme.shapes.medium
|
||||
) {
|
||||
Icon(Icons.Default.Add, contentDescription = null)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Add New Account", style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(horizontal = 20.dp)
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text = "Welcome back!",
|
||||
style = MaterialTheme.typography.headlineLarge,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Select an account to continue",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
modifier = Modifier.padding(bottom = 16.dp)
|
||||
)
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
contentPadding = PaddingValues(bottom = 16.dp)
|
||||
) {
|
||||
if (accounts.isEmpty()) {
|
||||
item {
|
||||
Box(
|
||||
modifier = Modifier.fillParentMaxHeight(0.6f).fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text(
|
||||
"No accounts yet.\nTap 'Add New Account' to start.",
|
||||
textAlign = TextAlign.Center,
|
||||
color = Color.Gray
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items(accounts) { account ->
|
||||
AccountItem(account = account, onClick = { onAccountClick(account) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AccountItem(account: Account, onClick: () -> Unit) {
|
||||
ElevatedCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onClick() },
|
||||
shape = MaterialTheme.shapes.large,
|
||||
colors = CardDefaults.elevatedCardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
// Stylized Avatar with Initial
|
||||
Surface(
|
||||
modifier = Modifier.size(52.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
text = account.name.take(1).uppercase(),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = account.name,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Default.Home,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(14.dp),
|
||||
tint = MaterialTheme.colorScheme.secondary
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text(
|
||||
text = account.wgName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.secondary
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Trailing Chevron
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.outline
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package de.miaurizius.shap_planner.ui.screens
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
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.Delete
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.network.SessionState
|
||||
import de.miaurizius.shap_planner.repository.Resource
|
||||
import de.miaurizius.shap_planner.viewmodels.MainViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DashboardScreen(
|
||||
account: Account,
|
||||
onExpenseClick: (Expense) -> Unit,
|
||||
onAddExpenseClick: () -> Unit,
|
||||
mainViewModel: MainViewModel,
|
||||
onBack: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
sessionState: SessionState,
|
||||
onValidate: () -> Unit,
|
||||
onSessionInvalid: () -> Unit
|
||||
) {
|
||||
val expenseResource by mainViewModel.expenseResource.collectAsState()
|
||||
|
||||
LaunchedEffect(Unit) { onValidate() }
|
||||
LaunchedEffect(account) { mainViewModel.loadExpenses(account, forceRefresh = false) }
|
||||
|
||||
if (sessionState == SessionState.Invalid) {
|
||||
LaunchedEffect(Unit) { onSessionInvalid() }
|
||||
return
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {
|
||||
Column {
|
||||
Text(account.wgName, style = MaterialTheme.typography.titleLarge)
|
||||
Text("Household", style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.Default.Refresh, "Switch")
|
||||
}
|
||||
IconButton(onClick = onDelete) {
|
||||
Icon(Icons.Default.Delete, "Delete", tint = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
androidx.compose.material3.FloatingActionButton(
|
||||
onClick = onAddExpenseClick,
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||||
) {
|
||||
Icon(Icons.Default.Add, "Neu")
|
||||
}
|
||||
}
|
||||
) { paddingValues ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
.background(MaterialTheme.colorScheme.surface)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Hello, ${account.name}!",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
SummaryCard(expenses = expenseResource.data ?: emptyList())
|
||||
}
|
||||
|
||||
Text(
|
||||
text = "Latest expenses",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
color = MaterialTheme.colorScheme.secondary
|
||||
)
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
if (expenseResource is Resource.Loading && expenseResource.data?.isEmpty() == true) {
|
||||
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
items(expenseResource.data ?: emptyList()) { expense ->
|
||||
ExpenseItem(expense = expense, onClick = { onExpenseClick(expense) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("DefaultLocale")
|
||||
@Composable
|
||||
fun SummaryCard(expenses: List<Expense>) {
|
||||
val total = expenses.sumOf { it.amount } / 100.0
|
||||
androidx.compose.material3.Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = androidx.compose.material3.CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.primaryContainer
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Text("Total expenditure", style = MaterialTheme.typography.labelMedium)
|
||||
Text(
|
||||
text = String.format("%.2f €", total),
|
||||
style = MaterialTheme.typography.displaySmall,
|
||||
fontWeight = FontWeight.Black
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("DefaultLocale")
|
||||
@Composable
|
||||
fun ExpenseItem(expense: Expense, onClick: () -> Unit) {
|
||||
androidx.compose.material3.ElevatedCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onClick() },
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
colors = androidx.compose.material3.CardDefaults.elevatedCardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
shape = androidx.compose.foundation.shape.CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
modifier = Modifier.size(40.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
text = expense.title.take(1).uppercase(),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = expense.title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = String.format("%.2f €", expense.amount / 100.0),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.ExtraBold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package de.miaurizius.shap_planner.ui.screens
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.viewmodels.ExpenseCreationViewModel
|
||||
|
||||
@SuppressLint("DefaultLocale")
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ExpenseCreationScreen(
|
||||
account: Account,
|
||||
viewModel: ExpenseCreationViewModel,
|
||||
onSaved: () -> Unit,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
var title by remember { mutableStateOf("") }
|
||||
var description by remember { mutableStateOf("") }
|
||||
var totalAmountStr by remember { mutableStateOf("") }
|
||||
val attachmentUris = remember { mutableStateListOf<android.net.Uri>() }
|
||||
val userShares = remember { mutableStateMapOf<java.util.UUID, String>() }
|
||||
val users by viewModel.users.collectAsState()
|
||||
|
||||
// Real-time calculation logic
|
||||
val totalCents = (totalAmountStr.replace(",", ".").toDoubleOrNull() ?: 0.0) * 100
|
||||
val distributedCents = userShares.values.sumOf {
|
||||
(it.replace(",", ".").toDoubleOrNull() ?: 0.0) * 100
|
||||
}.toLong()
|
||||
|
||||
val diff = totalCents.toLong() - distributedCents
|
||||
val isAmountMatched = totalCents > 0 && diff == 0L
|
||||
|
||||
// File Picker for multiple files (Images & PDFs)
|
||||
val launcher = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
contract = androidx.activity.result.contract.ActivityResultContracts.GetMultipleContents()
|
||||
) { uris ->
|
||||
attachmentUris.addAll(uris)
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) { viewModel.loadUsers() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("New Expense") },
|
||||
navigationIcon = { IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back")
|
||||
} }
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(padding).padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
// Header Info
|
||||
item {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
OutlinedTextField(
|
||||
value = title,
|
||||
onValueChange = { title = it },
|
||||
label = { Text("Title *") },
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = totalAmountStr,
|
||||
onValueChange = { totalAmountStr = it },
|
||||
label = { Text("Total Amount (€) *") },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Optional Description & Multi-File Attachments
|
||||
item {
|
||||
Text("Additional Info", style = MaterialTheme.typography.titleMedium)
|
||||
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
OutlinedTextField(
|
||||
value = description,
|
||||
onValueChange = { description = it },
|
||||
label = { Text("Description (Optional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 2
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text("Attachments (${attachmentUris.size})", style = MaterialTheme.typography.labelLarge)
|
||||
attachmentUris.forEach { uri ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Default.Description, "File", modifier = Modifier.size(20.dp))
|
||||
Text(" Document attached", modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodySmall)
|
||||
IconButton(onClick = { attachmentUris.remove(uri) }) {
|
||||
Icon(Icons.Default.Delete, "Remove", tint = Color.Red)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(onClick = { launcher.launch("*/*") }) {
|
||||
Text("Select Files (Images, PDF)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Split Details & Validation Message
|
||||
item {
|
||||
Column {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Split Details *", style = MaterialTheme.typography.titleMedium)
|
||||
TextButton(onClick = {
|
||||
if (totalCents > 0) {
|
||||
val share = String.format("%.2f", (totalCents / users.size) / 100.0)
|
||||
users.forEach { userShares[it.id] = share }
|
||||
}
|
||||
}) { Text("Split Equally") }
|
||||
}
|
||||
|
||||
// VALIDATION MESSAGE
|
||||
if (totalCents > 0) {
|
||||
val statusText = when {
|
||||
diff > 0 -> "Remaining: ${String.format("%.2f", diff / 100.0)} €"
|
||||
diff < 0 -> "Over-allocated: ${String.format("%.2f", Math.abs(diff) / 100.0)} €"
|
||||
else -> "Amount matched! ✓"
|
||||
}
|
||||
val statusColor = if (diff == 0L) Color(0xFF2E7D32) else MaterialTheme.colorScheme.error
|
||||
|
||||
Surface(
|
||||
color = statusColor.copy(alpha = 0.1f),
|
||||
shape = MaterialTheme.shapes.small,
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)
|
||||
) {
|
||||
Text(
|
||||
text = statusText,
|
||||
color = statusColor,
|
||||
modifier = Modifier.padding(8.dp),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items(users) { user ->
|
||||
UserShareInputItem(
|
||||
userName = user.name,
|
||||
amount = userShares[user.id] ?: "",
|
||||
onAmountChange = { userShares[user.id] = it }
|
||||
)
|
||||
}
|
||||
|
||||
// Save Actions
|
||||
item {
|
||||
Button(
|
||||
onClick = {
|
||||
viewModel.saveExpense(
|
||||
account = account,
|
||||
title = title,
|
||||
description = description,
|
||||
amountCents = totalCents.toInt(),
|
||||
shares = userShares.mapValues { (it.value.replace(",",".").toDoubleOrNull() ?: 0.0).toInt() * 100 }.filter { it.value > 0 },
|
||||
attachments = attachmentUris.map { it.toString() }
|
||||
)
|
||||
onSaved()
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().height(56.dp),
|
||||
enabled = title.isNotBlank() && isAmountMatched // STRICT VALIDATION
|
||||
) {
|
||||
Text("Save Expense")
|
||||
}
|
||||
|
||||
if (totalAmountStr.isNotBlank() && !isAmountMatched) {
|
||||
Text(
|
||||
"Sum of shares must equal total amount to save.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
|
||||
TextButton(onClick = onBack, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Cancel")
|
||||
}
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun UserShareInputItem(userName: String, amount: String, onAmountChange: (String) -> Unit) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f))
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Surface(
|
||||
shape = androidx.compose.foundation.shape.CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
modifier = Modifier.size(32.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Text(userName.take(1).uppercase(), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
Text(userName, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge)
|
||||
|
||||
OutlinedTextField(
|
||||
value = amount,
|
||||
onValueChange = onAmountChange,
|
||||
modifier = Modifier.width(100.dp),
|
||||
placeholder = { Text("0.00") },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
|
||||
singleLine = true,
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(textAlign = TextAlign.End)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("€")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package de.miaurizius.shap_planner.ui.screens
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.viewmodels.ExpenseDetailViewModel
|
||||
|
||||
@SuppressLint("DefaultLocale")
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ExpenseDetailScreen(
|
||||
expense: Expense,
|
||||
account: Account,
|
||||
viewModel: ExpenseDetailViewModel,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
val shares by viewModel.sharesWithUser.collectAsState()
|
||||
|
||||
LaunchedEffect(expense) {
|
||||
viewModel.loadExpenseDetail(account, expense)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Expense Details") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(16.dp)
|
||||
) {
|
||||
// Hero Section: Amount & Title
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = "Total Amount",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.secondary
|
||||
)
|
||||
Text(
|
||||
text = String.format("%.2f €", expense.amount / 100.0),
|
||||
style = MaterialTheme.typography.displayMedium,
|
||||
fontWeight = FontWeight.Black,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Text(
|
||||
text = expense.title,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
|
||||
// Description Card (only shown if not empty)
|
||||
if (expense.description.isNotBlank()) {
|
||||
androidx.compose.material3.ElevatedCard(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 24.dp),
|
||||
colors = androidx.compose.material3.CardDefaults.elevatedCardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Description",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(text = expense.description, style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = "Cost Distribution",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.padding(bottom = 12.dp)
|
||||
)
|
||||
|
||||
LazyColumn(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
items(shares) { item ->
|
||||
ShareItem(
|
||||
name = item.user?.name ?: "Unknown User",
|
||||
amountCents = item.share.share_cents
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("DefaultLocale")
|
||||
@Composable
|
||||
fun ShareItem(name: String, amountCents: Int) {
|
||||
androidx.compose.material3.OutlinedCard(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
colors = androidx.compose.material3.CardDefaults.outlinedCardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
// User Avatar Circle
|
||||
Surface(
|
||||
shape = androidx.compose.foundation.shape.CircleShape,
|
||||
color = MaterialTheme.colorScheme.secondaryContainer,
|
||||
modifier = Modifier.size(36.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
text = name.take(1).uppercase(),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSecondaryContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Text(
|
||||
text = name,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
|
||||
Text(
|
||||
text = String.format("%.2f €", amountCents / 100.0),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = if (amountCents > 0) Color(0xFF2E7D32) else Color.Gray
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package de.miaurizius.shap_planner.ui.screens
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
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.Cloud
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material.icons.filled.VpnKey
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun LoginScreen(
|
||||
onLogin: (String, String, String) -> Unit,
|
||||
onBack: (() -> Unit)? = null
|
||||
) {
|
||||
if (onBack != null) {
|
||||
BackHandler { onBack() }
|
||||
}
|
||||
|
||||
var serverUrl by remember { mutableStateOf("") }
|
||||
var username by remember { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
var passwordVisible by remember { mutableStateOf(false) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Add Account", fontWeight = FontWeight.Bold) },
|
||||
navigationIcon = {
|
||||
if (onBack != null) {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(24.dp)
|
||||
.verticalScroll(rememberScrollState()), // Scrollbar, falls die Tastatur den Platz wegnimmt
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
// App Icon or Welcome Text
|
||||
Icon(
|
||||
imageVector = Icons.Default.Lock,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(64.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
Text(
|
||||
text = "Connect to Server",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.padding(top = 16.dp)
|
||||
)
|
||||
|
||||
Text(
|
||||
text = "Enter your credentials to link your account",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(bottom = 32.dp)
|
||||
)
|
||||
|
||||
// Server URL Field
|
||||
OutlinedTextField(
|
||||
value = serverUrl,
|
||||
onValueChange = { serverUrl = it },
|
||||
label = { Text("Server URL") },
|
||||
placeholder = { Text("your-server.com") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
leadingIcon = { Icon(Icons.Default.Cloud, contentDescription = null) },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Username Field
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
label = { Text("Username") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
leadingIcon = { Icon(Icons.Default.Person, contentDescription = null) },
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Password Field
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("Password") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
leadingIcon = { Icon(Icons.Default.VpnKey, contentDescription = null) },
|
||||
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done
|
||||
),
|
||||
trailingIcon = {
|
||||
val image = if (passwordVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff
|
||||
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||
Icon(imageVector = image, contentDescription = "Toggle password visibility")
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
|
||||
// Login Button
|
||||
Button(
|
||||
onClick = { onLogin(serverUrl, username, password) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(56.dp),
|
||||
enabled = serverUrl.isNotBlank() && username.isNotBlank() && password.isNotBlank(),
|
||||
shape = MaterialTheme.shapes.medium
|
||||
) {
|
||||
Text("Connect Account", style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
|
||||
if (onBack != null) {
|
||||
TextButton(onClick = onBack, modifier = Modifier.padding(top = 8.dp)) {
|
||||
Text("Cancel", color = MaterialTheme.colorScheme.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package de.miaurizius.shap_planner.viewmodels
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import de.miaurizius.shap_planner.TokenStorage
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.entities.ExpenseDao
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShare
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShareDao
|
||||
import de.miaurizius.shap_planner.entities.User
|
||||
import de.miaurizius.shap_planner.entities.UserDao
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.UUID
|
||||
|
||||
class ExpenseCreationViewModel(
|
||||
private val userDao: UserDao,
|
||||
private val expenseDao: ExpenseDao,
|
||||
private val shareDao: ExpenseShareDao,
|
||||
private val tokenStorage: TokenStorage
|
||||
) : ViewModel() {
|
||||
private val _users = MutableStateFlow<List<User>>(emptyList())
|
||||
val users: StateFlow<List<User>> = _users
|
||||
|
||||
fun loadUsers() {
|
||||
viewModelScope.launch {
|
||||
userDao.getAllUsers().collect { _users.value = it }
|
||||
}
|
||||
}
|
||||
|
||||
fun saveExpense(
|
||||
account: Account,
|
||||
title: String,
|
||||
description: String,
|
||||
amountCents: Int,
|
||||
shares: Map<UUID, Int>,
|
||||
attachments: List<String>
|
||||
) {
|
||||
// viewModelScope.launch {
|
||||
// val expenseId = UUID.randomUUID()
|
||||
// val newExpense = Expense(
|
||||
// id = expenseId,
|
||||
// payer_id = account.id,
|
||||
// amount = amountCents,
|
||||
// title = title,
|
||||
// description = description,
|
||||
// attachments = if (attachments.isEmpty()) null else attachments,
|
||||
// created_at = (System.currentTimeMillis() / 1000).toInt(),
|
||||
// last_updated_at = 0
|
||||
// )
|
||||
//
|
||||
// expenseDao.insertExpense(newExpense)
|
||||
//
|
||||
// shares.forEach { (userId, shareCents) ->
|
||||
// shareDao.insertShare(
|
||||
// ExpenseShare(UUID.randomUUID(), expenseId, userId, shareCents)
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// // API POST Request
|
||||
//
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package de.miaurizius.shap_planner.viewmodels
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import de.miaurizius.shap_planner.TokenStorage
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.entities.ExpenseDao
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShare
|
||||
import de.miaurizius.shap_planner.entities.ExpenseShareDao
|
||||
import de.miaurizius.shap_planner.entities.User
|
||||
import de.miaurizius.shap_planner.entities.UserDao
|
||||
import de.miaurizius.shap_planner.network.RetrofitProvider
|
||||
import de.miaurizius.shap_planner.repository.ExpenseShareRepository
|
||||
import de.miaurizius.shap_planner.repository.Resource
|
||||
import de.miaurizius.shap_planner.repository.UserRepository
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class ShareWithUser(
|
||||
val share: ExpenseShare,
|
||||
val user: User?
|
||||
)
|
||||
|
||||
class ExpenseDetailViewModel(
|
||||
private val expenseDao: ExpenseDao,
|
||||
private val shareDao: ExpenseShareDao,
|
||||
private val userDao: UserDao,
|
||||
private val tokenStorage: TokenStorage
|
||||
) : ViewModel() {
|
||||
private val _sharesWithUser = MutableStateFlow<List<ShareWithUser>>(emptyList())
|
||||
val sharesWithUser: StateFlow<List<ShareWithUser>> = _sharesWithUser
|
||||
|
||||
fun loadExpenseDetail(account: Account, expense: Expense) {
|
||||
viewModelScope.launch {
|
||||
val api = RetrofitProvider.create(account.serverUrl)
|
||||
val token = tokenStorage.getAccess(account.id.toString()) ?: ""
|
||||
|
||||
val shareRepo = ExpenseShareRepository(shareDao, api)
|
||||
val userRepo = UserRepository(userDao, api)
|
||||
|
||||
shareRepo.getSharesByExpenseId(token, expense.id).collect { resource ->
|
||||
val shares = resource.data ?: emptyList()
|
||||
val combinedList = shares.map { share ->
|
||||
val cachedUser = userDao.getUserById(share.user_id).first()
|
||||
if (cachedUser == null) {
|
||||
val userResource = userRepo.getUser(token, share.user_id).first { it is Resource.Success || it is Resource.Error }
|
||||
ShareWithUser(share, userResource.data)
|
||||
} else {
|
||||
ShareWithUser(share, cachedUser)
|
||||
}
|
||||
}
|
||||
_sharesWithUser.value = combinedList
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.Locale.getDefault
|
||||
import java.util.UUID
|
||||
|
||||
class LoginViewModel(private val prefs: UserPreferences, private val appContext: Context) : ViewModel() {
|
||||
@@ -28,7 +29,7 @@ class LoginViewModel(private val prefs: UserPreferences, private val appContext:
|
||||
|
||||
try {
|
||||
val response = withContext(Dispatchers.IO) {
|
||||
api.login(LoginRequest(username, password))
|
||||
api.login(LoginRequest(username.lowercase(getDefault()).trim(), password))
|
||||
}
|
||||
|
||||
if(response.isSuccessful) {
|
||||
@@ -43,7 +44,7 @@ class LoginViewModel(private val prefs: UserPreferences, private val appContext:
|
||||
|
||||
val account = Account(
|
||||
id = UUID.fromString(body.user.id),
|
||||
name = username,
|
||||
name = username.trim(),
|
||||
wgName = body.wgName,
|
||||
avatarUrl = null,
|
||||
serverUrl = serverUrl,
|
||||
|
||||
@@ -5,32 +5,108 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import de.miaurizius.shap_planner.TokenStorage
|
||||
import de.miaurizius.shap_planner.entities.Account
|
||||
import de.miaurizius.shap_planner.entities.AccountDao
|
||||
import de.miaurizius.shap_planner.entities.Expense
|
||||
import de.miaurizius.shap_planner.entities.ExpenseDao
|
||||
import de.miaurizius.shap_planner.network.RefreshRequest
|
||||
import de.miaurizius.shap_planner.network.RetrofitProvider
|
||||
import de.miaurizius.shap_planner.network.SessionState
|
||||
import de.miaurizius.shap_planner.repository.ExpenseRepository
|
||||
import de.miaurizius.shap_planner.repository.Resource
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.collections.emptyList
|
||||
|
||||
class MainViewModel(private val accountDao: AccountDao) : ViewModel() {
|
||||
class MainViewModel(
|
||||
private val accountDao: AccountDao,
|
||||
private val expenseDao: ExpenseDao,
|
||||
private val tokenStorage: TokenStorage
|
||||
) : ViewModel() {
|
||||
|
||||
var selectedAccount by mutableStateOf<Account?>(null)
|
||||
private set
|
||||
val accounts: StateFlow<List<Account>> = accountDao.getAllAccounts()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||
var sessionState by mutableStateOf<SessionState>(SessionState.Loading)
|
||||
private set
|
||||
|
||||
private val _expenseResource = MutableStateFlow<Resource<List<Expense>>>(Resource.Loading(emptyList()))
|
||||
val expenseResource: StateFlow<Resource<List<Expense>>> = _expenseResource
|
||||
|
||||
fun loadExpenses(account: Account, forceRefresh: Boolean = false) {
|
||||
viewModelScope.launch {
|
||||
val api = RetrofitProvider.create(account.serverUrl)
|
||||
val repo = ExpenseRepository(expenseDao, api)
|
||||
val accessToken = tokenStorage.getAccess(account.id.toString()) ?: ""
|
||||
|
||||
repo.getExpenses(accessToken, forceRefresh).collect { result -> _expenseResource.value = result }
|
||||
}
|
||||
}
|
||||
|
||||
fun validateSession(account: Account) {
|
||||
viewModelScope.launch {
|
||||
sessionState = SessionState.Loading
|
||||
val api = RetrofitProvider.create(account.serverUrl)
|
||||
|
||||
val accessToken = tokenStorage.getAccess(account.id.toString())
|
||||
val refreshToken = tokenStorage.getRefresh(account.id.toString())
|
||||
|
||||
if(accessToken == null || refreshToken == null) {
|
||||
sessionState = SessionState.Invalid
|
||||
return@launch
|
||||
}
|
||||
|
||||
val pingResponse = api.ping("Bearer $accessToken")
|
||||
|
||||
if(pingResponse.isSuccessful) {
|
||||
sessionState = SessionState.Valid
|
||||
return@launch
|
||||
}
|
||||
|
||||
if(pingResponse.code() == 401) {
|
||||
val refreshResponse = api.refresh(RefreshRequest(refreshToken))
|
||||
|
||||
if(refreshResponse.isSuccessful) {
|
||||
val newTokens = refreshResponse.body()!!
|
||||
|
||||
tokenStorage.saveTokens(
|
||||
account.id.toString(),
|
||||
newTokens.access_token,
|
||||
newTokens.refresh_token
|
||||
)
|
||||
|
||||
sessionState = SessionState.Valid
|
||||
|
||||
return@launch
|
||||
} else {
|
||||
sessionState = SessionState.Invalid
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
sessionState = SessionState.Error("Server error")
|
||||
}
|
||||
}
|
||||
|
||||
fun addAccount(account: Account) {
|
||||
viewModelScope.launch {
|
||||
accountDao.insertAccount(account)
|
||||
}
|
||||
}
|
||||
|
||||
var selectedAccount by mutableStateOf<Account?>(null)
|
||||
private set
|
||||
|
||||
fun deleteAccount(account: Account) {
|
||||
viewModelScope.launch {
|
||||
accountDao.deleteAccount(account)
|
||||
tokenStorage.clearTokens(account.id.toString())
|
||||
selectedAccount = null
|
||||
}
|
||||
}
|
||||
fun selectAccount(account: Account) {
|
||||
selectedAccount = account
|
||||
}
|
||||
|
||||
fun logoutFromAccount() {
|
||||
selectedAccount = null
|
||||
}
|
||||
|
||||
8
app/src/main/res/xml/network_security_config.xml
Normal file
8
app/src/main/res/xml/network_security_config.xml
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<network-security-config>
|
||||
<debug-overrides>
|
||||
<trust-anchors>
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</debug-overrides>
|
||||
</network-security-config>
|
||||
Reference in New Issue
Block a user