Skip to content

Colota - Android GPS Location tracker

feat: configurable auto-export time and alarm-based scheduling

Max Dietrich569dcdc240ec
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 42a8e684..fb8e206e 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -178,9 +178,10 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A
| `TimedCache` | Generic TTL cache used for queue count, device info, profiles, and network state |
| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |
| `AppLogger` | Centralized logger - always active, all tags prefixed with `Colota.` for logcat filtering |
-| `AutoExportWorker` | WorkManager `CoroutineWorker` for scheduled exports - checks `AutoExportConfig.isExportDue()` on each run, streams chunked writes, verifies output, and cleans up old files beyond retention limit |
-| `AutoExportScheduler` | Schedules a daily (24h) check worker via WorkManager with battery-not-low constraint - frequency logic (daily/weekly/monthly) is handled at runtime by the worker |
-| `AutoExportConfig` | Typed data class wrapping auto-export settings from the SQLite settings table with validation, `isExportDue()`, and `nextExportTimestamp()` |
+| `AutoExportWorker` | WorkManager `CoroutineWorker` enqueued by `AutoExportAlarmReceiver` - performs the export (chunked writes, foreground service, retries, retention cleanup) and re-arms the next alarm in `finally` |
+| `AutoExportAlarmReceiver` | Broadcast receiver fired by AlarmManager at the configured time - hands off to `AutoExportWorker` because the receiver's 10s budget can't run an export |
+| `AutoExportScheduler` | Arms `AlarmManager.setAndAllowWhileIdle` for the next configured wall-clock time. Called on enable, after each worker run, after schedule edits and on boot |
+| `AutoExportConfig` | Typed data class wrapping auto-export settings (interval, time-of-day, weekday, day-of-month, enabledAt) from the SQLite settings table with validation, `isExportDue()` and `nextExportTimestamp()` |
| `ExportConverters` | Native Kotlin export converters (CSV, GeoJSON, GPX, KML) with in-memory, streaming, and file-based (`exportToFile`) interfaces |
| `ShortcutHandlerActivity` | Handles app shortcut intents (start/stop tracking) without showing UI - reads config from DB via `ServiceConfig.fromDatabase()` and dispatches to `LocationForegroundService` |
@@ -205,7 +206,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A
| `TripDetailScreen` | Full trip view with dedicated map, stats grid, speed and elevation profile charts, per-trip export, and per-trip delete |
| `LocationSummaryScreen` | Aggregated stats for selectable periods (week/month/30 days) with daily breakdown and tap-to-inspect navigation |
| `ExportDataScreen` | Export all tracked locations via native streaming converters as CSV, GeoJSON, GPX, or KML |
-| `AutoExportScreen` | Configure scheduled auto-export: directory, format, frequency, export range, and file retention |
+| `AutoExportScreen` | Configure scheduled auto-export: directory, format, frequency, time of day, weekday or day-of-month, export range and file retention |
| `OfflineMapsScreen` | Download and manage offline map areas - interactive bounding box picker, size estimate, progress tracking, and area deletion |
| `DataManagementScreen` | Clear sent history, delete old data, vacuum database, sync controls |
| `SetupImportScreen` | Confirmation screen for `colota://setup` deep link imports |
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.md
index 9fce1e22..bbf3197c 100644
--- a/apps/docs/docs/guides/data-export.md
+++ b/apps/docs/docs/guides/data-export.md
@@ -43,11 +43,11 @@ Automatically export your location data on a schedule without opening the app.
### Setup
-1. Go to **Data Management** > **Export Data**
-2. Tap the **Auto-Export** card at the bottom
-3. Select an export directory (files are saved there via Android's Storage Access Framework)
-4. Choose a format (CSV, GeoJSON, GPX, or KML)
-5. Set the frequency: **Daily**, **Weekly**, or **Monthly**
+1. Go to **Settings > Auto-Export**
+2. Select an export directory (files are saved there via Android's Storage Access Framework)
+3. Choose a format (CSV, GeoJSON, GPX, or KML)
+4. Set the frequency: **Daily**, **Weekly**, or **Monthly**
+5. Pick the **Time** (24-hour) in your device's local timezone. For **Weekly**, also pick a day of week. For **Monthly**, pick a day of month (1-31)
6. Enable the toggle
You can also tap **Export Now** to trigger an immediate export using your current auto-export settings, without waiting for the next scheduled run.
@@ -59,11 +59,13 @@ You can also tap **Export Now** to trigger an immediate export using your curren
### File Retention
-By default, auto-export keeps the last **10** export files and deletes older ones automatically. You can change this in the **File Retention** setting (1, 5, 10, 30, or Unlimited).
+By default, auto-export keeps the last **10** export files and deletes older ones automatically. You can change this in the **File Retention** setting - enter any number or **0** for unlimited (no automatic cleanup).
### How it works
-- Uses Android WorkManager with a daily check interval - the worker runs every 24 hours and checks whether an export is actually due based on your chosen frequency
+- Uses Android AlarmManager (`setAndAllowWhileIdle`) to fire at your configured wall-clock time. Typical accuracy is within minutes; Doze mode may delay by up to ~15 minutes
+- After each export the next alarm is armed automatically. Alarms also re-arm after device reboot
+- Exports fire at the configured time, not on enable. To run an export immediately for testing or backup, tap **Export Now**
- Promotes to a foreground service during export, preventing Android from killing long-running exports
- Streams data in chunks (10,000 locations at a time) to keep memory usage low even with very large datasets
- Writes to a temporary file first, then copies to the export directory - if something goes wrong mid-export, you never get a partial or corrupted file
@@ -74,7 +76,7 @@ By default, auto-export keeps the last **10** export files and deletes older one
- A notification is shown after each export with the file name and location count
- Old export files beyond the retention limit are cleaned up after each successful export
-:::note **Monthly** frequency uses a calendar month (e.g. Jan 15 to Feb 15), not a fixed 30-day interval. **Daily** and **Weekly** intervals are approximate due to Android battery optimization.
+:::note **Monthly** frequency uses a calendar month (e.g. Jan 15 to Feb 15), not a fixed 30-day interval. If the chosen day-of-month doesn't exist in a given month (e.g. day 31 in February), the export runs on the last day of that month instead. **Daily**, **Weekly** and **Monthly** intervals fire at the chosen wall-clock time via Android AlarmManager. Typical accuracy is within minutes.
:::
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index f3217534..00ea959d 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -89,14 +89,15 @@ To change: **Settings > Advanced Settings > Network Settings > Sync Only On**.
## Auto-export not working
-- Verify a directory is selected in **Export Data > Auto-Export**
+- Verify a directory is selected in **Settings > Auto-Export**
- Check that the toggle is enabled
-- Make sure battery is not critically low (exports are deferred when battery is low)
+- The first export fires at the configured time, not on enable. Tap **Export Now** to confirm the pipeline works without waiting
+- Doze mode can delay an alarm by up to ~15 minutes - if exports are running but a few minutes late, that's expected
- If you see a "Directory permission lost" notification, re-select the export directory
- Check that the selected directory still exists and is accessible
- Transient errors (I/O failures) retry up to 3 times automatically; permanent errors (invalid config, directory issues) fail immediately without retrying
- If old exports seem to disappear, check the **File Retention** setting - by default only the last 10 files are kept
-- Check the `AutoExportWorker` log tag in native logs for details
+- Check the `Colota.AutoExportAlarm`, `Colota.AutoExportScheduler` and `Colota.AutoExportWorker` log tags in native logs for details
## Database growing too large
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index edaa2ac0..321558c7 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -46,7 +46,7 @@ Colota has twenty-one screens, each focused on a specific task:
| **Trip Detail** | Full trip view with dedicated map, stats grid (distance, duration, avg speed, elevation), speed and elevation profile charts, export, and delete |
| **Location Summary** | Aggregated stats (total distance, trips, active days, avg distance) for selectable periods with daily breakdown and tap-to-inspect navigation |
| **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML |
-| **Auto-Export** | Configure scheduled exports: format, directory, frequency, export range, and file retention |
+| **Auto-Export** | Configure scheduled exports: directory, format, frequency, time of day (with weekday or day-of-month for weekly/monthly), export range and file retention |
| **Data Management** | Clear sent history, delete old data, vacuum the database |
| **Setup Import** | Confirmation screen for deep link configuration imports (`colota://setup`) |
| **Activity Log** | In-app log viewer with level filtering, search, and export for bug reports |
diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradle
index ab22bd06..ef2406a5 100644
--- a/apps/mobile/android/app/build.gradle
+++ b/apps/mobile/android/app/build.gradle
@@ -216,4 +216,5 @@ dependencies {
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2'
testImplementation 'org.robolectric:robolectric:4.16.1'
testImplementation 'androidx.test:core:1.6.1'
+ testImplementation 'androidx.work:work-testing:2.11.2'
}
diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml
index d6f32959..c58177bf 100644
--- a/apps/mobile/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml
@@ -104,6 +104,12 @@
</intent-filter>
</receiver>
+ <!-- Auto-export alarm receiver -->
+ <receiver
+ android:name=".export.AutoExportAlarmReceiver"
+ android:enabled="true"
+ android:exported="false" />
+
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index 7bdb7930..80135ea5 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -877,7 +877,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
throw Exception("Export directory permission lost. Please re-select the directory.")
}
}
- AutoExportScheduler.schedule(reactApplicationContext)
+ // Anchors isExportDue so the first fire waits for the next configured time.
+ config.saveEnabledAt(dbHelper, System.currentTimeMillis() / 1000)
+ AutoExportScheduler.scheduleNext(reactApplicationContext)
true
}
@@ -887,9 +889,16 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
true
}
+ @ReactMethod
+ fun rescheduleAutoExport(promise: Promise) = executeAsync(promise) {
+ AutoExportScheduler.scheduleNext(reactApplicationContext)
+ true
+ }
+
@ReactMethod
fun cancelAutoExport(promise: Promise) = executeAsync(promise) {
AutoExportScheduler.cancel(reactApplicationContext)
+ AutoExportConfig.from(dbHelper).saveEnabledAt(dbHelper, 0L)
true
}
@@ -911,6 +920,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
putString("lastFileName", config.lastFileName)
putInt("lastRowCount", config.lastRowCount)
putString("lastError", config.lastError)
+ putString("timeOfDay", config.timeOfDay)
+ putInt("weeklyDow", config.weeklyDow)
+ putInt("monthlyDom", config.monthlyDom)
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
index ed86dccd..643ecb12 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
@@ -18,8 +18,8 @@ class GeofenceHelper(private val context: Context) {
private val dbHelper by lazy { DatabaseHelper.getInstance(context) }
- /** Runtime view of an enabled pause-tracking geofence (what the service reads). */
- data class CachedGeofence(
+ /** Runtime view of an enabled pause-tracking geofence row. */
+ data class Geofence(
val name: String,
val lat: Double,
val lon: Double,
@@ -35,10 +35,10 @@ class GeofenceHelper(private val context: Context) {
private const val TAG = "GeofenceHelper"
}
- fun getGeofenceByName(name: String): CachedGeofence? =
+ fun getGeofenceByName(name: String): Geofence? =
loadGeofencesFromDB().find { it.name == name }
- fun getPauseZone(location: Location): CachedGeofence? {
+ fun getPauseZone(location: Location): Geofence? {
val match = loadGeofencesFromDB().find {
isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)
}
@@ -49,9 +49,9 @@ class GeofenceHelper(private val context: Context) {
return match
}
- private fun loadGeofencesFromDB(): List<CachedGeofence> {
+ private fun loadGeofencesFromDB(): List<Geofence> {
return try {
- val fences = mutableListOf<CachedGeofence>()
+ val fences = mutableListOf<Geofence>()
dbHelper.readableDatabase.query(
DatabaseHelper.TABLE_GEOFENCES,
arrayOf(
@@ -73,7 +73,7 @@ class GeofenceHelper(private val context: Context) {
val heartbeatIntervalIdx = cursor.getColumnIndexOrThrow("heartbeat_interval_minutes")
while (cursor.moveToNext()) {
- fences.add(CachedGeofence(
+ fences.add(Geofence(
name = cursor.getString(nameIdx),
lat = cursor.getDouble(latIdx),
lon = cursor.getDouble(lonIdx),
@@ -89,7 +89,7 @@ class GeofenceHelper(private val context: Context) {
AppLogger.d(TAG, "Loaded ${fences.size} active pause zone(s)")
fences
} catch (e: Exception) {
- AppLogger.e(TAG, "Failed to refresh geofence cache", e)
+ AppLogger.e(TAG, "Failed to load geofences from DB", e)
emptyList()
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportAlarmReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportAlarmReceiver.kt
new file mode 100644
index 00000000..5ec3c270
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportAlarmReceiver.kt
@@ -0,0 +1,32 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.export
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import androidx.work.OneTimeWorkRequestBuilder
+import androidx.work.WorkManager
+import com.Colota.util.AppLogger
+
+class AutoExportAlarmReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ AppLogger.i(TAG, "Alarm fired")
+ try {
+ WorkManager.getInstance(context.applicationContext)
+ .enqueue(OneTimeWorkRequestBuilder<AutoExportWorker>().build())
+ } catch (e: Exception) {
+ // Next alarm or boot will re-arm; just log so the failure is diagnosable.
+ AppLogger.e(TAG, "Failed to enqueue export worker", e)
+ }
+ }
+
+ companion object {
+ private const val TAG = "AutoExportAlarm"
+ const val ACTION_FIRE = "com.Colota.export.action.FIRE_AUTO_EXPORT"
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt
index d822588d..12e7ed78 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt
@@ -6,6 +6,8 @@
package com.Colota.export
import com.Colota.data.DatabaseHelper
+import java.util.Calendar
+import java.util.TimeZone
/**
* Typed wrapper for auto-export settings stored in the SQLite settings table.
@@ -22,7 +24,11 @@ data class AutoExportConfig(
val retentionCount: Int = 10,
val lastFileName: String? = null,
val lastRowCount: Int = 0,
- val lastError: String? = null
+ val lastError: String? = null,
+ val timeOfDay: String = "00:00",
+ val weeklyDow: Int = 1,
+ val monthlyDom: Int = 1,
+ val enabledAt: Long = 0L
) {
companion object {
private const val KEY_ENABLED = "autoExportEnabled"
@@ -36,15 +42,38 @@ data class AutoExportConfig(
private const val KEY_LAST_FILE_NAME = "autoExportLastFileName"
private const val KEY_LAST_ROW_COUNT = "autoExportLastRowCount"
private const val KEY_LAST_ERROR = "autoExportLastError"
+ private const val KEY_TIME_OF_DAY = "autoExportTimeOfDay"
+ private const val KEY_WEEKLY_DOW = "autoExportWeeklyDow"
+ private const val KEY_MONTHLY_DOM = "autoExportMonthlyDom"
+ private const val KEY_ENABLED_AT = "autoExportEnabledAt"
private val VALID_FORMATS = setOf("csv", "geojson", "gpx", "kml")
private val VALID_INTERVALS = setOf("daily", "weekly", "monthly")
private val VALID_MODES = setOf("all", "incremental")
+ private val TIME_OF_DAY_REGEX = Regex("^([01]\\d|2[0-3]):([0-5]\\d)$")
+
fun from(db: DatabaseHelper): AutoExportConfig {
val format = db.getSetting(KEY_FORMAT, "geojson") ?: "geojson"
val interval = db.getSetting(KEY_INTERVAL, "daily") ?: "daily"
val mode = db.getSetting(KEY_MODE, "all") ?: "all"
+ val lastTs = db.getSetting(KEY_LAST_TIMESTAMP, "0")?.toLongOrNull() ?: 0L
+
+ val rawTime = db.getSetting(KEY_TIME_OF_DAY)
+ val rawDow = db.getSetting(KEY_WEEKLY_DOW)?.toIntOrNull()
+ val rawDom = db.getSetting(KEY_MONTHLY_DOM)?.toIntOrNull()
+
+ // Derive from lastTs and persist once, otherwise each export would shift
+ // the derived time forward by a few seconds. Skip the write on fresh
+ // installs where there's nothing to migrate from.
+ val derived = deriveScheduleFrom(lastTs)
+ val shouldPersistMigration = lastTs > 0L
+ val timeOfDay = rawTime?.takeIf { TIME_OF_DAY_REGEX.matches(it) }
+ ?: derived.timeOfDay.also { if (shouldPersistMigration) db.saveSetting(KEY_TIME_OF_DAY, it) }
+ val weeklyDow = rawDow?.coerceIn(1, 7)
+ ?: derived.weeklyDow.also { if (shouldPersistMigration) db.saveSetting(KEY_WEEKLY_DOW, it.toString()) }
+ val monthlyDom = rawDom?.coerceIn(1, 31)
+ ?: derived.monthlyDom.also { if (shouldPersistMigration) db.saveSetting(KEY_MONTHLY_DOM, it.toString()) }
return AutoExportConfig(
enabled = db.getSetting(KEY_ENABLED, "false") == "true",
@@ -52,20 +81,45 @@ data class AutoExportConfig(
interval = if (interval in VALID_INTERVALS) interval else "daily",
mode = if (mode in VALID_MODES) mode else "all",
uri = db.getSetting(KEY_URI),
- lastExportTimestamp = db.getSetting(KEY_LAST_TIMESTAMP, "0")?.toLongOrNull() ?: 0L,
+ lastExportTimestamp = lastTs,
permissionLost = db.getSetting(KEY_PERMISSION_LOST, "false") == "true",
retentionCount = db.getSetting(KEY_RETENTION_COUNT, "10")?.toIntOrNull() ?: 10,
lastFileName = db.getSetting(KEY_LAST_FILE_NAME),
lastRowCount = db.getSetting(KEY_LAST_ROW_COUNT, "0")?.toIntOrNull() ?: 0,
- lastError = db.getSetting(KEY_LAST_ERROR)
+ lastError = db.getSetting(KEY_LAST_ERROR),
+ timeOfDay = timeOfDay,
+ weeklyDow = weeklyDow,
+ monthlyDom = monthlyDom,
+ enabledAt = db.getSetting(KEY_ENABLED_AT, "0")?.toLongOrNull() ?: 0L
+ )
+ }
+
+ private data class DerivedSchedule(val timeOfDay: String, val weeklyDow: Int, val monthlyDom: Int)
+
+ private fun deriveScheduleFrom(lastTs: Long): DerivedSchedule {
+ if (lastTs <= 0L) return DerivedSchedule("00:00", 1, 1)
+ val cal = Calendar.getInstance(TimeZone.getDefault())
+ cal.timeInMillis = lastTs * 1000
+ return DerivedSchedule(
+ timeOfDay = "%02d:%02d".format(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)),
+ weeklyDow = calendarDowToIso(cal.get(Calendar.DAY_OF_WEEK)),
+ monthlyDom = cal.get(Calendar.DAY_OF_MONTH)
)
}
+
+ // Calendar.DAY_OF_WEEK uses Sun=1..Sat=7; we use ISO Mon=1..Sun=7.
+ internal fun calendarDowToIso(calDow: Int): Int = ((calDow + 5) % 7) + 1
+ internal fun isoToCalendarDow(iso: Int): Int = (iso % 7) + 1
}
fun saveEnabled(db: DatabaseHelper, value: Boolean) {
db.saveSetting(KEY_ENABLED, value.toString())
}
+ fun saveEnabledAt(db: DatabaseHelper, timestamp: Long) {
+ db.saveSetting(KEY_ENABLED_AT, timestamp.toString())
+ }
+
fun saveLastExportTimestamp(db: DatabaseHelper, timestamp: Long) {
db.saveSetting(KEY_LAST_TIMESTAMP, timestamp.toString())
}
@@ -84,31 +138,118 @@ data class AutoExportConfig(
db.saveSetting(KEY_LAST_ERROR, error)
}
- /**
- * Calculates the next export timestamp based on interval and last export time.
- * Uses Calendar for monthly to handle variable month lengths.
- */
- fun nextExportTimestamp(): Long {
- if (!enabled || lastExportTimestamp == 0L) return 0L
+ fun nextExportTimestamp(): Long = nextExportTimestampAt(System.currentTimeMillis())
+
+ internal fun nextExportTimestampAt(nowMs: Long): Long {
+ if (!enabled) return 0L
+ val (hh, mm) = parseTimeOfDay(timeOfDay)
+ val zone = TimeZone.getDefault()
+
return when (interval) {
- "daily" -> lastExportTimestamp + (24 * 3600)
- "weekly" -> lastExportTimestamp + (168 * 3600)
- "monthly" -> {
- val cal = java.util.Calendar.getInstance()
- cal.timeInMillis = lastExportTimestamp * 1000
- cal.add(java.util.Calendar.MONTH, 1)
- cal.timeInMillis / 1000
- }
- else -> lastExportTimestamp + (24 * 3600)
+ "weekly" -> nextWeekly(zone, hh, mm, nowMs)
+ "monthly" -> nextMonthly(zone, hh, mm, nowMs)
+ else -> nextDaily(zone, hh, mm, nowMs)
+ }
+ }
+
+ private fun nextDaily(zone: TimeZone, hh: Int, mm: Int, nowMs: Long): Long {
+ val cal = todayAtTimeOfDay(zone, hh, mm, nowMs)
+ if (cal.timeInMillis <= nowMs) cal.add(Calendar.DAY_OF_YEAR, 1)
+ return cal.timeInMillis / 1000
+ }
+
+ private fun nextWeekly(zone: TimeZone, hh: Int, mm: Int, nowMs: Long): Long {
+ val cal = todayAtTimeOfDay(zone, hh, mm, nowMs)
+ val delta = forwardDeltaToWeekday(cal.get(Calendar.DAY_OF_WEEK), weeklyDow)
+ cal.add(Calendar.DAY_OF_YEAR, delta)
+ if (cal.timeInMillis <= nowMs) cal.add(Calendar.DAY_OF_YEAR, 7)
+ return cal.timeInMillis / 1000
+ }
+
+ private fun nextMonthly(zone: TimeZone, hh: Int, mm: Int, nowMs: Long): Long {
+ val thisMonth = monthlyOccurrenceMs(zone, hh, mm, nowMs, 0)
+ val ms = if (thisMonth > nowMs) thisMonth else monthlyOccurrenceMs(zone, hh, mm, nowMs, 1)
+ return ms / 1000
+ }
+
+ private fun todayAtTimeOfDay(zone: TimeZone, hh: Int, mm: Int, nowMs: Long): Calendar =
+ Calendar.getInstance(zone).apply {
+ timeInMillis = nowMs
+ set(Calendar.HOUR_OF_DAY, hh)
+ set(Calendar.MINUTE, mm)
+ set(Calendar.SECOND, 0)
+ set(Calendar.MILLISECOND, 0)
+ }
+
+ // DOM clamped to month length (Feb 31 -> Feb 28/29).
+ private fun monthlyOccurrenceMs(
+ zone: TimeZone,
+ hh: Int,
+ mm: Int,
+ baseMs: Long,
+ monthOffset: Int
+ ): Long {
+ val cal = Calendar.getInstance(zone).apply {
+ timeInMillis = baseMs
+ set(Calendar.DAY_OF_MONTH, 1)
+ set(Calendar.HOUR_OF_DAY, hh)
+ set(Calendar.MINUTE, mm)
+ set(Calendar.SECOND, 0)
+ set(Calendar.MILLISECOND, 0)
+ if (monthOffset != 0) add(Calendar.MONTH, monthOffset)
}
+ cal.set(Calendar.DAY_OF_MONTH, monthlyDom.coerceAtMost(cal.getActualMaximum(Calendar.DAY_OF_MONTH)))
+ return cal.timeInMillis
+ }
+
+ private fun forwardDeltaToWeekday(currentCalDow: Int, targetIso: Int): Int {
+ var delta = isoToCalendarDow(targetIso) - currentCalDow
+ if (delta < 0) delta += 7
+ return delta
+ }
+
+ private fun backwardDeltaToWeekday(currentCalDow: Int, targetIso: Int): Int {
+ var delta = isoToCalendarDow(targetIso) - currentCalDow
+ if (delta > 0) delta -= 7
+ return delta
+ }
+
+ private fun parseTimeOfDay(value: String): Pair<Int, Int> {
+ val match = TIME_OF_DAY_REGEX.matchEntire(value) ?: return 0 to 0
+ return match.groupValues[1].toInt() to match.groupValues[2].toInt()
}
- /**
- * Checks if an export is currently due based on interval timing.
- */
- fun isExportDue(): Boolean {
- if (lastExportTimestamp == 0L) return true // never exported, do it now
- val now = System.currentTimeMillis() / 1000
- return now >= nextExportTimestamp()
+ fun isExportDue(): Boolean = isExportDueAt(System.currentTimeMillis())
+
+ internal fun isExportDueAt(nowMs: Long): Boolean {
+ if (!enabled) return false
+ val now = nowMs / 1000
+ val (hh, mm) = parseTimeOfDay(timeOfDay)
+ val zone = TimeZone.getDefault()
+ val mostRecent = mostRecentScheduledAtOrBeforeMs(zone, hh, mm, nowMs) / 1000
+ val cutoff = maxOf(lastExportTimestamp, enabledAt)
+ return now >= mostRecent && cutoff < mostRecent
+ }
+
+ private fun mostRecentScheduledAtOrBeforeMs(zone: TimeZone, hh: Int, mm: Int, nowMs: Long): Long {
+ return when (interval) {
+ "weekly" -> {
+ val cal = todayAtTimeOfDay(zone, hh, mm, nowMs)
+ val delta = backwardDeltaToWeekday(cal.get(Calendar.DAY_OF_WEEK), weeklyDow)
+ cal.add(Calendar.DAY_OF_YEAR, delta)
+ if (cal.timeInMillis > nowMs) cal.add(Calendar.DAY_OF_YEAR, -7)
+ cal.timeInMillis
+ }
+ "monthly" -> {
+ val thisMonth = monthlyOccurrenceMs(zone, hh, mm, nowMs, 0)
+ if (thisMonth <= nowMs) thisMonth
+ else monthlyOccurrenceMs(zone, hh, mm, nowMs, -1)
+ }
+ else -> {
+ val cal = todayAtTimeOfDay(zone, hh, mm, nowMs)
+ if (cal.timeInMillis > nowMs) cal.add(Calendar.DAY_OF_YEAR, -1)
+ cal.timeInMillis
+ }
+ }
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt
index 5fb8aa91..1ba35d90 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt
@@ -5,64 +5,75 @@
package com.Colota.export
+import android.app.AlarmManager
+import android.app.PendingIntent
import android.content.Context
-import androidx.work.ExistingPeriodicWorkPolicy
+import android.content.Intent
+import androidx.annotation.WorkerThread
import androidx.work.OneTimeWorkRequestBuilder
-import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
+import com.Colota.data.DatabaseHelper
import com.Colota.util.AppLogger
-import java.util.concurrent.TimeUnit
/**
- * Manages scheduling/cancelling of periodic auto-export via WorkManager.
- *
- * Always schedules a daily (24h) worker. The worker itself checks
- * AutoExportConfig.isExportDue() to determine whether an export should
- * actually run (daily/weekly/monthly). This avoids unreliable long-interval
- * periodic work (e.g. 720h for monthly) and ensures calendar-accurate
- * monthly scheduling.
+ * AlarmManager-based scheduling. Worker reschedules the next slot on completion;
+ * BootReceiver re-arms after reboot. Uses setAndAllowWhileIdle to avoid the
+ * SCHEDULE_EXACT_ALARM permission, accepting ~minute accuracy in exchange.
*/
object AutoExportScheduler {
private const val TAG = "AutoExportScheduler"
- private const val WORK_NAME = "colota_auto_export"
- private const val CHECK_INTERVAL_HOURS = 24L
+ private const val ALARM_REQUEST_CODE = 9101
+ internal const val IMMEDIATE_WORK_TAG = "colota_auto_export_now"
+ // From the pre-AlarmManager build; cancelled here for upgrade hygiene.
+ private const val LEGACY_PERIODIC_WORK_NAME = "colota_auto_export"
- /**
- * Schedules the daily auto-export check worker.
- */
- fun schedule(context: Context) {
- val request = PeriodicWorkRequestBuilder<AutoExportWorker>(
- CHECK_INTERVAL_HOURS, TimeUnit.HOURS
- )
- .build()
-
- WorkManager.getInstance(context).enqueueUniquePeriodicWork(
- WORK_NAME,
- ExistingPeriodicWorkPolicy.UPDATE,
- request
- )
+ @WorkerThread
+ fun scheduleNext(context: Context) {
+ WorkManager.getInstance(context.applicationContext)
+ .cancelUniqueWork(LEGACY_PERIODIC_WORK_NAME)
- AppLogger.i(TAG, "Scheduled auto-export check (every ${CHECK_INTERVAL_HOURS}h)")
+ val db = DatabaseHelper.getInstance(context)
+ val config = AutoExportConfig.from(db)
+ if (!config.enabled) {
+ AppLogger.d(TAG, "Auto-export disabled, not scheduling")
+ return
+ }
+ val nextTs = config.nextExportTimestamp()
+ if (nextTs <= 0L) {
+ AppLogger.d(TAG, "No next export timestamp computed")
+ return
+ }
+ val triggerAtMillis = nextTs * 1000
+ val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ val pi = pendingIntent(context)
+ am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pi)
+ AppLogger.i(TAG, "Scheduled auto-export alarm for $nextTs (epoch s)")
}
- /**
- * Enqueues a one-time auto-export that runs immediately, bypassing isExportDue().
- */
fun runNow(context: Context) {
val request = OneTimeWorkRequestBuilder<AutoExportWorker>()
- .addTag("colota_auto_export_now")
+ .addTag(IMMEDIATE_WORK_TAG)
.build()
-
- WorkManager.getInstance(context).enqueue(request)
+ WorkManager.getInstance(context.applicationContext).enqueue(request)
AppLogger.i(TAG, "Enqueued immediate auto-export")
}
- /**
- * Cancels any scheduled auto-export work.
- */
fun cancel(context: Context) {
- WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
- AppLogger.i(TAG, "Cancelled auto-export")
+ val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ am.cancel(pendingIntent(context))
+ AppLogger.i(TAG, "Cancelled auto-export alarm")
+ }
+
+ private fun pendingIntent(context: Context): PendingIntent {
+ val intent = Intent(context, AutoExportAlarmReceiver::class.java).apply {
+ action = AutoExportAlarmReceiver.ACTION_FIRE
+ }
+ return PendingIntent.getBroadcast(
+ context,
+ ALARM_REQUEST_CODE,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
index dfe6222e..76fe6372 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
@@ -26,8 +26,10 @@ import java.io.File
import java.io.IOException
/**
- * Runs daily and asks AutoExportConfig.isExportDue() whether the configured
- * daily/weekly/monthly cadence has actually elapsed. Runs without the JS runtime.
+ * Performs the actual export. Triggered by AutoExportAlarmReceiver when the
+ * configured time arrives, or by an immediate "Export Now" enqueue. Runs as
+ * a foreground service so the OS does not kill long exports. Runs without the
+ * JS runtime.
*/
class AutoExportWorker(
private val appContext: Context,
@@ -59,6 +61,21 @@ class AutoExportWorker(
}
override suspend fun doWork(): Result {
+ val isManualRun = tags.contains(AutoExportScheduler.IMMEDIATE_WORK_TAG)
+ return try {
+ executeWork(isManualRun)
+ } finally {
+ if (!isManualRun) {
+ try {
+ AutoExportScheduler.scheduleNext(appContext)
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "scheduleNext failed: ${e.message}")
+ }
+ }
+ }
+ }
+
+ private suspend fun executeWork(isManualRun: Boolean): Result {
if (runAttemptCount >= MAX_RETRIES) {
AppLogger.e(TAG, "Auto-export failed after $MAX_RETRIES attempts, giving up")
showNotification("Auto-Export Failed", "Export failed after multiple attempts. Please check your settings.")
@@ -78,13 +95,13 @@ class AutoExportWorker(
return Result.failure()
}
- val isManualRun = tags.contains("colota_auto_export_now")
+ // Guards against early fires from stale alarms or mid-flight schedule edits.
if (!isManualRun && !config.isExportDue()) {
- AppLogger.d(TAG, "Export not yet due, skipping")
+ AppLogger.i(TAG, "Not due. ${config.interval} ${config.timeOfDay} next=${config.nextExportTimestamp()}")
return Result.success()
}
- AppLogger.i(TAG, "Starting auto-export: format=${config.format}, mode=${config.mode}")
+ AppLogger.i(TAG, "Starting export: format=${config.format} mode=${config.mode}")
// Some OEMs (Samsung, Xiaomi) throw under aggressive background restrictions;
// the export often still completes.
@@ -103,11 +120,14 @@ class AutoExportWorker(
// Write to cache first, then copy to SAF.
val tempFile = File(appContext.cacheDir, "auto_export_temp$ext")
+ // Used for both the incremental upper bound and the saved lastExport,
+ // so points written mid-export aren't dropped.
+ val exportStartSec = System.currentTimeMillis() / 1000
+
return try {
val rowCount = if (config.mode == "incremental" && config.lastExportTimestamp > 0) {
- val now = System.currentTimeMillis() / 1000
ExportConverters.exportToFile(config.format, tempFile, shouldCancel = { isStopped }) { limit, offset ->
- db.getLocationsByDateRange(config.lastExportTimestamp, now, limit, offset)
+ db.getLocationsByDateRange(config.lastExportTimestamp, exportStartSec, limit, offset)
}
} else {
ExportConverters.exportToFile(config.format, tempFile, shouldCancel = { isStopped }) { limit, offset ->
@@ -143,8 +163,7 @@ class AutoExportWorker(
tempFile.delete()
- val now = System.currentTimeMillis() / 1000
- config.saveLastExportTimestamp(db, now)
+ config.saveLastExportTimestamp(db, exportStartSec)
cleanupOldExports(dirUri, config.retentionCount)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
index 638d659b..f08039e1 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
@@ -11,6 +11,7 @@ import android.content.Context
import android.content.Intent
import com.Colota.data.DatabaseHelper
import com.Colota.data.SettingsKeys
+import com.Colota.export.AutoExportScheduler
import com.Colota.util.AppLogger
import com.Colota.util.DeviceInfoHelper
import kotlinx.coroutines.*
@@ -76,13 +77,20 @@ class LocationBootReceiver : BroadcastReceiver() {
private suspend fun handleBootCompleted(context: Context, action: String) {
try {
val dbHelper = DatabaseHelper.getInstance(context)
-
+
// Wait for database to be ready
if (!waitForDatabaseReady(dbHelper)) {
AppLogger.e(TAG, "Database not ready after $MAX_DB_RETRIES attempts")
return
}
-
+
+ // Alarms don't survive reboot. No-op if auto-export is disabled.
+ try {
+ AutoExportScheduler.scheduleNext(context)
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "scheduleNext failed on boot: ${e.message}")
+ }
+
val isEnabled = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"
if (!isEnabled) {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
index ac42f5b8..a72c5da5 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
@@ -94,8 +94,8 @@ class LocationForegroundService : Service() {
*/
@Volatile private var insidePauseZone = false
@Volatile private var currentZoneName: String? = null
- @Volatile private var currentZoneGeofence: GeofenceHelper.CachedGeofence? = null
- @Volatile private var pendingPauseZone: GeofenceHelper.CachedGeofence? = null
+ @Volatile private var currentZoneGeofence: GeofenceHelper.Geofence? = null
+ @Volatile private var pendingPauseZone: GeofenceHelper.Geofence? = null
@Volatile private var entryDelayJob: Job? = null
@Volatile private var heartbeatJob: Job? = null
@@ -514,7 +514,7 @@ class LocationForegroundService : Service() {
* Re-applies WiFi/motionless pause settings from a freshly loaded zone object.
* Called on RECHECK when already inside the zone so editor changes take effect immediately.
*/
- private fun applyZoneSettingsIfChanged(zone: GeofenceHelper.CachedGeofence) {
+ private fun applyZoneSettingsIfChanged(zone: GeofenceHelper.Geofence) {
val timeoutChanged = currentZoneGeofence?.motionlessTimeoutMinutes != zone.motionlessTimeoutMinutes
val heartbeatChanged = currentZoneGeofence?.heartbeatIntervalMinutes != zone.heartbeatIntervalMinutes
currentZoneGeofence = zone
@@ -551,7 +551,7 @@ class LocationForegroundService : Service() {
* Applies zone entry/exit state transitions common to both live location updates
* and manual zone rechecks. Returns the anchor [Job] if a zone exit was triggered.
*/
- private fun applyZoneTransition(zone: GeofenceHelper.CachedGeofence?): Job? {
+ private fun applyZoneTransition(zone: GeofenceHelper.Geofence?): Job? {
return when {
zone != null && (!insidePauseZone || zone.name != currentZoneName) -> {
if (pendingPauseZone?.name != zone.name) startEntryDelay(zone)
@@ -667,7 +667,7 @@ class LocationForegroundService : Service() {
* like GeoPulse enough arrival points for reliable trip detection.
* If the device exits the zone before the delay completes, the delay is cancelled.
*/
- private fun startEntryDelay(geofence: GeofenceHelper.CachedGeofence) {
+ private fun startEntryDelay(geofence: GeofenceHelper.Geofence) {
entryDelayJob?.cancel()
pendingPauseZone = geofence
@@ -701,7 +701,7 @@ class LocationForegroundService : Service() {
refreshNotificationForCurrentState()
}
- private fun enterPauseZone(geofence: GeofenceHelper.CachedGeofence) {
+ private fun enterPauseZone(geofence: GeofenceHelper.Geofence) {
insidePauseZone = true
currentZoneName = geofence.name
currentZoneGeofence = geofence
@@ -752,7 +752,7 @@ class LocationForegroundService : Service() {
* Starts any pause-zone holds (WiFi, motionless, heartbeat) that the zone has enabled.
* Must stay mirrored with [stopZoneHolds] - when adding a new hold, update both.
*/
- private fun startZoneHolds(zone: GeofenceHelper.CachedGeofence) {
+ private fun startZoneHolds(zone: GeofenceHelper.Geofence) {
if (zone.pauseOnWifi) registerWifiPause()
if (zone.pauseOnMotionless) startMotionlessCountdown(zone.motionlessTimeoutMinutes)
if (zone.heartbeatEnabled) startHeartbeat(zone.heartbeatIntervalMinutes)
@@ -1005,7 +1005,7 @@ class LocationForegroundService : Service() {
}
/** Logs a synthetic location at the geofence center on zone exit to give the departing trip a clean start point. */
- private fun saveAnchorPoint(geofence: GeofenceHelper.CachedGeofence): Job? {
+ private fun saveAnchorPoint(geofence: GeofenceHelper.Geofence): Job? {
if (!::config.isInitialized) {
AppLogger.w(TAG, "Config not yet initialized, skipping anchor point for '${geofence.name}'")
return null
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt
index dd8e4c05..dd2d15c0 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt
@@ -1,153 +1,173 @@
package com.Colota.export
+import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
+import org.junit.After
import org.junit.Assert.*
+import org.junit.Before
import org.junit.Test
+import java.util.Calendar
+import java.util.TimeZone
class AutoExportConfigTest {
- // --- isExportDue ---
+ private val originalTimeZone = TimeZone.getDefault()
- @Test
- fun `isExportDue returns true when never exported`() {
- val config = AutoExportConfig(enabled = true, lastExportTimestamp = 0L)
- assertTrue(config.isExportDue())
+ @Before
+ fun setUp() {
+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
}
- @Test
- fun `isExportDue returns true when daily interval has passed`() {
- val now = System.currentTimeMillis() / 1000
- val config = AutoExportConfig(
- enabled = true,
- interval = "daily",
- lastExportTimestamp = now - (25 * 3600) // 25 hours ago
- )
- assertTrue(config.isExportDue())
+ @After
+ fun tearDown() {
+ TimeZone.setDefault(originalTimeZone)
}
- @Test
- fun `isExportDue returns false when daily interval has not passed`() {
- val now = System.currentTimeMillis() / 1000
- val config = AutoExportConfig(
- enabled = true,
- interval = "daily",
- lastExportTimestamp = now - (23 * 3600) // 23 hours ago
- )
- assertFalse(config.isExportDue())
+ private fun atUtc(year: Int, month: Int, day: Int, hh: Int = 0, mm: Int = 0): Long {
+ val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
+ cal.set(year, month - 1, day, hh, mm, 0)
+ cal.set(Calendar.MILLISECOND, 0)
+ return cal.timeInMillis / 1000
}
+ // --- isExportDue ---
+
@Test
- fun `isExportDue returns true when weekly interval has passed`() {
- val now = System.currentTimeMillis() / 1000
- val config = AutoExportConfig(
- enabled = true,
- interval = "weekly",
- lastExportTimestamp = now - (169 * 3600) // 169 hours ago (> 168)
- )
- assertTrue(config.isExportDue())
+ fun `isExportDue returns false when disabled`() {
+ val config = AutoExportConfig(enabled = false, lastExportTimestamp = 0L)
+ assertFalse(config.isExportDue())
}
@Test
- fun `isExportDue returns false when weekly interval has not passed`() {
- val now = System.currentTimeMillis() / 1000
+ fun `enable after today's slot waits for tomorrow`() {
val config = AutoExportConfig(
enabled = true,
- interval = "weekly",
- lastExportTimestamp = now - (167 * 3600) // 167 hours ago (< 168)
+ interval = "daily",
+ timeOfDay = "09:00",
+ enabledAt = atUtc(2025, 6, 8, 14, 0)
)
- assertFalse(config.isExportDue())
+ assertFalse(config.isExportDueAt(atUtc(2025, 6, 8, 14, 1) * 1000))
+ assertFalse(config.isExportDueAt(atUtc(2025, 6, 9, 8, 59) * 1000))
+ assertTrue(config.isExportDueAt(atUtc(2025, 6, 9, 9, 1) * 1000))
}
@Test
- fun `isExportDue returns true when monthly interval has passed`() {
- val now = System.currentTimeMillis() / 1000
+ fun `enable before today's slot fires today`() {
val config = AutoExportConfig(
enabled = true,
- interval = "monthly",
- lastExportTimestamp = now - (32L * 24 * 3600) // 32 days ago
+ interval = "daily",
+ timeOfDay = "09:00",
+ enabledAt = atUtc(2025, 6, 8, 8, 0)
)
- assertTrue(config.isExportDue())
+ assertFalse(config.isExportDueAt(atUtc(2025, 6, 8, 8, 30) * 1000))
+ assertTrue(config.isExportDueAt(atUtc(2025, 6, 8, 9, 1) * 1000))
}
@Test
- fun `isExportDue returns false when monthly interval has not passed`() {
- val now = System.currentTimeMillis() / 1000
+ fun `same-slot double-fire is blocked`() {
val config = AutoExportConfig(
enabled = true,
- interval = "monthly",
- lastExportTimestamp = now - (27L * 24 * 3600) // 27 days ago
+ interval = "daily",
+ timeOfDay = "12:00",
+ lastExportTimestamp = atUtc(2025, 6, 9, 12, 1)
)
- assertFalse(config.isExportDue())
+ assertFalse(config.isExportDueAt(atUtc(2025, 6, 9, 12, 5) * 1000))
}
// --- nextExportTimestamp ---
@Test
fun `nextExportTimestamp returns 0 when disabled`() {
- val config = AutoExportConfig(enabled = false, lastExportTimestamp = 1000L)
+ val config = AutoExportConfig(enabled = false)
assertEquals(0L, config.nextExportTimestamp())
}
@Test
- fun `nextExportTimestamp returns 0 when never exported`() {
- val config = AutoExportConfig(enabled = true, lastExportTimestamp = 0L)
- assertEquals(0L, config.nextExportTimestamp())
+ fun `daily nextExportTimestamp anchors to configured time of day`() {
+ val config = AutoExportConfig(
+ enabled = true,
+ interval = "daily",
+ timeOfDay = "12:30"
+ )
+ val next = config.nextExportTimestamp()
+ val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
+ cal.timeInMillis = next * 1000
+ assertEquals(12, cal.get(Calendar.HOUR_OF_DAY))
+ assertEquals(30, cal.get(Calendar.MINUTE))
+ assertTrue("Next must be in the future", next > System.currentTimeMillis() / 1000)
}
@Test
- fun `nextExportTimestamp adds 24h for daily`() {
- val last = 1700000000L
+ fun `weekly nextExportTimestamp picks configured weekday`() {
val config = AutoExportConfig(
enabled = true,
- interval = "daily",
- lastExportTimestamp = last
+ interval = "weekly",
+ timeOfDay = "09:00",
+ weeklyDow = 1 // Monday
)
- assertEquals(last + (24 * 3600), config.nextExportTimestamp())
+ val next = config.nextExportTimestamp()
+ val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
+ cal.timeInMillis = next * 1000
+ assertEquals(Calendar.MONDAY, cal.get(Calendar.DAY_OF_WEEK))
+ assertEquals(9, cal.get(Calendar.HOUR_OF_DAY))
+ assertEquals(0, cal.get(Calendar.MINUTE))
}
@Test
- fun `nextExportTimestamp adds 168h for weekly`() {
- val last = 1700000000L
+ fun `weekly nextExportTimestamp picks Sunday correctly`() {
val config = AutoExportConfig(
enabled = true,
interval = "weekly",
- lastExportTimestamp = last
+ timeOfDay = "23:00",
+ weeklyDow = 7 // Sunday
)
- assertEquals(last + (168 * 3600), config.nextExportTimestamp())
+ val next = config.nextExportTimestamp()
+ val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
+ cal.timeInMillis = next * 1000
+ assertEquals(Calendar.SUNDAY, cal.get(Calendar.DAY_OF_WEEK))
}
@Test
- fun `nextExportTimestamp adds one month for monthly`() {
- // Jan 15 2024 -> Feb 15 2024
- val jan15 = 1705276800L // 2024-01-15 00:00:00 UTC
+ fun `monthly nextExportTimestamp clamps day 31 in February`() {
val config = AutoExportConfig(
enabled = true,
interval = "monthly",
- lastExportTimestamp = jan15
+ timeOfDay = "00:00",
+ monthlyDom = 31
)
val next = config.nextExportTimestamp()
- // Should be approximately 31 days later (Feb 15)
- val diff = next - jan15
- assertTrue("Monthly interval should be between 28 and 31 days, was ${diff / 86400} days",
- diff in (28L * 86400)..(31L * 86400))
+ val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
+ cal.timeInMillis = next * 1000
+ val month = cal.get(Calendar.MONTH)
+ val dom = cal.get(Calendar.DAY_OF_MONTH)
+ val maxForMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
+ assertEquals(
+ "Clamped DOM should equal min(31, monthMax) for month=$month",
+ minOf(31, maxForMonth),
+ dom
+ )
}
@Test
- fun `nextExportTimestamp defaults to 24h for unknown interval`() {
- val last = 1700000000L
+ fun `monthly nextExportTimestamp picks configured day for normal month`() {
val config = AutoExportConfig(
enabled = true,
- interval = "unknown",
- lastExportTimestamp = last
+ interval = "monthly",
+ timeOfDay = "06:00",
+ monthlyDom = 15
)
- assertEquals(last + (24 * 3600), config.nextExportTimestamp())
+ val next = config.nextExportTimestamp()
+ val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
+ cal.timeInMillis = next * 1000
+ assertEquals(15, cal.get(Calendar.DAY_OF_MONTH))
+ assertEquals(6, cal.get(Calendar.HOUR_OF_DAY))
}
// --- defaults ---
@Test
- fun `default config is disabled with sensible defaults`() {
+ fun `default config has sensible defaults`() {
val config = AutoExportConfig()
assertFalse(config.enabled)
assertEquals("geojson", config.format)
@@ -157,9 +177,91 @@ class AutoExportConfigTest {
assertEquals(0L, config.lastExportTimestamp)
assertFalse(config.permissionLost)
assertEquals(10, config.retentionCount)
- assertNull(config.lastFileName)
- assertEquals(0, config.lastRowCount)
- assertNull(config.lastError)
+ assertEquals("00:00", config.timeOfDay)
+ assertEquals(1, config.weeklyDow)
+ assertEquals(1, config.monthlyDom)
+ assertEquals(0L, config.enabledAt)
+ }
+
+ // --- migration: from() derives schedule from lastExportTimestamp ---
+
+ @Test
+ fun `from migrates legacy lastExportTimestamp into timeOfDay`() {
+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)
+ val legacy = atUtc(2024, 3, 15, 17, 11)
+ every { db.getSetting(any(), any()) } answers {
+ when (firstArg<String>()) {
+ "autoExportEnabled" -> "true"
+ "autoExportFormat" -> "geojson"
+ "autoExportInterval" -> "daily"
+ "autoExportMode" -> "all"
+ "lastAutoExportTimestamp" -> legacy.toString()
+ "autoExportPermissionLost" -> "false"
+ "autoExportRetentionCount" -> "10"
+ "autoExportLastRowCount" -> "0"
+ else -> null
+ }
+ }
+ val config = AutoExportConfig.from(db)
+ assertEquals("17:11", config.timeOfDay)
+ assertEquals(15, config.monthlyDom)
+ verify { db.saveSetting("autoExportTimeOfDay", "17:11") }
+ verify { db.saveSetting("autoExportMonthlyDom", "15") }
+ }
+
+ @Test
+ fun `from on fresh install does not write derived defaults to DB`() {
+ // No legacy lastTs and no schedule keys set - simulates a brand-new install.
+ // Reading config should not write anything because there's nothing to migrate.
+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)
+ every { db.getSetting(any(), any()) } answers {
+ when (firstArg<String>()) {
+ "autoExportEnabled" -> "false"
+ "autoExportFormat" -> "geojson"
+ "autoExportInterval" -> "daily"
+ "autoExportMode" -> "all"
+ "lastAutoExportTimestamp" -> "0"
+ "autoExportPermissionLost" -> "false"
+ "autoExportRetentionCount" -> "10"
+ "autoExportLastRowCount" -> "0"
+ else -> null
+ }
+ }
+ val config = AutoExportConfig.from(db)
+ assertEquals("00:00", config.timeOfDay)
+ assertEquals(1, config.weeklyDow)
+ assertEquals(1, config.monthlyDom)
+ verify(exactly = 0) { db.saveSetting("autoExportTimeOfDay", any()) }
+ verify(exactly = 0) { db.saveSetting("autoExportWeeklyDow", any()) }
+ verify(exactly = 0) { db.saveSetting("autoExportMonthlyDom", any()) }
+ }
+
+ @Test
+ fun `from does not overwrite explicitly-set timeOfDay`() {
+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)
+ every { db.getSetting(any(), any()) } answers {
+ when (firstArg<String>()) {
+ "autoExportEnabled" -> "true"
+ "autoExportFormat" -> "geojson"
+ "autoExportInterval" -> "daily"
+ "autoExportMode" -> "all"
+ "lastAutoExportTimestamp" -> "0"
+ "autoExportPermissionLost" -> "false"
+ "autoExportRetentionCount" -> "10"
+ "autoExportLastRowCount" -> "0"
+ "autoExportTimeOfDay" -> "09:00"
+ "autoExportWeeklyDow" -> "3"
+ "autoExportMonthlyDom" -> "15"
+ else -> null
+ }
+ }
+ val config = AutoExportConfig.from(db)
+ assertEquals("09:00", config.timeOfDay)
+ assertEquals(3, config.weeklyDow)
+ assertEquals(15, config.monthlyDom)
+ verify(exactly = 0) { db.saveSetting("autoExportTimeOfDay", any()) }
+ verify(exactly = 0) { db.saveSetting("autoExportWeeklyDow", any()) }
+ verify(exactly = 0) { db.saveSetting("autoExportMonthlyDom", any()) }
}
// --- saveLastResult / saveLastError ---
@@ -175,6 +277,69 @@ class AutoExportConfigTest {
verify { db.saveSetting("autoExportLastError", "") }
}
+ // --- monthly DOM=31 sequence Jan -> Feb -> Mar ---
+
+ @Test
+ fun `monthly dom 31 walks Jan to Feb to Mar`() {
+ val config = AutoExportConfig(
+ enabled = true, interval = "monthly", timeOfDay = "00:00", monthlyDom = 31
+ )
+ assertEquals(atUtc(2025, 1, 31), config.nextExportTimestampAt(atUtc(2025, 1, 30) * 1000))
+ assertEquals(atUtc(2025, 2, 28), config.nextExportTimestampAt(atUtc(2025, 2, 1) * 1000))
+ assertEquals(atUtc(2025, 3, 31), config.nextExportTimestampAt(atUtc(2025, 3, 1) * 1000))
+ }
+
+ // --- weekly when today is the target weekday and time is still in the future ---
+
+ @Test
+ fun `weekly today before slot returns today`() {
+ // 2025-06-09 is a Monday.
+ val config = AutoExportConfig(
+ enabled = true, interval = "weekly", timeOfDay = "23:00", weeklyDow = 1
+ )
+ assertEquals(
+ atUtc(2025, 6, 9, 23, 0),
+ config.nextExportTimestampAt(atUtc(2025, 6, 9, 6, 0) * 1000)
+ )
+ }
+
+ @Test
+ fun `weekly today after slot returns next week`() {
+ val config = AutoExportConfig(
+ enabled = true, interval = "weekly", timeOfDay = "09:00", weeklyDow = 1
+ )
+ assertEquals(
+ atUtc(2025, 6, 16, 9, 0),
+ config.nextExportTimestampAt(atUtc(2025, 6, 9, 14, 0) * 1000)
+ )
+ }
+
+ @Test
+ fun `weekly fires when today is target dow and slot has passed`() {
+ // 2025-06-09 is a Monday.
+ val config = AutoExportConfig(
+ enabled = true,
+ interval = "weekly",
+ timeOfDay = "09:00",
+ weeklyDow = 1,
+ lastExportTimestamp = atUtc(2025, 6, 2, 9, 0)
+ )
+ assertTrue(config.isExportDueAt(atUtc(2025, 6, 9, 14, 0) * 1000))
+ }
+
+ // --- isExportDue grace window blocks fast re-fire after schedule edit ---
+
+ @Test
+ fun `schedule edit to earlier time fires same day`() {
+ val config = AutoExportConfig(
+ enabled = true,
+ interval = "daily",
+ timeOfDay = "02:00",
+ lastExportTimestamp = atUtc(2025, 6, 8, 22, 0)
+ )
+ assertTrue(config.isExportDueAt(atUtc(2025, 6, 9, 3, 0) * 1000))
+ }
+
@Test
fun `saveLastError stores error message`() {
val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt
index 0b97b374..f6ae64a6 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt
@@ -1,25 +1,60 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
package com.Colota.export
+import android.app.AlarmManager
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import androidx.work.Configuration
+import androidx.work.WorkManager
+import androidx.work.testing.SynchronousExecutor
+import androidx.work.testing.WorkManagerTestInitHelper
+import com.Colota.data.DatabaseHelper
import com.Colota.util.AppLogger
import io.mockk.*
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
-/**
- * Tests for AutoExportScheduler constants and configuration.
- * WorkManager integration is verified at the integration/instrumented test level;
- * these tests validate the scheduler's public contract and constants.
- */
+@RunWith(RobolectricTestRunner::class)
class AutoExportSchedulerTest {
+ private lateinit var context: Context
+ private lateinit var db: DatabaseHelper
+ private lateinit var alarmManager: AlarmManager
+
@Before
fun setUp() {
+ context = ApplicationProvider.getApplicationContext()
+
+ // scheduleNext calls WorkManager.cancelUniqueWork; needs WorkManager initialized.
+ val config = Configuration.Builder()
+ .setExecutor(SynchronousExecutor())
+ .build()
+ WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
+
+ db = DatabaseHelper.getInstance(context)
+ alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+
mockkObject(AppLogger)
every { AppLogger.d(any(), any()) } just Runs
every { AppLogger.i(any(), any()) } just Runs
every { AppLogger.w(any(), any()) } just Runs
+ every { AppLogger.e(any(), any()) } just Runs
+
+ AutoExportScheduler.cancel(context)
+ listOf(
+ "autoExportEnabled", "autoExportFormat", "autoExportInterval", "autoExportMode",
+ "autoExportTimeOfDay", "autoExportWeeklyDow", "autoExportMonthlyDom",
+ "lastAutoExportTimestamp", "autoExportEnabledAt"
+ ).forEach { db.saveSetting(it, "") }
}
@After
@@ -28,24 +63,47 @@ class AutoExportSchedulerTest {
}
@Test
- fun `work name constant is colota_auto_export`() {
- val field = AutoExportScheduler::class.java.getDeclaredField("WORK_NAME")
- field.isAccessible = true
- assertEquals("colota_auto_export", field.get(null))
+ fun `scheduleNext does not arm alarm when auto-export is disabled`() {
+ db.saveSetting("autoExportEnabled", "false")
+
+ AutoExportScheduler.scheduleNext(context)
+
+ assertTrue(
+ "No alarm should be scheduled when disabled",
+ shadowOf(alarmManager).scheduledAlarms.isEmpty()
+ )
}
@Test
- fun `check interval is 24 hours`() {
- val field = AutoExportScheduler::class.java.getDeclaredField("CHECK_INTERVAL_HOURS")
- field.isAccessible = true
- assertEquals(24L, field.getLong(null))
+ fun `scheduleNext arms alarm when enabled with valid time`() {
+ db.saveSetting("autoExportEnabled", "true")
+ db.saveSetting("autoExportInterval", "daily")
+ db.saveSetting("autoExportTimeOfDay", "09:00")
+
+ AutoExportScheduler.scheduleNext(context)
+
+ val alarms = shadowOf(alarmManager).scheduledAlarms
+ assertEquals("Exactly one alarm should be queued", 1, alarms.size)
+ }
+
+ @Test
+ fun `cancel removes a pending alarm`() {
+ db.saveSetting("autoExportEnabled", "true")
+ db.saveSetting("autoExportInterval", "daily")
+ db.saveSetting("autoExportTimeOfDay", "09:00")
+ AutoExportScheduler.scheduleNext(context)
+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)
+
+ AutoExportScheduler.cancel(context)
+
+ assertTrue(
+ "AlarmManager should have no scheduled alarms after cancel",
+ shadowOf(alarmManager).scheduledAlarms.isEmpty()
+ )
}
@Test
fun `scheduler is a singleton object`() {
- // Verify AutoExportScheduler is an object (singleton)
- val instance1 = AutoExportScheduler
- val instance2 = AutoExportScheduler
- assertSame(instance1, instance2)
+ assertSame(AutoExportScheduler, AutoExportScheduler)
}
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
index 62a6ee84..4b8fb420 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
@@ -455,7 +455,7 @@ class LocationForegroundServiceTest {
// Entry delay pending - not yet inside zone
assertFalse(getField("insidePauseZone"))
- assertEquals(homeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(homeGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
// GPS location is saved during the delay window
verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
// Zone event not sent until delay completes
@@ -490,7 +490,7 @@ class LocationForegroundServiceTest {
// Still in Home until delay fires
assertTrue(getField("insidePauseZone"))
assertEquals("Home", getField<String?>("currentZoneName"))
- assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -579,7 +579,7 @@ class LocationForegroundServiceTest {
invokeRecheckZoneWithLocation(location)
assertFalse(getField("insidePauseZone"))
- assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -591,7 +591,7 @@ class LocationForegroundServiceTest {
invokeHandleZoneRecheckAction()
assertFalse(getField("insidePauseZone"))
- assertEquals(parkGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(parkGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -676,7 +676,7 @@ class LocationForegroundServiceTest {
assertTrue(getField("insidePauseZone"))
assertEquals("Home", getField<String?>("currentZoneName"))
- assertEquals(homeGeofence, getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))
+ assertEquals(homeGeofence, getField<GeofenceHelper.Geofence?>("currentZoneGeofence"))
verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }
}
@@ -748,7 +748,7 @@ class LocationForegroundServiceTest {
assertFalse(getField("insidePauseZone"))
assertNull(getField<String?>("currentZoneName"))
- assertNull(getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))
+ assertNull(getField<GeofenceHelper.Geofence?>("currentZoneGeofence"))
verify { LocationServiceModule.sendPauseZoneEvent(false, "Home") }
}
@@ -842,7 +842,7 @@ class LocationForegroundServiceTest {
invokeExitPauseZone()
assertFalse(getField("insidePauseZone"))
assertNull(getField<String?>("currentZoneName"))
- assertNull(getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))
+ assertNull(getField<GeofenceHelper.Geofence?>("currentZoneGeofence"))
}
@Test
@@ -879,7 +879,7 @@ class LocationForegroundServiceTest {
invokeRecheckZoneWithLocation(location)
assertFalse(getField("insidePauseZone"))
- assertEquals(parkGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(parkGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -908,7 +908,7 @@ class LocationForegroundServiceTest {
// Still in Home until delay fires
assertTrue(getField("insidePauseZone"))
assertEquals("Home", getField<String?>("currentZoneName"))
- assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -926,7 +926,7 @@ class LocationForegroundServiceTest {
verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
// Still in Home - delay pending for Office
assertEquals("Home", getField<String?>("currentZoneName"))
- assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -1030,7 +1030,7 @@ class LocationForegroundServiceTest {
invokeStartEntryDelay(homeGeofence)
assertFalse(getField("insidePauseZone"))
- assertEquals(homeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(homeGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
assertNotNull(getField<Job?>("entryDelayJob"))
}
@@ -1044,7 +1044,7 @@ class LocationForegroundServiceTest {
assertTrue(getField("insidePauseZone"))
assertEquals("Home", getField<String?>("currentZoneName"))
- assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertNull(getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }
}
@@ -1067,7 +1067,7 @@ class LocationForegroundServiceTest {
invokeStartEntryDelay(officeGeofence)
assertTrue(firstJob?.isCancelled == true)
- assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -1076,7 +1076,7 @@ class LocationForegroundServiceTest {
invokeCancelEntryDelay()
- assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertNull(getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
assertNull(getField<Job?>("entryDelayJob"))
}
@@ -1112,7 +1112,7 @@ class LocationForegroundServiceTest {
invokeHandleLocationUpdate(location)
verify { mockJob.cancel() }
- assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertNull(getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -1222,7 +1222,7 @@ class LocationForegroundServiceTest {
invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)
verify { mockJob.cancel() }
- assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertNull(getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -1398,7 +1398,7 @@ class LocationForegroundServiceTest {
invokeOnDestroy()
verify { mockJob.cancel() }
- assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertNull(getField<GeofenceHelper.Geofence?>("pendingPauseZone"))
}
@Test
@@ -1838,9 +1838,9 @@ class LocationForegroundServiceTest {
method.invoke(service, location)
}
- private fun invokeEnterPauseZone(geofence: GeofenceHelper.CachedGeofence) {
+ private fun invokeEnterPauseZone(geofence: GeofenceHelper.Geofence) {
val method = LocationForegroundService::class.java.getDeclaredMethod(
- "enterPauseZone", GeofenceHelper.CachedGeofence::class.java
+ "enterPauseZone", GeofenceHelper.Geofence::class.java
)
method.isAccessible = true
method.invoke(service, geofence)
@@ -1895,9 +1895,9 @@ class LocationForegroundServiceTest {
method.invoke(service)
}
- private fun invokeSaveAnchorPoint(geofence: GeofenceHelper.CachedGeofence) {
+ private fun invokeSaveAnchorPoint(geofence: GeofenceHelper.Geofence) {
val method = LocationForegroundService::class.java.getDeclaredMethod(
- "saveAnchorPoint", GeofenceHelper.CachedGeofence::class.java
+ "saveAnchorPoint", GeofenceHelper.Geofence::class.java
)
method.isAccessible = true
method.invoke(service, geofence)
@@ -2064,9 +2064,9 @@ class LocationForegroundServiceTest {
// Reflection helpers
// =========================================================================
- private fun invokeStartEntryDelay(geofence: GeofenceHelper.CachedGeofence) {
+ private fun invokeStartEntryDelay(geofence: GeofenceHelper.Geofence) {
val method = LocationForegroundService::class.java.getDeclaredMethod(
- "startEntryDelay", GeofenceHelper.CachedGeofence::class.java
+ "startEntryDelay", GeofenceHelper.Geofence::class.java
)
method.isAccessible = true
method.invoke(service, geofence)
@@ -2102,9 +2102,9 @@ class LocationForegroundServiceTest {
method.invoke(service)
}
- private fun invokeApplyZoneSettingsIfChanged(zone: GeofenceHelper.CachedGeofence) {
+ private fun invokeApplyZoneSettingsIfChanged(zone: GeofenceHelper.Geofence) {
val method = LocationForegroundService::class.java.getDeclaredMethod(
- "applyZoneSettingsIfChanged", GeofenceHelper.CachedGeofence::class.java
+ "applyZoneSettingsIfChanged", GeofenceHelper.Geofence::class.java
)
method.isAccessible = true
method.invoke(service, zone)
@@ -2118,7 +2118,7 @@ class LocationForegroundServiceTest {
pauseOnWifi: Boolean = false,
pauseOnMotionless: Boolean = false,
motionlessTimeoutMinutes: Int = 10
- ) = GeofenceHelper.CachedGeofence(name, lat, lon, radius, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes)
+ ) = GeofenceHelper.Geofence(name, lat, lon, radius, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes)
private fun invokeSendHeartbeatLocation() = runBlocking {
val method = LocationForegroundService::class.java.getDeclaredMethod(
diff --git a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
index a88210db..ace910b1 100644
--- a/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
+++ b/apps/mobile/src/components/features/inspector/CalendarPicker.tsx
@@ -9,6 +9,7 @@ import { ChevronLeft, ChevronRight, Calendar } from "lucide-react-native"
import { ThemeColors } from "../../../types/global"
import { fonts } from "../../../styles/typography"
import { formatDistance } from "../../../utils/geo"
+import { pad2 } from "../../../utils/format"
import { HIT_SLOP_LG } from "../../../constants"
interface CalendarPickerProps {
@@ -30,7 +31,7 @@ function isSameDay(a: Date, b: Date): boolean {
}
function formatDateKey(year: number, month: number, day: number): string {
- return `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`
+ return `${year}-${pad2(month + 1)}-${pad2(day)}`
}
export function CalendarPicker({
diff --git a/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsx b/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsx
index 0e76c2a6..a74aabcc 100644
--- a/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsx
+++ b/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsx
@@ -6,6 +6,7 @@
import React, { useState, useRef, useCallback, useMemo } from "react"
import { View, PanResponder, LayoutChangeEvent } from "react-native"
import Svg, { Path, Line, Circle, Rect, Text as SvgText } from "react-native-svg"
+import { clamp } from "../../../utils/format"
interface InteractiveLineChartProps {
data: number[]
@@ -53,9 +54,9 @@ export function InteractiveLineChart({
const d = dataRef.current
if (w === 0 || d.length === 0) return null
const plotW = w - CHART_PADDING.left - CHART_PADDING.right
- const clampedX = Math.max(0, Math.min(x - CHART_PADDING.left, plotW))
+ const clampedX = clamp(x - CHART_PADDING.left, 0, plotW)
const idx = Math.round((clampedX / plotW) * (d.length - 1))
- return Math.max(0, Math.min(idx, d.length - 1))
+ return clamp(idx, 0, d.length - 1)
}, [])
const panResponder = useMemo(
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index add64ec6..fc63d470 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -19,6 +19,7 @@ export { Button } from "./ui/Button"
export { SectionTitle } from "./ui/SectionTitle"
export { Divider } from "./ui/Divider"
export { NumericInput } from "./ui/NumericInput"
+export { TimePicker } from "./ui/TimePicker"
export { FloatingSaveIndicator } from "./ui/FloatingSaveIndicator"
export { Footer } from "./ui/Footer"
export { SpinningLoader } from "./ui/SpinningLoader"
diff --git a/apps/mobile/src/components/ui/TimePicker.tsx b/apps/mobile/src/components/ui/TimePicker.tsx
new file mode 100644
index 00000000..31e387a6
--- /dev/null
+++ b/apps/mobile/src/components/ui/TimePicker.tsx
@@ -0,0 +1,120 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useCallback, useEffect, useMemo, useState } from "react"
+import { View, Text, TextInput, StyleSheet } from "react-native"
+import { ThemeColors } from "../../types/global"
+import { fonts } from "../../styles/typography"
+import { clamp, pad2 } from "../../utils/format"
+
+interface TimePickerProps {
+ value: string
+ onChange: (value: string) => void
+ colors: ThemeColors
+}
+
+const HOUR_MIN = 0
+const HOUR_MAX = 23
+const MIN_MIN = 0
+const MIN_MAX = 59
+
+function parse(value: string): { h: number; m: number } {
+ const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value)
+ if (!match) return { h: 0, m: 0 }
+ return { h: parseInt(match[1], 10), m: parseInt(match[2], 10) }
+}
+
+function format(h: number, m: number): string {
+ return `${pad2(h)}:${pad2(m)}`
+}
+
+export function TimePicker({ value, onChange, colors }: TimePickerProps) {
+ const { h, m } = useMemo(() => parse(value), [value])
+
+ const [hourText, setHourText] = useState(pad2(h))
+ const [minuteText, setMinuteText] = useState(pad2(m))
+
+ useEffect(() => setHourText(pad2(h)), [h])
+ useEffect(() => setMinuteText(pad2(m)), [m])
+
+ const onHourChange = useCallback((text: string) => {
+ setHourText(text.replace(/\D/g, "").slice(0, 2))
+ }, [])
+ const onMinuteChange = useCallback((text: string) => {
+ setMinuteText(text.replace(/\D/g, "").slice(0, 2))
+ }, [])
+
+ const commitHour = useCallback(() => {
+ const parsed = parseInt(hourText, 10)
+ const next = isNaN(parsed) ? h : clamp(parsed, HOUR_MIN, HOUR_MAX)
+ setHourText(pad2(next))
+ if (next !== h) onChange(format(next, m))
+ }, [hourText, h, m, onChange])
+
+ const commitMinute = useCallback(() => {
+ const parsed = parseInt(minuteText, 10)
+ const next = isNaN(parsed) ? m : clamp(parsed, MIN_MIN, MIN_MAX)
+ setMinuteText(pad2(next))
+ if (next !== m) onChange(format(h, next))
+ }, [minuteText, h, m, onChange])
+
+ return (
+ <View style={styles.row}>
+ <TextInput
+ testID="timepicker-hour-value"
+ accessibilityLabel="Hours"
+ value={hourText}
+ onChangeText={onHourChange}
+ onBlur={commitHour}
+ keyboardType="number-pad"
+ maxLength={2}
+ selectTextOnFocus
+ style={[
+ styles.input,
+ { borderColor: colors.border, backgroundColor: colors.backgroundElevated, color: colors.text }
+ ]}
+ />
+ <Text style={[styles.separator, { color: colors.text }]}>:</Text>
+ <TextInput
+ testID="timepicker-minute-value"
+ accessibilityLabel="Minutes"
+ value={minuteText}
+ onChangeText={onMinuteChange}
+ onBlur={commitMinute}
+ keyboardType="number-pad"
+ maxLength={2}
+ selectTextOnFocus
+ style={[
+ styles.input,
+ { borderColor: colors.border, backgroundColor: colors.backgroundElevated, color: colors.text }
+ ]}
+ />
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ row: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 8,
+ paddingVertical: 4
+ },
+ input: {
+ minWidth: 64,
+ padding: 14,
+ borderRadius: 12,
+ borderWidth: 1,
+ fontSize: 15,
+ ...fonts.semiBold,
+ fontVariant: ["tabular-nums"],
+ textAlign: "center"
+ },
+ separator: {
+ fontSize: 15,
+ ...fonts.semiBold,
+ paddingHorizontal: 2
+ }
+})
diff --git a/apps/mobile/src/screens/AutoExportScreen.tsx b/apps/mobile/src/screens/AutoExportScreen.tsx
index f934c9dd..6ec091ef 100644
--- a/apps/mobile/src/screens/AutoExportScreen.tsx
+++ b/apps/mobile/src/screens/AutoExportScreen.tsx
@@ -17,7 +17,9 @@ import {
RadioDot,
FloatingSaveIndicator,
SettingRow,
- Button
+ Button,
+ TimePicker,
+ NumericInput
} from "../components"
import { useTheme } from "../hooks/useTheme"
import { useTimeout } from "../hooks/useTimeout"
@@ -26,7 +28,9 @@ import NativeLocationService from "../services/NativeLocationService"
import { ExportFormat, EXPORT_FORMATS } from "../utils/exportConverters"
import { fonts } from "../styles/typography"
import { logger } from "../utils/logger"
+import { formatExportDateTime, formatBytes } from "../utils/format"
import { showAlert } from "../services/modalService"
+import { SAVE_SUCCESS_DISPLAY_MS } from "../constants"
type ExportInterval = "daily" | "weekly" | "monthly"
type ExportMode = "all" | "incremental"
@@ -49,20 +53,17 @@ const MODE_OPTIONS: { key: ExportMode; label: string; description: string }[] =
{ key: "incremental", label: "Since last export", description: "Only export new locations" }
]
-const RETENTION_OPTIONS: readonly { value: string; label: string }[] = [
- { value: "1", label: "1 file" },
- { value: "5", label: "5 files" },
- { value: "10", label: "10 files" },
- { value: "30", label: "30 files" },
- { value: "0", label: "Unlimited" }
+// ISO weekday Mon=1..Sun=7
+const WEEKDAY_OPTIONS: readonly { value: string; label: string }[] = [
+ { value: "1", label: "Mon" },
+ { value: "2", label: "Tue" },
+ { value: "3", label: "Wed" },
+ { value: "4", label: "Thu" },
+ { value: "5", label: "Fri" },
+ { value: "6", label: "Sat" },
+ { value: "7", label: "Sun" }
]
-function formatFileSize(bytes: number): string {
- if (bytes < 1024) return `${bytes} B`
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
-}
-
export function AutoExportScreen(_props: ScreenProps) {
const { colors } = useTheme()
const [enabled, setEnabled] = useState(false)
@@ -74,16 +75,20 @@ export function AutoExportScreen(_props: ScreenProps) {
const [nextExport, setNextExport] = useState<number>(0)
const [fileCount, setFileCount] = useState<number>(0)
const [retentionCount, setRetentionCount] = useState<number>(10)
+ const [retentionInput, setRetentionInput] = useState<string>("10")
const [lastFileName, setLastFileName] = useState<string | null>(null)
const [lastRowCount, setLastRowCount] = useState<number>(0)
const [lastError, setLastError] = useState<string | null>(null)
+ const [timeOfDay, setTimeOfDay] = useState<string>("00:00")
+ const [weeklyDow, setWeeklyDow] = useState<number>(1)
+ const [monthlyDom, setMonthlyDom] = useState<number>(1)
+ const [monthlyDomInput, setMonthlyDomInput] = useState<string>("1")
const [exportFiles, setExportFiles] = useState<ExportFile[]>([])
const [loading, setLoading] = useState(true)
const [exporting, setExporting] = useState(false)
const [saving, setSaving] = useState(false)
const [saveSuccess, setSaveSuccess] = useState(false)
const successTimeout = useTimeout()
- const statusRefreshTimeout = useTimeout()
const loadStatus = useCallback(async () => {
try {
@@ -97,9 +102,14 @@ export function AutoExportScreen(_props: ScreenProps) {
setNextExport(status.nextExportTimestamp)
setFileCount(status.fileCount)
setRetentionCount(status.retentionCount ?? 10)
+ setRetentionInput((status.retentionCount ?? 10).toString())
setLastFileName(status.lastFileName || null)
setLastRowCount(status.lastRowCount ?? 0)
setLastError(status.lastError || null)
+ setTimeOfDay(status.timeOfDay || "00:00")
+ setWeeklyDow(status.weeklyDow || 1)
+ setMonthlyDom(status.monthlyDom || 1)
+ setMonthlyDomInput((status.monthlyDom || 1).toString())
const permissionLost = await NativeLocationService.getSetting("autoExportPermissionLost")
if (permissionLost === "true") {
@@ -133,7 +143,6 @@ export function AutoExportScreen(_props: ScreenProps) {
}, [loadStatus, loadExportFiles])
)
- // Listen for real-time export completion events
useEffect(() => {
const listener = DeviceEventEmitter.addListener(
"onAutoExportComplete",
@@ -161,7 +170,7 @@ export function AutoExportScreen(_props: ScreenProps) {
await NativeLocationService.saveSetting(key, value)
setSaving(false)
setSaveSuccess(true)
- successTimeout.set(() => setSaveSuccess(false), 2000)
+ successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)
} catch (error) {
setSaving(false)
logger.error("[AutoExportScreen] Save failed:", error)
@@ -206,12 +215,24 @@ export function AutoExportScreen(_props: ScreenProps) {
[saveSetting]
)
+ const reschedule = useCallback(async () => {
+ if (!enabled) return
+ try {
+ await NativeLocationService.rescheduleAutoExport()
+ } catch (error) {
+ logger.error("[AutoExportScreen] Reschedule failed:", error)
+ showAlert("Error", "Failed to reschedule auto-export. Please try again.", "error")
+ }
+ }, [enabled])
+
const handleIntervalChange = useCallback(
async (newInterval: ExportInterval) => {
setInterval(newInterval)
await saveSetting("autoExportInterval", newInterval)
+ await reschedule()
+ await loadStatus()
},
- [saveSetting]
+ [saveSetting, loadStatus, reschedule]
)
const handleModeChange = useCallback(
@@ -222,15 +243,53 @@ export function AutoExportScreen(_props: ScreenProps) {
[saveSetting]
)
- const handleRetentionChange = useCallback(
- async (newRetention: string) => {
- const count = parseInt(newRetention, 10)
- setRetentionCount(count)
- await saveSetting("autoExportRetentionCount", newRetention)
+ const handleTimeChange = useCallback(
+ async (newTime: string) => {
+ setTimeOfDay(newTime)
+ await saveSetting("autoExportTimeOfDay", newTime)
+ await reschedule()
+ await loadStatus()
},
- [saveSetting]
+ [saveSetting, loadStatus, reschedule]
)
+ const handleWeeklyDowChange = useCallback(
+ async (newDow: string) => {
+ const dow = parseInt(newDow, 10)
+ setWeeklyDow(dow)
+ await saveSetting("autoExportWeeklyDow", newDow)
+ await reschedule()
+ await loadStatus()
+ },
+ [saveSetting, loadStatus, reschedule]
+ )
+
+ const handleMonthlyDomChange = useCallback((text: string) => {
+ setMonthlyDomInput(text.replace(/\D/g, ""))
+ }, [])
+
+ const handleMonthlyDomBlur = useCallback(async () => {
+ const parsed = parseInt(monthlyDomInput, 10)
+ const dom = isNaN(parsed) ? monthlyDom : Math.max(1, Math.min(31, parsed))
+ setMonthlyDom(dom)
+ setMonthlyDomInput(dom.toString())
+ await saveSetting("autoExportMonthlyDom", dom.toString())
+ await reschedule()
+ await loadStatus()
+ }, [monthlyDomInput, monthlyDom, saveSetting, loadStatus, reschedule])
+
+ const handleRetentionChange = useCallback((text: string) => {
+ setRetentionInput(text.replace(/\D/g, ""))
+ }, [])
+
+ const handleRetentionBlur = useCallback(async () => {
+ const parsed = parseInt(retentionInput, 10)
+ const count = isNaN(parsed) ? retentionCount : Math.max(0, parsed)
+ setRetentionCount(count)
+ setRetentionInput(count.toString())
+ await saveSetting("autoExportRetentionCount", count.toString())
+ }, [retentionInput, retentionCount, saveSetting])
+
const handlePickDirectory = useCallback(async () => {
try {
const uri = await NativeLocationService.pickExportDirectory()
@@ -254,14 +313,13 @@ export function AutoExportScreen(_props: ScreenProps) {
try {
await NativeLocationService.runAutoExportNow()
showAlert("Export Started", "Export is running in the background. The status will update when complete.", "info")
- statusRefreshTimeout.set(() => loadStatus(), 3000)
} catch (error) {
logger.error("[AutoExportScreen] Export now failed:", error)
showAlert("Error", "Failed to start export.", "error")
} finally {
setExporting(false)
}
- }, [directoryUri, loadStatus, statusRefreshTimeout])
+ }, [directoryUri])
const handleShareFile = useCallback(async (file: ExportFile) => {
const ext = file.name.split(".").pop() || ""
@@ -278,11 +336,6 @@ export function AutoExportScreen(_props: ScreenProps) {
}
}, [])
- const formatTimestamp = (timestamp: number): string => {
- if (timestamp === 0) return "Never"
- return new Date(timestamp * 1000).toLocaleString()
- }
-
if (loading)
return (
<Container>
@@ -352,6 +405,37 @@ export function AutoExportScreen(_props: ScreenProps) {
<SectionTitle>Frequency</SectionTitle>
<Card>
<ChipGroup options={INTERVAL_OPTIONS} selected={interval} onSelect={handleIntervalChange} colors={colors} />
+ {interval === "weekly" && (
+ <>
+ <Divider />
+ <Text style={[styles.fieldLabel, { color: colors.textSecondary }]}>Day of week</Text>
+ <ChipGroup
+ options={WEEKDAY_OPTIONS}
+ selected={weeklyDow.toString()}
+ onSelect={handleWeeklyDowChange}
+ colors={colors}
+ />
+ </>
+ )}
+ {interval === "monthly" && (
+ <>
+ <Divider />
+ <NumericInput
+ label="Day of month"
+ value={monthlyDomInput}
+ onChange={handleMonthlyDomChange}
+ onBlur={handleMonthlyDomBlur}
+ unit="day"
+ placeholder="1"
+ min={1}
+ colors={colors}
+ hint="1-31. Falls back to last day in shorter months."
+ />
+ </>
+ )}
+ <Divider />
+ <Text style={[styles.fieldLabel, { color: colors.textSecondary }]}>Time (24h)</Text>
+ <TimePicker value={timeOfDay} onChange={handleTimeChange} colors={colors} />
</Card>
</View>
@@ -385,11 +469,16 @@ export function AutoExportScreen(_props: ScreenProps) {
<View style={styles.section}>
<SectionTitle>File Retention</SectionTitle>
<Card>
- <ChipGroup
- options={RETENTION_OPTIONS}
- selected={retentionCount.toString()}
- onSelect={handleRetentionChange}
+ <NumericInput
+ label="Files to keep"
+ value={retentionInput}
+ onChange={handleRetentionChange}
+ onBlur={handleRetentionBlur}
+ unit="files"
+ placeholder="10"
+ min={0}
colors={colors}
+ hint="Set to 0 for unlimited"
/>
</Card>
</View>
@@ -400,7 +489,7 @@ export function AutoExportScreen(_props: ScreenProps) {
<Card>
<View style={styles.statusRow}>
<Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Last Export</Text>
- <Text style={[styles.statusValue, { color: colors.text }]}>{formatTimestamp(lastExport)}</Text>
+ <Text style={[styles.statusValue, { color: colors.text }]}>{formatExportDateTime(lastExport)}</Text>
</View>
{lastFileName && (
<>
@@ -434,7 +523,7 @@ export function AutoExportScreen(_props: ScreenProps) {
<Divider />
<View style={styles.statusRow}>
<Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Next Export</Text>
- <Text style={[styles.statusValue, { color: colors.text }]}>{formatTimestamp(nextExport)}</Text>
+ <Text style={[styles.statusValue, { color: colors.text }]}>{formatExportDateTime(nextExport)}</Text>
</View>
</>
)}
@@ -476,7 +565,7 @@ export function AutoExportScreen(_props: ScreenProps) {
{file.name}
</Text>
<Text style={[styles.fileMeta, { color: colors.textSecondary }]}>
- {formatFileSize(file.size)} - {formatTimestamp(file.lastModified)}
+ {formatBytes(file.size)} - {formatExportDateTime(file.lastModified)}
</Text>
</View>
<Pressable
@@ -595,5 +684,13 @@ const styles = StyleSheet.create({
},
shareButton: {
padding: 8
+ },
+ fieldLabel: {
+ fontSize: 12,
+ ...fonts.semiBold,
+ textTransform: "uppercase",
+ letterSpacing: 0.5,
+ marginTop: 12,
+ marginBottom: 8
}
})
diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsx
index 560d60c4..eb7ea279 100644
--- a/apps/mobile/src/screens/ExportDataScreen.tsx
+++ b/apps/mobile/src/screens/ExportDataScreen.tsx
@@ -4,9 +4,9 @@
*/
import { useState, useEffect, useCallback } from "react"
-import { Text, StyleSheet, View, ActivityIndicator, ScrollView, Pressable } from "react-native"
+import { Text, StyleSheet, View, ActivityIndicator, ScrollView } from "react-native"
import { fonts } from "../styles/typography"
-import { Download, MapPinOff, Clock, ChevronRight } from "lucide-react-native"
+import { Download, MapPinOff } from "lucide-react-native"
import { Container, Card, SectionTitle, Button, FormatSelector } from "../components"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
@@ -15,16 +15,12 @@ import { logger } from "../utils/logger"
import { showAlert } from "../services/modalService"
import { ScreenProps } from "../types/global"
-export function ExportDataScreen({ navigation }: ScreenProps) {
+export function ExportDataScreen({}: ScreenProps) {
const { colors } = useTheme()
const [exporting, setExporting] = useState(false)
const [exportProgress, setExportProgress] = useState<string>("")
const [totalLocations, setTotalLocations] = useState(0)
const [selectedFormat, setSelectedFormat] = useState<ExportFormat | null>(null)
- const [autoExportEnabled, setAutoExportEnabled] = useState(false)
- const [autoExportInterval, setAutoExportInterval] = useState("")
- const [autoExportFormat, setAutoExportFormat] = useState("")
- const [lastExportTs, setLastExportTs] = useState(0)
const loadStats = useCallback(async () => {
try {
@@ -35,22 +31,9 @@ export function ExportDataScreen({ navigation }: ScreenProps) {
}
}, [])
- const loadAutoExportStatus = useCallback(async () => {
- try {
- const status = await NativeLocationService.getAutoExportStatus()
- setAutoExportEnabled(status.enabled)
- setAutoExportInterval(status.interval)
- setAutoExportFormat(status.format)
- setLastExportTs(status.lastExportTimestamp)
- } catch (error) {
- logger.error("[ExportDataScreen] Failed to load auto-export status:", error)
- }
- }, [])
-
useEffect(() => {
loadStats()
- loadAutoExportStatus()
- }, [loadStats, loadAutoExportStatus])
+ }, [loadStats])
const handleExport = async (format: ExportFormat) => {
if (totalLocations === 0) {
@@ -146,28 +129,6 @@ export function ExportDataScreen({ navigation }: ScreenProps) {
)}
</>
)}
-
- {/* Auto-Export */}
- <View style={styles.section}>
- <SectionTitle>Scheduled Export</SectionTitle>
- <Card>
- <Pressable
- style={({ pressed }) => [styles.autoExportRow, pressed && { opacity: colors.pressedOpacity }]}
- onPress={() => navigation.navigate("Auto-Export")}
- >
- <Clock size={22} color={autoExportEnabled ? colors.primary : colors.textLight} />
- <View style={styles.autoExportContent}>
- <Text style={[styles.autoExportLabel, { color: colors.text }]}>Auto-Export</Text>
- <Text style={[styles.autoExportSub, { color: colors.textSecondary }]}>
- {autoExportEnabled
- ? `${autoExportInterval === "daily" ? "Daily" : autoExportInterval === "weekly" ? "Weekly" : "Monthly"} - ${autoExportFormat.toUpperCase()}${lastExportTs > 0 ? ` - Last: ${new Date(lastExportTs * 1000).toLocaleDateString()}` : ""}`
- : "Schedule automatic exports"}
- </Text>
- </View>
- <ChevronRight size={20} color={colors.textLight} />
- </Pressable>
- </Card>
- </View>
</ScrollView>
{/* Loading Overlay */}
@@ -276,24 +237,6 @@ const styles = StyleSheet.create({
fontSize: 13,
textAlign: "center"
},
- autoExportRow: {
- flexDirection: "row",
- alignItems: "center",
- gap: 12,
- paddingVertical: 8
- },
- autoExportContent: {
- flex: 1
- },
- autoExportLabel: {
- fontSize: 16,
- ...fonts.semiBold,
- marginBottom: 2
- },
- autoExportSub: {
- fontSize: 13,
- ...fonts.regular
- },
exportButtonWrapper: {
marginBottom: 16
}
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index 81cb2e65..bccf36a4 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -18,6 +18,7 @@ import { TrackMap } from "../components/features/inspector/TrackMap"
import { TripList } from "../components/features/inspector/TripList"
import { LocationTable } from "../components/features/inspector/LocationTable"
import { formatDistance } from "../utils/geo"
+import { pad2 } from "../utils/format"
import { segmentTrips } from "../utils/trips"
import { TRIP_CONVERTERS, EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"
import { showAlert } from "../services/modalService"
@@ -81,7 +82,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
/** Fetch days-with-data and daily distances for a month into cache. */
const prefetchMonth = useCallback(async (year: number, month: number): Promise<Set<string>> => {
- const key = `${year}-${String(month + 1).padStart(2, "0")}`
+ const key = `${year}-${pad2(month + 1)}`
if (daysCache.current.has(key)) return daysCache.current.get(key)!
try {
const start = new Date(year, month, 1)
@@ -156,7 +157,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
/** Refresh on focus so trip deletions in TripDetail are reflected */
useFocusEffect(
useCallback(() => {
- const key = `${mapDate.getFullYear()}-${String(mapDate.getMonth() + 1).padStart(2, "0")}`
+ const key = `${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`
daysCache.current.delete(key)
distanceCache.current.delete(key)
fetchTrackData()
@@ -216,9 +217,7 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
distance={dailyDistance}
colors={colors}
daysWithData={daysWithData}
- dayDistances={distanceCache.current.get(
- `${mapDate.getFullYear()}-${String(mapDate.getMonth() + 1).padStart(2, "0")}`
- )}
+ dayDistances={distanceCache.current.get(`${mapDate.getFullYear()}-${pad2(mapDate.getMonth() + 1)}`)}
onMonthChange={fetchDaysWithData}
onPrefetchMonth={prefetchMonth}
/>
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index 7ba77caa..e09e2753 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -23,7 +23,8 @@ import {
Map,
ScrollText,
Info,
- Heart
+ Heart,
+ Clock
} from "lucide-react-native"
import { logger } from "../utils/logger"
@@ -181,6 +182,14 @@ export function SettingsScreen({ navigation }: Props) {
onPress={() => navigation.navigate("Export Data")}
/>
<Divider />
+ <ListItem
+ testID="nav-auto-export"
+ icon={Clock}
+ label="Auto-Export"
+ sub="Schedule daily, weekly or monthly exports"
+ onPress={() => navigation.navigate("Auto-Export")}
+ />
+ <Divider />
<ListItem
testID="nav-offline-maps"
icon={Map}
diff --git a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx
index d0fdb77c..784bb9b6 100644
--- a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx
@@ -41,11 +41,15 @@ const mockGetAutoExportStatus = jest.fn().mockResolvedValue({
retentionCount: 10,
lastFileName: null,
lastRowCount: 0,
- lastError: null
+ lastError: null,
+ timeOfDay: "00:00",
+ weeklyDow: 1,
+ monthlyDom: 1
})
const mockSaveSetting = jest.fn().mockResolvedValue(undefined)
const mockScheduleAutoExport = jest.fn().mockResolvedValue(true)
const mockCancelAutoExport = jest.fn().mockResolvedValue(true)
+const mockRescheduleAutoExport = jest.fn().mockResolvedValue(true)
const mockPickExportDirectory = jest.fn().mockResolvedValue(null)
const mockRunAutoExportNow = jest.fn().mockResolvedValue(true)
const mockGetSetting = jest.fn().mockResolvedValue(null)
@@ -70,6 +74,9 @@ jest.mock("../../services/NativeLocationService", () => ({
cancelAutoExport: function () {
return mockCancelAutoExport.apply(null, arguments)
},
+ rescheduleAutoExport: function () {
+ return mockRescheduleAutoExport.apply(null, arguments)
+ },
pickExportDirectory: function () {
return mockPickExportDirectory.apply(null, arguments)
},
@@ -161,6 +168,30 @@ jest.mock("../../components", () => {
RN.Pressable,
{ onPress: props.onPress, disabled: props.disabled },
R.createElement(RN.Text, null, props.title)
+ ),
+ TimePicker: (props: any) =>
+ R.createElement(
+ RN.View,
+ { testID: "time-picker" },
+ R.createElement(RN.Text, null, props.value),
+ R.createElement(
+ RN.Pressable,
+ { testID: "time-picker-bump", onPress: () => props.onChange("06:30") },
+ R.createElement(RN.Text, null, "bump")
+ )
+ ),
+ NumericInput: (props: any) =>
+ R.createElement(
+ RN.View,
+ null,
+ R.createElement(RN.Text, null, props.label),
+ props.hint && R.createElement(RN.Text, null, props.hint),
+ R.createElement(RN.TextInput, {
+ testID: `numeric-input-${props.label}`,
+ value: props.value,
+ onChangeText: props.onChange,
+ onBlur: props.onBlur
+ })
)
}
})
@@ -196,7 +227,10 @@ describe("AutoExportScreen", () => {
retentionCount: 10,
lastFileName: null,
lastRowCount: 0,
- lastError: null
+ lastError: null,
+ timeOfDay: "00:00",
+ weeklyDow: 1,
+ monthlyDom: 1
})
mockGetExportFiles.mockResolvedValue([])
})
@@ -441,17 +475,35 @@ describe("AutoExportScreen", () => {
})
})
- it("changing retention saves the setting", async () => {
- const { getByText } = render(<AutoExportScreen {...mockProps} />)
+ it("changing retention saves the setting on blur", async () => {
+ const { getByTestId } = render(<AutoExportScreen {...mockProps} />)
await waitFor(() => {
- expect(getByText("5 files")).toBeTruthy()
+ expect(getByTestId("numeric-input-Files to keep")).toBeTruthy()
})
- fireEvent.press(getByText("5 files"))
+ const input = getByTestId("numeric-input-Files to keep")
+ fireEvent.changeText(input, "25")
+ fireEvent(input, "blur")
await waitFor(() => {
- expect(mockSaveSetting).toHaveBeenCalledWith("autoExportRetentionCount", "5")
+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportRetentionCount", "25")
+ })
+ })
+
+ it("retention 0 saves as unlimited", async () => {
+ const { getByTestId, getByText } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByText("Set to 0 for unlimited")).toBeTruthy()
+ })
+
+ const input = getByTestId("numeric-input-Files to keep")
+ fireEvent.changeText(input, "0")
+ fireEvent(input, "blur")
+
+ await waitFor(() => {
+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportRetentionCount", "0")
})
})
@@ -630,6 +682,175 @@ describe("AutoExportScreen", () => {
})
})
+ it("renders time picker with configured timeOfDay", async () => {
+ mockGetAutoExportStatus.mockResolvedValue({
+ enabled: true,
+ format: "geojson",
+ interval: "daily",
+ uri: "content://some-uri",
+ mode: "all",
+ lastExportTimestamp: 0,
+ nextExportTimestamp: 0,
+ fileCount: 0,
+ retentionCount: 10,
+ lastFileName: null,
+ lastRowCount: 0,
+ lastError: null,
+ timeOfDay: "07:45",
+ weeklyDow: 1,
+ monthlyDom: 1
+ })
+
+ const { getByText } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByText("07:45")).toBeTruthy()
+ })
+ })
+
+ it("changing time of day saves the setting", async () => {
+ const { getByTestId } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByTestId("time-picker")).toBeTruthy()
+ })
+
+ fireEvent.press(getByTestId("time-picker-bump"))
+
+ await waitFor(() => {
+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportTimeOfDay", "06:30")
+ })
+ })
+
+ it("renders weekday chips when interval is weekly", async () => {
+ mockGetAutoExportStatus.mockResolvedValue({
+ enabled: true,
+ format: "geojson",
+ interval: "weekly",
+ uri: "content://some-uri",
+ mode: "all",
+ lastExportTimestamp: 0,
+ nextExportTimestamp: 0,
+ fileCount: 0,
+ retentionCount: 10,
+ lastFileName: null,
+ lastRowCount: 0,
+ lastError: null,
+ timeOfDay: "00:00",
+ weeklyDow: 3,
+ monthlyDom: 1
+ })
+
+ const { getByText } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByText("Mon")).toBeTruthy()
+ expect(getByText("Sun")).toBeTruthy()
+ })
+
+ fireEvent.press(getByText("Fri"))
+
+ await waitFor(() => {
+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportWeeklyDow", "5")
+ })
+ })
+
+ it("renders day-of-month input when interval is monthly", async () => {
+ mockGetAutoExportStatus.mockResolvedValue({
+ enabled: true,
+ format: "geojson",
+ interval: "monthly",
+ uri: "content://some-uri",
+ mode: "all",
+ lastExportTimestamp: 0,
+ nextExportTimestamp: 0,
+ fileCount: 0,
+ retentionCount: 10,
+ lastFileName: null,
+ lastRowCount: 0,
+ lastError: null,
+ timeOfDay: "00:00",
+ weeklyDow: 1,
+ monthlyDom: 7
+ })
+
+ const { getByTestId } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByTestId("numeric-input-Day of month")).toBeTruthy()
+ })
+
+ const input = getByTestId("numeric-input-Day of month")
+ fireEvent.changeText(input, "15")
+ fireEvent(input, "blur")
+
+ await waitFor(() => {
+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportMonthlyDom", "15")
+ })
+ })
+
+ it("clamps day-of-month to 31", async () => {
+ mockGetAutoExportStatus.mockResolvedValue({
+ enabled: true,
+ format: "geojson",
+ interval: "monthly",
+ uri: "content://some-uri",
+ mode: "all",
+ lastExportTimestamp: 0,
+ nextExportTimestamp: 0,
+ fileCount: 0,
+ retentionCount: 10,
+ lastFileName: null,
+ lastRowCount: 0,
+ lastError: null,
+ timeOfDay: "00:00",
+ weeklyDow: 1,
+ monthlyDom: 1
+ })
+
+ const { getByTestId } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByTestId("numeric-input-Day of month")).toBeTruthy()
+ })
+
+ const input = getByTestId("numeric-input-Day of month")
+ fireEvent.changeText(input, "99")
+ fireEvent(input, "blur")
+
+ await waitFor(() => {
+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportMonthlyDom", "31")
+ })
+ })
+
+ it("formats Last Export with 24h clock", async () => {
+ mockGetAutoExportStatus.mockResolvedValue({
+ enabled: true,
+ format: "geojson",
+ interval: "daily",
+ uri: "content://some-uri",
+ mode: "all",
+ lastExportTimestamp: 1700000000, // 2023-11-14 22:13:20 UTC
+ nextExportTimestamp: 1700086400,
+ fileCount: 0,
+ retentionCount: 10,
+ lastFileName: null,
+ lastRowCount: 0,
+ lastError: null,
+ timeOfDay: "00:00",
+ weeklyDow: 1,
+ monthlyDom: 1
+ })
+
+ const { queryAllByText } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ // Format: "YYYY-MM-DD HH:MM" - assert no AM/PM and digits look right.
+ const ampmMatches = queryAllByText(/\b(AM|PM)\b/)
+ expect(ampmMatches.length).toBe(0)
+ })
+ })
+
it("handles onAutoExportComplete event for failure", async () => {
const { getByText } = render(<AutoExportScreen {...mockProps} />)
diff --git a/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx b/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx
index fe980c4d..6086fe76 100644
--- a/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx
@@ -293,45 +293,4 @@ describe("ExportDataScreen", () => {
// totalLocations is 0 so the format cards are not rendered and no export button exists
expect(queryByText("CSV")).toBeNull()
})
-
- it("shows auto-export section with status", async () => {
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("Scheduled Export")).toBeTruthy()
- expect(getByText("Auto-Export")).toBeTruthy()
- })
- })
-
- it("shows auto-export summary when enabled", async () => {
- const mockModule = require("../../services/NativeLocationService").default
- mockModule.getAutoExportStatus.mockResolvedValueOnce({
- enabled: true,
- format: "csv",
- interval: "weekly",
- uri: "content://some-uri",
- mode: "all",
- lastExportTimestamp: 1700000000,
- nextExportTimestamp: 1700604800,
- fileCount: 5
- })
-
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText(/Weekly/)).toBeTruthy()
- })
- })
-
- it("navigates to Auto-Export screen on press", async () => {
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("Auto-Export")).toBeTruthy()
- })
-
- fireEvent.press(getByText("Auto-Export"))
-
- expect(mockNavigation.navigate).toHaveBeenCalledWith("Auto-Export")
- })
})
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 22e21b87..020aed29 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -718,9 +718,7 @@ class NativeLocationService {
}
/**
- * Schedules the daily auto-export check worker via WorkManager.
- * The worker checks AutoExportConfig.isExportDue() to determine
- * if an export should actually run (daily/weekly/monthly).
+ * Marks enabledAt and arms the first auto-export alarm.
*/
static async scheduleAutoExport(): Promise<boolean> {
this.ensureModule()
@@ -743,6 +741,14 @@ class NativeLocationService {
return LocationServiceModule.cancelAutoExport()
}
+ /**
+ * Re-arms the auto-export alarm after a schedule-affecting setting change.
+ */
+ static async rescheduleAutoExport(): Promise<boolean> {
+ this.ensureModule()
+ return LocationServiceModule.rescheduleAutoExport()
+ }
+
/**
* Returns current auto-export configuration and status.
*/
@@ -759,6 +765,9 @@ class NativeLocationService {
lastFileName: string | null
lastRowCount: number
lastError: string | null
+ timeOfDay: string
+ weeklyDow: number
+ monthlyDom: number
}> {
this.ensureModule()
return LocationServiceModule.getAutoExportStatus()
diff --git a/apps/mobile/src/utils/format.ts b/apps/mobile/src/utils/format.ts
index 1bda86cd..ea204e3d 100644
--- a/apps/mobile/src/utils/format.ts
+++ b/apps/mobile/src/utils/format.ts
@@ -9,3 +9,23 @@ export const formatBytes = (bytes: number): string => {
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
+
+/** Clamps `value` to the inclusive range [min, max]. */
+export const clamp = (value: number, min: number, max: number): number => Math.max(min, Math.min(max, value))
+
+/** Zero-pads a non-negative integer to width 2 (e.g. 7 -> "07"). */
+export const pad2 = (n: number): string => n.toString().padStart(2, "0")
+
+/** Locale-independent YYYY-MM-DD. Empty epoch -> "Never". */
+export const formatExportDate = (epochSeconds: number): string => {
+ if (epochSeconds === 0) return "Never"
+ const d = new Date(epochSeconds * 1000)
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`
+}
+
+/** Locale-independent YYYY-MM-DD HH:mm (24h). Empty epoch -> "Never". */
+export const formatExportDateTime = (epochSeconds: number): string => {
+ if (epochSeconds === 0) return "Never"
+ const d = new Date(epochSeconds * 1000)
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
+}