diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 40ffed0b..f8163dc5 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -141,6 +141,11 @@ android { } } +dependencies { + implementation("androidx.work:work-runtime-ktx:2.9.1") + testImplementation("junit:junit:4.13.2") +} + tasks.named("preBuild") { dependsOn(prepareEcardWidgetResources) } flutter { diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 854b54b6..167de237 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ + diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt b/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt index 5d7cbcf3..4c7ad956 100644 --- a/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt +++ b/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt @@ -14,6 +14,7 @@ import android.provider.CalendarContract.Events import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import club.geekpie.techpie.ecardbind.EcardBindVpnService +import club.geekpie.techpie.notification.SpendingNotificationBridge import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodCall @@ -25,6 +26,7 @@ class MainActivity : FlutterActivity() { private val mainHandler = Handler(Looper.getMainLooper()) private var ecardWidgets: EcardWidgetBridge? = null private var ecardFeedback: EcardFeedback? = null + private var spendingAlerts: SpendingNotificationBridge? = null override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) @@ -32,6 +34,7 @@ class MainActivity : FlutterActivity() { it.capture(intent, notifyFlutter = false) } ecardFeedback = EcardFeedback(this, flutterEngine.dartExecutor.binaryMessenger) + spendingAlerts = SpendingNotificationBridge(this, flutterEngine.dartExecutor.binaryMessenger, this) MethodChannel( flutterEngine.dartExecutor.binaryMessenger, @@ -82,6 +85,8 @@ class MainActivity : FlutterActivity() { ecardWidgets = null ecardFeedback?.dispose() ecardFeedback = null + spendingAlerts?.dispose() + spendingAlerts = null super.cleanUpFlutterEngine(flutterEngine) } @@ -193,6 +198,7 @@ class MainActivity : FlutterActivity() { grantResults: IntArray, ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == 48293) spendingAlerts?.refreshSchedule() if (requestCode != REQUEST_CALENDAR_PERMISSIONS) return diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingLedger.kt b/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingLedger.kt new file mode 100644 index 00000000..853d94cc --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingLedger.kt @@ -0,0 +1,44 @@ +package club.geekpie.techpie.notification + +/** Pure receipt state. Android persists only opaque keys and timestamps. */ +data class SpendingRecord( + val key: String, + val at: Long, + val spending: Boolean, + val title: String = "", + val body: String = "", +) + +data class SpendingLedger( + val owner: String? = null, + val generation: Long = 0, + val initialized: Boolean = false, + val floor: Long = Long.MIN_VALUE, + val seen: Map = emptyMap(), +) { + data class Update(val ledger: SpendingLedger, val receipts: List) + + fun configure(nextOwner: String?): SpendingLedger = + if (owner == nextOwner) this else SpendingLedger(nextOwner, generation + 1) + + fun observe(expectedOwner: String, expectedGeneration: Long, + records: List, now: Long): Update? { + if (owner == null || owner != expectedOwner || generation != expectedGeneration) return null + val page = records.filter { it.at > 0 && it.at <= now + 300_000L } + .distinctBy { it.key }.sortedWith(compareBy({ it.at }, { it.key })) + // An empty first page is still a baseline: the next real payment is news. + val baseline = if (initialized) floor else page.maxOfOrNull { it.at } ?: now + val receipts = if (!initialized) emptyList() else page.filter { + it.spending && it.at >= floor && !seen.containsKey(it.key) + } + val merged = seen.toMutableMap() + page.forEach { merged[it.key] = it.at } + val ordered = merged.entries.sortedWith(compareBy({ it.value }, { it.key })) + val removed = ordered.dropLast(LIMIT) + val nextFloor = maxOf(baseline, removed.maxOfOrNull { it.value + 1 } ?: Long.MIN_VALUE) + return Update(copy(initialized = true, floor = nextFloor, + seen = ordered.takeLast(LIMIT).associate { it.key to it.value }), receipts) + } + + companion object { const val LIMIT = 200 } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingNotificationBridge.kt b/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingNotificationBridge.kt new file mode 100644 index 00000000..b3c91877 --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingNotificationBridge.kt @@ -0,0 +1,170 @@ +package club.geekpie.techpie.notification + +import android.Manifest +import android.app.Activity +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.ActivityCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import club.geekpie.techpie.MainActivity +import club.geekpie.techpie.R +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import org.json.JSONObject + +/** One synchronized native ledger for all Flutter engines in the app process. */ +internal object SpendingNotificationState { + private const val PREFS = "techpie_spending_alerts_v1" + private const val TAG = "techpie.spending" + private const val CHANNEL = "spending_alerts" + private const val MAX_NOTIFICATIONS = 3 + private val lock = Any() + private val opaqueKey = Regex("^[0-9a-f]{64}$") + + private fun read(context: Context): SpendingLedger { + val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val seen = mutableMapOf() + runCatching { + val json = JSONObject(prefs.getString("seen", "{}") ?: "{}") + for (key in json.keys()) { + if (opaqueKey.matches(key) && seen.size < SpendingLedger.LIMIT) seen[key] = json.getLong(key) + } + } + return SpendingLedger( + owner = prefs.getString("owner", null), generation = prefs.getLong("generation", 0), + initialized = prefs.getBoolean("initialized", false), floor = prefs.getLong("floor", Long.MIN_VALUE), + seen = seen, + ) + } + + private fun save(context: Context, state: SpendingLedger): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString("owner", state.owner).putLong("generation", state.generation) + .putBoolean("initialized", state.initialized).putLong("floor", state.floor) + .putString("seen", JSONObject(state.seen).toString()).commit() + + fun status(context: Context): Map = synchronized(lock) { + val state = read(context) + mapOf("owner" to state.owner, "generation" to state.generation) + } + + fun configure(context: Context, owner: String?): Boolean = synchronized(lock) { + require(owner == null || opaqueKey.matches(owner)) { "Invalid notification scope" } + val before = read(context) + val next = before.configure(owner) + if (before != next) { + if (!save(context, next)) return@synchronized false + SpendingRefreshScheduler.cancel(context) + val manager = context.getSystemService(NotificationManager::class.java) + manager.activeNotifications.filter { it.tag == TAG }.forEach { manager.cancel(TAG, it.id) } + } + updateSchedule(context, next) + true + } + + fun refreshSchedule(context: Context) = synchronized(lock) { updateSchedule(context, read(context)) } + + private fun updateSchedule(context: Context, state: SpendingLedger) { + if (state.owner != null && NotificationManagerCompat.from(context).areNotificationsEnabled()) { + SpendingRefreshScheduler.schedule(context) + } else { + SpendingRefreshScheduler.cancel(context) + } + } + + fun observe(context: Context, owner: String, generation: Long, records: List): Boolean = synchronized(lock) { + val before = read(context) + val update = before.observe(owner, generation, records, System.currentTimeMillis()) + ?: return@synchronized false + // Persist before notifying: a concurrent engine cannot announce the same batch. + if (!save(context, update.ledger)) return@synchronized false + if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return@synchronized true + ensureChannel(context) + val shown = update.receipts.take(MAX_NOTIFICATIONS) + val folded = update.receipts.size - shown.size + shown.forEachIndexed { index, record -> + val id = (owner + record.key).hashCode() + val open = PendingIntent.getActivity(context, id, + Intent(context, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP + }, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val tail = if (index == shown.lastIndex && folded > 0) " · 另有 $folded 笔" else "" + val notification = NotificationCompat.Builder(context, CHANNEL) + .setSmallIcon(R.drawable.ic_spending_notification) + .setContentTitle(record.title).setContentText(record.body + tail) + .setStyle(NotificationCompat.BigTextStyle().bigText(record.body + tail)) + .setContentIntent(open).setAutoCancel(true) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setCategory(NotificationCompat.CATEGORY_STATUS) + .setGroup(TAG).setSilent(index > 0).build() + try { NotificationManagerCompat.from(context).notify(TAG, id, notification) } + catch (_: SecurityException) { /* Permission can be revoked between the check and post. */ } + } + true + } + + private fun ensureChannel(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + context.getSystemService(NotificationManager::class.java).createNotificationChannel( + NotificationChannel(CHANNEL, context.getString(R.string.spending_channel_name), + NotificationManager.IMPORTANCE_DEFAULT).apply { + description = context.getString(R.string.spending_channel_desc) + setShowBadge(false) + lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE + }) + } +} + +class SpendingNotificationBridge(context: Context, messenger: BinaryMessenger, + private val activity: Activity? = null) { + private val appContext = context.applicationContext + private val channel = MethodChannel(messenger, "techpie/spending_alerts") + init { + channel.setMethodCallHandler { call, result -> + try { + when (call.method) { + "configure" -> result.success(SpendingNotificationState.configure(appContext, call.argument("owner"))) + "status" -> result.success(SpendingNotificationState.status(appContext)) + "observe" -> result.success(observe(call)) + "requestPermission" -> result.success(requestPermission()) + else -> result.notImplemented() + } + } catch (_: Exception) { + result.error("SPENDING_NOTIFICATION_FAILED", "通知暂不可用", null) + } + } + } + + private fun observe(call: MethodCall): Boolean { + val owner = call.argument("owner") ?: return false + val generation = call.argument("generation")?.toLong() ?: return false + val raw = call.argument>>("records") ?: return false + val records = raw.take(50).mapNotNull { item -> + val key = (item["key"] as? String)?.takeIf { Regex("^[0-9a-f]{64}$").matches(it) } ?: return@mapNotNull null + val at = (item["at"] as? Number)?.toLong() ?: return@mapNotNull null + SpendingRecord(key, at, item["spending"] == true, + (item["title"] as? String).orEmpty().take(80), (item["body"] as? String).orEmpty().take(500)) + } + return SpendingNotificationState.observe(appContext, owner, generation, records) + } + + private fun requestPermission(): Boolean { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true + val granted = ContextCompat.checkSelfPermission(appContext, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED + if (!granted && activity != null) ActivityCompat.requestPermissions(activity, + arrayOf(Manifest.permission.POST_NOTIFICATIONS), 48293) + return granted + } + + fun refreshSchedule() = SpendingNotificationState.refreshSchedule(appContext) + + fun dispose() = channel.setMethodCallHandler(null) +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingRefreshWorker.kt b/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingRefreshWorker.kt new file mode 100644 index 00000000..2ac09d4d --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/notification/SpendingRefreshWorker.kt @@ -0,0 +1,93 @@ +package club.geekpie.techpie.notification + +import android.content.Context +import android.os.Handler +import android.os.Looper +import androidx.core.app.NotificationManagerCompat +import androidx.work.Constraints +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.NetworkType +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import io.flutter.FlutterInjector +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.embedding.engine.dart.DartExecutor +import io.flutter.plugin.common.MethodChannel +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +internal object SpendingRefreshScheduler { + private const val NAME = "techpie-spending-refresh" + fun schedule(context: Context) { + val request = PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES) + .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()) + .build() + WorkManager.getInstance(context).enqueueUniquePeriodicWork(NAME, ExistingPeriodicWorkPolicy.KEEP, request) + } + fun cancel(context: Context) { WorkManager.getInstance(context).cancelUniqueWork(NAME) } +} + +/** All engine/channel operations are on main; only the bounded wait is on Worker. */ +class SpendingRefreshWorker(appContext: Context, params: WorkerParameters) : Worker(appContext, params) { + private val main = Handler(Looper.getMainLooper()) + private val active = AtomicBoolean(true) + private val finished = CountDownLatch(1) + private val success = AtomicBoolean(false) + // The fields below are owned exclusively by the main thread. + private var engine: FlutterEngine? = null + private var bridge: SpendingNotificationBridge? = null + private var completion: MethodChannel? = null + + override fun doWork(): Result { + main.post { + if (!active.get() || isStopped) { finished.countDown(); return@post } + if (SpendingNotificationState.status(applicationContext)["owner"] == null || + !NotificationManagerCompat.from(applicationContext).areNotificationsEnabled()) { + success.set(true); finished.countDown(); return@post + } + try { + val loader = FlutterInjector.instance().flutterLoader() + loader.startInitialization(applicationContext) + loader.ensureInitializationComplete(applicationContext, null) + val running = FlutterEngine(applicationContext) + engine = running + val messenger = running.dartExecutor.binaryMessenger + bridge = SpendingNotificationBridge(applicationContext, messenger) + completion = MethodChannel(messenger, "techpie/spending_worker").also { channel -> + channel.setMethodCallHandler { call, result -> + if (call.method == "done") { + success.set(call.argument("success") == true) + result.success(true) + finished.countDown() + } else result.notImplemented() + } + } + running.dartExecutor.executeDartEntrypoint( + DartExecutor.DartEntrypoint(loader.findAppBundlePath(), "spendingBackgroundRefresh")) + } catch (_: Exception) { finished.countDown() } + } + try { finished.await(60, TimeUnit.SECONDS) } + catch (_: InterruptedException) { Thread.currentThread().interrupt() } + finally { active.set(false); main.post { cleanup() } } + return if (success.get() || runAttemptCount >= 2) Result.success() else Result.retry() + } + + override fun onStopped() { + active.set(false) + finished.countDown() + main.post { cleanup() } + super.onStopped() + } + + private fun cleanup() { + completion?.setMethodCallHandler(null) + completion = null + bridge?.dispose() + bridge = null + engine?.destroy() + engine = null + } +} diff --git a/android/app/src/main/res/drawable/ic_spending_notification.xml b/android/app/src/main/res/drawable/ic_spending_notification.xml new file mode 100644 index 00000000..bafbfe72 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_spending_notification.xml @@ -0,0 +1,9 @@ + + + diff --git a/android/app/src/main/res/values-ja/alert_strings.xml b/android/app/src/main/res/values-ja/alert_strings.xml new file mode 100644 index 00000000..7929c0f1 --- /dev/null +++ b/android/app/src/main/res/values-ja/alert_strings.xml @@ -0,0 +1,5 @@ + + + 利用通知 + アプリが利用明細で確認した学生証の支払いを通知します + diff --git a/android/app/src/main/res/values-zh/alert_strings.xml b/android/app/src/main/res/values-zh/alert_strings.xml new file mode 100644 index 00000000..7da667fc --- /dev/null +++ b/android/app/src/main/res/values-zh/alert_strings.xml @@ -0,0 +1,5 @@ + + + 消费提醒 + 报告应用刚从账单里读到的校园卡消费 + diff --git a/android/app/src/main/res/values/alert_strings.xml b/android/app/src/main/res/values/alert_strings.xml new file mode 100644 index 00000000..155af98c --- /dev/null +++ b/android/app/src/main/res/values/alert_strings.xml @@ -0,0 +1,5 @@ + + + Spending alerts + Reports campus card payments the app has just read from the ledger + diff --git a/android/app/src/test/kotlin/club/geekpie/techpie/notification/SpendingLedgerTest.kt b/android/app/src/test/kotlin/club/geekpie/techpie/notification/SpendingLedgerTest.kt new file mode 100644 index 00000000..593f16b4 --- /dev/null +++ b/android/app/src/test/kotlin/club/geekpie/techpie/notification/SpendingLedgerTest.kt @@ -0,0 +1,79 @@ +package club.geekpie.techpie.notification + +import org.junit.Assert.* +import org.junit.Test + +class SpendingLedgerTest { + private fun record(key: String, at: Long, spending: Boolean = true) = SpendingRecord(key, at, spending) + + @Test fun firstSnapshotOnlyCreatesBaseline() { + val state = SpendingLedger().configure("a") + val update = state.observe("a", state.generation, listOf(record("old", 1_000)), 2_000)!! + assertTrue(update.receipts.isEmpty()) + assertTrue(update.ledger.initialized) + assertEquals(1_000L, update.ledger.floor) + } + + @Test fun emptyBaselineStillNotifiesFirstLaterPayment() { + val state = SpendingLedger().configure("a") + val baseline = state.observe("a", state.generation, emptyList(), 2_000)!!.ledger + val update = baseline.observe("a", baseline.generation, listOf(record("new", 3_000)), 4_000)!! + assertEquals(listOf("new"), update.receipts.map { it.key }) + } + + @Test fun overlappingUnorderedPagesNotifyEachPaymentOnceOldestFirst() { + val state = SpendingLedger(owner = "a", generation = 3, initialized = true, floor = 1_000) + val page = listOf(record("b", 4_000), record("a", 3_000), record("a", 3_000)) + val first = state.observe("a", 3, page, 5_000)!! + assertEquals(listOf("a", "b"), first.receipts.map { it.key }) + assertTrue(first.ledger.observe("a", 3, page, 5_000)!!.receipts.isEmpty()) + } + + @Test fun aNewPaymentAtTheBaselineTimestampIsNotLost() { + val state = SpendingLedger(owner = "a", initialized = true, floor = 2_000, + seen = mapOf("old" to 2_000L)) + assertEquals(listOf("new"), state.observe("a", 0, + listOf(record("old", 2_000), record("new", 2_000)), 3_000)!!.receipts.map { it.key }) + } + + @Test fun rechargeRefundAndHistoricalEntriesNeverBecomeSpending() { + val state = SpendingLedger(owner = "a", initialized = true, floor = 2_000) + val result = state.observe("a", 0, listOf(record("old", 1_000), + record("refund", 3_000, false), record("recharge", 4_000, false)), 5_000)!! + assertTrue(result.receipts.isEmpty()) + assertEquals(3, result.ledger.seen.size) + } + + @Test fun disablingAndReenablingRejectsInflightReadsEvenForSameOwner() { + val enabled = SpendingLedger().configure("a") + val disabled = enabled.configure(null) + assertNull(disabled.observe("a", enabled.generation, listOf(record("old", 1_000)), 2_000)) + val reenabled = disabled.configure("a") + assertNull(reenabled.observe("a", enabled.generation, listOf(record("old", 1_000)), 2_000)) + assertTrue(reenabled.observe("a", reenabled.generation, listOf(record("old", 1_000)), 2_000)!!.receipts.isEmpty()) + } + + @Test fun switchingOwnerResetsBaselineAndRejectsOldAccount() { + val first = SpendingLedger(owner = "a", generation = 2, initialized = true, seen = mapOf("old" to 1_000)) + val second = first.configure("b") + assertNull(second.observe("a", first.generation, listOf(record("new", 2_000)), 3_000)) + assertTrue(second.observe("b", second.generation, listOf(record("new", 2_000)), 3_000)!!.receipts.isEmpty()) + assertEquals(first, first.configure("a")) + } + + @Test fun boundedLedgerDoesNotReplayEvictedOlderEntries() { + val state = SpendingLedger(owner = "a", initialized = true, floor = 0, + seen = (1..200).associate { "old$it" to it.toLong() }) + val updated = state.observe("a", 0, (201..250).map { record("new$it", it.toLong()) }, 1_000)!!.ledger + assertEquals(SpendingLedger.LIMIT, updated.seen.size) + assertEquals(51L, updated.floor) + assertTrue(updated.observe("a", 0, listOf(record("old1", 1), record("old50", 50)), 1_000)!!.receipts.isEmpty()) + } + + @Test fun invalidFutureAndZeroTimestampsCannotAdvanceBaseline() { + val state = SpendingLedger(owner = "a") + val updated = state.observe("a", 0, listOf(record("invalid", 0), record("future", 400_000)), 1_000)!! + assertEquals(1_000L, updated.ledger.floor) + assertTrue(updated.ledger.seen.isEmpty()) + } +} diff --git a/docs/spending-alerts.md b/docs/spending-alerts.md new file mode 100644 index 00000000..490d5f1d --- /dev/null +++ b/docs/spending-alerts.md @@ -0,0 +1,30 @@ +# Campus-card spending alerts + +Android users can opt into **校园卡消费提醒** in Settings. An alert shows the amount, merchant/location and balance when a fresh consumption record is discovered. Refunds, recharges, subsidies and transfers are not announced as spending. Notification details use private lock-screen visibility. + +The existing payment/history refresh supplies its full recent page to the notification port. A separate WorkManager task also checks up to 50 recent records when networking is available, at the platform's 15-minute minimum interval. This is polling, not a server push: delivery depends on ledger publication, network availability, notification permission and Android scheduling. It is not guaranteed to arrive at the time of the transaction. + +## State and lifecycle + +- Off by default. Scheduling requires accepted privacy terms, a signed-in primary account, a configured campus card and Android notification permission. +- The first successful snapshot is recorded silently. An empty first page is still an initialized baseline, so the first subsequent payment can be announced. +- Foreground and background Flutter engines submit snapshots to one synchronized native ledger. The ledger stores only an opaque hash of the primary/card identity, up to 200 hashed transaction IDs and timestamps. Notification text and credentials are not persisted there or logged. +- Snapshot merging deduplicates repeated IDs, sorts fresh receipts oldest-first, announces at most three per refresh and folds the remaining count into the last message. Only the first alert in a burst can make a sound. Old timestamps below the retained window cannot replay when IDs are evicted. Backfilled transactions older than that window may therefore be omitted. +- Disabling, signing out or changing accounts cancels periodic work, clears visible spending notices and resets the baseline. Native generation checks discard results from a request started before disable/re-enable, including when the same account returns. +- Background runs create and dispose their Flutter engine and channels on Android's main thread; only the bounded wait uses the worker thread. Work is network-constrained, limited to 60 seconds and at most two retries per failed cycle. No foreground service or resident keepalive is added. +- Payment success and history rendering do not depend on notification delivery. Demo/debug transactions are not sent to the notification port. + +## Scope and compatibility + +Ported from RCCE's spending-alert and periodic-refresh implementation, with explicit account scoping, a first-read baseline and a shared native deduplication ledger for upstream integration. The existing upstream application ID, minimum Android SDK, release version, signing, Apple Watch integration, pubspec/lock and release workflows are retained. + +This PR is independent of #194 (course/deadline island), #195 (Xiaomi wearable integration and class reminders) and #196 (cover/rear glance). It does not copy their modules. Class reminders already belong to #195; this change covers campus-card consumption notifications. + +## Validation + +- Flutter analysis; 777 Flutter tests passed. +- Nine native `SpendingLedgerTest` cases passed: first/empty baseline, duplicate/overlapping pages, same-timestamp payments, non-spending records, disabled/in-flight reads, owner changes, bounded history and invalid timestamps. +- Dart service tests: opt-in, consent/platform gates, opaque payloads, account mismatches, concurrent configuration, background cancellation and transient failures. +- Android debug and minified release APKs, and native unit tests. The release smoke build used a local test key only; upstream signing configuration remains unchanged. Real campus transactions, OS background restrictions and notification permission UX require device acceptance; mocked tests cannot establish delivery latency. + +Full Android lint also reports two pre-existing upstream errors outside this change: the API-28 private-DNS diagnostic call in `EcardBindVpnService.kt`, and the missing optional-camera hardware declaration in the base manifest. No errors remain in the added notification code. These unrelated base issues are not suppressed or folded into this feature PR. diff --git a/lib/features/campus_card/app/app_providers.dart b/lib/features/campus_card/app/app_providers.dart index af3ee145..b4040c4c 100644 --- a/lib/features/campus_card/app/app_providers.dart +++ b/lib/features/campus_card/app/app_providers.dart @@ -9,6 +9,7 @@ import '../application/campus_network_status.dart'; import '../application/payment_code_controller.dart'; import '../application/scan_payment_controller.dart'; import '../core/async_mutex.dart'; +import '../core/config/app_environment.dart'; import '../core/config/debug_mode_controller.dart'; import '../core/config/debug_mode_features.dart'; import '../core/config/offline_authorization_banner_controller.dart'; @@ -54,6 +55,7 @@ final campusNetworkStateProvider = StreamProvider( final campusCardAccountProvider = Provider((ref) => null); final homeWidgetPortProvider = Provider((ref) => null); +final spendingAlertPortProvider = Provider((ref) => null); enum CampusCardEntry { paymentCode, cardManagement } @@ -710,9 +712,10 @@ final class OfflineAuthorizationController } final accountHistoryRefreshProvider = Provider((ref) { - ref.watch(appRuntimeProvider); + final runtime = ref.watch(appRuntimeProvider); final coordinator = AccountHistoryRefresh( loadHistory: () async { + final subject = ref.read(authControllerProvider).valueOrNull?.session?.subjectId; const range = (begin: null, end: null); final provider = transactionFeedProvider(range); final exists = ref.exists(provider); @@ -721,6 +724,12 @@ final accountHistoryRefreshProvider = Provider((ref) { : null; ref.invalidate(transactionFeedProvider); final page = await ref.read(provider.future); + if (subject != null && + ref.read(authControllerProvider).valueOrNull?.session?.subjectId == subject && + runtime.environment != AppEnvironment.demo && + !(debugModeFeaturesAvailable && ref.read(debugModeProvider))) { + unawaited(ref.read(spendingAlertPortProvider)?.observeTransactions(page.items, subjectId: subject)); + } return previous != null && page.items.any((item) => !previous.contains(item.id)); }, diff --git a/lib/features/campus_card/domain/ports/bill_ports.dart b/lib/features/campus_card/domain/ports/bill_ports.dart index c3f07953..968759a1 100644 --- a/lib/features/campus_card/domain/ports/bill_ports.dart +++ b/lib/features/campus_card/domain/ports/bill_ports.dart @@ -18,3 +18,9 @@ abstract interface class DateRangeTransactionHistoryPort { int pageSize = 20, }); } + +/// Optional host integration. A complete recent page establishes or advances +/// the notification baseline; demos and filtered/history pages never call it. +abstract interface class SpendingAlertPort { + Future observeTransactions(List records, {required String subjectId}); +} diff --git a/lib/main.dart b/lib/main.dart index f87e697c..d2706ddc 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -24,17 +24,22 @@ import 'services/ids/ids_client.dart'; import 'services/oa_gym_service.dart'; import 'services/schedule_service.dart'; import 'services/service_provider.dart'; +import 'services/spending_alert_service.dart'; import 'services/storage_service.dart'; import 'services/sync_service.dart'; import 'services/theme_service.dart'; import 'services/third_party_auth_service.dart'; import 'services/uni_auth_service.dart'; import 'services/update_service.dart'; +import 'spending_background_refresh.dart'; import 'widgets/adaptive_feedback.dart'; import 'widgets/app_shell/app_shell.dart'; import 'widgets/privacy_consent.dart'; import 'widgets/update_dialogs.dart'; +@pragma('vm:entry-point') +Future spendingBackgroundRefresh() => runSpendingBackgroundRefresh(); + void main(List args) async { // If this Flutter engine is a desktop_webview_window title bar (secondary // engine inside the webview popup), render the navigation controls and @@ -74,6 +79,7 @@ Future _realMain(SharedPreferences prefs) async { final themeService = ThemeService(storageService); final campusCardService = CampusCardService(debugLogger: debugLogger, storage: storageService); + final spendingAlertService = SpendingAlertService(storageService); final ecardBindService = EcardBindService(); final ecardWidgetService = EcardWidgetService(); final thirdPartyAuthService = ThirdPartyAuthService( @@ -191,9 +197,11 @@ Future _realMain(SharedPreferences prefs) async { ecardBindService: ecardBindService, ecardWidgetService: ecardWidgetService, deadlineWidgetService: deadlineWidgetService, + spendingAlertService: spendingAlertService, ), ); + spendingAlertService.start(authService, campusCardService); bootMark('cached data ready'); if (!kIsWeb && (defaultTargetPlatform == TargetPlatform.iOS || @@ -325,6 +333,7 @@ class TechPieApp extends StatefulWidget { final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; final DeadlineWidgetService? deadlineWidgetService; + final SpendingAlertService? spendingAlertService; const TechPieApp({ super.key, @@ -344,6 +353,7 @@ class TechPieApp extends StatefulWidget { required this.ecardBindService, this.ecardWidgetService, this.deadlineWidgetService, + this.spendingAlertService, }); @override @@ -388,6 +398,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { WidgetsBinding.instance.removeObserver(this); widget.ecardWidgetService?.clearOpenPayHandler(); widget.deadlineWidgetService?.dispose(); + widget.spendingAlertService?.dispose(); widget.campusCardService.dispose(); super.dispose(); } @@ -398,6 +409,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { // Coming back is a cheap moment to top the SSO token up, and it is // guarded: a token with time left is left alone. unawaited(widget.authService.tryRenewSession()); + unawaited(widget.spendingAlertService?.synchronize()); unawaited(_checkForUpdatesQuietly()); } } @@ -484,6 +496,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { campusCardService: widget.campusCardService, ecardBindService: widget.ecardBindService, ecardWidgetService: widget.ecardWidgetService, + spendingAlertService: widget.spendingAlertService, child: MaterialApp( navigatorKey: _navigatorKey, scaffoldMessengerKey: rootMessengerKey, diff --git a/lib/pages/campus_card_page.dart b/lib/pages/campus_card_page.dart index e912d60f..d1ce2d35 100644 --- a/lib/pages/campus_card_page.dart +++ b/lib/pages/campus_card_page.dart @@ -47,6 +47,7 @@ class CampusCardPage extends StatelessWidget { ), campusCardEntryProvider.overrideWithValue(entry), homeWidgetPortProvider.overrideWithValue(services?.ecardWidgetService), + spendingAlertPortProvider.overrideWithValue(services?.spendingAlertService), ], child: const CampusCardFeature(), ), diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index dabca46e..ff13d469 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -201,6 +201,7 @@ class _SettingsPageState extends State { tpAuth, campusCard, sp.syncService, + if (sp.spendingAlertService != null) sp.spendingAlertService!, ]), builder: (context, _) { final session = auth.session; @@ -435,6 +436,16 @@ class _SettingsPageState extends State { // General section _sectionHeader(theme, 'General'), + if (sp.spendingAlertService case final spending? when spending.supported) + _AdaptiveSwitchTile( + key: const ValueKey('settings.spending-alerts'), + usesIosLiquidGlass: useIosChrome, + secondary: const Icon(Icons.notifications_active_outlined), + title: '校园卡消费提醒', + subtitle: '刷新发现新消费时通知;后台检查受系统调度限制', + value: spending.enabled, + onChanged: (value) => unawaited(spending.setEnabled(value)), + ), _AdaptiveSwitchTile( key: const ValueKey('settings.mask-personal-info'), usesIosLiquidGlass: useIosChrome, diff --git a/lib/services/service_provider.dart b/lib/services/service_provider.dart index a166d008..296fffdc 100644 --- a/lib/services/service_provider.dart +++ b/lib/services/service_provider.dart @@ -9,6 +9,7 @@ import 'ecard_widget_service.dart'; import 'egate_app_service.dart'; import 'oa_gym_service.dart'; import 'schedule_service.dart'; +import 'spending_alert_service.dart'; import 'storage_service.dart'; import 'sync_service.dart'; import 'theme_service.dart'; @@ -32,6 +33,7 @@ class ServiceProvider extends InheritedWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final SpendingAlertService? spendingAlertService; const ServiceProvider({ super.key, @@ -50,6 +52,7 @@ class ServiceProvider extends InheritedWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.spendingAlertService, required super.child, }); @@ -76,5 +79,6 @@ class ServiceProvider extends InheritedWidget { updateService != oldWidget.updateService || campusCardService != oldWidget.campusCardService || ecardBindService != oldWidget.ecardBindService || - ecardWidgetService != oldWidget.ecardWidgetService; + ecardWidgetService != oldWidget.ecardWidgetService || + spendingAlertService != oldWidget.spendingAlertService; } diff --git a/lib/services/spending_alert_service.dart b/lib/services/spending_alert_service.dart new file mode 100644 index 00000000..6a68bbf0 --- /dev/null +++ b/lib/services/spending_alert_service.dart @@ -0,0 +1,181 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import '../features/campus_card/data/storage/flutter_secure_credential_store.dart'; +import '../features/campus_card/domain/models/bill_models.dart'; +import '../features/campus_card/domain/ports/bill_ports.dart'; +import '../utils/platform.dart'; +import 'auth_service.dart'; +import 'campus_card_service.dart'; +import 'storage_service.dart'; + +/// Opaque scope for notifications; credentials never cross the notification channel. +class SpendingIdentity { + const SpendingIdentity({required this.owner, required this.subjectId}); + final String owner; + final String subjectId; +} + +typedef SpendingIdentityReader = Future Function(); + +/// Full snapshots reach one native ledger shared by foreground/background engines. +/// The first snapshot is a baseline, not a batch of historical receipts. +final class SpendingAlertService extends ChangeNotifier implements SpendingAlertPort { + SpendingAlertService( + this._storage, { + MethodChannel? channel, + SpendingIdentityReader? identityReader, + }) : _channel = channel ?? const MethodChannel('techpie/spending_alerts'), + _identityReader = identityReader; + + final StorageService _storage; + final MethodChannel _channel; + final SpendingIdentityReader? _identityReader; + AuthService? _auth; + CampusCardService? _card; + bool _disposed = false; + int _configurationRevision = 0; + + bool get supported => isAndroid(); + bool get enabled => supported && _storage.spendingAlertsEnabled; + + Future _identity() async { + if (!_storage.privacyAccepted || (_auth != null && !_auth!.isLoggedIn)) return null; + if (_identityReader != null) return _identityReader(); + final primary = await _storage.loadSession(); + if (primary == null) return null; + final store = SecureSessionCredentialStore(FlutterSecureCredentialStore()); + final openId = await store.readOpenId(); + if (openId == null || openId.isEmpty) return null; + final subject = (await store.readOpenIdChannel()).subjectId(openId); + final owner = sha256.convert(utf8.encode(jsonEncode([primary.userId, subject]))).toString(); + return SpendingIdentity(owner: owner, subjectId: subject); + } + + void start(AuthService auth, CampusCardService card) { + if (!supported || _auth != null) return; + _auth = auth; + _card = card; + auth.addListener(_accountChanged); + card.addListener(_accountChanged); + unawaited(synchronize()); + } + + void _accountChanged() => unawaited(synchronize()); + + /// Native configure is idempotent for the same owner, and invalidates in-flight + /// reads plus clears visible receipts on disable, sign-out or account change. + Future synchronize() async { + if (!supported || _disposed) return; + final revision = ++_configurationRevision; + try { + final identity = enabled ? await _identity() : null; + if (_disposed || revision != _configurationRevision) return; + await _channel.invokeMethod('configure', {'owner': identity?.owner}); + } catch (_) { + // Notification setup must never prevent the normal card/account flow. + } + } + + Future setEnabled(bool value) async { + if (!supported || _disposed) return; + await _storage.setSpendingAlertsEnabled(value); + if (_disposed) return; + notifyListeners(); + await synchronize(); + if (value && enabled && !_disposed) { + try { + await _channel.invokeMethod('requestPermission',); + } on PlatformException { + // The system notification setting remains authoritative. + } on MissingPluginException { + // Tests and other platform hosts have no Android bridge. + } + } + } + + Future?> _status() => _channel.invokeMapMethod('status'); + + @override + Future observeTransactions(List records, + {required String subjectId,}) async { + if (!enabled || _disposed) return; + try { + final identity = await _identity(); + if (identity == null || identity.subjectId != subjectId) return; + final status = await _status(); + if (status == null || status['owner'] != identity.owner) return; + await _submit(identity, status, records); + } catch (_) { + // A notification failure is separate from payment and ledger success. + } + } + + Future _submit( + SpendingIdentity identity, + Map status, + List records, + ) async { + if (_disposed || !enabled) return; + final current = await _identity(); + if (current?.owner != identity.owner) return; + await _channel.invokeMethod('observe', { + 'owner': identity.owner, + 'generation': status['generation'], + 'records': records + .take(50) + .map( + (record) => { + 'key': sha256.convert(utf8.encode(record.id)).toString(), + 'at': record.occurredAt.millisecondsSinceEpoch, + 'spending': record.kind == TransactionKind.consumption, + 'title': '消费提醒', + 'body': _body(record), + }, + ) + .toList(), + }); + } + + /// Called only by WorkManager. Capture native generation before I/O so a + /// disable/re-enable during the request cannot turn old results into news. + Future refreshInBackground(Future> Function() load) async { + if (!supported) return true; + try { + await _storage.reloadNotificationPreferences(); + if (!enabled || !_storage.privacyAccepted) return true; + final identity = await _identity(); + final status = await _status(); + if (identity == null || status == null || status['owner'] != identity.owner) return true; + final records = await load(); + await _storage.reloadNotificationPreferences(); + await _submit(identity, status, records); + return true; + } catch (_) { + return false; + } + } + + static String _body(TransactionRecord record) { + final amount = record.amount.toYuanFixed(); + final merchant = record.merchantName ?? record.location ?? record.title; + return [ + amount.startsWith('-') ? amount : '-$amount', + if (merchant.isNotEmpty) merchant, + if (record.balance != null) '余额 ${record.balance!.toYuanFixed()}', + ].join(' · '); + } + + @override + void dispose() { + _disposed = true; + _configurationRevision++; + _auth?.removeListener(_accountChanged); + _card?.removeListener(_accountChanged); + super.dispose(); + } +} diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 7c4e2bab..1b2e9143 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -211,6 +211,11 @@ class StorageService { return raw == null ? null : DateTime.tryParse(raw); } + /// Notifications are opt-in and never change the upstream release defaults. + bool get spendingAlertsEnabled => _prefs.getBool('spending_alerts_enabled') ?? false; + Future setSpendingAlertsEnabled(bool value) => _prefs.setBool('spending_alerts_enabled', value); + Future reloadNotificationPreferences() => _prefs.reload(); + // SharedPreferences for non-sensitive data bool get debugMode => !kReleaseMode && (_prefs.getBool(_debugModeKey) ?? false); diff --git a/lib/spending_background_refresh.dart b/lib/spending_background_refresh.dart new file mode 100644 index 00000000..d25b7f85 --- /dev/null +++ b/lib/spending_background_refresh.dart @@ -0,0 +1,52 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'features/campus_card/app/app_runtime.dart'; +import 'features/campus_card/app/real_runtime_factory.dart'; +import 'features/campus_card/core/config/app_environment.dart'; +import 'features/campus_card/data/auth/geekpie_ecard_session_issuer.dart'; +import 'features/campus_card/domain/ports/bill_ports.dart'; +import 'services/api_base_url.dart'; +import 'services/spending_alert_service.dart'; +import 'services/storage_service.dart'; + +/// A short-lived, activity-free ledger check; never creates a foreground service. +Future runSpendingBackgroundRefresh() async { + WidgetsFlutterBinding.ensureInitialized(); + AppRuntime? runtime; + SpendingAlertService? alerts; + var success = false; + try { + final storage = StorageService(await SharedPreferences.getInstance()); + alerts = SpendingAlertService(storage); + success = await alerts.refreshInBackground(() async { + final card = buildRealRuntime( + AppEnvironment.production, + sessionIssuer: GeekPieEcardSessionIssuer( + endpoint: () => Uri.parse('${apiBaseUrl(storage)}/auth/third-party/ecard'), + ), + ); + runtime = card; + final history = card.transactions; + if (history is! DateRangeTransactionHistoryPort) return []; + final page = await (history as DateRangeTransactionHistoryPort).timelineRange(pageSize: 50); + return page.items; + }); + } catch (_) { + // The worker can retry after a transient network/secure-storage failure. + } finally { + alerts?.dispose(); + try { + await runtime?.dispose(); + } catch (_) {/* The engine is also torn down. */} + try { + await const MethodChannel('techpie/spending_worker') + .invokeMethod('done', {'success': success}); + } on PlatformException { + // The worker was cancelled or timed out. + } on MissingPluginException { + // No background Android host. + } + } +} diff --git a/test/spending_alert_service_test.dart b/test/spending_alert_service_test.dart new file mode 100644 index 00000000..8664c3b6 --- /dev/null +++ b/test/spending_alert_service_test.dart @@ -0,0 +1,188 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/features/campus_card/domain/models/bill_models.dart'; +import 'package:techpie/features/campus_card/domain/money_fen.dart'; +import 'package:techpie/services/spending_alert_service.dart'; +import 'package:techpie/services/storage_service.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('techpie/spending_alerts'); + const identityA = SpendingIdentity(owner: 'owner-a', subjectId: 'subject-a'); + const identityB = SpendingIdentity(owner: 'owner-b', subjectId: 'subject-b'); + late StorageService storage; + late SpendingAlertService service; + SpendingIdentity? identity; + final calls = []; + var generation = 1; + String? nativeOwner; + + TransactionRecord record({String id = 'private-transaction-id', int fen = -1250}) => + TransactionRecord( + id: id, + occurredAt: DateTime.utc(2026, 11, 16, 12), + title: '消费', + amount: MoneyFen(fen), + kind: TransactionKind.consumption, + merchantName: '第一食堂', + balance: const MoneyFen(8800), + ); + + setUp(() async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + SharedPreferences.setMockInitialValues({'privacy_accepted_v1': true}); + storage = StorageService(await SharedPreferences.getInstance()); + calls.clear(); + generation = 1; + identity = identityA; + nativeOwner = 'owner-a'; + service = SpendingAlertService(storage, channel: channel, identityReader: () async => identity); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + calls.add(call); + if (call.method == 'status') return {'owner': nativeOwner, 'generation': generation}; + return true; + }); + }); + + tearDown(() { + service.dispose(); + debugDefaultTargetPlatformOverride = null; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + }); + + test('fresh installs opt out of alerts and background work', () async { + expect(service.enabled, isFalse); + await service.synchronize(); + expect((calls.single.arguments as Map)['owner'], isNull); + calls.clear(); + await service.observeTransactions([record()], subjectId: 'subject-a'); + expect(calls, isEmpty); + }); + + test('enabling configures an opaque account scope and requests permission', () async { + await service.setEnabled(true); + expect(storage.spendingAlertsEnabled, isTrue); + expect(calls.map((c) => c.method), ['configure', 'requestPermission']); + expect((calls.first.arguments as Map)['owner'], 'owner-a'); + }); + + test('missing privacy consent or signed-out identity never activates', () async { + await storage.setSpendingAlertsEnabled(true); + await storage.setPrivacyAccepted(false); + await service.synchronize(); + expect((calls.single.arguments as Map)['owner'], isNull); + calls.clear(); + await storage.setPrivacyAccepted(true); + identity = null; + await service.synchronize(); + expect((calls.single.arguments as Map)['owner'], isNull); + }); + + test('Android only: iOS keeps its own payment and notification behavior', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + await service.setEnabled(true); + await service.synchronize(); + expect(calls, isEmpty); + expect(storage.spendingAlertsEnabled, isFalse); + }); + + test('snapshot carries formatted amount and a hashed transaction key', () async { + await storage.setSpendingAlertsEnabled(true); + await service.observeTransactions([record(fen: 1250)], subjectId: 'subject-a'); + final args = calls.last.arguments as Map; + expect(calls.last.method, 'observe'); + expect(args['owner'], 'owner-a'); + expect(args['generation'], 1); + final row = (args['records'] as List).single as Map; + expect(row['body'], '-12.50 · 第一食堂 · 余额 88.00'); + expect(row['key'], matches(RegExp(r'^[0-9a-f]{64}$'))); + expect(args.toString(), isNot(contains('private-transaction-id'))); + }); + + test('foreground snapshots from a previous card identity are ignored', () async { + await storage.setSpendingAlertsEnabled(true); + identity = identityB; + await service.observeTransactions([record()], subjectId: 'subject-a'); + expect(calls, isEmpty); + }); + + test('snapshots cannot reconfigure a different native owner', () async { + await storage.setSpendingAlertsEnabled(true); + nativeOwner = 'owner-b'; + await service.observeTransactions([record()], subjectId: 'subject-a'); + expect(calls.map((c) => c.method), ['status']); + }); + + test('rapid disable invalidates an outstanding enable configuration', () async { + service.dispose(); + final pending = Completer(); + service = SpendingAlertService(storage, identityReader: () => pending.future); + final enabling = service.setEnabled(true); + await Future.delayed(Duration.zero); + await service.setEnabled(false); + pending.complete(identityA); + await enabling; + expect(calls.where((c) => c.method == 'configure'), hasLength(1)); + expect((calls.single.arguments as Map)['owner'], isNull); + }); + + test('disabled background refresh never calls the network loader', () async { + var loaded = false; + expect( + await service.refreshInBackground(() async { + loaded = true; + return []; + }), + isTrue,); + expect(loaded, isFalse); + expect(calls, isEmpty); + }); + + test('background captures native generation before the network read', () async { + await storage.setSpendingAlertsEnabled(true); + await service.refreshInBackground(() async { + generation = 2; + return [record()]; + }); + expect((calls.last.arguments as Map)['generation'], 1); + }); + + test('disable during network read discards the returned page', () async { + await storage.setSpendingAlertsEnabled(true); + await service.refreshInBackground(() async { + await storage.setSpendingAlertsEnabled(false); + return [record()]; + }); + expect(calls.map((c) => c.method), ['status']); + }); + + test('account switch during network read discards the returned page', () async { + await storage.setSpendingAlertsEnabled(true); + await service.refreshInBackground(() async { + identity = identityB; + return [record()]; + }); + expect(calls.map((c) => c.method), ['status']); + }); + + test('network failure asks WorkManager to retry without publishing', () async { + await storage.setSpendingAlertsEnabled(true); + expect(await service.refreshInBackground(() async => throw StateError('offline')), isFalse); + expect(calls.map((c) => c.method), ['status']); + }); + + test('notification channel failure does not fail payment/history', () async { + await storage.setSpendingAlertsEnabled(true); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (_) async { + throw PlatformException(code: 'denied'); + }); + await service.observeTransactions([record()], subjectId: 'subject-a'); + }); +} diff --git a/test/spending_history_integration_test.dart b/test/spending_history_integration_test.dart new file mode 100644 index 00000000..307917c1 --- /dev/null +++ b/test/spending_history_integration_test.dart @@ -0,0 +1,95 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/features/campus_card/app/app_providers.dart'; +import 'package:techpie/features/campus_card/app/app_runtime.dart'; +import 'package:techpie/features/campus_card/app/demo_runtime_factory.dart'; +import 'package:techpie/features/campus_card/core/config/app_environment.dart'; +import 'package:techpie/features/campus_card/core/config/debug_mode_controller.dart'; +import 'package:techpie/features/campus_card/domain/models/auth_models.dart'; +import 'package:techpie/features/campus_card/domain/models/bill_models.dart'; +import 'package:techpie/features/campus_card/domain/money_fen.dart'; +import 'package:techpie/features/campus_card/domain/ports/bill_ports.dart'; + +class _History implements TransactionHistoryPort, DateRangeTransactionHistoryPort { + Completer? pending; + final records = [TransactionRecord( + id: 'receipt', occurredAt: DateTime.utc(2026, 11, 17), title: 'Meal', + amount: const MoneyFen(-1200), kind: TransactionKind.consumption, + ),]; + @override + Future timelineRange({DateTime? begin, DateTime? end, String? cursor, int pageSize = 20}) async => + pending?.future ?? TransactionPage(items: records, hasMore: false); + @override + Future timeline({required String month, String? cursor, int pageSize = 20}) => timelineRange(); + @override + Future detail(String id) async => records.single; +} + +class _Alerts implements SpendingAlertPort { + final snapshots = >[]; + final subjects = []; + @override + Future observeTransactions(List records, {required String subjectId}) async { + snapshots.add(records); + subjects.add(subjectId); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late AppRuntime base; + late ProviderContainer container; + late _History history; + late _Alerts alerts; + + Future setup({AppEnvironment environment = AppEnvironment.production}) async { + SharedPreferences.setMockInitialValues({}); + base = await buildDemoRuntime(); + await base.auth.signIn(const DemoAuthCredential()); + history = _History(); + alerts = _Alerts(); + final runtime = AppRuntime( + environment: environment, capabilities: base.capabilities, auth: base.auth, + cards: base.cards, paymentCodes: base.paymentCodes, scanPayments: base.scanPayments, + transactions: history, securitySettings: base.securitySettings, + offlinePayments: base.offlinePayments, brightness: base.brightness, + connectivity: base.connectivity, lifecycle: base.lifecycle, feedback: base.feedback, + ); + container = ProviderContainer(overrides: [ + appRuntimeProvider.overrideWithValue(runtime), spendingAlertPortProvider.overrideWithValue(alerts), + ],); + await container.read(authControllerProvider.future); + await Future.delayed(Duration.zero); + addTearDown(() async { container.dispose(); await base.dispose(); }); + } + + test('history refresh sends the complete first page so native code can seed its baseline', () async { + await setup(); + await container.read(accountHistoryRefreshProvider).refresh(); + expect(alerts.snapshots.single.single.id, 'receipt'); + expect(alerts.subjects.single, 'demo-student-001'); + }); + + test('demo runtime cannot produce real consumption notifications', () async { + await setup(environment: AppEnvironment.demo); + await container.read(accountHistoryRefreshProvider).refresh(); + expect(alerts.snapshots, isEmpty); + }); + + test('debug ledger entries cannot produce notifications', () async { + await setup(); + await container.read(debugModeProvider.notifier).setEnabled(true); + await container.read(accountHistoryRefreshProvider).refresh(); + expect(alerts.snapshots, isEmpty); + }); + + test('signed-out ledger refreshes cannot be forwarded to notifications', () async { + await setup(); + await base.auth.signOut(); + await container.read(accountHistoryRefreshProvider).refresh(); + expect(alerts.snapshots, isEmpty); + }); +}