|
| 1 | +package to.bitkit.utils.timedsheets.sheets |
| 2 | + |
| 3 | +import kotlinx.coroutines.flow.first |
| 4 | +import to.bitkit.data.SettingsStore |
| 5 | +import to.bitkit.ext.nowMillis |
| 6 | +import to.bitkit.repositories.CurrencyRepo |
| 7 | +import to.bitkit.repositories.WalletRepo |
| 8 | +import to.bitkit.ui.components.TimedSheetType |
| 9 | +import to.bitkit.utils.Logger |
| 10 | +import to.bitkit.utils.timedsheets.ONE_DAY_ASK_INTERVAL_MILLIS |
| 11 | +import to.bitkit.utils.timedsheets.TimedSheetItem |
| 12 | +import to.bitkit.utils.timedsheets.checkTimeout |
| 13 | +import java.math.BigDecimal |
| 14 | +import javax.inject.Inject |
| 15 | +import kotlin.time.ExperimentalTime |
| 16 | + |
| 17 | +class HighBalanceTimedSheet @Inject constructor( |
| 18 | + private val settingsStore: SettingsStore, |
| 19 | + private val walletRepo: WalletRepo, |
| 20 | + private val currencyRepo: CurrencyRepo, |
| 21 | +) : TimedSheetItem { |
| 22 | + override val type = TimedSheetType.HIGH_BALANCE |
| 23 | + override val priority = 1 |
| 24 | + |
| 25 | + override suspend fun shouldShow(): Boolean { |
| 26 | + val settings = settingsStore.data.first() |
| 27 | + |
| 28 | + val totalOnChainSats = walletRepo.balanceState.value.totalSats |
| 29 | + val balanceUsd = satsToUsd(totalOnChainSats) ?: return false |
| 30 | + val thresholdReached = balanceUsd > BigDecimal(BALANCE_THRESHOLD_USD) |
| 31 | + |
| 32 | + if (!thresholdReached) { |
| 33 | + settingsStore.update { it.copy(balanceWarningTimes = 0) } |
| 34 | + return false |
| 35 | + } |
| 36 | + |
| 37 | + val belowMaxWarnings = settings.balanceWarningTimes < MAX_WARNINGS |
| 38 | + |
| 39 | + return checkTimeout( |
| 40 | + lastIgnoredMillis = settings.balanceWarningIgnoredMillis, |
| 41 | + intervalMillis = ONE_DAY_ASK_INTERVAL_MILLIS, |
| 42 | + additionalCondition = belowMaxWarnings |
| 43 | + ) |
| 44 | + } |
| 45 | + |
| 46 | + override suspend fun onShown() { |
| 47 | + Logger.debug("High balance sheet shown", context = TAG) |
| 48 | + } |
| 49 | + |
| 50 | + @OptIn(ExperimentalTime::class) |
| 51 | + override suspend fun onDismissed() { |
| 52 | + val currentTime = nowMillis() |
| 53 | + settingsStore.update { |
| 54 | + it.copy( |
| 55 | + balanceWarningTimes = it.balanceWarningTimes + 1, |
| 56 | + balanceWarningIgnoredMillis = currentTime, |
| 57 | + ) |
| 58 | + } |
| 59 | + Logger.debug("High balance sheet dismissed", context = TAG) |
| 60 | + } |
| 61 | + |
| 62 | + private fun satsToUsd(sats: ULong): BigDecimal? { |
| 63 | + val converted = currencyRepo.convertSatsToFiat(sats = sats.toLong(), currency = "USD").getOrNull() |
| 64 | + return converted?.value |
| 65 | + } |
| 66 | + |
| 67 | + companion object { |
| 68 | + private const val TAG = "HighBalanceTimedSheet" |
| 69 | + private const val BALANCE_THRESHOLD_USD = 500L |
| 70 | + private const val MAX_WARNINGS = 3 |
| 71 | + } |
| 72 | +} |
0 commit comments