package com.yaros.shiftmanager import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import androidx.room.* import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import android.content.Context import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import java.util.* import javax.inject.Inject @Entity(tableName = "incomes") data class Income( @PrimaryKey val id: String = UUID.randomUUID().toString(), val shiftId: String, val amount: Double, val type: IncomeType, val date: Date ) enum class IncomeType { REGULAR, TIPS, BONUS } @Dao interface IncomeDao { @Query("SELECT * FROM incomes") fun getAllIncomes(): Flow> @Query("SELECT * FROM incomes WHERE date BETWEEN :startDate AND :endDate") fun getIncomesForPeriod(startDate: Date, endDate: Date): Flow> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertIncome(income: Income) @Update suspend fun updateIncome(income: Income) @Delete suspend fun deleteIncome(income: Income) } class IncomeRepository @Inject constructor(private val incomeDao: IncomeDao) { val allIncomes: Flow> = incomeDao.getAllIncomes() fun getIncomesForPeriod(startDate: Date, endDate: Date): Flow> { return incomeDao.getIncomesForPeriod(startDate, endDate) } suspend fun insertIncome(income: Income) { incomeDao.insertIncome(income) } suspend fun updateIncome(income: Income) { incomeDao.updateIncome(income) } suspend fun deleteIncome(income: Income) { incomeDao.deleteIncome(income) } } @HiltViewModel class IncomeViewModel @Inject constructor(private val repository: IncomeRepository) : ViewModel() { val allIncomes: LiveData> = repository.allIncomes.asLiveData() fun getIncomesForPeriod(startDate: Date, endDate: Date): LiveData> { return repository.getIncomesForPeriod(startDate, endDate).asLiveData() } fun insertIncome(income: Income) = viewModelScope.launch { repository.insertIncome(income) } fun updateIncome(income: Income) = viewModelScope.launch { repository.updateIncome(income) } fun deleteIncome(income: Income) = viewModelScope.launch { repository.deleteIncome(income) } }