Colota - Android GPS Location tracker
feat: include tracking profiles in setup deep link
Max Dietrichdafd8f8d1e1b
diff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.mdindex 0931fe00..85713682 100644--- a/apps/docs/docs/guides/deep-link-setup.md+++ b/apps/docs/docs/guides/deep-link-setup.md@@ -55,6 +55,7 @@ The `config` parameter is a base64-encoded JSON object. Only include the setting| `auth.bearerToken` | string | Token for Bearer Auth || `customHeaders` | object | Custom HTTP headers (e.g. Cloudflare Access) || `geofences` | array | Pause zone definitions (see [Geofences](#geofences)) |+| `profiles` | array | Tracking profile definitions (see [Tracking Profiles](#tracking-profiles)) |### Geofences@@ -78,6 +79,26 @@ Imported geofences are appended by default. The import confirmation screen has aYou 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).+### Tracking Profiles++Each entry in the `profiles` array describes one [tracking profile](tracking-profiles.md). `name`, `interval`, `distance`, `syncInterval` and `condition` are required. Other fields fall back to safe defaults. `id` and `createdAt` are ignored on import - the receiving device always creates fresh rows.++| Field | Type | Default | Description |+| --- | --- | --- | --- |+| `name` | string | (required) | Display name |+| `interval` | number | (required) | GPS interval in seconds (must be >= 1) |+| `distance` | number | (required) | Movement threshold in meters |+| `syncInterval` | number | (required) | Sync interval in seconds (0 = instant) |+| `condition.type` | string | (required) | `charging`, `android_auto`, `speed_above`, `speed_below`, or `stationary` |+| `condition.speedThreshold` | number | - | Required for `speed_above` / `speed_below`. Speed in m/s (divide km/h by 3.6) |+| `priority` | number | `10` | Higher value wins when multiple profiles match |+| `deactivationDelay` | number | `60` | Seconds to keep the profile active after the condition stops matching |+| `enabled` | boolean | `true` | Profile is active on import |++Imported profiles are appended by default. When both profiles and geofences are present the same "Replace ... with the same name" toggle on the import screen also deletes existing profiles whose names match before creating the incoming ones.++You can build links with profiles using the in-browser generator above, the Node.js or Python snippets below, or by sharing profiles directly from the Tracking Profiles screen in the app.+## Generating Links Programmatically### Using Node.jsdiff --git a/apps/docs/src/components/DeepLinkGenerator.module.css b/apps/docs/src/components/DeepLinkGenerator.module.cssindex e8a38e44..0afe9da1 100644--- a/apps/docs/src/components/DeepLinkGenerator.module.css+++ b/apps/docs/src/components/DeepLinkGenerator.module.css@@ -248,8 +248,24 @@}.qrContainer canvas {- max-width: 200px;- max-height: 200px;+ width: 100%;+ max-width: 400px;+ height: auto;+ image-rendering: pixelated;+}++.qrWarning {+ display: flex;+ flex-direction: column;+ gap: 0.35rem;+ padding: 0.85rem 1rem;+ margin-top: 0.75rem;+ background: var(--ifm-color-warning-contrast-background, #fff8e1);+ border: 1px solid var(--ifm-color-warning, #f59e0b);+ border-radius: 8px;+ color: var(--ifm-color-warning-contrast-foreground, #78350f);+ font-size: 0.9rem;+ line-height: 1.4;}.empty {diff --git a/apps/docs/src/components/DeepLinkGenerator.tsx b/apps/docs/src/components/DeepLinkGenerator.tsxindex e496ebdd..49db07ee 100644--- a/apps/docs/src/components/DeepLinkGenerator.tsx+++ b/apps/docs/src/components/DeepLinkGenerator.tsx@@ -19,6 +19,31 @@ interface GeofenceRow {heartbeatIntervalMinutes: string}+type ProfileConditionType = "charging" | "android_auto" | "speed_above" | "speed_below" | "stationary"++interface ProfileRow {+ name: string+ conditionType: ProfileConditionType+ speedKmh: string+ interval: string+ distance: string+ syncInterval: string+ priority: string+ deactivationDelay: string+ enabled: boolean+}++// chosen to keep the QR below v25 at ECC L+const QR_MAX_SCANNABLE_LENGTH = 1200++const PROFILE_CONDITION_OPTIONS: { value: ProfileConditionType; label: string }[] = [+ { value: "charging", label: "Charging" },+ { value: "android_auto", label: "Android Auto / Car mode" },+ { value: "speed_above", label: "Speed above threshold" },+ { value: "speed_below", label: "Speed below threshold" },+ { value: "stationary", label: "Stationary" }+]+const API_TEMPLATES = ["custom","dawarich",@@ -72,6 +97,9 @@ export default function DeepLinkGenerator() {// Geofencesconst [geofences, setGeofences] = useState<GeofenceRow[]>([])+ // Tracking Profiles+ const [profiles, setProfiles] = useState<ProfileRow[]>([])+// QRconst qrRef = useRef<HTMLDivElement>(null)const [qrLib, setQrLib] = useState<any>(null)@@ -154,6 +182,33 @@ export default function DeepLinkGenerator() {})if (gfs.length > 0) obj.geofences = gfs+ const pfs: Record<string, unknown>[] = []+ for (const p of profiles) {+ if (!p.name) continue+ if (!p.interval || Number(p.interval) <= 0) continue+ if (p.distance === "" || Number(p.distance) < 0) continue+ if (p.syncInterval === "" || Number(p.syncInterval) < 0) continue++ const isSpeed = p.conditionType === "speed_above" || p.conditionType === "speed_below"+ const condition: Record<string, unknown> = { type: p.conditionType }+ if (isSpeed) {+ if (!p.speedKmh || Number(p.speedKmh) <= 0) continue+ condition.speedThreshold = Number(p.speedKmh) / 3.6+ }++ pfs.push({+ name: p.name,+ condition,+ interval: Number(p.interval),+ distance: Number(p.distance),+ syncInterval: Number(p.syncInterval),+ priority: p.priority ? Number(p.priority) : 10,+ deactivationDelay: p.deactivationDelay ? Number(p.deactivationDelay) : 60,+ enabled: p.enabled+ })+ }+ if (pfs.length > 0) obj.profiles = pfs+return obj}, [endpoint,@@ -176,7 +231,8 @@ export default function DeepLinkGenerator() {fieldMapEntries,customFields,customHeaders,- geofences+ geofences,+ profiles])const isEmpty = Object.keys(config).length === 0@@ -187,7 +243,8 @@ export default function DeepLinkGenerator() {return `colota://setup?config=${encoded}`}, [config, isEmpty])- // QR code rendering+ const isQrTooLarge = deepLink.length > QR_MAX_SCANNABLE_LENGTH+useEffect(() => {if (!qrRef.current || !qrLib || !deepLink) {if (qrRef.current) qrRef.current.innerHTML = ""@@ -195,7 +252,7 @@ export default function DeepLinkGenerator() {}const canvas = document.createElement("canvas")- qrLib.toCanvas(canvas, deepLink, { width: 200, margin: 2 }, (err: Error | null) => {+ qrLib.toCanvas(canvas, deepLink, { width: 400, margin: 2, errorCorrectionLevel: "L" }, (err: Error | null) => {if (!err && qrRef.current) {qrRef.current.innerHTML = ""qrRef.current.appendChild(canvas)@@ -268,6 +325,33 @@ export default function DeepLinkGenerator() {])}+ const updateProfile = <K extends keyof ProfileRow>(index: number, field: K, val: ProfileRow[K]) => {+ const next = [...profiles]+ next[index] = { ...next[index], [field]: val }+ setProfiles(next)+ }++ const removeProfile = (index: number) => {+ setProfiles(profiles.filter((_, i) => i !== index))+ }++ const addProfile = () => {+ setProfiles([+ ...profiles,+ {+ name: "",+ conditionType: "charging",+ speedKmh: "",+ interval: "5",+ distance: "0",+ syncInterval: "0",+ priority: "10",+ deactivationDelay: "60",+ enabled: true+ }+ ])+ }+return (<div className={styles.generator}>{/* Connection */}@@ -699,6 +783,140 @@ export default function DeepLinkGenerator() {</button></div>+ {/* Tracking Profiles */}+ <div className={styles.section}>+ <div className={styles.sectionTitle}>Tracking Profiles</div>+ <div className={styles.keyValueList}>+ {profiles.map((p, i) => {+ const isSpeed = p.conditionType === "speed_above" || p.conditionType === "speed_below"+ const isStationary = p.conditionType === "stationary"+ return (+ <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="Driving"+ value={p.name}+ onChange={(e) => updateProfile(i, "name", e.target.value)}+ />+ </div>+ <div className={styles.field}>+ <label className={styles.label}>Priority</label>+ <input+ className={styles.input}+ type="number"+ min="0"+ placeholder="10"+ value={p.priority}+ onChange={(e) => updateProfile(i, "priority", e.target.value)}+ />+ </div>+ </div>+ <div className={styles.row}>+ <div className={styles.field}>+ <label className={styles.label}>Condition</label>+ <select+ className={styles.select}+ value={p.conditionType}+ onChange={(e) => updateProfile(i, "conditionType", e.target.value as ProfileConditionType)}+ >+ {PROFILE_CONDITION_OPTIONS.map((opt) => (+ <option key={opt.value} value={opt.value}>+ {opt.label}+ </option>+ ))}+ </select>+ </div>+ {isSpeed && (+ <div className={styles.field}>+ <label className={styles.label}>Speed threshold (km/h)</label>+ <input+ className={styles.input}+ type="number"+ min="1"+ placeholder="30"+ value={p.speedKmh}+ onChange={(e) => updateProfile(i, "speedKmh", e.target.value)}+ />+ </div>+ )}+ </div>+ <div className={styles.row}>+ <div className={styles.field}>+ <label className={styles.label}>Interval (sec)</label>+ <input+ className={styles.input}+ type="number"+ min="1"+ placeholder="5"+ value={p.interval}+ onChange={(e) => updateProfile(i, "interval", e.target.value)}+ />+ </div>+ <div className={styles.field}>+ <label className={styles.label}>Distance (m)</label>+ <input+ className={styles.input}+ type="number"+ min="0"+ placeholder="0"+ value={p.distance}+ onChange={(e) => updateProfile(i, "distance", e.target.value)}+ />+ </div>+ </div>+ <div className={styles.row}>+ <div className={styles.field}>+ <label className={styles.label}>Sync interval (sec)</label>+ <input+ className={styles.input}+ type="number"+ min="0"+ placeholder="0"+ value={p.syncInterval}+ onChange={(e) => updateProfile(i, "syncInterval", e.target.value)}+ />+ </div>+ {!isStationary && (+ <div className={styles.field}>+ <label className={styles.label}>Deactivation delay (sec)</label>+ <input+ className={styles.input}+ type="number"+ min="0"+ placeholder="60"+ value={p.deactivationDelay}+ onChange={(e) => updateProfile(i, "deactivationDelay", e.target.value)}+ />+ </div>+ )}+ </div>+ <div className={styles.geofenceFlags}>+ <label className={styles.checkbox}>+ <input+ type="checkbox"+ checked={p.enabled}+ onChange={(e) => updateProfile(i, "enabled", e.target.checked)}+ />+ Enabled on import+ </label>+ </div>+ <div className={styles.geofenceActions}>+ <button className={styles.removeBtn} onClick={() => removeProfile(i)}>+ x+ </button>+ </div>+ </div>+ )+ })}+ </div>+ <button className={styles.addBtn} onClick={addProfile}>+ + Add profile+ </button>+ </div>+{/* Output */}<hr className={styles.divider} />@@ -724,6 +942,15 @@ export default function DeepLinkGenerator() {QR Code</div><div className={styles.qrContainer} ref={qrRef} />+ {isQrTooLarge && (+ <div className={styles.qrWarning}>+ <strong>This QR code may not be readable on all phones.</strong>+ <span>+ The configuration is large, so the QR has dense modules. If scanning fails, use the{" "}+ <em>Copy link</em> or <em>Download JSON</em> button above instead.+ </span>+ </div>+ )}</>)}</>diff --git a/apps/docs/src/css/custom.css b/apps/docs/src/css/custom.cssindex de832f3d..0c1f8c0d 100644--- a/apps/docs/src/css/custom.css+++ b/apps/docs/src/css/custom.css@@ -48,11 +48,4 @@[class*='admonitionHeading'] {text-transform: none;font-weight: 600;-}--/* Sidebar */-.theme-doc-sidebar-menu .menu__list-item-collapsible > .menu__link {- font-weight: 600;-}--+}\ No newline at end of filediff --git a/apps/mobile/src/screens/SetupImportScreen.tsx b/apps/mobile/src/screens/SetupImportScreen.tsxindex 8d32dcc8..b6cfd1a0 100644--- a/apps/mobile/src/screens/SetupImportScreen.tsx+++ b/apps/mobile/src/screens/SetupImportScreen.tsx@@ -28,10 +28,13 @@ import {type DawarichMode,type SelectablePreset,type SyncPreset,- type Geofence+ type Geofence,+ type TrackingProfile,+ type ProfileConditionType} from "../types/global"type ImportGeofence = Omit<Geofence, "id" | "createdAt">+type ImportProfile = Omit<TrackingProfile, "id" | "createdAt">// ============================================================================// TYPES@@ -41,12 +44,13 @@ interface ParsedConfig {settings: Partial<Settings>auth: Partial<AuthConfig> | nullgeofences: ImportGeofence[]+ profiles: ImportProfile[]}interface ConfigEntry {label: stringvalue: string- category: "tracking" | "api" | "auth" | "geofence"+ category: "tracking" | "api" | "auth" | "geofence" | "profile"rejected?: boolean}@@ -75,6 +79,14 @@ const VALID_HTTP_METHODS: HttpMethod[] = ["POST", "GET"]const VALID_DAWARICH_MODES: DawarichMode[] = ["single", "batch"]const VALID_AUTH_TYPES: AuthType[] = ["none", "basic", "bearer"]+const VALID_PROFILE_CONDITIONS: ProfileConditionType[] = [+ "charging",+ "android_auto",+ "speed_above",+ "speed_below",+ "stationary"+]+function detectPreset(settings: Partial<Settings>): SyncPreset {for (const [name, config] of Object.entries(TRACKING_PRESETS)) {if (@@ -93,7 +105,7 @@ function validateConfig(raw: unknown): ValidationResult {if (!raw || typeof raw !== "object") {return {valid: false,- config: { settings: {}, auth: null, geofences: [] },+ config: { settings: {}, auth: null, geofences: [], profiles: [] },entries: [],error: "Invalid configuration format"}@@ -318,16 +330,62 @@ function validateConfig(raw: unknown): ValidationResult {}}+ // --- Tracking Profiles ---++ const profiles: ImportProfile[] = []++ if ("profiles" in obj && Array.isArray(obj.profiles)) {+ for (const entry of obj.profiles) {+ if (!entry || typeof entry !== "object") continue+ const p = entry as Record<string, unknown>+ if (+ typeof p.name !== "string" ||+ p.name.length === 0 ||+ typeof p.interval !== "number" ||+ p.interval < 1 ||+ typeof p.distance !== "number" ||+ p.distance < 0 ||+ typeof p.syncInterval !== "number" ||+ p.syncInterval < 0+ ) {+ continue+ }++ const condRaw = p.condition as Record<string, unknown> | undefined+ if (!condRaw || typeof condRaw !== "object" || typeof condRaw.type !== "string") continue+ if (!VALID_PROFILE_CONDITIONS.includes(condRaw.type as ProfileConditionType)) continue+ const condType = condRaw.type as ProfileConditionType+ const needsSpeed = condType === "speed_above" || condType === "speed_below"+ if (needsSpeed && (typeof condRaw.speedThreshold !== "number" || condRaw.speedThreshold <= 0)) continue+ const condition: TrackingProfile["condition"] = needsSpeed+ ? { type: condType, speedThreshold: condRaw.speedThreshold as number }+ : { type: condType }++ profiles.push({+ name: p.name,+ interval: p.interval,+ distance: p.distance,+ syncInterval: p.syncInterval,+ priority: typeof p.priority === "number" ? p.priority : 10,+ deactivationDelay:+ typeof p.deactivationDelay === "number" && p.deactivationDelay >= 0 ? p.deactivationDelay : 60,+ enabled: typeof p.enabled === "boolean" ? p.enabled : true,+ condition+ })+ entries.push({ label: p.name, value: `${p.interval}s`, category: "profile" })+ }+ }+if (entries.length === 0) {return {valid: false,- config: { settings, auth, geofences },+ config: { settings, auth, geofences, profiles },entries,error: "No valid settings found in configuration"}}- return { valid: true, config: { settings, auth, geofences }, entries }+ return { valid: true, config: { settings, auth, geofences, profiles }, entries }}// ============================================================================@@ -346,7 +404,7 @@ export function SetupImportScreen({ route, navigation }: any) {if (!configParam || typeof configParam !== "string") {return {valid: false,- config: { settings: {}, auth: null, geofences: [] },+ config: { settings: {}, auth: null, geofences: [], profiles: [] },entries: [],error: "No configuration data in URL"} as ValidationResult@@ -359,7 +417,7 @@ export function SetupImportScreen({ route, navigation }: any) {logger.error("[SetupImport] Failed to parse config:", e)return {valid: false,- config: { settings: {}, auth: null, geofences: [] },+ config: { settings: {}, auth: null, geofences: [], profiles: [] },entries: [],error: "Invalid configuration data. The URL may be malformed."} as ValidationResult@@ -370,6 +428,7 @@ export function SetupImportScreen({ route, navigation }: any) {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 profileEntries = result.entries.filter((e) => e.category === "profile")const handleApply = async () => {setApplying(true)@@ -416,6 +475,21 @@ export function SetupImportScreen({ route, navigation }: any) {}}+ if (result.config.profiles.length > 0) {+ const existingProfilesByName = replaceByName+ ? new Map((await NativeLocationService.getProfiles()).map((p) => [p.name, p.id]))+ : null+ for (const p of result.config.profiles) {+ if (existingProfilesByName) {+ const existingId = existingProfilesByName.get(p.name)+ if (existingId !== undefined) {+ await NativeLocationService.deleteProfile(existingId)+ }+ }+ await NativeLocationService.createProfile(p)+ }+ }+showAlert("Configuration Applied", "Settings have been updated successfully.", "success")navigation.navigate("Dashboard")} catch (e) {@@ -501,18 +575,25 @@ export function SetupImportScreen({ route, navigation }: any) {{renderSection("API", apiEntries)}{renderSection("AUTHENTICATION", authEntries)}{renderSection("GEOFENCES", geofenceEntries)}+ {renderSection("TRACKING PROFILES", profileEntries)}- {geofenceEntries.length > 0 && (+ {(geofenceEntries.length > 0 || profileEntries.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.toggleLabel, { color: colors.text }]}>+ {geofenceEntries.length > 0 && profileEntries.length > 0+ ? "Replace zones and profiles with the same name"+ : profileEntries.length > 0+ ? "Replace profiles with the same name"+ : "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} />+ <Switch testID="replace-imports-switch" value={replaceByName} onValueChange={setReplaceByName} /></View></Card></View>diff --git a/apps/mobile/src/screens/TrackingProfilesScreen.tsx b/apps/mobile/src/screens/TrackingProfilesScreen.tsxindex f729866f..6979ca62 100644--- a/apps/mobile/src/screens/TrackingProfilesScreen.tsx+++ b/apps/mobile/src/screens/TrackingProfilesScreen.tsx@@ -4,7 +4,7 @@*/import React, { useState, useEffect, useCallback } from "react"-import { View, Text, StyleSheet, FlatList, Switch, Pressable } from "react-native"+import { View, Text, StyleSheet, FlatList, Switch, Pressable, Share } from "react-native"import { useTheme } from "../hooks/useTheme"import { useTracking } from "../contexts/TrackingProvider"import { ProfileService } from "../services/ProfileService"@@ -12,9 +12,9 @@ import { showAlert, showConfirm } from "../services/modalService"import { SavedTrackingProfile, ScreenProps } from "../types/global"import { fonts } from "../styles/typography"import { Container, SectionTitle, Card } from "../components"-import { Plus, X, Zap } from "lucide-react-native"+import { Plus, X, Zap, Share2 } from "lucide-react-native"import { logger } from "../utils/logger"-import { PROFILE_CONDITIONS, MS_TO_KMH } from "../constants"+import { PROFILE_CONDITIONS, MS_TO_KMH, HIT_SLOP_MD } from "../constants"function formatCondition(profile: SavedTrackingProfile): string {const condition = PROFILE_CONDITIONS.find((c) => c.type === profile.condition.type)@@ -73,6 +73,19 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {[loadProfiles])+ const handleShareProfiles = useCallback(async () => {+ if (profiles.length === 0) return+ try {+ const exportable = profiles.map(({ id: _id, createdAt: _createdAt, ...rest }) => rest)+ const encoded = btoa(JSON.stringify({ profiles: exportable }))+ const link = `colota://setup?config=${encoded}`+ await Share.share({ message: link })+ } catch (err) {+ logger.error("[TrackingProfilesScreen] Failed to share profiles:", err)+ showAlert("Error", "Failed to share profiles.", "error")+ }+ }, [profiles])+const handleDelete = useCallback(async (item: SavedTrackingProfile) => {const confirmed = await showConfirm({@@ -184,7 +197,19 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {<Text style={[styles.createBtnText, { color: colors.textOnPrimary }]}>Create Profile</Text></Pressable>- {profiles.length > 0 && <SectionTitle>Profiles ({profiles.length})</SectionTitle>}+ {profiles.length > 0 && (+ <View style={styles.activeHeader}>+ <SectionTitle>Profiles ({profiles.length})</SectionTitle>+ <Pressable+ testID="share-profiles-btn"+ onPress={handleShareProfiles}+ hitSlop={HIT_SLOP_MD}+ style={({ pressed }) => [styles.shareBtn, pressed && { opacity: colors.pressedOpacity }]}+ >+ <Share2 size={20} color={colors.textSecondary} />+ </Pressable>+ </View>+ )}</>}ListEmptyComponent={@@ -245,6 +270,8 @@ const styles = StyleSheet.create({alignItems: "center",justifyContent: "center"},+ activeHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },+ shareBtn: { padding: 4, marginBottom: 12 },empty: { alignItems: "center", paddingVertical: 40 },emptyText: { fontSize: 15, ...fonts.semiBold, marginBottom: 6 },emptyHint: {diff --git a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsxindex fa6d586c..be958054 100644--- a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx@@ -11,6 +11,9 @@ const mockSaveAuthConfig = jest.fn().mockResolvedValue(true)const mockCreateGeofence = jest.fn().mockResolvedValue(1)const mockGetGeofences = jest.fn().mockResolvedValue([])const mockDeleteGeofence = jest.fn().mockResolvedValue(true)+const mockCreateProfile = jest.fn().mockResolvedValue(1)+const mockGetProfiles = jest.fn().mockResolvedValue([])+const mockDeleteProfile = jest.fn().mockResolvedValue(true)const mockNavigate = jest.fn()const mockShowAlert = jest.fn()@@ -22,7 +25,10 @@ jest.mock("../../services/NativeLocationService", () => ({saveSetting: (...args: any[]) => mockSaveSetting(...args),createGeofence: (...args: any[]) => mockCreateGeofence(...args),getGeofences: (...args: any[]) => mockGetGeofences(...args),- deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args)+ deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args),+ createProfile: (...args: any[]) => mockCreateProfile(...args),+ getProfiles: (...args: any[]) => mockGetProfiles(...args),+ deleteProfile: (...args: any[]) => mockDeleteProfile(...args)}}))@@ -415,12 +421,12 @@ describe("SetupImportScreen", () => {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()+ expect(queryByTestId("replace-imports-switch")).toBeNull()})it("shows the toggle when geofences are in the import", () => {const { getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))- expect(getByTestId("replace-geofences-switch")).toBeTruthy()+ expect(getByTestId("replace-imports-switch")).toBeTruthy()})it("does not delete existing zones when toggle is off (default)", async () => {@@ -443,7 +449,7 @@ describe("SetupImportScreen", () => {])const { getByText, getByTestId } = renderScreen(encode({ geofences: [validGeofence] }))- fireEvent(getByTestId("replace-geofences-switch"), "valueChange", true)+ fireEvent(getByTestId("replace-imports-switch"), "valueChange", true)fireEvent.press(getByText("Apply Configuration"))await waitFor(() => {@@ -457,7 +463,7 @@ describe("SetupImportScreen", () => {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(getByTestId("replace-imports-switch"), "valueChange", true)fireEvent.press(getByText("Apply Configuration"))await waitFor(() => {@@ -479,7 +485,7 @@ describe("SetupImportScreen", () => {}const { getByText, getByTestId } = renderScreen(encode(config))- fireEvent(getByTestId("replace-geofences-switch"), "valueChange", true)+ fireEvent(getByTestId("replace-imports-switch"), "valueChange", true)fireEvent.press(getByText("Apply Configuration"))await waitFor(() => {@@ -489,4 +495,196 @@ describe("SetupImportScreen", () => {expect(mockDeleteGeofence).toHaveBeenCalledTimes(2)})})++ describe("profiles", () => {+ const validProfile = {+ name: "Driving",+ interval: 3,+ distance: 5,+ syncInterval: 60,+ priority: 20,+ deactivationDelay: 30,+ enabled: true,+ condition: { type: "speed_above", speedThreshold: 8.33 }+ }++ beforeEach(() => {+ mockGetProfiles.mockReset()+ mockGetProfiles.mockResolvedValue([])+ mockDeleteProfile.mockReset()+ mockDeleteProfile.mockResolvedValue(true)+ mockCreateProfile.mockReset()+ mockCreateProfile.mockResolvedValue(1)+ })++ it("parses a valid profile and shows it under TRACKING PROFILES", () => {+ const { getByText } = renderScreen(encode({ profiles: [validProfile] }))+ expect(getByText("TRACKING PROFILES")).toBeTruthy()+ expect(getByText("Driving")).toBeTruthy()+ })++ it("rejects a profile missing name", () => {+ const { getByText } = renderScreen(encode({ profiles: [{ ...validProfile, name: "" }] }))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("rejects a profile with unknown condition type", () => {+ const config = { profiles: [{ ...validProfile, condition: { type: "bogus" } }] }+ const { getByText } = renderScreen(encode(config))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("rejects a speed profile missing speedThreshold", () => {+ const config = { profiles: [{ ...validProfile, condition: { type: "speed_above" } }] }+ const { getByText } = renderScreen(encode(config))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("accepts a non-speed condition without speedThreshold", () => {+ const config = {+ profiles: [{ ...validProfile, condition: { type: "charging" } }]+ }+ const { getByText } = renderScreen(encode(config))+ expect(getByText("Driving")).toBeTruthy()+ })++ it("rejects a profile with interval < 1", () => {+ const { getByText } = renderScreen(encode({ profiles: [{ ...validProfile, interval: 0 }] }))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("calls createProfile on apply with all fields", async () => {+ const { getByText } = renderScreen(encode({ profiles: [validProfile] }))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockCreateProfile).toHaveBeenCalledTimes(1)+ })+ expect(mockCreateProfile).toHaveBeenCalledWith({+ name: "Driving",+ interval: 3,+ distance: 5,+ syncInterval: 60,+ priority: 20,+ deactivationDelay: 30,+ enabled: true,+ condition: { type: "speed_above", speedThreshold: 8.33 }+ })+ })++ it("fills in default priority/delay/enabled when omitted", async () => {+ const minimal = {+ name: "Charging",+ interval: 10,+ distance: 0,+ syncInterval: 0,+ condition: { type: "charging" }+ }+ const { getByText } = renderScreen(encode({ profiles: [minimal] }))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockCreateProfile).toHaveBeenCalledTimes(1)+ })+ expect(mockCreateProfile).toHaveBeenCalledWith(+ expect.objectContaining({+ name: "Charging",+ priority: 10,+ deactivationDelay: 60,+ enabled: true,+ condition: { type: "charging" }+ })+ )+ })++ it("creates multiple profiles in order", async () => {+ const config = {+ profiles: [validProfile, { ...validProfile, name: "Stationary", condition: { type: "stationary" } }]+ }+ const { getByText } = renderScreen(encode(config))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockCreateProfile).toHaveBeenCalledTimes(2)+ })+ expect(mockCreateProfile.mock.calls[0][0].name).toBe("Driving")+ expect(mockCreateProfile.mock.calls[1][0].name).toBe("Stationary")+ })++ it("does not call createProfile when no profiles 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(mockCreateProfile).not.toHaveBeenCalled()+ })++ it("deletes matching profiles before creating when replace toggle is on", async () => {+ mockGetProfiles.mockResolvedValueOnce([+ {+ id: 5,+ name: "Driving",+ interval: 1,+ distance: 0,+ syncInterval: 0,+ priority: 0,+ deactivationDelay: 0,+ enabled: true,+ condition: { type: "charging" }+ },+ {+ id: 6,+ name: "Other",+ interval: 1,+ distance: 0,+ syncInterval: 0,+ priority: 0,+ deactivationDelay: 0,+ enabled: true,+ condition: { type: "charging" }+ }+ ])+ const { getByText, getByTestId } = renderScreen(encode({ profiles: [validProfile] }))++ fireEvent(getByTestId("replace-imports-switch"), "valueChange", true)+ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockCreateProfile).toHaveBeenCalledTimes(1)+ })+ expect(mockDeleteProfile).toHaveBeenCalledTimes(1)+ expect(mockDeleteProfile).toHaveBeenCalledWith(5)+ })++ it("defaults to appending without deleting when replace toggle is off", async () => {+ mockGetProfiles.mockResolvedValueOnce([+ {+ id: 5,+ name: "Driving",+ interval: 1,+ distance: 0,+ syncInterval: 0,+ priority: 0,+ deactivationDelay: 0,+ enabled: true,+ condition: { type: "charging" }+ }+ ])+ const { getByText } = renderScreen(encode({ profiles: [validProfile] }))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockCreateProfile).toHaveBeenCalledTimes(1)+ })+ expect(mockGetProfiles).not.toHaveBeenCalled()+ expect(mockDeleteProfile).not.toHaveBeenCalled()+ })+ })})diff --git a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsxindex 535fa1e5..45e815ff 100644--- a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.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 { TrackingProfile } from "../../types/global"// --- Mocks ---@@ -246,4 +247,101 @@ describe("TrackingProfilesScreen", () => {expect(queryByText("Active")).toBeNull()})})++ describe("share profiles", () => {+ 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 profiles", async () => {+ mockGetProfiles.mockResolvedValue([])+ const { queryByTestId, getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("No profiles yet")).toBeTruthy()+ })++ expect(queryByTestId("share-profiles-btn")).toBeNull()+ })++ it("renders the share button when at least one profile exists", async () => {+ const { getByTestId } = renderScreen()++ await waitFor(() => {+ expect(getByTestId("share-profiles-btn")).toBeTruthy()+ })+ })++ it("opens the share sheet with a colota://setup link on press", async () => {+ const { getByTestId } = renderScreen()++ await waitFor(() => {+ expect(getByTestId("share-profiles-btn")).toBeTruthy()+ })++ fireEvent.press(getByTestId("share-profiles-btn"))++ await waitFor(() => {+ expect(shareSpy).toHaveBeenCalledTimes(1)+ })++ const arg = shareSpy.mock.calls[0][0]+ expect(arg.message).toMatch(/^colota:\/\/setup\?config=/)+ })++ it("encodes profiles without id or createdAt fields", async () => {+ const { getByTestId } = renderScreen()++ await waitFor(() => {+ expect(getByTestId("share-profiles-btn")).toBeTruthy()+ })++ fireEvent.press(getByTestId("share-profiles-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.profiles).toHaveLength(2)+ expect(decoded.profiles[0]).not.toHaveProperty("id")+ expect(decoded.profiles[0]).not.toHaveProperty("createdAt")+ expect(decoded.profiles[0]).toEqual({+ name: "Charging",+ interval: 10,+ distance: 0,+ syncInterval: 0,+ priority: 10,+ condition: { type: "charging" },+ deactivationDelay: 60,+ enabled: true+ })+ expect(decoded.profiles[1].condition).toEqual({ type: "speed_above", speedThreshold: 13.89 })+ })++ it("shows an error alert when sharing fails", async () => {+ shareSpy.mockRejectedValueOnce(new Error("share failed"))++ const { getByTestId } = renderScreen()++ await waitFor(() => {+ expect(getByTestId("share-profiles-btn")).toBeTruthy()+ })++ fireEvent.press(getByTestId("share-profiles-btn"))++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to share profiles.", "error")+ })+ })+ })})