Skip to content

Colota - Android GPS Location tracker

feat: add per-trip delete from trip detail screen

Max Dietricha1f2a5840d49
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 0781751b..5b594a1b 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -198,7 +198,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A
| `TrackingProfilesScreen` | List and manage condition-based tracking profiles |
| `ProfileEditorScreen` | Create/edit a profile's name, condition, GPS settings, priority, and deactivation delay |
| `LocationInspectorScreen` | Calendar day picker with activity dots, map tab with trip-colored tracks, trips tab with trip cards and export |
-| `TripDetailScreen` | Full trip view with dedicated map, stats grid, speed and elevation profile charts, and per-trip export |
+| `TripDetailScreen` | Full trip view with dedicated map, stats grid, speed and elevation profile charts, per-trip export, and per-trip delete |
| `LocationSummaryScreen` | Aggregated stats for selectable periods (week/month/30 days) with daily breakdown and tap-to-inspect navigation |
| `ExportDataScreen` | Export all tracked locations via native streaming converters as CSV, GeoJSON, GPX, or KML |
| `AutoExportScreen` | Configure scheduled auto-export: directory, format, frequency, export range, and file retention |
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 57ff5e4f..fdd1e1d4 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -40,7 +40,7 @@ Colota has eighteen screens, each focused on a specific task:
| **Tracking Profiles** | Create and manage condition-based profiles that automatically adjust tracking settings |
| **Profile Editor** | Configure profile name, condition trigger, GPS interval, distance filter, sync interval, priority, and deactivation delay |
| **Location History** | Browse recorded locations on a track map with calendar day picker and trip-colored segments, view segmented trips with per-trip stats |
-| **Trip Detail** | Full trip view with dedicated map, stats grid (distance, duration, avg speed, elevation), speed and elevation profile charts, and export |
+| **Trip Detail** | Full trip view with dedicated map, stats grid (distance, duration, avg speed, elevation), speed and elevation profile charts, export, and delete |
| **Location Summary** | Aggregated stats (total distance, trips, active days, avg distance) for selectable periods with daily breakdown and tap-to-inspect navigation |
| **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML |
| **Auto-Export** | Configure scheduled exports: format, directory, frequency, export range, and file retention |
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index 93e87fed..eb7c993d 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -351,6 +351,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
fun deleteOlderThan(days: Int, promise: Promise) = executeAsync(promise) {
deleteThenVacuum(refresh = true) { dbHelper.deleteOlderThan(days) }
}
+
+ @ReactMethod
+ fun deleteLocationsInRange(startTs: Double, endTs: Double, promise: Promise) = executeAsync(promise) {
+ deleteThenVacuum(refresh = true) { dbHelper.deleteInRange(startTs.toLong(), endTs.toLong()) }
+ }
@ReactMethod
fun vacuumDatabase(promise: Promise) = executeAsync(promise) {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
index a2606904..a30f7a6f 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
@@ -536,6 +536,14 @@ class DatabaseHelper private constructor(context: Context) :
return writableDatabase.delete(TABLE_LOCATIONS, "timestamp < ?", arrayOf(cutoff.toString()))
}
+ fun deleteInRange(startTs: Long, endTs: Long): Int {
+ return writableDatabase.delete(
+ TABLE_LOCATIONS,
+ "timestamp >= ? AND timestamp <= ?",
+ arrayOf(startTs.toString(), endTs.toString())
+ )
+ }
+
/** Reclaims unused space. Call from background thread only. */
fun vacuum() {
AppLogger.d(TAG, "Starting VACUUM + ANALYZE")
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
index e7a083c5..64e58f91 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
@@ -784,6 +784,27 @@ class DatabaseHelperSQLiteTest {
assertEquals(53.0, remaining[0]["latitude"] as Double, 0.001)
}
+ // ========================================================================
+ // deleteInRange
+ // ========================================================================
+
+ @Test
+ fun `deleteInRange removes only locations within inclusive range`() {
+ db.saveLocation(latitude = 50.0, longitude = 10.0, timestamp = 1000L) // before
+ db.saveLocation(latitude = 51.0, longitude = 11.0, timestamp = 2000L) // start (inclusive)
+ db.saveLocation(latitude = 52.0, longitude = 12.0, timestamp = 2500L) // inside
+ db.saveLocation(latitude = 53.0, longitude = 13.0, timestamp = 3000L) // end (inclusive)
+ db.saveLocation(latitude = 54.0, longitude = 14.0, timestamp = 4000L) // after
+
+ val deleted = db.deleteInRange(2000L, 3000L)
+ assertEquals(3, deleted)
+
+ val remaining = db.getTableData(DatabaseHelper.TABLE_LOCATIONS, 100, 0)
+ assertEquals(2, remaining.size)
+ val timestamps = remaining.map { (it["timestamp"] as Number).toLong() }.toSet()
+ assertEquals(setOf(1000L, 4000L), timestamps)
+ }
+
// ========================================================================
// Helpers
// ========================================================================
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index cc7a5f71..81cb2e65 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -5,6 +5,7 @@
import React, { useState, useEffect, useRef, useCallback, useMemo, useLayoutEffect } from "react"
import { View, Text, StyleSheet, Pressable } from "react-native"
+import { useFocusEffect } from "@react-navigation/native"
import { fonts } from "../styles/typography"
import { BarChart2 } from "lucide-react-native"
import { Container } from "../components"
@@ -152,6 +153,17 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
fetchTrackData()
}, [fetchTrackData])
+ /** Refresh on focus so trip deletions in TripDetail are reflected */
+ useFocusEffect(
+ useCallback(() => {
+ const key = `${mapDate.getFullYear()}-${String(mapDate.getMonth() + 1).padStart(2, "0")}`
+ daysCache.current.delete(key)
+ distanceCache.current.delete(key)
+ fetchTrackData()
+ fetchDaysWithData(mapDate.getFullYear(), mapDate.getMonth())
+ }, [fetchTrackData, fetchDaysWithData, mapDate])
+ )
+
/** Tap a trip card -> open detail screen */
const handleTripSelect = useCallback(
(trip: Trip) => {
diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsx
index e195c2f7..39130581 100644
--- a/apps/mobile/src/screens/TripDetailScreen.tsx
+++ b/apps/mobile/src/screens/TripDetailScreen.tsx
@@ -3,9 +3,19 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useMemo, useState, useCallback } from "react"
+import React, { useMemo, useState, useCallback, useLayoutEffect } from "react"
import { View, Text, StyleSheet, ScrollView, Pressable } from "react-native"
-import { Route, Clock, Gauge, TrendingUp, TrendingDown, MapPin, Share, type LucideIcon } from "lucide-react-native"
+import {
+ Route,
+ Clock,
+ Gauge,
+ TrendingUp,
+ TrendingDown,
+ MapPin,
+ Share,
+ Trash2,
+ type LucideIcon
+} from "lucide-react-native"
import { useTheme } from "../hooks/useTheme"
import { fonts } from "../styles/typography"
import { Card } from "../components/ui/Card"
@@ -15,7 +25,7 @@ import { InteractiveLineChart } from "../components/features/inspector/Interacti
import { getTripColor, computeTripStats } from "../utils/trips"
import { formatDate, formatDistance, formatDuration, formatSpeed, formatTime } from "../utils/geo"
import { TRIP_CONVERTERS, EXPORT_FORMATS, EXPORT_FORMAT_KEYS, type ExportFormat } from "../utils/exportConverters"
-import { showAlert } from "../services/modalService"
+import { showAlert, showConfirm } from "../services/modalService"
import { logger } from "../utils/logger"
import NativeLocationService from "../services/NativeLocationService"
import type { Trip, ThemeColors } from "../types/global"
@@ -38,10 +48,11 @@ function downsample(values: number[], maxBars: number): number[] {
return result
}
-export function TripDetailScreen({ route }: RootScreenProps<"Trip Detail">) {
+export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Detail">) {
const { colors } = useTheme()
const trip: Trip = route.params.trip
const tripColor = getTripColor(trip.index)
+ const [deleting, setDeleting] = useState(false)
const stats = useMemo(() => computeTripStats(trip.locations), [trip])
const duration = trip.endTime - trip.startTime
@@ -71,6 +82,45 @@ export function TripDetailScreen({ route }: RootScreenProps<"Trip Detail">) {
[trip, displayName]
)
+ const handleDelete = useCallback(async () => {
+ const confirmed = await showConfirm({
+ title: `Delete ${displayName}?`,
+ message: `This permanently removes ${trip.locationCount} location point${
+ trip.locationCount === 1 ? "" : "s"
+ } from this device. Unsent points will not be uploaded.`,
+ confirmText: "Delete",
+ destructive: true
+ })
+ if (!confirmed) return
+ setDeleting(true)
+ try {
+ await NativeLocationService.deleteLocationsInRange(trip.startTime, trip.endTime)
+ navigation.goBack()
+ } catch (error) {
+ logger.error("[TripDetail] Delete failed:", error)
+ showAlert("Delete Failed", "Unable to delete trip. Please try again.", "error")
+ setDeleting(false)
+ }
+ }, [trip, displayName, navigation])
+
+ const headerRight = useCallback(
+ () => (
+ <Pressable
+ onPress={handleDelete}
+ disabled={deleting}
+ hitSlop={8}
+ style={({ pressed }) => [styles.headerBtn, (pressed || deleting) && { opacity: colors.pressedOpacity }]}
+ >
+ <Trash2 size={20} color={colors.error} />
+ </Pressable>
+ ),
+ [handleDelete, deleting, colors.error, colors.pressedOpacity]
+ )
+
+ useLayoutEffect(() => {
+ navigation.setOptions({ headerRight })
+ }, [navigation, headerRight])
+
const speedProfile = useMemo(() => {
const raw = trip.locations.filter((loc) => loc.speed != null).map((loc) => loc.speed ?? 0)
return downsample(raw, MAX_BARS)
@@ -356,5 +406,8 @@ const styles = StyleSheet.create({
exportChipText: {
fontSize: 12,
...fonts.bold
+ },
+ headerBtn: {
+ padding: 8
}
})
diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
index 0531449a..f2faf507 100644
--- a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
@@ -108,6 +108,10 @@ jest.mock("../../utils/logger", () => ({
logger: { error: jest.fn(), info: jest.fn(), debug: jest.fn() }
}))
+jest.mock("@react-navigation/native", () => ({
+ useFocusEffect: jest.fn()
+}))
+
import { LocationHistoryScreen } from "../LocationInspectorScreen"
const createProps = () =>
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index d0cadcd3..ed60e9df 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -259,6 +259,16 @@ class NativeLocationService {
return LocationServiceModule.deleteOlderThan(days)
}
+ /**
+ * Deletes locations within an inclusive timestamp range (seconds since epoch)
+ * @returns Count of deleted records
+ */
+ static async deleteLocationsInRange(startTs: number, endTs: number): Promise<number> {
+ this.ensureModule()
+ logger.debug(`[NativeLocationService] Deleting locations in range ${startTs}-${endTs}`)
+ return LocationServiceModule.deleteLocationsInRange(startTs, endTs)
+ }
+
/**
* Runs SQLite VACUUM to reclaim disk space
*/
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index 6450be44..2e309fa4 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -19,6 +19,7 @@ jest.mock("react-native", () => ({
clearQueue: jest.fn().mockResolvedValue(10),
clearAllLocations: jest.fn().mockResolvedValue(50),
deleteOlderThan: jest.fn().mockResolvedValue(25),
+ deleteLocationsInRange: jest.fn().mockResolvedValue(7),
vacuumDatabase: jest.fn().mockResolvedValue(undefined),
getGeofences: jest.fn().mockResolvedValue([]),
createGeofence: jest.fn().mockResolvedValue(1),