Colota - Android GPS Location tracker
refactor(data): every action says what it deletes (#855)
Max Dietrich6568eaa0f18e
diff --git a/apps/docs/docs/guides/data-management.md b/apps/docs/docs/guides/data-management.mdindex b0f19d22..cc795681 100644--- a/apps/docs/docs/guides/data-management.md+++ b/apps/docs/docs/guides/data-management.md@@ -2,29 +2,34 @@sidebar_position: 3----# Data Management+# Data management-Manage your location database from the Data Management screen.+Manage your location database from the Data management screen.import ScreenshotGallery from '@site/src/components/ScreenshotGallery'-<ScreenshotGallery screenshots={[ { src: "/img/screenshots/DataManagement.png", label: "Data Management" }, ]} />+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/DataManagement.png", label: "Data management" }, ]} />-## Actions+## What the screen holds-| Action | Description |-| ---------------------------- | -------------------------------------------------------------------------- |-| **Sync Now** | Manually flush the queue and upload pending locations. A sync already running finishes first |-| **Clear Sent History** | Remove locations that have already been synced |-| **Clear Queue** | Remove unsent locations from the upload queue |-| **Delete Older Than X Days** | Clean up old data past a specified age |-| **Vacuum Database** | Reclaim disk space after deletions |-| **Export Locations** | Export location history - see [Data Export](data-export.md) |-| **Import Locations** | Merge external files into your history - see [Data Import](data-import.md) |+**Stored on this device** is the ledger: how many locations this device holds and what they take on disk.-In [offline mode](/docs/configuration/server-settings#offline-mode), sync-related actions (Sync Now, Clear Sent History, Clear Queue) are hidden since no queue is used. A **Delete All Locations** action is available instead. Data export remains fully available - see [Data Export](data-export.md).+| Control | What it does |+| --- | --- |+| **Sync now** | Uploads the queued locations immediately, whatever [Sync only on](/docs/configuration/sync-presets) says. A sync already running finishes first. The tracking notification appears for a moment if tracking was off, and nothing is recorded |+| **Compact database** | Rewrites the database to give unused space back. It deletes nothing. Deleting trips and points from Location History leaves gaps that only this reclaims, so press it after a round of track editing |+| **Delete queued locations** | Deletes the locations waiting to upload, not their pending uploads. Nothing else holds a copy, so they leave Location History too |+| **Delete synced locations** | Deletes locations already on your server. Those days leave Location History, notes included, and imported locations count as synced. Copies on your server stay |+| **Delete older than** | Deletes every location recorded before the age you pick: 30 days, 90 days, 1 year or a custom number of days. Sync state is ignored, so queued locations go with the rest |+| **Delete all locations** | Deletes every location and every manual trip split you made. Geofences, profiles and settings stay |-For a full archive of locations, settings and credentials in a single password-encrypted file, use **Settings → Backup & Restore** - see [Backup & Restore](backup-restore.md).+Each delete names its own count before you press it. No age is chosen when the screen opens, so nothing is counted until you pick one. Every delete asks you to confirm, and none can be undone.++In [offline mode](/docs/configuration/server-settings#offline-mode) nothing new is queued, so Sync now and both sync-scoped deletes leave the screen. Locations queued before you turned it on are still there, and the age delete and Delete all still reach them.++Location History deletes single points and whole trips, see below. Export lives on its own screen, see [Data Export](data-export.md), and so does import, see [Data Import](data-import.md).++For a full archive of locations, settings and credentials in a single password-encrypted file, use **Settings > Backup & restore** - see [Backup & restore](backup-restore.md).## Deleting from Location History@@ -40,11 +45,11 @@ To correct how points are grouped into trips rather than remove them, see [Editi### Single points-A stray fix can land far from where you actually were, which drags the track and the day's distance with it. On the **Map** tab, tap the point to open its popup, check the time and accuracy to make sure it is the one you mean, then tap the trash icon next to the close button. You'll be asked to confirm.+A stray fix can land far from where you actually were, which drags the track and the day's distance with it. On the **Map** tab, tap the point to open its card, check the time and accuracy to make sure it is the one you mean, then tap the trash icon next to the close button. You'll be asked to confirm. The **Data** tab lists every point of the day; tapping a row opens the same card.Only that one point is removed, so the rest of the trip stays intact. If the point had not synced yet, its pending upload is dropped with it.-The same popup carries a split icon, which starts a new trip at that point instead of removing it - see [Editing Trips](editing-trips.md).+The same card carries a split icon, which starts a new trip at that point instead of removing it - see [Editing Trips](editing-trips.md).Deleting locally does not remove anything already uploaded to your server.diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.tsindex da95fabb..49c96ac0 100644--- a/apps/mobile/src/components/index.ts+++ b/apps/mobile/src/components/index.ts@@ -71,7 +71,6 @@ export { StatRow } from "./ui/StatRow"export { Footer } from "./ui/Footer"export { FormatOption } from "./ui/FormatOption"export { FormatSelector } from "./ui/FormatSelector"-export { StatsCard } from "./features/settings/StatsCard"export { DashboardBanner } from "./features/dashboard/DashboardBanner"export { DashboardDock } from "./features/dashboard/DashboardDock"export { DayHeader } from "./features/inspector/DayHeader"@@ -79,3 +78,4 @@ export { DayPickerModal } from "./features/inspector/DayPickerModal"export { TripRow } from "./features/inspector/TripRow"export { InspectorDock } from "./features/inspector/InspectorDock"export { PointCard } from "./features/inspector/PointCard"+export { StatsCard } from "./features/settings/StatsCard"diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsxindex e6dcf4cd..25512ea5 100644--- a/apps/mobile/src/screens/DataManagementScreen.tsx+++ b/apps/mobile/src/screens/DataManagementScreen.tsx@@ -3,577 +3,561 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useCallback, useRef } from "react"-import {- Text,- StyleSheet,- View,- ScrollView,- Pressable,- TextInput,- KeyboardAvoidingView,- Platform,- NativeEventEmitter,- NativeModules-} from "react-native"-import { Lightbulb } from "lucide-react-native"+import React, { useState, useCallback, useRef, useEffect } from "react"+import { Text, StyleSheet, View, ScrollView, DeviceEventEmitter } from "react-native"+import { Archive, Clock, CloudUpload, HardDrive, MapPin, Trash2 } from "lucide-react-native"import { useFocusEffect } from "@react-navigation/native"-import { ScreenProps, DatabaseStats } from "../types/global"+import { DatabaseStats } from "../types/global"+import type { RootScreenProps } from "../types/navigation"import { useTheme } from "../hooks/useTheme"-import { fonts, fontSizes } from "../styles/typography"+import { fonts, fontSizes, lineHeights } from "../styles/typography"import NativeLocationService from "../services/NativeLocationService"import { useTracking } from "../contexts/TrackingProvider"-import { Button, SectionTitle, Card, Container, Divider, FloatingSaveIndicator } from "../components"-import { STATS_REFRESH_FAST, SAVE_SUCCESS_DISPLAY_MS } from "../constants"+import {+ Button,+ Card,+ ChipGroup,+ Container,+ Divider,+ EmptyState,+ FieldMessage,+ ListItem,+ NumericInput,+ SectionTitle,+ StatRow+} from "../components"+import {+ MANUAL_FLUSH_TIMEOUT_MS,+ RETENTION_PRESET_DAYS,+ RETENTION_PREVIEW_DEBOUNCE_MS,+ SAVE_SUCCESS_DISPLAY_MS,+ space+} from "../constants"import { useTimeout } from "../hooks/useTimeout"-import { showConfirm } from "../services/modalService"+import { showAlert, showConfirm } from "../services/modalService"+import { allSub, deleteCopy, olderSub, scopeSub, type DataScope } from "../utils/dataScope"+import { parseWholeNumber, wholeNumberError } from "../utils/settingsValidation"+import { formatWhen } from "../utils/geo"import { logger } from "../utils/logger"-const BACKUP_TIP = "Tip: back up your data first (Settings -> Backup & Restore)."+/** Only a placeholder in the custom field. Nothing is selected until the user selects it. */+const PLACEHOLDER_DAYS = 90-export function DataManagementScreen({}: ScreenProps) {+/** A hundred years. Past this the value stops being an age and starts being a typo. */+const MAX_RETENTION_DAYS = 36500++type Message = { text: string; failed?: boolean }+type Preview = { days: number; total: number; cutoffSeconds: number } | null++const EMPTY_STATS: DatabaseStats = {+ queued: 0,+ sent: 0,+ total: 0,+ today: 0,+ databaseSizeMB: 0,+ lastSyncTime: 0,+ lastSyncError: ""+}++export function DataManagementScreen({ navigation }: RootScreenProps<"Data Management">) {const { colors } = useTheme()- const { settings } = useTracking()+ const { settings, tracking } = useTracking()const isOfflineMode = settings.isOfflineMode- const [stats, setStats] = useState<DatabaseStats>({- queued: 0,- sent: 0,- total: 0,- today: 0,- databaseSizeMB: 0- })-- const [daysInput, setDaysInput] = useState("90")- const [isProcessing, setIsProcessing] = useState(false)- const [feedback, setFeedback] = useState<string | null>(null)- const [debugMode, setDebugMode] = useState(false)- const feedbackTimeout = useTimeout()-- // Update stats+ const [stats, setStats] = useState<DatabaseStats>(EMPTY_STATS)+ const [loaded, setLoaded] = useState(false)+ const [busy, setBusy] = useState<"count" | "flush" | "compact" | "delete" | null>(null)+ const [syncMessage, setSyncMessage] = useState<Message | null>(null)+ const [compactMessage, setCompactMessage] = useState<Message | null>(null)++ // Nothing preselected: an age is an argument to a delete, so the screen opens with none chosen,+ // arms nothing and counts nothing until the user picks one.+ const [ageChoice, setAgeChoice] = useState("")+ const [customText, setCustomText] = useState("")+ const lastValidDays = useRef<number | null>(null)+ const [clampNote, setClampNote] = useState<string | undefined>()+ const [preview, setPreview] = useState<Preview>(null)++ const compactTimeout = useTimeout()+ const clampTimeout = useTimeout()+ const previewTimeout = useTimeout()+ const flushTimeout = useTimeout()++ // A ref, not the state, because two presses inside one render both read the same state value.+ const busyRef = useRef(false)+ const isProcessing = busy !== null++ const statsIssued = useRef(0)+ const statsApplied = useRef(0)+ // The flush listener lives outside any effect, so only this removes it when the screen goes.+ const flushSub = useRef<{ remove: () => void } | null>(null)+ useEffect(() => () => flushSub.current?.remove(), [])++ /**+ * Reads are numbered so a slow earlier one cannot land on a newer one. The comparison is against+ * what has landed, not against what has been issued, or a newer read that then fails would leave+ * the screen with nothing applied and the ledger stuck on its placeholder.+ */+ const applyStats = useCallback((next: DatabaseStats, generation: number) => {+ if (generation < statsApplied.current) return+ statsApplied.current = generation+ setStats(next)+ setLoaded(true)+ }, [])+const updateStats = useCallback(async () => {+ const generation = ++statsIssued.currenttry {- const nativeStats = await NativeLocationService.getStats()- setStats(nativeStats)+ applyStats(await NativeLocationService.getStats(), generation)} catch (err) {logger.error("[DataManagementScreen] Failed to update stats:", err)}- }, [])+ }, [applyStats])++ const isCustom = ageChoice === "custom"+ const customDays = parseWholeNumber(customText)+ const days = isCustom ? customDays : parseWholeNumber(ageChoice)+ // The bridge parameter is a Kotlin Int, so an age past its range would arrive coerced and could+ // put the cutoff in the future, where every row matches.+ const ageError = isCustom+ ? (wholeNumberError(customText, 1, "day") ??+ (customDays !== null && customDays > MAX_RETENTION_DAYS ? `At most ${MAX_RETENTION_DAYS} days` : undefined))+ : undefined++ /** One count per settled age, from the same cutoff arithmetic the delete uses. */+ const runPreview = useCallback(+ (forDays: number | null) => {+ previewTimeout.clear()+ if (forDays === null || forDays < 1) {+ setPreview(null)+ return+ }+ if (forDays > MAX_RETENTION_DAYS) {+ setPreview(null)+ return+ }+ previewTimeout.set(async () => {+ // An age the user settled on long enough to have it counted. Recording per keystroke would+ // catch every prefix, so backspacing 365 to nothing would restore 3 and arm a far wider delete.+ lastValidDays.current = forDays+ try {+ const { total, cutoffSeconds } = await NativeLocationService.countOlderThan(forDays)+ setPreview({ days: forDays, total, cutoffSeconds })+ } catch (err) {+ logger.error("[DataManagementScreen] Failed to count old locations:", err)+ setPreview(null)+ }+ }, RETENTION_PREVIEW_DEBOUNCE_MS)+ },+ [previewTimeout]+ )- // Load debug mode setting+ // No preview call here. This callback is stable, so it would capture the age from the first+ // render, which is always none, and re-focusing would wipe a count the user had already asked for.+ // The preview runs from the controls that change the age.useFocusEffect(useCallback(() => {- NativeLocationService.getSetting("debug_mode_enabled", "false").then((value) => {- setDebugMode(value === "true")- })updateStats()- const interval = setInterval(updateStats, STATS_REFRESH_FAST)- return () => clearInterval(interval)+ const subs = ["onSyncProgress", "onSyncError", "onLocationUpdate", "onDatabaseCompacted"].map((event) =>+ DeviceEventEmitter.addListener(event, updateStats)+ )+ return () => subs.forEach((s) => s.remove())}, [updateStats]))- // Show feedback message- const showFeedback = useCallback(- (message: string, duration = SAVE_SUCCESS_DISPLAY_MS) => {- setFeedback(message)- feedbackTimeout.set(() => setFeedback(null), duration)- },- [feedbackTimeout]- )-- // Manual flush with progress- const progressListenerRef = useRef<any>(null)- const syncEmitter = useRef(new NativeEventEmitter(NativeModules.LocationServiceModule)).current- const flushTimeout = useTimeout()+ const handleAgeChoice = (value: string) => {+ setAgeChoice(value)+ setClampNote(undefined)+ runPreview(value === "custom" ? customDays : parseWholeNumber(value))+ }- const cleanupFlush = useCallback(async () => {- progressListenerRef.current?.remove()- progressListenerRef.current = null- flushTimeout.clear()- await updateStats()- setIsProcessing(false)- }, [updateStats, flushTimeout])+ const handleCustomChange = (text: string) => {+ setCustomText(text)+ setClampNote(undefined)+ const parsed = parseWholeNumber(text)+ runPreview(parsed !== null && parsed >= 1 ? parsed : null)+ }- const handleManualFlush = useCallback(async () => {- if (isProcessing || stats.queued === 0) return- const total = stats.queued+ // The siblings clamp an emptied field up to the minimum, which is right for a stored setting.+ // Here the value is a delete argument: clamping to 1 would arm "delete everything older than a+ // day" in silence, so an invalid entry falls back to the last age the user actually chose.+ const handleCustomBlur = () => {+ if (customDays !== null && customDays >= 1) {+ lastValidDays.current = customDays+ return+ }+ const restored = lastValidDays.current+ // Nothing settled yet, so there is nothing to fall back to. The field stays empty and the+ // delete stays disarmed, which is the right resting state for a delete argument.+ if (restored === null) return+ setCustomText(String(restored))+ setClampNote(`Set to ${restored} day${restored === 1 ? "" : "s"}`)+ clampTimeout.set(() => setClampNote(undefined), SAVE_SUCCESS_DISPLAY_MS)+ runPreview(restored)+ }- try {- setIsProcessing(true)- setFeedback(`Syncing 0/${total}...`)- feedbackTimeout.clear()-- const receivedProgress = { current: false }-- progressListenerRef.current = syncEmitter.addListener("onSyncProgress", (rawEvent: any) => {- const event = rawEvent as { sent: number; failed: number; total: number }- receivedProgress.current = true- const processed = event.sent + event.failed- if (processed >= event.total) {- // Sync finished - show final result, then clean up- const msg =- event.failed > 0- ? `Synced ${event.sent}/${event.total} (${event.failed} failed)`- : `Synced ${event.sent}/${event.total}`- setFeedback(msg)- flushTimeout.set(async () => {- await cleanupFlush()- showFeedback("Sync complete")- }, 1500)- } else {- setFeedback(`Syncing ${processed}/${event.total}...`)+ /** Every dialog names a count read immediately before it opens, never one held in state. */+ const confirmAndDelete = useCallback(+ async (scope: DataScope, run: () => Promise<number>) => {+ if (busyRef.current) return+ busyRef.current = true+ setBusy("count")+ try {+ const generation = ++statsIssued.current+ const fresh = await NativeLocationService.getStats()+ applyStats(fresh, generation)+ let count = fresh.total+ let older+ if (scope === "queued") count = fresh.queued+ if (scope === "synced") count = fresh.sent+ if (scope === "older") {+ if (days === null) return+ const { total, cutoffSeconds } = await NativeLocationService.countOlderThan(days)+ count = total+ // Reads every match, so it is taken here and nowhere on the way here.+ const unsent = total === 0 ? 0 : await NativeLocationService.countUnsentOlderThan(days)+ older = { days, unsent, cutoffSeconds }+ }+ if (count === 0) {+ showAlert("Nothing to delete", "That count came back empty. The figures above are current.", "info")+ return}- })- // manualFlush is fire-and-forget; fall back after 30s if no progress events arrive- await NativeLocationService.manualFlush()- flushTimeout.set(async () => {- await cleanupFlush()- showFeedback(receivedProgress.current ? "Sync complete" : "Sync failed! Check connection")- }, 30000)- } catch (err) {- logger.error("[DataManagementScreen] Manual flush error:", err)- await cleanupFlush()- showFeedback("Sync failed. Check your connection and endpoint.")- }- }, [stats.queued, isProcessing, showFeedback, feedbackTimeout, flushTimeout, syncEmitter, cleanupFlush])+ const copy = deleteCopy(scope, count, older)+ if (!(await showConfirm({ ...copy, destructive: true }))) return- // Generic delete handler- const handleDeleteAction = useCallback(- async (action: () => Promise<number | void>, successMessage: (count: number) => string) => {- setIsProcessing(true)- try {- const deleted = await action()+ setBusy("delete")+ await run()await updateStats()- if (typeof deleted === "number") {- showFeedback(successMessage(deleted))- }+ runPreview(days)} catch (err) {- logger.error("[DataManagementScreen] Delete action failed:", err)- showFeedback("Action failed")+ logger.error(`[DataManagementScreen] Failed to delete ${scope} locations:`, err)+ showAlert(+ "Delete failed",+ "The database reported an error. Check the figures above before trying again.",+ "error"+ )} finally {- setIsProcessing(false)+ busyRef.current = false+ setBusy(null)}},- [updateStats, showFeedback]+ [days, updateStats, runPreview, applyStats])- const handleClearSentHistory = useCallback(async () => {- const confirmed = await showConfirm({- title: "Clear Sent History",- message: `Delete ${stats.sent} sent location${stats.sent !== 1 ? "s" : ""}? This cannot be undone.\n\n${BACKUP_TIP}`,- confirmText: "Clear",- destructive: true- })- if (!confirmed) return-- handleDeleteAction(- () => NativeLocationService.clearSentHistory().then(() => stats.sent),- (count) => `Cleared ${count} sent location${count !== 1 ? "s" : ""}`- )- }, [handleDeleteAction, stats.sent])-- const handleClearQueue = useCallback(async () => {- const confirmed = await showConfirm({- title: "Clear Queue",- message: `Delete ${stats.queued} pending location${stats.queued !== 1 ? "s" : ""}? These will not be synced.\n\n${BACKUP_TIP}`,- confirmText: "Clear",- destructive: true- })- if (!confirmed) return-- handleDeleteAction(- () => NativeLocationService.clearQueue(),- (count) => `Cleared ${count} queued location${count !== 1 ? "s" : ""}`- )- }, [handleDeleteAction, stats.queued])-- const handleDeleteAllLocations = useCallback(async () => {- const confirmed = await showConfirm({- title: "Delete All Locations",- message: `Delete all ${stats.total} stored location${stats.total !== 1 ? "s" : ""}? This cannot be undone.\n\n${BACKUP_TIP}`,- confirmText: "Delete All",- destructive: true- })- if (!confirmed) return-- handleDeleteAction(- () => NativeLocationService.clearAllLocations(),- (count) => `Deleted ${count} location${count !== 1 ? "s" : ""}`- )- }, [handleDeleteAction, stats.total])-- const handleDeleteOlderThan = useCallback(async () => {- const days = parseInt(daysInput, 10)- if (isNaN(days) || days <= 0) {- showFeedback("Please enter a valid number of days")- return+ const handleManualFlush = useCallback(async () => {+ if (busyRef.current || stats.queued === 0 || !settings.endpoint) return+ busyRef.current = true+ const queuedBefore = stats.queued+ setBusy("flush")+ setSyncMessage({ text: `Sent 0 of ${queuedBefore.toLocaleString()}.` })++ const finish = async (message: Message) => {+ flushTimeout.clear()+ sub.remove()+ flushSub.current = null+ await updateStats()+ setSyncMessage(message)+ busyRef.current = false+ setBusy(null)}- const confirmed = await showConfirm({- title: "Delete Old Locations",- message: `Delete all locations older than ${days} day${days !== 1 ? "s" : ""}? This cannot be undone.\n\n${BACKUP_TIP}`,- confirmText: "Delete",- destructive: true- })- if (!confirmed) return-- handleDeleteAction(- () => NativeLocationService.deleteOlderThan(days),- (count) => `Deleted ${count} location${count !== 1 ? "s" : ""} older than ${days} day${days !== 1 ? "s" : ""}`+ // The fallback means no event for this long, not no ending within this long of the press. A pass+ // over a large queue outlives the window while still reporting, and declaring it dead would+ // remove the listener and re-enable the button over a run that is still uploading.+ const armFallback = () =>+ flushTimeout.set(+ () => finish({ text: "No answer from the tracking service. Check the queued count above.", failed: true }),+ MANUAL_FLUSH_TIMEOUT_MS+ )++ const sub = DeviceEventEmitter.addListener(+ "onSyncProgress",+ (event: { sent: number; failed: number; total: number; remaining?: number }) => {+ // Only the event that ends a pass carries `remaining`. A pass caps at a fixed number of+ // batches, so the running count reaching the queue it started with is not the signal.+ if (event.remaining === undefined) {+ armFallback()+ setSyncMessage({ text: `Sent ${event.sent.toLocaleString()} of ${queuedBefore.toLocaleString()}.` })+ return+ }+ // `remaining` is a fresh count of the queue. `failed` counts attempts inside the pass and can+ // exceed it, since a row that failed twice is one row, so it never stands in for the queue.+ const sent = `Sent ${event.sent.toLocaleString()} of ${queuedBefore.toLocaleString()}.`+ const left = event.remaining > 0 ? ` ${event.remaining.toLocaleString()} still queued; press again.` : ""+ if (event.failed > 0) {+ finish({ text: `${sent} Some uploads failed.${left}`, failed: true })+ } else {+ finish({ text: `${sent}${left}` })+ }+ })- }, [daysInput, handleDeleteAction, showFeedback])- const handleInsertDummyData = useCallback(async () => {- const confirmed = await showConfirm({- title: "Insert Dummy Data",- message: "Insert ~200 fake GPS locations across the past 7 days? This is for testing only.",- confirmText: "Insert"- })- if (!confirmed) return+ flushSub.current = sub- setIsProcessing(true)try {- const count = await NativeLocationService.insertDummyData()- await updateStats()- showFeedback(`Inserted ${count} dummy locations`)+ await NativeLocationService.manualFlush()+ armFallback()} catch (err) {- logger.error("[DataManagementScreen] Insert dummy data failed:", err)- showFeedback("Failed to insert dummy data")- } finally {- setIsProcessing(false)+ logger.error("[DataManagementScreen] Manual flush failed:", err)+ flushTimeout.clear()+ sub.remove()+ flushSub.current = null+ busyRef.current = false+ setBusy(null)+ setSyncMessage(null)+ showAlert("Sync failed", "Check your connection settings and try again.", "error")}- }, [updateStats, showFeedback])+ }, [stats.queued, settings.endpoint, updateStats, flushTimeout])- const handleVacuum = useCallback(async () => {- setIsProcessing(true)+ const handleCompact = useCallback(async () => {+ if (busyRef.current) return+ busyRef.current = true+ setBusy("compact")try {- const sizeBefore = stats.databaseSizeMB+ // Both figures come from the same moment, and both go through the generation guard so a read+ // issued before the rewrite cannot land after it and put the old size back.+ const beforeGeneration = ++statsIssued.current+ const beforeStats = await NativeLocationService.getStats()+ applyStats(beforeStats, beforeGeneration)+ const before = beforeStats.databaseSizeMBawait NativeLocationService.vacuumDatabase()- const freshStats = await NativeLocationService.getStats()- setStats(freshStats)- const freed = sizeBefore - freshStats.databaseSizeMB- if (freed > 0.01) {- showFeedback(`Freed ${freed.toFixed(2)} MB`)- } else {- showFeedback("Database already optimized")- }+ const afterGeneration = ++statsIssued.current+ const after = await NativeLocationService.getStats()+ applyStats(after, afterGeneration)+ const freed = before - after.databaseSizeMB+ setCompactMessage({ text: freed > 0.01 ? `Released ${freed.toFixed(2)} MB` : "Nothing to release" })+ compactTimeout.set(() => setCompactMessage(null), SAVE_SUCCESS_DISPLAY_MS)} catch (err) {- logger.error("[DataManagementScreen] Vacuum failed:", err)- showFeedback("Optimization failed")+ logger.error("[DataManagementScreen] Compact failed:", err)+ showAlert("Could not compact", "The database is busy. Try again in a moment.", "error")} finally {- setIsProcessing(false)+ busyRef.current = false+ setBusy(null)}- }, [stats.databaseSizeMB, showFeedback])+ }, [compactTimeout, applyStats])++ const syncBlocker = !settings.endpoint+ ? "No server configured. Set one on Connection."+ : stats.queued === 0+ ? stats.lastSyncTime > 0+ ? `Nothing queued. Last upload ${formatWhen(Math.floor(stats.lastSyncTime / 1000))}.`+ : "Nothing queued. New locations upload on their own."+ : null+ const syncIdle = `Uploads the ${stats.queued.toLocaleString()} queued location${stats.queued === 1 ? "" : "s"} now, whatever Sync only on says.${+ tracking ? "" : " The tracking notification appears for a moment. Nothing is recorded."+ }`+ const syncLine = busy === "flush" || syncMessage ? syncMessage : { text: syncBlocker ?? syncIdle }++ const ageCount = preview && preview.days === days ? preview.total : null+ // The field owns its own error; repeating it here would print the same sentence twice.+ const ageLine = ageError+ ? "Fix the age above."+ : days === null+ ? "Choose how old a location must be."+ : ageCount === null+ ? "Counting…"+ : olderSub(ageCount, days, preview?.cutoffSeconds ?? 0)return (<Container>- <KeyboardAvoidingView style={styles.keyboardAvoid} behavior={Platform.OS === "ios" ? "padding" : undefined}>- <ScrollView contentContainerStyle={styles.scrollContent}>- {/* Header */}- <View style={styles.header}>- <Text style={[styles.title, { color: colors.text }]}>Data Management</Text>- </View>-- {/* Stats */}- <View style={styles.section}>- <SectionTitle>DATABASE STATISTICS</SectionTitle>- <Card>- {[- ["Total Locations", stats.total.toLocaleString(), colors.text],- ...(!isOfflineMode- ? [- ["Sent", stats.sent.toLocaleString(), colors.success],- ["Queued", stats.queued.toLocaleString(), colors.warning]- ]- : []),- ["Today", stats.today.toLocaleString(), colors.info],- ["Storage", `${stats.databaseSizeMB.toFixed(2)} MB`, colors.primary]- ].map(([label, value, color], i, arr) => (- <React.Fragment key={i}>- <View style={styles.statRow}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>{label}</Text>- <Text style={[styles.statValue, { color }]}>{value}</Text>- </View>- {i < arr.length - 1 && <Divider />}- </React.Fragment>- ))}- </Card>- </View>+ <ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">+ <Text style={[styles.intro, { color: colors.textSecondary }]}>+ What this device is storing, and what deleting it takes away.+ </Text>++ <View style={styles.section}>+ <SectionTitle>Stored on this device</SectionTitle>+ <Card rows>+ <StatRow+ icon={MapPin}+ label="Locations"+ value={loaded ? stats.total.toLocaleString() : "…"}+ testID="stat-locations"+ />+ <Divider tight inset />+ <StatRow+ icon={HardDrive}+ label="Database size"+ value={loaded ? `${stats.databaseSizeMB.toFixed(2)} MB` : "…"}+ testID="stat-size"+ />+ </Card>- {/* Queue Actions */}{!isOfflineMode && (- <View style={styles.section}>- <SectionTitle>QUEUE ACTIONS</SectionTitle>- <Card>- <Button onPress={handleManualFlush} disabled={isProcessing || stats.queued === 0} title="Sync Now" />- <Text style={[styles.hint, { color: colors.textLight }]}>- {stats.queued === 0- ? "Queue is empty"- : `Trigger immediate sync of ${stats.queued} queued location${stats.queued !== 1 ? "s" : ""}`}- </Text>- </Card>+ <View>+ <Button+ variant="secondary"+ title="Sync now"+ testID="sync-now-btn"+ loading={busy === "flush"}+ disabled={isProcessing || syncBlocker !== null}+ onPress={handleManualFlush}+ />+ <FieldMessage variant={syncLine?.failed ? "error" : "info"}>{syncLine?.text ?? ""}</FieldMessage></View>)}- {/* Cleanup Actions */}- <View style={styles.section}>- <SectionTitle>CLEANUP ACTIONS</SectionTitle>- <Card>- {!isOfflineMode ? (- <>- {/* Clear Sent History */}- <ActionRow- label="Clear Sent History"- hint="Delete all successfully sent locations"- color={colors.success}- textColor={colors.textLight}- value={stats.sent.toLocaleString()}- onPress={handleClearSentHistory}- disabled={isProcessing || stats.sent === 0}- />- <Divider />-- {/* Clear Queue */}- <ActionRow- label="Clear Queue"- hint="Delete all pending locations"- color={colors.warning}- textColor={colors.textLight}- value={stats.queued.toLocaleString()}- onPress={handleClearQueue}- disabled={isProcessing || stats.queued === 0}- />- <Divider />- </>- ) : (- <>- {/* Delete All Locations (offline mode) */}- <ActionRow- label="Delete All Locations"- hint="Remove all stored locations from the database"- color={colors.error}- textColor={colors.textLight}- value={stats.total.toLocaleString()}- onPress={handleDeleteAllLocations}- disabled={isProcessing || stats.total === 0}- />- <Divider />- </>- )}-- {/* Delete Older Than */}- <View style={styles.actionColumn}>- <Text style={[styles.actionLabel, { color: colors.text }]}>Delete Old Locations</Text>- <Text style={[styles.actionHint, { color: colors.textLight }]}>- Remove locations older than specified days- </Text>- <View style={styles.daysInputRow}>- <TextInput- style={[- styles.daysInput,- {- borderColor: colors.border,- color: colors.text,- backgroundColor: colors.backgroundElevated- }- ]}- keyboardType="numeric"- value={daysInput}- onChangeText={setDaysInput}- placeholder="90"- placeholderTextColor={colors.placeholder}- />- <Text style={[styles.daysLabel, { color: colors.textSecondary }]}>days</Text>- <Button- style={[isProcessing && styles.buttonDisabled]}- onPress={handleDeleteOlderThan}- disabled={isProcessing}- title="Delete"- />- </View>- </View>- <Divider />-- {/* Vacuum */}- <View style={styles.actionColumn}>- <Text style={[styles.actionLabel, { color: colors.text }]}>Optimize Database</Text>- <Text style={[styles.actionHint, { color: colors.textLight }]}>- Reclaim unused space and improve performance- </Text>- <View style={styles.hintRow}>- <Lightbulb size={12} color={colors.textLight} />- <Text style={[styles.actionHint, { color: colors.textLight }]}>- Run after large deletions to reclaim space- </Text>- </View>- <Button onPress={handleVacuum} disabled={isProcessing} title="Optimize" variant="secondary" />- </View>- </Card>+ <View>+ <Button+ variant="ghost"+ title="Compact database"+ testID="compact-btn"+ loading={busy === "compact"}+ disabled={isProcessing}+ onPress={handleCompact}+ />+ <FieldMessage>+ {compactMessage?.text ??+ "Rewrites the database to give unused space back. Deleting trips and points leaves gaps that only this reclaims. Nothing is deleted."}+ </FieldMessage></View>- {/* Dev Tools */}- {debugMode && (- <View style={styles.section}>- <SectionTitle>DEV TOOLS</SectionTitle>- <Card>- <View style={styles.actionColumn}>- <Text style={[styles.actionLabel, { color: colors.text }]}>Insert Dummy Data</Text>- <Text style={[styles.actionHint, { color: colors.textLight }]}>- Generate ~200 fake GPS locations across the past 7 days for testing trips and calendar- </Text>- <Button onPress={handleInsertDummyData} disabled={isProcessing} title="Insert" variant="secondary" />- </View>+ </View>++ <View style={styles.section}>+ <SectionTitle>Delete locations</SectionTitle>+ {/* Until the first count lands the screen knows nothing, and "Nothing stored" over a full+ database is both a lie and a whole subtree that mounts only to be torn down again. */}+ {!loaded ? null : stats.total === 0 ? (+ <Card rows style={styles.emptyCard}>+ <EmptyState title="Nothing stored" hint="This device has no locations yet." style={styles.empty} />+ </Card>+ ) : (+ <>+ <Card rows>+ <ListItem+ testID="nav-backup-restore"+ icon={Archive}+ label="Back up first"+ sub="A backup is the only way to bring any of this back."+ subLines={2}+ onPress={() => navigation.navigate("Backup & Restore")}+ />+ {!isOfflineMode && (+ <>+ <Divider tight inset />+ <ListItem+ testID="delete-queued-row"+ icon={Clock}+ trailingIcon={Trash2}+ label="Delete queued locations"+ sub={scopeSub("queued", stats.queued)}+ subLines={2}+ disabled={isProcessing || stats.queued === 0}+ accessibilityHint="Asks you to confirm, then deletes"+ onPress={() => confirmAndDelete("queued", () => NativeLocationService.clearQueue())}+ />+ <Divider tight inset />+ <ListItem+ testID="delete-synced-row"+ icon={CloudUpload}+ trailingIcon={Trash2}+ label="Delete synced locations"+ sub={scopeSub("synced", stats.sent)}+ subLines={2}+ disabled={isProcessing || stats.sent === 0}+ accessibilityHint="Asks you to confirm, then deletes"+ onPress={() => confirmAndDelete("synced", () => NativeLocationService.clearSentHistory())}+ />+ </>+ )}</Card>- </View>++ <Card style={styles.ageCard}>+ <ChipGroup+ accessibilityLabel="Age"+ options={[+ ...RETENTION_PRESET_DAYS.map((preset) => ({+ value: String(preset),+ label: preset === 365 ? "1 year" : `${preset} days`,+ testID: `age-${preset}`+ })),+ { value: "custom", label: "Custom", testID: "age-custom" }+ ]}+ selected={ageChoice}+ onSelect={handleAgeChoice}+ />+ {isCustom && (+ <View style={styles.customField}>+ <NumericInput+ label="Delete locations older than"+ testID="retention-days-input"+ value={customText}+ onChange={handleCustomChange}+ onBlur={handleCustomBlur}+ unit="days"+ placeholder={String(PLACEHOLDER_DAYS)}+ hint="At least 1 day."+ error={ageError}+ message={clampNote}+ />+ </View>+ )}+ </Card>++ <View>+ <Button+ variant="ghost"+ color={colors.error}+ icon={Trash2}+ testID="delete-older-btn"+ title={+ ageCount && ageCount > 0+ ? `Delete ${ageCount.toLocaleString()} location${ageCount === 1 ? "" : "s"}`+ : "Delete older locations"+ }+ loading={busy === "count" || busy === "delete"}+ disabled={isProcessing || !!ageError || days === null || !ageCount}+ onPress={() => confirmAndDelete("older", () => NativeLocationService.deleteOlderThan(days as number))}+ />+ <FieldMessage variant={ageError ? "error" : "info"}>{ageLine}</FieldMessage>+ </View>++ <View>+ <Button+ variant="danger"+ icon={Trash2}+ title="Delete all locations"+ testID="delete-all-btn"+ loading={busy === "count" || busy === "delete"}+ disabled={isProcessing}+ onPress={() => confirmAndDelete("all", () => NativeLocationService.clearAllLocations())}+ />+ <FieldMessage>{allSub(stats.total)}</FieldMessage>+ </View>+ </>)}- </ScrollView>-- {/* Floating Feedback */}- <FloatingSaveIndicator- saving={isProcessing}- success={false}- message={feedback}- isError={feedback?.toLowerCase().includes("failed") ?? false}- colors={colors}- />- </KeyboardAvoidingView>+ </View>+ </ScrollView></Container>)}-// ActionRow Component-const ActionRow = ({- label,- hint,- color,- textColor,- value,- onPress,- disabled-}: {- label: string- hint: string- color: string- textColor: string- value: string- onPress: () => void- disabled: boolean-}) => (- <Pressable- style={({ pressed }) => [styles.actionRow, pressed && { opacity: 0.7 }]}- onPress={onPress}- disabled={disabled}- >- <View style={styles.actionInfo}>- <Text style={[styles.actionLabel, { color }]}>{label}</Text>- <Text style={[styles.actionHint, { color: textColor }]}>{hint}</Text>- </View>- <View style={[styles.actionBadge, { backgroundColor: color + "20", borderColor: color }]}>- <Text style={[styles.actionBadgeText, { color }]}>{value}</Text>- </View>- </Pressable>-)-const styles = StyleSheet.create({- keyboardAvoid: {- flex: 1- },scrollContent: {- paddingHorizontal: 16,- paddingBottom: 40- },- header: {- marginTop: 20,- marginBottom: 24- },- title: {- fontSize: 28,- ...fonts.bold,- marginBottom: 4- },- section: {- marginBottom: 24- },- statRow: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- paddingVertical: 8- },- statLabel: {- fontSize: 14,- ...fonts.medium+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl},- statValue: {- fontSize: 16,- ...fonts.bold- },- hint: {- fontSize: 12,- ...fonts.regular,- textAlign: "center",- fontStyle: "italic",- lineHeight: 16,- marginTop: 8- },- actionRow: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- paddingVertical: 12- },- actionColumn: {- paddingVertical: 12- },- actionInfo: {- flex: 1- },- actionLabel: {- fontSize: fontSizes.label,- ...fonts.semiBold,- marginBottom: 4- },- actionHint: {- fontSize: 12,+ intro: {+ fontSize: fontSizes.body,...fonts.regular,- lineHeight: 16,- marginTop: 2- },- actionBadge: {- paddingHorizontal: 12,- paddingVertical: 6,- borderRadius: 16,- borderWidth: 1+ lineHeight: lineHeights.body,+ marginBottom: space.lg},- actionBadgeText: {- fontSize: 13,- ...fonts.bold- },- daysInputRow: {- flexDirection: "row",- alignItems: "center",- marginTop: 12,- gap: 8+ section: {+ marginBottom: space.xl},- daysInput: {- flex: 1,- borderWidth: 1,- padding: 10,- borderRadius: 8,- fontSize: 15,- textAlign: "center"+ ageCard: {+ marginTop: space.md},- hintRow: {- flexDirection: "row",- alignItems: "center",- gap: 6,- marginTop: 2+ customField: {+ marginTop: space.lg},- daysLabel: {- fontSize: 15,- ...fonts.medium+ emptyCard: {+ paddingVertical: space.lg},- buttonDisabled: {- opacity: 0.5+ empty: {+ paddingHorizontal: 0}})diff --git a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsxindex 17905afc..a3935862 100644--- a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx@@ -1,376 +1,800 @@import React from "react"-import { render, fireEvent, waitFor } from "@testing-library/react-native"--// --- Mocks ----+import { render, fireEvent, waitFor, act, within } from "@testing-library/react-native"+import { DeviceEventEmitter } from "react-native"+import { DEFAULT_SETTINGS, Settings } from "../../types/global"++// The device re-invokes the same captured callback on every focus, and a callback whose+// dependencies are all stable is captured once and never rebuilt. A test has to be able to fire it+// again or every closure-capture bug in a focus effect is invisible.+let mockRefocus: (() => void) | null = nulljest.mock("@react-navigation/native", () => ({- useFocusEffect: jest.fn((cb) => cb()())+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {+ let cleanup = cb()+ mockRefocus = () => {+ if (typeof cleanup === "function") cleanup()+ cleanup = cb()+ }+ return () => {+ if (typeof cleanup === "function") cleanup()+ mockRefocus = null+ }+ }, [cb])+ }}))jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- card: "#fff",- border: "#e5e7eb",- background: "#fff",- backgroundElevated: "#f9fafb",- success: "#22c55e",- warning: "#f59e0b",- info: "#3b82f6",- error: "#ef4444",- placeholder: "#9ca3af",- textOnPrimary: "#fff",- overlay: "rgba(0,0,0,0.5)"- }- })-}))--jest.mock("../../hooks/useTimeout", () => ({- useTimeout: () => ({ set: jest.fn(), clear: jest.fn() })+ useTheme: () => ({ colors: require("@colota/shared").lightColors })}))-const mockGetStats = jest.fn().mockResolvedValue({ queued: 5, sent: 100, total: 105, today: 3, databaseSizeMB: 1.5 })-const mockGetSetting = jest.fn().mockResolvedValue("false")-const mockManualFlush = jest.fn().mockResolvedValue(undefined)-const mockClearSentHistory = jest.fn().mockResolvedValue(undefined)-const mockClearQueue = jest.fn().mockResolvedValue(5)-const mockDeleteOlderThan = jest.fn().mockResolvedValue(10)-const mockVacuumDatabase = jest.fn().mockResolvedValue(undefined)-const mockInsertDummyData = jest.fn().mockResolvedValue(200)--jest.mock("../../services/NativeLocationService", () => ({- __esModule: true,- default: {- getStats: function () {- return mockGetStats.apply(null, arguments)- },- getSetting: function () {- return mockGetSetting.apply(null, arguments)- },- manualFlush: function () {- return mockManualFlush.apply(null, arguments)- },- clearSentHistory: function () {- return mockClearSentHistory.apply(null, arguments)- },- clearQueue: function () {- return mockClearQueue.apply(null, arguments)- },- deleteOlderThan: function () {- return mockDeleteOlderThan.apply(null, arguments)- },- vacuumDatabase: function () {- return mockVacuumDatabase.apply(null, arguments)- },- insertDummyData: function () {- return mockInsertDummyData.apply(null, arguments)+// The preview debounce coalesces the way it does on a device: a callback scheduled while an earlier+// one is pending replaces it, so keystrokes inside one tick produce a single count. Longer timers+// are held rather than dropped, so a test can decide when the flush fallback fires and can count how+// often it was re-armed. The object is stable per hook instance, as the real hook's is, or a caller+// listing it as a dependency loops.+const mockLongTimers: Array<{ later: (() => void) | null }> = []+let mockLongArms = 0+jest.mock("../../hooks/useTimeout", () => {+ const R = require("react")+ const { RETENTION_PREVIEW_DEBOUNCE_MS } = jest.requireActual("../../constants")+ return {+ useTimeout: () => {+ const ref = R.useRef(null)+ if (!ref.current) {+ ref.current = { pending: null, later: null }+ mockLongTimers.push(ref.current)+ }+ const state = ref.current+ return R.useMemo(+ () => ({+ set: (fn: () => void, delay: number) => {+ if (delay !== RETENTION_PREVIEW_DEBOUNCE_MS) {+ mockLongArms += 1+ state.later = fn+ return+ }+ state.pending = fn+ Promise.resolve().then(() => {+ if (state.pending !== fn) return+ state.pending = null+ fn()+ })+ },+ clear: () => {+ state.pending = null+ state.later = null+ }+ }),+ [state]+ )}}-}))--const mockShowConfirm = jest.fn().mockResolvedValue(true)+})-jest.mock("../../services/modalService", () => ({- showConfirm: function () {- return mockShowConfirm.apply(null, arguments)- }-}))+/** Runs whatever long timer is currently armed, the way the device would after its delay elapsed. */+const fireLongTimers = () => mockLongTimers.forEach((t) => t.later?.())-jest.mock("../../utils/logger", () => ({- logger: { error: jest.fn(), warn: jest.fn() }+let mockSettings: Settings = { ...DEFAULT_SETTINGS }+let mockTracking = true+jest.mock("../../contexts/TrackingProvider", () => ({+ useTracking: () => ({ settings: mockSettings, tracking: mockTracking })}))-let mockIsOfflineMode = false-jest.mock("../../contexts/TrackingProvider", () => ({- useTracking: () => ({- settings: { isOfflineMode: mockIsOfflineMode }+const mockGetStats = jest.fn()+const mockCountOlderThan = jest.fn()+const mockCountUnsentOlderThan = jest.fn()+/** The boundary native reports back, so the dialog's date is pinned rather than read off the clock. */+const CUTOFF = 1735689600+const mockManualFlush = jest.fn()+const mockClearSentHistory = jest.fn()+const mockClearQueue = jest.fn()+const mockClearAllLocations = jest.fn()+const mockDeleteOlderThan = jest.fn()+const mockVacuumDatabase = jest.fn()++// Every real method is a static opening with `this.ensureModule()`, so a callback handed over+// unbound throws before it reaches native. Arrows on a plain object would swallow that and a dead+// button would pass, so the mock loses its receiver the same way the real service does.+jest.mock("../../services/NativeLocationService", () => {+ const service: Record<string, unknown> = {}+ const onReceiver = (impl: (...a: unknown[]) => unknown) =>+ function (this: unknown, ...a: unknown[]) {+ if (this !== service) throw new TypeError("undefined is not a function")+ return impl(...a)+ }+ Object.assign(service, {+ getStats: onReceiver((...a) => mockGetStats(...a)),+ countOlderThan: onReceiver((...a) => mockCountOlderThan(...a)),+ countUnsentOlderThan: onReceiver((...a) => mockCountUnsentOlderThan(...a)),+ manualFlush: onReceiver((...a) => mockManualFlush(...a)),+ clearSentHistory: onReceiver((...a) => mockClearSentHistory(...a)),+ clearQueue: onReceiver((...a) => mockClearQueue(...a)),+ clearAllLocations: onReceiver((...a) => mockClearAllLocations(...a)),+ deleteOlderThan: onReceiver((...a) => mockDeleteOlderThan(...a)),+ vacuumDatabase: onReceiver((...a) => mockVacuumDatabase(...a))})+ return { __esModule: true, default: service }+})++const mockShowConfirm = jest.fn()+const mockShowAlert = jest.fn()+jest.mock("../../services/modalService", () => ({+ showConfirm: (...a: unknown[]) => mockShowConfirm(...a),+ showAlert: (...a: unknown[]) => mockShowAlert(...a)}))+jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn() } }))+jest.mock("../../components", () => {const R = require("react")- const RN = require("react-native")+ const { View, Text, Pressable, TextInput } = require("react-native")return {- Button: function (props: any) {- return R.createElement(- RN.Pressable,- { onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },- R.createElement(RN.Text, null, props.title)+ Container: ({ children }: any) => R.createElement(View, null, children),+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),+ Divider: () => R.createElement(View, null),+ StatRow: ({ label, value, testID }: any) =>+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, value)),+ EmptyState: ({ title, hint }: any) =>+ R.createElement(View, null, R.createElement(Text, null, title), R.createElement(Text, null, hint)),+ FieldMessage: ({ children, variant }: any) =>+ R.createElement(Text, { accessibilityValue: { text: variant ?? "info" } }, children),+ Button: ({ title, onPress, disabled, testID, variant, color }: any) =>+ R.createElement(+ Pressable,+ {+ testID,+ onPress,+ disabled,+ accessibilityRole: "button",+ accessibilityState: { disabled: !!disabled },+ accessibilityValue: { text: `${variant ?? "primary"}${color ? "/error" : ""}` }+ },+ R.createElement(Text, null, title)+ ),+ ListItem: ({ testID, label, sub, onPress, disabled, trailingIcon }: any) =>+ R.createElement(+ Pressable,+ {+ testID,+ onPress,+ disabled,+ accessibilityRole: "button",+ accessibilityState: { disabled: !!disabled },+ accessibilityValue: { text: trailingIcon ? "trash" : "chevron" }+ },+ R.createElement(Text, null, label),+ R.createElement(Text, null, sub)+ ),+ ChipGroup: ({ options, selected, onSelect }: any) =>+ R.createElement(+ View,+ null,+ options.map((o: any) =>+ R.createElement(+ Pressable,+ {+ key: o.value,+ testID: o.testID,+ onPress: () => onSelect(o.value),+ accessibilityState: { selected: selected === o.value }+ },+ R.createElement(Text, null, o.label)+ )+ )+ ),+ NumericInput: ({ label, value, onChange, onBlur, unit, hint, error, message, testID }: any) =>+ R.createElement(+ View,+ null,+ R.createElement(Text, null, label),+ hint ? R.createElement(Text, null, hint) : null,+ R.createElement(TextInput, { testID, value, onChangeText: onChange, onBlur }),+ R.createElement(Text, null, unit),+ error ? R.createElement(Text, null, error) : null,+ message ? R.createElement(Text, null, message) : null)- },- SectionTitle: function (props: any) {- return R.createElement(RN.Text, null, props.children)- },- Card: function (props: any) {- return R.createElement(RN.View, null, props.children)- },- Container: function (props: any) {- return R.createElement(RN.View, null, props.children)- },- Divider: function () {- return R.createElement(RN.View, null)- },- FloatingSaveIndicator: function () {- return null- }}})-jest.mock("lucide-react-native", () => {- const R = require("react")- const RN = require("react-native")- function stub(name: any) {- return function () {- return R.createElement(RN.Text, null, name)- }- }- return {- Lightbulb: stub("Lightbulb")- }-})+import { DataManagementScreen } from "../DataManagementScreen"-// Mock NativeEventEmitter from react-native-const mockAddListener = jest.fn().mockReturnValue({ remove: jest.fn() })-jest.mock("react-native/Libraries/EventEmitter/NativeEventEmitter", () => {- return {- __esModule: true,- default: function () {- return {- addListener: function () {- return mockAddListener.apply(null, arguments)- }- }- }- }+const props = { navigation: { navigate: jest.fn() }, route: { key: "d", name: "Data Management" } } as any+const renderScreen = () => render(<DataManagementScreen {...props} />)+const stats = (over: Partial<Record<string, number | string>> = {}) => ({+ queued: 412,+ sent: 12068,+ total: 12480,+ today: 142,+ databaseSizeMB: 3.4213,+ lastSyncTime: 0,+ lastSyncError: "",+ ...over})-import { DataManagementScreen } from "../DataManagementScreen"-describe("DataManagementScreen", () => {beforeEach(() => {jest.clearAllMocks()- mockIsOfflineMode = false- mockGetStats.mockResolvedValue({ queued: 5, sent: 100, total: 105, today: 3, databaseSizeMB: 1.5 })- mockGetSetting.mockResolvedValue("false")+ mockSettings = { ...DEFAULT_SETTINGS, endpoint: "https://api.example.com/track" }+ mockTracking = true+ mockGetStats.mockResolvedValue(stats())+ mockCountOlderThan.mockResolvedValue({ total: 3120, cutoffSeconds: CUTOFF })+ mockCountUnsentOlderThan.mockResolvedValue(96)+ mockClearQueue.mockResolvedValue(412)+ mockClearSentHistory.mockResolvedValue(12068)+ mockClearAllLocations.mockResolvedValue(12480)+ mockDeleteOlderThan.mockResolvedValue(3120)+ mockVacuumDatabase.mockResolvedValue(undefined)+ mockManualFlush.mockResolvedValue(undefined)mockShowConfirm.mockResolvedValue(true)})- function renderScreen() {- return render(<DataManagementScreen navigation={{} as any} />)- }+ describe("the ledger", () => {+ it("shows two figures in the shape the Settings row that opens this screen prints", async () => {+ const api = renderScreen()++ expect(await api.findByText("12,480")).toBeTruthy()+ expect(api.getByText("3.42 MB")).toBeTruthy()+ })- it("renders Data Management title", async () => {- const { getByText } = renderScreen()+ it("carries no Sent, Queued or Today figure, because those parts never sum to the total", async () => {+ // Offline-recorded rows are neither sent nor queued, and a mid-sync read can make the parts exceed the whole.+ const api = renderScreen()+ await api.findByText("12,480")- await waitFor(() => {- expect(getByText("Data Management")).toBeTruthy()+ expect(api.queryByText("12,068")).toBeNull()+ expect(api.queryByText("142")).toBeNull()+ expect(api.queryByTestId("stat-queued")).toBeNull()})- })- it("shows database statistics with correct values", async () => {- const { getByText, getAllByText } = renderScreen()-- await waitFor(() => {- expect(getByText("Total Locations")).toBeTruthy()- expect(getByText("105")).toBeTruthy()- expect(getByText("Sent")).toBeTruthy()- // "100" appears as stat value and as badge count for Clear Sent History- expect(getAllByText("100").length).toBeGreaterThanOrEqual(1)- expect(getByText("Queued")).toBeTruthy()- expect(getAllByText("5").length).toBeGreaterThanOrEqual(1)- expect(getByText("Today")).toBeTruthy()- expect(getByText("3")).toBeTruthy()- expect(getByText("Storage")).toBeTruthy()- expect(getByText("1.50 MB")).toBeTruthy()+ it("refreshes on a sync event rather than polling every three seconds", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ mockGetStats.mockResolvedValue(stats({ total: 12500 }))+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", { sent: 1, failed: 0, total: 1, remaining: 0 })+ })++ expect(await api.findByText("12,500")).toBeTruthy()})})- it("shows Sync Now button", async () => {- const { getByText } = renderScreen()+ describe("what each delete says it takes", () => {+ it("tells the queued row the recordings go and no copy survives", async () => {+ const api = renderScreen()- await waitFor(() => {- expect(getByText("Sync Now")).toBeTruthy()+ expect(+ await api.findByText("412 locations waiting to upload. Nothing else holds a copy, and they leave History too.")+ ).toBeTruthy()})- })- it("disables Sync Now when queue is empty", async () => {- mockGetStats.mockResolvedValue({ queued: 0, sent: 100, total: 100, today: 3, databaseSizeMB: 1.5 })+ it("tells the synced row that an import counts as synced, which no label said before", async () => {+ const api = renderScreen()- const { getByText } = renderScreen()+ expect(+ await api.findByText("12,068 locations already on your server. Imported locations count as synced.")+ ).toBeTruthy()+ })- await waitFor(() => {- expect(getByText("Queue is empty")).toBeTruthy()+ it("names the trip splits and merges under Delete all, which no label, hint or dialog named", async () => {+ const api = renderScreen()++ expect(+ await api.findByText(+ "All 12,480 locations and every trip split and merge you made. Geofences, profiles and settings stay."+ )+ ).toBeTruthy()})- })- it("shows Clear Sent History with badge count", async () => {- const { getByText, getAllByText } = renderScreen()+ it("explains a disabled row in the same slot rather than leaving it blank", async () => {+ mockGetStats.mockResolvedValue(stats({ queued: 0 }))+ const api = renderScreen()- await waitFor(() => {- expect(getByText("Clear Sent History")).toBeTruthy()- // "100" appears both as the Sent stat and as the Clear Sent History badge- expect(getAllByText("100").length).toBeGreaterThanOrEqual(2)+ expect(await api.findByText("Nothing queued.")).toBeTruthy()+ expect(api.getByTestId("delete-queued-row").props.accessibilityState.disabled).toBe(true)})})- it("shows Clear Queue action", async () => {- const { getByText } = renderScreen()+ describe("confirming a delete", () => {+ it("quotes a count read at the moment of the press, never the one on screen", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ mockGetStats.mockResolvedValue(stats({ sent: 12100 }))++ fireEvent.press(api.getByTestId("delete-synced-row"))- await waitFor(() => {- expect(getByText("Clear Queue")).toBeTruthy()+ await waitFor(() =>+ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Delete 12,100 synced locations?", destructive: true })+ )+ )+ expect(mockClearSentHistory).toHaveBeenCalled()})- })- it("shows Delete Old Locations section with days input", async () => {- const { getByText, getByDisplayValue } = renderScreen()+ it("deletes nothing when the dialog is dismissed", async () => {+ mockShowConfirm.mockResolvedValue(false)+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("delete-all-btn"))- await waitFor(() => {- expect(getByText("Delete Old Locations")).toBeTruthy()- expect(getByDisplayValue("90")).toBeTruthy()- expect(getByText("days")).toBeTruthy()- expect(getByText("Delete")).toBeTruthy()+ await waitFor(() => expect(mockShowConfirm).toHaveBeenCalled())+ expect(mockClearAllLocations).not.toHaveBeenCalled()})- })- it("shows Optimize Database action", async () => {- const { getByText } = renderScreen()+ it("asks for a distinct verb on the one that empties everything", async () => {+ const api = renderScreen()+ await api.findByText("12,480")- await waitFor(() => {- expect(getByText("Optimize Database")).toBeTruthy()- expect(getByText("Optimize")).toBeTruthy()+ fireEvent.press(api.getByTestId("delete-all-btn"))++ await waitFor(() =>+ expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ confirmText: "Delete all" }))+ )})- })- it("shows DEV TOOLS section when debug mode enabled", async () => {- mockGetSetting.mockResolvedValue("true")+ // A confirmed delete has to reach native. Asserting only the dialog let three dead buttons ship.+ it.each([+ ["delete-queued-row", () => mockClearQueue],+ ["delete-synced-row", () => mockClearSentHistory],+ ["delete-all-btn", () => mockClearAllLocations]+ ])("runs the native delete behind %s once confirmed", async (testID, fn) => {+ const api = renderScreen()+ await api.findByText("12,480")- const { getByText } = renderScreen()+ fireEvent.press(api.getByTestId(testID as string))- await waitFor(() => {- expect(getByText("DEV TOOLS")).toBeTruthy()- expect(getByText("Insert Dummy Data")).toBeTruthy()+ await waitFor(() => expect((fn as () => jest.Mock)()).toHaveBeenCalled())+ expect(mockShowAlert).not.toHaveBeenCalled()})- })- it("hides DEV TOOLS section when debug mode disabled", async () => {- mockGetSetting.mockResolvedValue("false")+ it("runs the native delete behind the age button once an age is chosen and confirmed", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("age-90"))+ await api.findByText("Delete 3,120 locations")++ fireEvent.press(api.getByTestId("delete-older-btn"))++ await waitFor(() => expect(mockDeleteOlderThan).toHaveBeenCalledWith(90))+ expect(mockShowAlert).not.toHaveBeenCalled()+ })++ it("reports a failure instead of leaving the screen looking successful", async () => {+ // The rejection has to come from native. A handler that threw before reaching it would raise+ // the same alert, which is how a dead button once passed this test.+ mockClearQueue.mockRejectedValue(new Error("db"))+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("delete-queued-row"))++ await waitFor(() =>+ expect(mockShowAlert).toHaveBeenCalledWith(+ "Delete failed",+ "The database reported an error. Check the figures above before trying again.",+ "error"+ )+ )+ expect(mockClearQueue).toHaveBeenCalled()+ })- const { queryByText } = renderScreen()+ it("spends the one filled danger button on Delete all and keeps the age delete a text button", async () => {+ const api = renderScreen()+ await api.findByText("12,480")- await waitFor(() => {- expect(queryByText("DEV TOOLS")).toBeNull()- expect(queryByText("Insert Dummy Data")).toBeNull()+ expect(api.getByTestId("delete-all-btn").props.accessibilityValue.text).toBe("danger")+ expect(api.getByTestId("delete-older-btn").props.accessibilityValue.text).toBe("ghost/error")})})- it("Clear Sent History shows confirmation dialog", async () => {- const { getByText, getAllByText } = renderScreen()+ describe("the age argument", () => {+ // An age is an argument to a delete, so opening the screen must not choose one, must not count+ // for one, and must not arm one.+ it("chooses nothing on open, so it counts nothing and arms nothing", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ expect(mockCountOlderThan).not.toHaveBeenCalled()+ expect(api.getByText("Choose how old a location must be.")).toBeTruthy()+ expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)+ })++ it("counts once an age is chosen, and names the boundary it counted at", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("age-90"))- // Wait for stats to load so the ActionRow is enabled (stats.sent > 0)- await waitFor(() => {- expect(getAllByText("100").length).toBeGreaterThanOrEqual(1)+ expect(await api.findByText("Delete 3,120 locations")).toBeTruthy()+ expect(mockCountOlderThan).toHaveBeenCalledWith(90)})- fireEvent.press(getByText("Clear Sent History"))+ // The unsent count reads every matching row, so it is worth taking once, on the press.+ it("keeps the never-uploaded count off the typing path and puts it in the confirmation", async () => {+ const api = renderScreen()+ await api.findByText("12,480")- await waitFor(() => {+ fireEvent.press(api.getByTestId("age-90"))+ await api.findByText("Delete 3,120 locations")++ expect(mockCountUnsentOlderThan).not.toHaveBeenCalled()++ fireEvent.press(api.getByTestId("delete-older-btn"))++ await waitFor(() => expect(mockCountUnsentOlderThan).toHaveBeenCalledWith(90))expect(mockShowConfirm).toHaveBeenCalledWith(- expect.objectContaining({- title: "Clear Sent History",- destructive: true- })+ expect.objectContaining({ message: expect.stringContaining("96 of them have never been uploaded") }))})++ it("re-counts when the age changes", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("age-90"))+ await api.findByText("Delete 3,120 locations")++ mockCountOlderThan.mockResolvedValue({ total: 40, cutoffSeconds: CUTOFF })+ fireEvent.press(api.getByTestId("age-365"))++ expect(await api.findByText("Delete 40 locations")).toBeTruthy()+ expect(mockCountOlderThan).toHaveBeenLastCalledWith(365)+ })++ it("offers no delete when nothing matches", async () => {+ mockCountOlderThan.mockResolvedValue({ total: 0, cutoffSeconds: CUTOFF })+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("age-90"))++ expect(await api.findByText("Nothing on this device is older than 90 days.")).toBeTruthy()+ expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)+ })++ it("rejects a decimal instead of silently deleting by its integer part", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("age-custom"))++ fireEvent.changeText(api.getByTestId("retention-days-input"), "1.5")++ expect(await api.findByText("A whole number")).toBeTruthy()+ // The field owns the error; the button points at it rather than printing it twice.+ expect(api.getByText("Fix the age above.")).toBeTruthy()+ expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)+ })++ it("restores the last settled age on blur, never the minimum, so an emptied box cannot arm a one-day delete", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("age-custom"))+ fireEvent.changeText(api.getByTestId("retention-days-input"), "365")+ await waitFor(() => expect(mockCountOlderThan).toHaveBeenLastCalledWith(365))+ fireEvent.changeText(api.getByTestId("retention-days-input"), "")++ fireEvent(api.getByTestId("retention-days-input"), "blur")++ expect(api.getByTestId("retention-days-input").props.value).toBe("365")+ expect(await api.findByText("Set to 365 days")).toBeTruthy()+ expect(mockCountOlderThan).not.toHaveBeenCalledWith(1)+ })++ // Recording per keystroke caught every prefix, so clearing 365 armed a delete for 3 days.+ it("never restores a keystroke the count skipped", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("age-custom"))+ fireEvent.changeText(api.getByTestId("retention-days-input"), "365")+ fireEvent.changeText(api.getByTestId("retention-days-input"), "36")+ fireEvent.changeText(api.getByTestId("retention-days-input"), "3")+ fireEvent.changeText(api.getByTestId("retention-days-input"), "")++ fireEvent(api.getByTestId("retention-days-input"), "blur")++ expect(api.getByTestId("retention-days-input").props.value).toBe("")+ expect(mockCountOlderThan).not.toHaveBeenCalledWith(3)+ expect(mockCountOlderThan).not.toHaveBeenCalledWith(36)+ })++ // The focus callback is built once from stable dependencies, so anything it reads off state is+ // frozen at the first render. Counting from inside it wiped a count the user had asked for.+ it("keeps the count when the screen is left and come back to", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("age-90"))+ await api.findByText("Delete 3,120 locations")++ await act(async () => {+ mockRefocus?.()+ })++ expect(api.getByText("Delete 3,120 locations")).toBeTruthy()+ expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(false)+ })++ // Nothing has settled, so there is nothing to fall back to and nothing may be armed.+ it("leaves an emptied field empty when no age has ever settled", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("age-custom"))++ fireEvent(api.getByTestId("retention-days-input"), "blur")++ expect(api.getByTestId("retention-days-input").props.value).toBe("")+ expect(api.getByTestId("delete-older-btn").props.accessibilityState.disabled).toBe(true)+ expect(mockCountOlderThan).not.toHaveBeenCalled()+ })})- describe("offline mode", () => {+ describe("sync now", () => {beforeEach(() => {- mockIsOfflineMode = true+ mockLongTimers.length = 0+ mockLongArms = 0+ })++ it("says what it overrides, and that a flush records nothing", async () => {+ mockTracking = false+ const api = renderScreen()++ expect(+ await api.findByText(+ "Uploads the 412 queued locations now, whatever Sync only on says. The tracking notification appears for a moment. Nothing is recorded."+ )+ ).toBeTruthy()+ })++ it("is disabled with the reason when no server is configured, since native does nothing", async () => {+ mockSettings = { ...DEFAULT_SETTINGS, endpoint: "" }+ const api = renderScreen()++ expect(await api.findByText("No server configured. Set one on Connection.")).toBeTruthy()+ expect(api.getByTestId("sync-now-btn").props.accessibilityState.disabled).toBe(true)})- it("hides Sent and Queued stats", async () => {- const { queryByText, getByText } = renderScreen()+ it("reports the run from the progress event and never claims success after failures", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())- await waitFor(() => {- expect(getByText("Total Locations")).toBeTruthy()+ // Native's real shape: ticks while it works, then one event carrying `remaining` to end the pass.+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", { sent: 400, failed: 0, total: 412 })+ DeviceEventEmitter.emit("onSyncProgress", { sent: 400, failed: 12, total: 412, remaining: 12 })})- expect(queryByText("Sent")).toBeNull()- expect(queryByText("Queued")).toBeNull()+ const line = await api.findByText("Sent 400 of 412. Some uploads failed. 12 still queued; press again.")+ expect(line.props.accessibilityValue.text).toBe("error")})- it("hides Queue Actions section", async () => {- const { queryByText, getByText } = renderScreen()+ it("says how many are left when a pass hits the batch cap", async () => {+ mockGetStats.mockResolvedValue(stats({ queued: 620 }))+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", { sent: 500, failed: 0, total: 500, remaining: 120 })+ })++ expect(await api.findByText("Sent 500 of 620. 120 still queued; press again.")).toBeTruthy()+ })- await waitFor(() => {- expect(getByText("Data Management")).toBeTruthy()+ // A pass caps at a fixed number of batches, so its running count never reaches the queue it+ // started with. Waiting for that is what made a good upload report a failure 30 seconds later.+ it("finishes on the pass-end event rather than waiting for the running count to reach the queue", async () => {+ mockGetStats.mockResolvedValue(stats({ queued: 5000 }))+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", { sent: 500, failed: 0, total: 5000, remaining: 4500 })})- expect(queryByText("QUEUE ACTIONS")).toBeNull()- expect(queryByText("Sync Now")).toBeNull()+ expect(await api.findByText("Sent 500 of 5,000. 4,500 still queued; press again.")).toBeTruthy()+ expect(api.queryByText("No answer from the tracking service. The queue is unchanged.")).toBeNull()+ await waitFor(() => expect(api.getByTestId("sync-now-btn").props.accessibilityState.disabled).toBe(false))})- it("hides Clear Sent History and Clear Queue actions", async () => {- const { queryByText, getByText } = renderScreen()+ it("says the queue emptied when it did, and nothing about pressing again", async () => {+ const api = renderScreen()+ await api.findByText("12,480")- await waitFor(() => {- expect(getByText("Data Management")).toBeTruthy()+ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ mockGetStats.mockResolvedValue(stats({ queued: 0 }))+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", { sent: 412, failed: 0, total: 412, remaining: 0 })})- expect(queryByText("Clear Sent History")).toBeNull()- expect(queryByText("Clear Queue")).toBeNull()+ const line = await api.findByText("Sent 412 of 412.")+ expect(line.props.accessibilityValue.text).toBe("info")+ expect(api.queryByText(/press again/)).toBeNull()})- it("still shows Delete Old Locations and Optimize Database", async () => {- const { getByText } = renderScreen()+ // A pass where every upload failed never fires a progress tick, because the tick sites are gated+ // on a batch succeeding, so a terminal event of zero and zero is what a total failure looks like.+ it("does not report a pass that moved nothing as ordinary progress", async () => {+ const api = renderScreen()+ await api.findByText("12,480")- await waitFor(() => {- expect(getByText("Delete Old Locations")).toBeTruthy()- expect(getByText("Optimize Database")).toBeTruthy()+ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", { sent: 0, failed: 412, total: 412, remaining: 412 })})++ const line = await api.findByText("Sent 0 of 412. Some uploads failed. 412 still queued; press again.")+ expect(line.props.accessibilityValue.text).toBe("error")})- it("still shows Today and Storage stats", async () => {- const { getByText } = renderScreen()+ // The fallback means no event for the window, not no ending within the window of the press. Armed+ // once, a pass that keeps reporting past 30 s is declared dead while it is still uploading.+ it("re-arms its silence timer on every progress event", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockLongArms).toBe(1))- await waitFor(() => {- expect(getByText("Today")).toBeTruthy()- expect(getByText("Storage")).toBeTruthy()+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", { sent: 100, failed: 0, total: 412 })})++ expect(mockLongArms).toBe(2)+ expect(await api.findByText("Sent 100 of 412.")).toBeTruthy()})- it("shows Delete All Locations action with total count", async () => {- const { getByText, getAllByText } = renderScreen()+ it("blames the silence rather than the queue when nothing answers", async () => {+ const api = renderScreen()+ await api.findByText("12,480")- await waitFor(() => {- expect(getByText("Delete All Locations")).toBeTruthy()- // "105" appears as Total Locations stat and as Delete All badge- expect(getAllByText("105").length).toBeGreaterThanOrEqual(2)+ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ await act(async () => {+ fireLongTimers()})++ const line = await api.findByText("No answer from the tracking service. Check the queued count above.")+ expect(line.props.accessibilityValue.text).toBe("error")+ await waitFor(() => expect(api.getByTestId("sync-now-btn").props.accessibilityState.disabled).toBe(false))})- it("Delete All Locations shows confirmation dialog", async () => {- const { getByText, getAllByText } = renderScreen()+ it("stops listening for progress once the screen is gone", async () => {+ const api = renderScreen()+ await api.findByText("12,480")+ fireEvent.press(api.getByTestId("sync-now-btn"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ const during = DeviceEventEmitter.listenerCount("onSyncProgress")- await waitFor(() => {- expect(getAllByText("105").length).toBeGreaterThanOrEqual(1)+ api.unmount()++ expect(DeviceEventEmitter.listenerCount("onSyncProgress")).toBeLessThan(during)+ })++ it("leaves the screen entirely in offline mode, where the queue is frozen", async () => {+ mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }+ const api = renderScreen()+ await api.findByText("12,480")++ expect(api.queryByTestId("sync-now-btn")).toBeNull()+ expect(api.queryByTestId("delete-queued-row")).toBeNull()+ expect(api.getByTestId("delete-all-btn")).toBeTruthy()+ })+ })++ describe("what the screen claims before it knows", () => {+ it("does not report an empty device while the first count is still running", async () => {+ mockGetStats.mockReturnValue(new Promise(() => {}))+ const api = renderScreen()++ expect(api.queryByText("Nothing stored")).toBeNull()+ expect(api.queryByTestId("delete-all-btn")).toBeNull()+ expect(within(api.getByTestId("stat-locations")).getByText("…")).toBeTruthy()+ })++ // Every read is numbered, so an earlier one landing late cannot revive a deleted database.+ it("keeps the newer count when a slower earlier read lands after it", async () => {+ let releaseSlow: (v: unknown) => void = () => {}+ mockGetStats+ .mockReturnValueOnce(new Promise((resolve) => (releaseSlow = resolve)))+ .mockResolvedValue(stats({ total: 7 }))+ const api = renderScreen()++ act(() => {+ DeviceEventEmitter.emit("onLocationUpdate", {})})+ await waitFor(() => expect(within(api.getByTestId("stat-locations")).getByText("7")).toBeTruthy())- fireEvent.press(getByText("Delete All Locations"))+ await act(async () => {+ releaseSlow(stats({ total: 12480 }))+ })- await waitFor(() => {- expect(mockShowConfirm).toHaveBeenCalledWith(- expect.objectContaining({- title: "Delete All Locations",- destructive: true- })- )+ expect(within(api.getByTestId("stat-locations")).getByText("7")).toBeTruthy()+ })++ // Both presses land before React commits the busy state, so the disabled prop cannot stop the+ // second one. Only the ref can, which is why the guard is a ref.+ it("cannot arm two confirmations from two presses inside one render", async () => {+ mockShowConfirm.mockReturnValue(new Promise(() => {}))+ const api = renderScreen()+ await api.findByText("12,480")++ act(() => {+ fireEvent.press(api.getByTestId("delete-all-btn"))+ fireEvent.press(api.getByTestId("delete-synced-row"))})++ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ expect(mockShowConfirm).toHaveBeenCalledTimes(1)+ })++ it("says so when the fresh count comes back empty instead of doing nothing", async () => {+ mockGetStats.mockResolvedValue(stats())+ const api = renderScreen()+ await api.findByText("12,480")+ mockGetStats.mockResolvedValue(stats({ sent: 0 }))++ fireEvent.press(api.getByTestId("delete-synced-row"))++ await waitFor(() =>+ expect(mockShowAlert).toHaveBeenCalledWith(+ "Nothing to delete",+ "That count came back empty. The figures above are current.",+ "info"+ )+ )+ expect(mockShowConfirm).not.toHaveBeenCalled()+ })+ })++ describe("compact", () => {+ it("says it deletes nothing and that the deletes already do this", async () => {+ const api = renderScreen()++ expect(+ await api.findByText(+ "Rewrites the database to give unused space back. Deleting trips and points leaves gaps that only this reclaims. Nothing is deleted."+ )+ ).toBeTruthy()+ })++ it("measures both sizes at the same moment, and says nothing rather than claiming a non-event", async () => {+ mockGetStats.mockResolvedValue(stats({ databaseSizeMB: 3.42 }))+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("compact-btn"))++ expect(await api.findByText("Nothing to release")).toBeTruthy()+ })++ it("reports what a real compaction released", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ // Queued only once the mount read has landed, so the sizes pair with the two reads compact takes.+ mockGetStats.mockResolvedValueOnce(stats()).mockResolvedValue(stats({ databaseSizeMB: 3.0 }))+ fireEvent.press(api.getByTestId("compact-btn"))++ expect(await api.findByText(/^Released 0\.4\d MB$/)).toBeTruthy()})})++ it("offers no delete on an empty database and keeps the ledger and Compact", async () => {+ mockGetStats.mockResolvedValue(stats({ total: 0, sent: 0, queued: 0, databaseSizeMB: 0.02 }))+ const api = renderScreen()++ expect(await api.findByText("Nothing stored")).toBeTruthy()+ expect(api.queryByTestId("delete-all-btn")).toBeNull()+ expect(api.getByText("0.02 MB")).toBeTruthy()+ expect(api.getByTestId("compact-btn")).toBeTruthy()+ })})diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex 32caa06e..831e24ff 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -439,9 +439,9 @@ export interface DatabaseStats {today: numberdatabaseSizeMB: number/** Epoch milliseconds of the last successful sync, 0 when none has happened yet. */- lastSyncTime?: number+ lastSyncTime: number/** The masked message of the last sync failure that crossed the consecutive-failure gate, empty after a success. */- lastSyncError?: string+ lastSyncError: string}// ============================================================================diff --git a/apps/mobile/src/utils/__tests__/dataScope.test.ts b/apps/mobile/src/utils/__tests__/dataScope.test.tsnew file mode 100644index 00000000..3df8f2de--- /dev/null+++ b/apps/mobile/src/utils/__tests__/dataScope.test.ts@@ -0,0 +1,116 @@+import { allSub, deleteCopy, olderSub, scopeSub } from "../dataScope"+import { formatDateWithYear, loadDisplayPreferences } from "../geo"++const mockGetSetting = jest.fn()+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: { getSetting: (...args: string[]) => mockGetSetting(...args) }+}))++beforeAll(async () => {+ mockGetSetting.mockResolvedValue("")+ await loadDisplayPreferences()+})++const CUTOFF = Math.floor(new Date(2026, 5, 10, 12, 0, 0).getTime() / 1000)++describe("scopeSub", () => {+ it("says of the queue that no copy survives, because these were never uploaded", () => {+ expect(scopeSub("queued", 412)).toBe(+ "412 locations waiting to upload. Nothing else holds a copy, and they leave History too."+ )+ })++ it("says of the synced set that an import counts as synced, which no label has said", () => {+ // bulkInsertImportedLocations writes sent = 1, so an archive that never touched a network is inside this delete.+ expect(scopeSub("synced", 12068)).toBe(+ "12,068 locations already on your server. Imported locations count as synced."+ )+ })++ it("explains a disabled row in its own slot instead of leaving it blank", () => {+ expect(scopeSub("queued", 0)).toBe("Nothing queued.")+ expect(scopeSub("synced", 0)).toBe("Nothing has been uploaded yet.")+ })++ it("agrees with itself at one, so no row says 1 locations", () => {+ expect(scopeSub("queued", 1)).toMatch(/^1 location waiting/)+ expect(scopeSub("synced", 1)).toMatch(/^1 location already/)+ })+})++describe("olderSub", () => {+ it("names the boundary the count used", () => {+ expect(olderSub(3120, 90, CUTOFF)).toBe(`Recorded before ${formatDateWithYear(CUTOFF)}.`)+ })++ // Counting those reads every matching row, so the confirmation is the only place worth taking it.+ it("leaves how many were never uploaded to the confirmation", () => {+ expect(olderSub(3120, 90, CUTOFF)).not.toContain("uploaded")+ })++ it("says nothing matches rather than offering a delete of zero", () => {+ expect(olderSub(0, 90, CUTOFF)).toBe("Nothing on this device is older than 90 days.")+ expect(olderSub(0, 1, CUTOFF)).toBe("Nothing on this device is older than 1 day.")+ })+})++describe("allSub", () => {+ it("names the trip splits and merges, which no label, hint or dialog has ever named", () => {+ // clearAllLocations empties boundary_overrides as well as locations and the queue.+ expect(allSub(12480)).toBe(+ "All 12,480 locations and every trip split and merge you made. Geofences, profiles and settings stay."+ )+ })+})++describe("deleteCopy", () => {+ it("tells the queued case that the recordings go, not the pending uploads", () => {+ const copy = deleteCopy("queued", 412)+ expect(copy.title).toBe("Delete 412 queued locations?")+ expect(copy.message).toMatch(/^These are the locations themselves, not their pending uploads\./)+ expect(copy.message).toMatch(/no copy survives anywhere and they leave History too/)+ // The one confirmation that used to omit it, while destroying recordings.+ expect(copy.message).toMatch(/This cannot be undone\.$/)+ expect(copy.confirmText).toBe("Delete")+ })++ it("tells the synced case that History empties and an import is included", () => {+ const copy = deleteCopy("synced", 12068)+ expect(copy.title).toBe("Delete 12,068 synced locations?")+ expect(copy.message).toMatch(/not an upload record/)+ expect(copy.message).toMatch(/locations you imported count as synced/)+ expect(copy.message).toMatch(/Copies already on your server stay there/)+ })++ it("tells the age case that it ignores sync state, naming the boundary and the unsent matches", () => {+ const copy = deleteCopy("older", 3120, { days: 90, cutoffSeconds: CUTOFF, unsent: 96 })+ expect(copy.title).toBe("Delete 3,120 locations older than 90 days?")+ expect(copy.message).toMatch(new RegExp(`before ${formatDateWithYear(CUTOFF)}`))+ expect(copy.message).toMatch(/96 of them have never been uploaded, so no copy of those survives/)+ })++ it("drops the unsent clause from the age case when there is none, leaving one space between sentences", () => {+ const copy = deleteCopy("older", 3120, { days: 90, cutoffSeconds: CUTOFF, unsent: 0 })+ expect(copy.message).not.toMatch(/never been uploaded/)+ expect(copy.message).not.toMatch(/ {2}/)+ })++ it("tells the everything case about the trip splits and what survives, and asks for a distinct verb", () => {+ const copy = deleteCopy("all", 12480)+ expect(copy.title).toBe("Delete all 12,480 locations?")+ expect(copy.message).toMatch(/every manual trip split and merge you made/)+ expect(copy.message).toMatch(/settings, geofences and profiles stay/)+ expect(copy.confirmText).toBe("Delete all")+ })++ it("ends every confirmation with the permanence, since none of the four can be undone", () => {+ const cases = [+ deleteCopy("queued", 1),+ deleteCopy("synced", 1),+ deleteCopy("older", 1, { days: 1, cutoffSeconds: CUTOFF, unsent: 0 }),+ deleteCopy("all", 1)+ ]+ for (const copy of cases) expect(copy.message).toMatch(/This cannot be undone\.$/)+ })+})diff --git a/apps/mobile/src/utils/dataScope.ts b/apps/mobile/src/utils/dataScope.tsnew file mode 100644index 00000000..e59a1192--- /dev/null+++ b/apps/mobile/src/utils/dataScope.ts@@ -0,0 +1,98 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { formatDateWithYear } from "./geo"++/**+ * What each delete on Data management takes, in the words the control and its confirmation use.+ *+ * The wording is pinned to the SQL, not to the old labels: `clearSentHistory` is+ * `DELETE FROM locations WHERE sent = 1`, so synced days leave History and imported archives go+ * with them; `clearQueue` deletes the recordings, not their pending uploads; `deleteOlderThan`+ * ignores sync state; `clearAllLocations` also empties `boundary_overrides`, every manual trip+ * split. A test pins every sentence without rendering the screen.+ */++export type DataScope = "queued" | "synced" | "older" | "all"++export interface DeleteCopy {+ title: string+ message: string+ confirmText: string+}++const plural = (n: number, noun: string) => `${n.toLocaleString()} ${noun}${n === 1 ? "" : "s"}`++/** The sub under a delete row, or the message under a delete button: what this press would take. */+export function scopeSub(scope: "queued" | "synced", count: number): string {+ if (scope === "queued") {+ return count === 0+ ? "Nothing queued."+ : `${plural(count, "location")} waiting to upload. Nothing else holds a copy, and they leave History too.`+ }+ return count === 0+ ? "Nothing has been uploaded yet."+ : `${plural(count, "location")} already on your server. Imported locations count as synced.`+}++/**+ * The line under the age button: the boundary the count used. How many of them have no copy on the+ * server is not here, because that count reads every matching row and is only worth taking once, on+ * the press, where `deleteCopy` says it.+ */+export function olderSub(count: number, days: number, cutoffSeconds: number): string {+ if (count === 0) return `Nothing on this device is older than ${plural(days, "day")}.`+ return `Recorded before ${formatDateWithYear(cutoffSeconds)}.`+}++/** The line under Delete all: the two things it takes that no label has ever named. */+export function allSub(total: number): string {+ return `All ${plural(total, "location")} and every trip split and merge you made. Geofences, profiles and settings stay.`+}++export interface OlderArgs {+ days: number+ /** The boundary in Unix seconds, from the same native read that produced the count. */+ cutoffSeconds: number+ unsent: number+}++/** The confirmation for one delete. Every count comes from a read taken immediately before the dialog. */+export function deleteCopy(scope: DataScope, count: number, older?: OlderArgs): DeleteCopy {+ switch (scope) {+ case "queued":+ return {+ title: `Delete ${plural(count, "queued location")}?`,+ message:+ "These are the locations themselves, not their pending uploads. Once deleted, no copy survives anywhere and they leave History too. Points already handed to your server during a running sync may still arrive. This cannot be undone.",+ confirmText: "Delete"+ }+ case "synced":+ return {+ title: `Delete ${plural(count, "synced location")}?`,+ message: `Removes ${plural(count, "location")} from this device, not an upload record. Those days leave History, notes included, and locations you imported count as synced. Copies already on your server stay there. This cannot be undone.`,+ confirmText: "Delete"+ }+ case "older": {+ const { days = 0, cutoffSeconds = 0, unsent = 0 } = older ?? ({} as OlderArgs)+ const never =+ unsent === 0+ ? ""+ : ` ${unsent.toLocaleString()} of them have never been uploaded, so no copy of those survives.`+ return {+ title: `Delete ${plural(count, "location")} older than ${plural(days, "day")}?`,+ message: `Removes every location recorded before ${formatDateWithYear(cutoffSeconds)} from this device.${never} Those days leave History. Copies already on your server stay there. This cannot be undone.`,+ confirmText: "Delete"+ }+ }+ case "all":+ return {+ title: `Delete all ${plural(count, "location")}?`,+ message:+ "Removes every location on this device, its upload queue and every manual trip split and merge you made. History becomes empty. Your settings, geofences and profiles stay, and copies already on your server are not touched. This cannot be undone.",+ confirmText: "Delete all"+ }+ }+}