Colota - Android GPS Location tracker
Improve code quality: logger, credential masking, pause zone rename
Max Dietrichc5fe386170f1
diff --git a/README.md b/README.mdindex 1b55f11b..b6bbaf47 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su- **Privacy First** — No analytics, no telemetry, no third-party SDKs. Open source (AGPL-3.0).- **Works Offline** — Fully functional without a server. Export as CSV, GeoJSON, GPX, or KML.- **Reliable Tracking** — Foreground service, auto-start on boot, exponential backoff retry.-- **Geofencing** — Silent zones that automatically pause tracking.+- **Geofencing** — Pause zones that automatically pause tracking.- **Flexible Sync** — Instant, batch, or offline modes.- **Authentication** — Basic Auth, Bearer Token, or custom headers with AES-256-GCM encryption.diff --git a/apps/docs/docs/contributing.md b/apps/docs/docs/contributing.mdindex a9bbc43e..0e475836 100644--- a/apps/docs/docs/contributing.md+++ b/apps/docs/docs/contributing.md@@ -26,10 +26,12 @@ See the [Development Guide](/docs/development/architecture) for architecture det- **TypeScript / React Native** for the UI layer- **Kotlin** for native Android modules- Follow existing patterns in the codebase+- Use `logger` instead of `console.log` — import from `src/services/logger`- Run before submitting:```bash- npm run lint- npx tsc --noEmit+ npm run lint -w @colota/mobile+ npx -w @colota/mobile tsc --noEmit+ npm test -w @colota/mobile```## Project Structurediff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex fd418cd9..753d2fd3 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -61,7 +61,7 @@ The primary React Native bridge module (exposed as `"LocationServiceModule"`). HEmits two events back to JavaScript:- `onLocationUpdate` — new GPS fix received-- `onSilentZoneChange` — entered or exited a geofence pause zone+- `onPauseZoneChange` — entered or exited a geofence pause zone### LocationForegroundService@@ -127,6 +127,7 @@ Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credentia| `NativeLocationService` | TypeScript bridge to the native `LocationServiceModule` with typed methods for all native operations || `LocationServicePermission` | Sequential Android permission requests (fine location → background location → notifications → battery exemption) || `SettingsService` | Bridges UI state to native SQLite with type conversion (seconds↔ms, objects↔JSON) |+| `logger` | Environment-aware logging — suppresses debug/info in production via `__DEV__`, always logs warn/error |### Hooksdiff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.mdindex f8eea7ad..4e1de281 100644--- a/apps/docs/docs/development/local-setup.md+++ b/apps/docs/docs/development/local-setup.md@@ -6,12 +6,12 @@ sidebar_position: 2## Prerequisites-- **Node.js** ≥ 18+- **Node.js** ≥ 20- **npm** ≥ 9 (ships with Node.js)- **Java Development Kit** (JDK) 17-- **Android SDK** (API level 35)- - Build Tools 35.0.0- - Android SDK Platform 35+- **Android SDK** (API level 36)+ - Build Tools 36.0.0+ - Android SDK Platform 36- **Android Studio** (recommended for emulator and SDK management)## Clone and Install@@ -62,9 +62,9 @@ The app reads build configuration from `apps/mobile/android/app/build.gradle`. K| Property | Default | Description || ------------------- | ------------ | -------------------------- || `applicationId` | `com.Colota` | Android package identifier |-| `minSdkVersion` | 26 | Minimum Android 8.0 |-| `targetSdkVersion` | 35 | Target Android 15 |-| `compileSdkVersion` | 35 | Compile against Android 15 |+| `minSdkVersion` | 24 | Minimum Android 7.0 |+| `targetSdkVersion` | 36 | Target Android 16 |+| `compileSdkVersion` | 36 | Compile against Android 16 |## Run the Docs Site@@ -140,6 +140,16 @@ colota/2. Run `npm run build` in `packages/shared/`3. Both the mobile app and docs site will pick up the changes+### Bumping the Version++Use the version bump script to update all packages and the Android build in one command:++```bash+npm run version:bump 1.2.0+```++This updates `version` in all `package.json` files, `versionName` in `build.gradle`, and auto-increments `versionCode`.+### Adding Documentation1. Create a Markdown file in `apps/docs/docs/`diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.mdindex 896f75ee..90b64d8e 100644--- a/apps/docs/docs/guides/geofencing.md+++ b/apps/docs/docs/guides/geofencing.md@@ -4,7 +4,7 @@ sidebar_position: 1# Geofencing-Create zones where tracking pauses automatically. These "silent zones" save battery and stop recording at places you visit often.+Create zones where tracking pauses automatically. These "pause zones" save battery and stop recording at places you visit often.## Use Cases@@ -29,7 +29,7 @@ Create zones where tracking pauses automatically. These "silent zones" save batt## How It Works- Zone detection uses the Haversine formula (1--2ms per check)-- When entering a silent zone, GPS stops updating+- When entering a pause zone, GPS stops updating- The notification shows "Paused: [Zone Name]"- When exiting the zone, tracking automatically resumes- Zone checks happen every location update with minimal overheaddiff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 0dfed55b..301ecf10 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -13,7 +13,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to- **Privacy First** — No analytics, no telemetry, no third-party SDKs, no cloud services. Open source under AGPL-3.0.- **Works Offline** — Works without a server. Store location history locally and export as CSV, GeoJSON, GPX, or KML.- **Background Tracking** — Foreground service, auto-start on boot, retry with exponential backoff, battery-critical shutdown.-- **Geofencing** — Create silent zones where tracking automatically pauses to save battery.+- **Geofencing** — Create pause zones where tracking automatically pauses to save battery.- **Sync Modes** — Instant, batch, or offline. Configurable intervals with automatic retry.- **Data Export** — Export location history in CSV, GeoJSON, GPX, or KML formats.- **Authentication** — Basic Auth, Bearer Token, or custom HTTP headers with AES-256-GCM encrypted storage.diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xmlindex b848b87c..c768a8cd 100644--- a/apps/mobile/android/app/src/main/AndroidManifest.xml+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml@@ -64,7 +64,7 @@android:foregroundServiceType="location"><intent-filter>- <action android:name="com.Colota.RECHECK_SILENT_ZONE" />+ <action android:name="com.Colota.RECHECK_PAUSE_ZONE" /><action android:name="com.Colota.ACTION_MANUAL_FLUSH" /></intent-filter></service>diff --git a/apps/mobile/android/app/src/main/java/com/colota/GeofenceHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/GeofenceHelper.ktindex 445bc9a1..f4390003 100644--- a/apps/mobile/android/app/src/main/java/com/colota/GeofenceHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/GeofenceHelper.kt@@ -54,10 +54,10 @@ class GeofenceHelper(private val context: Context) {// --- Core Logic ---/**- * Checks if location is within any active silent zone.+ * Checks if location is within any active pause zone.* Returns immediately on first match for better performance.*/- fun getSilentZone(location: Location): String? {+ fun getPauseZone(location: Location): String? {val fences = getGeofences()return fences.find {isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)diff --git a/apps/mobile/android/app/src/main/java/com/colota/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/LocationForegroundService.ktindex 5ecc14f0..1e756999 100644--- a/apps/mobile/android/app/src/main/java/com/colota/LocationForegroundService.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/LocationForegroundService.kt@@ -35,7 +35,7 @@ class LocationForegroundService : Service() {// --- State ---private var locationCallback: LocationCallback? = null- private var insideSilentZone = false+ private var insidePauseZone = falseprivate var currentZoneName: String? = nullprivate var lastNotificationText: String? = null@@ -58,7 +58,7 @@ class LocationForegroundService : Service() {companion object {private const val TAG = "LocationService"const val ACTION_MANUAL_FLUSH = "com.Colota.ACTION_MANUAL_FLUSH"- const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_SILENT_ZONE"+ const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"const val ACTION_FORCE_EXIT_ZONE = "com.Colota.FORCE_EXIT_ZONE"}@@ -114,11 +114,11 @@ class LocationForegroundService : Service() {when (action) {ACTION_FORCE_EXIT_ZONE -> {- if (insideSilentZone) {+ if (insidePauseZone) {if (BuildConfig.DEBUG) {Log.d(TAG, "Force exit from zone: $currentZoneName")}- exitSilentZone()+ exitPauseZone()// Immediately recheck with current locationlastKnownLocation?.let { recheckZoneWithLocation(it) }}@@ -214,8 +214,8 @@ class LocationForegroundService : Service() {lastKnownLocation = it// Check if starting in a pause zone- geofenceHelper.getSilentZone(it)?.let { zoneName ->- enterSilentZone(GeofenceInfo(-1, zoneName))+ geofenceHelper.getPauseZone(it)?.let { zoneName ->+ enterPauseZone(GeofenceInfo(-1, zoneName))} ?: run {// Not in zone - show coordinates immediatelyupdateNotification(it.latitude, it.longitude, forceUpdate = true)@@ -250,18 +250,18 @@ class LocationForegroundService : Service() {recheckZoneWithLocation(it)} ?: run {// No location available - if in zone, exit it- if (insideSilentZone) {+ if (insidePauseZone) {if (BuildConfig.DEBUG) {Log.d(TAG, "No location for recheck, forcing exit from zone")}- exitSilentZone()+ exitPauseZone()}}}.addOnFailureListener { e ->Log.e(TAG, "Recheck error", e)// On error, also exit zone if in one- if (insideSilentZone) {- exitSilentZone()+ if (insidePauseZone) {+ exitPauseZone()}}}@@ -269,21 +269,21 @@ class LocationForegroundService : Service() {private fun recheckZoneWithLocation(location: android.location.Location) {- val zoneName = geofenceHelper.getSilentZone(location)+ val zoneName = geofenceHelper.getPauseZone(location)when {// Just entered a pause zone or changed zones- zoneName != null && (!insideSilentZone || zoneName != currentZoneName) -> {- enterSilentZone(GeofenceInfo(-1, zoneName))+ zoneName != null && (!insidePauseZone || zoneName != currentZoneName) -> {+ enterPauseZone(GeofenceInfo(-1, zoneName))}// Just exited pause zone- zoneName == null && insideSilentZone -> {- exitSilentZone()+ zoneName == null && insidePauseZone -> {+ exitPauseZone()}// Still in the same pause zone - update coords but keep paused status- zoneName != null && insideSilentZone && zoneName == currentZoneName -> {+ zoneName != null && insidePauseZone && zoneName == currentZoneName -> {updateNotification(lat = location.latitude,lon = location.longitude,@@ -317,20 +317,20 @@ class LocationForegroundService : Service() {// Cache locationlastKnownLocation = location- // Silent Zone Logic - CHECK IF IT'S A PAUSE ZONE- val zoneName = geofenceHelper.getSilentZone(location)+ // Pause Zone Logic - CHECK IF IT'S A PAUSE ZONE+ val zoneName = geofenceHelper.getPauseZone(location)when {- zoneName != null && !insideSilentZone -> {+ zoneName != null && !insidePauseZone -> {// Entering a pause zone- enterSilentZone(GeofenceInfo(-1, zoneName))+ enterPauseZone(GeofenceInfo(-1, zoneName))return // Don't record location in pause zone}- zoneName == null && insideSilentZone -> {+ zoneName == null && insidePauseZone -> {// Exiting pause zone- exitSilentZone()+ exitPauseZone()}- zoneName != null && insideSilentZone -> {+ zoneName != null && insidePauseZone -> {// Still in pause zone, skip recordingreturn}@@ -377,11 +377,11 @@ class LocationForegroundService : Service() {updateNotification(location.latitude, location.longitude)}- private fun enterSilentZone(zone: GeofenceInfo) {- insideSilentZone = true+ private fun enterPauseZone(zone: GeofenceInfo) {+ insidePauseZone = truecurrentZoneName = zone.name- // Always show paused status when entering a silent zone+ // Always show paused status when entering a pause zonelastKnownLocation?.let { loc ->updateNotification(lat = loc.latitude,@@ -398,7 +398,7 @@ class LocationForegroundService : Service() {)}- LocationServiceModule.sendSilentZoneEvent(true, zone.name)+ LocationServiceModule.sendPauseZoneEvent(true, zone.name)if (BuildConfig.DEBUG) {Log.d(TAG, "Entered pause zone: ${zone.name}")@@ -406,8 +406,8 @@ class LocationForegroundService : Service() {}- private fun exitSilentZone() {- insideSilentZone = false+ private fun exitPauseZone() {+ insidePauseZone = falseval exited = currentZoneNamecurrentZoneName = null@@ -422,7 +422,7 @@ class LocationForegroundService : Service() {updateNotification(forceUpdate = true)}- LocationServiceModule.sendSilentZoneEvent(false, exited)+ LocationServiceModule.sendPauseZoneEvent(false, exited)if (BuildConfig.DEBUG) Log.d(TAG, "Exited pause zone: $exited")}@@ -502,7 +502,7 @@ class LocationForegroundService : Service() {val lastCoords = lastNotificationCoords// Check if this is a zone change (always update immediately)- val isZoneChange = pausedInZone != insideSilentZone || zoneName != currentZoneName+ val isZoneChange = pausedInZone != insidePauseZone || zoneName != currentZoneName// Apply smart filtering unless forced or zone changeif (!forceUpdate && !isZoneChange && lat != null && lon != null) {@@ -535,7 +535,7 @@ class LocationForegroundService : Service() {// Build notification textval queuedCount = syncManager.getCachedQueuedCount()- val isCurrentlyPaused = pausedInZone || insideSilentZone+ val isCurrentlyPaused = pausedInZone || insidePauseZoneval activeZone = zoneName ?: currentZoneNameval statusText = when {@@ -560,7 +560,7 @@ class LocationForegroundService : Service() {}private fun startForegroundServiceWithNotification() {- val initialStatus = if (insideSilentZone) {+ val initialStatus = if (insidePauseZone) {"Paused: ${currentZoneName ?: "Unknown"}"} else {"Initializing..."@@ -674,7 +674,7 @@ class LocationForegroundService : Service() {║ CURRENT SERVICE STATE ║╟────────────────────────────────────────────────────────────────╢║ Tracking Status: ✓ ACTIVE- ║ Silent Zone: ${if(insideSilentZone) "⏸️ PAUSED in '$currentZoneName'" else "✓ Not in zone"}+ ║ Pause Zone: ${if(insidePauseZone) "⏸️ PAUSED in '$currentZoneName'" else "✓ Not in zone"}║ Battery Level: $batteryStatusStr║ Queued Locations: ${syncManager.getCachedQueuedCount()} items║ Last Sync: ${getTimeSinceLastSync()}diff --git a/apps/mobile/android/app/src/main/java/com/colota/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/LocationServiceModule.ktindex 4367834a..e5d3f3fd 100644--- a/apps/mobile/android/app/src/main/java/com/colota/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/LocationServiceModule.kt@@ -90,10 +90,10 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}/**- * Emits silent zone entry/exit events to the React Native 'onSilentZoneChange' listener.+ * Emits pause zone entry/exit events to the React Native 'onPauseZoneChange' listener.*/@JvmStatic- fun sendSilentZoneEvent(entered: Boolean, zoneName: String?): Boolean {+ fun sendPauseZoneEvent(entered: Boolean, zoneName: String?): Boolean {val context = reactContextStatic ?: return falseif (!context.hasActiveCatalystInstance()) return false@@ -104,10 +104,10 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)- .emit("onSilentZoneChange", params)+ .emit("onPauseZoneChange", params)true} catch (e: Exception) {- Log.e(TAG, "Failed to send silent zone event", e)+ Log.e(TAG, "Failed to send pause zone event", e)false}}@@ -389,11 +389,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}// ==============================================================- // SILENT ZONE LOGIC+ // PAUSE ZONE LOGIC// ==============================================================@ReactMethod- fun checkCurrentSilentZone(promise: Promise) {+ fun checkCurrentPauseZone(promise: Promise) {val fusedClient = LocationServices.getFusedLocationProviderClient(reactApplicationContext)try {@@ -402,11 +402,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :promise.resolve(null)} else {executeAsync(promise) {- geofenceHelper.getSilentZone(loc)+ geofenceHelper.getPauseZone(loc)}}}.addOnFailureListener { e ->- Log.e(TAG, "Failed to get location for silent zone check", e)+ Log.e(TAG, "Failed to get location for pause zone check", e)promise.resolve(null)}} catch (e: SecurityException) {diff --git a/apps/mobile/android/app/src/main/java/com/colota/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/NetworkManager.ktindex 2a4f3e03..d288a1d8 100644--- a/apps/mobile/android/app/src/main/java/com/colota/NetworkManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/NetworkManager.kt@@ -82,7 +82,8 @@ class NetworkManager(private val context: Context) {Log.d(TAG, "Method: POST")Log.d(TAG, "Headers:")connection.requestProperties.forEach { (key, values) ->- Log.d(TAG, "$key: ${values.joinToString()}")+ val masked = values.map { maskSensitiveHeaderValue(key, it) }+ Log.d(TAG, "$key: ${masked.joinToString()}")}Log.d(TAG, "Body: ${payload.toString(2)}") // Pretty print JSONLog.d(TAG, "===================")@@ -141,6 +142,26 @@ class NetworkManager(private val context: Context) {}}+ /**+ * Masks the value of sensitive headers before logging.+ * Shows the first 4 characters followed by "***", or the full value+ * if it is shorter than 4 characters (replaced entirely with "***").+ */+ private fun maskSensitiveHeaderValue(headerName: String, headerValue: String): String {+ val sensitivePatterns = listOf(+ "authorization", "bearer", "token", "secret", "password", "api-key", "apikey"+ )+ val nameLower = headerName.lowercase()+ val isSensitive = sensitivePatterns.any { pattern -> nameLower.contains(pattern) }+ if (!isSensitive) return headerValue++ return if (headerValue.length > 4) {+ "${headerValue.substring(0, 4)}***"+ } else {+ "***"+ }+ }+/*** Checks for an active, validated internet connection with caching.*/diff --git a/apps/mobile/android/settings.gradle b/apps/mobile/android/settings.gradleindex 69797ea5..b230b45c 100644--- a/apps/mobile/android/settings.gradle+++ b/apps/mobile/android/settings.gradle@@ -1,11 +1,6 @@-pluginManagement {- includeBuild("../../../node_modules/@react-native/gradle-plugin")-}--plugins {- id("com.facebook.react.settings")-}-+pluginManagement { includeBuild("../../../node_modules/@react-native/gradle-plugin") }+plugins { id("com.facebook.react.settings") }+extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }rootProject.name = 'Colota'--include ':app'\ No newline at end of file+include ':app'+includeBuild('../../../node_modules/@react-native/gradle-plugin')diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsxindex 4a70eeb0..34108edd 100644--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx@@ -15,6 +15,7 @@ import { useFocusEffect } from "@react-navigation/native"import { STATS_REFRESH_IDLE } from "../../../constants"import { MapCenterButton } from "../map/MapCenterButton"import icon from "../../../assets/icons/icon.png"+import { logger } from "../../../services/logger"type Props = {coords: LocationCoords | null@@ -33,7 +34,7 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {const initialCoords = useRef<LocationCoords | null>(null)const [hasInitialCoords, setHasInitialCoords] = useState(false)- const [currentSilentZone, setCurrentSilentZone] = useState<string | null>(null)+ const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)const [isOffline, setIsOffline] = useState(false)useFocusEffect(@@ -63,7 +64,7 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {const data = await NativeLocationService.getGeofences()setGeofences(data)} catch (err) {- console.error("[GeofenceScreen] Failed to load geofences:", err)+ logger.error("[GeofenceScreen] Failed to load geofences:", err)}}, [])@@ -71,20 +72,20 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {loadGeofences()}, [loadGeofences])- // Check for silent zone+ // Check for pause zoneuseEffect(() => {- const checkSilentZone = async () => {+ const checkPauseZone = async () => {try {- const zoneName = await NativeLocationService.checkCurrentSilentZone()- setCurrentSilentZone(zoneName)+ const zoneName = await NativeLocationService.checkCurrentPauseZone()+ setCurrentPauseZone(zoneName)} catch (err) {- console.error("[GeofenceScreen] Failed to check silent zone:", err)+ logger.error("[GeofenceScreen] Failed to check pause zone:", err)}}- checkSilentZone()+ checkPauseZone()const listener = DeviceEventEmitter.addListener("geofenceUpdated", () => {- checkSilentZone()+ checkPauseZone()loadGeofences() // Reload geofences when they're updated})return () => listener.remove()@@ -98,11 +99,11 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {action: "update_user_pos",coords,tracking,- isPaused: !!currentSilentZone+ isPaused: !!currentPauseZone}))}- }, [coords, mapReady, tracking, currentSilentZone])+ }, [coords, mapReady, tracking, currentPauseZone])// Update geofencesuseEffect(() => {@@ -491,7 +492,7 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {action: "update_user_pos",coords,tracking,- isPaused: !!currentSilentZone+ isPaused: !!currentPauseZone}))}@@ -501,7 +502,7 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {setIsCentered(data.value)}} catch (err) {- console.error("WebView message error:", err)+ logger.error("WebView message error:", err)}}}/>diff --git a/apps/mobile/src/components/ui/ErrorBoundary.tsx b/apps/mobile/src/components/ui/ErrorBoundary.tsxindex 4a2eeb78..074d33b5 100644--- a/apps/mobile/src/components/ui/ErrorBoundary.tsx+++ b/apps/mobile/src/components/ui/ErrorBoundary.tsx@@ -6,6 +6,7 @@ import React, { Component } from "react"import { View, Text, StyleSheet, TouchableOpacity } from "react-native"import { ThemeColors } from "../../types/global"import { useTheme } from "../../hooks/useTheme"+import { logger } from "../../services/logger"import { fonts, fontSizes } from "../../styles/typography"interface ErrorBoundaryInternalProps {@@ -29,7 +30,7 @@ class ErrorBoundaryInternal extends Component<ErrorBoundaryInternalProps, ErrorB}componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {- console.error("ErrorBoundary caught an error:", error, errorInfo)+ logger.error("ErrorBoundary caught an error:", error, errorInfo)}handleReset = () => {diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsxindex 17f09a09..5e61bae8 100644--- a/apps/mobile/src/contexts/TrackingProvider.tsx+++ b/apps/mobile/src/contexts/TrackingProvider.tsx@@ -8,6 +8,7 @@ import { Settings, DEFAULT_SETTINGS, LocationCoords, ApiTemplateName } from "../import { useLocationTracking } from "../hooks/useLocationTracking"import NativeLocationService from "../services/NativeLocationService"import SettingsService from "../services/SettingsService"+import { logger } from "../services/logger"type TrackingContextType = {settings: Settings@@ -90,7 +91,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {*/const setSettings = useCallback(async (newSettings: Settings) => {try {- console.log("[TrackingContext] 💾 Batch syncing to Native storage...")+ logger.debug("[TrackingContext] Batch syncing to Native storage...")// SettingsService handles unit conversion (seconds -> ms)await SettingsService.updateMultiple(newSettings)@@ -99,7 +100,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {setError(null) // Clear any previous errors}} catch (err) {- console.error("[TrackingContext] Persistence failed:", err)+ logger.error("[TrackingContext] Persistence failed:", err)if (isMountedRef.current) {setError(err instanceof Error ? err : new Error(String(err)))}@@ -126,14 +127,14 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {const init = async () => {try {- console.log("[TrackingContext] 📂 Hydrating settings and state...")+ logger.debug("[TrackingContext] Hydrating settings and state...")const allRaw = await NativeLocationService.getAllSettings()if (!isMountedRef.current) return// Initialize DB with defaults if emptyif (Object.keys(allRaw).length === 0) {- console.log("[TrackingContext] 🆕 Initializing DB with defaults")+ logger.debug("[TrackingContext] Initializing DB with defaults")await setSettings(DEFAULT_SETTINGS)return}@@ -147,11 +148,11 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {// Auto-reconnect UI if tracking was activeconst isTrackingActive = allRaw.tracking_enabled === "true"if (isTrackingActive) {- console.log("[TrackingContext] 🔄 Re-syncing UI with active background service")+ logger.debug("[TrackingContext] Re-syncing UI with active background service")internalReconnect()}} catch (err) {- console.error("[TrackingContext] Hydration failed:", err)+ logger.error("[TrackingContext] Hydration failed:", err)if (isMountedRef.current) {setError(err instanceof Error ? err : new Error(String(err)))}@@ -168,7 +169,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {// Safety timeout: force isLoading=false if init hangsconst timeout = setTimeout(() => {if (isMountedRef.current && !hasInitializedRef.current) {- console.error("[TrackingContext] Initialization timed out after 5s, forcing ready state")+ logger.error("[TrackingContext] Initialization timed out after 5s, forcing ready state")setIsLoading(false)hasInitializedRef.current = true}@@ -191,7 +192,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {setError(null)}} catch (err) {- console.error("[TrackingContext] Failed to start tracking:", err)+ logger.error("[TrackingContext] Failed to start tracking:", err)if (isMountedRef.current) {setError(err instanceof Error ? err : new Error(String(err)))}@@ -206,7 +207,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {setError(null)}} catch (err) {- console.error("[TrackingContext] Failed to stop tracking:", err)+ logger.error("[TrackingContext] Failed to stop tracking:", err)if (isMountedRef.current) {setError(err instanceof Error ? err : new Error(String(err)))}@@ -221,7 +222,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {setError(null)}} catch (err) {- console.error("[TrackingContext] Failed to restart tracking:", err)+ logger.error("[TrackingContext] Failed to restart tracking:", err)if (isMountedRef.current) {setError(err instanceof Error ? err : new Error(String(err)))}diff --git a/apps/mobile/src/hooks/useAutoSave.ts b/apps/mobile/src/hooks/useAutoSave.tsindex a9d02c5d..e772f8ed 100644--- a/apps/mobile/src/hooks/useAutoSave.ts+++ b/apps/mobile/src/hooks/useAutoSave.ts@@ -6,6 +6,7 @@import { useState, useCallback } from "react"import { useTimeout } from "./useTimeout"import { AUTOSAVE_DEBOUNCE_MS, SAVE_SUCCESS_DISPLAY_MS } from "../constants"+import { logger } from "../services/logger"/*** Hook that encapsulates the debounced auto-save pattern used across settings screens.@@ -38,14 +39,14 @@ export function useAutoSave() {setSaveSuccess(true)successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)} catch (err) {- console.error("[useAutoSave] Restart failed:", err)+ logger.error("[useAutoSave] Restart failed:", err)} finally {setSaving(false)}}, AUTOSAVE_DEBOUNCE_MS)} catch (err) {setSaving(false)- console.error("[useAutoSave] Save failed:", err)+ logger.error("[useAutoSave] Save failed:", err)}}, AUTOSAVE_DEBOUNCE_MS)},@@ -69,7 +70,7 @@ export function useAutoSave() {setSaveSuccess(true)successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)} catch (err) {- console.error("[useAutoSave] Restart failed:", err)+ logger.error("[useAutoSave] Restart failed:", err)} finally {setSaving(false)}@@ -77,7 +78,7 @@ export function useAutoSave() {}).catch((err) => {setSaving(false)- console.error("[useAutoSave] Save failed:", err)+ logger.error("[useAutoSave] Save failed:", err)})},[saveTimeout, restartTimeout, successTimeout]diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.tsindex 6c647d11..0517163d 100644--- a/apps/mobile/src/hooks/useLocationTracking.ts+++ b/apps/mobile/src/hooks/useLocationTracking.ts@@ -8,6 +8,7 @@ import { NativeEventEmitter, NativeModules, Alert } from "react-native"import NativeLocationService from "../services/NativeLocationService"import { LocationCoords, Settings, LocationTrackingResult } from "../types/global"import { ensurePermissions } from "../services/LocationServicePermission"+import { logger } from "../services/logger"const { LocationServiceModule } = NativeModulesconst locationEventEmitter = new NativeEventEmitter(LocationServiceModule)@@ -71,7 +72,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult})}} catch (err) {- console.error("[useLocationTracking] Failed to fetch initial location:", err)+ logger.error("[useLocationTracking] Failed to fetch initial location:", err)}}}@@ -84,7 +85,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult*/useEffect(() => {if (tracking && !listenerRef.current) {- console.log("[useLocationTracking] 📡 Attaching native listener")+ logger.debug("[useLocationTracking] Attaching native listener")listenerRef.current = locationEventEmitter.addListener("onLocationUpdate", (event: any) => {setCoords({latitude: event.latitude,@@ -102,7 +103,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResultreturn () => {if (listenerRef.current) {- console.log("[useLocationTracking] 🔌 Detaching native listener")+ logger.debug("[useLocationTracking] Detaching native listener")listenerRef.current.remove()listenerRef.current = null}@@ -115,7 +116,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult*/const startTracking = useCallback(async (overrideSettings?: Settings) => {if (isTrackingRef.current) {- console.log("[useLocationTracking] Already tracking")+ logger.debug("[useLocationTracking] Already tracking")return}@@ -134,10 +135,10 @@ export function useLocationTracking(settings: Settings): LocationTrackingResulttry {await NativeLocationService.start(effectiveSettings)- console.log(`[useLocationTracking] ✅ Service started (offline: ${effectiveSettings.isOfflineMode})`)+ logger.debug(`[useLocationTracking] Service started (offline: ${effectiveSettings.isOfflineMode})`)} catch (error) {setTracking(false)- console.error("[useLocationTracking] ❌ Failed to start:", error)+ logger.error("[useLocationTracking] Failed to start:", error)Alert.alert("Error", "Failed to start location tracking.")}}, [])@@ -147,11 +148,11 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult*/const stopTracking = useCallback(() => {if (!isTrackingRef.current) {- console.log("[useLocationTracking] Not tracking")+ logger.debug("[useLocationTracking] Not tracking")return}- console.log("[useLocationTracking] Stopping service")+ logger.debug("[useLocationTracking] Stopping service")if (listenerRef.current) {listenerRef.current.remove()@@ -171,12 +172,12 @@ export function useLocationTracking(settings: Settings): LocationTrackingResultconst restartTracking = useCallback(async (newSettings?: Settings) => {if (restartingRef.current) {- console.log("[useLocationTracking] Restart already in progress, queuing")+ logger.debug("[useLocationTracking] Restart already in progress, queuing")restartQueuedRef.current = truereturn}- console.log("[useLocationTracking] Restarting service")+ logger.debug("[useLocationTracking] Restarting service")setIsRestarting(true)restartingRef.current = true@@ -194,7 +195,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult// Process queued restart if anyif (restartQueuedRef.current) {restartQueuedRef.current = false- console.log("[useLocationTracking] Processing queued restart")+ logger.debug("[useLocationTracking] Processing queued restart")setTimeout(() => restartTracking(newSettings), 100)}}@@ -209,11 +210,11 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult*/const reconnect = useCallback(async () => {if (isTrackingRef.current) {- console.log("[useLocationTracking] Already tracking, skip reconnect")+ logger.debug("[useLocationTracking] Already tracking, skip reconnect")return}- console.log("[useLocationTracking] Reconnecting to active service")+ logger.debug("[useLocationTracking] Reconnecting to active service")setTracking(true)try {@@ -232,7 +233,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult})}} catch (err) {- console.error("[useLocationTracking] Failed to fetch location on reconnect:", err)+ logger.error("[useLocationTracking] Failed to fetch location on reconnect:", err)}}, [])@@ -242,7 +243,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult*/useEffect(() => {return () => {- console.log("[useLocationTracking] 🧹 Component unmounted, service remains active")+ logger.debug("[useLocationTracking] Component unmounted, service remains active")restartQueuedRef.current = falserestartingRef.current = false}diff --git a/apps/mobile/src/screens/AboutScreen.tsx b/apps/mobile/src/screens/AboutScreen.tsxindex 7358a6b4..430ce9fe 100644--- a/apps/mobile/src/screens/AboutScreen.tsx+++ b/apps/mobile/src/screens/AboutScreen.tsx@@ -13,6 +13,7 @@ import { Card, Container, Divider, Footer } from "../components"import NativeLocationService from "../services/NativeLocationService"import icon from "../assets/icons/icon.png"import { REPO_URL, PRIVACY_POLICY_URL } from "../constants"+import { logger } from "../services/logger"// Helper function to map SDK to Android versionfunction getAndroidVersion(sdkVersion: number): string {@@ -115,7 +116,7 @@ export function AboutScreen({}: ScreenProps) {apiLevel: info.apiLevel.toString()})} catch (err) {- console.error("Failed to load device info:", err)+ logger.error("Failed to load device info:", err)}}@@ -123,7 +124,7 @@ export function AboutScreen({}: ScreenProps) {}, [])const handleOpenURL = (url: string) => {- Linking.openURL(url).catch((err) => console.error("Failed to open URL:", err))+ Linking.openURL(url).catch((err) => logger.error("Failed to open URL:", err))}// Fallback if buildConfig is not availablediff --git a/apps/mobile/src/screens/AuthSettingsScreen.tsx b/apps/mobile/src/screens/AuthSettingsScreen.tsxindex 97640bd3..461db0bc 100644--- a/apps/mobile/src/screens/AuthSettingsScreen.tsx+++ b/apps/mobile/src/screens/AuthSettingsScreen.tsx@@ -12,6 +12,7 @@ import { useTracking } from "../contexts/TrackingProvider"import { fonts, fontSizes } from "../styles/typography"import { SectionTitle, FloatingSaveIndicator, Container, Card, Divider } from "../components"import NativeLocationService from "../services/NativeLocationService"+import { logger } from "../services/logger"const AUTH_TYPES: { value: AuthType; label: string }[] = [{ value: "none", label: "None" },@@ -37,7 +38,7 @@ export function AuthSettingsScreen({}: ScreenProps) {const saved = await NativeLocationService.getAuthConfig()setConfig(saved)} catch (err) {- console.error("[AuthSettingsScreen] Failed to load auth config:", err)+ logger.error("[AuthSettingsScreen] Failed to load auth config:", err)} finally {setLoading(false)}diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsxindex a25ee892..f73277f0 100644--- a/apps/mobile/src/screens/DashboardScreen.tsx+++ b/apps/mobile/src/screens/DashboardScreen.tsx@@ -22,6 +22,7 @@ import {} from "../components"import { STATS_REFRESH_IDLE } from "../constants"import { Square, Play } from "lucide-react-native"+import { logger } from "../services/logger"export function DashboardScreen({ navigation }: ScreenProps) {const { coords, settings, tracking, startTracking, stopTracking, setSettings } = useTracking()@@ -36,13 +37,13 @@ export function DashboardScreen({ navigation }: ScreenProps) {})const prevStats = useRef(stats)- const [currentSilentZone, setCurrentSilentZone] = useState<string | null>(null)+ const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)const [scrollEnabled, setScrollEnabled] = useState(true)// Animation for buttonconst buttonScale = useRef(new Animated.Value(1)).current- const isInSilentZone = !!currentSilentZone+ const isInPauseZone = !!currentPauseZoneconst handleStart = async () => {// Bounce animation@@ -93,24 +94,24 @@ export function DashboardScreen({ navigation }: ScreenProps) {prevStats.current = nativeStats}} catch (err) {- console.error("[Dashboard] Failed to update stats:", err)+ logger.error("[Dashboard] Failed to update stats:", err)}}, [])- const updateSilentZone = useCallback(async () => {+ const updatePauseZone = useCallback(async () => {try {- const zoneName = await NativeLocationService.checkCurrentSilentZone()- setCurrentSilentZone(zoneName)+ const zoneName = await NativeLocationService.checkCurrentPauseZone()+ setCurrentPauseZone(zoneName)} catch (err) {- console.error("[Dashboard] Failed to update silent zone:", err)- setCurrentSilentZone(null)+ logger.error("[Dashboard] Failed to update pause zone:", err)+ setCurrentPauseZone(null)}}, [])useFocusEffect(useCallback(() => {updateStats()- updateSilentZone()+ updatePauseZone()const interval = tracking ? Math.max(settings.interval * 1000, 2000) : STATS_REFRESH_IDLE@@ -119,27 +120,27 @@ export function DashboardScreen({ navigation }: ScreenProps) {return () => {clearInterval(statsTimer)}- }, [tracking, updateStats, updateSilentZone, settings.interval])+ }, [tracking, updateStats, updatePauseZone, settings.interval]))useEffect(() => {- const listener = DeviceEventEmitter.addListener("geofenceUpdated", updateSilentZone)+ const listener = DeviceEventEmitter.addListener("geofenceUpdated", updatePauseZone)return () => listener.remove()- }, [updateSilentZone])+ }, [updatePauseZone])useEffect(() => {- const silentZoneListener = DeviceEventEmitter.addListener(- "onSilentZoneChange",+ const pauseZoneListener = DeviceEventEmitter.addListener(+ "onPauseZoneChange",(data: { entered: boolean; zoneName: string | null }) => {if (data.entered) {- setCurrentSilentZone(data.zoneName)+ setCurrentPauseZone(data.zoneName)} else {- setCurrentSilentZone(null)+ setCurrentPauseZone(null)}})- return () => silentZoneListener.remove()+ return () => pauseZoneListener.remove()}, [])return (@@ -160,8 +161,8 @@ export function DashboardScreen({ navigation }: ScreenProps) {<DashboardMapcoords={coords}tracking={tracking}- isPaused={isInSilentZone}- activeZoneName={currentSilentZone}+ isPaused={isInPauseZone}+ activeZoneName={currentPauseZone}/></View>diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsxindex 454c90cc..850ec804 100644--- a/apps/mobile/src/screens/DataManagementScreen.tsx+++ b/apps/mobile/src/screens/DataManagementScreen.tsx@@ -23,6 +23,7 @@ import NativeLocationService from "../services/NativeLocationService"import { Button, SectionTitle, Card, Container, Divider, FloatingSaveIndicator } from "../components"import { STATS_REFRESH_FAST } from "../constants"import { useTimeout } from "../hooks/useTimeout"+import { logger } from "../services/logger"export function DataManagementScreen({}: ScreenProps) {const { colors } = useTheme()@@ -46,7 +47,7 @@ export function DataManagementScreen({}: ScreenProps) {const nativeStats = await NativeLocationService.getStats()setStats(nativeStats)} catch (err) {- console.error("[DataManagementScreen] Failed to update stats:", err)+ logger.error("[DataManagementScreen] Failed to update stats:", err)}}, [])@@ -85,7 +86,7 @@ export function DataManagementScreen({}: ScreenProps) {showFeedback("Sync initiated successfully!")}, 2000)} catch (err) {- console.error("[DataManagementScreen] Manual flush error:", err)+ logger.error("[DataManagementScreen] Manual flush error:", err)setIsProcessing(false)showFeedback("Failed to sync queue")}@@ -102,7 +103,7 @@ export function DataManagementScreen({}: ScreenProps) {showFeedback(successMessage(deleted))}} catch (err) {- console.error("[DataManagementScreen] Delete action failed:", err)+ logger.error("[DataManagementScreen] Delete action failed:", err)showFeedback("Action failed")} finally {setIsProcessing(false)@@ -145,7 +146,7 @@ export function DataManagementScreen({}: ScreenProps) {await updateStats()showFeedback("Database optimized")} catch (err) {- console.error("[DataManagementScreen] Vacuum failed:", err)+ logger.error("[DataManagementScreen] Vacuum failed:", err)showFeedback("Optimization failed")} finally {setIsProcessing(false)diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsxindex ec54c92b..0ec02f7e 100644--- a/apps/mobile/src/screens/ExportDataScreen.tsx+++ b/apps/mobile/src/screens/ExportDataScreen.tsx@@ -12,6 +12,7 @@ import { useTheme } from "../hooks/useTheme"import { ThemeColors, LocationCoords } from "../types/global"import NativeLocationService from "../services/NativeLocationService"import { LARGE_FILE_THRESHOLD, formatBytes, getByteSize, EXPORT_FORMATS, ExportFormat } from "../utils/exportConverters"+import { logger } from "../services/logger"interface ExportStats {totalLocations: number@@ -41,7 +42,7 @@ export function ExportDataScreen() {setStats({ totalLocations: data.length })}} catch (error) {- console.error("[ExportDataScreen] Failed to load stats:", error)+ logger.error("[ExportDataScreen] Failed to load stats:", error)}}, [])@@ -122,18 +123,18 @@ export function ExportDataScreen() {try {await NativeLocationService.shareFile(filePath, mimeType, `Colota Export - ${stats.totalLocations} locations`)} catch (shareError: any) {- console.warn("[ExportDataScreen] Share error:", shareError)+ logger.warn("[ExportDataScreen] Share error:", shareError)}setTimeout(async () => {try {await NativeLocationService.deleteFile(filePath)} catch (err) {- console.warn("[ExportDataScreen] Failed to cleanup temp file:", err)+ logger.warn("[ExportDataScreen] Failed to cleanup temp file:", err)}}, 2000)} catch (error) {- console.error("[ExportDataScreen] Export failed:", error)+ logger.error("[ExportDataScreen] Export failed:", error)Alert.alert("Export Failed", "Unable to export your data. Please try again.")} finally {setExporting(false)diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsxindex 03bf0083..3942d7ea 100644--- a/apps/mobile/src/screens/GeofenceScreen.tsx+++ b/apps/mobile/src/screens/GeofenceScreen.tsx@@ -26,6 +26,7 @@ import { Container, SectionTitle, Card } from "../components"import { useFocusEffect } from "@react-navigation/native"import { STATS_REFRESH_IDLE } from "../constants"import { MapCenterButton } from "../components/features/map/MapCenterButton"+import { logger } from "../services/logger"export function GeofenceScreen({}: ScreenProps) {const { coords, tracking } = useTracking()@@ -39,7 +40,7 @@ export function GeofenceScreen({}: ScreenProps) {const [isCentered, setIsCentered] = useState(true)const [mapReady, setMapReady] = useState(false)const [hasInitialCoords, setHasInitialCoords] = useState(false)- const [currentSilentZone, setCurrentSilentZone] = useState<string | null>(null)+ const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)const [isOffline, setIsOffline] = useState(false)const webviewRef = useRef<WebView>(null)@@ -94,7 +95,7 @@ export function GeofenceScreen({}: ScreenProps) {const data = await NativeLocationService.getGeofences()setGeofences(data)} catch (err) {- console.error("[GeofenceScreen] Failed to load geofences:", err)+ logger.error("[GeofenceScreen] Failed to load geofences:", err)}}, [])@@ -102,19 +103,19 @@ export function GeofenceScreen({}: ScreenProps) {loadGeofences()}, [loadGeofences])- // Check for silent zone+ // Check for pause zoneuseEffect(() => {- const checkSilentZone = async () => {+ const checkPauseZone = async () => {try {- const zoneName = await NativeLocationService.checkCurrentSilentZone()- setCurrentSilentZone(zoneName)+ const zoneName = await NativeLocationService.checkCurrentPauseZone()+ setCurrentPauseZone(zoneName)} catch (err) {- console.error("[GeofenceScreen] Failed to check silent zone:", err)+ logger.error("[GeofenceScreen] Failed to check pause zone:", err)}}- checkSilentZone()- const listener = DeviceEventEmitter.addListener("geofenceUpdated", checkSilentZone)+ checkPauseZone()+ const listener = DeviceEventEmitter.addListener("geofenceUpdated", checkPauseZone)return () => listener.remove()}, [])@@ -126,11 +127,11 @@ export function GeofenceScreen({}: ScreenProps) {action: "update_user_pos",coords,tracking,- isPaused: !!currentSilentZone+ isPaused: !!currentPauseZone}))}- }, [coords, mapReady, tracking, currentSilentZone])+ }, [coords, mapReady, tracking, currentPauseZone])// Update geofencesuseEffect(() => {@@ -173,7 +174,7 @@ export function GeofenceScreen({}: ScreenProps) {}}} catch (err) {- console.error("[GeofenceScreen] Message error:", err)+ logger.error("[GeofenceScreen] Message error:", err)}},[newName, newRadius, loadGeofences]diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsxindex a641bf77..c8861199 100644--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx@@ -12,6 +12,7 @@ import { useTheme } from "../hooks/useTheme"import { ThemeColors } from "../types/global"import NativeLocationService from "../services/NativeLocationService"import { STATS_REFRESH_FAST } from "../constants"+import { logger } from "../services/logger"// Typesinterface LocationData {@@ -127,7 +128,7 @@ export function LocationInspectorScreen() {const result = await NativeLocationService.getTableData(activeTable, limit, offset)setData(result || [])} catch (err) {- console.error("[LocationInspector] Fetch error:", err)+ logger.error("[LocationInspector] Fetch error:", err)setData([])}}, [activeTable, limit, page])diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsxindex b2709d69..6edf2e1a 100644--- a/apps/mobile/src/screens/SettingsScreen.tsx+++ b/apps/mobile/src/screens/SettingsScreen.tsx@@ -16,6 +16,7 @@ import { fonts } from "../styles/typography"import { SectionTitle, Card, Container, Divider } from "../components"import { ChevronRight } from "lucide-react-native"import { StatsCard } from "../components"+import { logger } from "../services/logger"import { ConnectionSettings } from "../components/features/settings/ConnectionSettings"import { SyncStrategySettings } from "../components/features/settings/SyncStrategySettings"@@ -47,7 +48,7 @@ export function SettingsScreen({ navigation }: ScreenProps) {setQueueCount(stats.queued)setSentCount(stats.sent)} catch (err) {- console.error("[SettingsScreen] Failed to get stats:", err)+ logger.error("[SettingsScreen] Failed to get stats:", err)}}, [])diff --git a/apps/mobile/src/services/LocationServicePermission.ts b/apps/mobile/src/services/LocationServicePermission.tsindex 698c90d8..ab7a5485 100644--- a/apps/mobile/src/services/LocationServicePermission.ts+++ b/apps/mobile/src/services/LocationServicePermission.ts@@ -5,6 +5,7 @@import { Platform, PermissionsAndroid, Alert } from "react-native"import NativeLocationService from "./NativeLocationService"+import { logger } from "./logger"/*** Permission status for location tracking@@ -64,7 +65,7 @@ export async function ensurePermissions(): Promise<boolean> {return true} catch (err) {- console.error("[PermissionService] Permission request error:", err)+ logger.error("[PermissionService] Permission request error:", err)Alert.alert("Permission Error", "Failed to request permissions. Please try again.", [{ text: "OK" }])return false}@@ -146,7 +147,7 @@ async function requestBatteryOptimizationExemption(): Promise<void> {await NativeLocationService.requestIgnoreBatteryOptimizations()}} catch (err) {- console.error("[PermissionService] Battery optimization request failed:", err)+ logger.error("[PermissionService] Battery optimization request failed:", err)// Non-critical, don't block}}@@ -227,7 +228,7 @@ async function checkBatteryOptimization(): Promise<boolean> {try {return await NativeLocationService.isIgnoringBatteryOptimizations()} catch (err) {- console.error("[PermissionService] Battery optimization check failed:", err)+ logger.error("[PermissionService] Battery optimization check failed:", err)return false}}diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 21ee1b13..0718ff94 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -5,6 +5,7 @@import { NativeModules } from "react-native"import { AuthConfig, DatabaseStats, Geofence, Settings } from "../types/global"+import { logger } from "./logger"const { LocationServiceModule, BuildConfigModule } = NativeModules@@ -35,7 +36,7 @@ class NativeLocationService {try {return await operation()} catch (error) {- console.error(`[NativeLocationService] ${errorPrefix}:`, error)+ logger.error(`[NativeLocationService] ${errorPrefix}:`, error)return fallback}}@@ -64,15 +65,15 @@ class NativeLocationService {isOfflineMode: settings.isOfflineMode}- console.log(+ logger.debug(`[NativeLocationService] Starting service - interval: ${settings.interval}s, distance: ${settings.distance}m, sync: ${settings.syncInterval}s`)try {await LocationServiceModule.startService(config)- console.log("[NativeLocationService] Service started")+ logger.debug("[NativeLocationService] Service started")} catch (error) {- console.error("[NativeLocationService] Start failed:", error)+ logger.error("[NativeLocationService] Start failed:", error)throw error}}@@ -82,11 +83,11 @@ class NativeLocationService {*/static stop(): void {if (!LocationServiceModule) {- console.warn("[NativeLocationService] Module not available")+ logger.warn("[NativeLocationService] Module not available")return}- console.log("[NativeLocationService] Stopping service")+ logger.debug("[NativeLocationService] Stopping service")LocationServiceModule.stopService()}@@ -117,13 +118,13 @@ class NativeLocationService {*/static async manualFlush(): Promise<boolean> {this.ensureModule()- console.log("[NativeLocationService] Triggering manual flush")+ logger.debug("[NativeLocationService] Triggering manual flush")try {const result = await LocationServiceModule.manualFlush()- console.log("[NativeLocationService] Flush completed")+ logger.debug("[NativeLocationService] Flush completed")return result} catch (error) {- console.error("[NativeLocationService] Flush failed:", error)+ logger.error("[NativeLocationService] Flush failed:", error)throw error}}@@ -184,7 +185,7 @@ class NativeLocationService {*/static async clearSentHistory(): Promise<void> {this.ensureModule()- console.log("[NativeLocationService] Clearing sent history")+ logger.debug("[NativeLocationService] Clearing sent history")await LocationServiceModule.clearSentHistory()}@@ -194,7 +195,7 @@ class NativeLocationService {*/static async clearQueue(): Promise<number> {this.ensureModule()- console.log("[NativeLocationService] Clearing queue")+ logger.debug("[NativeLocationService] Clearing queue")return LocationServiceModule.clearQueue()}@@ -204,7 +205,7 @@ class NativeLocationService {*/static async clearAllLocations(): Promise<number> {this.ensureModule()- console.log("[NativeLocationService] Clearing all locations")+ logger.debug("[NativeLocationService] Clearing all locations")return LocationServiceModule.clearAllLocations()}@@ -215,7 +216,7 @@ class NativeLocationService {*/static async deleteOlderThan(days: number): Promise<number> {this.ensureModule()- console.log(`[NativeLocationService] Deleting locations older than ${days} days`)+ logger.debug(`[NativeLocationService] Deleting locations older than ${days} days`)return LocationServiceModule.deleteOlderThan(days)}@@ -224,7 +225,7 @@ class NativeLocationService {*/static async vacuumDatabase(): Promise<void> {this.ensureModule()- console.log("[NativeLocationService] Vacuuming database")+ logger.debug("[NativeLocationService] Vacuuming database")await LocationServiceModule.vacuumDatabase()}@@ -246,7 +247,7 @@ class NativeLocationService {*/static async createGeofence(geofence: Omit<Geofence, "id" | "createdAt">): Promise<number> {this.ensureModule()- console.log("[NativeLocationService] Creating geofence:", geofence.name)+ logger.debug("[NativeLocationService] Creating geofence:", geofence.name)return LocationServiceModule.createGeofence(geofence.name,geofence.lat,@@ -266,7 +267,7 @@ class NativeLocationService {throw new Error("Geofence ID is required")}- console.log("[NativeLocationService] Updating geofence:", update.id)+ logger.debug("[NativeLocationService] Updating geofence:", update.id)return LocationServiceModule.updateGeofence(update.id,update.name ?? null,@@ -283,30 +284,30 @@ class NativeLocationService {*/static async deleteGeofence(id: number): Promise<boolean> {this.ensureModule()- console.log("[NativeLocationService] Deleting geofence:", id)+ logger.debug("[NativeLocationService] Deleting geofence:", id)return LocationServiceModule.deleteGeofence(id)}/**- * Checks if device is currently inside a silent zone- * @returns Silent zone name or null+ * Checks if device is currently inside a pause zone+ * @returns Pause zone name or null*/- static async checkCurrentSilentZone(): Promise<string | null> {+ static async checkCurrentPauseZone(): Promise<string | null> {this.ensureModule()- return this.safeExecute(() => LocationServiceModule.checkCurrentSilentZone(), null, "checkCurrentSilentZone failed")+ return this.safeExecute(() => LocationServiceModule.checkCurrentPauseZone(), null, "checkCurrentPauseZone failed")}/**- * Triggers immediate recheck of silent zone settings+ * Triggers immediate recheck of pause zone settings* Use after modifying geofence pause settings to update notification instantly*/static async recheckZoneSettings(): Promise<void> {this.ensureModule()- console.log("[NativeLocationService] Triggering zone settings recheck")+ logger.debug("[NativeLocationService] Triggering zone settings recheck")try {await LocationServiceModule.recheckZoneSettings()} catch (error) {- console.error("[NativeLocationService] ❌ Recheck failed:", error)+ logger.error("[NativeLocationService] Recheck failed:", error)}}@@ -372,7 +373,7 @@ class NativeLocationService {*/static async requestIgnoreBatteryOptimizations(): Promise<boolean> {this.ensureModule()- console.log("[NativeLocationService] Requesting battery optimization exemption")+ logger.debug("[NativeLocationService] Requesting battery optimization exemption")return this.safeExecute(() => LocationServiceModule.requestIgnoreBatteryOptimizations(),false,@@ -399,7 +400,7 @@ class NativeLocationService {VERSION_CODE: number} | null {if (!BuildConfigModule) {- console.warn("[NativeLocationService] BuildConfigModule not available")+ logger.warn("[NativeLocationService] BuildConfigModule not available")return null}return BuildConfigModulediff --git a/apps/mobile/src/services/SettingsService.ts b/apps/mobile/src/services/SettingsService.tsindex 21ff5b2b..08ad277c 100644--- a/apps/mobile/src/services/SettingsService.ts+++ b/apps/mobile/src/services/SettingsService.ts@@ -5,6 +5,7 @@import NativeLocationService from "./NativeLocationService"import { Settings } from "../types/global"+import { logger } from "./logger"/*** Bridge between UI state and native SQLite configuration.@@ -66,7 +67,7 @@ export const SettingsService = {*/updateMultiple: async (settingsUpdate: Partial<Settings>): Promise<void> => {const entries = Object.entries(settingsUpdate)- console.log(`[SettingsService] Batch updating ${entries.length} settings`)+ logger.debug(`[SettingsService] Batch updating ${entries.length} settings`)const results = await Promise.allSettled(entries.map(([key, val]) => SettingsService.updateSetting(key as keyof Settings, val))@@ -74,11 +75,11 @@ export const SettingsService = {const failures = results.filter((r) => r.status === "rejected")if (failures.length > 0) {- failures.forEach((f) => console.error("[SettingsService] Setting failed:", (f as PromiseRejectedResult).reason))+ failures.forEach((f) => logger.error("[SettingsService] Setting failed:", (f as PromiseRejectedResult).reason))throw new Error(`Failed to save ${failures.length} of ${entries.length} settings`)}- console.log("[SettingsService] Batch update completed")+ logger.debug("[SettingsService] Batch update completed")}}diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex 230081b0..36fa695b 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -23,7 +23,7 @@ jest.mock("react-native", () => ({createGeofence: jest.fn().mockResolvedValue(1),updateGeofence: jest.fn().mockResolvedValue(true),deleteGeofence: jest.fn().mockResolvedValue(true),- checkCurrentSilentZone: jest.fn().mockResolvedValue(null),+ checkCurrentPauseZone: jest.fn().mockResolvedValue(null),recheckZoneSettings: jest.fn().mockResolvedValue(undefined),saveSetting: jest.fn().mockResolvedValue(undefined),getSetting: jest.fn().mockResolvedValue(null),diff --git a/apps/mobile/src/services/logger.ts b/apps/mobile/src/services/logger.tsnew file mode 100644index 00000000..b2ac4f57--- /dev/null+++ b/apps/mobile/src/services/logger.ts@@ -0,0 +1,24 @@+/**+ * Logger utility that suppresses debug/info logs in production builds.+ * Uses React Native's __DEV__ flag to determine environment.+ *+ * - debug/info: Only logged in development+ * - warn/error: Always logged+ */++/* eslint-disable no-console */++export const logger = {+ debug: (...args: unknown[]) => {+ if (__DEV__) console.log(...args)+ },+ info: (...args: unknown[]) => {+ if (__DEV__) console.log(...args)+ },+ warn: (...args: unknown[]) => {+ console.warn(...args)+ },+ error: (...args: unknown[]) => {+ console.error(...args)+ }+}diff --git a/package.json b/package.jsonindex 40f84aed..1d8ee405 100644--- a/package.json+++ b/package.json@@ -11,7 +11,8 @@"test": "npm run test --workspaces --if-present","clean": "npm run clean --workspaces --if-present","format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",- "format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,md}\""+ "format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,md}\"",+ "version:bump": "bash scripts/bump-version.sh"},"devDependencies": {"prettier": "^2.8.8"diff --git a/scripts/bump-version.sh b/scripts/bump-version.shnew file mode 100644index 00000000..e9cdaf68--- /dev/null+++ b/scripts/bump-version.sh@@ -0,0 +1,164 @@+#!/usr/bin/env bash+#+# bump-version.sh — Update the version across the entire Colota monorepo.+#+# Usage:+# ./scripts/bump-version.sh <version>+#+# Example:+# ./scripts/bump-version.sh 1.1.0+#+# The script updates:+# - package.json (root)+# - apps/mobile/package.json+# - apps/docs/package.json+# - packages/shared/package.json+# - apps/mobile/android/app/build.gradle (versionName + auto-incremented versionCode)+#+# It does NOT create any git commits or tags.++set -euo pipefail++# ---------------------------------------------------------------------------+# Resolve the repository root (parent of the scripts/ directory)+# ---------------------------------------------------------------------------+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"++# ---------------------------------------------------------------------------+# Validate arguments+# ---------------------------------------------------------------------------+if [[ $# -ne 1 ]]; then+ echo "Usage: $0 <version>"+ echo " version must be in semver format: x.y.z (e.g. 1.2.3)"+ exit 1+fi++NEW_VERSION="$1"++# Validate semver format (major.minor.patch, all non-negative integers)+if ! [[ "$NEW_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ echo "Error: Invalid version format '$NEW_VERSION'."+ echo " Expected semver format: x.y.z (e.g. 1.2.3)"+ exit 1+fi++# ---------------------------------------------------------------------------+# Paths+# ---------------------------------------------------------------------------+ROOT_PKG="$REPO_ROOT/package.json"+MOBILE_PKG="$REPO_ROOT/apps/mobile/package.json"+DOCS_PKG="$REPO_ROOT/apps/docs/package.json"+SHARED_PKG="$REPO_ROOT/packages/shared/package.json"+BUILD_GRADLE="$REPO_ROOT/apps/mobile/android/app/build.gradle"++# ---------------------------------------------------------------------------+# Helper: convert a path to a form that Node.js can use on any OS.+# On Windows (MSYS2/Git Bash) paths like /c/Users/... must become C:/Users/...+# ---------------------------------------------------------------------------+to_node_path() {+ local p="$1"+ # Detect MSYS/Git-Bash style /c/ prefix and convert to C:/+ if [[ "$p" =~ ^/([a-zA-Z])/ ]]; then+ p="${BASH_REMATCH[1]^}:/${p:3}"+ fi+ echo "$p"+}++# ---------------------------------------------------------------------------+# Helper: update "version" in a package.json using node (handles JSON safely)+# ---------------------------------------------------------------------------+update_package_json() {+ local file="$1"+ local version="$2"++ if [[ ! -f "$file" ]]; then+ echo " Warning: $file not found — skipping."+ return+ fi++ local node_file+ node_file=$(to_node_path "$file")++ # Read old version (may be absent)+ local old_version+ old_version=$(node -e "+ const fs = require('fs');+ const pkg = JSON.parse(fs.readFileSync('$node_file', 'utf8'));+ console.log(pkg.version || '(none)');+ " 2>/dev/null) || old_version="(unknown)"++ # Write new version — use a small Node script to preserve formatting+ node -e "+ const fs = require('fs');+ const raw = fs.readFileSync('$node_file', 'utf8');+ const pkg = JSON.parse(raw);+ pkg.version = '$version';+ // Detect indent (default 2 spaces)+ const indent = (raw.match(/^[ \t]+/m) || [' '])[0];+ fs.writeFileSync('$node_file', JSON.stringify(pkg, null, indent) + '\n');+ "++ # Display a relative-ish path for readability+ local display_path="${file#$REPO_ROOT/}"+ echo " $display_path: $old_version -> $version"+}++# ---------------------------------------------------------------------------+# Helper: update versionName and versionCode in build.gradle+# ---------------------------------------------------------------------------+update_build_gradle() {+ local file="$1"+ local version="$2"++ if [[ ! -f "$file" ]]; then+ echo " Warning: $file not found — skipping."+ return+ fi++ # Read current versionName+ local old_version_name+ old_version_name=$(sed -n 's/.*versionName "\(.*\)"/\1/p' "$file" | head -1)++ # Read current versionCode+ local old_version_code+ old_version_code=$(sed -n 's/.*versionCode \([0-9]*\)/\1/p' "$file" | head -1)++ # Compute new versionCode+ local new_version_code=$(( old_version_code + 1 ))++ # Update versionName+ sed -i "s/versionName \"$old_version_name\"/versionName \"$version\"/" "$file"++ # Update versionCode+ sed -i "s/versionCode $old_version_code/versionCode $new_version_code/" "$file"++ local display_path="${file#$REPO_ROOT/}"+ echo " $display_path:"+ echo " versionName: \"$old_version_name\" -> \"$version\""+ echo " versionCode: $old_version_code -> $new_version_code"+}++# ---------------------------------------------------------------------------+# Main+# ---------------------------------------------------------------------------+echo ""+echo "Bumping version to $NEW_VERSION"+echo "================================"+echo ""++echo "Updating package.json files:"+update_package_json "$ROOT_PKG" "$NEW_VERSION"+update_package_json "$MOBILE_PKG" "$NEW_VERSION"+update_package_json "$DOCS_PKG" "$NEW_VERSION"+update_package_json "$SHARED_PKG" "$NEW_VERSION"+echo ""++echo "Updating build.gradle:"+update_build_gradle "$BUILD_GRADLE" "$NEW_VERSION"+echo ""++echo "================================"+echo "Done. Version bumped to $NEW_VERSION."+echo "No git commits or tags were created."+echo ""