Base app working
This commit is contained in:
62
app/build.gradle.kts
Normal file
62
app/build.gradle.kts
Normal file
@@ -0,0 +1,62 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.budget"
|
||||
compileSdk = 34
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.example.budget"
|
||||
minSdk = 24
|
||||
targetSdk = 34
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
useSupportLibrary = true
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
composeOptions {
|
||||
kotlinCompilerExtensionVersion = "1.5.8"
|
||||
}
|
||||
packaging {
|
||||
resources {
|
||||
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.bundles.base)
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.bundles.compose)
|
||||
implementation(libs.bundles.network)
|
||||
|
||||
debugImplementation(libs.bundles.compose.debug)
|
||||
testImplementation(libs.junit)
|
||||
androidTestImplementation(libs.bundles.android.test)
|
||||
}
|
||||
24
app/src/main/AndroidManifest.xml
Normal file
24
app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="Бюджет"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
184
app/src/main/java/com/example/budget/MainActivity.kt
Normal file
184
app/src/main/java/com/example/budget/MainActivity.kt
Normal file
@@ -0,0 +1,184 @@
|
||||
package com.example.budget
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.List
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||
import androidx.navigation.NavType
|
||||
import androidx.navigation.compose.*
|
||||
import androidx.navigation.navArgument
|
||||
import com.example.budget.network.ApiClient
|
||||
import com.example.budget.network.SessionManager
|
||||
import com.example.budget.ui.auth.AuthScreen
|
||||
import com.example.budget.ui.auth.AuthViewModel
|
||||
import com.example.budget.ui.main.MainScreen
|
||||
import com.example.budget.ui.planning.PlanningScreen
|
||||
import com.example.budget.ui.stats.StatsScreen
|
||||
import com.example.budget.ui.transaction.AddEditTransactionScreen
|
||||
|
||||
sealed class Screen(val route: String, val title: String, val icon: ImageVector) {
|
||||
object Main : Screen("main", "Обзор", Icons.AutoMirrored.Filled.List)
|
||||
object Stats : Screen("stats", "Анализ", Icons.Default.PieChart)
|
||||
object Planning : Screen("planning", "Планы", Icons.Default.DateRange)
|
||||
object Profile : Screen("profile", "Профиль", Icons.Default.Person)
|
||||
}
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
val sessionManager = SessionManager(this)
|
||||
ApiClient.init(sessionManager)
|
||||
|
||||
setContent {
|
||||
MaterialTheme {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background
|
||||
) {
|
||||
BudgetNavHost(sessionManager)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun BudgetNavHost(sessionManager: SessionManager) {
|
||||
val navController = rememberNavController()
|
||||
val hasToken = sessionManager.hasToken()
|
||||
val startDestination = if (hasToken) "home_scaffold" else "auth"
|
||||
|
||||
NavHost(navController = navController, startDestination = startDestination) {
|
||||
composable("auth") {
|
||||
val authViewModel: AuthViewModel = viewModel()
|
||||
authViewModel.init(sessionManager)
|
||||
AuthScreen(
|
||||
onLoginSuccess = {
|
||||
navController.navigate("home_scaffold") {
|
||||
popUpTo("auth") { inclusive = true }
|
||||
}
|
||||
},
|
||||
viewModel = authViewModel
|
||||
)
|
||||
}
|
||||
|
||||
composable("home_scaffold") {
|
||||
HomeScaffold(navController, sessionManager)
|
||||
}
|
||||
|
||||
composable(
|
||||
route = "add_edit_transaction?transactionId={transactionId}",
|
||||
arguments = listOf(
|
||||
navArgument("transactionId") {
|
||||
type = NavType.IntType
|
||||
defaultValue = -1
|
||||
}
|
||||
)
|
||||
) { backStackEntry ->
|
||||
val transactionId = backStackEntry.arguments?.getInt("transactionId")?.takeIf { it != -1 }
|
||||
AddEditTransactionScreen(
|
||||
transactionId = transactionId,
|
||||
onNavigateBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun HomeScaffold(rootNavController: androidx.navigation.NavController, sessionManager: SessionManager) {
|
||||
val bottomNavController = rememberNavController()
|
||||
val items = listOf(Screen.Main, Screen.Stats, Screen.Planning, Screen.Profile)
|
||||
|
||||
Scaffold(
|
||||
bottomBar = {
|
||||
NavigationBar {
|
||||
val navBackStackEntry by bottomNavController.currentBackStackEntryAsState()
|
||||
val currentDestination = navBackStackEntry?.destination
|
||||
items.forEach { screen ->
|
||||
NavigationBarItem(
|
||||
icon = { Icon(screen.icon, contentDescription = null) },
|
||||
label = { Text(screen.title) },
|
||||
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
|
||||
onClick = {
|
||||
bottomNavController.navigate(screen.route) {
|
||||
popUpTo(bottomNavController.graph.findStartDestination().id) {
|
||||
saveState = true
|
||||
}
|
||||
launchSingleTop = true
|
||||
restoreState = true
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
) { innerPadding ->
|
||||
NavHost(
|
||||
navController = bottomNavController,
|
||||
startDestination = Screen.Main.route,
|
||||
modifier = Modifier.padding(innerPadding)
|
||||
) {
|
||||
composable(Screen.Main.route) {
|
||||
MainScreen(
|
||||
onAddTransaction = {
|
||||
rootNavController.navigate("add_edit_transaction")
|
||||
},
|
||||
onEditTransaction = { id ->
|
||||
rootNavController.navigate("add_edit_transaction?transactionId=$id")
|
||||
}
|
||||
)
|
||||
}
|
||||
composable(Screen.Stats.route) {
|
||||
StatsScreen()
|
||||
}
|
||||
composable(Screen.Planning.route) {
|
||||
PlanningScreen()
|
||||
}
|
||||
composable(Screen.Profile.route) {
|
||||
ProfileScreen(onLogout = {
|
||||
sessionManager.clearSession()
|
||||
rootNavController.navigate("auth") {
|
||||
popUpTo("home_scaffold") { inclusive = true }
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ProfileScreen(onLogout: () -> Unit) {
|
||||
Scaffold(
|
||||
topBar = { TopAppBar(title = { Text("Профиль") }) }
|
||||
) { padding ->
|
||||
androidx.compose.foundation.layout.Column(
|
||||
modifier = Modifier
|
||||
.padding(padding)
|
||||
.padding(16.dp)
|
||||
.fillMaxSize(),
|
||||
horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally,
|
||||
verticalArrangement = androidx.compose.foundation.layout.Arrangement.Center
|
||||
) {
|
||||
Button(
|
||||
onClick = onLogout,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)
|
||||
) {
|
||||
Text("Выйти из аккаунта")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
app/src/main/java/com/example/budget/network/ApiClient.kt
Normal file
52
app/src/main/java/com/example/budget/network/ApiClient.kt
Normal file
@@ -0,0 +1,52 @@
|
||||
package com.example.budget.network
|
||||
|
||||
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
|
||||
import kotlinx.serialization.json.Json
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import retrofit2.Retrofit
|
||||
|
||||
object ApiClient {
|
||||
|
||||
private const val BASE_URL = "https://tube.buhit.uz/"
|
||||
|
||||
private var sessionManager: SessionManager? = null
|
||||
|
||||
fun init(manager: SessionManager) {
|
||||
sessionManager = manager
|
||||
}
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
}
|
||||
|
||||
private val loggingInterceptor = HttpLoggingInterceptor().apply {
|
||||
level = HttpLoggingInterceptor.Level.BODY
|
||||
}
|
||||
|
||||
private val authInterceptor = Interceptor { chain ->
|
||||
val originalRequest = chain.request()
|
||||
val builder: Request.Builder = originalRequest.newBuilder()
|
||||
sessionManager?.getAuthToken()?.let {
|
||||
builder.header("Authorization", "Bearer $it")
|
||||
}
|
||||
chain.proceed(builder.build())
|
||||
}
|
||||
|
||||
private val okHttpClient = OkHttpClient.Builder()
|
||||
.addInterceptor(loggingInterceptor)
|
||||
.addInterceptor(authInterceptor)
|
||||
.build()
|
||||
|
||||
val apiService: BudgetApiService by lazy {
|
||||
Retrofit.Builder()
|
||||
.baseUrl(BASE_URL)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
|
||||
.build()
|
||||
.create(BudgetApiService::class.java)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.example.budget.network
|
||||
|
||||
import retrofit2.http.*
|
||||
|
||||
interface BudgetApiService {
|
||||
|
||||
@POST("/api/auth/login")
|
||||
suspend fun login(@Body request: LoginRequest): TokenResponse
|
||||
|
||||
// Transactions
|
||||
@GET("/api/transactions")
|
||||
suspend fun getTransactions(@Query("limit") limit: Int = 100): List<TransactionResponse>
|
||||
|
||||
@GET("/api/transactions/{id}")
|
||||
suspend fun getTransaction(@Path("id") id: Int): TransactionResponse
|
||||
|
||||
@POST("/api/transactions")
|
||||
suspend fun createTransaction(@Body transaction: TransactionCreate): TransactionResponse
|
||||
|
||||
@PATCH("/api/transactions/{id}")
|
||||
suspend fun updateTransaction(@Path("id") id: Int, @Body transaction: TransactionUpdate): TransactionResponse
|
||||
|
||||
@DELETE("/api/transactions/{id}")
|
||||
suspend fun deleteTransaction(@Path("id") id: Int)
|
||||
|
||||
@GET("/api/transactions/stats")
|
||||
suspend fun getStats(
|
||||
@Query("start_date") startDate: String? = null,
|
||||
@Query("end_date") endDate: String? = null
|
||||
): StatsResponse
|
||||
|
||||
// Categories
|
||||
@GET("/api/categories")
|
||||
suspend fun getCategories(@Query("type") type: String? = null): List<CategoryResponse>
|
||||
|
||||
// Wallets
|
||||
@GET("/api/wallets")
|
||||
suspend fun getWallets(): List<WalletResponse>
|
||||
|
||||
@POST("/api/wallets/transfer")
|
||||
suspend fun transferMoney(@Body request: WalletTransferRequest)
|
||||
|
||||
// Debts
|
||||
@GET("/api/debts")
|
||||
suspend fun getDebts(): List<DebtResponse>
|
||||
|
||||
// Planned Payments
|
||||
@GET("/api/planned_payments")
|
||||
suspend fun getPlannedPayments(): List<PlannedPaymentResponse>
|
||||
}
|
||||
138
app/src/main/java/com/example/budget/network/NetworkModels.kt
Normal file
138
app/src/main/java/com/example/budget/network/NetworkModels.kt
Normal file
@@ -0,0 +1,138 @@
|
||||
package com.example.budget.network
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.SerialName
|
||||
|
||||
@Serializable
|
||||
data class LoginRequest(
|
||||
val username: String,
|
||||
val password: String
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TokenResponse(
|
||||
val token: String,
|
||||
val user: UserResponse? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class UserResponse(
|
||||
val id: Int,
|
||||
val username: String? = null,
|
||||
@SerialName("telegram_id") val telegramId: Long? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TransactionResponse(
|
||||
val id: Int,
|
||||
val amount: Double,
|
||||
val type: String, // "expense" or "income"
|
||||
val date: String,
|
||||
val comment: String? = null,
|
||||
val currency: String,
|
||||
@SerialName("category_id") val categoryId: Int? = null,
|
||||
@SerialName("wallet_id") val walletId: Int? = null,
|
||||
@SerialName("category_name") val categoryName: String? = null,
|
||||
@SerialName("tag_name") val tagName: String? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TransactionCreate(
|
||||
val amount: Double,
|
||||
@SerialName("category_id") val categoryId: Int? = null,
|
||||
val type: String,
|
||||
val date: String,
|
||||
val comment: String? = null,
|
||||
val currency: String = "UZS",
|
||||
@SerialName("wallet_id") val walletId: Int? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TransactionUpdate(
|
||||
val amount: Double? = null,
|
||||
@SerialName("category_id") val categoryId: Int? = null,
|
||||
val type: String? = null,
|
||||
val date: String? = null,
|
||||
val comment: String? = null,
|
||||
val currency: String? = null,
|
||||
@SerialName("wallet_id") val walletId: Int? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CategoryResponse(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val type: String
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class WalletResponse(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val balance: Double,
|
||||
val currency: String,
|
||||
@SerialName("is_default") val isDefault: Boolean = false
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class WalletTransferRequest(
|
||||
@SerialName("from_wallet_id") val fromWalletId: Int,
|
||||
@SerialName("to_wallet_id") val toWalletId: Int,
|
||||
val amount: Double
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DebtResponse(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val type: String, // "credit" or "debt"
|
||||
val amount: Double,
|
||||
val currency: String,
|
||||
@SerialName("due_date") val dueDate: String? = null,
|
||||
@SerialName("is_paid") val isPaid: Boolean = false
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PlannedPaymentResponse(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val amount: Double,
|
||||
val currency: String,
|
||||
val frequency: String,
|
||||
@SerialName("next_payment_date") val nextPaymentDate: String,
|
||||
@SerialName("category_id") val categoryId: Int? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class StatsResponse(
|
||||
@SerialName("total_balance_by_currency") val totalBalance: Map<String, Double>,
|
||||
@SerialName("period_by_currency") val periodStats: Map<String, PeriodStats> = emptyMap(),
|
||||
@SerialName("by_category") val byCategory: List<CategoryStat> = emptyList(),
|
||||
@SerialName("upcoming_payments") val upcomingPayments: List<UpcomingPayment> = emptyList()
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PeriodStats(
|
||||
@SerialName("total_income") val totalIncome: Double,
|
||||
@SerialName("total_expense") val totalExpense: Double,
|
||||
val balance: Double
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CategoryStat(
|
||||
@SerialName("category_id") val categoryId: Int?,
|
||||
@SerialName("category_name") val categoryName: String,
|
||||
val amount: Double,
|
||||
val type: String,
|
||||
val currency: String
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class UpcomingPayment(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val amount: Double,
|
||||
val currency: String,
|
||||
@SerialName("due_date") val dueDate: String,
|
||||
val type: String // "debt" or "planned_payment"
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.budget.network
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
|
||||
class SessionManager(context: Context) {
|
||||
private val prefs: SharedPreferences = context.getSharedPreferences("budget_prefs", Context.MODE_PRIVATE)
|
||||
|
||||
companion object {
|
||||
private const val AUTH_TOKEN = "auth_token"
|
||||
}
|
||||
|
||||
fun saveAuthToken(token: String) {
|
||||
prefs.edit().putString(AUTH_TOKEN, token).apply()
|
||||
}
|
||||
|
||||
fun getAuthToken(): String? {
|
||||
return prefs.getString(AUTH_TOKEN, null)
|
||||
}
|
||||
|
||||
fun clearSession() {
|
||||
prefs.edit().remove(AUTH_TOKEN).apply()
|
||||
}
|
||||
|
||||
fun hasToken(): Boolean {
|
||||
return getAuthToken() != null
|
||||
}
|
||||
}
|
||||
76
app/src/main/java/com/example/budget/ui/auth/AuthScreen.kt
Normal file
76
app/src/main/java/com/example/budget/ui/auth/AuthScreen.kt
Normal file
@@ -0,0 +1,76 @@
|
||||
package com.example.budget.ui.auth
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
|
||||
@Composable
|
||||
fun AuthScreen(
|
||||
onLoginSuccess: () -> Unit,
|
||||
viewModel: AuthViewModel = viewModel()
|
||||
) {
|
||||
var telegramId by remember { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
val authState by viewModel.authState.collectAsState()
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Text(text = "Авторизация", style = MaterialTheme.typography.headlineMedium)
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = telegramId,
|
||||
onValueChange = { telegramId = it },
|
||||
label = { Text("Telegram ID") },
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("Пароль") },
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
if (authState is AuthState.Loading) {
|
||||
CircularProgressIndicator()
|
||||
} else {
|
||||
Button(
|
||||
onClick = { viewModel.login(telegramId, password) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = telegramId.isNotBlank() && password.isNotBlank()
|
||||
) {
|
||||
Text("Войти")
|
||||
}
|
||||
}
|
||||
|
||||
if (authState is AuthState.Error) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text(
|
||||
text = (authState as AuthState.Error).message,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
|
||||
LaunchedEffect(authState) {
|
||||
if (authState is AuthState.Success) {
|
||||
onLoginSuccess()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.example.budget.ui.auth
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.budget.network.ApiClient
|
||||
import com.example.budget.network.LoginRequest
|
||||
import com.example.budget.network.SessionManager
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
sealed class AuthState {
|
||||
object Idle : AuthState()
|
||||
object Loading : AuthState()
|
||||
data class Success(val token: String) : AuthState()
|
||||
data class Error(val message: String) : AuthState()
|
||||
}
|
||||
|
||||
class AuthViewModel : ViewModel() {
|
||||
|
||||
private val _authState = MutableStateFlow<AuthState>(AuthState.Idle)
|
||||
val authState: StateFlow<AuthState> = _authState
|
||||
|
||||
// SessionManager будет инжектироваться через Hilt в будущем
|
||||
private var sessionManager: SessionManager? = null
|
||||
|
||||
fun init(manager: SessionManager) {
|
||||
sessionManager = manager
|
||||
}
|
||||
|
||||
fun login(telegramId: String, password: String) {
|
||||
viewModelScope.launch {
|
||||
_authState.value = AuthState.Loading
|
||||
try {
|
||||
val response = ApiClient.apiService.login(LoginRequest(telegramId, password))
|
||||
sessionManager?.saveAuthToken(response.token)
|
||||
_authState.value = AuthState.Success(response.token)
|
||||
} catch (e: Exception) {
|
||||
_authState.value = AuthState.Error(e.message ?: "Ошибка авторизации")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
118
app/src/main/java/com/example/budget/ui/main/MainScreen.kt
Normal file
118
app/src/main/java/com/example/budget/ui/main/MainScreen.kt
Normal file
@@ -0,0 +1,118 @@
|
||||
package com.example.budget.ui.main
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
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.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.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.example.budget.network.TransactionResponse
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun MainScreen(
|
||||
onAddTransaction: () -> Unit,
|
||||
onEditTransaction: (Int) -> Unit,
|
||||
viewModel: MainViewModel = viewModel()
|
||||
) {
|
||||
val state by viewModel.state.collectAsState()
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.loadData()
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(title = { Text("Мой Бюджет") })
|
||||
},
|
||||
floatingActionButton = {
|
||||
FloatingActionButton(onClick = onAddTransaction) {
|
||||
Icon(Icons.Default.Add, contentDescription = "Добавить транзакцию")
|
||||
}
|
||||
}
|
||||
) { padding ->
|
||||
Column(modifier = Modifier.padding(padding)) {
|
||||
when (val currentState = state) {
|
||||
is MainState.Loading -> {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
is MainState.Success -> {
|
||||
BalanceHeader(currentState.stats.totalBalance)
|
||||
TransactionList(currentState.transactions, onEditTransaction)
|
||||
}
|
||||
is MainState.Error -> {
|
||||
Text("Ошибка: ${currentState.message}", color = Color.Red, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun BalanceHeader(balances: Map<String, Double>) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text("Общий баланс:", style = MaterialTheme.typography.titleMedium)
|
||||
balances.forEach { (currency, amount) ->
|
||||
Text(
|
||||
text = String.format("%,.2f %s", amount, currency),
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun TransactionList(transactions: List<TransactionResponse>, onEditTransaction: (Int) -> Unit) {
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(transactions) { transaction ->
|
||||
TransactionItem(transaction) {
|
||||
onEditTransaction(transaction.id)
|
||||
}
|
||||
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun TransactionItem(transaction: TransactionResponse, onClick: () -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(16.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text(text = transaction.categoryName ?: "Без категории", fontWeight = FontWeight.SemiBold)
|
||||
Text(text = transaction.date, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
val color = if (transaction.type == "income") Color(0xFF4CAF50) else Color(0xFFE91E63)
|
||||
val prefix = if (transaction.type == "income") "+" else "-"
|
||||
Text(
|
||||
text = String.format("%s%,.2f %s", prefix, transaction.amount, transaction.currency),
|
||||
color = color,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 18.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.example.budget.ui.main
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.budget.network.ApiClient
|
||||
import com.example.budget.network.TransactionResponse
|
||||
import com.example.budget.network.StatsResponse
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
sealed class MainState {
|
||||
object Loading : MainState()
|
||||
data class Success(val transactions: List<TransactionResponse>, val stats: StatsResponse) : MainState()
|
||||
data class Error(val message: String) : MainState()
|
||||
}
|
||||
|
||||
class MainViewModel : ViewModel() {
|
||||
|
||||
private val _state = MutableStateFlow<MainState>(MainState.Loading)
|
||||
val state: StateFlow<MainState> = _state
|
||||
|
||||
fun loadData() {
|
||||
viewModelScope.launch {
|
||||
_state.value = MainState.Loading
|
||||
try {
|
||||
// Токен добавляется автоматически через ApiClient.authInterceptor
|
||||
val transactions = ApiClient.apiService.getTransactions()
|
||||
val stats = ApiClient.apiService.getStats()
|
||||
_state.value = MainState.Success(transactions, stats)
|
||||
} catch (e: Exception) {
|
||||
_state.value = MainState.Error(e.message ?: "Ошибка загрузки данных")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.example.budget.ui.planning
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
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.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.example.budget.network.DebtResponse
|
||||
import com.example.budget.network.PlannedPaymentResponse
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PlanningScreen(viewModel: PlanningViewModel = viewModel()) {
|
||||
val state by viewModel.state.collectAsState()
|
||||
var selectedTab by remember { mutableIntStateOf(0) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.loadData()
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(title = { Text("Планирование") })
|
||||
}
|
||||
) { padding ->
|
||||
Column(modifier = Modifier.padding(padding)) {
|
||||
TabRow(selectedTabIndex = selectedTab) {
|
||||
Tab(selected = selectedTab == 0, onClick = { selectedTab = 0 }) {
|
||||
Text("Долги", modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
Tab(selected = selectedTab == 1, onClick = { selectedTab = 1 }) {
|
||||
Text("Платежи", modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
when (val s = state) {
|
||||
is PlanningState.Loading -> {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
is PlanningState.Error -> {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text("Ошибка: ${s.message}", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
is PlanningState.Success -> {
|
||||
if (selectedTab == 0) {
|
||||
DebtList(s.debts)
|
||||
} else {
|
||||
PlannedPaymentList(s.plannedPayments)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun DebtList(debts: List<DebtResponse>) {
|
||||
if (debts.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text("Нет долгов")
|
||||
}
|
||||
} else {
|
||||
LazyColumn(contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(debts) { debt ->
|
||||
DebtItem(debt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun DebtItem(debt: DebtResponse) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(debt.name, fontWeight = FontWeight.Bold, fontSize = 18.sp)
|
||||
Text(
|
||||
"${debt.amount} ${debt.currency}",
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = if (debt.type == "credit") Color(0xFF4CAF50) else Color(0xFFE91E63)
|
||||
)
|
||||
}
|
||||
Text("Тип: ${if (debt.type == "credit") "Мне должны" else "Я должен"}")
|
||||
debt.dueDate?.let { Text("Срок: $it") }
|
||||
if (debt.isPaid) {
|
||||
Text("Оплачено", color = Color(0xFF4CAF50), fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun PlannedPaymentList(payments: List<PlannedPaymentResponse>) {
|
||||
if (payments.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text("Нет плановых платежей")
|
||||
}
|
||||
} else {
|
||||
LazyColumn(contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(payments) { payment ->
|
||||
PlannedPaymentItem(payment)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun PlannedPaymentItem(payment: PlannedPaymentResponse) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(payment.name, fontWeight = FontWeight.Bold, fontSize = 18.sp)
|
||||
Text("${payment.amount} ${payment.currency}", fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Text("Частота: ${payment.frequency}")
|
||||
Text("След. платеж: ${payment.nextPaymentDate}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.example.budget.ui.planning
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.budget.network.ApiClient
|
||||
import com.example.budget.network.DebtResponse
|
||||
import com.example.budget.network.PlannedPaymentResponse
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
sealed class PlanningState {
|
||||
object Loading : PlanningState()
|
||||
data class Success(val debts: List<DebtResponse>, val plannedPayments: List<PlannedPaymentResponse>) : PlanningState()
|
||||
data class Error(val message: String) : PlanningState()
|
||||
}
|
||||
|
||||
class PlanningViewModel : ViewModel() {
|
||||
|
||||
private val _state = MutableStateFlow<PlanningState>(PlanningState.Loading)
|
||||
val state: StateFlow<PlanningState> = _state
|
||||
|
||||
fun loadData() {
|
||||
viewModelScope.launch {
|
||||
_state.value = PlanningState.Loading
|
||||
try {
|
||||
val debts = ApiClient.apiService.getDebts()
|
||||
val plannedPayments = ApiClient.apiService.getPlannedPayments()
|
||||
_state.value = PlanningState.Success(debts, plannedPayments)
|
||||
} catch (e: Exception) {
|
||||
_state.value = PlanningState.Error(e.message ?: "Ошибка загрузки данных")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
161
app/src/main/java/com/example/budget/ui/stats/StatsScreen.kt
Normal file
161
app/src/main/java/com/example/budget/ui/stats/StatsScreen.kt
Normal file
@@ -0,0 +1,161 @@
|
||||
package com.example.budget.ui.stats
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
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.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.example.budget.network.CategoryStat
|
||||
import com.example.budget.network.UpcomingPayment
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun StatsScreen(viewModel: StatsViewModel = viewModel()) {
|
||||
val state by viewModel.state.collectAsState()
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.loadStats()
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = { TopAppBar(title = { Text("Анализ") }) }
|
||||
) { padding ->
|
||||
when (val s = state) {
|
||||
is StatsState.Loading -> {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
is StatsState.Error -> {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("Ошибка: ${s.message}", color = MaterialTheme.colorScheme.error)
|
||||
Button(onClick = { viewModel.loadStats() }) {
|
||||
Text("Повторить")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
is StatsState.Success -> {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.padding(padding)
|
||||
.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
item {
|
||||
Text("Расходы по категориям", style = MaterialTheme.typography.titleLarge)
|
||||
}
|
||||
|
||||
val expenses = s.stats.byCategory.filter { it.type == "expense" }
|
||||
if (expenses.isEmpty()) {
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
|
||||
) {
|
||||
Text(
|
||||
"Нет данных о расходах за этот месяц",
|
||||
modifier = Modifier.padding(16.dp),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
items(expenses) { stat ->
|
||||
CategoryStatItem(stat)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text("Ближайшие платежи", style = MaterialTheme.typography.titleLarge)
|
||||
}
|
||||
|
||||
if (s.stats.upcomingPayments.isEmpty()) {
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
|
||||
) {
|
||||
Text(
|
||||
"Нет запланированных платежей",
|
||||
modifier = Modifier.padding(16.dp),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
items(s.stats.upcomingPayments) { payment ->
|
||||
UpcomingPaymentItem(payment)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Button(
|
||||
onClick = { viewModel.loadStats() },
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp)
|
||||
) {
|
||||
Text("Обновить")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CategoryStatItem(stat: CategoryStat) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(stat.categoryName, fontWeight = FontWeight.Medium)
|
||||
Text(
|
||||
"${String.format("%,.2f", stat.amount)} ${stat.currency}",
|
||||
color = Color(0xFFE91E63),
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun UpcomingPaymentItem(payment: UpcomingPayment) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = if (payment.type == "debt")
|
||||
MaterialTheme.colorScheme.secondaryContainer
|
||||
else
|
||||
MaterialTheme.colorScheme.tertiaryContainer
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(payment.name, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"${String.format("%,.2f", payment.amount)} ${payment.currency}",
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"Дата: ${payment.dueDate} • ${if (payment.type == "debt") "Долг" else "План"}",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.example.budget.ui.stats
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.budget.network.ApiClient
|
||||
import com.example.budget.network.StatsResponse
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
sealed class StatsState {
|
||||
object Loading : StatsState()
|
||||
data class Success(val stats: StatsResponse) : StatsState()
|
||||
data class Error(val message: String) : StatsState()
|
||||
}
|
||||
|
||||
class StatsViewModel : ViewModel() {
|
||||
|
||||
private val _state = MutableStateFlow<StatsState>(StatsState.Loading)
|
||||
val state: StateFlow<StatsState> = _state
|
||||
|
||||
fun loadStats() {
|
||||
viewModelScope.launch {
|
||||
_state.value = StatsState.Loading
|
||||
try {
|
||||
val calendar = Calendar.getInstance()
|
||||
val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
|
||||
|
||||
// First day of current month
|
||||
calendar.set(Calendar.DAY_OF_MONTH, 1)
|
||||
val startDate = sdf.format(calendar.time)
|
||||
|
||||
// Last day of current month
|
||||
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH))
|
||||
val endDate = sdf.format(calendar.time)
|
||||
|
||||
val stats = ApiClient.apiService.getStats(startDate, endDate)
|
||||
_state.value = StatsState.Success(stats)
|
||||
} catch (e: Exception) {
|
||||
_state.value = StatsState.Error(e.message ?: "Ошибка загрузки статистики")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package com.example.budget.ui.transaction
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
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 androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddEditTransactionScreen(
|
||||
transactionId: Int? = null,
|
||||
onNavigateBack: () -> Unit,
|
||||
viewModel: AddEditTransactionViewModel = viewModel()
|
||||
) {
|
||||
val state by viewModel.state.collectAsState()
|
||||
val categories by viewModel.categories.collectAsState()
|
||||
val wallets by viewModel.wallets.collectAsState()
|
||||
val existingTransaction by viewModel.existingTransaction.collectAsState()
|
||||
|
||||
var amount by remember { mutableStateOf("") }
|
||||
var type by remember { mutableStateOf("expense") }
|
||||
var selectedCategoryId by remember { mutableStateOf<Int?>(null) }
|
||||
var selectedWalletId by remember { mutableStateOf<Int?>(null) }
|
||||
var comment by remember { mutableStateOf("") }
|
||||
var date by remember { mutableStateOf(SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())) }
|
||||
|
||||
var categoryExpanded by remember { mutableStateOf(false) }
|
||||
var walletExpanded by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(transactionId) {
|
||||
if (transactionId != null) {
|
||||
viewModel.loadTransaction(transactionId)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(existingTransaction) {
|
||||
existingTransaction?.let {
|
||||
amount = it.amount.toString()
|
||||
type = it.type
|
||||
selectedCategoryId = it.categoryId
|
||||
selectedWalletId = it.walletId
|
||||
comment = it.comment ?: ""
|
||||
date = it.date
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(if (transactionId == null) "Новая транзакция" else "Редактирование") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = "Назад")
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (transactionId != null) {
|
||||
IconButton(onClick = { viewModel.deleteTransaction(transactionId) }) {
|
||||
Icon(Icons.Default.Delete, contentDescription = "Удалить")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(padding)
|
||||
.padding(16.dp)
|
||||
.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
// Type Toggle
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
|
||||
FilterChip(
|
||||
selected = type == "expense",
|
||||
onClick = { type = "expense" },
|
||||
label = { Text("Расход") }
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
FilterChip(
|
||||
selected = type == "income",
|
||||
onClick = { type = "income" },
|
||||
label = { Text("Доход") }
|
||||
)
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = amount,
|
||||
onValueChange = { if (it.isEmpty() || it.toDoubleOrNull() != null) amount = it },
|
||||
label = { Text("Сумма") },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
|
||||
// Category Dropdown
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = categoryExpanded,
|
||||
onExpandedChange = { categoryExpanded = !categoryExpanded }
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = categories.find { it.id == selectedCategoryId }?.name ?: "Выберите категорию",
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text("Категория") },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = categoryExpanded) },
|
||||
modifier = Modifier.menuAnchor().fillMaxWidth()
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = categoryExpanded,
|
||||
onDismissRequest = { categoryExpanded = false }
|
||||
) {
|
||||
categories.filter { it.type == type }.forEach { category ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(category.name) },
|
||||
onClick = {
|
||||
selectedCategoryId = category.id
|
||||
categoryExpanded = false
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wallet Dropdown
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = walletExpanded,
|
||||
onExpandedChange = { walletExpanded = !walletExpanded }
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = wallets.find { it.id == selectedWalletId }?.name ?: "Выберите кошелек",
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text("Кошелек") },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = walletExpanded) },
|
||||
modifier = Modifier.menuAnchor().fillMaxWidth()
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = walletExpanded,
|
||||
onDismissRequest = { walletExpanded = false }
|
||||
) {
|
||||
wallets.forEach { wallet ->
|
||||
DropdownMenuItem(
|
||||
text = { Text("${wallet.name} (${wallet.currency})") },
|
||||
onClick = {
|
||||
selectedWalletId = wallet.id
|
||||
walletExpanded = false
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = comment,
|
||||
onValueChange = { comment = it },
|
||||
label = { Text("Комментарий") },
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
viewModel.saveTransaction(
|
||||
id = transactionId,
|
||||
amount = amount.toDoubleOrNull() ?: 0.0,
|
||||
type = type,
|
||||
categoryId = selectedCategoryId,
|
||||
walletId = selectedWalletId,
|
||||
comment = comment,
|
||||
date = date
|
||||
)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = amount.isNotBlank() && state !is AddEditState.Loading
|
||||
) {
|
||||
Text(if (state is AddEditState.Loading) "Сохранение..." else "Сохранить")
|
||||
}
|
||||
|
||||
if (state is AddEditState.Error) {
|
||||
Text(
|
||||
text = (state as AddEditState.Error).message,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
|
||||
LaunchedEffect(state) {
|
||||
if (state is AddEditState.Success) {
|
||||
onNavigateBack()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.example.budget.ui.transaction
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.budget.network.*
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
sealed class AddEditState {
|
||||
object Idle : AddEditState()
|
||||
object Loading : AddEditState()
|
||||
object Success : AddEditState()
|
||||
data class Error(val message: String) : AddEditState()
|
||||
}
|
||||
|
||||
class AddEditTransactionViewModel : ViewModel() {
|
||||
|
||||
private val _state = MutableStateFlow<AddEditState>(AddEditState.Idle)
|
||||
val state: StateFlow<AddEditState> = _state
|
||||
|
||||
private val _categories = MutableStateFlow<List<CategoryResponse>>(emptyList())
|
||||
val categories: StateFlow<List<CategoryResponse>> = _categories
|
||||
|
||||
private val _wallets = MutableStateFlow<List<WalletResponse>>(emptyList())
|
||||
val wallets: StateFlow<List<WalletResponse>> = _wallets
|
||||
|
||||
private val _existingTransaction = MutableStateFlow<TransactionResponse?>(null)
|
||||
val existingTransaction: StateFlow<TransactionResponse?> = _existingTransaction
|
||||
|
||||
init {
|
||||
loadMetadata()
|
||||
}
|
||||
|
||||
private fun loadMetadata() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_categories.value = ApiClient.apiService.getCategories()
|
||||
_wallets.value = ApiClient.apiService.getWallets()
|
||||
} catch (e: Exception) {
|
||||
// Handle metadata load error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadTransaction(id: Int) {
|
||||
viewModelScope.launch {
|
||||
_state.value = AddEditState.Loading
|
||||
try {
|
||||
val transaction = ApiClient.apiService.getTransaction(id)
|
||||
_existingTransaction.value = transaction
|
||||
_state.value = AddEditState.Idle
|
||||
} catch (e: Exception) {
|
||||
_state.value = AddEditState.Error(e.message ?: "Ошибка загрузки транзакции")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun saveTransaction(
|
||||
id: Int?,
|
||||
amount: Double,
|
||||
type: String,
|
||||
categoryId: Int?,
|
||||
walletId: Int?,
|
||||
comment: String,
|
||||
date: String
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
_state.value = AddEditState.Loading
|
||||
try {
|
||||
if (id == null) {
|
||||
ApiClient.apiService.createTransaction(
|
||||
TransactionCreate(
|
||||
amount = amount,
|
||||
type = type,
|
||||
categoryId = categoryId,
|
||||
walletId = walletId,
|
||||
comment = comment,
|
||||
date = date
|
||||
)
|
||||
)
|
||||
} else {
|
||||
ApiClient.apiService.updateTransaction(
|
||||
id,
|
||||
TransactionUpdate(
|
||||
amount = amount,
|
||||
type = type,
|
||||
categoryId = categoryId,
|
||||
walletId = walletId,
|
||||
comment = comment,
|
||||
date = date
|
||||
)
|
||||
)
|
||||
}
|
||||
_state.value = AddEditState.Success
|
||||
} catch (e: Exception) {
|
||||
_state.value = AddEditState.Error(e.message ?: "Ошибка сохранения")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteTransaction(id: Int) {
|
||||
viewModelScope.launch {
|
||||
_state.value = AddEditState.Loading
|
||||
try {
|
||||
ApiClient.apiService.deleteTransaction(id)
|
||||
_state.value = AddEditState.Success
|
||||
} catch (e: Exception) {
|
||||
_state.value = AddEditState.Error(e.message ?: "Ошибка удаления")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
10
app/src/main/res/drawable/ic_launcher_background.xml
Normal file
10
app/src/main/res/drawable/ic_launcher_background.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#3DDC84"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
</vector>
|
||||
12
app/src/main/res/drawable/ic_launcher_foreground.xml
Normal file
12
app/src/main/res/drawable/ic_launcher_foreground.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<g android:scaleX="2.61" android:scaleY="2.61" android:translateX="22.68" android:translateY="22.68">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M13.5,3H7C5.34,3 4,4.34 4,6v10c0,1.66 1.34,3 3,3h2v2h2v-2h2v-2H9V5h4.5C14.33,5 15,5.67 15,6.5S14.33,8 13.5,8H9v2h3.5c1.66,0 3,1.34 3,3s-1.34,3 -3,3H7v2h6.5c2.76,0 5,-2.24 5,-5s-2.24,-5 -5,-5z" />
|
||||
</g>
|
||||
</vector>
|
||||
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Normal file
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
Normal file
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
11
app/src/main/res/values/colors.xml
Normal file
11
app/src/main/res/values/colors.xml
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
<color name="ic_launcher_background">#3DDC84</color>
|
||||
</resources>
|
||||
Reference in New Issue
Block a user