update the dashboard

This commit is contained in:
Meghdad committed 2026-06-23 01:55:43 +03:30
1 parent 74f70ae3e7
commit f5971f2fb2
1 file changed
+615 -41
@@ -2,6 +2,7 @@ package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -36,7 +37,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
@@ -46,6 +46,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.AccountSummary import net.rodakot.remaining.data.AccountSummary
import net.rodakot.remaining.domain.AccountStatus import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.asTrafficDisplay import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.ui.RemainingUiState import net.rodakot.remaining.ui.RemainingUiState
import net.rodakot.remaining.ui.components.MetricPill import net.rodakot.remaining.ui.components.MetricPill
@@ -60,6 +61,7 @@ import net.rodakot.remaining.ui.components.UsageBar
import net.rodakot.remaining.ui.components.accentColor import net.rodakot.remaining.ui.components.accentColor
import net.rodakot.remaining.ui.components.formatTimestamp import net.rodakot.remaining.ui.components.formatTimestamp
import net.rodakot.remaining.ui.components.remainingProgress import net.rodakot.remaining.ui.components.remainingProgress
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -71,6 +73,8 @@ fun DashboardScreen(
onPrepareCaptcha: (String) -> Unit, onPrepareCaptcha: (String) -> Unit,
onOpenSettings: () -> Unit onOpenSettings: () -> Unit
) { ) {
val insights = buildDashboardInsights(state.accounts, System.currentTimeMillis())
RemainingBackground { RemainingBackground {
Scaffold( Scaffold(
containerColor = Color.Transparent, containerColor = Color.Transparent,
@@ -84,7 +88,7 @@ fun DashboardScreen(
Column { Column {
Text("Remaining", fontWeight = FontWeight.Bold) Text("Remaining", fontWeight = FontWeight.Bold)
Text( Text(
"${state.accounts.size} connected account${if (state.accounts.size == 1) "" else "s"}", insights.topBarSummary,
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -117,16 +121,35 @@ fun DashboardScreen(
verticalArrangement = Arrangement.spacedBy(14.dp) verticalArrangement = Arrangement.spacedBy(14.dp)
) { ) {
item { item {
OverviewCard(accounts = state.accounts) CommandCenterCard(
insights = insights,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
}
item {
SignalGrid(insights = insights)
}
item {
WatchlistPanel(
watchItems = insights.watchItems,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
}
item {
ProviderBreakdown(providerStats = insights.providerStats)
} }
item { item {
SectionHeader( SectionHeader(
title = "Accounts", title = "Accounts by priority",
subtitle = "Tap an account for packages, refresh settings, and history.", subtitle = "Sorted by action needed, low data, expiry, and refresh freshness.",
modifier = Modifier.padding(top = 4.dp) modifier = Modifier.padding(top = 4.dp)
) )
} }
items(state.accounts, key = { it.id }) { account -> items(insights.sortedAccounts, key = { it.id }) { account ->
AccountCard( AccountCard(
account = account, account = account,
busy = state.action.busyAccountIds.contains(account.id), busy = state.action.busyAccountIds.contains(account.id),
@@ -165,7 +188,7 @@ private fun EmptyDashboard(modifier: Modifier = Modifier, onAddAccount: () -> Un
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
"Connect MCI, Webotel, or TCI and the app will keep quota, refresh health, and alerts in one clean view.", "Connect MCI, Webotel, or TCI and the dashboard will show quota risk, stale refreshes, expiry warnings, and the next useful action.",
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(top = 8.dp) modifier = Modifier.padding(top = 8.dp)
@@ -181,20 +204,13 @@ private fun EmptyDashboard(modifier: Modifier = Modifier, onAddAccount: () -> Un
} }
@Composable @Composable
private fun OverviewCard(accounts: List<AccountSummary>) { private fun CommandCenterCard(
val knownRemaining = remember(accounts) { accounts.mapNotNull { it.remainingBytes } } insights: DashboardInsights,
val totalRemaining = remember(knownRemaining) { knownRemaining.takeIf { it.isNotEmpty() }?.sum() } onOpenAccount: (String) -> Unit,
val knownTotal = remember(accounts) { accounts.mapNotNull { it.totalBytes } } onRefreshAccount: (String) -> Unit,
val totalQuota = remember(knownTotal) { knownTotal.takeIf { it.isNotEmpty() }?.sum() } onPrepareCaptcha: (String) -> Unit
val issueCount = accounts.count { ) {
it.status == AccountStatus.ERROR || val focus = insights.focus
it.status == AccountStatus.CAPTCHA_REQUIRED ||
it.status == AccountStatus.NEEDS_AUTH
}
val activeCount = accounts.count { it.status == AccountStatus.ACTIVE }
val nextRefresh = accounts.mapNotNull { it.nextRefreshAt }.minOrNull()
val progress = remainingProgress(totalRemaining, totalQuota)
Surface( Surface(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(8.dp), shape = RoundedCornerShape(8.dp),
@@ -208,7 +224,7 @@ private fun OverviewCard(accounts: List<AccountSummary>) {
Brush.linearGradient( Brush.linearGradient(
listOf( listOf(
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.88f), MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.88f),
MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.70f), MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.62f),
MaterialTheme.colorScheme.surfaceContainer.copy(alpha = 0.94f) MaterialTheme.colorScheme.surfaceContainer.copy(alpha = 0.94f)
) )
) )
@@ -219,42 +235,260 @@ private fun OverviewCard(accounts: List<AccountSummary>) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text( Text(
"Live quota", "Today’s focus",
color = MaterialTheme.colorScheme.onPrimaryContainer, color = MaterialTheme.colorScheme.onPrimaryContainer,
style = MaterialTheme.typography.labelLarge style = MaterialTheme.typography.labelLarge
) )
Text( Text(
totalRemaining?.asTrafficDisplay() ?: "Unknown", focus.title,
style = MaterialTheme.typography.displaySmall, style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onPrimaryContainer color = MaterialTheme.colorScheme.onSurface
) )
Text( Text(
"Remaining across every connected service", focus.message,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodyMedium style = MaterialTheme.typography.bodyMedium
) )
} }
Spacer(modifier = Modifier.width(12.dp))
QuotaRing( QuotaRing(
progress = progress, progress = insights.quotaProgress,
value = totalRemaining?.asTrafficDisplay() ?: "--", value = insights.availablePercentLabel,
label = "left" label = "available",
modifier = Modifier.size(132.dp)
) )
} }
QuotaBar(progress = progress) QuotaBar(progress = insights.quotaProgress)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Active", activeCount.toString(), Modifier.weight(1f)) MetricPill("Tracked left", insights.totalRemaining?.asTrafficDisplay() ?: "Unknown", Modifier.weight(1f))
MetricPill("Needs action", issueCount.toString(), Modifier.weight(1f)) MetricPill("Ratio data", insights.quotaCoverageLabel, Modifier.weight(1f))
} }
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { focus.account?.let { account ->
MetricPill("Accounts", accounts.size.toString(), Modifier.weight(1f)) FocusActionButton(
MetricPill("Next refresh", nextRefresh.formatTimestamp(), Modifier.weight(1f)) focus = focus,
account = account,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
} }
} }
} }
} }
} }
@Composable
private fun FocusActionButton(
focus: DashboardFocus,
account: AccountSummary,
onOpenAccount: (String) -> Unit,
onRefreshAccount: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit
) {
Button(
onClick = {
when (focus.action) {
FocusAction.CAPTCHA -> onPrepareCaptcha(account.id)
FocusAction.REFRESH -> onRefreshAccount(account.id)
FocusAction.OPEN -> onOpenAccount(account.id)
}
},
enabled = account.enabled || focus.action != FocusAction.REFRESH,
modifier = Modifier.fillMaxWidth()
) {
Text(focus.actionLabel)
}
}
@Composable
private fun SignalGrid(insights: DashboardInsights) {
ModernPanel {
SectionHeader(
title = "Health signals",
subtitle = "Counts that should change your next action, not vanity totals."
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Needs action", insights.attentionCount.toString(), Modifier.weight(1f))
MetricPill("Low data", insights.lowDataAccounts.size.toString(), Modifier.weight(1f))
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Expiring soon", insights.expiringAccounts.size.toString(), Modifier.weight(1f))
MetricPill("Stale refresh", insights.staleAccounts.size.toString(), Modifier.weight(1f))
}
insights.nextRefreshAccount?.let {
Text(
"Next scheduled refresh: ${it.displayName} · ${it.nextRefreshAt.formatTimestamp()}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
}
}
@Composable
private fun WatchlistPanel(
watchItems: List<WatchItem>,
onOpenAccount: (String) -> Unit,
onRefreshAccount: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit
) {
ModernPanel {
SectionHeader(
title = "Watchlist",
subtitle = if (watchItems.isEmpty()) {
"No account needs immediate attention."
} else {
"The most important account-level issues, ordered by urgency."
}
)
if (watchItems.isEmpty()) {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
contentColor = MaterialTheme.colorScheme.primary,
modifier = Modifier.fillMaxWidth()
) {
Text(
"All clear. Your connected accounts are healthy enough for now.",
modifier = Modifier.padding(12.dp),
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold
)
}
} else {
watchItems.take(4).forEach { item ->
WatchItemRow(
item = item,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
}
}
}
}
@Composable
private fun WatchItemRow(
item: WatchItem,
onOpenAccount: (String) -> Unit,
onRefreshAccount: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit
) {
val account = item.account
val accent = item.type.color()
Surface(
modifier = Modifier
.fillMaxWidth()
.clickable { onOpenAccount(account.id) },
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.surfaceContainerHigh.copy(alpha = 0.62f),
contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, accent.copy(alpha = 0.34f))
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(verticalAlignment = Alignment.Top, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(item.title, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleSmall)
Text(
item.detail,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
Spacer(modifier = Modifier.width(8.dp))
ServiceBadge(account.serviceType)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
account.displayName,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
when (item.type) {
WatchType.CAPTCHA -> OutlinedButton(onClick = { onPrepareCaptcha(account.id) }) {
Text("Captcha")
}
WatchType.STALE -> OutlinedButton(
onClick = { onRefreshAccount(account.id) },
enabled = account.enabled
) {
Text("Refresh")
}
else -> OutlinedButton(onClick = { onOpenAccount(account.id) }) {
Text("Open")
}
}
}
}
}
}
@Composable
private fun ProviderBreakdown(providerStats: List<ProviderStat>) {
ModernPanel {
SectionHeader(
title = "Provider breakdown",
subtitle = "Where your known quota and service issues are concentrated."
)
providerStats.forEach { stat ->
ProviderRow(stat)
}
}
}
@Composable
private fun ProviderRow(stat: ProviderStat) {
val accent = stat.serviceType.accentColor()
Column(verticalArrangement = Arrangement.spacedBy(7.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
ServiceBadge(stat.serviceType)
Spacer(modifier = Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(stat.serviceType.displayName, fontWeight = FontWeight.SemiBold)
Text(
"${stat.accountCount} account${if (stat.accountCount == 1) "" else "s"} · ${stat.remainingLabel}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
if (stat.issueCount > 0) {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.error.copy(alpha = 0.12f),
contentColor = MaterialTheme.colorScheme.error
) {
Text(
"${stat.issueCount} issue${if (stat.issueCount == 1) "" else "s"}",
style = MaterialTheme.typography.labelSmall,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 5.dp)
)
}
}
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(8.dp)
.background(MaterialTheme.colorScheme.surfaceContainerHighest, RoundedCornerShape(8.dp))
) {
Box(
modifier = Modifier
.fillMaxWidth(stat.quotaShare)
.height(8.dp)
.background(accent, RoundedCornerShape(8.dp))
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
private fun AccountCard( private fun AccountCard(
@@ -265,6 +499,7 @@ private fun AccountCard(
onPrepareCaptcha: () -> Unit onPrepareCaptcha: () -> Unit
) { ) {
val accent = account.serviceType.accentColor() val accent = account.serviceType.accentColor()
val signals = accountSignals(account, System.currentTimeMillis())
Card( Card(
onClick = onOpen, onClick = onOpen,
shape = RoundedCornerShape(8.dp), shape = RoundedCornerShape(8.dp),
@@ -352,6 +587,13 @@ private fun AccountCard(
totalBytes = account.totalBytes, totalBytes = account.totalBytes,
totalDisplay = account.totalDisplay totalDisplay = account.totalDisplay
) )
if (signals.isNotEmpty()) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
signals.take(2).forEach {
SignalPill(signal = it, modifier = Modifier.weight(1f))
}
}
}
account.lastErrorMessage?.let { account.lastErrorMessage?.let {
Surface( Surface(
shape = RoundedCornerShape(8.dp), shape = RoundedCornerShape(8.dp),
@@ -389,12 +631,344 @@ private fun AccountCard(
} }
} }
} }
Text( Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
"Last success: ${account.lastSuccessAt.formatTimestamp()}", MetricPill("Last success", account.lastSuccessAt.formatTimestamp(), Modifier.weight(1f))
color = MaterialTheme.colorScheme.onSurfaceVariant, MetricPill("Next", account.nextRefreshAt.formatTimestamp(), Modifier.weight(1f))
style = MaterialTheme.typography.bodySmall }
)
} }
} }
} }
} }
@Composable
private fun SignalPill(signal: AccountSignal, modifier: Modifier = Modifier) {
val color = signal.type.color()
Surface(
modifier = modifier,
shape = RoundedCornerShape(8.dp),
color = color.copy(alpha = 0.12f),
contentColor = color,
border = BorderStroke(1.dp, color.copy(alpha = 0.30f))
) {
Text(
signal.label,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
private data class DashboardInsights(
val totalRemaining: Long?,
val totalQuota: Long?,
val quotaProgress: Float?,
val knownQuotaAccounts: Int,
val attentionCount: Int,
val lowDataAccounts: List<AccountSummary>,
val expiringAccounts: List<AccountSummary>,
val staleAccounts: List<AccountSummary>,
val nextRefreshAccount: AccountSummary?,
val providerStats: List<ProviderStat>,
val watchItems: List<WatchItem>,
val sortedAccounts: List<AccountSummary>,
val focus: DashboardFocus
) {
val topBarSummary: String =
if (attentionCount > 0) {
"$attentionCount account${if (attentionCount == 1) "" else "s"} need attention"
} else {
"${sortedAccounts.size} account${if (sortedAccounts.size == 1) "" else "s"} monitored"
}
val quotaCoverageLabel: String =
"$knownQuotaAccounts/${sortedAccounts.size} accounts"
val availablePercentLabel: String =
quotaProgress?.let { "${String.format(Locale.US, "%.0f", it * 100f)}%" } ?: "Unknown"
}
private data class DashboardFocus(
val title: String,
val message: String,
val account: AccountSummary?,
val action: FocusAction,
val actionLabel: String
)
private enum class FocusAction {
CAPTCHA,
REFRESH,
OPEN
}
private data class ProviderStat(
val serviceType: ServiceType,
val accountCount: Int,
val issueCount: Int,
val remainingBytes: Long?,
val quotaShare: Float
) {
val remainingLabel: String = remainingBytes?.asTrafficDisplay() ?: "unknown quota"
}
private data class WatchItem(
val account: AccountSummary,
val title: String,
val detail: String,
val type: WatchType
)
private data class AccountSignal(
val label: String,
val type: WatchType
)
private enum class WatchType {
ERROR,
CAPTCHA,
AUTH,
LOW_DATA,
EXPIRY,
STALE,
DISABLED
}
private fun buildDashboardInsights(accounts: List<AccountSummary>, now: Long): DashboardInsights {
val knownRemaining = accounts.mapNotNull { it.remainingBytes }
val totalRemaining = knownRemaining.takeIf { it.isNotEmpty() }?.sum()
val quotaAccounts = accounts.filter {
it.remainingBytes != null && it.totalBytes != null && it.totalBytes > 0L
}
val quotaRemaining = quotaAccounts.mapNotNull { it.remainingBytes }.takeIf { it.isNotEmpty() }?.sum()
val totalQuota = quotaAccounts.mapNotNull { it.totalBytes }.takeIf { it.isNotEmpty() }?.sum()
val lowDataAccounts = accounts.filter { it.isLowData() }
val expiringAccounts = accounts.filter { it.isExpiringSoon(now) }
val staleAccounts = accounts.filter { it.isStale(now) }
val issueAccounts = accounts.filter { it.needsUserAction() || !it.enabled }
val nextRefreshAccount = accounts
.filter { it.enabled }
.mapNotNull { account -> account.nextRefreshAt?.let { account to it } }
.minByOrNull { it.second }
?.first
val providerStats = buildProviderStats(accounts, totalRemaining)
val watchItems = accounts
.flatMap { account -> accountWatchItems(account, now) }
.sortedByDescending { it.type.priority }
val sortedAccounts = accounts.sortedWith(
compareByDescending<AccountSummary> { accountPriority(it, now) }
.thenBy { it.displayName.lowercase(Locale.US) }
)
return DashboardInsights(
totalRemaining = totalRemaining,
totalQuota = totalQuota,
quotaProgress = remainingProgress(quotaRemaining, totalQuota),
knownQuotaAccounts = quotaAccounts.size,
attentionCount = issueAccounts.size,
lowDataAccounts = lowDataAccounts,
expiringAccounts = expiringAccounts,
staleAccounts = staleAccounts,
nextRefreshAccount = nextRefreshAccount,
providerStats = providerStats,
watchItems = watchItems,
sortedAccounts = sortedAccounts,
focus = buildFocus(
accounts = accounts,
watchItems = watchItems,
nextRefreshAccount = nextRefreshAccount,
quotaProgress = remainingProgress(quotaRemaining, totalQuota)
)
)
}
private fun buildProviderStats(accounts: List<AccountSummary>, totalRemaining: Long?): List<ProviderStat> =
ServiceType.entries.mapNotNull { serviceType ->
val serviceAccounts = accounts.filter { it.serviceType == serviceType }
if (serviceAccounts.isEmpty()) return@mapNotNull null
val remaining = serviceAccounts.mapNotNull { it.remainingBytes }.takeIf { it.isNotEmpty() }?.sum()
ProviderStat(
serviceType = serviceType,
accountCount = serviceAccounts.size,
issueCount = serviceAccounts.count { it.needsUserAction() || !it.enabled },
remainingBytes = remaining,
quotaShare = if (remaining != null && totalRemaining != null && totalRemaining > 0L) {
(remaining.toFloat() / totalRemaining.toFloat()).coerceIn(0.04f, 1f)
} else {
0.04f
}
)
}
private fun buildFocus(
accounts: List<AccountSummary>,
watchItems: List<WatchItem>,
nextRefreshAccount: AccountSummary?,
quotaProgress: Float?
): DashboardFocus {
val urgent = watchItems.firstOrNull()
if (urgent != null) {
val action = when (urgent.type) {
WatchType.CAPTCHA -> FocusAction.CAPTCHA
WatchType.STALE -> FocusAction.REFRESH
else -> FocusAction.OPEN
}
return DashboardFocus(
title = urgent.title,
message = "${urgent.account.displayName}: ${urgent.detail}",
account = urgent.account,
action = action,
actionLabel = when (action) {
FocusAction.CAPTCHA -> "Solve captcha"
FocusAction.REFRESH -> "Refresh ${urgent.account.displayName}"
FocusAction.OPEN -> "Open ${urgent.account.displayName}"
}
)
}
val lowest = accounts
.filter { it.remainingBytes != null }
.minByOrNull { it.remainingBytes ?: Long.MAX_VALUE }
if (lowest != null) {
return DashboardFocus(
title = "Lowest balance: ${lowest.remainingDisplay}",
message = "${lowest.displayName} has the least remaining quota. Known quota-ratio availability is ${quotaProgress?.let { "${String.format(Locale.US, "%.0f", it * 100f)}%" } ?: "unknown"}.",
account = lowest,
action = FocusAction.OPEN,
actionLabel = "Review lowest balance"
)
}
return DashboardFocus(
title = "Waiting for first usage snapshot",
message = nextRefreshAccount?.let {
"Next scheduled refresh is ${it.displayName} at ${it.nextRefreshAt.formatTimestamp()}."
} ?: "Refresh an account to populate quota, expiry, and health signals.",
account = nextRefreshAccount,
action = FocusAction.REFRESH,
actionLabel = nextRefreshAccount?.let { "Refresh ${it.displayName}" } ?: "Refresh account"
)
}
private fun accountWatchItems(account: AccountSummary, now: Long): List<WatchItem> {
val items = mutableListOf<WatchItem>()
when (account.status) {
AccountStatus.CAPTCHA_REQUIRED -> items += WatchItem(
account = account,
title = "Captcha blocks refresh",
detail = "Manual captcha is required before this account can update.",
type = WatchType.CAPTCHA
)
AccountStatus.NEEDS_AUTH -> items += WatchItem(
account = account,
title = "Sign-in required",
detail = "Credentials or session need attention.",
type = WatchType.AUTH
)
AccountStatus.ERROR -> items += WatchItem(
account = account,
title = "Refresh is failing",
detail = account.lastErrorMessage ?: "The last refresh failed.",
type = WatchType.ERROR
)
AccountStatus.ACTIVE,
AccountStatus.REFRESHING,
AccountStatus.DISABLED -> Unit
}
if (!account.enabled) {
items += WatchItem(
account = account,
title = "Account disabled",
detail = "Background refresh and alerts are paused.",
type = WatchType.DISABLED
)
}
if (account.isLowData()) {
items += WatchItem(
account = account,
title = "Low data threshold hit",
detail = "${account.remainingDisplay} is at or below ${account.lowDataThresholdMb} MB.",
type = WatchType.LOW_DATA
)
}
if (account.isExpiringSoon(now)) {
items += WatchItem(
account = account,
title = "Package expires soon",
detail = account.expiresAtText ?: "Package expiry is inside the warning window.",
type = WatchType.EXPIRY
)
}
if (account.isStale(now)) {
items += WatchItem(
account = account,
title = "Usage data is stale",
detail = "Last success: ${account.lastSuccessAt.formatTimestamp()}.",
type = WatchType.STALE
)
}
return items
}
private fun accountSignals(account: AccountSummary, now: Long): List<AccountSignal> =
buildList {
if (account.status == AccountStatus.CAPTCHA_REQUIRED) add(AccountSignal("Captcha", WatchType.CAPTCHA))
if (account.status == AccountStatus.ERROR) add(AccountSignal("Refresh failing", WatchType.ERROR))
if (account.status == AccountStatus.NEEDS_AUTH) add(AccountSignal("Sign-in needed", WatchType.AUTH))
if (!account.enabled) add(AccountSignal("Disabled", WatchType.DISABLED))
if (account.isLowData()) add(AccountSignal("Low data", WatchType.LOW_DATA))
if (account.isExpiringSoon(now)) add(AccountSignal("Expires soon", WatchType.EXPIRY))
if (account.isStale(now)) add(AccountSignal("Stale", WatchType.STALE))
}
private fun accountPriority(account: AccountSummary, now: Long): Int =
accountWatchItems(account, now).maxOfOrNull { it.type.priority } ?: 0
private fun AccountSummary.needsUserAction(): Boolean =
status == AccountStatus.ERROR ||
status == AccountStatus.CAPTCHA_REQUIRED ||
status == AccountStatus.NEEDS_AUTH
private fun AccountSummary.isLowData(): Boolean {
val remaining = remainingBytes ?: return false
return remaining <= lowDataThresholdMb * BYTES_PER_MB
}
private fun AccountSummary.isExpiringSoon(now: Long): Boolean {
val expiry = expiresAtMillis ?: return false
return expiry <= now + expiryThresholdDays * MILLIS_PER_DAY
}
private fun AccountSummary.isStale(now: Long): Boolean {
if (!enabled || status == AccountStatus.CAPTCHA_REQUIRED) return false
val lastSuccess = lastSuccessAt ?: return true
val allowedAge = refreshInterval.minutes * MILLIS_PER_MINUTE * 2
return now - lastSuccess > allowedAge
}
private val WatchType.priority: Int
get() = when (this) {
WatchType.CAPTCHA -> 70
WatchType.ERROR -> 65
WatchType.AUTH -> 60
WatchType.LOW_DATA -> 50
WatchType.EXPIRY -> 45
WatchType.STALE -> 30
WatchType.DISABLED -> 10
}
private fun WatchType.color(): Color =
when (this) {
WatchType.CAPTCHA -> Color(0xFFFFD166)
WatchType.ERROR -> Color(0xFFFF6B7A)
WatchType.AUTH -> Color(0xFFFF9F6E)
WatchType.LOW_DATA -> Color(0xFFFFD166)
WatchType.EXPIRY -> Color(0xFFFFB86B)
WatchType.STALE -> Color(0xFF8EEBFF)
WatchType.DISABLED -> Color(0xFF93A39A)
}
private const val BYTES_PER_MB = 1024L * 1024L
private const val MILLIS_PER_MINUTE = 60_000L
private const val MILLIS_PER_DAY = 24L * 60L * 60L * 1000L