Skip to content

Colota - Android GPS Location tracker

feat: share geofences via setup deep link (#337)

Max Dietrich4a5c79930307
diff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.md
index d86b5200..c6a7c35e 100644
--- a/apps/docs/docs/guides/deep-link-setup.md
+++ b/apps/docs/docs/guides/deep-link-setup.md
@@ -52,6 +52,29 @@ The `config` parameter is a base64-encoded JSON object. Only include the setting
| `auth.password` | string | Password for Basic Auth |
| `auth.bearerToken` | string | Token for Bearer Auth |
| `customHeaders` | object | Custom HTTP headers (e.g. Cloudflare Access) |
+| `geofences` | array | Pause zone definitions (see [Geofences](#geofences)) |
+
+### Geofences
+
+Each entry in the `geofences` array describes one pause zone. `name`, `lat`, `lon` and `radius` are required. Other fields fall back to safe defaults.
+
+| Field | Type | Default | Description |
+| -------------------------- | ------- | ---------- | ------------------------------------------------------------ |
+| `name` | string | (required) | Display name |
+| `lat` | number | (required) | Latitude in decimal degrees |
+| `lon` | number | (required) | Longitude in decimal degrees |
+| `radius` | number | (required) | Radius in meters, must be > 0 |
+| `enabled` | boolean | `true` | Zone is active on import |
+| `pauseTracking` | boolean | `false` | Stop saving locations inside the zone |
+| `pauseOnWifi` | boolean | `false` | Also stop GPS while connected to Wi-Fi or Ethernet |
+| `pauseOnMotionless` | boolean | `false` | Also stop GPS after no motion for `motionlessTimeoutMinutes` |
+| `motionlessTimeoutMinutes` | number | `10` | Minutes of stillness before motionless pause kicks in |
+| `heartbeatEnabled` | boolean | `false` | Send periodic location updates while paused |
+| `heartbeatIntervalMinutes` | number | `15` | Heartbeat interval in minutes |
+
+Imported geofences are appended by default. The import confirmation screen has a "Replace zones with the same name" toggle that deletes existing zones whose names match before creating the incoming ones.
+
+You can build links with geofences using the in-browser generator above, the Node.js or Python snippets below, or by sharing zones directly from the Geofences screen in the app (see the [Geofencing](geofencing.md#sharing-zones) guide).
## Generating Links Programmatically
@@ -63,7 +86,10 @@ const config = {
endpoint: 'https://my-server.com/api/locations',
interval: 10,
apiTemplate: 'owntracks',
- auth: { type: 'bearer', bearerToken: 'my-token' }
+ auth: { type: 'bearer', bearerToken: 'my-token' },
+ geofences: [
+ { name: 'Home', lat: 52.52, lon: 13.405, radius: 100, pauseTracking: true }
+ ]
};
const encoded = Buffer.from(JSON.stringify(config)).toString('base64');
console.log('colota://setup?config=' + encoded);
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 1b7dcc87..c3278564 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -53,6 +53,21 @@ When both **WiFi** and **motionless** pause are enabled, GPS only resumes when *
:::
+## Sharing Zones
+
+You can share all your geofences with another device or another user via a setup link instead of recreating zones by hand.
+
+1. Open the **Geofences** screen
+2. Tap the share icon next to "Active Geofences"
+3. The system share sheet opens with a `colota://setup?config=...` link
+4. Send the link through any messenger, email or as a QR code
+
+When the recipient opens the link, Colota shows the import confirmation screen listing every incoming zone. By default, tapping **Apply Configuration** appends the zones to the recipient's existing list. A "Replace zones with the same name" toggle on the confirmation screen swaps incoming zones for any existing zones whose names match - the original zones are deleted before the new ones are created.
+
+The share button is all-or-nothing - every zone in the list is included. The `id`, `createdAt` and `enabled` fields are stripped, so imported zones always start enabled and get fresh database entries on the recipient's device.
+
+See the [Deep Link Setup](deep-link-setup.md#geofences) guide for the full payload format.
+
## How It Works
- Zone detection uses the Haversine formula (1-2ms per check)
diff --git a/apps/docs/src/components/DeepLinkGenerator.module.css b/apps/docs/src/components/DeepLinkGenerator.module.css
index b0cc4bc5..e8a38e44 100644
--- a/apps/docs/src/components/DeepLinkGenerator.module.css
+++ b/apps/docs/src/components/DeepLinkGenerator.module.css
@@ -128,6 +128,50 @@
margin-top: 0.25rem;
}
+.geofenceCard {
+ border: 1px solid var(--colota-border);
+ border-radius: 8px;
+ padding: 0.75rem;
+ margin-bottom: 0.5rem;
+}
+
+.geofenceFlags {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ flex-wrap: wrap;
+ margin-bottom: 0.5rem;
+}
+
+.geofenceFlags .checkbox {
+ margin-bottom: 0;
+}
+
+.conditionalRow {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ margin-bottom: 0.5rem;
+}
+
+.conditionalRow > * {
+ flex: 1;
+}
+
+.conditionalRow .checkbox {
+ margin-bottom: 0;
+}
+
+.hidden {
+ visibility: hidden;
+}
+
+.geofenceActions {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 0.25rem;
+}
+
.addBtn:hover {
background: rgba(13, 148, 136, 0.05);
border-color: var(--ifm-color-primary);
diff --git a/apps/docs/src/components/DeepLinkGenerator.tsx b/apps/docs/src/components/DeepLinkGenerator.tsx
index f9ac132a..ee14d2d7 100644
--- a/apps/docs/src/components/DeepLinkGenerator.tsx
+++ b/apps/docs/src/components/DeepLinkGenerator.tsx
@@ -6,6 +6,19 @@ interface KeyValue {
value: string
}
+interface GeofenceRow {
+ name: string
+ lat: string
+ lon: string
+ radius: string
+ pauseTracking: boolean
+ pauseOnWifi: boolean
+ pauseOnMotionless: boolean
+ motionlessTimeoutMinutes: string
+ heartbeatEnabled: boolean
+ heartbeatIntervalMinutes: string
+}
+
const API_TEMPLATES = ["custom", "dawarich", "geopulse", "owntracks", "phonetrack", "reitti", "traccar"] as const
const AUTH_TYPES = ["none", "basic", "bearer"] as const
const SYNC_CONDITIONS = ["any", "wifi_any", "wifi_ssid", "vpn"] as const
@@ -43,6 +56,9 @@ export default function DeepLinkGenerator() {
// Custom headers
const [customHeaders, setCustomHeaders] = useState<KeyValue[]>([])
+ // Geofences
+ const [geofences, setGeofences] = useState<GeofenceRow[]>([])
+
// QR
const qrRef = useRef<HTMLDivElement>(null)
const [qrLib, setQrLib] = useState<any>(null)
@@ -96,6 +112,33 @@ export default function DeepLinkGenerator() {
}
if (Object.keys(ch).length > 0) obj.customHeaders = ch
+ const gfs = geofences
+ .filter((g) => g.name && g.lat && g.lon && g.radius && Number(g.radius) > 0)
+ .map((g) => {
+ const entry: Record<string, unknown> = {
+ name: g.name,
+ lat: Number(g.lat),
+ lon: Number(g.lon),
+ radius: Number(g.radius)
+ }
+ if (g.pauseTracking) entry.pauseTracking = true
+ if (g.pauseOnWifi) entry.pauseOnWifi = true
+ if (g.pauseOnMotionless) {
+ entry.pauseOnMotionless = true
+ if (g.motionlessTimeoutMinutes && Number(g.motionlessTimeoutMinutes) > 0) {
+ entry.motionlessTimeoutMinutes = Number(g.motionlessTimeoutMinutes)
+ }
+ }
+ if (g.heartbeatEnabled) {
+ entry.heartbeatEnabled = true
+ if (g.heartbeatIntervalMinutes && Number(g.heartbeatIntervalMinutes) > 0) {
+ entry.heartbeatIntervalMinutes = Number(g.heartbeatIntervalMinutes)
+ }
+ }
+ return entry
+ })
+ if (gfs.length > 0) obj.geofences = gfs
+
return obj
}, [
endpoint,
@@ -115,7 +158,8 @@ export default function DeepLinkGenerator() {
authBearerToken,
fieldMapEntries,
customFields,
- customHeaders
+ customHeaders,
+ geofences
])
const isEmpty = Object.keys(config).length === 0
@@ -179,6 +223,34 @@ export default function DeepLinkGenerator() {
setList(list.filter((_, i) => i !== index))
}
+ const updateGeofence = <K extends keyof GeofenceRow>(index: number, field: K, val: GeofenceRow[K]) => {
+ const next = [...geofences]
+ next[index] = { ...next[index], [field]: val }
+ setGeofences(next)
+ }
+
+ const removeGeofence = (index: number) => {
+ setGeofences(geofences.filter((_, i) => i !== index))
+ }
+
+ const addGeofence = () => {
+ setGeofences([
+ ...geofences,
+ {
+ name: "",
+ lat: "",
+ lon: "",
+ radius: "",
+ pauseTracking: true,
+ pauseOnWifi: false,
+ pauseOnMotionless: false,
+ motionlessTimeoutMinutes: "",
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: ""
+ }
+ ])
+ }
+
return (
<div className={styles.generator}>
{/* Connection */}
@@ -286,6 +358,14 @@ export default function DeepLinkGenerator() {
onChange={(e) => setSyncInterval(e.target.value)}
/>
</div>
+ <div className={styles.field}>
+ <label className={styles.label}>Offline mode</label>
+ <select className={styles.select} value={isOfflineMode} onChange={(e) => setIsOfflineMode(e.target.value)}>
+ <option value="">-- not set --</option>
+ <option value="true">Enabled</option>
+ <option value="false">Disabled</option>
+ </select>
+ </div>
</div>
<div className={styles.row}>
<div className={styles.field}>
@@ -311,14 +391,6 @@ export default function DeepLinkGenerator() {
</div>
)}
</div>
- <div className={styles.field}>
- <label className={styles.label}>Offline mode</label>
- <select className={styles.select} value={isOfflineMode} onChange={(e) => setIsOfflineMode(e.target.value)}>
- <option value="">-- not set --</option>
- <option value="true">Enabled</option>
- <option value="false">Disabled</option>
- </select>
- </div>
</div>
{/* Auth */}
@@ -456,6 +528,129 @@ export default function DeepLinkGenerator() {
</button>
</div>
+ {/* Geofences */}
+ <div className={styles.section}>
+ <div className={styles.sectionTitle}>Geofences</div>
+ <div className={styles.keyValueList}>
+ {geofences.map((g, i) => (
+ <div key={i} className={styles.geofenceCard}>
+ <div className={styles.row}>
+ <div className={styles.field}>
+ <label className={styles.label}>Name</label>
+ <input
+ className={styles.input}
+ placeholder="Home"
+ value={g.name}
+ onChange={(e) => updateGeofence(i, "name", e.target.value)}
+ />
+ </div>
+ <div className={styles.field}>
+ <label className={styles.label}>Radius (m)</label>
+ <input
+ className={styles.input}
+ type="number"
+ min="1"
+ placeholder="100"
+ value={g.radius}
+ onChange={(e) => updateGeofence(i, "radius", e.target.value)}
+ />
+ </div>
+ </div>
+ <div className={styles.row}>
+ <div className={styles.field}>
+ <label className={styles.label}>Latitude</label>
+ <input
+ className={styles.input}
+ type="number"
+ step="any"
+ placeholder="52.52"
+ value={g.lat}
+ onChange={(e) => updateGeofence(i, "lat", e.target.value)}
+ />
+ </div>
+ <div className={styles.field}>
+ <label className={styles.label}>Longitude</label>
+ <input
+ className={styles.input}
+ type="number"
+ step="any"
+ placeholder="13.405"
+ value={g.lon}
+ onChange={(e) => updateGeofence(i, "lon", e.target.value)}
+ />
+ </div>
+ </div>
+ <div className={styles.geofenceFlags}>
+ <label className={styles.checkbox}>
+ <input
+ type="checkbox"
+ checked={g.pauseTracking}
+ onChange={(e) => updateGeofence(i, "pauseTracking", e.target.checked)}
+ />
+ Pause tracking
+ </label>
+ <label className={styles.checkbox}>
+ <input
+ type="checkbox"
+ checked={g.pauseOnWifi}
+ onChange={(e) => updateGeofence(i, "pauseOnWifi", e.target.checked)}
+ />
+ Pause on Wi-Fi
+ </label>
+ </div>
+ <div className={styles.conditionalRow}>
+ <label className={styles.checkbox}>
+ <input
+ type="checkbox"
+ checked={g.pauseOnMotionless}
+ onChange={(e) => updateGeofence(i, "pauseOnMotionless", e.target.checked)}
+ />
+ Pause when motionless
+ </label>
+ <input
+ className={`${styles.input} ${!g.pauseOnMotionless ? styles.hidden : ""}`}
+ type="number"
+ min="1"
+ placeholder="Timeout in min (default 10)"
+ value={g.motionlessTimeoutMinutes}
+ onChange={(e) => updateGeofence(i, "motionlessTimeoutMinutes", e.target.value)}
+ aria-hidden={!g.pauseOnMotionless}
+ tabIndex={g.pauseOnMotionless ? 0 : -1}
+ />
+ </div>
+ <div className={styles.conditionalRow}>
+ <label className={styles.checkbox}>
+ <input
+ type="checkbox"
+ checked={g.heartbeatEnabled}
+ onChange={(e) => updateGeofence(i, "heartbeatEnabled", e.target.checked)}
+ />
+ Stationary heartbeat
+ </label>
+ <input
+ className={`${styles.input} ${!g.heartbeatEnabled ? styles.hidden : ""}`}
+ type="number"
+ min="1"
+ placeholder="Interval in min (default 15)"
+ value={g.heartbeatIntervalMinutes}
+ onChange={(e) => updateGeofence(i, "heartbeatIntervalMinutes", e.target.value)}
+ aria-hidden={!g.heartbeatEnabled}
+ tabIndex={g.heartbeatEnabled ? 0 : -1}
+ />
+ </div>
+ <div className={styles.geofenceActions}>
+ <button className={styles.removeBtn} onClick={() => removeGeofence(i)}>
+ x
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ <button className={styles.addBtn} onClick={addGeofence}>
+ + Add geofence
+ </button>
+ </div>
+
{/* Output */}
<hr className={styles.divider} />
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 2abb3334..3000de4c 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -4,14 +4,14 @@
*/
import React, { useState, useEffect, useRef, useMemo, useCallback } from "react"
-import { View, Text, StyleSheet, TextInput, Pressable, FlatList, DeviceEventEmitter } from "react-native"
+import { View, Text, StyleSheet, TextInput, Pressable, FlatList, DeviceEventEmitter, Share } from "react-native"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
import { showAlert } from "../services/modalService"
import { Geofence, ScreenProps } from "../types/global"
import { useTracking, useCoords } from "../contexts/TrackingProvider"
import { fonts } from "../styles/typography"
-import { ChevronRight, Wifi, PersonStanding, MapPinHouse } from "lucide-react-native"
+import { ChevronRight, Wifi, PersonStanding, MapPinHouse, Share2 } from "lucide-react-native"
import { Container, SectionTitle, Card } from "../components"
import {
DEFAULT_MAP_ZOOM,
@@ -229,6 +229,19 @@ export function GeofenceScreen({ navigation }: ScreenProps) {
setFocusRequest({ geofence: item, key: ++focusKeyRef.current })
}, [])
+ const handleShareGeofences = useCallback(async () => {
+ if (geofences.length === 0) return
+ try {
+ const exportable = geofences.map(({ id: _id, createdAt: _createdAt, enabled: _enabled, ...rest }) => rest)
+ const encoded = btoa(JSON.stringify({ geofences: exportable }))
+ const link = `colota://setup?config=${encoded}`
+ await Share.share({ message: link })
+ } catch (err) {
+ logger.error("[GeofenceScreen] Failed to share geofences:", err)
+ showAlert("Error", "Failed to share geofences.", "error")
+ }
+ }, [geofences])
+
const geofenceData = useMemo(() => buildGeofencesGeoJSON(geofences, colors), [geofences, colors])
const renderItem = useCallback(
@@ -348,7 +361,19 @@ export function GeofenceScreen({ navigation }: ScreenProps) {
</Card>
</View>
- {geofences.length > 0 && <SectionTitle>Active Geofences ({geofences.length})</SectionTitle>}
+ {geofences.length > 0 && (
+ <View style={styles.activeHeader}>
+ <SectionTitle>Active Geofences ({geofences.length})</SectionTitle>
+ <Pressable
+ testID="share-geofences-btn"
+ onPress={handleShareGeofences}
+ hitSlop={HIT_SLOP_MD}
+ style={({ pressed }) => [styles.shareBtn, pressed && { opacity: colors.pressedOpacity }]}
+ >
+ <Share2 size={20} color={colors.textSecondary} />
+ </Pressable>
+ </View>
+ )}
</>
}
ListEmptyComponent={
@@ -401,6 +426,8 @@ const styles = StyleSheet.create({
justifyContent: "space-between"
},
zoomBtn: { padding: 4, marginRight: 16 },
+ activeHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
+ shareBtn: { padding: 4, marginBottom: 12 },
editBtn: { flex: 1, flexDirection: "row", alignItems: "center" },
info: { flex: 1, marginRight: 12 },
name: { fontSize: 15, ...fonts.semiBold, marginBottom: 2 },
diff --git a/apps/mobile/src/screens/SetupImportScreen.tsx b/apps/mobile/src/screens/SetupImportScreen.tsx
index 3a0594c4..95787734 100644
--- a/apps/mobile/src/screens/SetupImportScreen.tsx
+++ b/apps/mobile/src/screens/SetupImportScreen.tsx
@@ -4,7 +4,7 @@
*/
import React, { useState, useMemo } from "react"
-import { View, Text, ScrollView, StyleSheet } from "react-native"
+import { View, Text, ScrollView, StyleSheet, Switch } from "react-native"
import { useTheme } from "../hooks/useTheme"
import { useTracking } from "../contexts/TrackingProvider"
import { Container, Card, Button, SectionTitle } from "../components"
@@ -25,9 +25,12 @@ import {
type ApiTemplateName,
type HttpMethod,
type SelectablePreset,
- type SyncPreset
+ type SyncPreset,
+ type Geofence
} from "../types/global"
+type ImportGeofence = Omit<Geofence, "id" | "createdAt">
+
// ============================================================================
// TYPES
// ============================================================================
@@ -35,12 +38,13 @@ import {
interface ParsedConfig {
settings: Partial<Settings>
auth: Partial<AuthConfig> | null
+ geofences: ImportGeofence[]
}
interface ConfigEntry {
label: string
value: string
- category: "tracking" | "api" | "auth"
+ category: "tracking" | "api" | "auth" | "geofence"
rejected?: boolean
}
@@ -83,7 +87,12 @@ function detectPreset(settings: Partial<Settings>): SyncPreset {
function validateConfig(raw: unknown): ValidationResult {
if (!raw || typeof raw !== "object") {
- return { valid: false, config: { settings: {}, auth: null }, entries: [], error: "Invalid configuration format" }
+ return {
+ valid: false,
+ config: { settings: {}, auth: null, geofences: [] },
+ entries: [],
+ error: "Invalid configuration format"
+ }
}
const obj = raw as Record<string, unknown>
@@ -251,11 +260,51 @@ function validateConfig(raw: unknown): ValidationResult {
}
}
+ // --- Geofences ---
+
+ const geofences: ImportGeofence[] = []
+
+ if ("geofences" in obj && Array.isArray(obj.geofences)) {
+ for (const entry of obj.geofences) {
+ if (!entry || typeof entry !== "object") continue
+ const g = entry as Record<string, unknown>
+ if (
+ typeof g.name !== "string" ||
+ g.name.length === 0 ||
+ typeof g.lat !== "number" ||
+ typeof g.lon !== "number" ||
+ typeof g.radius !== "number" ||
+ g.radius <= 0
+ ) {
+ continue
+ }
+ geofences.push({
+ name: g.name,
+ lat: g.lat,
+ lon: g.lon,
+ radius: g.radius,
+ enabled: typeof g.enabled === "boolean" ? g.enabled : true,
+ pauseTracking: typeof g.pauseTracking === "boolean" ? g.pauseTracking : false,
+ pauseOnWifi: typeof g.pauseOnWifi === "boolean" ? g.pauseOnWifi : false,
+ pauseOnMotionless: typeof g.pauseOnMotionless === "boolean" ? g.pauseOnMotionless : false,
+ motionlessTimeoutMinutes: typeof g.motionlessTimeoutMinutes === "number" ? g.motionlessTimeoutMinutes : 10,
+ heartbeatEnabled: typeof g.heartbeatEnabled === "boolean" ? g.heartbeatEnabled : false,
+ heartbeatIntervalMinutes: typeof g.heartbeatIntervalMinutes === "number" ? g.heartbeatIntervalMinutes : 15
+ })
+ entries.push({ label: g.name, value: `${g.radius}m`, category: "geofence" })
+ }
+ }
+
if (entries.length === 0) {
- return { valid: false, config: { settings, auth }, entries, error: "No valid settings found in configuration" }
+ return {
+ valid: false,
+ config: { settings, auth, geofences },
+ entries,
+ error: "No valid settings found in configuration"
+ }
}
- return { valid: true, config: { settings, auth }, entries }
+ return { valid: true, config: { settings, auth, geofences }, entries }
}
// ============================================================================
@@ -266,6 +315,7 @@ export function SetupImportScreen({ route, navigation }: any) {
const { colors } = useTheme()
const { settings: currentSettings, setSettings } = useTracking()
const [applying, setApplying] = useState(false)
+ const [replaceByName, setReplaceByName] = useState(false)
const result = useMemo(() => {
try {
@@ -273,7 +323,7 @@ export function SetupImportScreen({ route, navigation }: any) {
if (!configParam || typeof configParam !== "string") {
return {
valid: false,
- config: { settings: {}, auth: null },
+ config: { settings: {}, auth: null, geofences: [] },
entries: [],
error: "No configuration data in URL"
} as ValidationResult
@@ -286,7 +336,7 @@ export function SetupImportScreen({ route, navigation }: any) {
logger.error("[SetupImport] Failed to parse config:", e)
return {
valid: false,
- config: { settings: {}, auth: null },
+ config: { settings: {}, auth: null, geofences: [] },
entries: [],
error: "Invalid configuration data. The URL may be malformed."
} as ValidationResult
@@ -296,6 +346,7 @@ export function SetupImportScreen({ route, navigation }: any) {
const trackingEntries = result.entries.filter((e) => e.category === "tracking")
const apiEntries = result.entries.filter((e) => e.category === "api")
const authEntries = result.entries.filter((e) => e.category === "auth")
+ const geofenceEntries = result.entries.filter((e) => e.category === "geofence")
const handleApply = async () => {
setApplying(true)
@@ -311,7 +362,7 @@ export function SetupImportScreen({ route, navigation }: any) {
await SettingsService.updateMultiple(merged)
await setSettings(merged)
- // Apply auth — deep merge customHeaders
+ // Apply auth - deep merge customHeaders
if (result.config.auth) {
const currentAuth = await NativeLocationService.getAuthConfig()
const mergedAuth = { ...currentAuth, ...result.config.auth }
@@ -321,6 +372,27 @@ export function SetupImportScreen({ route, navigation }: any) {
await NativeLocationService.saveAuthConfig(mergedAuth)
}
+ // Apply geofences. Default is append-only (may create duplicates by name).
+ // When replaceByName is on, existing zones with matching names are deleted first.
+ if (result.config.geofences.length > 0) {
+ const existingByName = replaceByName
+ ? new Map(
+ (await NativeLocationService.getGeofences())
+ .filter((g) => typeof g.id === "number")
+ .map((g) => [g.name, g.id as number])
+ )
+ : null
+ for (const g of result.config.geofences) {
+ if (existingByName) {
+ const existingId = existingByName.get(g.name)
+ if (existingId !== undefined) {
+ await NativeLocationService.deleteGeofence(existingId)
+ }
+ }
+ await NativeLocationService.createGeofence(g)
+ }
+ }
+
showAlert("Configuration Applied", "Settings have been updated successfully.", "success")
navigation.navigate("Dashboard")
} catch (e) {
@@ -405,6 +477,23 @@ export function SetupImportScreen({ route, navigation }: any) {
{renderSection("TRACKING", trackingEntries)}
{renderSection("API", apiEntries)}
{renderSection("AUTHENTICATION", authEntries)}
+ {renderSection("GEOFENCES", geofenceEntries)}
+
+ {geofenceEntries.length > 0 && (
+ <View style={styles.section}>
+ <Card>
+ <View style={styles.toggleRow}>
+ <View style={styles.toggleText}>
+ <Text style={[styles.toggleLabel, { color: colors.text }]}>Replace zones with the same name</Text>
+ <Text style={[styles.toggleHint, { color: colors.textSecondary }]}>
+ Off: imports are added as new entries
+ </Text>
+ </View>
+ <Switch testID="replace-geofences-switch" value={replaceByName} onValueChange={setReplaceByName} />
+ </View>
+ </Card>
+ </View>
+ )}
<View style={styles.actions}>
<Button
@@ -467,6 +556,24 @@ const styles = StyleSheet.create({
fontSize: 13,
...fonts.semiBold
},
+ toggleRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ paddingVertical: 6,
+ gap: 12
+ },
+ toggleText: {
+ flex: 1
+ },
+ toggleLabel: {
+ fontSize: 13,
+ ...fonts.semiBold
+ },
+ toggleHint: {
+ fontSize: 12,
+ ...fonts.regular,
+ marginTop: 2
+ },
settingValue: {
fontSize: 13,
...fonts.regular,
diff --git a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
index 4f7aa103..cece37ca 100644
--- a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
@@ -1,5 +1,6 @@
import React from "react"
import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { Share } from "react-native"
import { Geofence } from "../../types/global"
// --- Mocks ---
@@ -141,7 +142,8 @@ jest.mock("lucide-react-native", () => {
ChevronRight: (props: any) => R.createElement(Text, props, "ChevronRight"),
Wifi: (props: any) => R.createElement(Text, props, "Wifi"),
PersonStanding: (props: any) => R.createElement(Text, props, "PersonStanding"),
- MapPinHouse: (props: any) => R.createElement(Text, props, "MapPinHouse")
+ MapPinHouse: (props: any) => R.createElement(Text, props, "MapPinHouse"),
+ Share2: (props: any) => R.createElement(Text, props, "Share2")
}
})
@@ -278,4 +280,106 @@ describe("GeofenceScreen", () => {
expect(mockNavigate).toHaveBeenCalledWith("Geofence Editor", { geofenceId: 1 })
})
+
+ describe("share geofences", () => {
+ let shareSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ shareSpy = jest.spyOn(Share, "share").mockResolvedValue({ action: "sharedAction" })
+ })
+
+ afterEach(() => {
+ shareSpy.mockRestore()
+ })
+
+ it("does not render the share button when there are no geofences", async () => {
+ const { queryByTestId, getByText } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByText("No geofences yet")).toBeTruthy()
+ })
+
+ expect(queryByTestId("share-geofences-btn")).toBeNull()
+ })
+
+ it("renders the share button when at least one geofence exists", async () => {
+ mockGetGeofences.mockResolvedValue(mockGeofences)
+ const { getByTestId } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByTestId("share-geofences-btn")).toBeTruthy()
+ })
+ })
+
+ it("opens the share sheet with a colota://setup link on press", async () => {
+ mockGetGeofences.mockResolvedValue(mockGeofences)
+ const { getByTestId } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByTestId("share-geofences-btn")).toBeTruthy()
+ })
+
+ fireEvent.press(getByTestId("share-geofences-btn"))
+
+ await waitFor(() => {
+ expect(shareSpy).toHaveBeenCalledTimes(1)
+ })
+
+ const arg = shareSpy.mock.calls[0][0]
+ expect(arg.message).toMatch(/^colota:\/\/setup\?config=/)
+ })
+
+ it("encodes geofences without id, createdAt, or enabled fields", async () => {
+ mockGetGeofences.mockResolvedValue(mockGeofences)
+ const { getByTestId } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByTestId("share-geofences-btn")).toBeTruthy()
+ })
+
+ fireEvent.press(getByTestId("share-geofences-btn"))
+
+ await waitFor(() => {
+ expect(shareSpy).toHaveBeenCalledTimes(1)
+ })
+
+ const link = shareSpy.mock.calls[0][0].message as string
+ const encoded = link.split("config=")[1]
+ const decoded = JSON.parse(atob(encoded))
+
+ expect(decoded.geofences).toHaveLength(2)
+ expect(decoded.geofences[0]).toEqual({
+ name: "Home",
+ lat: 48.1,
+ lon: 11.5,
+ radius: 100,
+ pauseTracking: true,
+ pauseOnWifi: false,
+ pauseOnMotionless: false,
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
+ })
+ expect(decoded.geofences[0]).not.toHaveProperty("id")
+ expect(decoded.geofences[0]).not.toHaveProperty("createdAt")
+ expect(decoded.geofences[0]).not.toHaveProperty("enabled")
+ })
+
+ it("shows an error alert when sharing fails", async () => {
+ mockGetGeofences.mockResolvedValue(mockGeofences)
+ shareSpy.mockRejectedValueOnce(new Error("share failed"))
+
+ const { getByTestId } = renderScreen()
+
+ await waitFor(() => {
+ expect(getByTestId("share-geofences-btn")).toBeTruthy()
+ })
+
+ fireEvent.press(getByTestId("share-geofences-btn"))
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to share geofences.", "error")
+ })
+ })
+ })
})
diff --git a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
index 60b90926..fa6d586c 100644
--- a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
@@ -8,6 +8,9 @@ const mockSetSettings = jest.fn().mockResolvedValue(undefined)
const mockSaveSetting = jest.fn().mockResolvedValue(undefined)
const mockGetAuthConfig = jest.fn().mockResolvedValue({ ...DEFAULT_AUTH_CONFIG })
const mockSaveAuthConfig = jest.fn().mockResolvedValue(true)
+const mockCreateGeofence = jest.fn().mockResolvedValue(1)
+const mockGetGeofences = jest.fn().mockResolvedValue([])
+const mockDeleteGeofence = jest.fn().mockResolvedValue(true)
const mockNavigate = jest.fn()
const mockShowAlert = jest.fn()
@@ -16,7 +19,10 @@ jest.mock("../../services/NativeLocationService", () => ({
default: {
getAuthConfig: (...args: any[]) => mockGetAuthConfig(...args),
saveAuthConfig: (...args: any[]) => mockSaveAuthConfig(...args),
- saveSetting: (...args: any[]) => mockSaveSetting(...args)
+ saveSetting: (...args: any[]) => mockSaveSetting(...args),
+ createGeofence: (...args: any[]) => mockCreateGeofence(...args),
+ getGeofences: (...args: any[]) => mockGetGeofences(...args),
+ deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args)
}
}))
@@ -279,4 +285,208 @@ describe("SetupImportScreen", () => {
expect(mockNavigate).toHaveBeenCalledWith("Dashboard")
})
})
+
+ describe("geofences", () => {
+ const validGeofence = { name: "Home", lat: 52.5, lon: 13.4, radius: 100 }
+
+ it("parses a valid geofence and shows it under GEOFENCES", () => {
+ const { getByText } = renderScreen(encode({ geofences: [validGeofence] }))
+ expect(getByText("GEOFENCES")).toBeTruthy()
+ expect(getByText("Home")).toBeTruthy()
+ expect(getByText("100m")).toBeTruthy()
+ })
+
+ it("rejects a geofence missing required fields", () => {
+ const { getByText } = renderScreen(encode({ geofences: [{ name: "X", lat: 52.5 }] }))
+ expect(getByText("Invalid Configuration")).toBeTruthy()
+ })
+
+ it("rejects a geofence with non-positive radius", () => {
+ const { getByText } = renderScreen(encode({ geofences: [{ ...validGeofence, radius: 0 }] }))
+ expect(getByText("Invalid Configuration")).toBeTruthy()
+ })
+
+ it("skips invalid entries but keeps valid ones", () => {
+ const config = {
+ geofences: [{ name: "X", lat: 52.5 }, validGeofence]
+ }
+ const { getByText, queryByText } = renderScreen(encode(config))
+ expect(getByText("Home")).toBeTruthy()
+ expect(queryByText("X")).toBeNull()
+ })
+
+ it("calls createGeofence on apply with defaults filled in", async () => {
+ const { getByText } = renderScreen(encode({ geofences: [validGeofence] }))
+
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
+ })
+ expect(mockCreateGeofence).toHaveBeenCalledWith({
+ name: "Home",
+ lat: 52.5,
+ lon: 13.4,
+ radius: 100,
+ enabled: true,
+ pauseTracking: false,
+ pauseOnWifi: false,
+ pauseOnMotionless: false,
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
+ })
+ })
+
+ it("preserves explicit boolean and numeric flags", async () => {
+ const config = {
+ geofences: [
+ {
+ ...validGeofence,
+ pauseTracking: true,
+ pauseOnWifi: true,
+ pauseOnMotionless: true,
+ motionlessTimeoutMinutes: 5,
+ heartbeatEnabled: true,
+ heartbeatIntervalMinutes: 30,
+ enabled: false
+ }
+ ]
+ }
+ const { getByText } = renderScreen(encode(config))
+
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
+ })
+ expect(mockCreateGeofence).toHaveBeenCalledWith(
+ expect.objectContaining({
+ pauseTracking: true,
+ pauseOnWifi: true,
+ pauseOnMotionless: true,
+ motionlessTimeoutMinutes: 5,
+ heartbeatEnabled: true,
+ heartbeatIntervalMinutes: 30,
+ enabled: false
+ })
+ )
+ })
+
+ it("creates multiple geofences in order", async () => {
+ const config = {
+ geofences: [
+ { name: "Home", lat: 52.5, lon: 13.4, radius: 100 },
+ { name: "Office", lat: 52.6, lon: 13.5, radius: 200 }
+ ]
+ }
+ const { getByText } = renderScreen(encode(config))
+
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockCreateGeofence).toHaveBeenCalledTimes(2)
+ })
+ expect(mockCreateGeofence.mock.calls[0][0].name).toBe("Home")
+ expect(mockCreateGeofence.mock.calls[1][0].name).toBe("Office")
+ })
+
+ it("does not call createGeofence when no geofences in config", async () => {
+ const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))
+
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Configuration Applied", expect.any(String), "success")
+ })
+ expect(mockCreateGeofence).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("replace geofences toggle", () => {
+ const validGeofence = { name: "Home", lat: 52.5, lon: 13.4, radius: 100 }
+
+ beforeEach(() => {
+ mockGetGeofences.mockReset()
+ mockGetGeofences.mockResolvedValue([])
+ mockDeleteGeofence.mockReset()
+ mockDeleteGeofence.mockResolvedValue(true)
+ })
+
+ it("hides the toggle when no geofences are in the import", () => {
+ const { queryByTestId } = renderScreen(encode({ endpoint: "https://test.com" }))
+ expect(queryByTestId("replace-geofences-switch")).toBeNull()
+ })
+
+ it("shows the toggle when geofences are in the import", () => {
+ const { getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))
+ expect(getByTestId("replace-geofences-switch")).toBeTruthy()
+ })
+
+ it("does not delete existing zones when toggle is off (default)", async () => {
+ mockGetGeofences.mockResolvedValueOnce([{ id: 7, name: "Home", lat: 0, lon: 0, radius: 50, enabled: true }])
+ const { getByText } = renderScreen(encode({ geofences: [validGeofence] }))
+
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
+ })
+ expect(mockGetGeofences).not.toHaveBeenCalled()
+ expect(mockDeleteGeofence).not.toHaveBeenCalled()
+ })
+
+ it("deletes matching zones before creating when toggle is on", async () => {
+ mockGetGeofences.mockResolvedValueOnce([
+ { id: 7, name: "Home", lat: 0, lon: 0, radius: 50, enabled: true },
+ { id: 8, name: "Other", lat: 0, lon: 0, radius: 50, enabled: true }
+ ])
+ const { getByText, getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))
+
+ fireEvent(getByTestId("replace-geofences-switch"), "valueChange", true)
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
+ })
+ expect(mockDeleteGeofence).toHaveBeenCalledTimes(1)
+ expect(mockDeleteGeofence).toHaveBeenCalledWith(7)
+ })
+
+ it("creates without delete when toggle is on but no name match exists", async () => {
+ mockGetGeofences.mockResolvedValueOnce([{ id: 8, name: "Other", lat: 0, lon: 0, radius: 50, enabled: true }])
+ const { getByText, getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))
+
+ fireEvent(getByTestId("replace-geofences-switch"), "valueChange", true)
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockCreateGeofence).toHaveBeenCalledTimes(1)
+ })
+ expect(mockDeleteGeofence).not.toHaveBeenCalled()
+ })
+
+ it("only fetches existing zones once when replacing multiple imports", async () => {
+ mockGetGeofences.mockResolvedValueOnce([
+ { id: 7, name: "Home", lat: 0, lon: 0, radius: 50, enabled: true },
+ { id: 8, name: "Office", lat: 0, lon: 0, radius: 50, enabled: true }
+ ])
+ const config = {
+ geofences: [
+ { name: "Home", lat: 52.5, lon: 13.4, radius: 100 },
+ { name: "Office", lat: 52.6, lon: 13.5, radius: 200 }
+ ]
+ }
+ const { getByText, getByTestId } = renderScreen(encode(config))
+
+ fireEvent(getByTestId("replace-geofences-switch"), "valueChange", true)
+ fireEvent.press(getByText("Apply Configuration"))
+
+ await waitFor(() => {
+ expect(mockCreateGeofence).toHaveBeenCalledTimes(2)
+ })
+ expect(mockGetGeofences).toHaveBeenCalledTimes(1)
+ expect(mockDeleteGeofence).toHaveBeenCalledTimes(2)
+ })
+ })
})