Skip to content

Colota - Android GPS Location tracker

Add tracking profiles with condition-based config switching and active profile visibility

Max Dietrich634a6e3071e6
diff --git a/.gitignore b/.gitignore
index c1b9169d..ad65d0be 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,5 +50,9 @@ coverage/
!.yarn/sdks
!.yarn/versions
+# Test output
+*-test-output.txt
+test-output.txt
+
# Misc
testers
diff --git a/.maestro/screenshots/06-profile-editor.yaml b/.maestro/screenshots/06-profile-editor.yaml
new file mode 100644
index 00000000..421f2c61
--- /dev/null
+++ b/.maestro/screenshots/06-profile-editor.yaml
@@ -0,0 +1,14 @@
+appId: com.colota
+---
+- launchApp
+- waitForAnimationToEnd
+- tapOn: "Settings"
+- waitForAnimationToEnd
+- scrollUntilVisible:
+ element: "Tracking Profiles"
+ direction: DOWN
+- tapOn: "Tracking Profiles"
+- waitForAnimationToEnd
+- tapOn: "Create Profile"
+- waitForAnimationToEnd
+- takeScreenshot: ProfileEditor
diff --git a/.maestro/screenshots/06-geofences.yaml b/.maestro/screenshots/07-geofences.yaml
similarity index 100%
rename from .maestro/screenshots/06-geofences.yaml
rename to .maestro/screenshots/07-geofences.yaml
diff --git a/.maestro/screenshots/07-location-inspector.yaml b/.maestro/screenshots/08-location-inspector.yaml
similarity index 100%
rename from .maestro/screenshots/07-location-inspector.yaml
rename to .maestro/screenshots/08-location-inspector.yaml
diff --git a/.maestro/screenshots/08-export-data.yaml b/.maestro/screenshots/09-export-data.yaml
similarity index 100%
rename from .maestro/screenshots/08-export-data.yaml
rename to .maestro/screenshots/09-export-data.yaml
diff --git a/.maestro/screenshots/09-dark-mode.yaml b/.maestro/screenshots/10-dark-mode.yaml
similarity index 100%
rename from .maestro/screenshots/09-dark-mode.yaml
rename to .maestro/screenshots/10-dark-mode.yaml
diff --git a/README.md b/README.md
index 4a375cc6..622a6c56 100644
--- a/README.md
+++ b/README.md
@@ -15,6 +15,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su
- **Works Offline** — Fully functional without a server. Export as CSV, GeoJSON, GPX, or KML.
- **Reliable Tracking** — Foreground service, auto-start on boot, exponential backoff retry.
- **Geofencing** — Pause zones that automatically pause tracking.
+- **Tracking Profiles** — Automatically adjust GPS interval, distance filter, and sync settings based on conditions like charging, car mode, or speed.
- **Flexible Sync** — Instant, batch, Wi-Fi only, or offline modes.
- **Authentication** — Basic Auth, Bearer Token, or custom headers with AES-256-GCM encryption.
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index a4b13788..c1120f5e 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -68,6 +68,7 @@ Emits events back to JavaScript:
- `onTrackingStopped` — service stopped (user action or OOM kill)
- `onSyncError` — 3+ consecutive sync failures
- `onPauseZoneChange` — entered or exited a geofence pause zone
+- `onProfileSwitch` — a tracking profile was activated or deactivated
### LocationProvider Abstraction
@@ -93,20 +94,22 @@ An Android foreground service that runs continuously for GPS tracking. Manages:
Handles all notification logic for the tracking service:
- Channel creation and notification building
+- Dynamic title: "Colota Tracking" by default, "Colota · ProfileName" when a tracking profile is active
- Status text generation (coordinates, sync status, pause zones)
- Throttled updates (10s minimum interval, 2m minimum movement)
- Deduplication to avoid unnecessary notification redraws
### DatabaseHelper
-SQLite database singleton with four tables:
+SQLite database singleton with six tables:
-| Table | Purpose |
-| ----------- | --------------------------------- |
-| `locations` | All recorded GPS locations |
-| `queue` | Locations pending upload |
-| `settings` | App configuration key-value pairs |
-| `geofences` | Pause zone definitions |
+| Table | Purpose |
+| ------------------- | -------------------------------------------- |
+| `locations` | All recorded GPS locations |
+| `queue` | Locations pending upload |
+| `settings` | App configuration key-value pairs |
+| `geofences` | Pause zone definitions |
+| `tracking_profiles` | Condition-based tracking profile definitions |
Uses WAL (Write-Ahead Logging) mode and prepared statements for performance.
@@ -127,6 +130,22 @@ HTTP client. Validates endpoints, enforces HTTPS for public hosts, injects auth
Manages pause zones using the **haversine formula** for distance calculations. Maintains an in-memory cache of geofences that invalidates on CRUD changes.
+### ProfileManager
+
+Evaluates tracking profile conditions and switches GPS settings automatically. Supports four condition types: charging, Android Auto / car mode, speed above threshold, and speed below threshold. Uses a rolling speed buffer for averaged speed readings, deactivation delays (hysteresis) to prevent rapid toggling, and priority-based resolution when multiple profiles match.
+
+### ProfileHelper
+
+Database access layer for tracking profiles and trip events. Maintains a `TimedCache` of enabled profiles (30s TTL) and provides CRUD operations plus trip event logging.
+
+### ConditionMonitor
+
+Registers and manages `BroadcastReceiver` instances for charging state and Android Auto / car mode detection. Forwards state changes to `ProfileManager` for condition evaluation.
+
+### ProfileConstants
+
+Centralized constants for condition type strings (`charging`, `android_auto`, `speed_above`, `speed_below`), event types (`activated`, `deactivated`), cache TTL, speed buffer size, and minimum interval.
+
### SecureStorageHelper
Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credential storage (Basic Auth passwords, Bearer tokens, custom headers).
@@ -151,6 +170,7 @@ Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credentia
| --- | --- |
| `NativeLocationService` | TypeScript bridge to the native `LocationServiceModule` with typed methods for all native operations |
| `LocationServicePermission` | Sequential Android permission requests (fine location → background location → notifications → battery exemption) |
+| `ProfileService` | Thin wrapper over `NativeLocationService` for tracking profile CRUD and trip event queries |
| `SettingsService` | Bridges UI state to native SQLite with type conversion (seconds↔ms, objects↔JSON) |
### Utils
@@ -176,7 +196,7 @@ Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credentia
The app uses React Context for global state:
- **ThemeProvider** — Light/dark theme with system preference sync
-- **TrackingProvider** — Single source of truth for tracking state, coordinates, and settings. Hydrates from SQLite on mount and persists changes back through `SettingsService`.
+- **TrackingProvider** — Single source of truth for tracking state, coordinates, settings, and active profile name. Hydrates from SQLite on mount, restores the active profile from the running service on reconnect, and persists changes back through `SettingsService`.
### Data Flow
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
new file mode 100644
index 00000000..a538e323
--- /dev/null
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -0,0 +1,62 @@
+---
+sidebar_position: 2
+---
+
+# Tracking Profiles
+
+Tracking profiles automatically adjust GPS interval, distance filter, and sync settings when conditions like charging, car mode, or speed thresholds are met.
+
+## Use Cases
+
+- **Charging** — Increase tracking frequency while plugged in (battery isn't a concern)
+- **Driving** — Switch to frequent updates when Android Auto connects or speed exceeds a threshold
+- **Walking** — Use longer intervals at low speeds to conserve battery
+- **Parked** — Reduce updates when stationary with a speed-below profile
+
+## Setup
+
+1. Go to **Settings** → **Tracking Profiles**
+2. Tap **Create Profile**
+3. Enter a name and select a condition trigger
+4. Configure the GPS interval, distance filter, and sync interval
+5. Set a priority (higher priority profiles take precedence when multiple conditions match)
+6. Tap **Create Profile** to save
+
+## Condition Types
+
+| Condition | Trigger |
+| --------------- | --------------------------------------------------------- |
+| **Charging** | Phone is plugged in to a power source |
+| **Car Mode** | Android Auto is connected |
+| **Speed Above** | Average speed exceeds the configured threshold (km/h) |
+| **Speed Below** | Average speed drops below the configured threshold (km/h) |
+
+Speed conditions use a rolling average of the last 5 GPS readings to avoid triggering on momentary speed spikes.
+
+## Profile Settings
+
+Each profile overrides the default tracking configuration with:
+
+- **GPS Interval** — How often to request a location fix (seconds)
+- **Distance Filter** — Minimum movement required between updates (meters)
+- **Sync Interval** — How often to sync with the server (Instant, 1 min, 5 min, or 15 min)
+- **Priority** — Determines which profile wins when multiple conditions match simultaneously (higher = wins)
+- **Deactivation Delay** — How long to wait after the condition stops matching before reverting to default settings (seconds). Prevents rapid toggling when conditions fluctuate.
+
+## How It Works
+
+- When tracking starts, all enabled profiles are evaluated against current conditions
+- The highest-priority matching profile's settings override the defaults
+- When the condition no longer matches, a deactivation delay timer starts
+- If the condition matches again before the delay expires, the timer is cancelled
+- After the delay expires, settings revert to the defaults configured in the Settings screen
+- Profile changes made in the editor take effect immediately on the running service
+
+## Active Profile Indicators
+
+When a profile is active, Colota shows it in two places:
+
+- **Notification** — The foreground notification title changes from "Colota Tracking" to "Colota · ProfileName" (e.g., "Colota · Charging")
+- **Dashboard** — An info card appears on the map showing the active profile name. When inside a pause zone, the pause card shows which profile will resume on exit (e.g., "Profile 'Charging' resumes on exit").
+
+Both indicators disappear automatically when the profile deactivates (after the deactivation delay) or when tracking stops.
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 7216eb82..4d8111b7 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -14,6 +14,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to
- **Works Offline** — Works without a server. Store location history locally and export as CSV, GeoJSON, GPX, or KML.
- **Background Tracking** — Foreground service, auto-start on boot, retry with exponential backoff, battery-critical shutdown.
- **Geofencing** — Create pause zones where tracking automatically pauses to save battery.
+- **Tracking Profiles** — Automatically switch GPS interval, distance filter, and sync settings based on conditions like charging, car mode, or speed thresholds.
- **Sync Modes** — Instant, batch, or offline. Wi-Fi only sync, configurable intervals with automatic retry.
- **Data Export** — Export location history in CSV, GeoJSON, GPX, or KML formats.
- **Authentication** — Basic Auth, Bearer Token, or custom HTTP headers with AES-256-GCM encrypted storage.
@@ -21,7 +22,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to
## App Screens
-Colota has nine screens, each focused on a specific task:
+Colota has eleven screens, each focused on a specific task:
| Screen | Purpose |
| --- | --- |
@@ -30,6 +31,8 @@ Colota has nine screens, each focused on a specific task:
| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends |
| **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |
| **Geofences** | Create, edit, and delete pause zones on an interactive map |
+| **Tracking Profiles** | Create and manage condition-based profiles that automatically adjust tracking settings |
+| **Profile Editor** | Configure profile name, condition trigger, GPS interval, distance filter, sync interval, priority, and deactivation delay |
| **Location History** | Browse recorded locations on a track map with day picker and daily distance traveled, or as a paginated list with accuracy indicators |
| **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML |
| **Data Management** | Clear sent history, delete old data, vacuum the database |
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 3247d2e7..00db322d 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -41,6 +41,7 @@ const sidebars: SidebarsConfig = {
label: "Guides",
items: [
"guides/geofencing",
+ "guides/tracking-profiles",
"guides/data-export",
"guides/data-management",
"guides/battery-optimization",
diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradle
index e35d62c4..b2f136cb 100644
--- a/apps/mobile/android/app/build.gradle
+++ b/apps/mobile/android/app/build.gradle
@@ -159,7 +159,7 @@ android {
reset()
enable true
universalApk false
- include "arm64-v8a", "armeabi-v7a"
+ include "arm64-v8a", "armeabi-v7a", "x86_64", "x86"
}
}
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 af32b3fa..c3905b04 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
@@ -11,6 +11,7 @@ import com.Colota.data.DatabaseHelper
import com.Colota.data.GeofenceHelper
import com.Colota.data.ProfileHelper
import com.Colota.service.LocationForegroundService
+import com.Colota.service.ProfileConstants
import com.Colota.service.ServiceConfig
import com.Colota.service.getDoubleOrNull
import com.Colota.service.getIntOrNull
@@ -60,6 +61,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@Volatile
private var isAppInForeground: Boolean = true
+
+ @Volatile
+ private var activeProfileName: String? = null
/** Skips when app is backgrounded to avoid unnecessary bridge overhead. */
@JvmStatic
@@ -142,6 +146,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
/** Emits profile switch events to JS when a tracking profile activates/deactivates. */
@JvmStatic
fun sendProfileSwitchEvent(profileName: String?, profileId: Int?): Boolean {
+ activeProfileName = profileName
val context = reactContextRef.get() ?: return false
if (!context.hasActiveCatalystInstance()) return false
@@ -481,12 +486,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun createProfile(config: ReadableMap, promise: Promise) = executeAsync(promise) {
val id = profileHelper.insertProfile(
- name = config.getString("name") ?: "",
+ name = (config.getString("name") ?: "").trim(),
intervalMs = config.getDouble("intervalMs").toLong(),
minUpdateDistance = config.getDouble("minUpdateDistance").toFloat(),
syncIntervalSeconds = config.getInt("syncIntervalSeconds"),
priority = config.getInt("priority"),
- conditionType = config.getString("conditionType") ?: "charging",
+ conditionType = config.getString("conditionType") ?: ProfileConstants.CONDITION_CHARGING,
speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))
config.getDouble("speedThreshold").toFloat() else null,
deactivationDelaySeconds = config.getInt("deactivationDelaySeconds")
@@ -500,10 +505,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun updateProfile(config: ReadableMap, promise: Promise) = executeAsync(promise) {
- val id = config.getInt("id")
val result = profileHelper.updateProfile(
- id = id,
- name = config.getStringOrNull("name"),
+ id = config.getInt("id"),
+ name = config.getStringOrNull("name")?.trim(),
intervalMs = config.getDoubleOrNull("intervalMs")?.toLong(),
minUpdateDistance = config.getDoubleOrNull("minUpdateDistance")?.toFloat(),
syncIntervalSeconds = config.getIntOrNull("syncIntervalSeconds"),
@@ -534,17 +538,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun getActiveProfile(promise: Promise) {
- // Active profile state is managed by the foreground service's ProfileManager.
- // Return null if service isn't running — the JS side listens for onProfileSwitch events.
- promise.resolve(null)
+ promise.resolve(activeProfileName)
}
- @ReactMethod
- fun getTripEvents(startTimestamp: Double, endTimestamp: Double, promise: Promise) =
- executeAsync(promise) {
- profileHelper.getTripEventsAsArray(startTimestamp.toLong(), endTimestamp.toLong())
- }
-
@ReactMethod
fun recheckProfiles(promise: Promise) {
try {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
index e7f2ffa8..4882b285 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
@@ -32,8 +32,6 @@ class DatabaseHelper private constructor(context: Context) :
const val TABLE_SETTINGS = "settings"
const val TABLE_GEOFENCES = "geofences"
const val TABLE_PROFILES = "tracking_profiles"
- const val TABLE_TRIP_EVENTS = "trip_events"
-
private val DEFAULT_FIELD_MAP = mapOf(
"lat" to "lat", "lon" to "lon", "acc" to "acc",
"alt" to "alt", "vel" to "vel", "batt" to "batt",
@@ -113,13 +111,28 @@ class DatabaseHelper private constructor(context: Context) :
)
""")
- createProfileTables(db)
+ db.execSQL("""
+ CREATE TABLE $TABLE_PROFILES (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ interval_ms INTEGER NOT NULL,
+ min_update_distance REAL NOT NULL,
+ sync_interval_seconds INTEGER NOT NULL,
+ priority INTEGER NOT NULL DEFAULT 0,
+ condition_type TEXT NOT NULL,
+ speed_threshold REAL,
+ deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL
+ )
+ """)
db.execSQL("CREATE INDEX idx_queue_created ON $TABLE_QUEUE(created_at)")
db.execSQL("CREATE INDEX idx_queue_location ON $TABLE_QUEUE(location_id)")
db.execSQL("CREATE INDEX idx_locations_timestamp ON $TABLE_LOCATIONS(timestamp DESC)")
db.execSQL("CREATE INDEX idx_locations_created ON $TABLE_LOCATIONS(created_at DESC)")
db.execSQL("CREATE INDEX idx_geofences_enabled ON $TABLE_GEOFENCES(enabled, pause_tracking)")
+ db.execSQL("CREATE INDEX idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)")
db.execSQL("CREATE INDEX idx_queue_retry ON $TABLE_QUEUE(retry_count)")
prepopulateSettings(db)
@@ -170,43 +183,24 @@ class DatabaseHelper private constructor(context: Context) :
db.rawQuery("PRAGMA busy_timeout = 5000", null).use { it.moveToFirst() }
}
- private fun createProfileTables(db: SQLiteDatabase) {
- db.execSQL("""
- CREATE TABLE $TABLE_PROFILES (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT NOT NULL,
- interval_ms INTEGER NOT NULL,
- min_update_distance REAL NOT NULL,
- sync_interval_seconds INTEGER NOT NULL,
- priority INTEGER NOT NULL DEFAULT 0,
- condition_type TEXT NOT NULL,
- speed_threshold REAL,
- deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
- enabled INTEGER NOT NULL DEFAULT 1,
- created_at INTEGER NOT NULL
- )
- """)
-
- db.execSQL("""
- CREATE TABLE $TABLE_TRIP_EVENTS (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- profile_id INTEGER,
- profile_name TEXT NOT NULL,
- event_type TEXT NOT NULL,
- latitude REAL,
- longitude REAL,
- timestamp INTEGER NOT NULL,
- FOREIGN KEY (profile_id) REFERENCES $TABLE_PROFILES(id) ON DELETE SET NULL
- )
- """)
-
- db.execSQL("CREATE INDEX idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)")
- db.execSQL("CREATE INDEX idx_trip_events_timestamp ON $TABLE_TRIP_EVENTS(timestamp DESC)")
- }
-
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 2) {
- createProfileTables(db)
+ db.execSQL("""
+ CREATE TABLE IF NOT EXISTS $TABLE_PROFILES (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ interval_ms INTEGER NOT NULL,
+ min_update_distance REAL NOT NULL,
+ sync_interval_seconds INTEGER NOT NULL,
+ priority INTEGER NOT NULL DEFAULT 0,
+ condition_type TEXT NOT NULL,
+ speed_threshold REAL,
+ deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL
+ )
+ """)
+ db.execSQL("CREATE INDEX IF NOT EXISTS idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)")
}
}
@@ -289,7 +283,7 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- private val ALLOWED_TABLES = setOf(TABLE_LOCATIONS, TABLE_QUEUE, TABLE_SETTINGS, TABLE_GEOFENCES, TABLE_PROFILES, TABLE_TRIP_EVENTS)
+ private val ALLOWED_TABLES = setOf(TABLE_LOCATIONS, TABLE_QUEUE, TABLE_SETTINGS, TABLE_GEOFENCES, TABLE_PROFILES)
fun getTableData(tableName: String, limit: Int, offset: Int): List<Map<String, Any?>> {
require(tableName in ALLOWED_TABLES) { "Invalid table name: $tableName" }
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
index 550c4c8a..974b7270 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
@@ -7,6 +7,7 @@ package com.Colota.data
import android.content.ContentValues
import com.Colota.BuildConfig
+import com.Colota.service.ProfileConstants
import com.Colota.util.TimedCache
import android.content.Context
import android.util.Log
@@ -17,7 +18,7 @@ class ProfileHelper(private val context: Context) {
private val dbHelper by lazy { DatabaseHelper.getInstance(context) }
- private val profileCache = TimedCache(30000L) { loadEnabledProfilesFromDB() }
+ private val profileCache = TimedCache(ProfileConstants.CACHE_TTL_MS) { loadEnabledProfilesFromDB() }
data class CachedProfile(
val id: Int,
@@ -44,6 +45,21 @@ class ProfileHelper(private val context: Context) {
fun getEnabledProfiles(): List<CachedProfile> = profileCache.get()
+ private fun cursorToProfile(cursor: android.database.Cursor): CachedProfile {
+ val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
+ return CachedProfile(
+ id = cursor.getInt(cursor.getColumnIndexOrThrow("id")),
+ name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
+ intervalMs = cursor.getLong(cursor.getColumnIndexOrThrow("interval_ms")),
+ minUpdateDistance = cursor.getFloat(cursor.getColumnIndexOrThrow("min_update_distance")),
+ syncIntervalSeconds = cursor.getInt(cursor.getColumnIndexOrThrow("sync_interval_seconds")),
+ priority = cursor.getInt(cursor.getColumnIndexOrThrow("priority")),
+ conditionType = cursor.getString(cursor.getColumnIndexOrThrow("condition_type")),
+ speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),
+ deactivationDelaySeconds = cursor.getInt(cursor.getColumnIndexOrThrow("deactivation_delay_seconds"))
+ )
+ }
+
private fun loadEnabledProfilesFromDB(): List<CachedProfile> {
return try {
val profiles = mutableListOf<CachedProfile>()
@@ -58,28 +74,8 @@ class ProfileHelper(private val context: Context) {
null, null, null,
"priority DESC"
).use { cursor ->
- val idIdx = cursor.getColumnIndexOrThrow("id")
- val nameIdx = cursor.getColumnIndexOrThrow("name")
- val intervalIdx = cursor.getColumnIndexOrThrow("interval_ms")
- val distIdx = cursor.getColumnIndexOrThrow("min_update_distance")
- val syncIdx = cursor.getColumnIndexOrThrow("sync_interval_seconds")
- val prioIdx = cursor.getColumnIndexOrThrow("priority")
- val condIdx = cursor.getColumnIndexOrThrow("condition_type")
- val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
- val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")
-
while (cursor.moveToNext()) {
- profiles.add(CachedProfile(
- id = cursor.getInt(idIdx),
- name = cursor.getString(nameIdx),
- intervalMs = cursor.getLong(intervalIdx),
- minUpdateDistance = cursor.getFloat(distIdx),
- syncIntervalSeconds = cursor.getInt(syncIdx),
- priority = cursor.getInt(prioIdx),
- conditionType = cursor.getString(condIdx),
- speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),
- deactivationDelaySeconds = cursor.getInt(delayIdx)
- ))
+ profiles.add(cursorToProfile(cursor))
}
}
profiles
@@ -218,73 +214,4 @@ class ProfileHelper(private val context: Context) {
) > 0
}
- fun logTripEvent(
- profileId: Int?,
- profileName: String,
- eventType: String,
- latitude: Double?,
- longitude: Double?,
- timestamp: Long
- ) {
- try {
- val values = ContentValues().apply {
- if (profileId != null) {
- put("profile_id", profileId)
- } else {
- putNull("profile_id")
- }
- put("profile_name", profileName)
- put("event_type", eventType)
- if (latitude != null) put("latitude", latitude) else putNull("latitude")
- if (longitude != null) put("longitude", longitude) else putNull("longitude")
- put("timestamp", timestamp)
- }
-
- dbHelper.writableDatabase.insert(DatabaseHelper.TABLE_TRIP_EVENTS, null, values)
- } catch (e: Exception) {
- Log.e(TAG, "Failed to log trip event", e)
- }
- }
-
- fun getTripEventsAsArray(startTimestamp: Long, endTimestamp: Long): WritableArray {
- val array = Arguments.createArray()
-
- try {
- dbHelper.readableDatabase.query(
- DatabaseHelper.TABLE_TRIP_EVENTS,
- null,
- "timestamp >= ? AND timestamp <= ?",
- arrayOf(startTimestamp.toString(), endTimestamp.toString()),
- null, null,
- "timestamp DESC"
- ).use { cursor ->
- val idIdx = cursor.getColumnIndexOrThrow("id")
- val profIdIdx = cursor.getColumnIndexOrThrow("profile_id")
- val profNameIdx = cursor.getColumnIndexOrThrow("profile_name")
- val typeIdx = cursor.getColumnIndexOrThrow("event_type")
- val latIdx = cursor.getColumnIndexOrThrow("latitude")
- val lonIdx = cursor.getColumnIndexOrThrow("longitude")
- val tsIdx = cursor.getColumnIndexOrThrow("timestamp")
-
- while (cursor.moveToNext()) {
- array.pushMap(Arguments.createMap().apply {
- putInt("id", cursor.getInt(idIdx))
- if (cursor.isNull(profIdIdx)) putNull("profileId")
- else putInt("profileId", cursor.getInt(profIdIdx))
- putString("profileName", cursor.getString(profNameIdx))
- putString("eventType", cursor.getString(typeIdx))
- if (cursor.isNull(latIdx)) putNull("latitude")
- else putDouble("latitude", cursor.getDouble(latIdx))
- if (cursor.isNull(lonIdx)) putNull("longitude")
- else putDouble("longitude", cursor.getDouble(lonIdx))
- putDouble("timestamp", cursor.getLong(tsIdx).toDouble())
- })
- }
- }
- } catch (e: Exception) {
- Log.e(TAG, "Failed to load trip events", e)
- }
-
- return array
- }
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
index e56725c2..288ce31f 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
@@ -34,34 +34,39 @@ class ConditionMonitor(
private var carModeReceiver: BroadcastReceiver? = null
fun start() {
+ // Unregister first to prevent duplicate receivers on repeated start() calls
+ stop()
+
registerChargingMonitor()
registerCarModeMonitor()
// Read initial states
- profileManager.onChargingStateChanged(readCurrentChargingState())
- profileManager.onCarModeStateChanged(readCurrentCarModeState())
+ val charging = readCurrentChargingState()
+ val carMode = readCurrentCarModeState()
+ profileManager.onChargingStateChanged(charging)
+ profileManager.onCarModeStateChanged(carMode)
if (BuildConfig.DEBUG) {
- Log.d(TAG, "Condition monitors started — charging: ${readCurrentChargingState()}, carMode: ${readCurrentCarModeState()}")
+ Log.d(TAG, "Condition monitors started — charging: $charging, carMode: $carMode")
}
}
fun stop() {
- chargingReceiver?.let {
- try { context.unregisterReceiver(it) } catch (_: Exception) {}
- }
- chargingReceiver = null
-
- carModeReceiver?.let {
- try { context.unregisterReceiver(it) } catch (_: Exception) {}
- }
- carModeReceiver = null
+ chargingReceiver = unregisterSafely(chargingReceiver)
+ carModeReceiver = unregisterSafely(carModeReceiver)
if (BuildConfig.DEBUG) {
Log.d(TAG, "Condition monitors stopped")
}
}
+ private fun unregisterSafely(receiver: BroadcastReceiver?): Nothing? {
+ receiver?.let {
+ try { context.unregisterReceiver(it) } catch (_: Exception) {}
+ }
+ return null
+ }
+
private fun registerChargingMonitor() {
chargingReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
@@ -82,7 +87,7 @@ class ConditionMonitor(
addAction(Intent.ACTION_POWER_CONNECTED)
addAction(Intent.ACTION_POWER_DISCONNECTED)
}
- context.registerReceiver(chargingReceiver, filter)
+ context.registerReceiver(chargingReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
}
private fun registerCarModeMonitor() {
@@ -96,7 +101,7 @@ class ConditionMonitor(
}
}
- context.registerReceiver(carModeReceiver, IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED))
+ context.registerReceiver(carModeReceiver, IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED), Context.RECEIVER_NOT_EXPORTED)
}
private fun readCurrentChargingState(): Boolean {
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 aea29b7e..59daede0 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
@@ -87,8 +87,8 @@ class LocationForegroundService : Service() {
secureStorage = SecureStorageHelper.getInstance(this)
syncManager = SyncManager(dbHelper, networkManager, serviceScope!!)
profileHelper = ProfileHelper(this)
- profileManager = ProfileManager(profileHelper, serviceScope!!) { interval, distance, syncInterval, profileName, _ ->
- applyProfileConfig(interval, distance, syncInterval, profileName)
+ profileManager = ProfileManager(profileHelper, serviceScope!!) { interval, distance, syncInterval, _, _ ->
+ applyProfileConfig(interval, distance, syncInterval)
}
conditionMonitor = ConditionMonitor(this, profileManager)
@@ -125,9 +125,12 @@ class LocationForegroundService : Service() {
val initialStatus = notificationHelper.getInitialStatus(
insidePauseZone, currentZoneName, lastKnownLocation
)
+ val initialTitle = notificationHelper.buildTitle(
+ if (::profileManager.isInitialized) profileManager.getActiveProfileName() else null
+ )
startForeground(
NotificationHelper.NOTIFICATION_ID,
- notificationHelper.buildTrackingNotification(initialStatus)
+ notificationHelper.buildTrackingNotification(initialTitle, initialStatus)
)
if (!isLightweight) {
@@ -162,6 +165,7 @@ class LocationForegroundService : Service() {
}
ACTION_RECHECK_PROFILES -> {
profileManager.invalidateProfiles()
+ profileManager.evaluate()
return START_STICKY
}
ACTION_MANUAL_FLUSH -> {
@@ -335,14 +339,14 @@ class LocationForegroundService : Service() {
}
private fun handleLocationUpdate(location: android.location.Location) {
- // Feed location to profile manager for speed-based condition evaluation
- // (must run before accuracy filter so speed data is always captured)
- profileManager.onLocationUpdate(location)
-
if (config.filterInaccurateLocations && location.accuracy > config.accuracyThreshold) {
return
}
+ // Feed location to profile manager for speed-based condition evaluation
+ // (after accuracy filter so bad GPS data doesn't pollute speed average)
+ profileManager.onLocationUpdate(location)
+
lastKnownLocation = location
val zoneName = geofenceHelper.getPauseZone(location)
@@ -465,6 +469,7 @@ class LocationForegroundService : Service() {
zoneName = activeZone,
queuedCount = syncManager.getCachedQueuedCount(),
lastSyncTime = syncManager.lastSuccessfulSyncTime,
+ activeProfileName = profileManager.getActiveProfileName(),
forceUpdate = forceUpdate
)
}
@@ -474,6 +479,11 @@ class LocationForegroundService : Service() {
Log.i(TAG, "Stopping: $reason")
}
+ // Clear active profile so JS UI resets the profile indicator
+ if (profileManager.getActiveProfileName() != null) {
+ LocationServiceModule.sendProfileSwitchEvent(null, null)
+ }
+
LocationServiceModule.sendTrackingStoppedEvent(reason)
dbHelper.saveSetting("tracking_enabled", "false")
@@ -497,7 +507,7 @@ class LocationForegroundService : Service() {
* Dynamically switches GPS interval and sync config when a profile activates/deactivates.
* No full service restart — just re-requests location updates with new parameters.
*/
- private fun applyProfileConfig(interval: Long, distance: Float, syncInterval: Int, profileName: String?) {
+ private fun applyProfileConfig(interval: Long, distance: Float, syncInterval: Int) {
config = config.copy(
interval = interval,
minUpdateDistance = distance,
@@ -522,8 +532,13 @@ class LocationForegroundService : Service() {
}
}
+ // Update notification to show/hide profile name in title
+ lastKnownLocation?.let {
+ updateNotification(lat = it.latitude, lon = it.longitude, forceUpdate = true)
+ } ?: updateNotification(forceUpdate = true)
+
if (BuildConfig.DEBUG) {
- Log.i(TAG, "Profile config applied: ${profileName ?: "default"} — interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")
+ Log.i(TAG, "Profile config applied: ${profileManager.getActiveProfileName() ?: "default"} — interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
index e4208922..6e1bdab9 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
@@ -49,7 +49,7 @@ class NotificationHelper(
}
}
- fun buildTrackingNotification(statusText: String): Notification {
+ fun buildTrackingNotification(title: String, statusText: String): Notification {
val pendingIntent = PendingIntent.getActivity(
context,
0,
@@ -58,7 +58,7 @@ class NotificationHelper(
)
return NotificationCompat.Builder(context, CHANNEL_ID)
- .setContentTitle("Colota Tracking")
+ .setContentTitle(title)
.setContentText(statusText)
.setSmallIcon(android.R.drawable.ic_menu_mylocation)
.setOngoing(true)
@@ -68,6 +68,10 @@ class NotificationHelper(
.build()
}
+ /** Returns the notification title, including the active profile name if one is set. */
+ fun buildTitle(activeProfileName: String?): String =
+ if (activeProfileName != null) "Colota \u00b7 $activeProfileName" else "Colota Tracking"
+
fun buildStoppedNotification(reason: String): Notification {
return NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Colota: Stopped")
@@ -156,6 +160,7 @@ class NotificationHelper(
zoneName: String? = null,
queuedCount: Int = 0,
lastSyncTime: Long = 0L,
+ activeProfileName: String? = null,
forceUpdate: Boolean = false
): Boolean {
val now = System.currentTimeMillis()
@@ -185,12 +190,13 @@ class NotificationHelper(
val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime)
// Dedup: skip if notification text hasn't changed
- val cacheKey = "$statusText-$queuedCount"
+ val cacheKey = "$statusText-$queuedCount-$activeProfileName"
if (cacheKey == lastText) return false
lastText = cacheKey
lastQueuedCount = queuedCount
- notificationManager.notify(NOTIFICATION_ID, buildTrackingNotification(statusText))
+ val title = buildTitle(activeProfileName)
+ notificationManager.notify(NOTIFICATION_ID, buildTrackingNotification(title, statusText))
return true
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt
new file mode 100644
index 00000000..1a45930a
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt
@@ -0,0 +1,17 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+object ProfileConstants {
+ const val CONDITION_CHARGING = "charging"
+ const val CONDITION_ANDROID_AUTO = "android_auto"
+ const val CONDITION_SPEED_ABOVE = "speed_above"
+ const val CONDITION_SPEED_BELOW = "speed_below"
+
+ const val CACHE_TTL_MS = 30_000L
+ const val SPEED_BUFFER_SIZE = 5
+ const val MIN_INTERVAL_MS = 1000L
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
index 1afab052..c27c8759 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
@@ -5,7 +5,6 @@
package com.Colota.service
-import android.location.Location
import android.util.Log
import com.Colota.BuildConfig
import com.Colota.bridge.LocationServiceModule
@@ -30,7 +29,6 @@ class ProfileManager(
) {
companion object {
private const val TAG = "ProfileManager"
- private const val SPEED_BUFFER_SIZE = 5
}
// Default config values (set by the service after loading config)
@@ -50,8 +48,6 @@ class ProfileManager(
private val speedBuffer = ArrayDeque<Float>()
private val speedLock = Any()
- // Last known location for trip event logging
- @Volatile private var lastLocation: Location? = null
fun onChargingStateChanged(charging: Boolean) {
isCharging = charging
@@ -63,12 +59,10 @@ class ProfileManager(
evaluate()
}
- fun onLocationUpdate(location: Location) {
- lastLocation = location
-
+ fun onLocationUpdate(location: android.location.Location) {
if (location.hasSpeed()) {
synchronized(speedLock) {
- if (speedBuffer.size >= SPEED_BUFFER_SIZE) {
+ if (speedBuffer.size >= ProfileConstants.SPEED_BUFFER_SIZE) {
speedBuffer.removeFirst()
}
speedBuffer.addLast(location.speed)
@@ -88,12 +82,16 @@ class ProfileManager(
* Must handle concurrent calls from location updates, broadcasts, and service actions.
*/
@Synchronized
- private fun evaluate() {
+ fun evaluate() {
val profiles = profileHelper.getEnabledProfiles()
+
+ // If the active profile was disabled or deleted, deactivate immediately (no delay)
+ if (activeProfile != null && profiles.none { it.id == activeProfile!!.id }) {
+ cancelDeactivation()
+ deactivateToDefault()
+ }
+
if (profiles.isEmpty()) {
- if (activeProfile != null) {
- scheduleDeactivation(activeProfile!!)
- }
return
}
@@ -103,14 +101,20 @@ class ProfileManager(
when {
// A profile matches — activate it (or keep if already active)
matchingProfile != null -> {
+ cancelDeactivation()
+
if (activeProfile?.id == matchingProfile.id) {
- // Same profile still matches — cancel any pending deactivation
- cancelDeactivation()
+ // Same profile still matches — re-apply only if config changed
+ val active = activeProfile!!
+ if (active.intervalMs != matchingProfile.intervalMs ||
+ active.minUpdateDistance != matchingProfile.minUpdateDistance ||
+ active.syncIntervalSeconds != matchingProfile.syncIntervalSeconds) {
+ activateProfile(matchingProfile)
+ }
return
}
// Different profile or new activation
- cancelDeactivation()
activateProfile(matchingProfile)
}
@@ -123,14 +127,14 @@ class ProfileManager(
private fun matchesCondition(profile: ProfileHelper.CachedProfile): Boolean {
return when (profile.conditionType) {
- "charging" -> isCharging
- "android_auto" -> isCarMode
- "speed_above" -> {
+ ProfileConstants.CONDITION_CHARGING -> isCharging
+ ProfileConstants.CONDITION_ANDROID_AUTO -> isCarMode
+ ProfileConstants.CONDITION_SPEED_ABOVE -> {
val avgSpeed = getAverageSpeed()
val threshold = profile.speedThreshold
avgSpeed != null && threshold != null && avgSpeed > threshold
}
- "speed_below" -> {
+ ProfileConstants.CONDITION_SPEED_BELOW -> {
val avgSpeed = getAverageSpeed()
val threshold = profile.speedThreshold
avgSpeed != null && threshold != null && avgSpeed < threshold
@@ -149,17 +153,6 @@ class ProfileManager(
private fun activateProfile(profile: ProfileHelper.CachedProfile) {
activeProfile = profile
- // Log trip event
- val loc = lastLocation
- profileHelper.logTripEvent(
- profileId = profile.id,
- profileName = profile.name,
- eventType = "activated",
- latitude = loc?.latitude,
- longitude = loc?.longitude,
- timestamp = System.currentTimeMillis() / 1000
- )
-
if (BuildConfig.DEBUG) {
Log.i(TAG, "Activated profile: ${profile.name} (interval=${profile.intervalMs}ms, sync=${profile.syncIntervalSeconds}s)")
}
@@ -180,9 +173,11 @@ class ProfileManager(
private fun scheduleDeactivation(profile: ProfileHelper.CachedProfile) {
if (deactivationJob?.isActive == true) return // already scheduled
+ val scheduledProfileId = profile.id
deactivationJob = scope.launch {
delay(profile.deactivationDelaySeconds * 1000L)
- deactivateToDefault()
+ ensureActive()
+ deactivateIfStillActive(scheduledProfileId)
}
if (BuildConfig.DEBUG) {
@@ -190,28 +185,28 @@ class ProfileManager(
}
}
+ /**
+ * Called from the deactivation coroutine. Re-checks under lock that the
+ * profile being deactivated is still the active one — prevents a race
+ * where evaluate() activated a new profile between ensureActive() and
+ * acquiring the synchronized lock.
+ */
+ @Synchronized
+ private fun deactivateIfStillActive(scheduledProfileId: Int) {
+ if (activeProfile?.id != scheduledProfileId) return
+ deactivateToDefault()
+ }
+
private fun cancelDeactivation() {
deactivationJob?.cancel()
deactivationJob = null
}
- @Synchronized
private fun deactivateToDefault() {
val previousProfile = activeProfile ?: return
activeProfile = null
deactivationJob = null
- // Log trip event
- val loc = lastLocation
- profileHelper.logTripEvent(
- profileId = previousProfile.id,
- profileName = previousProfile.name,
- eventType = "deactivated",
- latitude = loc?.latitude,
- longitude = loc?.longitude,
- timestamp = System.currentTimeMillis() / 1000
- )
-
if (BuildConfig.DEBUG) {
Log.i(TAG, "Deactivated profile: ${previousProfile.name} — reverting to defaults")
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt
new file mode 100644
index 00000000..29fe8ada
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt
@@ -0,0 +1,228 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.data
+
+import android.database.Cursor
+import android.database.sqlite.SQLiteDatabase
+import io.mockk.*
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+/**
+ * Tests for ProfileHelper cache behavior and public API contracts.
+ * Database interactions are mocked since unit tests don't have SQLite.
+ */
+class ProfileHelperTest {
+
+ private lateinit var mockDb: SQLiteDatabase
+ private lateinit var mockDbHelper: DatabaseHelper
+
+ @Before
+ fun setup() {
+ mockDb = mockk(relaxed = true)
+ mockDbHelper = mockk {
+ every { readableDatabase } returns mockDb
+ every { writableDatabase } returns mockDb
+ }
+
+ // Use reflection to set the singleton for tests
+ mockkObject(DatabaseHelper.Companion)
+ every { DatabaseHelper.getInstance(any()) } returns mockDbHelper
+ }
+
+ private fun mockCursorWithProfiles(profiles: List<Map<String, Any?>>): Cursor {
+ val cursor = mockk<Cursor>(relaxed = true)
+ var position = -1
+
+ every { cursor.moveToNext() } answers {
+ position++
+ position < profiles.size
+ }
+
+ // Column index mapping
+ val columns = listOf(
+ "id", "name", "interval_ms", "min_update_distance",
+ "sync_interval_seconds", "priority", "condition_type",
+ "speed_threshold", "deactivation_delay_seconds", "enabled", "created_at"
+ )
+
+ for ((idx, col) in columns.withIndex()) {
+ every { cursor.getColumnIndexOrThrow(col) } returns idx
+ }
+
+ every { cursor.getInt(any()) } answers {
+ val col = firstArg<Int>()
+ val profile = profiles[position]
+ val key = columns[col]
+ (profile[key] as? Number)?.toInt() ?: 0
+ }
+
+ every { cursor.getLong(any()) } answers {
+ val col = firstArg<Int>()
+ val profile = profiles[position]
+ val key = columns[col]
+ (profile[key] as? Number)?.toLong() ?: 0L
+ }
+
+ every { cursor.getFloat(any()) } answers {
+ val col = firstArg<Int>()
+ val profile = profiles[position]
+ val key = columns[col]
+ (profile[key] as? Number)?.toFloat() ?: 0f
+ }
+
+ every { cursor.getString(any()) } answers {
+ val col = firstArg<Int>()
+ val profile = profiles[position]
+ val key = columns[col]
+ profile[key] as? String ?: ""
+ }
+
+ every { cursor.isNull(any()) } answers {
+ val col = firstArg<Int>()
+ val profile = profiles[position]
+ val key = columns[col]
+ profile[key] == null
+ }
+
+ every { cursor.close() } just Runs
+
+ return cursor
+ }
+
+ @Test
+ fun `getEnabledProfiles returns profiles from database`() {
+ val cursor = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "Charging", "interval_ms" to 10000L,
+ "min_update_distance" to 0f, "sync_interval_seconds" to 0,
+ "priority" to 10, "condition_type" to "charging",
+ "speed_threshold" to null, "deactivation_delay_seconds" to 60
+ )
+ ))
+
+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returns cursor
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+ val profiles = helper.getEnabledProfiles()
+
+ assertEquals(1, profiles.size)
+ assertEquals("Charging", profiles[0].name)
+ assertEquals(10000L, profiles[0].intervalMs)
+ assertEquals("charging", profiles[0].conditionType)
+ assertNull(profiles[0].speedThreshold)
+ }
+
+ @Test
+ fun `getEnabledProfiles caches results on second call`() {
+ val cursor = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "Test", "interval_ms" to 5000L,
+ "min_update_distance" to 0f, "sync_interval_seconds" to 0,
+ "priority" to 10, "condition_type" to "charging",
+ "speed_threshold" to null, "deactivation_delay_seconds" to 30
+ )
+ ))
+
+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returns cursor
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+
+ helper.getEnabledProfiles()
+ helper.getEnabledProfiles()
+
+ // Query should only be called once due to caching
+ verify(exactly = 1) { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `invalidateCache causes reload on next call`() {
+ val cursor1 = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "V1", "interval_ms" to 5000L,
+ "min_update_distance" to 0f, "sync_interval_seconds" to 0,
+ "priority" to 10, "condition_type" to "charging",
+ "speed_threshold" to null, "deactivation_delay_seconds" to 30
+ )
+ ))
+ val cursor2 = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "V2", "interval_ms" to 10000L,
+ "min_update_distance" to 0f, "sync_interval_seconds" to 0,
+ "priority" to 10, "condition_type" to "charging",
+ "speed_threshold" to null, "deactivation_delay_seconds" to 30
+ )
+ ))
+
+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returnsMany listOf(cursor1, cursor2)
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+
+ val first = helper.getEnabledProfiles()
+ assertEquals("V1", first[0].name)
+
+ helper.invalidateCache()
+
+ val second = helper.getEnabledProfiles()
+ assertEquals("V2", second[0].name)
+
+ verify(exactly = 2) { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `getEnabledProfiles returns empty list on database error`() {
+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } throws RuntimeException("DB error")
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+ val profiles = helper.getEnabledProfiles()
+
+ assertTrue(profiles.isEmpty())
+ }
+
+ @Test
+ fun `getEnabledProfiles handles speed threshold`() {
+ val cursor = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "Fast", "interval_ms" to 2000L,
+ "min_update_distance" to 10f, "sync_interval_seconds" to 0,
+ "priority" to 15, "condition_type" to "speed_above",
+ "speed_threshold" to 13.89f, "deactivation_delay_seconds" to 30
+ )
+ ))
+
+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returns cursor
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+ val profiles = helper.getEnabledProfiles()
+
+ assertEquals(1, profiles.size)
+ assertEquals(13.89f, profiles[0].speedThreshold!!, 0.01f)
+ assertEquals("speed_above", profiles[0].conditionType)
+ }
+
+ @Test
+ fun `deleteProfile calls database delete`() {
+ every { mockDb.delete(any(), any(), any()) } returns 1
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+ val result = helper.deleteProfile(42)
+
+ assertTrue(result)
+ verify { mockDb.delete(DatabaseHelper.TABLE_PROFILES, "id = ?", arrayOf("42")) }
+ }
+
+ @Test
+ fun `deleteProfile returns false when no rows affected`() {
+ every { mockDb.delete(any(), any(), any()) } returns 0
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+ val result = helper.deleteProfile(999)
+
+ assertFalse(result)
+ }
+
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
index ff2fdb66..b4cf4b6f 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
@@ -157,6 +157,23 @@ class NotificationHelperTest {
assertFalse(shouldFilterByMovement(5.0f))
}
+ // --- buildTitle ---
+
+ @Test
+ fun `title shows Colota Tracking when no profile active`() {
+ assertEquals("Colota Tracking", buildTitle(null))
+ }
+
+ @Test
+ fun `title includes profile name when active`() {
+ assertEquals("Colota \u00b7 Charging", buildTitle("Charging"))
+ }
+
+ @Test
+ fun `title includes custom profile name`() {
+ assertEquals("Colota \u00b7 Fast Driving", buildTitle("Fast Driving"))
+ }
+
// --- Deduplication ---
@Test
@@ -179,6 +196,11 @@ class NotificationHelperTest {
assertTrue(shouldUpdate("52.00000, 13.00000 (Synced)-0", "52.00000, 13.00000 (Synced)-5"))
}
+ @Test
+ fun `profile name change triggers update`() {
+ assertTrue(shouldUpdate("52.00000, 13.00000-0-null", "52.00000, 13.00000-0-Charging"))
+ }
+
// --- Helper methods that mirror NotificationHelper logic ---
private fun formatTimeSinceSync(lastSyncTime: Long, now: Long): String {
@@ -223,4 +245,7 @@ class NotificationHelperTest {
private fun shouldUpdate(lastText: String?, newText: String): Boolean =
newText != lastText
+
+ private fun buildTitle(activeProfileName: String?): String =
+ if (activeProfileName != null) "Colota \u00b7 $activeProfileName" else "Colota Tracking"
}
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
new file mode 100644
index 00000000..cc66b6ad
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
@@ -0,0 +1,482 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.location.Location
+import com.Colota.data.ProfileHelper
+import io.mockk.*
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class ProfileManagerTest {
+
+ private lateinit var profileHelper: ProfileHelper
+ private lateinit var testScope: TestScope
+ private var switchedInterval: Long = 0
+ private var switchedDistance: Float = 0f
+ private var switchedSyncInterval: Int = 0
+ private var switchedProfileName: String? = null
+ private var switchedProfileId: Int? = null
+ private var switchCount = 0
+
+ private fun createManager(): ProfileManager {
+ return ProfileManager(profileHelper, testScope) { interval, distance, sync, name, id ->
+ switchedInterval = interval
+ switchedDistance = distance
+ switchedSyncInterval = sync
+ switchedProfileName = name
+ switchedProfileId = id
+ switchCount++
+ }
+ }
+
+ private fun chargingProfile(
+ id: Int = 1,
+ name: String = "Charging",
+ intervalMs: Long = 10000,
+ priority: Int = 10,
+ deactivationDelay: Int = 60
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = name,
+ intervalMs = intervalMs,
+ minUpdateDistance = 0f,
+ syncIntervalSeconds = 0,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_CHARGING,
+ speedThreshold = null,
+ deactivationDelaySeconds = deactivationDelay
+ )
+
+ private fun carModeProfile(
+ id: Int = 2,
+ name: String = "Car Mode",
+ intervalMs: Long = 3000,
+ priority: Int = 20
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = name,
+ intervalMs = intervalMs,
+ minUpdateDistance = 5f,
+ syncIntervalSeconds = 60,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_ANDROID_AUTO,
+ speedThreshold = null,
+ deactivationDelaySeconds = 30
+ )
+
+ private fun speedAboveProfile(
+ id: Int = 3,
+ threshold: Float = 13.89f, // ~50 km/h
+ priority: Int = 15
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = "Fast",
+ intervalMs = 2000,
+ minUpdateDistance = 10f,
+ syncIntervalSeconds = 0,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_SPEED_ABOVE,
+ speedThreshold = threshold,
+ deactivationDelaySeconds = 30
+ )
+
+ private fun speedBelowProfile(
+ id: Int = 4,
+ threshold: Float = 5.56f, // ~20 km/h
+ priority: Int = 5
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = "Slow",
+ intervalMs = 15000,
+ minUpdateDistance = 0f,
+ syncIntervalSeconds = 300,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_SPEED_BELOW,
+ speedThreshold = threshold,
+ deactivationDelaySeconds = 60
+ )
+
+ private fun mockLocation(speed: Float, hasSpeed: Boolean = true): Location {
+ return mockk {
+ every { [email protected] } returns speed
+ every { [email protected]() } returns hasSpeed
+ every { latitude } returns 52.52
+ every { longitude } returns 13.405
+ }
+ }
+
+ @Before
+ fun setup() {
+ testScope = TestScope()
+ profileHelper = mockk(relaxed = true)
+ switchCount = 0
+ switchedInterval = 0
+ switchedDistance = 0f
+ switchedSyncInterval = 0
+ switchedProfileName = null
+ switchedProfileId = null
+
+ mockkObject(com.Colota.bridge.LocationServiceModule)
+ every { com.Colota.bridge.LocationServiceModule.sendProfileSwitchEvent(any(), any()) } returns true
+ }
+
+ // --- Charging condition ---
+
+ @Test
+ fun `activates charging profile when charging starts`() = runTest {
+ val profile = chargingProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+
+ assertEquals("Charging", switchedProfileName)
+ assertEquals(10000L, switchedInterval)
+ assertEquals(1, switchCount)
+ }
+
+ @Test
+ fun `does not activate charging profile when not charging`() = runTest {
+ val profile = chargingProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(false)
+
+ assertEquals(0, switchCount)
+ }
+
+ // --- Car mode condition ---
+
+ @Test
+ fun `activates car mode profile when car mode enabled`() = runTest {
+ val profile = carModeProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.onCarModeStateChanged(true)
+
+ assertEquals("Car Mode", switchedProfileName)
+ assertEquals(3000L, switchedInterval)
+ }
+
+ // --- Speed conditions ---
+
+ @Test
+ fun `activates speed above profile when average speed exceeds threshold`() = runTest {
+ val profile = speedAboveProfile(threshold = 10f)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ // Feed enough speed samples to fill buffer
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(15f))
+ }
+
+ assertEquals("Fast", switchedProfileName)
+ }
+
+ @Test
+ fun `does not activate speed above profile when speed is below threshold`() = runTest {
+ val profile = speedAboveProfile(threshold = 20f)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(10f))
+ }
+
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `activates speed below profile when speed is under threshold`() = runTest {
+ val profile = speedBelowProfile(threshold = 10f)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(5f))
+ }
+
+ assertEquals("Slow", switchedProfileName)
+ }
+
+ @Test
+ fun `speed buffer ignores locations without speed`() = runTest {
+ val profile = speedAboveProfile(threshold = 10f)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ // Feed locations without speed — should not trigger
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(0f, hasSpeed = false))
+ }
+
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `speed buffer uses rolling average`() = runTest {
+ val profile = speedAboveProfile(threshold = 10f)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ // Buffer size is 5, fill with 5 speeds: [5, 5, 5, 20, 20] = avg 11
+ manager.onLocationUpdate(mockLocation(5f))
+ manager.onLocationUpdate(mockLocation(5f))
+ manager.onLocationUpdate(mockLocation(5f))
+ manager.onLocationUpdate(mockLocation(20f))
+ manager.onLocationUpdate(mockLocation(20f))
+
+ assertEquals("Fast", switchedProfileName)
+ }
+
+ // --- Priority ---
+
+ @Test
+ fun `highest priority profile wins when multiple match`() = runTest {
+ val lowPriority = chargingProfile(id = 1, name = "Low", priority = 5)
+ val highPriority = chargingProfile(id = 2, name = "High", priority = 20)
+ // getEnabledProfiles returns sorted by priority DESC
+ every { profileHelper.getEnabledProfiles() } returns listOf(highPriority, lowPriority)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+
+ assertEquals("High", switchedProfileName)
+ assertEquals(2, switchedProfileId)
+ }
+
+ // --- Deactivation delay ---
+
+ @Test
+ fun `schedules deactivation when condition stops matching`() = testScope.runTest {
+ val profile = chargingProfile(deactivationDelay = 30)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ // Activate
+ manager.onChargingStateChanged(true)
+ assertEquals("Charging", switchedProfileName)
+ val activateCount = switchCount
+
+ // Stop charging — should NOT immediately deactivate
+ manager.onChargingStateChanged(false)
+ assertEquals(activateCount, switchCount)
+
+ // Advance past deactivation delay
+ advanceTimeBy(31_000)
+
+ // Now should have reverted to defaults
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ }
+
+ @Test
+ fun `cancels deactivation when condition matches again`() = testScope.runTest {
+ val profile = chargingProfile(deactivationDelay = 60)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+
+ // Activate
+ manager.onChargingStateChanged(true)
+ val countAfterActivate = switchCount
+
+ // Stop charging
+ manager.onChargingStateChanged(false)
+
+ // Start charging again before deactivation delay
+ advanceTimeBy(10_000)
+ manager.onChargingStateChanged(true)
+
+ // Wait past original delay
+ advanceTimeBy(60_000)
+
+ // Should still be on the charging profile (no deactivation happened)
+ assertEquals("Charging", switchedProfileName)
+ }
+
+ // --- Config change detection ---
+
+ @Test
+ fun `reapplies config when same profile matches with different settings`() = runTest {
+ val original = chargingProfile(intervalMs = 10000)
+ every { profileHelper.getEnabledProfiles() } returns listOf(original)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ assertEquals(10000L, switchedInterval)
+ val countAfterActivate = switchCount
+
+ // Profile updated with different interval
+ val updated = chargingProfile(intervalMs = 5000)
+ every { profileHelper.getEnabledProfiles() } returns listOf(updated)
+
+ manager.invalidateProfiles()
+ manager.evaluate()
+
+ assertEquals(5000L, switchedInterval)
+ assertTrue(switchCount > countAfterActivate)
+ }
+
+ @Test
+ fun `does not reapply config when same profile matches with same settings`() = runTest {
+ val profile = chargingProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ val countAfterActivate = switchCount
+
+ // Re-evaluate with same profile
+ manager.evaluate()
+
+ assertEquals(countAfterActivate, switchCount)
+ }
+
+ // --- Empty profiles ---
+
+ @Test
+ fun `no activation when profiles list is empty`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns emptyList()
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+
+ assertEquals(0, switchCount)
+ }
+
+ @Test
+ fun `getActiveProfileName returns null when no profile is active`() {
+ every { profileHelper.getEnabledProfiles() } returns emptyList()
+ val manager = createManager()
+ assertNull(manager.getActiveProfileName())
+ }
+
+ @Test
+ fun `getActiveProfileName returns name after activation`() {
+ val profile = chargingProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+
+ assertEquals("Charging", manager.getActiveProfileName())
+ }
+
+ // --- Profile switching ---
+
+ @Test
+ fun `switches from one profile to another when conditions change`() = runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+
+ // Start charging — charging profile activates (car mode doesn't match)
+ manager.onChargingStateChanged(true)
+ assertEquals("Charging", switchedProfileName)
+
+ // Enable car mode — higher priority car mode profile takes over
+ manager.onCarModeStateChanged(true)
+ assertEquals("Car Mode", switchedProfileName)
+ }
+
+ // --- Immediate deactivation when profile disabled/deleted ---
+
+ @Test
+ fun `deactivates immediately when active profile is disabled`() = runTest {
+ val profile = chargingProfile(deactivationDelay = 60)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ // Activate
+ manager.onChargingStateChanged(true)
+ assertEquals("Charging", switchedProfileName)
+
+ // Profile is disabled — getEnabledProfiles returns empty
+ every { profileHelper.getEnabledProfiles() } returns emptyList()
+ manager.invalidateProfiles()
+ manager.evaluate()
+
+ // Should deactivate immediately (no delay)
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ }
+
+ @Test
+ fun `deactivates immediately when active profile is deleted`() = runTest {
+ val profile = chargingProfile(id = 1, deactivationDelay = 60)
+ val otherProfile = carModeProfile(id = 2, priority = 5)
+
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile, otherProfile)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ // Activate charging profile
+ manager.onChargingStateChanged(true)
+ assertEquals("Charging", switchedProfileName)
+
+ // Profile 1 deleted — only profile 2 remains (but car mode not active)
+ every { profileHelper.getEnabledProfiles() } returns listOf(otherProfile)
+ manager.invalidateProfiles()
+ manager.evaluate()
+
+ // Should deactivate immediately to defaults
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ }
+
+ // --- Unknown condition type ---
+
+ @Test
+ fun `unknown condition type does not match`() = runTest {
+ val profile = ProfileHelper.CachedProfile(
+ id = 99,
+ name = "Unknown",
+ intervalMs = 5000,
+ minUpdateDistance = 0f,
+ syncIntervalSeconds = 0,
+ priority = 10,
+ conditionType = "unknown_condition",
+ speedThreshold = null,
+ deactivationDelaySeconds = 30
+ )
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+
+ assertEquals(0, switchCount)
+ }
+}
diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
index e632ad93..875bc8dc 100644
--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
@@ -29,9 +29,10 @@ type Props = {
coords: LocationCoords | null
tracking: boolean
activeZoneName: string | null
+ activeProfileName: string | null
}
-export function DashboardMap({ coords, tracking, activeZoneName }: Props) {
+export function DashboardMap({ coords, tracking, activeZoneName, activeProfileName }: Props) {
const webviewRef = useRef<WebView>(null)
const { colors, mode } = useTheme()
const isDark = mode === "dark"
@@ -413,7 +414,24 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {
]}
>
<Text style={[styles.infoTitle, { color: colors.text }]}>Paused in {activeZoneName}</Text>
- <Text style={[styles.infoSub, { color: colors.textSecondary }]}>Location not being recorded</Text>
+ <Text style={[styles.infoSub, { color: colors.textSecondary }]}>
+ {activeProfileName ? `Profile "${activeProfileName}" resumes on exit` : "Location not being recorded"}
+ </Text>
+ </View>
+ )}
+
+ {!activeZoneName && activeProfileName && (
+ <View
+ style={[
+ styles.topInfoCard,
+ {
+ backgroundColor: colors.card,
+ borderLeftColor: colors.primary
+ }
+ ]}
+ >
+ <Text style={[styles.infoTitle, { color: colors.text }]}>Profile: {activeProfileName}</Text>
+ <Text style={[styles.infoSub, { color: colors.textSecondary }]}>Tracking settings adjusted</Text>
</View>
)}
</View>
diff --git a/apps/mobile/src/components/features/dashboard/ServerConnection.tsx b/apps/mobile/src/components/features/dashboard/ServerConnection.tsx
index ec8bc12e..955c646a 100644
--- a/apps/mobile/src/components/features/dashboard/ServerConnection.tsx
+++ b/apps/mobile/src/components/features/dashboard/ServerConnection.tsx
@@ -140,7 +140,7 @@ const styles = StyleSheet.create({
padding: 14,
borderRadius: 12,
borderWidth: 1,
- marginBottom: 16
+ marginBottom: 22
},
dot: {
width: 8,
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
new file mode 100644
index 00000000..d1caf0d8
--- /dev/null
+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
@@ -0,0 +1,110 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+
+jest.mock("react-native-webview", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { WebView: (props: any) => R.createElement(View, { testID: "webview", ...props }) }
+})
+
+jest.mock("@react-navigation/native", () => ({
+ useFocusEffect: jest.fn()
+}))
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ text: "#000",
+ textSecondary: "#6b7280",
+ card: "#fff",
+ warning: "#f59e0b",
+ background: "#fff",
+ border: "#e5e7eb",
+ borderRadius: 12
+ },
+ mode: "light"
+ })
+}))
+
+jest.mock("../../../../services/NativeLocationService", () => ({
+ isNetworkAvailable: jest.fn().mockResolvedValue(true),
+ getGeofences: jest.fn().mockResolvedValue([]),
+ checkCurrentPauseZone: jest.fn().mockResolvedValue(null),
+ getMostRecentLocation: jest.fn().mockResolvedValue(null)
+}))
+
+jest.mock("../../../../assets/icons/icon.png", () => "mock-icon")
+
+jest.mock("../../map/mapHtml", () => ({
+ mapStyles: jest.fn().mockReturnValue(""),
+ mapMarkerHelpers: jest.fn().mockReturnValue("")
+}))
+
+jest.mock("../../map/MapCenterButton", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { MapCenterButton: () => R.createElement(View, { testID: "center-button" }) }
+})
+
+import { DashboardMap } from "../DashboardMap"
+
+describe("DashboardMap info cards", () => {
+ const validCoords = { latitude: 48.1, longitude: 11.5, accuracy: 10 }
+
+ const baseProps = {
+ coords: validCoords,
+ tracking: true,
+ activeZoneName: null as string | null,
+ activeProfileName: null as string | null
+ }
+
+ it("shows profile card when activeProfileName is set and no pause zone", () => {
+ const { getByText } = render(<DashboardMap {...baseProps} activeProfileName="Charging" />)
+
+ expect(getByText("Profile: Charging")).toBeTruthy()
+ expect(getByText("Tracking settings adjusted")).toBeTruthy()
+ })
+
+ it("hides profile card when no profile is active", () => {
+ const { queryByText } = render(<DashboardMap {...baseProps} activeProfileName={null} />)
+
+ expect(queryByText(/^Profile:/)).toBeNull()
+ })
+
+ it("shows pause zone card when inside a pause zone", () => {
+ const { getByText } = render(<DashboardMap {...baseProps} activeZoneName="Home" />)
+
+ expect(getByText("Paused in Home")).toBeTruthy()
+ expect(getByText("Location not being recorded")).toBeTruthy()
+ })
+
+ it("shows combined card when both pause zone and profile are active", () => {
+ const { getByText, queryByText } = render(
+ <DashboardMap {...baseProps} activeZoneName="Home" activeProfileName="Charging" />
+ )
+
+ expect(getByText("Paused in Home")).toBeTruthy()
+ expect(getByText('Profile "Charging" resumes on exit')).toBeTruthy()
+ expect(queryByText("Tracking settings adjusted")).toBeNull()
+ })
+
+ it("hides standalone profile card when pause zone is active", () => {
+ const { queryByText } = render(<DashboardMap {...baseProps} activeZoneName="Office" activeProfileName="Charging" />)
+
+ expect(queryByText("Profile: Charging")).toBeNull()
+ expect(queryByText('Profile "Charging" resumes on exit')).toBeTruthy()
+ })
+
+ it("shows default pause message when no profile active in pause zone", () => {
+ const { getByText } = render(<DashboardMap {...baseProps} activeZoneName="Home" activeProfileName={null} />)
+
+ expect(getByText("Location not being recorded")).toBeTruthy()
+ })
+
+ it("shows Tracking Disabled when not tracking", () => {
+ const { getByText } = render(<DashboardMap {...baseProps} tracking={false} coords={null} />)
+
+ expect(getByText("Tracking Disabled")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsx
index ca33d540..8c76a5a3 100644
--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx
+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx
@@ -6,7 +6,7 @@
import React, { useRef, useEffect, useMemo, useState, useCallback } from "react"
import { View, StyleSheet, Text } from "react-native"
import { WebView } from "react-native-webview"
-import { MapPin } from "lucide-react-native"
+import { MapPinOff } from "lucide-react-native"
import { ThemeColors } from "../../../types/global"
import { fonts } from "../../../styles/typography"
import { MapCenterButton } from "../map/MapCenterButton"
@@ -342,7 +342,7 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
return (
<View style={[styles.emptyContainer, { backgroundColor: colors.card, borderRadius: colors.borderRadius }]}>
<View style={[styles.iconCircle, { backgroundColor: colors.border }]}>
- <MapPin size={32} color={colors.textSecondary} />
+ <MapPinOff size={32} color={colors.textSecondary} />
</View>
<Text style={[styles.emptyTitle, { color: colors.text }]}>No Locations</Text>
<Text style={[styles.emptySubtext, { color: colors.textSecondary }]}>No tracked locations for this day.</Text>
diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.ts
index 653b1b4a..230c11a5 100644
--- a/apps/mobile/src/constants/index.ts
+++ b/apps/mobile/src/constants/index.ts
@@ -3,6 +3,9 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import type { ProfileConditionType } from "../types/global"
+import { Zap, Car, ArrowUp, ArrowDown } from "lucide-react-native"
+
// Timing
export const AUTOSAVE_DEBOUNCE_MS = 1500
export const STATS_REFRESH_IDLE = 30_000
@@ -20,6 +23,40 @@ export const MARKER_ANIMATION_DURATION_MS = 500
export const MAP_ANIMATION_DURATION_MS = 400
export const MIN_STATS_INTERVAL_MS = 2000
+// Profiles
+export const MS_TO_KMH = 3.6
+
+export const PROFILE_CONDITIONS: {
+ type: ProfileConditionType
+ label: string
+ listLabel: string
+ icon: typeof Zap
+ description: string
+}[] = [
+ { type: "charging", label: "Charging", listLabel: "When charging", icon: Zap, description: "Phone is plugged in" },
+ {
+ type: "android_auto",
+ label: "Car Mode",
+ listLabel: "Android Auto / Car mode",
+ icon: Car,
+ description: "Android Auto connected"
+ },
+ {
+ type: "speed_above",
+ label: "Speed Above",
+ listLabel: "Speed above",
+ icon: ArrowUp,
+ description: "Moving faster than threshold"
+ },
+ {
+ type: "speed_below",
+ label: "Speed Below",
+ listLabel: "Speed below",
+ icon: ArrowDown,
+ description: "Moving slower than threshold"
+ }
+]
+
// Thresholds
export const HIGH_QUEUE_THRESHOLD = 50
export const CRITICAL_QUEUE_THRESHOLD = 100
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index be9af2ef..c345bc90 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -4,6 +4,7 @@
*/
import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, useRef } from "react"
+import { DeviceEventEmitter } from "react-native"
import { Settings, DEFAULT_SETTINGS, LocationCoords, ApiTemplateName, HttpMethod } from "../types/global"
import { useLocationTracking } from "../hooks/useLocationTracking"
import NativeLocationService from "../services/NativeLocationService"
@@ -20,6 +21,7 @@ type TrackingContextType = {
tracking: boolean
isLoading: boolean
error: Error | null
+ activeProfileName: string | null
startTracking: () => Promise<void>
stopTracking: () => void
restartTracking: (newSettings?: Settings) => Promise<void>
@@ -83,6 +85,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
const [settings, setSettingsState] = useState<Settings>(DEFAULT_SETTINGS)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<Error | null>(null)
+ const [activeProfileName, setActiveProfileName] = useState<string | null>(null)
// Ref to track if component is mounted (prevents state updates after unmount)
const isMountedRef = useRef(true)
@@ -155,6 +158,12 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
if (isTrackingActive) {
logger.debug("[TrackingContext] Re-syncing UI with active background service")
internalReconnect()
+
+ // Restore active profile name from the running service
+ const profileName = await NativeLocationService.getActiveProfileName()
+ if (isMountedRef.current) {
+ setActiveProfileName(profileName)
+ }
}
} catch (err) {
logger.error("[TrackingContext] Hydration failed:", err)
@@ -187,6 +196,16 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
}
}, [internalReconnect, setSettings])
+ // Listen for profile switch events from the native service
+ useEffect(() => {
+ const listener = DeviceEventEmitter.addListener("onProfileSwitch", (event) => {
+ if (isMountedRef.current) {
+ setActiveProfileName(event.profileName ?? null)
+ }
+ })
+ return () => listener.remove()
+ }, [])
+
/**
* Wrapped tracking controls with useCallback for stable references
*/
@@ -209,6 +228,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
try {
internalStop()
if (isMountedRef.current) {
+ setActiveProfileName(null)
setError(null)
}
} catch (err) {
@@ -250,11 +270,23 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
tracking,
isLoading,
error,
+ activeProfileName,
startTracking,
stopTracking,
restartTracking
}),
- [settings, coords, tracking, isLoading, error, setSettings, startTracking, stopTracking, restartTracking]
+ [
+ settings,
+ coords,
+ tracking,
+ isLoading,
+ error,
+ activeProfileName,
+ setSettings,
+ startTracking,
+ stopTracking,
+ restartTracking
+ ]
)
return (
diff --git a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
index 3d16b9bc..c63877fa 100644
--- a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
+++ b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
@@ -8,7 +8,8 @@ jest.mock("../../services/NativeLocationService", () => ({
stop: jest.fn(),
saveSetting: jest.fn().mockResolvedValue(undefined),
isServiceRunning: jest.fn().mockResolvedValue(false),
- isTrackingActive: jest.fn().mockResolvedValue(false)
+ isTrackingActive: jest.fn().mockResolvedValue(false),
+ getActiveProfileName: jest.fn().mockResolvedValue(null)
}))
jest.mock("../../services/SettingsService", () => ({
@@ -250,4 +251,87 @@ describe("useTracking", () => {
expect(result.current.error).toBeNull()
})
+
+ it("updates activeProfileName when onProfileSwitch event fires", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })
+
+ const { DeviceEventEmitter } = require("react-native")
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(result.current.activeProfileName).toBeNull()
+
+ await act(async () => {
+ DeviceEventEmitter.emit("onProfileSwitch", { profileName: "Charging" })
+ })
+
+ expect(result.current.activeProfileName).toBe("Charging")
+ })
+
+ it("clears activeProfileName when onProfileSwitch fires with null", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })
+
+ const { DeviceEventEmitter } = require("react-native")
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ await act(async () => {
+ DeviceEventEmitter.emit("onProfileSwitch", { profileName: "Charging" })
+ })
+
+ expect(result.current.activeProfileName).toBe("Charging")
+
+ await act(async () => {
+ DeviceEventEmitter.emit("onProfileSwitch", { profileName: null })
+ })
+
+ expect(result.current.activeProfileName).toBeNull()
+ })
+
+ it("clears activeProfileName when stopTracking is called", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })
+
+ const { DeviceEventEmitter } = require("react-native")
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ await act(async () => {
+ DeviceEventEmitter.emit("onProfileSwitch", { profileName: "Fast Driving" })
+ })
+
+ expect(result.current.activeProfileName).toBe("Fast Driving")
+
+ await act(async () => {
+ result.current.stopTracking()
+ })
+
+ expect(result.current.activeProfileName).toBeNull()
+ })
+
+ it("restores activeProfileName on reconnect when tracking was active", async () => {
+ const mockGetActiveProfileName = NativeLocationService.getActiveProfileName as jest.Mock
+ mockGetActiveProfileName.mockResolvedValueOnce("Charging")
+ mockGetAllSettings.mockResolvedValueOnce({
+ interval: "5000",
+ tracking_enabled: "true"
+ })
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(mockGetActiveProfileName).toHaveBeenCalled()
+ expect(result.current.activeProfileName).toBe("Charging")
+ })
})
diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsx
index d4c3c055..86e836fe 100644
--- a/apps/mobile/src/screens/DashboardScreen.tsx
+++ b/apps/mobile/src/screens/DashboardScreen.tsx
@@ -25,7 +25,7 @@ import { Square, Play } from "lucide-react-native"
import { logger } from "../utils/logger"
export function DashboardScreen({ navigation }: ScreenProps) {
- const { coords, settings, tracking, startTracking, stopTracking, setSettings } = useTracking()
+ const { coords, settings, tracking, startTracking, stopTracking, setSettings, activeProfileName } = useTracking()
const { colors } = useTheme()
const [stats, setStats] = useState<DatabaseStats>({
@@ -156,7 +156,12 @@ export function DashboardScreen({ navigation }: ScreenProps) {
onTouchStart={() => setScrollEnabled(false)}
onTouchEnd={() => setScrollEnabled(true)}
>
- <DashboardMap coords={coords} tracking={tracking} activeZoneName={currentPauseZone} />
+ <DashboardMap
+ coords={coords}
+ tracking={tracking}
+ activeZoneName={currentPauseZone}
+ activeProfileName={activeProfileName}
+ />
</View>
{/* Tracking Control Button */}
diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsx
index c840da24..618b2033 100644
--- a/apps/mobile/src/screens/ExportDataScreen.tsx
+++ b/apps/mobile/src/screens/ExportDataScreen.tsx
@@ -147,7 +147,7 @@ export function ExportDataScreen() {
) : (
<>
{/* Stats Card */}
- <Card>
+ <View style={[styles.statsContainer, { backgroundColor: colors.card, borderColor: colors.border }]}>
<View style={styles.statsGrid}>
<View style={styles.statItem}>
<Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total</Text>
@@ -163,7 +163,7 @@ export function ExportDataScreen() {
<Text style={[styles.statValue, { color: colors.success }]}>{fileSize ?? "–"}</Text>
</View>
</View>
- </Card>
+ </View>
{/* Format Selection */}
<View style={styles.section}>
@@ -313,6 +313,12 @@ const styles = StyleSheet.create({
textAlign: "center",
lineHeight: 18
},
+ statsContainer: {
+ borderRadius: 16,
+ borderWidth: 2,
+ marginBottom: 24,
+ overflow: "hidden"
+ },
statsGrid: {
flexDirection: "row",
padding: 20
diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsx
index 019811c4..621703cb 100644
--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx
+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx
@@ -11,20 +11,9 @@ import { showAlert } from "../services/modalService"
import { TrackingProfile, ProfileConditionType } from "../types/global"
import { fonts } from "../styles/typography"
import { Container, SectionTitle, Card, Divider } from "../components"
-import { Zap, Car, ArrowUp, ArrowDown, Check } from "lucide-react-native"
+import { Check } from "lucide-react-native"
import { logger } from "../utils/logger"
-
-const CONDITION_OPTIONS: {
- type: ProfileConditionType
- label: string
- icon: any
- description: string
-}[] = [
- { type: "charging", label: "Charging", icon: Zap, description: "Phone is plugged in" },
- { type: "android_auto", label: "Car Mode", icon: Car, description: "Android Auto connected" },
- { type: "speed_above", label: "Speed Above", icon: ArrowUp, description: "Moving faster than threshold" },
- { type: "speed_below", label: "Speed Below", icon: ArrowDown, description: "Moving slower than threshold" }
-]
+import { MS_TO_KMH, PROFILE_CONDITIONS } from "../constants"
const SYNC_OPTIONS = [
{ label: "Instant", value: 0 },
@@ -62,29 +51,35 @@ export function ProfileEditorScreen({ navigation, route }: any) {
useEffect(() => {
if (!profileId) return
- ProfileService.getProfiles().then((profiles) => {
- const existing = profiles.find((p) => p.id === profileId)
- if (existing) {
- setProfile({
- name: existing.name,
- interval: existing.interval,
- distance: existing.distance,
- syncInterval: existing.syncInterval,
- priority: existing.priority,
- condition: existing.condition,
- deactivationDelay: existing.deactivationDelay,
- enabled: existing.enabled
- })
- setIntervalStr(String(existing.interval))
- setDistanceStr(String(existing.distance))
- setPriorityStr(String(existing.priority))
- setDelayStr(String(existing.deactivationDelay))
- if (existing.condition.speedThreshold) {
- setSpeedKmh((existing.condition.speedThreshold * 3.6).toFixed(0))
+ ProfileService.getProfiles()
+ .then((profiles) => {
+ const existing = profiles.find((p) => p.id === profileId)
+ if (existing) {
+ setProfile({
+ name: existing.name,
+ interval: existing.interval,
+ distance: existing.distance,
+ syncInterval: existing.syncInterval,
+ priority: existing.priority,
+ condition: existing.condition,
+ deactivationDelay: existing.deactivationDelay,
+ enabled: existing.enabled
+ })
+ setIntervalStr(String(existing.interval))
+ setDistanceStr(String(existing.distance))
+ setPriorityStr(String(existing.priority))
+ setDelayStr(String(existing.deactivationDelay))
+ if (existing.condition.speedThreshold) {
+ setSpeedKmh((existing.condition.speedThreshold * MS_TO_KMH).toFixed(0))
+ }
}
- }
- })
- }, [profileId])
+ })
+ .catch((err) => {
+ logger.error("[ProfileEditor] Failed to load profile:", err)
+ showAlert("Error", "Failed to load profile data.", "error")
+ navigation.goBack()
+ })
+ }, [profileId, navigation])
const handleNumericChange = useCallback(
(setter: (v: string) => void, field: keyof typeof profile, value: string, min = 0) => {
@@ -104,7 +99,7 @@ export function ProfileEditorScreen({ navigation, route }: any) {
...prev,
condition: {
type,
- ...(isSpeed ? { speedThreshold: Number(speedKmh) / 3.6 } : {})
+ ...(isSpeed ? { speedThreshold: Number(speedKmh) / MS_TO_KMH } : {})
}
}))
},
@@ -117,7 +112,7 @@ export function ProfileEditorScreen({ navigation, route }: any) {
if (!isNaN(num) && num > 0) {
setProfile((prev) => ({
...prev,
- condition: { ...prev.condition, speedThreshold: num / 3.6 }
+ condition: { ...prev.condition, speedThreshold: num / MS_TO_KMH }
}))
}
}, [])
@@ -127,6 +122,15 @@ export function ProfileEditorScreen({ navigation, route }: any) {
showAlert("Missing Name", "Please enter a profile name.", "warning")
return
}
+ if (profile.interval < 1) {
+ showAlert("Invalid Interval", "Tracking interval must be at least 1 second.", "warning")
+ return
+ }
+ const isSpeed = profile.condition.type === "speed_above" || profile.condition.type === "speed_below"
+ if (isSpeed && (!profile.condition.speedThreshold || profile.condition.speedThreshold <= 0)) {
+ showAlert("Missing Speed", "Speed conditions require a positive speed threshold.", "warning")
+ return
+ }
setSaving(true)
try {
@@ -203,7 +207,7 @@ export function ProfileEditorScreen({ navigation, route }: any) {
<SectionTitle style={styles.sectionGap}>Activation Condition</SectionTitle>
<Card>
<View style={styles.conditionGrid}>
- {CONDITION_OPTIONS.map((opt) => {
+ {PROFILE_CONDITIONS.map((opt) => {
const Icon = opt.icon
const selected = profile.condition.type === opt.type
return (
@@ -291,7 +295,7 @@ export function ProfileEditorScreen({ navigation, route }: any) {
<Divider />
- <Text style={[styles.label, { color: colors.textSecondary, marginBottom: 8 }]}>Sync Interval</Text>
+ <Text style={[styles.label, styles.syncSectionLabel, { color: colors.textSecondary }]}>Sync Interval</Text>
<View style={styles.syncGrid}>
{SYNC_OPTIONS.map((opt) => {
const selected = profile.syncInterval === opt.value
@@ -343,7 +347,7 @@ export function ProfileEditorScreen({ navigation, route }: any) {
{/* Save Button */}
<TouchableOpacity
- style={[styles.saveBtn, { backgroundColor: colors.primary, opacity: saving ? 0.6 : 1 }]}
+ style={[styles.saveBtn, { backgroundColor: colors.primary }, saving && styles.saveBtnDisabled]}
onPress={handleSave}
disabled={saving}
activeOpacity={0.7}
@@ -425,5 +429,7 @@ const styles = StyleSheet.create({
marginTop: 16
},
saveBtnText: { fontSize: 16, ...fonts.semiBold },
+ saveBtnDisabled: { opacity: 0.6 },
+ syncSectionLabel: { marginBottom: 8 },
sectionGap: { marginTop: 24 }
})
diff --git a/apps/mobile/src/screens/TrackingProfilesScreen.tsx b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
index 99737905..f14bd449 100644
--- a/apps/mobile/src/screens/TrackingProfilesScreen.tsx
+++ b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
@@ -4,40 +4,29 @@
*/
import React, { useState, useEffect, useCallback } from "react"
-import { View, Text, StyleSheet, FlatList, Switch, TouchableOpacity, DeviceEventEmitter } from "react-native"
+import { View, Text, StyleSheet, FlatList, Switch, TouchableOpacity } from "react-native"
import { useTheme } from "../hooks/useTheme"
+import { useTracking } from "../contexts/TrackingProvider"
import { ProfileService } from "../services/ProfileService"
import { showAlert, showConfirm } from "../services/modalService"
-import { TrackingProfile, ScreenProps } from "../types/global"
+import { SavedTrackingProfile, ScreenProps } from "../types/global"
import { fonts } from "../styles/typography"
import { Container, SectionTitle, Card } from "../components"
-import { Plus, X, Zap, Car, ArrowUp, ArrowDown } from "lucide-react-native"
+import { Plus, X, Zap } from "lucide-react-native"
import { logger } from "../utils/logger"
+import { PROFILE_CONDITIONS, MS_TO_KMH } from "../constants"
-const CONDITION_LABELS: Record<string, string> = {
- charging: "When charging",
- android_auto: "Android Auto / Car mode",
- speed_above: "Speed above",
- speed_below: "Speed below"
-}
-
-const CONDITION_ICONS: Record<string, any> = {
- charging: Zap,
- android_auto: Car,
- speed_above: ArrowUp,
- speed_below: ArrowDown
-}
-
-function formatCondition(profile: TrackingProfile): string {
- const label = CONDITION_LABELS[profile.condition.type] || profile.condition.type
+function formatCondition(profile: SavedTrackingProfile): string {
+ const condition = PROFILE_CONDITIONS.find((c) => c.type === profile.condition.type)
+ const label = condition?.listLabel || profile.condition.type
if (profile.condition.type === "speed_above" || profile.condition.type === "speed_below") {
- const kmh = ((profile.condition.speedThreshold ?? 0) * 3.6).toFixed(0)
+ const kmh = ((profile.condition.speedThreshold ?? 0) * MS_TO_KMH).toFixed(0)
return `${label} ${kmh} km/h`
}
return label
}
-function formatSettings(profile: TrackingProfile): string {
+function formatSettings(profile: SavedTrackingProfile): string {
const parts = [`${profile.interval}s interval`]
if (profile.distance > 0) parts.push(`${profile.distance}m threshold`)
parts.push(profile.syncInterval === 0 ? "instant sync" : `${profile.syncInterval}s sync`)
@@ -46,8 +35,8 @@ function formatSettings(profile: TrackingProfile): string {
export function TrackingProfilesScreen({ navigation }: ScreenProps) {
const { colors } = useTheme()
- const [profiles, setProfiles] = useState<TrackingProfile[]>([])
- const [activeProfileName, setActiveProfileName] = useState<string | null>(null)
+ const { activeProfileName } = useTracking()
+ const [profiles, setProfiles] = useState<SavedTrackingProfile[]>([])
const loadProfiles = useCallback(async () => {
try {
@@ -62,14 +51,6 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
loadProfiles()
}, [loadProfiles])
- // Listen for profile switch events from the native service
- useEffect(() => {
- const listener = DeviceEventEmitter.addListener("onProfileSwitch", (event) => {
- setActiveProfileName(event.profileName ?? null)
- })
- return () => listener.remove()
- }, [])
-
// Reload when returning from editor
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
@@ -91,7 +72,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
)
const handleDelete = useCallback(
- async (item: TrackingProfile) => {
+ async (item: SavedTrackingProfile) => {
const confirmed = await showConfirm({
title: "Delete Profile",
message: `Delete "${item.name}"?`,
@@ -102,7 +83,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
if (!confirmed) return
try {
- await ProfileService.deleteProfile(item.id!)
+ await ProfileService.deleteProfile(item.id)
await loadProfiles()
} catch {
showAlert("Error", "Failed to delete profile.", "error")
@@ -112,12 +93,13 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
)
const renderItem = useCallback(
- ({ item }: { item: TrackingProfile }) => {
- const ConditionIcon = CONDITION_ICONS[item.condition.type] || Zap
+ ({ item }: { item: SavedTrackingProfile }) => {
+ const condition = PROFILE_CONDITIONS.find((c) => c.type === item.condition.type)
+ const ConditionIcon = condition?.icon || Zap
const isActive = activeProfileName === item.name
return (
- <Card style={[styles.card, isActive && { borderColor: colors.primary, borderWidth: 2 }]}>
+ <Card style={[styles.card, isActive && styles.activeCard, isActive && { borderColor: colors.primary }]}>
<TouchableOpacity
style={styles.row}
onPress={() => navigation.navigate("Profile Editor", { profileId: item.id })}
@@ -146,7 +128,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
<View style={styles.actions}>
<Switch
value={item.enabled}
- onValueChange={(val) => toggleEnabled(item.id!, val)}
+ onValueChange={(val) => toggleEnabled(item.id, val)}
trackColor={{ false: colors.border, true: colors.primary + "80" }}
thumbColor={item.enabled ? colors.primary : colors.border}
/>
@@ -170,7 +152,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
<Container>
<FlatList
data={profiles}
- keyExtractor={(item) => item.id!.toString()}
+ keyExtractor={(item) => item.id.toString()}
contentContainerStyle={styles.list}
showsVerticalScrollIndicator={false}
ListHeaderComponent={
@@ -225,6 +207,7 @@ const styles = StyleSheet.create({
},
createBtnText: { fontSize: 15, ...fonts.semiBold },
card: { marginBottom: 12, padding: 14 },
+ activeCard: { borderWidth: 2 },
row: { flexDirection: "row", alignItems: "center" },
iconWrap: {
width: 36,
diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
new file mode 100644
index 00000000..eb8ce598
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
@@ -0,0 +1,303 @@
+import React from "react"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { TrackingProfile } from "../../types/global"
+
+// --- Mocks ---
+
+const mockProfiles: TrackingProfile[] = [
+ {
+ id: 1,
+ name: "Existing Profile",
+ interval: 10,
+ distance: 5,
+ syncInterval: 60,
+ priority: 15,
+ condition: { type: "speed_above", speedThreshold: 13.89 },
+ deactivationDelay: 30,
+ enabled: true
+ }
+]
+
+const mockGetProfiles = jest.fn().mockResolvedValue(mockProfiles)
+const mockCreateProfile = jest.fn().mockResolvedValue(1)
+const mockUpdateProfile = jest.fn().mockResolvedValue(true)
+
+jest.mock("../../services/ProfileService", () => ({
+ ProfileService: {
+ getProfiles: () => mockGetProfiles(),
+ createProfile: (p: any) => mockCreateProfile(p),
+ updateProfile: (p: any) => mockUpdateProfile(p)
+ }
+}))
+
+const mockShowAlert = jest.fn()
+
+jest.mock("../../services/modalService", () => ({
+ showAlert: (...args: any[]) => mockShowAlert(...args)
+}))
+
+jest.mock("../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ border: "#e5e7eb",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ background: "#fff",
+ info: "#3b82f6",
+ success: "#22c55e",
+ error: "#ef4444",
+ card: "#fff",
+ backgroundElevated: "#f9fafb",
+ placeholder: "#9ca3af",
+ textOnPrimary: "#fff"
+ }
+ })
+}))
+
+jest.mock("../../components", () => {
+ const R = require("react")
+ const { View, Text } = require("react-native")
+ return {
+ Container: ({ children }: any) => R.createElement(View, null, children),
+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
+ Card: ({ children }: any) => R.createElement(View, null, children),
+ Divider: () => R.createElement(View, null)
+ }
+})
+
+const mockGoBack = jest.fn()
+
+const mockNavigation = {
+ goBack: mockGoBack
+}
+
+import { ProfileEditorScreen } from "../ProfileEditorScreen"
+
+describe("ProfileEditorScreen", () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockGetProfiles.mockResolvedValue(mockProfiles)
+ })
+
+ function renderNewProfile() {
+ return render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: {} }} />)
+ }
+
+ function renderEditProfile(profileId = 1) {
+ return render(<ProfileEditorScreen navigation={mockNavigation as any} route={{ params: { profileId } }} />)
+ }
+
+ // --- New Profile Mode ---
+
+ it("renders new profile title", () => {
+ const { getByText } = renderNewProfile()
+ expect(getByText("New Profile")).toBeTruthy()
+ })
+
+ it("shows Create Profile button for new profile", () => {
+ const { getByText } = renderNewProfile()
+ expect(getByText("Create Profile")).toBeTruthy()
+ })
+
+ it("shows all condition options", () => {
+ const { getByText } = renderNewProfile()
+
+ expect(getByText("Charging")).toBeTruthy()
+ expect(getByText("Car Mode")).toBeTruthy()
+ expect(getByText("Speed Above")).toBeTruthy()
+ expect(getByText("Speed Below")).toBeTruthy()
+ })
+
+ it("shows all sync interval options", () => {
+ const { getByText } = renderNewProfile()
+
+ expect(getByText("Instant")).toBeTruthy()
+ expect(getByText("1 min")).toBeTruthy()
+ expect(getByText("5 min")).toBeTruthy()
+ expect(getByText("15 min")).toBeTruthy()
+ })
+
+ // --- Validation ---
+
+ it("shows alert when saving with empty name", async () => {
+ const { getByText } = renderNewProfile()
+
+ fireEvent.press(getByText("Create Profile"))
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Missing Name", "Please enter a profile name.", "warning")
+ })
+ })
+
+ it("allows setting interval to valid value", () => {
+ const { getByDisplayValue } = renderNewProfile()
+
+ const intervalInput = getByDisplayValue("5")
+ fireEvent.changeText(intervalInput, "15")
+
+ expect(getByDisplayValue("15")).toBeTruthy()
+ })
+
+ it("saves with speed condition when threshold is valid", async () => {
+ const { getByText, getByDisplayValue } = renderNewProfile()
+
+ const nameInput = getByDisplayValue("")
+ fireEvent.changeText(nameInput, "Speed Test")
+
+ // Select speed_above condition — defaults to 30 km/h threshold
+ fireEvent.press(getByText("Speed Above"))
+
+ fireEvent.press(getByText("Create Profile"))
+
+ await waitFor(() => {
+ expect(mockCreateProfile).toHaveBeenCalled()
+ expect(mockGoBack).toHaveBeenCalled()
+ })
+ })
+
+ // --- Successful save ---
+
+ it("creates profile and navigates back on valid save", async () => {
+ const { getByText, getByDisplayValue } = renderNewProfile()
+
+ const nameInput = getByDisplayValue("")
+ fireEvent.changeText(nameInput, "My Profile")
+
+ fireEvent.press(getByText("Create Profile"))
+
+ await waitFor(() => {
+ expect(mockCreateProfile).toHaveBeenCalled()
+ expect(mockGoBack).toHaveBeenCalled()
+ })
+ })
+
+ it("does not call createProfile when validation fails", async () => {
+ const { getByText } = renderNewProfile()
+
+ // Try to save with empty name
+ fireEvent.press(getByText("Create Profile"))
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalled()
+ })
+
+ expect(mockCreateProfile).not.toHaveBeenCalled()
+ })
+
+ // --- Edit Mode ---
+
+ it("renders edit profile title when editing", async () => {
+ const { getByText } = renderEditProfile()
+
+ await waitFor(() => {
+ expect(getByText("Edit Profile")).toBeTruthy()
+ })
+ })
+
+ it("shows Save Changes button when editing", async () => {
+ const { getByText } = renderEditProfile()
+
+ await waitFor(() => {
+ expect(getByText("Save Changes")).toBeTruthy()
+ })
+ })
+
+ it("loads existing profile data", async () => {
+ const { getByDisplayValue } = renderEditProfile()
+
+ await waitFor(() => {
+ expect(getByDisplayValue("Existing Profile")).toBeTruthy()
+ expect(getByDisplayValue("15")).toBeTruthy() // priority
+ expect(getByDisplayValue("10")).toBeTruthy() // interval
+ })
+ })
+
+ it("loads speed threshold in km/h", async () => {
+ const { getByDisplayValue } = renderEditProfile()
+
+ // 13.89 m/s * 3.6 = 50 km/h
+ await waitFor(() => {
+ expect(getByDisplayValue("50")).toBeTruthy()
+ })
+ })
+
+ it("calls updateProfile when saving in edit mode", async () => {
+ const { getByText } = renderEditProfile()
+
+ await waitFor(() => {
+ expect(getByText("Save Changes")).toBeTruthy()
+ })
+
+ fireEvent.press(getByText("Save Changes"))
+
+ await waitFor(() => {
+ expect(mockUpdateProfile).toHaveBeenCalled()
+ expect(mockGoBack).toHaveBeenCalled()
+ })
+ })
+
+ it("shows error and navigates back on load failure", async () => {
+ mockGetProfiles.mockRejectedValueOnce(new Error("DB Error"))
+
+ renderEditProfile()
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to load profile data.", "error")
+ expect(mockGoBack).toHaveBeenCalled()
+ })
+ })
+
+ it("shows error when save fails", async () => {
+ mockCreateProfile.mockRejectedValueOnce(new Error("Save failed"))
+
+ const { getByText, getByDisplayValue } = renderNewProfile()
+
+ const nameInput = getByDisplayValue("")
+ fireEvent.changeText(nameInput, "Fail Profile")
+
+ fireEvent.press(getByText("Create Profile"))
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to save profile.", "error")
+ })
+ })
+
+ // --- Speed condition visibility ---
+
+ it("shows speed threshold input only for speed conditions", () => {
+ const { getByText, queryByText } = renderNewProfile()
+
+ // Default is charging — no speed input
+ expect(queryByText("Speed Threshold (km/h)")).toBeNull()
+
+ // Select Speed Above
+ fireEvent.press(getByText("Speed Above"))
+ expect(getByText("Speed Threshold (km/h)")).toBeTruthy()
+
+ // Switch back to charging
+ fireEvent.press(getByText("Charging"))
+ expect(queryByText("Speed Threshold (km/h)")).toBeNull()
+ })
+
+ // --- Numeric input ---
+
+ it("updates interval via numeric input", () => {
+ const { getByDisplayValue } = renderNewProfile()
+
+ const intervalInput = getByDisplayValue("5")
+ fireEvent.changeText(intervalInput, "15")
+
+ expect(getByDisplayValue("15")).toBeTruthy()
+ })
+
+ it("updates priority via numeric input", () => {
+ const { getByDisplayValue } = renderNewProfile()
+
+ const priorityInput = getByDisplayValue("10")
+ fireEvent.changeText(priorityInput, "25")
+
+ expect(getByDisplayValue("25")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
new file mode 100644
index 00000000..9624c825
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
@@ -0,0 +1,235 @@
+import React from "react"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { TrackingProfile } from "../../types/global"
+
+// --- Mocks ---
+
+const mockProfiles: TrackingProfile[] = [
+ {
+ id: 1,
+ name: "Charging",
+ interval: 10,
+ distance: 0,
+ syncInterval: 0,
+ priority: 10,
+ condition: { type: "charging" },
+ deactivationDelay: 60,
+ enabled: true
+ },
+ {
+ id: 2,
+ name: "Driving",
+ interval: 3,
+ distance: 5,
+ syncInterval: 60,
+ priority: 20,
+ condition: { type: "speed_above", speedThreshold: 13.89 },
+ deactivationDelay: 30,
+ enabled: false
+ }
+]
+
+const mockGetProfiles = jest.fn().mockResolvedValue(mockProfiles)
+const mockUpdateProfile = jest.fn().mockResolvedValue(true)
+const mockDeleteProfile = jest.fn().mockResolvedValue(true)
+
+jest.mock("../../services/ProfileService", () => ({
+ ProfileService: {
+ getProfiles: () => mockGetProfiles(),
+ updateProfile: (update: any) => mockUpdateProfile(update),
+ deleteProfile: (id: number) => mockDeleteProfile(id)
+ }
+}))
+
+const mockShowAlert = jest.fn()
+const mockShowConfirm = jest.fn().mockResolvedValue(true)
+
+jest.mock("../../services/modalService", () => ({
+ showAlert: (...args: any[]) => mockShowAlert(...args),
+ showConfirm: (...args: any[]) => mockShowConfirm(...args)
+}))
+
+let mockActiveProfileName: string | null = null
+
+jest.mock("../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({ activeProfileName: mockActiveProfileName })
+}))
+
+jest.mock("../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ border: "#e5e7eb",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ background: "#fff",
+ success: "#22c55e",
+ error: "#ef4444",
+ card: "#fff",
+ backgroundElevated: "#f9fafb",
+ textOnPrimary: "#fff"
+ }
+ })
+}))
+
+jest.mock("../../components", () => {
+ const R = require("react")
+ const { View, Text } = require("react-native")
+ return {
+ Container: ({ children }: any) => R.createElement(View, null, children),
+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
+ Card: ({ children, style }: any) => R.createElement(View, { style }, children)
+ }
+})
+
+const mockNavigate = jest.fn()
+const mockAddListener = jest.fn().mockReturnValue(jest.fn())
+
+const mockNavigation = {
+ navigate: mockNavigate,
+ addListener: mockAddListener
+}
+
+import { TrackingProfilesScreen } from "../TrackingProfilesScreen"
+
+describe("TrackingProfilesScreen", () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockActiveProfileName = null
+ mockGetProfiles.mockResolvedValue(mockProfiles)
+ mockShowConfirm.mockResolvedValue(true)
+ })
+
+ function renderScreen() {
+ return render(<TrackingProfilesScreen navigation={mockNavigation as any} />)
+ }
+
+ it("renders profile list", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Charging")).toBeTruthy()
+ expect(getByText("Driving")).toBeTruthy()
+ })
+ })
+
+ it("shows profile condition text", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("When charging")).toBeTruthy()
+ expect(getByText(/Speed above 50 km\/h/)).toBeTruthy()
+ })
+ })
+
+ it("shows profile settings summary", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText(/10s interval/)).toBeTruthy()
+ expect(getByText(/3s interval/)).toBeTruthy()
+ })
+ })
+
+ it("shows priority badges", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("P10")).toBeTruthy()
+ expect(getByText("P20")).toBeTruthy()
+ })
+ })
+
+ it("shows empty state when no profiles", async () => {
+ mockGetProfiles.mockResolvedValue([])
+
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("No profiles yet")).toBeTruthy()
+ })
+ })
+
+ it("navigates to editor when pressing Create Profile", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Create Profile")).toBeTruthy()
+ })
+
+ fireEvent.press(getByText("Create Profile"))
+
+ expect(mockNavigate).toHaveBeenCalledWith("Profile Editor", {})
+ })
+
+ it("navigates to editor with profileId when pressing a profile", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Charging")).toBeTruthy()
+ })
+
+ fireEvent.press(getByText("Charging"))
+
+ expect(mockNavigate).toHaveBeenCalledWith("Profile Editor", { profileId: 1 })
+ })
+
+ it("shows confirmation dialog before deleting", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Charging")).toBeTruthy()
+ })
+
+ // The delete buttons are X icons — simulate by finding the delete touchable
+ // Since we can't easily target the X button, verify the confirm dialog is called
+ // when handleDelete is triggered
+ expect(mockDeleteProfile).not.toHaveBeenCalled()
+ })
+
+ it("shows section title with profile count", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Profiles (2)")).toBeTruthy()
+ })
+ })
+
+ it("shows error when toggle fails", async () => {
+ mockUpdateProfile.mockRejectedValueOnce(new Error("Network error"))
+
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Charging")).toBeTruthy()
+ })
+ })
+
+ it("reloads profiles on focus", () => {
+ renderScreen()
+
+ // Verify navigation focus listener is registered
+ expect(mockAddListener).toHaveBeenCalledWith("focus", expect.any(Function))
+ })
+
+ it("shows Active badge when profile matches activeProfileName from context", async () => {
+ mockActiveProfileName = "Charging"
+
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Active")).toBeTruthy()
+ })
+ })
+
+ it("does not show Active badge when no profile is active", async () => {
+ mockActiveProfileName = null
+
+ const { queryByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(queryByText("Active")).toBeNull()
+ })
+ })
+})
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 72030779..396d1859 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -4,7 +4,7 @@
*/
import { NativeModules } from "react-native"
-import { AuthConfig, DatabaseStats, Geofence, Settings, TrackingProfile, TripEvent } from "../types/global"
+import { AuthConfig, DatabaseStats, Geofence, Settings, TrackingProfile, SavedTrackingProfile } from "../types/global"
import { logger } from "../utils/logger"
const { LocationServiceModule, BuildConfigModule } = NativeModules
@@ -328,7 +328,7 @@ class NativeLocationService {
/**
* Fetches all tracking profiles
*/
- static async getProfiles(): Promise<TrackingProfile[]> {
+ static async getProfiles(): Promise<SavedTrackingProfile[]> {
this.ensureModule()
const raw = await this.safeExecute(() => LocationServiceModule.getProfiles(), [], "getProfiles failed")
return raw.map((p: any) => ({
@@ -412,15 +412,11 @@ class NativeLocationService {
}
/**
- * Fetches trip events within a date range
+ * Returns the name of the currently active tracking profile, or null if using defaults
*/
- static async getTripEvents(startTimestamp: number, endTimestamp: number): Promise<TripEvent[]> {
+ static async getActiveProfileName(): Promise<string | null> {
this.ensureModule()
- return this.safeExecute(
- () => LocationServiceModule.getTripEvents(startTimestamp, endTimestamp),
- [],
- "getTripEvents failed"
- )
+ return this.safeExecute(() => LocationServiceModule.getActiveProfile(), null, "getActiveProfile failed")
}
// ============================================================================
diff --git a/apps/mobile/src/services/ProfileService.ts b/apps/mobile/src/services/ProfileService.ts
index adcf0cba..c30d0801 100644
--- a/apps/mobile/src/services/ProfileService.ts
+++ b/apps/mobile/src/services/ProfileService.ts
@@ -4,14 +4,14 @@
*/
import NativeLocationService from "./NativeLocationService"
-import { TrackingProfile, TripEvent } from "../types/global"
+import { TrackingProfile, SavedTrackingProfile } from "../types/global"
/**
* Service for managing tracking profiles.
* Thin wrapper over NativeLocationService profile methods.
*/
export const ProfileService = {
- getProfiles: (): Promise<TrackingProfile[]> => NativeLocationService.getProfiles(),
+ getProfiles: (): Promise<SavedTrackingProfile[]> => NativeLocationService.getProfiles(),
createProfile: (profile: Omit<TrackingProfile, "id" | "createdAt">): Promise<number> =>
NativeLocationService.createProfile(profile),
@@ -21,10 +21,7 @@ export const ProfileService = {
deleteProfile: (id: number): Promise<boolean> => NativeLocationService.deleteProfile(id),
- recheckProfiles: (): Promise<void> => NativeLocationService.recheckProfiles(),
-
- getTripEvents: (startTimestamp: number, endTimestamp: number): Promise<TripEvent[]> =>
- NativeLocationService.getTripEvents(startTimestamp, endTimestamp)
+ recheckProfiles: (): Promise<void> => NativeLocationService.recheckProfiles()
}
export default ProfileService
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index 9b52f7e9..83f197d4 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -54,7 +54,8 @@ jest.mock("react-native", () => ({
}),
saveAuthConfig: jest.fn().mockResolvedValue(true),
getAuthHeaders: jest.fn().mockResolvedValue({}),
- isNetworkAvailable: jest.fn().mockResolvedValue(true)
+ isNetworkAvailable: jest.fn().mockResolvedValue(true),
+ getActiveProfile: jest.fn().mockResolvedValue(null)
},
BuildConfigModule: {
MIN_SDK_VERSION: 26,
@@ -254,6 +255,27 @@ describe("NativeLocationService", () => {
})
})
+ describe("getActiveProfileName", () => {
+ it("returns profile name when a profile is active", async () => {
+ nativeMock.getActiveProfile.mockResolvedValueOnce("Charging")
+ const name = await NativeLocationService.getActiveProfileName()
+ expect(name).toBe("Charging")
+ expect(nativeMock.getActiveProfile).toHaveBeenCalled()
+ })
+
+ it("returns null when no profile is active", async () => {
+ nativeMock.getActiveProfile.mockResolvedValueOnce(null)
+ const name = await NativeLocationService.getActiveProfileName()
+ expect(name).toBeNull()
+ })
+
+ it("returns null on error", async () => {
+ nativeMock.getActiveProfile.mockRejectedValueOnce(new Error("Native error"))
+ const name = await NativeLocationService.getActiveProfileName()
+ expect(name).toBeNull()
+ })
+ })
+
describe("file operations", () => {
it("writeFile returns file path", async () => {
const path = await NativeLocationService.writeFile("test.csv", "data")
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index 97cc8584..925a26e2 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -350,21 +350,8 @@ export interface TrackingProfile {
createdAt?: number
}
-export interface ActiveProfileInfo {
- profileId: number
- profileName: string
- activatedAt: number
-}
-
-export interface TripEvent {
- id: number
- profileId: number | null
- profileName: string
- eventType: "activated" | "deactivated"
- latitude: number | null
- longitude: number | null
- timestamp: number
-}
+/** A profile that has been persisted to the database (always has an id). */
+export type SavedTrackingProfile = TrackingProfile & { id: number }
// ============================================================================
// DATABASE
diff --git a/scripts/sync-screenshots.sh b/scripts/sync-screenshots.sh
index 24e87479..d8f8f594 100644
--- a/scripts/sync-screenshots.sh
+++ b/scripts/sync-screenshots.sh
@@ -33,6 +33,7 @@ STORE_ORDER=(
"Authentication.png"
"DataManagement.png"
"ApiFieldMapping.png"
+ "ProfileEditor.png"
"Geofences.png"
"LocationInspector.png"
"ExportData.png"