Skip to content

Colota - Android GPS Location tracker

feat: add offline mode - toggle to disable sync, hide network UI, track sent status in DB

Max Dietrich1d8cfa5ea650
diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.md
index 3dedd5bd..f5bc3663 100644
--- a/apps/docs/docs/configuration/server-settings.md
+++ b/apps/docs/docs/configuration/server-settings.md
@@ -31,7 +31,48 @@ Use the **Test Connection** button in settings to verify your server is reachabl
- **Instant (0s)**: Each location is sent immediately after recording
- **Batch (1 min, 5 min, 15 min, or Custom)**: Locations are queued and sent in batches at the configured interval
-- **Offline**: No network activity - data is stored locally only
+- **Offline**: No network activity - data is stored locally only. See [Offline Mode](#offline-mode) below.
+
+## Offline Mode
+
+Enable **Offline Mode** in Settings to use Colota as a standalone tracker without any server. Locations are recorded and stored locally on-device.
+
+### Enabling Offline Mode
+
+When you toggle offline mode on with unsent locations still in the queue, a dialog offers several options:
+
+- **Sync First** - attempt to upload queued locations before switching (only available if an endpoint is configured)
+- **Keep in Queue** - preserve queued locations for later sync when you disable offline mode
+- **Delete Queue** - permanently delete all pending locations
+- **Cancel** - abort and stay in online mode
+
+If no locations are queued, offline mode enables immediately.
+
+### What Changes in Offline Mode
+
+The UI simplifies to remove sync-related elements that don't apply:
+
+**Hidden in offline mode:**
+
+- Server Endpoint and Test Connection
+- Authentication & Headers
+- API Field Mapping
+- Sync Interval, Retry Failed Uploads, Wi-Fi Only Sync
+- Queue statistics (Queued / Sent counts)
+- Queue actions (Sync Now, Clear Sent History, Clear Queue)
+- Queue info in the tracking notification
+
+**Still available in offline mode:**
+
+- All tracking parameters (interval, movement threshold, accuracy)
+- Tracking profiles and geofences
+- Data export (CSV, GeoJSON, GPX, KML) - both manual and auto-export
+- Database statistics (Total locations, Today count, Storage)
+- Data cleanup (Delete All Locations, Delete Old, Optimize Database)
+
+### Disabling Offline Mode
+
+Toggle offline mode off in Settings to return to online mode. If you had an endpoint configured before, syncing resumes with your previous settings. Any locations that were kept in the queue will be sent on the next sync cycle.
## Retry Behavior
diff --git a/apps/docs/docs/configuration/sync-presets.md b/apps/docs/docs/configuration/sync-presets.md
index a47beaf2..b942944d 100644
--- a/apps/docs/docs/configuration/sync-presets.md
+++ b/apps/docs/docs/configuration/sync-presets.md
@@ -26,3 +26,7 @@ This is useful for:
- **Battery savings** - Reduce radio usage on metered connections
Toggle this in **Settings > Advanced Settings > Network Settings > Wi-Fi Only Sync**. Locations continue to be recorded and queued regardless of this setting - they sync automatically once Wi-Fi is available.
+
+## Offline Mode
+
+In [offline mode](/docs/configuration/server-settings#offline-mode), network settings (sync interval, retry behavior, Wi-Fi only sync) are hidden since no syncing occurs. Preset descriptions adjust to show only tracking parameters.
diff --git a/apps/docs/docs/guides/data-management.md b/apps/docs/docs/guides/data-management.md
index 7a3d0c7a..1a619a73 100644
--- a/apps/docs/docs/guides/data-management.md
+++ b/apps/docs/docs/guides/data-management.md
@@ -21,6 +21,8 @@ import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
| **Vacuum Database** | Reclaim disk space after deletions |
| **Export Data** | Export location history - see [Data Export](data-export.md) |
+In [offline mode](/docs/configuration/server-settings#offline-mode), sync-related actions (Sync Now, Clear Sent History, Clear Queue) are hidden since no queue is used. A **Delete All Locations** action is available instead. Data export remains fully available - see [Data Export](data-export.md).
+
## Storage Reference
- ~200 bytes per location
diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradle
index 23c42741..f4d9a6bc 100644
--- a/apps/mobile/android/app/build.gradle
+++ b/apps/mobile/android/app/build.gradle
@@ -95,7 +95,7 @@ android {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 26
- versionName "1.4.0-rc1"
+ versionName "1.4.0-rc2"
// Strip Build IDs for reproducible builds (IzzyOnDroid/F-Droid)
externalNativeBuild {
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 6b920b1f..21ebe87c 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
@@ -350,13 +350,13 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun getStats(promise: Promise) = executeAsync(promise) {
- val (queued, total, today) = dbHelper.getStats()
-
+ val stats = dbHelper.getStats()
+
Arguments.createMap().apply {
- putInt("queued", queued)
- putInt("sent", total - queued)
- putInt("total", total)
- putInt("today", today)
+ putInt("queued", stats.queued)
+ putInt("sent", stats.sent)
+ putInt("total", stats.total)
+ putInt("today", stats.today)
putDouble("databaseSizeMB", dbHelper.getDatabaseSizeMB())
}
}
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 233ed694..b5ead664 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,7 +32,7 @@ class DatabaseHelper private constructor(context: Context) :
companion object {
private const val DATABASE_NAME = "Colota.db"
- private const val DATABASE_VERSION = 2
+ private const val DATABASE_VERSION = 3
const val TABLE_LOCATIONS = "locations"
const val TABLE_QUEUE = "queue"
@@ -82,6 +82,7 @@ class DatabaseHelper private constructor(context: Context) :
battery_status INTEGER,
timestamp INTEGER NOT NULL,
endpoint TEXT,
+ sent INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
)
""")
@@ -212,6 +213,11 @@ class DatabaseHelper private constructor(context: Context) :
""")
db.execSQL("CREATE INDEX IF NOT EXISTS idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)")
}
+ if (oldVersion < 3) {
+ db.execSQL("ALTER TABLE $TABLE_LOCATIONS ADD COLUMN sent INTEGER NOT NULL DEFAULT 0")
+ // Mark existing locations not in queue as sent (accurate for pre-offline-mode users)
+ db.execSQL("UPDATE $TABLE_LOCATIONS SET sent = 1 WHERE id NOT IN (SELECT location_id FROM $TABLE_QUEUE)")
+ }
}
override fun onOpen(db: SQLiteDatabase) {
@@ -457,29 +463,50 @@ class DatabaseHelper private constructor(context: Context) :
}
- fun getStats(): Triple<Int, Int, Int> {
+ data class Stats(val queued: Int, val sent: Int, val total: Int, val today: Int)
+
+ fun getStats(): Stats {
val query = """
- SELECT
+ SELECT
(SELECT COUNT(*) FROM $TABLE_QUEUE) as queued,
+ (SELECT COUNT(*) FROM $TABLE_LOCATIONS WHERE sent = 1) as sent,
(SELECT COUNT(*) FROM $TABLE_LOCATIONS) as total,
(SELECT COUNT(*) FROM $TABLE_LOCATIONS WHERE timestamp >= ?) as today
""".trimIndent()
-
+
val todayStart = getTodayStartTimestamp()
-
+
return readableDatabase.rawQuery(query, arrayOf(todayStart.toString())).use { cursor ->
if (cursor.moveToFirst()) {
- Triple(
- cursor.getInt(0), // queued
- cursor.getInt(1), // total
- cursor.getInt(2) // today
+ Stats(
+ queued = cursor.getInt(0),
+ sent = cursor.getInt(1),
+ total = cursor.getInt(2),
+ today = cursor.getInt(3)
)
} else {
- Triple(0, 0, 0)
+ Stats(0, 0, 0, 0)
}
}
}
+ fun markLocationSent(locationId: Long) {
+ writableDatabase.execSQL(
+ "UPDATE $TABLE_LOCATIONS SET sent = 1 WHERE id = ?",
+ arrayOf(locationId)
+ )
+ }
+
+ fun markLocationsSent(locationIds: List<Long>) {
+ if (locationIds.isEmpty()) return
+ val placeholders = locationIds.joinToString(",") { "?" }
+ val args = locationIds.map { it.toString() }.toTypedArray()
+ writableDatabase.execSQL(
+ "UPDATE $TABLE_LOCATIONS SET sent = 1 WHERE id IN ($placeholders)",
+ args
+ )
+ }
+
fun getQueuedCount(): Int {
return readableDatabase.rawQuery("SELECT COUNT(*) FROM $TABLE_QUEUE", null).use {
if (it.moveToFirst()) it.getInt(0) else 0
@@ -496,7 +523,7 @@ class DatabaseHelper private constructor(context: Context) :
AppLogger.d(TAG, "Clearing sent history")
return writableDatabase.delete(
TABLE_LOCATIONS,
- "id NOT IN (SELECT location_id FROM $TABLE_QUEUE)",
+ "sent = 1",
null
)
}
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 1254bc91..53f2efef 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
@@ -206,7 +206,7 @@ class LocationForegroundService : Service() {
conditionMonitor.start()
}
- if (config.syncIntervalSeconds == 0 && config.endpoint.isNotBlank() &&
+ if (!config.isOfflineMode && config.syncIntervalSeconds == 0 && config.endpoint.isNotBlank() &&
!(config.isWifiOnlySync && !networkManager.isUnmeteredConnection())) {
syncManager.manualFlush()
}
@@ -548,15 +548,17 @@ class LocationForegroundService : Service() {
val isCurrentlyPaused = pausedInZone || insidePauseZone
val activeZone = zoneName ?: currentZoneName
+ val offline = ::config.isInitialized && config.isOfflineMode
notificationHelper.update(
lat = lat,
lon = lon,
isPaused = isCurrentlyPaused,
zoneName = activeZone,
- queuedCount = syncManager.getCachedQueuedCount(),
- lastSyncTime = syncManager.lastSuccessfulSyncTime,
+ queuedCount = if (offline) 0 else syncManager.getCachedQueuedCount(),
+ lastSyncTime = if (offline) 0L else syncManager.lastSuccessfulSyncTime,
activeProfileName = profileManager.getActiveProfileName(),
- forceUpdate = forceUpdate
+ forceUpdate = forceUpdate,
+ isOfflineMode = offline
)
}
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 16f2d9c6..340b4302 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
@@ -104,12 +104,15 @@ class NotificationHelper(
lat: Double?,
lon: Double?,
queuedCount: Int,
- lastSyncTime: Long
+ lastSyncTime: Long,
+ isOfflineMode: Boolean = false
): String = when {
isPaused -> "Paused: ${zoneName ?: "Unknown"}"
lat != null && lon != null -> {
val coords = String.format(Locale.US, "%.5f, %.5f", lat, lon)
- if (queuedCount > 0 && lastSyncTime > 0) {
+ if (isOfflineMode) {
+ coords
+ } else if (queuedCount > 0 && lastSyncTime > 0) {
"$coords (Queued: $queuedCount · ${formatTimeSinceSync(lastSyncTime)})"
} else if (queuedCount > 0) {
"$coords (Queued: $queuedCount)"
@@ -158,7 +161,8 @@ class NotificationHelper(
queuedCount: Int = 0,
lastSyncTime: Long = 0L,
activeProfileName: String? = null,
- forceUpdate: Boolean = false
+ forceUpdate: Boolean = false,
+ isOfflineMode: Boolean = false
): Boolean {
val now = System.currentTimeMillis()
@@ -184,7 +188,7 @@ class NotificationHelper(
lastCoords = Pair(lat, lon)
}
- val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime)
+ val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode)
// Dedup: skip if notification text hasn't changed
val cacheKey = "$statusText-$queuedCount-$activeProfileName"
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
index e68dd67e..b92075f2 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
@@ -124,12 +124,17 @@ class SyncManager(
}
suspend fun queueAndSend(locationId: Long, payload: JSONObject) {
+ if (isOfflineMode) {
+ AppLogger.d(TAG, "Skipping queue for location $locationId - offline mode")
+ return
+ }
+
val queueId = dbHelper.addToQueue(locationId, payload.toString())
invalidateQueueCache()
- if (endpoint.isBlank() || isOfflineMode) {
- AppLogger.d(TAG, "Queued location $locationId - ${if (isOfflineMode) "offline mode" else "no endpoint"}")
+ if (endpoint.isBlank()) {
+ AppLogger.d(TAG, "Queued location $locationId - no endpoint configured")
return
}
@@ -140,6 +145,7 @@ class SyncManager(
val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod)
if (success) {
+ dbHelper.markLocationSent(locationId)
dbHelper.removeFromQueueByLocationId(locationId)
invalidateQueueCache()
lastSuccessfulSyncTime = System.currentTimeMillis()
@@ -251,6 +257,10 @@ class SyncManager(
}
val toRemove = successfulIds + permanentlyFailedIds
+ if (successfulIds.isNotEmpty()) {
+ val sentLocationIds = retriable.filter { it.queueId in successfulIds }.map { it.locationId }
+ dbHelper.markLocationsSent(sentLocationIds)
+ }
if (toRemove.isNotEmpty()) {
dbHelper.removeBatchFromQueue(toRemove)
diff --git a/apps/mobile/src/components/features/dashboard/ServerConnection.tsx b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx
similarity index 92%
rename from apps/mobile/src/components/features/dashboard/ServerConnection.tsx
rename to apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx
index 5efec0a7..c20d5d5b 100644
--- a/apps/mobile/src/components/features/dashboard/ServerConnection.tsx
+++ b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx
@@ -9,12 +9,12 @@ import { ChevronRight } from "lucide-react-native"
import { useFocusEffect } from "@react-navigation/native"
import { useTheme } from "../../../hooks/useTheme"
import { useTracking } from "../../../contexts/TrackingProvider"
-import { ServerStatus, ServerConnectionProps } from "../../../types/global"
+import { ServerStatus, ConnectionStatusProps } from "../../../types/global"
import { fonts } from "../../../styles/typography"
import NativeLocationService from "../../../services/NativeLocationService"
import { SERVER_TIMEOUT, SERVER_CHECK_INTERVAL } from "../../../constants"
-export function ServerConnection({ endpoint, navigation }: ServerConnectionProps) {
+export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusProps) {
const { colors } = useTheme()
const { settings } = useTracking()
const isOffline = settings.isOfflineMode
@@ -107,7 +107,7 @@ export function ServerConnection({ endpoint, navigation }: ServerConnectionProps
error: { color: colors.error, label: "Unreachable" },
notConfigured: { color: colors.warning, label: "No endpoint" },
deviceOffline: { color: colors.textSecondary, label: "Device offline" },
- offline: { color: colors.textSecondary, label: "Offline" },
+ offline: { color: colors.textSecondary, label: "Offline Mode" },
loading: { color: colors.textLight, label: "Checking" }
}
@@ -128,9 +128,9 @@ export function ServerConnection({ endpoint, navigation }: ServerConnectionProps
>
<View style={[styles.dot, { backgroundColor: config.color }]} />
<Text style={[styles.host, { color: colors.text }]} numberOfLines={1}>
- {displayUrl || "Server"}
+ {isOffline ? "Offline Mode" : displayUrl || "Server"}
</Text>
- <Text style={[styles.status, { color: config.color }]}>{config.label}</Text>
+ {!isOffline && <Text style={[styles.status, { color: config.color }]}>{config.label}</Text>}
<ChevronRight size={16} color={colors.textLight} />
</Pressable>
)
diff --git a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx b/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
index c30f0571..62b27449 100644
--- a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
+++ b/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
@@ -6,6 +6,7 @@ import React from "react"
import { Text, StyleSheet, View } from "react-native"
import { SectionTitle, Card } from "../.."
import { useTheme } from "../../../hooks/useTheme"
+import { useTracking } from "../../../contexts/TrackingProvider"
import { fonts } from "../../../styles/typography"
import { DatabaseStats } from "../../../types/global"
import { getQueueColor } from "../../../utils/queueStatus"
@@ -15,6 +16,8 @@ type DatabaseStatisticsProps = {
}
export function DatabaseStatistics({ stats }: DatabaseStatisticsProps) {
+ const { settings } = useTracking()
+ const isOfflineMode = settings.isOfflineMode
const { colors } = useTheme()
const queuedColor = getQueueColor(stats.queued, colors)
@@ -23,18 +26,28 @@ export function DatabaseStatistics({ stats }: DatabaseStatisticsProps) {
{/* Database Statistics */}
<View style={styles.metricsSection}>
<SectionTitle>DATABASE STATISTICS</SectionTitle>
- <View style={styles.statsGrid}>
- <Card variant="elevated" style={styles.statCard}>
- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Queued</Text>
- <Text style={[styles.statValue, { color: queuedColor }]}>{stats.queued.toLocaleString()}</Text>
- <Text style={[styles.statUnit, { color: colors.textLight }]}>pending</Text>
- </Card>
- <Card variant="elevated" style={styles.statCard}>
- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Sent</Text>
- <Text style={[styles.statValue, { color: colors.success }]}>{stats.sent.toLocaleString()}</Text>
- <Text style={[styles.statUnit, { color: colors.textLight }]}>synced</Text>
- </Card>
- </View>
+ {!isOfflineMode ? (
+ <View style={styles.statsGrid}>
+ <Card variant="elevated" style={styles.statCard}>
+ <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Queued</Text>
+ <Text style={[styles.statValue, { color: queuedColor }]}>{stats.queued.toLocaleString()}</Text>
+ <Text style={[styles.statUnit, { color: colors.textLight }]}>pending</Text>
+ </Card>
+ <Card variant="elevated" style={styles.statCard}>
+ <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Sent</Text>
+ <Text style={[styles.statValue, { color: colors.success }]}>{stats.sent.toLocaleString()}</Text>
+ <Text style={[styles.statUnit, { color: colors.textLight }]}>synced</Text>
+ </Card>
+ </View>
+ ) : (
+ <View style={styles.statsGrid}>
+ <Card variant="elevated" style={styles.statCard}>
+ <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total</Text>
+ <Text style={[styles.statValue, { color: colors.primary }]}>{stats.total.toLocaleString()}</Text>
+ <Text style={[styles.statUnit, { color: colors.textLight }]}>locations</Text>
+ </Card>
+ </View>
+ )}
<View style={[styles.statsGrid, styles.statsGridSpaced]}>
<Card variant="elevated" style={styles.statCard}>
<Text style={[styles.statLabel, { color: colors.textSecondary }]}>Today</Text>
diff --git a/apps/mobile/src/components/features/dashboard/WelcomeCard.tsx b/apps/mobile/src/components/features/dashboard/WelcomeCard.tsx
index 0adf4174..f9d72829 100644
--- a/apps/mobile/src/components/features/dashboard/WelcomeCard.tsx
+++ b/apps/mobile/src/components/features/dashboard/WelcomeCard.tsx
@@ -7,6 +7,7 @@ import React from "react"
import { Text, StyleSheet, View, Pressable } from "react-native"
import { Check, ChevronRight } from "lucide-react-native"
import { Settings, ThemeColors } from "../../../types/global"
+import { useTracking } from "../../../contexts/TrackingProvider"
import { fonts } from "../../../styles/typography"
import { Card } from "../../ui/Card"
@@ -75,6 +76,9 @@ export function WelcomeCard({
onNavigateToSettings,
onNavigateToApiConfig
}: WelcomeCardProps) {
+ const {
+ settings: { isOfflineMode }
+ } = useTracking()
const hasEndpoint = settings.endpoint.trim().length > 0
return (
@@ -85,18 +89,22 @@ export function WelcomeCard({
<View style={styles.checklist}>
<ChecklistItem label="1. Start tracking" completed={tracking} colors={colors} onPress={onStartTracking} />
- <ChecklistItem
- label="2. Configure your server endpoint"
- completed={hasEndpoint}
- colors={colors}
- onPress={onNavigateToSettings}
- />
+ {!isOfflineMode && (
+ <ChecklistItem
+ label="2. Configure your server endpoint"
+ completed={hasEndpoint}
+ colors={colors}
+ onPress={onNavigateToSettings}
+ />
+ )}
</View>
<View style={styles.linkRow}>
- <Pressable onPress={onNavigateToApiConfig} style={({ pressed }) => pressed && { opacity: 0.6 }}>
- <Text style={[styles.link, { color: colors.primaryDark }]}>API field mapping</Text>
- </Pressable>
+ {!isOfflineMode && (
+ <Pressable onPress={onNavigateToApiConfig} style={({ pressed }) => pressed && { opacity: 0.6 }}>
+ <Text style={[styles.link, { color: colors.primaryDark }]}>API field mapping</Text>
+ </Pressable>
+ )}
<Pressable onPress={onNavigateToSettings} style={({ pressed }) => pressed && { opacity: 0.6 }}>
<Text style={[styles.link, { color: colors.primaryDark }]}>Tracking presets</Text>
</Pressable>
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/ServerConnection.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx
similarity index 83%
rename from apps/mobile/src/components/features/dashboard/__tests__/ServerConnection.test.tsx
rename to apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx
index 88943616..df7a0c32 100644
--- a/apps/mobile/src/components/features/dashboard/__tests__/ServerConnection.test.tsx
+++ b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx
@@ -45,7 +45,7 @@ jest.mock("@react-navigation/native", () => ({
const mockFetch = jest.fn()
;(globalThis as any).fetch = mockFetch
-import { ServerConnection } from "../ServerConnection"
+import { ConnectionStatus } from "../ConnectionStatus"
const mockNavigation = { navigate: jest.fn() }
@@ -61,12 +61,12 @@ afterEach(() => {
jest.useRealTimers()
})
-describe("ServerConnection", () => {
+describe("ConnectionStatus", () => {
it("shows 'Checking' initially before server check completes", () => {
mockFetch.mockReturnValue(new Promise(() => {}))
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
expect(getByText("Checking")).toBeTruthy()
@@ -76,7 +76,7 @@ describe("ServerConnection", () => {
mockFetch.mockResolvedValue({ ok: true, status: 200 })
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
await waitFor(() => {
@@ -88,7 +88,7 @@ describe("ServerConnection", () => {
mockFetch.mockRejectedValue(new Error("Network error"))
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
await waitFor(() => {
@@ -97,7 +97,7 @@ describe("ServerConnection", () => {
})
it("shows 'No endpoint' when endpoint is empty", async () => {
- const { getByText } = render(<ServerConnection endpoint="" navigation={mockNavigation} />)
+ const { getByText } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)
await waitFor(() => {
expect(getByText("No endpoint")).toBeTruthy()
@@ -105,22 +105,22 @@ describe("ServerConnection", () => {
})
it("shows 'No endpoint' when endpoint is null", async () => {
- const { getByText } = render(<ServerConnection endpoint={null} navigation={mockNavigation} />)
+ const { getByText } = render(<ConnectionStatus endpoint={null} navigation={mockNavigation} />)
await waitFor(() => {
expect(getByText("No endpoint")).toBeTruthy()
})
})
- it("shows 'Offline' when offline mode is enabled", async () => {
+ it("shows 'Offline Mode' when offline mode is enabled", async () => {
mockSettings.isOfflineMode = true
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
await waitFor(() => {
- expect(getByText("Offline")).toBeTruthy()
+ expect(getByText("Offline Mode")).toBeTruthy()
})
})
@@ -128,7 +128,7 @@ describe("ServerConnection", () => {
mockIsNetworkAvailable.mockResolvedValue(false)
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
await waitFor(() => {
@@ -142,7 +142,7 @@ describe("ServerConnection", () => {
.mockResolvedValueOnce({ ok: true, status: 200 }) // original endpoint
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
await waitFor(() => {
@@ -159,7 +159,7 @@ describe("ServerConnection", () => {
.mockResolvedValueOnce({ ok: true, status: 200 }) // base URL
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
await waitFor(() => {
@@ -173,14 +173,14 @@ describe("ServerConnection", () => {
mockFetch.mockResolvedValue({ ok: true, status: 200 })
const { getByText } = render(
- <ServerConnection endpoint="https://my-server.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://my-server.com/api/locations" navigation={mockNavigation} />
)
expect(getByText("my-server.com")).toBeTruthy()
})
it("displays 'Server' when endpoint is empty", () => {
- const { getByText } = render(<ServerConnection endpoint="" navigation={mockNavigation} />)
+ const { getByText } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)
expect(getByText("Server")).toBeTruthy()
})
@@ -189,7 +189,7 @@ describe("ServerConnection", () => {
mockGetAuthHeaders.mockResolvedValue({ Authorization: "Bearer token123" })
mockFetch.mockResolvedValue({ ok: true, status: 200 })
- render(<ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />)
+ render(<ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />)
await waitFor(() => {
expect(mockFetch).toHaveBeenCalledWith(
@@ -206,7 +206,7 @@ describe("ServerConnection", () => {
mockFetch.mockResolvedValue({ ok: true, status: 200 })
const { getByText } = render(
- <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
)
await waitFor(() => {
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DatabaseStatistics.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DatabaseStatistics.test.tsx
new file mode 100644
index 00000000..71c660dd
--- /dev/null
+++ b/apps/mobile/src/components/features/dashboard/__tests__/DatabaseStatistics.test.tsx
@@ -0,0 +1,129 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+
+let mockSettings = { isOfflineMode: false }
+
+jest.mock("../../../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: mockSettings
+ })
+}))
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ primaryDark: "#115E59",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ success: "#22c55e",
+ info: "#3b82f6",
+ card: "#fff",
+ border: "#e5e7eb"
+ }
+ })
+}))
+
+jest.mock("../../../index", () => {
+ const R = require("react")
+ const { View, Text } = require("react-native")
+ return {
+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
+ Card: ({ children, variant }: any) => R.createElement(View, { testID: `card-${variant || "default"}` }, children)
+ }
+})
+
+jest.mock("../../../../utils/queueStatus", () => ({
+ getQueueColor: () => "#000"
+}))
+
+import { DatabaseStatistics } from "../DatabaseStatistics"
+
+const baseStats = {
+ queued: 12,
+ sent: 100,
+ total: 500,
+ today: 8,
+ databaseSizeMB: 2.5
+}
+
+describe("DatabaseStatistics", () => {
+ beforeEach(() => {
+ mockSettings = { isOfflineMode: false }
+ })
+
+ it("shows section title", () => {
+ const { getByText } = render(<DatabaseStatistics stats={baseStats} />)
+
+ expect(getByText("DATABASE STATISTICS")).toBeTruthy()
+ })
+
+ describe("online mode (default)", () => {
+ it("shows Queued and Sent cards", () => {
+ const { getByText } = render(<DatabaseStatistics stats={baseStats} />)
+
+ expect(getByText("Queued")).toBeTruthy()
+ expect(getByText("12")).toBeTruthy()
+ expect(getByText("pending")).toBeTruthy()
+ expect(getByText("Sent")).toBeTruthy()
+ expect(getByText("100")).toBeTruthy()
+ expect(getByText("synced")).toBeTruthy()
+ })
+
+ it("does not show Total locations card", () => {
+ const { queryByText } = render(<DatabaseStatistics stats={baseStats} />)
+
+ expect(queryByText("locations")).toBeNull()
+ })
+
+ it("shows Today and Storage cards", () => {
+ const { getByText } = render(<DatabaseStatistics stats={baseStats} />)
+
+ expect(getByText("Today")).toBeTruthy()
+ expect(getByText("8")).toBeTruthy()
+ expect(getByText("tracked")).toBeTruthy()
+ expect(getByText("Storage")).toBeTruthy()
+ expect(getByText("2.5")).toBeTruthy()
+ expect(getByText("MB")).toBeTruthy()
+ })
+ })
+
+ describe("offline mode", () => {
+ beforeEach(() => {
+ mockSettings = { isOfflineMode: true }
+ })
+
+ it("shows Total locations card instead of Queued/Sent", () => {
+ const { getByText } = render(<DatabaseStatistics stats={baseStats} />)
+
+ expect(getByText("Total")).toBeTruthy()
+ expect(getByText("500")).toBeTruthy()
+ expect(getByText("locations")).toBeTruthy()
+ })
+
+ it("hides Queued and Sent cards", () => {
+ const { queryByText } = render(<DatabaseStatistics stats={baseStats} />)
+
+ expect(queryByText("Queued")).toBeNull()
+ expect(queryByText("pending")).toBeNull()
+ expect(queryByText("Sent")).toBeNull()
+ expect(queryByText("synced")).toBeNull()
+ })
+
+ it("still shows Today and Storage cards", () => {
+ const { getByText } = render(<DatabaseStatistics stats={baseStats} />)
+
+ expect(getByText("Today")).toBeTruthy()
+ expect(getByText("Storage")).toBeTruthy()
+ })
+ })
+
+ it("formats large numbers with locale string", () => {
+ mockSettings = { isOfflineMode: true }
+ const largeStats = { ...baseStats, total: 1234567 }
+ const { getByText } = render(<DatabaseStatistics stats={largeStats} />)
+
+ expect(getByText((1234567).toLocaleString())).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/WelcomeCard.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/WelcomeCard.test.tsx
new file mode 100644
index 00000000..59064264
--- /dev/null
+++ b/apps/mobile/src/components/features/dashboard/__tests__/WelcomeCard.test.tsx
@@ -0,0 +1,143 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { DEFAULT_SETTINGS } from "../../../../types/global"
+
+let mockSettings = { isOfflineMode: false }
+
+jest.mock("../../../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: mockSettings
+ })
+}))
+
+jest.mock("../../../ui/Card", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ Card: ({ children }: any) => R.createElement(View, null, children)
+ }
+})
+
+jest.mock("lucide-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ Check: () => R.createElement(View, null),
+ ChevronRight: () => R.createElement(View, null)
+ }
+})
+
+import { WelcomeCard } from "../WelcomeCard"
+
+const mockColors = {
+ primary: "#0d9488",
+ primaryDark: "#115E59",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ success: "#22c55e",
+ border: "#e5e7eb"
+} as any
+
+const defaultProps = {
+ settings: DEFAULT_SETTINGS,
+ tracking: false,
+ colors: mockColors,
+ onDismiss: jest.fn(),
+ onStartTracking: jest.fn(),
+ onNavigateToSettings: jest.fn(),
+ onNavigateToApiConfig: jest.fn()
+}
+
+describe("WelcomeCard", () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockSettings = { isOfflineMode: false }
+ })
+
+ it("renders welcome title and subtitle", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(getByText("Welcome to Colota")).toBeTruthy()
+ expect(getByText("Get started by completing these steps:")).toBeTruthy()
+ })
+
+ it("shows Start tracking checklist item", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(getByText("1. Start tracking")).toBeTruthy()
+ })
+
+ describe("online mode (default)", () => {
+ it("shows server endpoint checklist item", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(getByText("2. Configure your server endpoint")).toBeTruthy()
+ })
+
+ it("shows API field mapping link", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(getByText("API field mapping")).toBeTruthy()
+ })
+
+ it("shows Tracking presets link", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(getByText("Tracking presets")).toBeTruthy()
+ })
+ })
+
+ describe("offline mode", () => {
+ beforeEach(() => {
+ mockSettings = { isOfflineMode: true }
+ })
+
+ it("hides server endpoint checklist item", () => {
+ const { queryByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(queryByText("2. Configure your server endpoint")).toBeNull()
+ })
+
+ it("hides API field mapping link", () => {
+ const { queryByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(queryByText("API field mapping")).toBeNull()
+ })
+
+ it("still shows Tracking presets link", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(getByText("Tracking presets")).toBeTruthy()
+ })
+
+ it("still shows Start tracking checklist item", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ expect(getByText("1. Start tracking")).toBeTruthy()
+ })
+ })
+
+ it("calls onDismiss when Got it is pressed", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ fireEvent.press(getByText("Got it"))
+
+ expect(defaultProps.onDismiss).toHaveBeenCalledTimes(1)
+ })
+
+ it("calls onNavigateToSettings when Tracking presets is pressed", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} />)
+
+ fireEvent.press(getByText("Tracking presets"))
+
+ expect(defaultProps.onNavigateToSettings).toHaveBeenCalledTimes(1)
+ })
+
+ it("marks Start tracking as completed when tracking is active", () => {
+ const { getByText } = render(<WelcomeCard {...defaultProps} tracking />)
+
+ const label = getByText("1. Start tracking")
+ expect(label).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
index e3e2858d..41701399 100644
--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
@@ -16,6 +16,7 @@ import { useTimeout } from "../../../hooks/useTimeout"
import { CONNECTION_TEST_TIMEOUT, TEST_RESULT_DISPLAY_MS } from "../../../constants"
import { logger } from "../../../utils/logger"
import { Button, Card, SectionTitle, Divider } from "../../index"
+import { showChoice } from "../../../services/modalService"
interface ConnectionSettingsProps {
settings: Settings
@@ -40,7 +41,46 @@ export function ConnectionSettings({
const timeout = useTimeout()
const handleOfflineModeChange = useCallback(
- (enabled: boolean) => {
+ async (enabled: boolean) => {
+ if (enabled) {
+ try {
+ const stats = await NativeLocationService.getStats()
+ if (stats.queued > 0) {
+ const hasEndpoint = !!settings.endpoint
+ const buttons = [
+ ...(hasEndpoint ? [{ text: "Sync First", style: "primary" as const }] : []),
+ { text: "Keep in Queue", style: "secondary" as const },
+ { text: "Delete Queue", style: "destructive" as const },
+ { text: "Cancel", style: "secondary" as const }
+ ]
+ const choice = await showChoice({
+ title: "Unsent Locations",
+ message: `You have ${stats.queued} locations waiting to sync. What would you like to do?`,
+ buttons
+ })
+ // Normalize index: with endpoint [Sync, Keep, Delete, Cancel], without [Keep, Delete, Cancel]
+ const action = hasEndpoint
+ ? (["sync", "keep", "delete", "cancel"] as const)[choice]
+ : (["keep", "delete", "cancel"] as const)[choice]
+ if (action === "sync") {
+ try {
+ await NativeLocationService.manualFlush()
+ } catch {
+ // sync may fail, proceed to offline anyway
+ }
+ onSettingsChange({ ...settings, isOfflineMode: true })
+ } else if (action === "keep") {
+ onSettingsChange({ ...settings, isOfflineMode: true })
+ } else if (action === "delete") {
+ await NativeLocationService.clearQueue()
+ onSettingsChange({ ...settings, isOfflineMode: true })
+ }
+ return
+ }
+ } catch {
+ // stats fetch failed, proceed normally
+ }
+ }
onSettingsChange({ ...settings, isOfflineMode: enabled })
},
[settings, onSettingsChange]
diff --git a/apps/mobile/src/components/features/settings/PresetOption.tsx b/apps/mobile/src/components/features/settings/PresetOption.tsx
index d89d79cf..4ae6662d 100644
--- a/apps/mobile/src/components/features/settings/PresetOption.tsx
+++ b/apps/mobile/src/components/features/settings/PresetOption.tsx
@@ -7,6 +7,7 @@ import { Zap, Check } from "lucide-react-native"
import { SelectablePreset, TRACKING_PRESETS } from "../../../types/global"
import { fonts } from "../../../styles/typography"
import { useTheme } from "../../../hooks/useTheme"
+import { useTracking } from "../../../contexts/TrackingProvider"
import { RadioDot } from "../../ui/RadioDot"
interface PresetOptionProps {
@@ -16,6 +17,8 @@ interface PresetOptionProps {
}
export function PresetOption({ preset, isSelected, onSelect }: PresetOptionProps) {
+ const { settings } = useTracking()
+ const isOfflineMode = settings.isOfflineMode
const { colors } = useTheme()
const config = TRACKING_PRESETS[preset]
const showRecommendedBadge = preset === "balanced"
@@ -73,7 +76,9 @@ export function PresetOption({ preset, isSelected, onSelect }: PresetOptionProps
</View>
)}
</View>
- <Text style={[styles.description, { color: colors.textSecondary }]}>{config.description}</Text>
+ <Text style={[styles.description, { color: colors.textSecondary }]}>
+ {isOfflineMode ? config.description.split(" • ")[0] : config.description}
+ </Text>
</View>
</View>
diff --git a/apps/mobile/src/components/features/settings/StatsCard.tsx b/apps/mobile/src/components/features/settings/StatsCard.tsx
index d124e08f..3d3e6b25 100644
--- a/apps/mobile/src/components/features/settings/StatsCard.tsx
+++ b/apps/mobile/src/components/features/settings/StatsCard.tsx
@@ -6,6 +6,7 @@ import React from "react"
import { View, Text, StyleSheet, Pressable } from "react-native"
import { AlertTriangle, ChevronRight } from "lucide-react-native"
import { ThemeColors } from "../../../types/global"
+import { useTracking } from "../../../contexts/TrackingProvider"
import { getQueueColor } from "../../../utils/queueStatus"
import { fonts } from "../../../styles/typography"
import { HIGH_QUEUE_THRESHOLD, CRITICAL_QUEUE_THRESHOLD } from "../../../constants"
@@ -13,8 +14,8 @@ import { HIGH_QUEUE_THRESHOLD, CRITICAL_QUEUE_THRESHOLD } from "../../../constan
interface StatsCardProps {
queueCount: number
sentCount: number
+ todayCount?: number
interval: string
- isOfflineMode: boolean
onManageClick?: () => void
colors: ThemeColors
}
@@ -30,7 +31,9 @@ type WarningLevel = "normal" | "warning" | "critical"
* - Improved warning states
* - More prominent CTA when needed
*/
-export function StatsCard({ queueCount, sentCount, interval, isOfflineMode, onManageClick, colors }: StatsCardProps) {
+export function StatsCard({ queueCount, sentCount, todayCount, interval, onManageClick, colors }: StatsCardProps) {
+ const { settings } = useTracking()
+ const isOfflineMode = settings.isOfflineMode
const getWarningLevel = (): WarningLevel => {
if (queueCount > CRITICAL_QUEUE_THRESHOLD) return "critical"
if (queueCount > HIGH_QUEUE_THRESHOLD) return "warning"
@@ -80,31 +83,35 @@ export function StatsCard({ queueCount, sentCount, interval, isOfflineMode, onMa
{/* Stats Grid */}
<View style={styles.statsGrid}>
- {/* Queued */}
- <View style={styles.statItem}>
- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Queued</Text>
- <Text style={[styles.statValue, { color: queuedColor }]}>{queueCount.toLocaleString()}</Text>
- </View>
+ {isOfflineMode ? (
+ <>
+ {/* Today */}
+ <View style={styles.statItem}>
+ <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Today</Text>
+ <Text style={[styles.statValue, { color: colors.info }]}>{(todayCount ?? 0).toLocaleString()}</Text>
+ </View>
- <View style={[styles.divider, { backgroundColor: colors.border }]} />
+ <View style={[styles.divider, { backgroundColor: colors.border }]} />
+ </>
+ ) : (
+ <>
+ {/* Queued */}
+ <View style={styles.statItem}>
+ <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Queued</Text>
+ <Text style={[styles.statValue, { color: queuedColor }]}>{queueCount.toLocaleString()}</Text>
+ </View>
- {/* Sent */}
- <View style={styles.statItem}>
- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Sent</Text>
- <Text
- style={[
- styles.statValue,
- {
- color: isOfflineMode ? colors.textLight : colors.success
- }
- ]}
- >
- {isOfflineMode ? "—" : sentCount.toLocaleString()}
- </Text>
- {isOfflineMode && <Text style={[styles.disabledHint, { color: colors.textLight }]}>Offline</Text>}
- </View>
+ <View style={[styles.divider, { backgroundColor: colors.border }]} />
+
+ {/* Sent */}
+ <View style={styles.statItem}>
+ <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Sent</Text>
+ <Text style={[styles.statValue, { color: colors.success }]}>{sentCount.toLocaleString()}</Text>
+ </View>
- <View style={[styles.divider, { backgroundColor: colors.border }]} />
+ <View style={[styles.divider, { backgroundColor: colors.border }]} />
+ </>
+ )}
{/* Interval */}
<View style={styles.statItem}>
@@ -117,7 +124,7 @@ export function StatsCard({ queueCount, sentCount, interval, isOfflineMode, onMa
</View>
{/* Warning Banner */}
- {showWarning && onManageClick && (
+ {!isOfflineMode && showWarning && onManageClick && (
<View style={styles.warningWrapper}>
<Pressable
style={({ pressed }) => {
diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
index accb9fd4..ac05dae6 100644
--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
@@ -98,8 +98,7 @@ export function SyncStrategySettings({
syncPreset: preset,
interval: config.interval,
distance: config.distance,
- syncInterval: config.syncInterval,
- retryInterval: config.retryInterval
+ ...(settings.isOfflineMode ? {} : { syncInterval: config.syncInterval, retryInterval: config.retryInterval })
}
onSettingsChange(next)
@@ -195,159 +194,165 @@ export function SyncStrategySettings({
/>
</View>
- <Divider />
+ {!settings.isOfflineMode && (
+ <>
+ <Divider />
- {/* Network Parameters Group */}
- <View style={styles.paramGroup}>
- <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Network Settings</Text>
-
- {/* Sync Interval */}
- <View style={styles.settingBlock}>
- <Text style={[styles.blockLabel, { color: colors.text }]}>Sync Interval</Text>
- <Text style={[styles.blockHint, { color: colors.textSecondary }]}>
- How often to upload data to server
- </Text>
-
- <View style={styles.optionsGrid}>
- {SYNC_INTERVAL_PRESETS.map((sec) => {
- const isSelected = settings.syncInterval === sec && !isCustomSyncInterval
- return (
+ {/* Network Parameters Group */}
+ <View style={styles.paramGroup}>
+ <Text style={[styles.paramGroupTitle, { color: colors.text }]}>Network Settings</Text>
+
+ {/* Sync Interval */}
+ <View style={styles.settingBlock}>
+ <Text style={[styles.blockLabel, { color: colors.text }]}>Sync Interval</Text>
+ <Text style={[styles.blockHint, { color: colors.textSecondary }]}>
+ How often to upload data to server
+ </Text>
+
+ <View style={styles.optionsGrid}>
+ {SYNC_INTERVAL_PRESETS.map((sec) => {
+ const isSelected = settings.syncInterval === sec && !isCustomSyncInterval
+ return (
+ <Pressable
+ key={sec}
+ style={({ pressed }) => [
+ styles.gridOption,
+ {
+ borderColor: colors.border,
+ backgroundColor: colors.background
+ },
+ isSelected && {
+ borderColor: colors.primary,
+ backgroundColor: colors.primary + "20"
+ },
+ pressed && { opacity: 0.7 }
+ ]}
+ onPress={() => handleGridSelect("syncInterval", sec)}
+ >
+ <Text style={[styles.gridLabel, { color: isSelected ? colors.primary : colors.text }]}>
+ {SYNC_INTERVAL_LABELS[sec]}
+ </Text>
+ </Pressable>
+ )
+ })}
<Pressable
- key={sec}
style={({ pressed }) => [
styles.gridOption,
{
borderColor: colors.border,
backgroundColor: colors.background
},
- isSelected && {
+ isCustomSyncInterval && {
borderColor: colors.primary,
backgroundColor: colors.primary + "20"
},
pressed && { opacity: 0.7 }
]}
- onPress={() => handleGridSelect("syncInterval", sec)}
+ onPress={() => {
+ if (!isCustomSyncInterval) {
+ const customValue = 1800
+ setSyncIntervalInput(customValue.toString())
+ handleGridSelect("syncInterval", customValue)
+ }
+ }}
>
- <Text style={[styles.gridLabel, { color: isSelected ? colors.primary : colors.text }]}>
- {SYNC_INTERVAL_LABELS[sec]}
+ <Text
+ style={[styles.gridLabel, { color: isCustomSyncInterval ? colors.primary : colors.text }]}
+ >
+ Custom
</Text>
</Pressable>
- )
- })}
- <Pressable
- style={({ pressed }) => [
- styles.gridOption,
- {
- borderColor: colors.border,
- backgroundColor: colors.background
- },
- isCustomSyncInterval && {
- borderColor: colors.primary,
- backgroundColor: colors.primary + "20"
- },
- pressed && { opacity: 0.7 }
- ]}
- onPress={() => {
- if (!isCustomSyncInterval) {
- const customValue = 1800
- setSyncIntervalInput(customValue.toString())
- handleGridSelect("syncInterval", customValue)
- }
- }}
+ </View>
+ </View>
+
+ {isCustomSyncInterval && (
+ <View style={styles.customSyncInput}>
+ <NumericInput
+ label="Custom Sync Interval"
+ value={syncIntervalInput}
+ onChange={(val) => {
+ setSyncIntervalInput(val)
+ const num = Number(val)
+ if (!isNaN(num) && num >= 1) {
+ const next = { ...settings, syncInterval: num, syncPreset: "custom" as const }
+ onDebouncedSave(next)
+ }
+ }}
+ onBlur={() => {
+ let val = Number(syncIntervalInput)
+ if (isNaN(val) || val < 1) {
+ val = 1
+ setSyncIntervalInput("1")
+ const next = { ...settings, syncInterval: val, syncPreset: "custom" as const }
+ onSettingsChange(next)
+ onImmediateSave(next)
+ }
+ }}
+ unit="seconds"
+ placeholder="1800"
+ hint="Custom interval in seconds"
+ colors={colors}
+ />
+ </View>
+ )}
+
+ {/* Retry Forever Toggle */}
+ <SettingRow
+ label="Retry Failed Uploads"
+ hint={
+ settings.maxRetries === 0
+ ? "Failed uploads stay in the queue until they succeed"
+ : "Failed uploads are permanently deleted after 5 failed send attempts"
+ }
>
- <Text style={[styles.gridLabel, { color: isCustomSyncInterval ? colors.primary : colors.text }]}>
- Custom
- </Text>
- </Pressable>
- </View>
- </View>
-
- {isCustomSyncInterval && (
- <View style={styles.customSyncInput}>
- <NumericInput
- label="Custom Sync Interval"
- value={syncIntervalInput}
- onChange={(val) => {
- setSyncIntervalInput(val)
- const num = Number(val)
- if (!isNaN(num) && num >= 1) {
- const next = { ...settings, syncInterval: num, syncPreset: "custom" as const }
- onDebouncedSave(next)
- }
- }}
- onBlur={() => {
- let val = Number(syncIntervalInput)
- if (isNaN(val) || val < 1) {
- val = 1
- setSyncIntervalInput("1")
- const next = { ...settings, syncInterval: val, syncPreset: "custom" as const }
+ <Switch
+ value={settings.maxRetries === 0}
+ onValueChange={(retryForever) => {
+ const next = {
+ ...settings,
+ maxRetries: retryForever ? 0 : 5,
+ syncPreset: "custom" as const
+ }
onSettingsChange(next)
onImmediateSave(next)
- }
- }}
- unit="seconds"
- placeholder="1800"
- hint="Custom interval in seconds"
- colors={colors}
- />
+ }}
+ trackColor={{
+ false: colors.border,
+ true: colors.primary + "80"
+ }}
+ thumbColor={settings.maxRetries === 0 ? colors.primary : colors.border}
+ />
+ </SettingRow>
+
+ {/* Wi-Fi Only Sync Toggle */}
+ <SettingRow
+ label="Wi-Fi Only Sync"
+ hint="Only upload when connected to Wi-Fi"
+ style={styles.settingRowSpaced}
+ >
+ <Switch
+ value={settings.isWifiOnlySync}
+ onValueChange={(value) => {
+ const next = {
+ ...settings,
+ isWifiOnlySync: value,
+ syncPreset: "custom" as const
+ }
+ onSettingsChange(next)
+ onImmediateSave(next)
+ }}
+ trackColor={{
+ false: colors.border,
+ true: colors.primary + "80"
+ }}
+ thumbColor={settings.isWifiOnlySync ? colors.primary : colors.border}
+ />
+ </SettingRow>
</View>
- )}
-
- {/* Retry Forever Toggle */}
- <SettingRow
- label="Retry Failed Uploads"
- hint={
- settings.maxRetries === 0
- ? "Failed uploads stay in the queue until they succeed"
- : "Failed uploads are permanently deleted after 5 failed send attempts"
- }
- >
- <Switch
- value={settings.maxRetries === 0}
- onValueChange={(retryForever) => {
- const next = {
- ...settings,
- maxRetries: retryForever ? 0 : 5,
- syncPreset: "custom" as const
- }
- onSettingsChange(next)
- onImmediateSave(next)
- }}
- trackColor={{
- false: colors.border,
- true: colors.primary + "80"
- }}
- thumbColor={settings.maxRetries === 0 ? colors.primary : colors.border}
- />
- </SettingRow>
-
- {/* Wi-Fi Only Sync Toggle */}
- <SettingRow
- label="Wi-Fi Only Sync"
- hint="Only upload when connected to Wi-Fi"
- style={styles.settingRowSpaced}
- >
- <Switch
- value={settings.isWifiOnlySync}
- onValueChange={(value) => {
- const next = {
- ...settings,
- isWifiOnlySync: value,
- syncPreset: "custom" as const
- }
- onSettingsChange(next)
- onImmediateSave(next)
- }}
- trackColor={{
- false: colors.border,
- true: colors.primary + "80"
- }}
- thumbColor={settings.isWifiOnlySync ? colors.primary : colors.border}
- />
- </SettingRow>
- </View>
- <Divider />
+ <Divider />
+ </>
+ )}
{/* Quality Parameters Group */}
<View style={styles.paramGroup}>
diff --git a/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx
new file mode 100644
index 00000000..04d40872
--- /dev/null
+++ b/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx
@@ -0,0 +1,313 @@
+import React from "react"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { DEFAULT_SETTINGS, Settings } from "../../../../types/global"
+
+jest.mock("../../../index", () => {
+ const R = require("react")
+ const { View, Text, Pressable } = require("react-native")
+ return {
+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
+ Card: ({ children }: any) => R.createElement(View, null, children),
+ Divider: () => R.createElement(View, null),
+ Button: ({ title, onPress, disabled }: any) =>
+ R.createElement(Pressable, { onPress, disabled }, R.createElement(Text, null, title)),
+ SettingRow: ({ label, hint, children }: any) =>
+ R.createElement(
+ View,
+ null,
+ R.createElement(Text, null, label),
+ hint && R.createElement(Text, null, hint),
+ children
+ )
+ }
+})
+
+jest.mock("../../../ui/SettingRow", () => {
+ const R = require("react")
+ const { View, Text } = require("react-native")
+ return {
+ SettingRow: ({ label, hint, children }: any) =>
+ R.createElement(
+ View,
+ null,
+ R.createElement(Text, null, label),
+ hint && R.createElement(Text, null, hint),
+ children
+ )
+ }
+})
+
+jest.mock("lucide-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ CheckCircle: () => R.createElement(View, null),
+ ChevronRight: () => R.createElement(View, null)
+ }
+})
+
+const mockGetStats = jest.fn().mockResolvedValue({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0 })
+const mockManualFlush = jest.fn().mockResolvedValue(undefined)
+const mockClearQueue = jest.fn().mockResolvedValue(5)
+const mockGetMostRecentLocation = jest.fn().mockResolvedValue(null)
+const mockGetAuthHeaders = jest.fn().mockResolvedValue({})
+const mockIsNetworkAvailable = jest.fn().mockResolvedValue(true)
+
+jest.mock("../../../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: {
+ getStats: (...args: any[]) => mockGetStats(...args),
+ manualFlush: (...args: any[]) => mockManualFlush(...args),
+ clearQueue: (...args: any[]) => mockClearQueue(...args),
+ getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args),
+ getAuthHeaders: (...args: any[]) => mockGetAuthHeaders(...args),
+ isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args)
+ }
+}))
+
+const mockShowChoice = jest.fn().mockResolvedValue(0)
+jest.mock("../../../../services/modalService", () => ({
+ showChoice: (...args: any[]) => mockShowChoice(...args)
+}))
+
+jest.mock("../../../../utils/settingsValidation", () => ({
+ isPrivateHost: () => false,
+ isEndpointAllowed: () => true
+}))
+
+jest.mock("../../../../services/LocationServicePermission", () => ({
+ ensureLocalNetworkPermission: jest.fn().mockResolvedValue(true)
+}))
+
+jest.mock("../../../../hooks/useTimeout", () => ({
+ useTimeout: () => ({ set: jest.fn(), clear: jest.fn() })
+}))
+
+jest.mock("../../../../utils/logger", () => ({
+ logger: { warn: jest.fn(), error: jest.fn() }
+}))
+
+import { ConnectionSettings } from "../ConnectionSettings"
+
+const mockColors = {
+ primary: "#0d9488",
+ primaryDark: "#115E59",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ background: "#fff",
+ border: "#e5e7eb",
+ success: "#22c55e",
+ warning: "#f59e0b",
+ error: "#ef4444",
+ placeholder: "#9ca3af",
+ card: "#fff"
+} as any
+
+const mockNavigation = { navigate: jest.fn() }
+
+describe("ConnectionSettings", () => {
+ let mockOnSettingsChange: jest.Mock
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockOnSettingsChange = jest.fn()
+ })
+
+ function renderComponent(overrides?: Partial<Settings>, endpointInput = "https://example.com/api/locations") {
+ const settings = { ...DEFAULT_SETTINGS, ...overrides }
+ return render(
+ <ConnectionSettings
+ settings={settings}
+ endpointInput={endpointInput}
+ onEndpointInputChange={jest.fn()}
+ onSettingsChange={mockOnSettingsChange}
+ colors={mockColors}
+ navigation={mockNavigation}
+ />
+ )
+ }
+
+ it("renders Connection section title", () => {
+ const { getByText } = renderComponent()
+
+ expect(getByText("Connection")).toBeTruthy()
+ })
+
+ it("shows Offline Mode toggle", () => {
+ const { getByText } = renderComponent()
+
+ expect(getByText("Offline Mode")).toBeTruthy()
+ expect(getByText("Save locally, no network sync")).toBeTruthy()
+ })
+
+ describe("online mode", () => {
+ it("shows Server Endpoint input", () => {
+ const { getByText } = renderComponent()
+
+ expect(getByText("Server Endpoint")).toBeTruthy()
+ })
+
+ it("shows Test Connection button", () => {
+ const { getByText } = renderComponent()
+
+ expect(getByText("Test Connection")).toBeTruthy()
+ })
+
+ it("shows Authentication & Headers link", () => {
+ const { getByText } = renderComponent()
+
+ expect(getByText("Authentication & Headers")).toBeTruthy()
+ })
+
+ it("shows HTTPS badge for https endpoint", () => {
+ const { getByText } = renderComponent({}, "https://example.com/api/locations")
+
+ expect(getByText("HTTPS")).toBeTruthy()
+ })
+
+ it("shows HTTP badge for http endpoint", () => {
+ const { getByText } = renderComponent({}, "http://192.168.1.1/api/locations")
+
+ expect(getByText("HTTP")).toBeTruthy()
+ })
+ })
+
+ describe("offline mode", () => {
+ it("hides Server Endpoint input", () => {
+ const { queryByText } = renderComponent({ isOfflineMode: true })
+
+ expect(queryByText("Server Endpoint")).toBeNull()
+ })
+
+ it("hides Test Connection button", () => {
+ const { queryByText } = renderComponent({ isOfflineMode: true })
+
+ expect(queryByText("Test Connection")).toBeNull()
+ })
+
+ it("hides Authentication & Headers link", () => {
+ const { queryByText } = renderComponent({ isOfflineMode: true })
+
+ expect(queryByText("Authentication & Headers")).toBeNull()
+ })
+ })
+
+ describe("offline mode toggle with queue", () => {
+ it("enables offline mode directly when queue is empty", async () => {
+ mockGetStats.mockResolvedValue({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0 })
+ const { getAllByRole } = renderComponent()
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", true)
+
+ await waitFor(() => {
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
+ })
+ })
+
+ it("shows choice dialog when queue has items", async () => {
+ mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
+ mockShowChoice.mockResolvedValue(3) // Cancel
+ const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", true)
+
+ await waitFor(() => {
+ expect(mockShowChoice).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Unsent Locations",
+ message: expect.stringContaining("10 locations")
+ })
+ )
+ })
+ })
+
+ it("syncs first then enables offline when Sync First chosen", async () => {
+ mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
+ mockShowChoice.mockResolvedValue(0) // Sync First (with endpoint)
+ const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", true)
+
+ await waitFor(() => {
+ expect(mockManualFlush).toHaveBeenCalled()
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
+ })
+ })
+
+ it("keeps queue and enables offline when Keep chosen", async () => {
+ mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
+ mockShowChoice.mockResolvedValue(1) // Keep in Queue (with endpoint)
+ const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", true)
+
+ await waitFor(() => {
+ expect(mockManualFlush).not.toHaveBeenCalled()
+ expect(mockClearQueue).not.toHaveBeenCalled()
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
+ })
+ })
+
+ it("deletes queue and enables offline when Delete chosen", async () => {
+ mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
+ mockShowChoice.mockResolvedValue(2) // Delete Queue (with endpoint)
+ const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", true)
+
+ await waitFor(() => {
+ expect(mockClearQueue).toHaveBeenCalled()
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
+ })
+ })
+
+ it("does not enable offline when Cancel chosen", async () => {
+ mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
+ mockShowChoice.mockResolvedValue(3) // Cancel (with endpoint)
+ const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", true)
+
+ await waitFor(() => {
+ expect(mockShowChoice).toHaveBeenCalled()
+ })
+ expect(mockOnSettingsChange).not.toHaveBeenCalled()
+ })
+
+ it("disables offline mode directly without dialog", async () => {
+ const { getAllByRole } = renderComponent({ isOfflineMode: true })
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", false)
+
+ await waitFor(() => {
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: false }))
+ })
+ expect(mockShowChoice).not.toHaveBeenCalled()
+ })
+
+ it("omits Sync First button when no endpoint configured", async () => {
+ mockGetStats.mockResolvedValue({ queued: 5, sent: 0, total: 5, today: 5, databaseSizeMB: 0.1 })
+ mockShowChoice.mockResolvedValue(0) // Keep in Queue (no endpoint, so index 0 = keep)
+ const { getAllByRole } = renderComponent({ endpoint: "" }, "")
+
+ const toggle = getAllByRole("switch")[0]
+ fireEvent(toggle, "valueChange", true)
+
+ await waitFor(() => {
+ expect(mockShowChoice).toHaveBeenCalledWith(
+ expect.objectContaining({
+ buttons: expect.not.arrayContaining([expect.objectContaining({ text: "Sync First" })])
+ })
+ )
+ })
+ })
+ })
+})
diff --git a/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx b/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx
new file mode 100644
index 00000000..edfd0f20
--- /dev/null
+++ b/apps/mobile/src/components/features/settings/__tests__/PresetOption.test.tsx
@@ -0,0 +1,100 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { TRACKING_PRESETS } from "../../../../types/global"
+
+let mockSettings = { isOfflineMode: false }
+
+jest.mock("../../../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: mockSettings
+ })
+}))
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ primaryDark: "#115E59",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ success: "#22c55e",
+ warning: "#f59e0b",
+ border: "#e5e7eb"
+ }
+ })
+}))
+
+jest.mock("../../../ui/RadioDot", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ RadioDot: ({ selected }: any) => R.createElement(View, { testID: selected ? "radio-selected" : "radio-unselected" })
+ }
+})
+
+jest.mock("lucide-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ Zap: () => R.createElement(View, null),
+ Check: () => R.createElement(View, null)
+ }
+})
+
+import { PresetOption } from "../PresetOption"
+
+describe("PresetOption", () => {
+ const mockOnSelect = jest.fn()
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockSettings = { isOfflineMode: false }
+ })
+
+ it("renders preset label and description", () => {
+ const { getByText } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+
+ expect(getByText(TRACKING_PRESETS.balanced.label)).toBeTruthy()
+ expect(getByText(TRACKING_PRESETS.balanced.description)).toBeTruthy()
+ })
+
+ it("shows offline description when isOfflineMode is true", () => {
+ mockSettings = { isOfflineMode: true }
+ const { getByText } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+
+ expect(getByText(TRACKING_PRESETS.balanced.description.split(" • ")[0])).toBeTruthy()
+ })
+
+ it("calls onSelect with preset when pressed", () => {
+ const { getByRole } = render(<PresetOption preset="instant" isSelected={false} onSelect={mockOnSelect} />)
+
+ fireEvent.press(getByRole("radio"))
+
+ expect(mockOnSelect).toHaveBeenCalledWith("instant")
+ })
+
+ it("shows selected radio dot when isSelected", () => {
+ const { getByTestId } = render(<PresetOption preset="balanced" isSelected onSelect={mockOnSelect} />)
+
+ expect(getByTestId("radio-selected")).toBeTruthy()
+ })
+
+ it("shows unselected radio dot when not selected", () => {
+ const { getByTestId } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+
+ expect(getByTestId("radio-unselected")).toBeTruthy()
+ })
+
+ it("shows Recommended badge for balanced preset", () => {
+ const { getByText } = render(<PresetOption preset="balanced" isSelected={false} onSelect={mockOnSelect} />)
+
+ expect(getByText("Recommended")).toBeTruthy()
+ })
+
+ it("shows High Battery Usage badge for instant preset", () => {
+ const { getByText } = render(<PresetOption preset="instant" isSelected={false} onSelect={mockOnSelect} />)
+
+ expect(getByText("High Battery Usage")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/features/settings/__tests__/StatsCard.test.tsx b/apps/mobile/src/components/features/settings/__tests__/StatsCard.test.tsx
new file mode 100644
index 00000000..f108ef16
--- /dev/null
+++ b/apps/mobile/src/components/features/settings/__tests__/StatsCard.test.tsx
@@ -0,0 +1,128 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+
+let mockSettings = { isOfflineMode: false }
+
+jest.mock("../../../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: mockSettings
+ })
+}))
+
+jest.mock("../../../../utils/queueStatus", () => ({
+ getQueueColor: () => "#000"
+}))
+
+jest.mock("lucide-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ AlertTriangle: () => R.createElement(View, null),
+ ChevronRight: () => R.createElement(View, null)
+ }
+})
+
+import { StatsCard } from "../StatsCard"
+
+const mockColors = {
+ primary: "#0d9488",
+ text: "#000",
+ textSecondary: "#6b7280",
+ success: "#22c55e",
+ warning: "#f59e0b",
+ error: "#ef4444",
+ info: "#3b82f6",
+ card: "#fff",
+ border: "#e5e7eb"
+} as any
+
+const baseProps = {
+ queueCount: 5,
+ sentCount: 100,
+ todayCount: 8,
+ interval: "30",
+ colors: mockColors
+}
+
+describe("StatsCard", () => {
+ beforeEach(() => {
+ mockSettings = { isOfflineMode: false }
+ })
+
+ describe("online mode", () => {
+ it("shows Queued, Sent, and Interval stats", () => {
+ const { getByText } = render(<StatsCard {...baseProps} />)
+
+ expect(getByText("Queued")).toBeTruthy()
+ expect(getByText("5")).toBeTruthy()
+ expect(getByText("Sent")).toBeTruthy()
+ expect(getByText("100")).toBeTruthy()
+ expect(getByText("Interval")).toBeTruthy()
+ })
+
+ it("does not show Today stat", () => {
+ const { queryByText } = render(<StatsCard {...baseProps} />)
+
+ expect(queryByText("Today")).toBeNull()
+ })
+
+ it("shows warning banner when queue is high", () => {
+ const onManage = jest.fn()
+ const { getByText } = render(<StatsCard {...baseProps} queueCount={75} onManageClick={onManage} />)
+
+ expect(getByText("High Queue Size")).toBeTruthy()
+ expect(getByText("Tap to manage data")).toBeTruthy()
+ })
+
+ it("shows critical warning when queue is very high", () => {
+ const onManage = jest.fn()
+ const { getByText } = render(<StatsCard {...baseProps} queueCount={200} onManageClick={onManage} />)
+
+ expect(getByText("Critical Queue Size")).toBeTruthy()
+ })
+
+ it("calls onManageClick when warning banner is pressed", () => {
+ const onManage = jest.fn()
+ const { getByText } = render(<StatsCard {...baseProps} queueCount={75} onManageClick={onManage} />)
+
+ fireEvent.press(getByText("Tap to manage data"))
+
+ expect(onManage).toHaveBeenCalledTimes(1)
+ })
+ })
+
+ describe("offline mode", () => {
+ beforeEach(() => {
+ mockSettings = { isOfflineMode: true }
+ })
+
+ it("shows Today and Interval instead of Queued/Sent", () => {
+ const { getByText } = render(<StatsCard {...baseProps} />)
+
+ expect(getByText("Today")).toBeTruthy()
+ expect(getByText("8")).toBeTruthy()
+ expect(getByText("Interval")).toBeTruthy()
+ })
+
+ it("hides Queued and Sent stats", () => {
+ const { queryByText } = render(<StatsCard {...baseProps} />)
+
+ expect(queryByText("Queued")).toBeNull()
+ expect(queryByText("Sent")).toBeNull()
+ })
+
+ it("hides warning banner even with high queue count", () => {
+ const onManage = jest.fn()
+ const { queryByText } = render(<StatsCard {...baseProps} queueCount={200} onManageClick={onManage} />)
+
+ expect(queryByText("High Queue Size")).toBeNull()
+ expect(queryByText("Critical Queue Size")).toBeNull()
+ })
+ })
+
+ it("shows interval with seconds unit", () => {
+ const { getByText } = render(<StatsCard {...baseProps} interval="15" />)
+
+ expect(getByText("s")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
index f23cadfb..5892d210 100644
--- a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
+++ b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
@@ -130,6 +130,20 @@ describe("SyncStrategySettings", () => {
})
)
})
+
+ it("selecting a preset in offline mode skips sync fields", () => {
+ const { getByTestId } = renderComponent({ isOfflineMode: true })
+
+ fireEvent.press(getByTestId("preset-balanced"))
+
+ const savedSettings = mockOnImmediateSave.mock.calls[0][0]
+ expect(savedSettings.syncPreset).toBe("balanced")
+ expect(savedSettings.interval).toBe(TRACKING_PRESETS.balanced.interval)
+ expect(savedSettings.distance).toBe(TRACKING_PRESETS.balanced.distance)
+ // syncInterval and retryInterval should NOT be overwritten in offline mode
+ expect(savedSettings.syncInterval).toBe(DEFAULT_SETTINGS.syncInterval)
+ expect(savedSettings.retryInterval).toBe(DEFAULT_SETTINGS.retryInterval)
+ })
})
describe("advanced toggle", () => {
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index 2051efb7..cdb2bd9f 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -37,7 +37,7 @@ export { SettingRow } from "./ui/SettingRow"
export { DashboardMap } from "./features/dashboard/DashboardMap"
export { CoordinateDisplay } from "./features/dashboard/CoordinateDisplay"
export { QuickAccess } from "./features/dashboard/QuickAccess"
-export { ServerConnection } from "./features/dashboard/ServerConnection"
+export { ConnectionStatus } from "./features/dashboard/ConnectionStatus"
export { WelcomeCard } from "./features/dashboard/WelcomeCard"
export { DatabaseStatistics } from "./features/dashboard/DatabaseStatistics"
diff --git a/apps/mobile/src/components/ui/AppModal.tsx b/apps/mobile/src/components/ui/AppModal.tsx
index ac94e58c..c82667a9 100644
--- a/apps/mobile/src/components/ui/AppModal.tsx
+++ b/apps/mobile/src/components/ui/AppModal.tsx
@@ -71,13 +71,18 @@ export function AppModal() {
<Text style={[styles.title, { color: colors.text }]}>{current.title}</Text>
<Text style={[styles.body, { color: colors.textSecondary }]}>{current.message}</Text>
- <View style={styles.buttons}>
+ <View style={[styles.buttons, current.buttons.length > 2 && styles.buttonsVertical]}>
{current.buttons.map((btn, i) => {
const btnStyles = getButtonStyles(btn.style, colors)
return (
<Pressable
key={i}
- style={({ pressed }) => [styles.button, btnStyles.container, pressed && { opacity: 0.7 }]}
+ style={({ pressed }) => [
+ styles.button,
+ current.buttons.length > 2 && styles.buttonFullWidth,
+ btnStyles.container,
+ pressed && { opacity: 0.7 }
+ ]}
onPress={() => handlePress(i)}
>
<Text style={[styles.buttonText, btnStyles.text]}>{btn.text}</Text>
@@ -169,6 +174,12 @@ const styles = StyleSheet.create({
gap: 12,
marginTop: 24
},
+ buttonsVertical: {
+ flexDirection: "column"
+ },
+ buttonFullWidth: {
+ flex: 0
+ },
button: {
flex: 1,
paddingVertical: 14,
diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsx
index cef01144..d2d14bc7 100644
--- a/apps/mobile/src/screens/DashboardScreen.tsx
+++ b/apps/mobile/src/screens/DashboardScreen.tsx
@@ -12,7 +12,7 @@ import { useTracking, useCoords } from "../contexts/TrackingProvider"
import { useFocusEffect } from "@react-navigation/native"
import {
Button,
- ServerConnection,
+ ConnectionStatus,
DashboardMap,
CoordinateDisplay,
Container,
@@ -207,7 +207,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {
<DatabaseStatistics stats={stats} />
{/* Server Connection */}
- <ServerConnection endpoint={settings.endpoint} navigation={navigation} />
+ {!settings.isOfflineMode && <ConnectionStatus endpoint={settings.endpoint} navigation={navigation} />}
{/* Quick Access */}
<QuickAccess navigation={navigation} />
diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsx
index c2bf0f3d..37ddcd22 100644
--- a/apps/mobile/src/screens/DataManagementScreen.tsx
+++ b/apps/mobile/src/screens/DataManagementScreen.tsx
@@ -22,6 +22,7 @@ import { ScreenProps, DatabaseStats } from "../types/global"
import { useTheme } from "../hooks/useTheme"
import { fonts, fontSizes } from "../styles/typography"
import NativeLocationService from "../services/NativeLocationService"
+import { useTracking } from "../contexts/TrackingProvider"
import { Button, SectionTitle, Card, Container, Divider, FloatingSaveIndicator } from "../components"
import { STATS_REFRESH_FAST, SAVE_SUCCESS_DISPLAY_MS } from "../constants"
import { useTimeout } from "../hooks/useTimeout"
@@ -30,6 +31,8 @@ import { logger } from "../utils/logger"
export function DataManagementScreen({}: ScreenProps) {
const { colors } = useTheme()
+ const { settings } = useTracking()
+ const isOfflineMode = settings.isOfflineMode
const [stats, setStats] = useState<DatabaseStats>({
queued: 0,
@@ -185,6 +188,21 @@ export function DataManagementScreen({}: ScreenProps) {
)
}, [handleDeleteAction, stats.queued])
+ const handleDeleteAllLocations = useCallback(async () => {
+ const confirmed = await showConfirm({
+ title: "Delete All Locations",
+ message: `Delete all ${stats.total} stored location${stats.total !== 1 ? "s" : ""}? This cannot be undone.`,
+ confirmText: "Delete All",
+ destructive: true
+ })
+ if (!confirmed) return
+
+ handleDeleteAction(
+ () => NativeLocationService.clearAllLocations(),
+ (count) => `Deleted ${count} location${count !== 1 ? "s" : ""}`
+ )
+ }, [handleDeleteAction, stats.total])
+
const handleDeleteOlderThan = useCallback(async () => {
const days = parseInt(daysInput, 10)
if (isNaN(days) || days <= 0) {
@@ -263,8 +281,12 @@ export function DataManagementScreen({}: ScreenProps) {
<Card>
{[
["Total Locations", stats.total.toLocaleString(), colors.text],
- ["Sent", stats.sent.toLocaleString(), colors.success],
- ["Queued", stats.queued.toLocaleString(), colors.warning],
+ ...(!isOfflineMode
+ ? [
+ ["Sent", stats.sent.toLocaleString(), colors.success],
+ ["Queued", stats.queued.toLocaleString(), colors.warning]
+ ]
+ : []),
["Today", stats.today.toLocaleString(), colors.info],
["Storage", `${stats.databaseSizeMB.toFixed(2)} MB`, colors.primary]
].map(([label, value, color], i, arr) => (
@@ -280,45 +302,65 @@ export function DataManagementScreen({}: ScreenProps) {
</View>
{/* Queue Actions */}
- <View style={styles.section}>
- <SectionTitle>QUEUE ACTIONS</SectionTitle>
- <Card>
- <Button onPress={handleManualFlush} disabled={isProcessing || stats.queued === 0} title="Sync Now" />
- <Text style={[styles.hint, { color: colors.textLight }]}>
- {stats.queued === 0
- ? "Queue is empty"
- : `Trigger immediate sync of ${stats.queued} queued location${stats.queued !== 1 ? "s" : ""}`}
- </Text>
- </Card>
- </View>
+ {!isOfflineMode && (
+ <View style={styles.section}>
+ <SectionTitle>QUEUE ACTIONS</SectionTitle>
+ <Card>
+ <Button onPress={handleManualFlush} disabled={isProcessing || stats.queued === 0} title="Sync Now" />
+ <Text style={[styles.hint, { color: colors.textLight }]}>
+ {stats.queued === 0
+ ? "Queue is empty"
+ : `Trigger immediate sync of ${stats.queued} queued location${stats.queued !== 1 ? "s" : ""}`}
+ </Text>
+ </Card>
+ </View>
+ )}
{/* Cleanup Actions */}
<View style={styles.section}>
<SectionTitle>CLEANUP ACTIONS</SectionTitle>
<Card>
- {/* Clear Sent History */}
- <ActionRow
- label="Clear Sent History"
- hint="Delete all successfully sent locations"
- color={colors.success}
- textColor={colors.textLight}
- value={stats.sent.toLocaleString()}
- onPress={handleClearSentHistory}
- disabled={isProcessing || stats.sent === 0}
- />
- <Divider />
-
- {/* Clear Queue */}
- <ActionRow
- label="Clear Queue"
- hint="Delete all pending locations"
- color={colors.warning}
- textColor={colors.textLight}
- value={stats.queued.toLocaleString()}
- onPress={handleClearQueue}
- disabled={isProcessing || stats.queued === 0}
- />
- <Divider />
+ {!isOfflineMode ? (
+ <>
+ {/* Clear Sent History */}
+ <ActionRow
+ label="Clear Sent History"
+ hint="Delete all successfully sent locations"
+ color={colors.success}
+ textColor={colors.textLight}
+ value={stats.sent.toLocaleString()}
+ onPress={handleClearSentHistory}
+ disabled={isProcessing || stats.sent === 0}
+ />
+ <Divider />
+
+ {/* Clear Queue */}
+ <ActionRow
+ label="Clear Queue"
+ hint="Delete all pending locations"
+ color={colors.warning}
+ textColor={colors.textLight}
+ value={stats.queued.toLocaleString()}
+ onPress={handleClearQueue}
+ disabled={isProcessing || stats.queued === 0}
+ />
+ <Divider />
+ </>
+ ) : (
+ <>
+ {/* Delete All Locations (offline mode) */}
+ <ActionRow
+ label="Delete All Locations"
+ hint="Remove all stored locations from the database"
+ color={colors.error}
+ textColor={colors.textLight}
+ value={stats.total.toLocaleString()}
+ onPress={handleDeleteAllLocations}
+ disabled={isProcessing || stats.total === 0}
+ />
+ <Divider />
+ </>
+ )}
{/* Delete Older Than */}
<View style={styles.actionColumn}>
diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsx
index ee578023..f496010f 100644
--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx
+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx
@@ -6,6 +6,7 @@
import React, { useState, useEffect, useCallback } from "react"
import { View, Text, StyleSheet, ScrollView, TextInput, Pressable } from "react-native"
import { useTheme } from "../hooks/useTheme"
+import { useTracking } from "../contexts/TrackingProvider"
import { ProfileService } from "../services/ProfileService"
import { showAlert } from "../services/modalService"
import { TrackingProfile, ProfileConditionType } from "../types/global"
@@ -29,6 +30,7 @@ const DEFAULT_PROFILE: Omit<TrackingProfile, "id" | "createdAt"> = {
export function ProfileEditorScreen({ navigation, route }: any) {
const { colors } = useTheme()
+ const { settings } = useTracking()
const profileId = route?.params?.profileId as number | undefined
const isEditing = !!profileId
@@ -279,79 +281,86 @@ export function ProfileEditorScreen({ navigation, route }: any) {
</View>
</SettingRow>
- <Divider />
+ {!settings.isOfflineMode && (
+ <>
+ <Divider />
- <Text style={[styles.syncLabel, { color: colors.textSecondary }]}>Sync Interval</Text>
- <View style={styles.syncGrid}>
- {SYNC_INTERVAL_PRESETS.map((sec) => {
- const isSelected = profile.syncInterval === sec && SYNC_INTERVAL_PRESETS.includes(profile.syncInterval)
- return (
+ <Text style={[styles.syncLabel, { color: colors.textSecondary }]}>Sync Interval</Text>
+ <View style={styles.syncGrid}>
+ {SYNC_INTERVAL_PRESETS.map((sec) => {
+ const isSelected =
+ profile.syncInterval === sec && SYNC_INTERVAL_PRESETS.includes(profile.syncInterval)
+ return (
+ <Pressable
+ key={sec}
+ style={({ pressed }) => [
+ styles.syncOption,
+ {
+ backgroundColor: isSelected ? colors.primary + "15" : colors.background,
+ borderColor: isSelected ? colors.primary : colors.border
+ },
+ pressed && { opacity: 0.7 }
+ ]}
+ onPress={() => setProfile((prev) => ({ ...prev, syncInterval: sec }))}
+ >
+ <Text style={[styles.syncOptionLabel, { color: isSelected ? colors.primary : colors.text }]}>
+ {SYNC_INTERVAL_LABELS[sec]}
+ </Text>
+ </Pressable>
+ )
+ })}
<Pressable
- key={sec}
style={({ pressed }) => [
styles.syncOption,
{
- backgroundColor: isSelected ? colors.primary + "15" : colors.background,
- borderColor: isSelected ? colors.primary : colors.border
+ backgroundColor: isCustomSyncInterval ? colors.primary + "15" : colors.background,
+ borderColor: isCustomSyncInterval ? colors.primary : colors.border
},
pressed && { opacity: 0.7 }
]}
- onPress={() => setProfile((prev) => ({ ...prev, syncInterval: sec }))}
+ onPress={() => {
+ if (!isCustomSyncInterval) {
+ const customValue = 1800
+ setSyncIntervalStr(customValue.toString())
+ setProfile((prev) => ({ ...prev, syncInterval: customValue }))
+ }
+ }}
>
- <Text style={[styles.syncOptionLabel, { color: isSelected ? colors.primary : colors.text }]}>
- {SYNC_INTERVAL_LABELS[sec]}
+ <Text
+ style={[styles.syncOptionLabel, { color: isCustomSyncInterval ? colors.primary : colors.text }]}
+ >
+ Custom
</Text>
</Pressable>
- )
- })}
- <Pressable
- style={({ pressed }) => [
- styles.syncOption,
- {
- backgroundColor: isCustomSyncInterval ? colors.primary + "15" : colors.background,
- borderColor: isCustomSyncInterval ? colors.primary : colors.border
- },
- pressed && { opacity: 0.7 }
- ]}
- onPress={() => {
- if (!isCustomSyncInterval) {
- const customValue = 1800
- setSyncIntervalStr(customValue.toString())
- setProfile((prev) => ({ ...prev, syncInterval: customValue }))
- }
- }}
- >
- <Text style={[styles.syncOptionLabel, { color: isCustomSyncInterval ? colors.primary : colors.text }]}>
- Custom
- </Text>
- </Pressable>
- </View>
+ </View>
- {isCustomSyncInterval && (
- <View style={styles.customSyncInput}>
- <NumericInput
- label="Custom Sync Interval"
- value={syncIntervalStr}
- onChange={(val) => {
- setSyncIntervalStr(val)
- const num = Number(val)
- if (!isNaN(num) && num >= 0) {
- setProfile((prev) => ({ ...prev, syncInterval: num }))
- }
- }}
- onBlur={() => {
- const num = Number(syncIntervalStr)
- if (isNaN(num) || num < 0) {
- setSyncIntervalStr("0")
- setProfile((prev) => ({ ...prev, syncInterval: 0 }))
- }
- }}
- unit="seconds"
- placeholder="1800"
- hint="Custom interval in seconds"
- colors={colors}
- />
- </View>
+ {isCustomSyncInterval && (
+ <View style={styles.customSyncInput}>
+ <NumericInput
+ label="Custom Sync Interval"
+ value={syncIntervalStr}
+ onChange={(val) => {
+ setSyncIntervalStr(val)
+ const num = Number(val)
+ if (!isNaN(num) && num >= 0) {
+ setProfile((prev) => ({ ...prev, syncInterval: num }))
+ }
+ }}
+ onBlur={() => {
+ const num = Number(syncIntervalStr)
+ if (isNaN(num) || num < 0) {
+ setSyncIntervalStr("0")
+ setProfile((prev) => ({ ...prev, syncInterval: 0 }))
+ }
+ }}
+ unit="seconds"
+ placeholder="1800"
+ hint="Custom interval in seconds"
+ colors={colors}
+ />
+ </View>
+ )}
+ </>
)}
</Card>
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index ec5dbd0d..b03a851b 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -34,6 +34,7 @@ export function SettingsScreen({ navigation }: ScreenProps) {
// Stats
const [queueCount, setQueueCount] = useState(0)
const [sentCount, setSentCount] = useState(0)
+ const [todayCount, setTodayCount] = useState(0)
// Endpoint input (managed here since ConnectionSettings needs it and we sync with settings)
const [endpointInput, setEndpointInput] = useState(settings.endpoint || "")
@@ -83,6 +84,7 @@ export function SettingsScreen({ navigation }: ScreenProps) {
const stats = await NativeLocationService.getStats()
setQueueCount(stats.queued)
setSentCount(stats.sent)
+ setTodayCount(stats.today)
} catch (err) {
logger.error("[SettingsScreen] Failed to get stats:", err)
}
@@ -133,8 +135,8 @@ export function SettingsScreen({ navigation }: ScreenProps) {
<StatsCard
queueCount={queueCount}
sentCount={sentCount}
+ todayCount={todayCount}
interval={settings.interval.toString()}
- isOfflineMode={settings.isOfflineMode}
onManageClick={() => navigation.navigate("Data Management")}
colors={colors}
/>
@@ -234,18 +236,24 @@ export function SettingsScreen({ navigation }: ScreenProps) {
<ChevronRight size={20} color={colors.textLight} />
</Pressable>
- <Divider />
+ {!settings.isOfflineMode && (
+ <>
+ <Divider />
- <Pressable
- style={({ pressed }) => [styles.linkRow, pressed && { opacity: 0.6 }]}
- onPress={() => navigation.navigate("API Config")}
- >
- <View style={styles.linkContent}>
- <Text style={[styles.linkLabel, { color: colors.text }]}>API Field Mapping</Text>
- <Text style={[styles.linkSub, { color: colors.textSecondary }]}>Customize JSON payload structure</Text>
- </View>
- <ChevronRight size={20} color={colors.textLight} />
- </Pressable>
+ <Pressable
+ style={({ pressed }) => [styles.linkRow, pressed && { opacity: 0.6 }]}
+ onPress={() => navigation.navigate("API Config")}
+ >
+ <View style={styles.linkContent}>
+ <Text style={[styles.linkLabel, { color: colors.text }]}>API Field Mapping</Text>
+ <Text style={[styles.linkSub, { color: colors.textSecondary }]}>
+ Customize JSON payload structure
+ </Text>
+ </View>
+ <ChevronRight size={20} color={colors.textLight} />
+ </Pressable>
+ </>
+ )}
</Card>
</View>
</ScrollView>
diff --git a/apps/mobile/src/screens/TrackingProfilesScreen.tsx b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
index e6604888..27fdf004 100644
--- a/apps/mobile/src/screens/TrackingProfilesScreen.tsx
+++ b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
@@ -26,16 +26,18 @@ function formatCondition(profile: SavedTrackingProfile): string {
return label
}
-function formatSettings(profile: SavedTrackingProfile): string {
+function formatSettings(profile: SavedTrackingProfile, isOfflineMode?: boolean): 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`)
+ if (!isOfflineMode) {
+ parts.push(profile.syncInterval === 0 ? "instant sync" : `${profile.syncInterval}s sync`)
+ }
return parts.join(" \u2022 ")
}
export function TrackingProfilesScreen({ navigation }: ScreenProps) {
const { colors } = useTheme()
- const { activeProfileName } = useTracking()
+ const { settings, activeProfileName } = useTracking()
const [profiles, setProfiles] = useState<SavedTrackingProfile[]>([])
const loadProfiles = useCallback(async () => {
@@ -121,7 +123,9 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
</View>
</View>
<Text style={[styles.condition, { color: colors.textSecondary }]}>{formatCondition(item)}</Text>
- <Text style={[styles.settings, { color: colors.textLight }]}>{formatSettings(item)}</Text>
+ <Text style={[styles.settings, { color: colors.textLight }]}>
+ {formatSettings(item, settings.isOfflineMode)}
+ </Text>
</View>
<View style={styles.actions}>
@@ -149,7 +153,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
</Card>
)
},
- [colors, activeProfileName, toggleEnabled, handleDelete, navigation]
+ [colors, activeProfileName, settings.isOfflineMode, toggleEnabled, handleDelete, navigation]
)
return (
diff --git a/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx
index 3b309d33..0490136f 100644
--- a/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx
@@ -70,7 +70,7 @@ jest.mock("../../components", () => {
DashboardMap: () => R.createElement(View, { testID: "DashboardMap" }),
CoordinateDisplay: () => R.createElement(View, { testID: "CoordinateDisplay" }),
DatabaseStatistics: () => R.createElement(View, { testID: "DatabaseStatistics" }),
- ServerConnection: () => R.createElement(View, { testID: "ServerConnection" }),
+ ConnectionStatus: () => R.createElement(View, { testID: "ConnectionStatus" }),
QuickAccess: () => R.createElement(View, { testID: "QuickAccess" }),
WelcomeCard: () => R.createElement(View, { testID: "WelcomeCard" }),
Container: ({ children }: any) => R.createElement(View, null, children),
@@ -146,9 +146,25 @@ describe("DashboardScreen", () => {
expect(getByTestId("DatabaseStatistics")).toBeTruthy()
})
- it("renders ServerConnection component", () => {
+ it("renders ConnectionStatus component", () => {
const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)
- expect(getByTestId("ServerConnection")).toBeTruthy()
+ expect(getByTestId("ConnectionStatus")).toBeTruthy()
+ })
+
+ it("hides ConnectionStatus when offline mode is enabled", () => {
+ mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }
+
+ const { queryByTestId } = render(<DashboardScreen navigation={mockNavigation} />)
+
+ expect(queryByTestId("ConnectionStatus")).toBeNull()
+ })
+
+ it("still renders DatabaseStatistics when offline mode is enabled", () => {
+ mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }
+
+ const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)
+
+ expect(getByTestId("DatabaseStatistics")).toBeTruthy()
})
})
diff --git a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx
index 46ee6240..17905afc 100644
--- a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx
@@ -85,6 +85,13 @@ jest.mock("../../utils/logger", () => ({
logger: { error: jest.fn(), warn: jest.fn() }
}))
+let mockIsOfflineMode = false
+jest.mock("../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: { isOfflineMode: mockIsOfflineMode }
+ })
+}))
+
jest.mock("../../components", () => {
const R = require("react")
const RN = require("react-native")
@@ -147,6 +154,7 @@ import { DataManagementScreen } from "../DataManagementScreen"
describe("DataManagementScreen", () => {
beforeEach(() => {
jest.clearAllMocks()
+ mockIsOfflineMode = false
mockGetStats.mockResolvedValue({ queued: 5, sent: 100, total: 105, today: 3, databaseSizeMB: 1.5 })
mockGetSetting.mockResolvedValue("false")
mockShowConfirm.mockResolvedValue(true)
@@ -279,4 +287,90 @@ describe("DataManagementScreen", () => {
)
})
})
+
+ describe("offline mode", () => {
+ beforeEach(() => {
+ mockIsOfflineMode = true
+ })
+
+ it("hides Sent and Queued stats", async () => {
+ const { queryByText, getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Total Locations")).toBeTruthy()
+ })
+
+ expect(queryByText("Sent")).toBeNull()
+ expect(queryByText("Queued")).toBeNull()
+ })
+
+ it("hides Queue Actions section", async () => {
+ const { queryByText, getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Data Management")).toBeTruthy()
+ })
+
+ expect(queryByText("QUEUE ACTIONS")).toBeNull()
+ expect(queryByText("Sync Now")).toBeNull()
+ })
+
+ it("hides Clear Sent History and Clear Queue actions", async () => {
+ const { queryByText, getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Data Management")).toBeTruthy()
+ })
+
+ expect(queryByText("Clear Sent History")).toBeNull()
+ expect(queryByText("Clear Queue")).toBeNull()
+ })
+
+ it("still shows Delete Old Locations and Optimize Database", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Delete Old Locations")).toBeTruthy()
+ expect(getByText("Optimize Database")).toBeTruthy()
+ })
+ })
+
+ it("still shows Today and Storage stats", async () => {
+ const { getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Today")).toBeTruthy()
+ expect(getByText("Storage")).toBeTruthy()
+ })
+ })
+
+ it("shows Delete All Locations action with total count", async () => {
+ const { getByText, getAllByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("Delete All Locations")).toBeTruthy()
+ // "105" appears as Total Locations stat and as Delete All badge
+ expect(getAllByText("105").length).toBeGreaterThanOrEqual(2)
+ })
+ })
+
+ it("Delete All Locations shows confirmation dialog", async () => {
+ const { getByText, getAllByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getAllByText("105").length).toBeGreaterThanOrEqual(1)
+ })
+
+ fireEvent.press(getByText("Delete All Locations"))
+
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Delete All Locations",
+ destructive: true
+ })
+ )
+ })
+ })
+ })
})
diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
index ac32b116..16614fbe 100644
--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
@@ -36,6 +36,12 @@ jest.mock("../../services/modalService", () => ({
showAlert: (...args: any[]) => mockShowAlert(...args)
}))
+jest.mock("../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: { isOfflineMode: false }
+ })
+}))
+
jest.mock("../../hooks/useTheme", () => ({
useTheme: () => ({
colors: {
diff --git a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
index 9b83914d..535fa1e5 100644
--- a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
@@ -52,7 +52,10 @@ jest.mock("../../services/modalService", () => ({
let mockActiveProfileName: string | null = null
jest.mock("../../contexts/TrackingProvider", () => ({
- useTracking: () => ({ activeProfileName: mockActiveProfileName })
+ useTracking: () => ({
+ activeProfileName: mockActiveProfileName,
+ settings: { isOfflineMode: false }
+ })
}))
jest.mock("../../hooks/useTheme", () => ({
diff --git a/apps/mobile/src/services/modalService.ts b/apps/mobile/src/services/modalService.ts
index 7fe1da10..d32ba3d5 100644
--- a/apps/mobile/src/services/modalService.ts
+++ b/apps/mobile/src/services/modalService.ts
@@ -41,6 +41,45 @@ export function showAlert(title: string, message: string, variant: AlertVariant
})
}
+export function showChoice(options: {
+ title: string
+ message: string
+ variant?: AlertVariant
+ buttons: Array<{
+ text: string
+ style?: "primary" | "secondary" | "destructive"
+ }>
+}): Promise<number> {
+ const { title, message, variant = "warning", buttons } = options
+
+ return new Promise((resolve) => {
+ if (!_handler) {
+ Alert.alert(
+ title,
+ message,
+ buttons.map((btn, i) => ({
+ text: btn.text,
+ style: btn.style === "destructive" ? "destructive" : btn.style === "secondary" ? "cancel" : "default",
+ onPress: () => resolve(i)
+ })),
+ { cancelable: false }
+ )
+ return
+ }
+
+ _handler({
+ title,
+ message,
+ variant,
+ buttons: buttons.map((btn) => ({
+ text: btn.text,
+ style: btn.style ?? "secondary"
+ })),
+ resolve: (index) => resolve(index)
+ })
+ })
+}
+
export function showConfirm(options: {
title: string
message: string
diff --git a/apps/mobile/src/types/__tests__/defaults.test.ts b/apps/mobile/src/types/__tests__/defaults.test.ts
index 7c1c2200..990f5cc5 100644
--- a/apps/mobile/src/types/__tests__/defaults.test.ts
+++ b/apps/mobile/src/types/__tests__/defaults.test.ts
@@ -112,6 +112,13 @@ describe("TRACKING_PRESETS", () => {
expect(TRACKING_PRESETS[name].label).toBeTruthy()
})
+ it.each(presetNames)("%s description uses bullet separator for sync info", (name) => {
+ const parts = TRACKING_PRESETS[name].description.split(" • ")
+ expect(parts[0]).toBeTruthy()
+ expect(parts[0]).not.toContain("Send")
+ expect(parts[0]).not.toContain("Batch")
+ })
+
it.each(presetNames)("%s has valid batteryImpact", (name) => {
expect(["Low", "Medium", "High"]).toContain(TRACKING_PRESETS[name].batteryImpact)
})
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index 741d4ded..f367936d 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -60,7 +60,7 @@ export interface LocationTrackingResult {
export type ServerStatus = "connected" | "error" | "notConfigured"
-export interface ServerConnectionProps {
+export interface ConnectionStatusProps {
endpoint: string | null
navigation: any
}