Review: ask on value milestones, not exports

The old gate needed two exports, three days of install age, one prompt per
version and 120 days between prompts. Aptabase shows only 9% of users ever
export and 5% export twice, so `Review Prompt Requested` never fired once in
19 days and the store has a single rating.

Replace the export counter with three milestones -- a fully configured system,
an opened bill of materials, a completed export -- each counted at most once
per install, and ask once two different ones are reached. Recording and asking
are now separate: milestones are booked mid-task, where StoreKit and Play drop
the request, so the ask happens from calm screens only (system overview,
export preview dismissal, share sheet dismissal).

Two fixes that made the old prompt lose its slot for good: the throttle keys
were written before checking for a foreground scene, and the export trigger
fired while the Quick Look sheet was still animating away. Both platforms now
mark the throttle only once the store API really has a review flow to show.

Add a Settings entry that links straight to the store review page. It is never
throttled, and 45% of users open Settings versus 9% who export. New analytics
event `Review Milestone Reached` makes the funnel measurable.

Existing installs keep their legacy export credit and still need a second
milestone before being asked.
This commit is contained in:
2026-08-19 15:07:46 +02:00
parent 165827c4d4
commit 9673bde107
21 changed files with 479 additions and 140 deletions

View File

@@ -7,6 +7,7 @@ import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import app.voltplan.cable.BuildConfig
@@ -20,109 +21,144 @@ import kotlinx.coroutines.flow.first
/**
* Decides when to ask the user for a Play Store rating via the Play In-App Review API.
* Google throttles the actual dialog (and shows nothing in debug/sideload builds), so this gate
* keeps requests rare and tied to genuine success moments — a completed export/share.
* Mirrors the iOS `ReviewPrompt` enum, sharing the same gate thresholds and the `cable_settings`
* DataStore so both platforms behave identically.
* keeps requests rare and tied to genuine success moments. Booking a milestone and asking for the
* rating are deliberately separate: milestones are reached mid-task (a screen opens, a share
* intent fires), which is exactly when the review flow gets dropped. [promptIfEligible] is
* therefore only called from calm screens.
* Mirrors the iOS `ReviewPrompt` enum, sharing the same milestones and thresholds and the
* `cable_settings` DataStore so both platforms behave identically.
*/
object ReviewPrompt {
private val MIGRATION_DONE = stringPreferencesKey("review.migrationDone")
private val FIRST_LAUNCH_DATE = longPreferencesKey("review.firstLaunchDate")
private val EXPORT_COUNT = intPreferencesKey("review.successfulExportCount")
/**
* Distinct proofs that the user got real value out of the app. Each one counts at most once
* per install, so navigating in circles cannot inflate the gate.
*/
enum class Milestone(val key: String) {
/** A system whose loads are all fully configured — the app's own definition of a finished plan. */
SYSTEM_PLANNED("systemPlanned"),
/** Opened a system's bill of materials. */
BILL_OF_MATERIALS("billOfMaterials"),
/** Completed an export/share (Overview PDF, BOM PDF, diagram image). */
EXPORTED("exported"),
}
private val GATE_VERSION = intPreferencesKey("review.gateVersion")
private val MILESTONES = stringSetPreferencesKey("review.milestones")
private val LAST_PROMPT_DATE = longPreferencesKey("review.lastPromptDate")
private val LAST_PROMPTED_VERSION = stringPreferencesKey("review.lastPromptedVersion")
private val USER_TYPE = stringPreferencesKey("review.userType")
private val LEGACY_EXPORT_COUNT = intPreferencesKey("review.successfulExportCount")
private val LEGACY_FIRST_LAUNCH_DATE = longPreferencesKey("review.firstLaunchDate")
private val LEGACY_MIGRATION_DONE = stringPreferencesKey("review.migrationDone")
private const val MIN_EXPORTS = 2
private const val MIN_DAYS_SINCE_INSTALL = 3L
private const val MIN_DAYS_BETWEEN_PROMPTS = 120L
/** Two *different* milestones — a single one (only opening the parts list, say) is not enough. */
private const val MIN_MILESTONES = 2
private const val MIN_DAYS_BETWEEN_PROMPTS = 90L
private const val DAY_MS = 24L * 60 * 60 * 1000
/** Bump when the milestone semantics change so [migrateIfNeeded] runs again. */
private const val CURRENT_GATE_VERSION = 2
/** Play listing, used by the manual entry point in Settings. Unlike the in-app review flow this
* is never throttled or suppressed, so it is the only path a willing user can always take. */
const val PLAY_STORE_URI = "market://details?id=app.voltplan.cable"
const val PLAY_STORE_WEB_URL = "https://play.google.com/store/apps/details?id=app.voltplan.cable"
/**
* One-time setup distinguishing fresh installs from users updating into this feature.
* Existing users are backdated and pre-seeded so the prompt can fire on their *first*
* successful export after updating. Pass the value returned by [UnitSystemSettings.consumeFirstLaunch].
* One-time setup, called on every launch. Existing installs keep the credit they earned under
* the previous export-only gate: the legacy counter was pre-seeded on update, so any non-zero
* value means "knows the app already" and counts as the export milestone. They still need a
* second, real milestone before we ask. Pass the value returned by
* [UnitSystemSettings.consumeFirstLaunch].
*/
suspend fun migrateIfNeeded(context: Context, isFirstLaunch: Boolean) {
if (context.dataStore.data.first()[MIGRATION_DONE] != null) return
val now = System.currentTimeMillis()
context.dataStore.edit {
if (isFirstLaunch) {
// Genuine new install: normal flow — needs 2 exports and 3 days.
it[FIRST_LAUNCH_DATE] = now
it[EXPORT_COUNT] = 0
it[USER_TYPE] = "new"
} else {
// Existing user updating in: backdate install past the age gate and pre-seed the
// counter so the very next successful export satisfies the gate.
it[FIRST_LAUNCH_DATE] = now - MIN_DAYS_SINCE_INSTALL * DAY_MS
it[EXPORT_COUNT] = MIN_EXPORTS - 1
it[USER_TYPE] = "existing"
}
it[MIGRATION_DONE] = "true"
val prefs = context.dataStore.data.first()
if ((prefs[GATE_VERSION] ?: 0) >= CURRENT_GATE_VERSION) return
if ((prefs[LEGACY_EXPORT_COUNT] ?: 0) > 0) {
record(context, Milestone.EXPORTED)
}
context.dataStore.edit {
if (it[USER_TYPE] == null) it[USER_TYPE] = if (isFirstLaunch) "new" else "existing"
it.remove(LEGACY_EXPORT_COUNT)
it.remove(LEGACY_FIRST_LAUNCH_DATE)
it.remove(LEGACY_MIGRATION_DONE)
it[GATE_VERSION] = CURRENT_GATE_VERSION
}
}
/** Books a success moment. Never shows anything — safe to call from anywhere. */
suspend fun record(context: Context, milestone: Milestone) {
var reached = emptySet<String>()
var added = false
context.dataStore.edit {
val current = it[MILESTONES] ?: emptySet()
added = milestone.key !in current
reached = current + milestone.key
if (added) it[MILESTONES] = reached
}
if (!added) return
Analytics.log(
"Review Milestone Reached",
mapOf("milestone" to milestone.key, "reached" to reached.size),
)
}
/**
* Call after any successful export/share (Overview PDF, BOM PDF, Diagram image).
* Increments the shared counter, then requests a review if every gate condition holds.
* Asks for a rating if the gate allows it. Call only from a screen at rest — never right
* before starting an activity.
*/
suspend fun registerSuccessfulExport(context: Context) {
var count = 0
var firstLaunch = 0L
context.dataStore.edit {
if (it[FIRST_LAUNCH_DATE] == null) it[FIRST_LAUNCH_DATE] = System.currentTimeMillis()
count = (it[EXPORT_COUNT] ?: 0) + 1
it[EXPORT_COUNT] = count
firstLaunch = it[FIRST_LAUNCH_DATE] ?: 0L
}
if (shouldRequest(context, count, firstLaunch)) {
requestReview(context)
}
}
suspend fun promptIfEligible(context: Context) {
if (!isEligible(context)) return
private suspend fun shouldRequest(context: Context, exportCount: Int, firstLaunch: Long): Boolean {
// A: enough successful exports
if (exportCount < MIN_EXPORTS) return false
val activity = context.findActivity() ?: return
val manager = ReviewManagerFactory.create(context)
// Play decides whether there is a flow to show at all; asking first means a suppressed
// request never burns this version's single slot.
val reviewInfo = runCatching { manager.requestReview() }.getOrNull() ?: return
val now = System.currentTimeMillis()
// B: installed long enough
if (now - firstLaunch < MIN_DAYS_SINCE_INSTALL * DAY_MS) return false
// Wait until the activity is resumed so the dialog doesn't overlap a share sheet that was
// just launched (startActivity returns immediately, so we may still be paused).
(activity as? LifecycleOwner)?.lifecycle?.currentStateFlow
?.filter { state: Lifecycle.State -> state.isAtLeast(Lifecycle.State.RESUMED) }
?.first()
val prefs = context.dataStore.data.first()
// C: not prompted too recently
val lastPrompt = prefs[LAST_PROMPT_DATE] ?: 0L
if (lastPrompt > 0 && now - lastPrompt < MIN_DAYS_BETWEEN_PROMPTS * DAY_MS) return false
// D: at most once per app version
if (prefs[LAST_PROMPTED_VERSION] == BuildConfig.VERSION_NAME) return false
return true
}
private suspend fun requestReview(context: Context) {
// Mark as requested up front — Google may suppress the dialog, but we still count it
// against our own throttle so we don't ask again immediately.
context.dataStore.edit {
it[LAST_PROMPT_DATE] = System.currentTimeMillis()
it[LAST_PROMPTED_VERSION] = BuildConfig.VERSION_NAME
}
val userType = context.dataStore.data.first()[USER_TYPE] ?: "unknown"
Analytics.log(
"Review Prompt Requested",
mapOf("version" to BuildConfig.VERSION_NAME, "userType" to userType),
mapOf(
"version" to BuildConfig.VERSION_NAME,
"userType" to (prefs[USER_TYPE] ?: "unknown"),
"milestones" to (prefs[MILESTONES] ?: emptySet()).sorted().joinToString(","),
),
)
val activity = context.findActivity() ?: return
runCatching {
val manager = ReviewManagerFactory.create(context)
val reviewInfo = manager.requestReview()
// Wait until the activity is resumed so the dialog doesn't overlap a share sheet
// that was just launched (startActivity returns immediately, so we may still be paused).
(activity as? LifecycleOwner)?.lifecycle?.currentStateFlow
?.filter { state: Lifecycle.State -> state.isAtLeast(Lifecycle.State.RESUMED) }
?.first()
manager.launchReview(activity, reviewInfo)
}
runCatching { manager.launchReview(activity, reviewInfo) }
}
/** Internal rather than private so the gate can be tested without an Activity. */
internal suspend fun isEligible(context: Context): Boolean {
val prefs = context.dataStore.data.first()
// A: enough distinct milestones
if ((prefs[MILESTONES] ?: emptySet()).size < MIN_MILESTONES) return false
// B: not prompted too recently
val now = System.currentTimeMillis()
val lastPrompt = prefs[LAST_PROMPT_DATE] ?: 0L
if (lastPrompt > 0 && now - lastPrompt < MIN_DAYS_BETWEEN_PROMPTS * DAY_MS) return false
// C: at most once per app version
if (prefs[LAST_PROMPTED_VERSION] == BuildConfig.VERSION_NAME) return false
return true
}
private fun Context.findActivity(): Activity? {

View File

@@ -77,7 +77,8 @@ fun BillOfMaterialsScreen(systemId: String, onBack: () -> Unit) {
vm.logPdfExported()
scope.launch {
SystemBomPdf.exportAndShare(context, state, unit)
ReviewPrompt.registerSuccessfulExport(context)
ReviewPrompt.record(context, ReviewPrompt.Milestone.EXPORTED)
ReviewPrompt.promptIfEligible(context)
}
},
) { Icon(Icons.Outlined.PictureAsPdf, contentDescription = stringResource(R.string.bom_export_pdf_button)) }

View File

@@ -1,5 +1,9 @@
package app.voltplan.cable.ui.settings
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
@@ -9,9 +13,11 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.Warning
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
@@ -25,18 +31,24 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import app.voltplan.cable.R
import app.voltplan.cable.analytics.Analytics
import app.voltplan.cable.data.ReviewPrompt
import app.voltplan.cable.data.UnitSystem
import app.voltplan.cable.ui.LocalUnitSettings
import app.voltplan.cable.ui.theme.SysOrange
import app.voltplan.cable.ui.theme.SysYellow
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(onBack: () -> Unit) {
val context = LocalContext.current
val settings = LocalUnitSettings.current
val unit by settings.unitSystem.collectAsStateWithLifecycle()
@@ -68,6 +80,33 @@ fun SettingsScreen(onBack: () -> Unit) {
)
}
Row(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.clickable {
Analytics.log("Rate App Tapped")
openPlayStoreListing(context)
}
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Icon(Icons.Filled.Star, contentDescription = null, tint = SysYellow, modifier = Modifier.size(20.dp))
Column {
Text(
stringResource(R.string.settings_rate_title),
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.SemiBold,
)
Text(
stringResource(R.string.settings_rate_footnote),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Outlined.Warning, contentDescription = null, tint = SysOrange, modifier = Modifier.size(18.dp))
Text(stringResource(R.string.settings_disclaimer_title), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
@@ -77,3 +116,12 @@ fun SettingsScreen(onBack: () -> Unit) {
}
}
}
/** Opens the Play listing, falling back to the web listing on devices without the Play app. */
private fun openPlayStoreListing(context: Context) {
runCatching {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ReviewPrompt.PLAY_STORE_URI)))
}.recoverCatching {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ReviewPrompt.PLAY_STORE_WEB_URL)))
}
}

View File

@@ -22,6 +22,7 @@ import androidx.compose.material.icons.outlined.Bolt
import androidx.compose.material.icons.outlined.IosShare
import androidx.compose.material.icons.outlined.PictureAsPdf
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -110,6 +111,15 @@ fun SystemDetailScreen(
var diagramBitmapPreview by remember { mutableStateOf<Bitmap?>(null) }
val system = state.system
// A finished plan is the app's own definition of success, and the overview is the calm moment
// where a rating request can actually be presented.
val systemPlanned = state.loads.isNotEmpty() &&
state.loads.all { it.length > 0 && it.current > 0 && it.crossSection > 0 }
LaunchedEffect(systemPlanned) {
if (systemPlanned) ReviewPrompt.record(context, ReviewPrompt.Milestone.SYSTEM_PLANNED)
ReviewPrompt.promptIfEligible(context)
}
// Switch to the matching tab before opening an editor, so returning from the
// editor lands on that tab with the newly created component visible.
val newLoad = { tab = ComponentTab.COMPONENTS; onNewLoad() }
@@ -184,7 +194,8 @@ fun SystemDetailScreen(
exporting = true
SystemOverviewPdf.exportAndShare(context, state, unitSystem)
exporting = false
ReviewPrompt.registerSuccessfulExport(context)
ReviewPrompt.record(context, ReviewPrompt.Milestone.EXPORTED)
ReviewPrompt.promptIfEligible(context)
}
},
)
@@ -221,7 +232,11 @@ fun SystemDetailScreen(
onAddBattery = newBattery,
onAddCharger = newCharger,
onOpenLibrary = { onOpenLibrary(ComponentLibraryType.LOAD) },
onOpenBom = { vm.logBomOpened(); onOpenBom() },
onOpenBom = {
vm.logBomOpened()
scope.launch { ReviewPrompt.record(context, ReviewPrompt.Milestone.BILL_OF_MATERIALS) }
onOpenBom()
},
onSelectLoads = { tab = ComponentTab.COMPONENTS; vm.logTabChange(ComponentTab.COMPONENTS.analytics) },
onSelectBatteries = { tab = ComponentTab.BATTERIES; vm.logTabChange(ComponentTab.BATTERIES.analytics) },
onSelectChargers = { tab = ComponentTab.CHARGERS; vm.logTabChange(ComponentTab.CHARGERS.analytics) },
@@ -261,7 +276,8 @@ fun SystemDetailScreen(
scope.launch {
SystemDiagram.share(context, bmp, state.system?.name ?: "System")
diagramBitmapPreview = null
ReviewPrompt.registerSuccessfulExport(context)
ReviewPrompt.record(context, ReviewPrompt.Milestone.EXPORTED)
ReviewPrompt.promptIfEligible(context)
}
},
onDismiss = { diagramBitmapPreview = null },

View File

@@ -259,6 +259,8 @@
<string name="settings_units_section">Einheiten</string>
<string name="units_metric_display">Metrisch (mm², m)</string>
<string name="units_imperial_display">Imperial (AWG, ft)</string>
<string name="settings_rate_title">Cable bewerten</string>
<string name="settings_rate_footnote">Bewertungen helfen anderen Monteuren, Cable im Play Store zu finden.</string>
<string name="settings_disclaimer_title">Sicherheitshinweis</string>
<string name="settings_disclaimer_body">Diese Anwendung erstellt elektrische Berechnungen zu Schulungszwecken.</string>
<string name="settings_disclaimer_points">• Ziehe für tatsächliche Installationen stets qualifizierte Elektriker hinzu\n• Beachte alle örtlichen Vorschriften und Normen\n• Elektroarbeiten sollten nur von zertifizierten Fachkräften ausgeführt werden\n• Diese Berechnungen berücksichtigen möglicherweise nicht alle Umgebungsfaktoren\n• Die App-Entwickler übernehmen keine Haftung für elektrische Installationen</string>

View File

@@ -259,6 +259,8 @@
<string name="settings_units_section">Unidades</string>
<string name="units_metric_display">Métrico (mm², m)</string>
<string name="units_imperial_display">Imperial (AWG, ft)</string>
<string name="settings_rate_title">Valorar Cable</string>
<string name="settings_rate_footnote">Las valoraciones ayudan a que otros instaladores encuentren Cable en Play Store.</string>
<string name="settings_disclaimer_title">Aviso de seguridad</string>
<string name="settings_disclaimer_body">Esta aplicación proporciona cálculos eléctricos únicamente con fines educativos y de estimación.</string>
<string name="settings_disclaimer_points">• Consulta siempre a electricistas calificados para las instalaciones reales\n• Cumple todas las normativas y códigos eléctricos locales\n• Los trabajos eléctricos solo deben realizarlos profesionales autorizados\n• Estos cálculos pueden no tener en cuenta todos los factores ambientales\n• Los desarrolladores de la app no asumen responsabilidad por las instalaciones eléctricas</string>

View File

@@ -259,6 +259,8 @@
<string name="settings_units_section">Unités</string>
<string name="units_metric_display">Métrique (mm², m)</string>
<string name="units_imperial_display">Impérial (AWG, ft)</string>
<string name="settings_rate_title">Noter Cable</string>
<string name="settings_rate_footnote">Les avis aident les autres installateurs à trouver Cable sur le Play Store.</string>
<string name="settings_disclaimer_title">Avertissement de sécurité</string>
<string name="settings_disclaimer_body">Cette application fournit des calculs électriques uniquement à des fins pédagogiques et d\'estimation.</string>
<string name="settings_disclaimer_points">• Faites toujours appel à des électriciens qualifiés pour les installations réelles\n• Respectez toutes les normes et réglementations électriques locales\n• Les travaux électriques doivent être réalisés uniquement par des professionnels certifiés\n• Ces calculs peuvent ne pas prendre en compte tous les facteurs environnementaux\n• Les développeurs de l\'application déclinent toute responsabilité quant aux installations électriques</string>

View File

@@ -259,6 +259,8 @@
<string name="settings_units_section">Eenheden</string>
<string name="units_metric_display">Metrisch (mm², m)</string>
<string name="units_imperial_display">Imperiaal (AWG, ft)</string>
<string name="settings_rate_title">Cable beoordelen</string>
<string name="settings_rate_footnote">Beoordelingen helpen andere installateurs om Cable in de Play Store te vinden.</string>
<string name="settings_disclaimer_title">Veiligheidswaarschuwing</string>
<string name="settings_disclaimer_body">Deze app levert elektrische berekeningen uitsluitend voor educatieve doeleinden en schattingen.</string>
<string name="settings_disclaimer_points">• Raadpleeg voor echte installaties altijd een gekwalificeerde elektricien\n• Volg alle lokale elektrische voorschriften en regels\n• Elektrisch werk mag alleen worden uitgevoerd door bevoegde professionals\n• Deze berekeningen houden mogelijk niet met alle omgevingsfactoren rekening\n• De ontwikkelaars van de app aanvaarden geen aansprakelijkheid voor elektrische installaties</string>

View File

@@ -259,6 +259,8 @@
<string name="settings_units_section">Units</string>
<string name="units_metric_display">Metric (mm², m)</string>
<string name="units_imperial_display">Imperial (AWG, ft)</string>
<string name="settings_rate_title">Rate Cable</string>
<string name="settings_rate_footnote">Ratings are how other installers find Cable in the Play Store.</string>
<string name="settings_disclaimer_title">Safety Disclaimer</string>
<string name="settings_disclaimer_body">This application provides electrical calculations for educational and estimation purposes only.</string>
<string name="settings_disclaimer_points">• Always consult qualified electricians for actual installations\n• Follow all local electrical codes and regulations\n• Electrical work should only be performed by licensed professionals\n• These calculations may not account for all environmental factors\n• The app developers assume no liability for electrical installations</string>