feat: Sprint 5 — PIN lock, biometric auth, sync screen, QR code, merge logic

- lib/pinService.ts: PIN storage/verification via expo-secure-store
- lib/syncService.ts: sync abstraction with full merge logic (mDNS/TCP stubbed)
- app/lock.tsx: full-screen PIN lock with biometric support
- components/ui/PinPad.tsx: reusable 6-digit PIN pad component
- components/sync/QRScanner.tsx: QR code scanner via expo-camera
- app/(tabs)/sync.tsx: Sync tab with QR display, partner input, history
- app/sync-progress.tsx: animated sync progress screen with summary
- app/(tabs)/settings.tsx: full settings with PIN setup, security, data sections
- app/(tabs)/_layout.tsx: added Sync tab (RefreshCw icon)
- app/_layout.tsx: AppState listener locks app after 60s background
- package.json: added expo-secure-store, react-native-qrcode-svg
This commit is contained in:
2026-02-18 19:57:35 +08:00
parent 123b21f4db
commit 6fe6ebef13
12 changed files with 18385 additions and 22 deletions

View File

@@ -1,7 +1,7 @@
// app/(tabs)/_layout.tsx
import { Tabs, router } from 'expo-router';
import { useEffect } from 'react';
import { Home, Users, Map, Settings, MapPin } from 'lucide-react-native';
import { Home, Users, Map, Settings, MapPin, RefreshCw } from 'lucide-react-native';
import { useUserStore } from '@/store/useUserStore';
export default function TabLayout() {
@@ -21,11 +21,48 @@ export default function TabLayout() {
headerShown: false,
}}
>
<Tabs.Screen name="index" options={{ title: 'Home', tabBarIcon: ({ color, size }) => <Home size={size} color={color} /> }} />
<Tabs.Screen name="contacts" options={{ title: 'Contacts', tabBarIcon: ({ color, size }) => <Users size={size} color={color} /> }} />
<Tabs.Screen name="territories" options={{ title: 'Territories', tabBarIcon: ({ color, size }) => <MapPin size={size} color={color} /> }} />
<Tabs.Screen name="map" options={{ title: 'Map', tabBarIcon: ({ color, size }) => <Map size={size} color={color} /> }} />
<Tabs.Screen name="settings" options={{ title: 'Settings', tabBarIcon: ({ color, size }) => <Settings size={size} color={color} /> }} />
<Tabs.Screen
name="index"
options={{
title: 'Home',
tabBarIcon: ({ color, size }) => <Home size={size} color={color} />,
}}
/>
<Tabs.Screen
name="contacts"
options={{
title: 'Contacts',
tabBarIcon: ({ color, size }) => <Users size={size} color={color} />,
}}
/>
<Tabs.Screen
name="territories"
options={{
title: 'Territories',
tabBarIcon: ({ color, size }) => <MapPin size={size} color={color} />,
}}
/>
<Tabs.Screen
name="map"
options={{
title: 'Map',
tabBarIcon: ({ color, size }) => <Map size={size} color={color} />,
}}
/>
<Tabs.Screen
name="sync"
options={{
title: 'Sync',
tabBarIcon: ({ color, size }) => <RefreshCw size={size} color={color} />,
}}
/>
<Tabs.Screen
name="settings"
options={{
title: 'Settings',
tabBarIcon: ({ color, size }) => <Settings size={size} color={color} />,
}}
/>
</Tabs>
);
}

View File

@@ -1,10 +1,574 @@
import { View, Text } from 'react-native';
// app/(tabs)/settings.tsx — Full Settings Screen with PIN setup
import React, { useState, useEffect, useCallback } from 'react';
import {
View,
Text,
StyleSheet,
ScrollView,
Switch,
TouchableOpacity,
Alert,
Modal,
SafeAreaView,
ActivityIndicator,
} from 'react-native';
import { router } from 'expo-router';
import {
User,
Shield,
Fingerprint,
RefreshCw,
BookOpen,
Download,
Upload,
Trash2,
Info,
ChevronRight,
X,
} from 'lucide-react-native';
import * as LocalAuthentication from 'expo-local-authentication';
import { useUserStore } from '@/store/useUserStore';
import {
isPinEnabled,
setPin,
verifyPin,
disablePin,
isBiometricEnabled,
setBiometricEnabled,
} from '@/lib/pinService';
import { getDatabase } from '@/lib/database';
import PinPad from '@/components/ui/PinPad';
// ── PIN Flow Modal ────────────────────────────────────────────────────────────
type PinFlowMode = 'set' | 'verify';
interface PinFlowProps {
mode: PinFlowMode;
onSuccess: (pin?: string) => void;
onCancel: () => void;
title: string;
subtitle?: string;
}
function PinFlowModal({ mode, onSuccess, onCancel, title, subtitle }: PinFlowProps) {
const [step, setStep] = useState<'enter' | 'confirm'>('enter');
const [pin, setCurrentPin] = useState('');
const [firstPin, setFirstPin] = useState('');
const [error, setError] = useState('');
const handlePinChange = async (newPin: string) => {
setCurrentPin(newPin);
setError('');
if (newPin.length < 6) return;
if (mode === 'verify') {
const ok = await verifyPin(newPin);
if (ok) {
onSuccess(newPin);
} else {
setError('Incorrect PIN. Try again.');
setTimeout(() => setCurrentPin(''), 600);
}
return;
}
// mode === 'set'
if (step === 'enter') {
setFirstPin(newPin);
setCurrentPin('');
setStep('confirm');
} else {
// confirm step
if (newPin === firstPin) {
onSuccess(newPin);
} else {
setError('PINs do not match. Try again.');
setStep('enter');
setFirstPin('');
setTimeout(() => setCurrentPin(''), 400);
}
}
};
const displayTitle = mode === 'set'
? step === 'enter' ? 'Set PIN' : 'Confirm PIN'
: title;
const displaySubtitle = mode === 'set'
? step === 'enter'
? 'Enter a 6-digit PIN'
: 'Re-enter your PIN to confirm'
: subtitle;
return (
<Modal visible animationType="slide" onRequestClose={onCancel}>
<SafeAreaView style={pinStyles.container}>
<View style={pinStyles.header}>
<TouchableOpacity onPress={onCancel} style={pinStyles.closeBtn}>
<X size={22} color="#9CA3AF" />
</TouchableOpacity>
</View>
<View style={pinStyles.content}>
<Text style={pinStyles.title}>{displayTitle}</Text>
{displaySubtitle ? (
<Text style={pinStyles.subtitle}>{displaySubtitle}</Text>
) : null}
{error ? <Text style={pinStyles.error}>{error}</Text> : null}
<PinPad pin={pin} onPinChange={handlePinChange} maxLength={6} />
</View>
</SafeAreaView>
</Modal>
);
}
const pinStyles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#0F172A' },
header: { alignItems: 'flex-end', padding: 16 },
closeBtn: {
width: 36, height: 36, borderRadius: 18,
backgroundColor: 'rgba(255,255,255,0.08)',
justifyContent: 'center', alignItems: 'center',
},
content: {
flex: 1, alignItems: 'center', justifyContent: 'center',
paddingHorizontal: 24, gap: 28,
},
title: { fontSize: 24, fontWeight: '700', color: '#F9FAFB' },
subtitle: { fontSize: 15, color: '#9CA3AF', textAlign: 'center' },
error: { fontSize: 14, color: '#F87171', textAlign: 'center' },
});
// ── Settings Screen ───────────────────────────────────────────────────────────
export default function SettingsScreen() {
const user = useUserStore((s) => s.user);
const clearUser = useUserStore((s) => s.clearUser);
const [pinEnabled, setPinEnabledState] = useState(false);
const [biometricEnabled, setBiometricEnabledState] = useState(false);
const [biometricSupported, setBiometricSupported] = useState(false);
const [loading, setLoading] = useState(true);
const [pinFlowVisible, setPinFlowVisible] = useState(false);
const [pinFlowMode, setPinFlowMode] = useState<'set' | 'verify'>('set');
const [pinFlowCallback, setPinFlowCallback] = useState<((pin?: string) => void) | null>(null);
const [pinFlowTitle, setPinFlowTitle] = useState('');
const [pinFlowSubtitle, setPinFlowSubtitle] = useState('');
useEffect(() => {
loadSecurityState();
}, []);
const loadSecurityState = async () => {
try {
const [pinOn, bioOn, hw, enrolled] = await Promise.all([
isPinEnabled(),
isBiometricEnabled(),
LocalAuthentication.hasHardwareAsync(),
LocalAuthentication.isEnrolledAsync(),
]);
setPinEnabledState(pinOn);
setBiometricEnabledState(bioOn);
setBiometricSupported(hw && enrolled);
} catch {
// ignore
} finally {
setLoading(false);
}
};
const openPinFlow = useCallback(
(
mode: 'set' | 'verify',
title: string,
subtitle: string,
callback: (pin?: string) => void
) => {
setPinFlowMode(mode);
setPinFlowTitle(title);
setPinFlowSubtitle(subtitle);
setPinFlowCallback(() => callback);
setPinFlowVisible(true);
},
[]
);
const handleTogglePin = async (value: boolean) => {
if (value) {
// Turning ON: show Set PIN flow
openPinFlow('set', 'Set PIN', 'Enter a 6-digit PIN', async (pin) => {
if (pin) {
await setPin(pin);
setPinEnabledState(true);
setPinFlowVisible(false);
Alert.alert('PIN Set', 'Your app is now protected with a PIN.');
}
});
} else {
// Turning OFF: verify first
openPinFlow(
'verify',
'Disable PIN Lock',
'Enter your current PIN to disable',
async () => {
await disablePin();
setPinEnabledState(false);
setBiometricEnabledState(false);
setPinFlowVisible(false);
Alert.alert('PIN Disabled', 'App lock has been turned off.');
}
);
}
};
const handleToggleBiometric = async (value: boolean) => {
await setBiometricEnabled(value);
setBiometricEnabledState(value);
};
const handleClearData = () => {
Alert.alert(
'Clear All Data',
'This will permanently delete all contacts, visits, territories, and sync history. This cannot be undone.',
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete Everything',
style: 'destructive',
onPress: async () => {
try {
const db = await getDatabase();
await db.execAsync(`
DELETE FROM contacts;
DELETE FROM visits;
DELETE FROM territories;
DELETE FROM sync_log;
`);
Alert.alert('Done', 'All data has been cleared.');
} catch {
Alert.alert('Error', 'Failed to clear data.');
}
},
},
]
);
};
const handleExportBackup = () => {
Alert.alert('Export Backup', 'Export feature coming in a future sprint.');
};
const handleImportBackup = () => {
Alert.alert('Import Backup', 'Import feature coming in a future sprint.');
};
if (loading) {
return (
<View className="flex-1 items-center justify-center bg-secondary">
<Text className="text-xl text-charcoal">Settings</Text>
<Text className="text-gray-500 mt-2">Coming in Sprint 6</Text>
<View style={styles.loadingContainer}>
<ActivityIndicator color="#1A6B72" />
</View>
);
}
return (
<SafeAreaView style={styles.safe}>
<ScrollView
style={styles.container}
contentContainerStyle={styles.content}
showsVerticalScrollIndicator={false}
>
{/* Header */}
<Text style={styles.pageTitle}>Settings</Text>
{/* ── Profile ── */}
<SectionHeader title="Profile" />
<View style={styles.card}>
<View style={styles.profileRow}>
<View style={styles.avatar}>
<User size={28} color="#1A6B72" />
</View>
<View style={{ flex: 1, gap: 2 }}>
<Text style={styles.profileName}>{user?.displayName ?? '—'}</Text>
<Text style={styles.profileShareId}>
Share ID: <Text style={styles.shareIdMono}>{user?.shareId ?? '—'}</Text>
</Text>
</View>
</View>
</View>
{/* ── Security ── */}
<SectionHeader title="Security" />
<View style={styles.card}>
<SettingsRow
icon={<Shield size={18} color="#1A6B72" />}
label="App Lock (PIN)"
right={
<Switch
value={pinEnabled}
onValueChange={handleTogglePin}
trackColor={{ false: '#D1D5DB', true: '#1A6B72' }}
thumbColor="#fff"
/>
}
/>
{pinEnabled && biometricSupported && (
<>
<Divider />
<SettingsRow
icon={<Fingerprint size={18} color="#1A6B72" />}
label="Biometric Unlock"
right={
<Switch
value={biometricEnabled}
onValueChange={handleToggleBiometric}
trackColor={{ false: '#D1D5DB', true: '#1A6B72' }}
thumbColor="#fff"
/>
}
/>
</>
)}
</View>
{/* ── Sync ── */}
<SectionHeader title="Sync" />
<View style={styles.card}>
<SettingsRow
icon={<RefreshCw size={18} color="#1A6B72" />}
label="Sync with Device"
right={<ChevronRight size={16} color="#9CA3AF" />}
onPress={() => router.push('/(tabs)/sync')}
/>
</View>
{/* ── Data ── */}
<SectionHeader title="Data" />
<View style={styles.card}>
<SettingsRow
icon={<BookOpen size={18} color="#1A6B72" />}
label="Topic Library"
right={<ChevronRight size={16} color="#9CA3AF" />}
onPress={() =>
Alert.alert('Topic Library', 'Manage visit topics in a future update.')
}
/>
<Divider />
<SettingsRow
icon={<Download size={18} color="#1A6B72" />}
label="Export Backup"
right={<ChevronRight size={16} color="#9CA3AF" />}
onPress={handleExportBackup}
/>
<Divider />
<SettingsRow
icon={<Upload size={18} color="#1A6B72" />}
label="Import Backup"
right={<ChevronRight size={16} color="#9CA3AF" />}
onPress={handleImportBackup}
/>
<Divider />
<SettingsRow
icon={<Trash2 size={18} color="#EF4444" />}
label="Clear All Data"
labelStyle={{ color: '#EF4444' }}
right={<ChevronRight size={16} color="#9CA3AF" />}
onPress={handleClearData}
/>
</View>
{/* ── About ── */}
<SectionHeader title="About" />
<View style={styles.card}>
<SettingsRow
icon={<Info size={18} color="#1A6B72" />}
label="TerritoryLog"
right={<Text style={styles.versionText}>v1.0.0 (Sprint 5)</Text>}
/>
<Divider />
<View style={styles.aboutRow}>
<Text style={styles.aboutText}>
A local-first ministry record keeping app. All data stays on your device.
</Text>
</View>
</View>
<View style={{ height: 32 }} />
</ScrollView>
{/* PIN Flow Modal */}
{pinFlowVisible && pinFlowCallback && (
<PinFlowModal
mode={pinFlowMode}
title={pinFlowTitle}
subtitle={pinFlowSubtitle}
onSuccess={(pin) => pinFlowCallback(pin)}
onCancel={() => setPinFlowVisible(false)}
/>
)}
</SafeAreaView>
);
}
// ── Sub-components ──────────────────────────────────────────────────────────
function SectionHeader({ title }: { title: string }) {
return <Text style={styles.sectionHeader}>{title}</Text>;
}
function Divider() {
return <View style={styles.divider} />;
}
interface SettingsRowProps {
icon: React.ReactNode;
label: string;
labelStyle?: object;
right?: React.ReactNode;
onPress?: () => void;
}
function SettingsRow({ icon, label, labelStyle, right, onPress }: SettingsRowProps) {
const Row = onPress ? TouchableOpacity : View;
return (
<Row
style={styles.settingsRow}
onPress={onPress}
activeOpacity={0.7}
>
<View style={styles.settingsRowLeft}>
<View style={styles.rowIcon}>{icon}</View>
<Text style={[styles.rowLabel, labelStyle]}>{label}</Text>
</View>
{right && <View style={styles.settingsRowRight}>{right}</View>}
</Row>
);
}
// ── Styles ──────────────────────────────────────────────────────────────────
const styles = StyleSheet.create({
safe: {
flex: 1,
backgroundColor: '#F8F4EF',
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F8F4EF',
},
container: {
flex: 1,
},
content: {
paddingBottom: 16,
},
pageTitle: {
fontSize: 28,
fontWeight: '700',
color: '#111827',
paddingHorizontal: 20,
paddingTop: 20,
paddingBottom: 4,
},
sectionHeader: {
fontSize: 12,
fontWeight: '600',
color: '#6B7280',
letterSpacing: 0.8,
textTransform: 'uppercase',
paddingHorizontal: 20,
paddingTop: 20,
paddingBottom: 6,
},
card: {
backgroundColor: '#fff',
marginHorizontal: 16,
borderRadius: 16,
paddingVertical: 4,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.05,
shadowRadius: 4,
elevation: 2,
},
profileRow: {
flexDirection: 'row',
alignItems: 'center',
padding: 16,
gap: 14,
},
avatar: {
width: 52,
height: 52,
borderRadius: 26,
backgroundColor: '#EFF9F9',
justifyContent: 'center',
alignItems: 'center',
borderWidth: 2,
borderColor: '#B2DFDF',
},
profileName: {
fontSize: 17,
fontWeight: '700',
color: '#111827',
},
profileShareId: {
fontSize: 13,
color: '#6B7280',
},
shareIdMono: {
fontFamily: 'monospace',
color: '#1A6B72',
fontWeight: '600',
},
settingsRow: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 16,
paddingVertical: 14,
},
settingsRowLeft: {
flexDirection: 'row',
alignItems: 'center',
gap: 12,
flex: 1,
},
rowIcon: {
width: 32,
height: 32,
borderRadius: 8,
backgroundColor: '#F3F4F6',
justifyContent: 'center',
alignItems: 'center',
},
rowLabel: {
fontSize: 15,
color: '#111827',
fontWeight: '500',
},
settingsRowRight: {
flexShrink: 0,
marginLeft: 8,
},
divider: {
height: 1,
backgroundColor: '#F3F4F6',
marginHorizontal: 16,
},
versionText: {
fontSize: 13,
color: '#9CA3AF',
},
aboutRow: {
paddingHorizontal: 16,
paddingVertical: 12,
},
aboutText: {
fontSize: 13,
color: '#6B7280',
lineHeight: 20,
},
});

599
app/(tabs)/sync.tsx Normal file
View File

@@ -0,0 +1,599 @@
// app/(tabs)/sync.tsx — Sync Tab
import React, { useState, useEffect, useCallback } from 'react';
import {
View,
Text,
StyleSheet,
ScrollView,
TouchableOpacity,
TextInput,
Alert,
Modal,
SafeAreaView,
ActivityIndicator,
} from 'react-native';
import { router } from 'expo-router';
import {
RefreshCw,
QrCode,
Camera,
Wifi,
Clock,
ChevronDown,
ChevronUp,
Share2,
AlertCircle,
} from 'lucide-react-native';
import { useUserStore } from '@/store/useUserStore';
import { getSyncHistory, SyncLogEntry } from '@/lib/syncService';
import QRScanner from '@/components/sync/QRScanner';
// Lazy-load QRCode to handle missing package gracefully
let QRCode: any = null;
try {
QRCode = require('react-native-qrcode-svg').default;
} catch {
QRCode = null;
}
function formatDate(ts: number): string {
return new Date(ts * 1000).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
});
}
export default function SyncScreen() {
const user = useUserStore((s) => s.user);
const shareId = user?.shareId ?? 'TL-????????';
const [syncHistory, setSyncHistory] = useState<SyncLogEntry[]>([]);
const [loadingHistory, setLoadingHistory] = useState(true);
const [partnerShareId, setPartnerShareId] = useState('');
const [showScanner, setShowScanner] = useState(false);
const [showHowTo, setShowHowTo] = useState(false);
useEffect(() => {
loadHistory();
}, []);
const loadHistory = async () => {
try {
const history = await getSyncHistory();
setSyncHistory(history);
} catch (e) {
console.error('Failed to load sync history:', e);
} finally {
setLoadingHistory(false);
}
};
const handleScanned = useCallback((scannedId: string) => {
setShowScanner(false);
setPartnerShareId(scannedId);
}, []);
const handleStartSync = () => {
const trimmed = partnerShareId.trim().toUpperCase();
if (!trimmed.match(/^TL-[A-Z0-9]{8}$/)) {
Alert.alert(
'Invalid Share ID',
'Please enter a valid Share ID in the format TL-XXXXXXXX'
);
return;
}
if (trimmed === shareId) {
Alert.alert('Same Device', 'You cannot sync with yourself.');
return;
}
// Navigate to sync-progress (actual sync requires bare workflow)
Alert.alert(
'WiFi Sync Not Available',
'Direct WiFi sync requires expo-dev-client and bare workflow.\n\nShare IDs can be exchanged manually. Network sync will be available in a future release.',
[
{ text: 'OK' },
{
text: 'View Progress Demo',
onPress: () =>
router.push({
pathname: '/sync-progress',
params: {
partnerName: trimmed,
sentCount: '0',
receivedCount: '0',
conflictCount: '0',
},
}),
},
]
);
};
return (
<SafeAreaView style={styles.safe}>
<ScrollView
style={styles.container}
contentContainerStyle={styles.content}
showsVerticalScrollIndicator={false}
>
{/* Header */}
<View style={styles.header}>
<RefreshCw size={24} color="#1A6B72" />
<Text style={styles.headerTitle}>Sync</Text>
</View>
{/* ── Your Share ID ── */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Your Share ID</Text>
<View style={styles.qrCard}>
{QRCode ? (
<View style={styles.qrCodeWrapper}>
<QRCode
value={shareId}
size={180}
color="#111827"
backgroundColor="#FFFFFF"
/>
</View>
) : (
<View style={styles.qrPlaceholder}>
<QrCode size={64} color="#9CA3AF" />
<Text style={styles.qrPlaceholderText}>QR Code</Text>
<Text style={styles.qrPlaceholderSub}>
Install react-native-qrcode-svg to display
</Text>
</View>
)}
<View style={styles.shareIdRow}>
<Text style={styles.shareIdLabel}>Share ID</Text>
<View style={styles.shareIdBadge}>
<Share2 size={14} color="#1A6B72" />
<Text style={styles.shareIdText}>{shareId}</Text>
</View>
</View>
<Text style={styles.shareIdHint}>
Show this QR code to your partner so they can connect to you.
</Text>
</View>
</View>
{/* ── Connect to Partner ── */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Connect to Partner</Text>
<View style={styles.card}>
{/* Scan QR button */}
<TouchableOpacity
style={styles.scanBtn}
onPress={() => setShowScanner(true)}
>
<Camera size={20} color="#fff" />
<Text style={styles.scanBtnText}>Scan Partner QR Code</Text>
</TouchableOpacity>
<View style={styles.orRow}>
<View style={styles.orLine} />
<Text style={styles.orText}>or enter manually</Text>
<View style={styles.orLine} />
</View>
{/* Manual input */}
<TextInput
style={styles.input}
placeholder="TL-XXXXXXXX"
placeholderTextColor="#9CA3AF"
value={partnerShareId}
onChangeText={setPartnerShareId}
autoCapitalize="characters"
maxLength={11}
/>
<TouchableOpacity
style={[
styles.connectBtn,
!partnerShareId && styles.connectBtnDisabled,
]}
onPress={handleStartSync}
disabled={!partnerShareId}
>
<RefreshCw size={18} color="#fff" />
<Text style={styles.connectBtnText}>Start Sync</Text>
</TouchableOpacity>
</View>
</View>
{/* ── Discovered Devices ── */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Discovered Devices</Text>
<View style={[styles.card, styles.wifiNotice]}>
<AlertCircle size={20} color="#F59E0B" />
<View style={{ flex: 1, gap: 4 }}>
<Text style={styles.wifiNoticeTitle}>WiFi Sync Requires Setup</Text>
<Text style={styles.wifiNoticeText}>
Automatic device discovery (mDNS) requires expo-dev-client and
bare workflow. Exchange Share IDs manually for now.
</Text>
</View>
</View>
</View>
{/* ── Sync History ── */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Sync History</Text>
<View style={styles.card}>
{loadingHistory ? (
<ActivityIndicator color="#1A6B72" style={{ padding: 16 }} />
) : syncHistory.length === 0 ? (
<View style={styles.emptyHistory}>
<Clock size={32} color="#D1D5DB" />
<Text style={styles.emptyHistoryText}>No syncs yet</Text>
</View>
) : (
syncHistory.map((entry) => (
<View key={entry.id} style={styles.historyItem}>
<View style={styles.historyLeft}>
<Text style={styles.historyPartner}>
{entry.partner_name ?? entry.partner_id}
</Text>
<Text style={styles.historyDate}>
{formatDate(entry.synced_at)}
</Text>
</View>
<View style={styles.historyRight}>
<Text style={styles.historySent}> {entry.sent_count}</Text>
<Text style={styles.historyReceived}> {entry.received_count}</Text>
</View>
</View>
))
)}
</View>
</View>
{/* ── How to Sync ── */}
<View style={styles.section}>
<TouchableOpacity
style={styles.howToToggle}
onPress={() => setShowHowTo(!showHowTo)}
>
<Text style={styles.sectionTitle}>How to Sync</Text>
{showHowTo ? (
<ChevronUp size={18} color="#6B7280" />
) : (
<ChevronDown size={18} color="#6B7280" />
)}
</TouchableOpacity>
{showHowTo && (
<View style={styles.card}>
{HOW_TO_STEPS.map((step, i) => (
<View key={i} style={styles.howToStep}>
<View style={styles.howToNumber}>
<Text style={styles.howToNumberText}>{i + 1}</Text>
</View>
<View style={{ flex: 1, gap: 2 }}>
<Text style={styles.howToStepTitle}>{step.title}</Text>
<Text style={styles.howToStepBody}>{step.body}</Text>
</View>
</View>
))}
</View>
)}
</View>
</ScrollView>
{/* QR Scanner Modal */}
<Modal
visible={showScanner}
animationType="slide"
onRequestClose={() => setShowScanner(false)}
>
<QRScanner
onScanned={handleScanned}
onCancel={() => setShowScanner(false)}
/>
</Modal>
</SafeAreaView>
);
}
const HOW_TO_STEPS = [
{
title: 'Open TerritoryLog on both devices',
body: 'Both devices must have TerritoryLog installed and be on the same WiFi network.',
},
{
title: 'Share your QR code or Share ID',
body: 'Show the QR code above to your partner, or tell them your Share ID (TL-XXXXXXXX).',
},
{
title: 'Scan or enter their Share ID',
body: "Use the scanner or type their Share ID into the input field on one device.",
},
{
title: 'Start sync',
body: 'Tap "Start Sync". Records are merged intelligently — the most recently updated version of each record wins.',
},
{
title: 'Done!',
body: 'Both devices will have the same up-to-date data. No cloud required.',
},
];
const styles = StyleSheet.create({
safe: {
flex: 1,
backgroundColor: '#F8F4EF',
},
container: {
flex: 1,
},
content: {
paddingBottom: 32,
},
header: {
flexDirection: 'row',
alignItems: 'center',
gap: 10,
paddingHorizontal: 20,
paddingTop: 20,
paddingBottom: 8,
},
headerTitle: {
fontSize: 26,
fontWeight: '700',
color: '#111827',
},
section: {
marginTop: 20,
paddingHorizontal: 16,
gap: 8,
},
sectionTitle: {
fontSize: 13,
fontWeight: '600',
color: '#6B7280',
letterSpacing: 0.6,
textTransform: 'uppercase',
},
card: {
backgroundColor: '#fff',
borderRadius: 16,
padding: 16,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.05,
shadowRadius: 4,
elevation: 2,
gap: 12,
},
qrCard: {
backgroundColor: '#fff',
borderRadius: 16,
padding: 20,
alignItems: 'center',
gap: 16,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.05,
shadowRadius: 4,
elevation: 2,
},
qrCodeWrapper: {
padding: 12,
backgroundColor: '#fff',
borderRadius: 12,
borderWidth: 1,
borderColor: '#E5E7EB',
},
qrPlaceholder: {
width: 180,
height: 180,
backgroundColor: '#F3F4F6',
borderRadius: 12,
justifyContent: 'center',
alignItems: 'center',
gap: 8,
borderWidth: 2,
borderColor: '#E5E7EB',
borderStyle: 'dashed',
},
qrPlaceholderText: {
color: '#6B7280',
fontSize: 14,
fontWeight: '600',
},
qrPlaceholderSub: {
color: '#9CA3AF',
fontSize: 11,
textAlign: 'center',
paddingHorizontal: 12,
},
shareIdRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 10,
},
shareIdLabel: {
color: '#6B7280',
fontSize: 13,
},
shareIdBadge: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
backgroundColor: '#EFF9F9',
paddingVertical: 6,
paddingHorizontal: 12,
borderRadius: 20,
borderWidth: 1,
borderColor: '#B2DFDF',
},
shareIdText: {
color: '#1A6B72',
fontSize: 15,
fontWeight: '700',
letterSpacing: 1,
fontFamily: 'monospace',
},
shareIdHint: {
color: '#9CA3AF',
fontSize: 12,
textAlign: 'center',
},
scanBtn: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
backgroundColor: '#1A6B72',
borderRadius: 12,
paddingVertical: 13,
},
scanBtnText: {
color: '#fff',
fontSize: 15,
fontWeight: '600',
},
orRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 10,
},
orLine: {
flex: 1,
height: 1,
backgroundColor: '#E5E7EB',
},
orText: {
color: '#9CA3AF',
fontSize: 12,
},
input: {
borderWidth: 1,
borderColor: '#E5E7EB',
borderRadius: 12,
paddingVertical: 12,
paddingHorizontal: 16,
fontSize: 16,
color: '#111827',
letterSpacing: 1,
fontFamily: 'monospace',
},
connectBtn: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
backgroundColor: '#115E67',
borderRadius: 12,
paddingVertical: 13,
},
connectBtnDisabled: {
backgroundColor: '#D1D5DB',
},
connectBtnText: {
color: '#fff',
fontSize: 15,
fontWeight: '600',
},
wifiNotice: {
flexDirection: 'row',
alignItems: 'flex-start',
gap: 12,
backgroundColor: '#FFFBEB',
borderWidth: 1,
borderColor: '#FDE68A',
},
wifiNoticeTitle: {
fontSize: 14,
fontWeight: '600',
color: '#92400E',
},
wifiNoticeText: {
fontSize: 12,
color: '#92400E',
lineHeight: 18,
},
emptyHistory: {
alignItems: 'center',
gap: 8,
paddingVertical: 16,
},
emptyHistoryText: {
color: '#9CA3AF',
fontSize: 14,
},
historyItem: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 8,
borderBottomWidth: 1,
borderBottomColor: '#F3F4F6',
},
historyLeft: {
gap: 2,
},
historyPartner: {
fontSize: 14,
fontWeight: '600',
color: '#111827',
},
historyDate: {
fontSize: 12,
color: '#9CA3AF',
},
historyRight: {
flexDirection: 'row',
gap: 12,
},
historySent: {
fontSize: 13,
color: '#1A6B72',
fontWeight: '600',
},
historyReceived: {
fontSize: 13,
color: '#10B981',
fontWeight: '600',
},
howToToggle: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
howToStep: {
flexDirection: 'row',
gap: 12,
alignItems: 'flex-start',
},
howToNumber: {
width: 24,
height: 24,
borderRadius: 12,
backgroundColor: '#1A6B72',
justifyContent: 'center',
alignItems: 'center',
flexShrink: 0,
marginTop: 1,
},
howToNumberText: {
color: '#fff',
fontSize: 12,
fontWeight: '700',
},
howToStepTitle: {
fontSize: 14,
fontWeight: '600',
color: '#111827',
},
howToStepBody: {
fontSize: 13,
color: '#6B7280',
lineHeight: 18,
},
});

View File

@@ -1,25 +1,38 @@
// app/_layout.tsx
import { Stack } from 'expo-router';
import { Stack, router } from 'expo-router';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { useEffect, useState } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { useEffect, useRef, useState } from 'react';
import { View, ActivityIndicator, AppState, AppStateStatus } from 'react-native';
import { useUserStore } from '@/store/useUserStore';
import { getDatabase } from '@/lib/database';
import { isPinEnabled } from '@/lib/pinService';
import '../global.css';
const LOCK_AFTER_SECONDS = 60;
export default function RootLayout() {
const [loading, setLoading] = useState(true);
const setUser = useUserStore((s) => s.setUser);
// Track when app was backgrounded
const backgroundedAt = useRef<number | null>(null);
const appState = useRef<AppStateStatus>(AppState.currentState);
useEffect(() => {
async function bootstrap() {
try {
const db = await getDatabase();
const user = await db.getFirstAsync<{ id: string; display_name: string; share_id: string }>(
'SELECT id, display_name, share_id FROM users WHERE is_self = 1 LIMIT 1'
);
const user = await db.getFirstAsync<{
id: string;
display_name: string;
share_id: string;
}>('SELECT id, display_name, share_id FROM users WHERE is_self = 1 LIMIT 1');
if (user) {
setUser({ id: user.id, displayName: user.display_name, shareId: user.share_id });
setUser({
id: user.id,
displayName: user.display_name,
shareId: user.share_id,
});
}
} catch (e) {
console.error('Bootstrap error:', e);
@@ -30,9 +43,56 @@ export default function RootLayout() {
bootstrap();
}, []);
// PIN lock on resume
useEffect(() => {
const subscription = AppState.addEventListener(
'change',
async (nextState: AppStateStatus) => {
const prev = appState.current;
if (
(prev === 'active' || prev === 'inactive') &&
nextState === 'background'
) {
// App going to background — record timestamp
backgroundedAt.current = Date.now();
}
if (
(prev === 'background' || prev === 'inactive') &&
nextState === 'active'
) {
// App coming to foreground
const bgAt = backgroundedAt.current;
if (bgAt !== null) {
const elapsedSec = (Date.now() - bgAt) / 1000;
if (elapsedSec >= LOCK_AFTER_SECONDS) {
const pinOn = await isPinEnabled();
if (pinOn) {
router.replace('/lock');
}
}
}
backgroundedAt.current = null;
}
appState.current = nextState;
}
);
return () => subscription.remove();
}, []);
if (loading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F8F4EF' }}>
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F8F4EF',
}}
>
<ActivityIndicator size="large" color="#1A6B72" />
</View>
);
@@ -43,6 +103,21 @@ export default function RootLayout() {
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="onboarding" />
<Stack.Screen name="(tabs)" />
<Stack.Screen
name="lock"
options={{
presentation: 'fullScreenModal',
animation: 'fade',
gestureEnabled: false,
}}
/>
<Stack.Screen
name="sync-progress"
options={{
presentation: 'fullScreenModal',
animation: 'slide_from_bottom',
}}
/>
</Stack>
</GestureHandlerRootView>
);

205
app/lock.tsx Normal file
View File

@@ -0,0 +1,205 @@
// app/lock.tsx — Full-screen PIN lock screen
import React, { useEffect, useState, useCallback } from 'react';
import {
View,
Text,
StyleSheet,
Alert,
TouchableOpacity,
SafeAreaView,
} from 'react-native';
import { router } from 'expo-router';
import * as LocalAuthentication from 'expo-local-authentication';
import { Shield } from 'lucide-react-native';
import PinPad from '@/components/ui/PinPad';
import { verifyPin, disablePin } from '@/lib/pinService';
import { getDatabase } from '@/lib/database';
import { useUserStore } from '@/store/useUserStore';
export default function LockScreen() {
const [pin, setPin] = useState('');
const [error, setError] = useState('');
const [biometricAvailable, setBiometricAvailable] = useState(false);
const clearUser = useUserStore((s) => s.clearUser);
useEffect(() => {
checkBiometric();
}, []);
const checkBiometric = async () => {
try {
const hardware = await LocalAuthentication.hasHardwareAsync();
const enrolled = await LocalAuthentication.isEnrolledAsync();
setBiometricAvailable(hardware && enrolled);
} catch {
setBiometricAvailable(false);
}
};
const handleBiometric = useCallback(async () => {
try {
const result = await LocalAuthentication.authenticateAsync({
promptMessage: 'Unlock TerritoryLog',
fallbackLabel: 'Use PIN',
cancelLabel: 'Cancel',
});
if (result.success) {
router.replace('/(tabs)');
} else {
setError('Biometric authentication failed. Use your PIN.');
}
} catch {
setError('Biometric not available.');
}
}, []);
// Auto-trigger biometric on mount if available
useEffect(() => {
if (biometricAvailable) {
handleBiometric();
}
}, [biometricAvailable, handleBiometric]);
const handlePinChange = async (newPin: string) => {
setPin(newPin);
setError('');
if (newPin.length === 6) {
const ok = await verifyPin(newPin);
if (ok) {
router.replace('/(tabs)');
} else {
setError('Incorrect PIN. Try again.');
setTimeout(() => setPin(''), 600);
}
}
};
const handleForgotPin = () => {
Alert.alert(
'Forgot PIN?',
'Resetting your PIN will clear ALL app data. This cannot be undone.',
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Clear & Reset',
style: 'destructive',
onPress: async () => {
try {
const db = await getDatabase();
await db.execAsync(`
DELETE FROM contacts;
DELETE FROM visits;
DELETE FROM territories;
DELETE FROM users;
DELETE FROM sync_log;
DELETE FROM topics;
`);
await disablePin();
clearUser();
router.replace('/onboarding');
} catch (e) {
Alert.alert('Error', 'Could not clear data. Please try again.');
}
},
},
]
);
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.content}>
{/* Logo */}
<View style={styles.logoArea}>
<View style={styles.iconCircle}>
<Shield size={40} color="#1A6B72" />
</View>
<Text style={styles.appName}>TerritoryLog</Text>
<Text style={styles.subtitle}>Enter your PIN to continue</Text>
</View>
{/* Error */}
{error ? <Text style={styles.error}>{error}</Text> : null}
{/* PIN Pad */}
<PinPad pin={pin} onPinChange={handlePinChange} maxLength={6} />
{/* Biometric button */}
{biometricAvailable && (
<TouchableOpacity style={styles.biometricBtn} onPress={handleBiometric}>
<Text style={styles.biometricText}>Use Biometrics</Text>
</TouchableOpacity>
)}
{/* Forgot PIN */}
<TouchableOpacity style={styles.forgotBtn} onPress={handleForgotPin}>
<Text style={styles.forgotText}>Forgot PIN? (Clear App Data)</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#111827',
},
content: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 24,
gap: 32,
},
logoArea: {
alignItems: 'center',
gap: 12,
},
iconCircle: {
width: 80,
height: 80,
borderRadius: 40,
backgroundColor: 'rgba(26,107,114,0.15)',
justifyContent: 'center',
alignItems: 'center',
borderWidth: 2,
borderColor: 'rgba(26,107,114,0.4)',
},
appName: {
fontSize: 28,
fontWeight: '700',
color: '#F9FAFB',
letterSpacing: 0.5,
},
subtitle: {
fontSize: 15,
color: '#9CA3AF',
},
error: {
color: '#F87171',
fontSize: 14,
textAlign: 'center',
},
biometricBtn: {
paddingVertical: 12,
paddingHorizontal: 28,
borderRadius: 24,
borderWidth: 1,
borderColor: '#1A6B72',
},
biometricText: {
color: '#1A6B72',
fontSize: 15,
fontWeight: '600',
},
forgotBtn: {
marginTop: 8,
},
forgotText: {
color: '#6B7280',
fontSize: 13,
textDecorationLine: 'underline',
},
});

333
app/sync-progress.tsx Normal file
View File

@@ -0,0 +1,333 @@
// app/sync-progress.tsx — Full-screen active sync progress
import React, { useEffect, useState } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
SafeAreaView,
Animated,
Easing,
} from 'react-native';
import { router, useLocalSearchParams } from 'expo-router';
import { CheckCircle, RefreshCw } from 'lucide-react-native';
type SyncPhase =
| 'connecting'
| 'sending'
| 'receiving'
| 'done'
| 'error';
export default function SyncProgressScreen() {
const params = useLocalSearchParams<{
partnerName?: string;
sentCount?: string;
receivedCount?: string;
conflictCount?: string;
error?: string;
}>();
const [phase, setPhase] = useState<SyncPhase>('connecting');
const [sendProgress] = useState(new Animated.Value(0));
const [receiveProgress] = useState(new Animated.Value(0));
const spinAnim = useState(new Animated.Value(0))[0];
const sentCount = parseInt(params.sentCount ?? '0', 10);
const receivedCount = parseInt(params.receivedCount ?? '0', 10);
const conflictCount = parseInt(params.conflictCount ?? '0', 10);
const partnerName = params.partnerName ?? 'Partner';
const errorMsg = params.error;
useEffect(() => {
if (errorMsg) {
setPhase('error');
return;
}
// Simulate sync animation sequence
const connectTimer = setTimeout(() => {
setPhase('sending');
Animated.timing(sendProgress, {
toValue: 1,
duration: 1200,
useNativeDriver: false,
easing: Easing.out(Easing.cubic),
}).start(() => {
setPhase('receiving');
Animated.timing(receiveProgress, {
toValue: 1,
duration: 1200,
useNativeDriver: false,
easing: Easing.out(Easing.cubic),
}).start(() => {
setPhase('done');
});
});
}, 1000);
return () => clearTimeout(connectTimer);
}, []);
// Spinning icon animation
useEffect(() => {
if (phase === 'connecting' || phase === 'sending' || phase === 'receiving') {
Animated.loop(
Animated.timing(spinAnim, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
easing: Easing.linear,
})
).start();
} else {
spinAnim.stopAnimation();
}
}, [phase]);
const spin = spinAnim.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg'],
});
const sendWidth = sendProgress.interpolate({
inputRange: [0, 1],
outputRange: ['0%', '100%'],
});
const receiveWidth = receiveProgress.interpolate({
inputRange: [0, 1],
outputRange: ['0%', '100%'],
});
const phaseLabel = {
connecting: `Connecting to ${partnerName}`,
sending: `Sending records…`,
receiving: `Receiving records…`,
done: 'Sync Complete!',
error: 'Sync Failed',
}[phase];
return (
<SafeAreaView style={styles.container}>
<View style={styles.content}>
{/* Icon */}
<View style={styles.iconArea}>
{phase === 'done' ? (
<CheckCircle size={64} color="#22C55E" />
) : phase === 'error' ? (
<View style={styles.errorCircle}>
<Text style={styles.errorX}></Text>
</View>
) : (
<Animated.View style={{ transform: [{ rotate: spin }] }}>
<RefreshCw size={56} color="#1A6B72" />
</Animated.View>
)}
</View>
{/* Phase label */}
<Text style={styles.phaseLabel}>{phaseLabel}</Text>
{errorMsg ? (
<Text style={styles.errorDetail}>{errorMsg}</Text>
) : null}
{/* Progress bars */}
{phase !== 'done' && phase !== 'error' && (
<View style={styles.progressArea}>
<View style={styles.progressRow}>
<Text style={styles.progressLabel}>Sending</Text>
<View style={styles.progressBar}>
<Animated.View
style={[styles.progressFill, styles.sendFill, { width: sendWidth }]}
/>
</View>
<Text style={styles.progressCount}>{sentCount}</Text>
</View>
<View style={styles.progressRow}>
<Text style={styles.progressLabel}>Receiving</Text>
<View style={styles.progressBar}>
<Animated.View
style={[styles.progressFill, styles.receiveFill, { width: receiveWidth }]}
/>
</View>
<Text style={styles.progressCount}>{receivedCount}</Text>
</View>
</View>
)}
{/* Summary card */}
{phase === 'done' && (
<View style={styles.summaryCard}>
<Text style={styles.summaryTitle}>Sync Summary</Text>
<View style={styles.summaryRow}>
<Text style={styles.summaryKey}>Partner</Text>
<Text style={styles.summaryValue}>{partnerName}</Text>
</View>
<View style={styles.summaryRow}>
<Text style={styles.summaryKey}>Sent</Text>
<Text style={[styles.summaryValue, styles.sentColor]}>{sentCount} records</Text>
</View>
<View style={styles.summaryRow}>
<Text style={styles.summaryKey}>Received</Text>
<Text style={[styles.summaryValue, styles.receivedColor]}>{receivedCount} records</Text>
</View>
{conflictCount > 0 && (
<View style={styles.summaryRow}>
<Text style={styles.summaryKey}>Conflicts</Text>
<Text style={[styles.summaryValue, styles.conflictColor]}>
{conflictCount} resolved
</Text>
</View>
)}
</View>
)}
{/* Done button */}
{(phase === 'done' || phase === 'error') && (
<TouchableOpacity
style={[styles.doneBtn, phase === 'error' && styles.errorBtn]}
onPress={() => router.back()}
>
<Text style={styles.doneBtnText}>
{phase === 'done' ? 'Done' : 'Go Back'}
</Text>
</TouchableOpacity>
)}
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#0F172A',
},
content: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 24,
gap: 24,
},
iconArea: {
width: 100,
height: 100,
justifyContent: 'center',
alignItems: 'center',
},
errorCircle: {
width: 64,
height: 64,
borderRadius: 32,
backgroundColor: '#FEE2E2',
justifyContent: 'center',
alignItems: 'center',
},
errorX: {
fontSize: 28,
color: '#EF4444',
fontWeight: '700',
},
phaseLabel: {
fontSize: 22,
fontWeight: '700',
color: '#F9FAFB',
textAlign: 'center',
},
errorDetail: {
fontSize: 14,
color: '#F87171',
textAlign: 'center',
paddingHorizontal: 16,
},
progressArea: {
width: '100%',
gap: 16,
backgroundColor: 'rgba(255,255,255,0.05)',
borderRadius: 16,
padding: 20,
},
progressRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 10,
},
progressLabel: {
color: '#9CA3AF',
fontSize: 13,
width: 72,
},
progressBar: {
flex: 1,
height: 8,
backgroundColor: 'rgba(255,255,255,0.1)',
borderRadius: 4,
overflow: 'hidden',
},
progressFill: {
height: '100%',
borderRadius: 4,
},
sendFill: {
backgroundColor: '#1A6B72',
},
receiveFill: {
backgroundColor: '#10B981',
},
progressCount: {
color: '#D1D5DB',
fontSize: 13,
width: 32,
textAlign: 'right',
},
summaryCard: {
width: '100%',
backgroundColor: 'rgba(255,255,255,0.06)',
borderRadius: 16,
padding: 20,
gap: 12,
borderWidth: 1,
borderColor: 'rgba(255,255,255,0.1)',
},
summaryTitle: {
color: '#F9FAFB',
fontSize: 16,
fontWeight: '700',
marginBottom: 4,
},
summaryRow: {
flexDirection: 'row',
justifyContent: 'space-between',
},
summaryKey: {
color: '#9CA3AF',
fontSize: 14,
},
summaryValue: {
color: '#F9FAFB',
fontSize: 14,
fontWeight: '600',
},
sentColor: { color: '#1A6B72' },
receivedColor: { color: '#10B981' },
conflictColor: { color: '#F59E0B' },
doneBtn: {
paddingVertical: 14,
paddingHorizontal: 48,
backgroundColor: '#1A6B72',
borderRadius: 14,
marginTop: 8,
},
errorBtn: {
backgroundColor: '#6B7280',
},
doneBtnText: {
color: '#fff',
fontSize: 16,
fontWeight: '700',
},
});

View File

@@ -0,0 +1,234 @@
// components/sync/QRScanner.tsx
import React, { useState, useEffect, useRef } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Alert,
} from 'react-native';
import { CameraView, Camera, BarcodeScanningResult } from 'expo-camera';
import { X } from 'lucide-react-native';
interface QRScannerProps {
onScanned: (shareId: string) => void;
onCancel: () => void;
}
export default function QRScanner({ onScanned, onCancel }: QRScannerProps) {
const [hasPermission, setHasPermission] = useState<boolean | null>(null);
const [scanned, setScanned] = useState(false);
const lastScannedRef = useRef<string | null>(null);
useEffect(() => {
requestPermission();
}, []);
const requestPermission = async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === 'granted');
};
const handleBarCodeScanned = (result: BarcodeScanningResult) => {
if (scanned) return;
const { data } = result;
// Prevent duplicate scans of the same code
if (lastScannedRef.current === data) return;
lastScannedRef.current = data;
// Extract Share ID — expected format: "TL-XXXXXXXX" (8 alphanumeric chars)
const match = data.match(/TL-[A-Z0-9]{8}/i);
if (match) {
setScanned(true);
onScanned(match[0].toUpperCase());
} else {
Alert.alert(
'Invalid QR Code',
'This QR code does not contain a valid TerritoryLog Share ID.',
[
{
text: 'Try Again',
onPress: () => {
lastScannedRef.current = null;
},
},
{ text: 'Cancel', onPress: onCancel },
]
);
}
};
if (hasPermission === null) {
return (
<View style={styles.centered}>
<Text style={styles.message}>Requesting camera permission</Text>
</View>
);
}
if (hasPermission === false) {
return (
<View style={styles.centered}>
<Text style={styles.message}>Camera access denied.</Text>
<Text style={styles.submessage}>
Enable camera access in your device settings to scan QR codes.
</Text>
<TouchableOpacity style={styles.cancelBtn} onPress={onCancel}>
<Text style={styles.cancelText}>Go Back</Text>
</TouchableOpacity>
</View>
);
}
return (
<View style={styles.container}>
<CameraView
style={StyleSheet.absoluteFillObject}
barcodeScannerSettings={{
barcodeTypes: ['qr'],
}}
onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
/>
{/* Overlay */}
<View style={styles.overlay}>
{/* Top */}
<View style={styles.overlayTop}>
<TouchableOpacity style={styles.closeBtn} onPress={onCancel}>
<X size={24} color="#fff" />
</TouchableOpacity>
<Text style={styles.overlayTitle}>Scan Partner QR Code</Text>
<Text style={styles.overlaySubtitle}>
Point your camera at your partner's TerritoryLog QR code
</Text>
</View>
{/* Scan frame row */}
<View style={styles.frameRow}>
<View style={styles.frameShade} />
<View style={styles.frame}>
{/* Corner markers */}
<View style={[styles.corner, styles.cornerTL]} />
<View style={[styles.corner, styles.cornerTR]} />
<View style={[styles.corner, styles.cornerBL]} />
<View style={[styles.corner, styles.cornerBR]} />
</View>
<View style={styles.frameShade} />
</View>
{/* Bottom */}
<View style={styles.overlayBottom}>
<Text style={styles.overlayHint}>Share ID format: TL-XXXXXXXX</Text>
</View>
</View>
</View>
);
}
const FRAME_SIZE = 240;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000',
},
centered: {
flex: 1,
backgroundColor: '#111827',
justifyContent: 'center',
alignItems: 'center',
padding: 24,
gap: 12,
},
message: {
color: '#F9FAFB',
fontSize: 16,
textAlign: 'center',
},
submessage: {
color: '#9CA3AF',
fontSize: 14,
textAlign: 'center',
},
cancelBtn: {
marginTop: 16,
paddingVertical: 12,
paddingHorizontal: 24,
backgroundColor: '#1A6B72',
borderRadius: 12,
},
cancelText: {
color: '#fff',
fontSize: 15,
fontWeight: '600',
},
overlay: {
flex: 1,
flexDirection: 'column',
},
overlayTop: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.6)',
alignItems: 'center',
paddingTop: 60,
paddingHorizontal: 24,
gap: 8,
},
closeBtn: {
position: 'absolute',
top: 52,
right: 24,
width: 40,
height: 40,
borderRadius: 20,
backgroundColor: 'rgba(255,255,255,0.2)',
justifyContent: 'center',
alignItems: 'center',
},
overlayTitle: {
color: '#fff',
fontSize: 20,
fontWeight: '700',
marginTop: 8,
},
overlaySubtitle: {
color: '#D1D5DB',
fontSize: 13,
textAlign: 'center',
},
frameRow: {
flexDirection: 'row',
height: FRAME_SIZE,
},
frameShade: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.6)',
},
frame: {
width: FRAME_SIZE,
height: FRAME_SIZE,
backgroundColor: 'transparent',
},
corner: {
position: 'absolute',
width: 28,
height: 28,
borderColor: '#1A6B72',
borderWidth: 3,
},
cornerTL: { top: 0, left: 0, borderBottomWidth: 0, borderRightWidth: 0 },
cornerTR: { top: 0, right: 0, borderBottomWidth: 0, borderLeftWidth: 0 },
cornerBL: { bottom: 0, left: 0, borderTopWidth: 0, borderRightWidth: 0 },
cornerBR: { bottom: 0, right: 0, borderTopWidth: 0, borderLeftWidth: 0 },
overlayBottom: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.6)',
alignItems: 'center',
paddingTop: 24,
},
overlayHint: {
color: '#9CA3AF',
fontSize: 13,
},
});

130
components/ui/PinPad.tsx Normal file
View File

@@ -0,0 +1,130 @@
// components/ui/PinPad.tsx
import React from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Vibration,
} from 'react-native';
import { Delete } from 'lucide-react-native';
interface PinPadProps {
pin: string;
onPinChange: (pin: string) => void;
maxLength?: number;
}
const KEYS = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['', '0', 'del'],
];
export default function PinPad({
pin,
onPinChange,
maxLength = 6,
}: PinPadProps) {
const handleKey = (key: string) => {
if (key === 'del') {
onPinChange(pin.slice(0, -1));
} else if (key !== '' && pin.length < maxLength) {
Vibration.vibrate(30);
onPinChange(pin + key);
}
};
return (
<View style={styles.container}>
{/* PIN dots */}
<View style={styles.dotsRow}>
{Array.from({ length: maxLength }).map((_, i) => (
<View
key={i}
style={[styles.dot, i < pin.length && styles.dotFilled]}
/>
))}
</View>
{/* Keypad */}
{KEYS.map((row, ri) => (
<View key={ri} style={styles.row}>
{row.map((key, ki) => {
if (key === '') {
return <View key={ki} style={styles.keyEmpty} />;
}
if (key === 'del') {
return (
<TouchableOpacity
key={ki}
style={styles.key}
onPress={() => handleKey('del')}
activeOpacity={0.6}
>
<Delete size={22} color="#E5E7EB" />
</TouchableOpacity>
);
}
return (
<TouchableOpacity
key={ki}
style={styles.key}
onPress={() => handleKey(key)}
activeOpacity={0.6}
>
<Text style={styles.keyText}>{key}</Text>
</TouchableOpacity>
);
})}
</View>
))}
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
gap: 24,
},
dotsRow: {
flexDirection: 'row',
gap: 16,
marginBottom: 8,
},
dot: {
width: 16,
height: 16,
borderRadius: 8,
borderWidth: 2,
borderColor: '#9CA3AF',
backgroundColor: 'transparent',
},
dotFilled: {
backgroundColor: '#1A6B72',
borderColor: '#1A6B72',
},
row: {
flexDirection: 'row',
gap: 20,
},
key: {
width: 72,
height: 72,
borderRadius: 36,
backgroundColor: 'rgba(255,255,255,0.08)',
justifyContent: 'center',
alignItems: 'center',
},
keyEmpty: {
width: 72,
height: 72,
},
keyText: {
fontSize: 26,
fontWeight: '500',
color: '#F9FAFB',
},
});

52
lib/pinService.ts Normal file
View File

@@ -0,0 +1,52 @@
// lib/pinService.ts
import * as SecureStore from 'expo-secure-store';
const PIN_KEY = 'territory_log_pin';
const PIN_ENABLED_KEY = 'territory_log_pin_enabled';
const BIOMETRIC_ENABLED_KEY = 'territory_log_biometric_enabled';
export async function isPinEnabled(): Promise<boolean> {
try {
const val = await SecureStore.getItemAsync(PIN_ENABLED_KEY);
return val === 'true';
} catch {
return false;
}
}
export async function setPin(pin: string): Promise<void> {
await SecureStore.setItemAsync(PIN_KEY, pin);
await SecureStore.setItemAsync(PIN_ENABLED_KEY, 'true');
}
export async function verifyPin(pin: string): Promise<boolean> {
try {
const stored = await SecureStore.getItemAsync(PIN_KEY);
return stored === pin;
} catch {
return false;
}
}
export async function disablePin(): Promise<void> {
await SecureStore.deleteItemAsync(PIN_KEY);
await SecureStore.setItemAsync(PIN_ENABLED_KEY, 'false');
await SecureStore.setItemAsync(BIOMETRIC_ENABLED_KEY, 'false');
}
export async function getPinEnabled(): Promise<boolean> {
return isPinEnabled();
}
export async function isBiometricEnabled(): Promise<boolean> {
try {
const val = await SecureStore.getItemAsync(BIOMETRIC_ENABLED_KEY);
return val === 'true';
} catch {
return false;
}
}
export async function setBiometricEnabled(enabled: boolean): Promise<void> {
await SecureStore.setItemAsync(BIOMETRIC_ENABLED_KEY, enabled ? 'true' : 'false');
}

402
lib/syncService.ts Normal file
View File

@@ -0,0 +1,402 @@
// lib/syncService.ts
import { getDatabase } from '@/lib/database';
// ── Types ─────────────────────────────────────────────────────────────────────
export interface SyncPartner {
id: string;
name: string;
address: string; // IP:port
}
export interface Contact {
id: string;
owner_id: string;
full_name: string;
address?: string;
household_count?: number;
gender?: string;
category: string;
status?: string;
tags?: string;
notes?: string;
territory_code?: string;
latitude?: number;
longitude?: number;
created_at: number;
updated_at: number;
deleted_at?: number | null;
}
export interface Visit {
id: string;
contact_id: string;
visited_by_name: string;
visited_by_id: string;
visit_date: number;
topic?: string;
response?: string;
remarks?: string;
next_visit_date?: number;
created_at: number;
updated_at: number;
}
export interface Territory {
id: string;
territory_code: string;
municipality?: string;
barangay?: string;
area?: string;
block?: string;
assigned_to?: string;
created_at: number;
updated_at: number;
}
export interface SyncPayload {
contacts: Contact[];
visits: Visit[];
territories: Territory[];
exportedAt: number;
exportedBy: string;
}
export interface SyncResult {
sent: number;
received: number;
conflicts: number;
}
// ── STUB: mDNS Discovery ──────────────────────────────────────────────────────
// TODO: Implement with react-native-zeroconf in bare workflow (expo-dev-client).
// This requires native modules that are not available in managed Expo Go.
// Steps to activate:
// 1. Run `npx expo eject` or use a bare workflow
// 2. Install: npm install react-native-zeroconf
// 3. Run `npx pod-install` (iOS) and rebuild
// 4. Replace this stub with actual Zeroconf implementation
export async function discoverPartners(): Promise<SyncPartner[]> {
// STUB — bare workflow required
throw new Error(
'mDNS discovery requires expo-dev-client and bare workflow. ' +
'Install react-native-zeroconf after ejecting from managed workflow.'
);
}
// ── STUB: TCP Sync Server ─────────────────────────────────────────────────────
// TODO: Implement with react-native-tcp-socket in bare workflow.
// Steps to activate:
// 1. Run `npx expo eject` or use a bare workflow
// 2. Install: npm install react-native-tcp-socket
// 3. Run `npx pod-install` (iOS) and rebuild
// 4. Replace this stub with actual TCP server implementation
export async function startSyncServer(port: number): Promise<void> {
// STUB — bare workflow required
throw new Error(
'TCP server requires expo-dev-client and bare workflow. ' +
'Install react-native-tcp-socket after ejecting from managed workflow.'
);
}
// ── Merge Logic (FULLY IMPLEMENTED) ──────────────────────────────────────────
/**
* Merges two arrays of records, resolving conflicts using updated_at timestamp.
* - Latest updated_at wins per record (by id)
* - Soft deletes (deleted_at != null) are respected
*/
export function mergeRecords<T extends {
id: string;
updated_at: number;
deleted_at?: number | null;
}>(local: T[], remote: T[]): T[] {
const merged = new Map<string, T>();
// Load all local records
for (const record of local) {
merged.set(record.id, record);
}
// Merge remote records: remote wins if updated_at is newer or equal
for (const remoteRecord of remote) {
const localRecord = merged.get(remoteRecord.id);
if (!localRecord) {
// New record from remote
merged.set(remoteRecord.id, remoteRecord);
} else {
// Conflict: pick the most recently updated
if (remoteRecord.updated_at >= localRecord.updated_at) {
merged.set(remoteRecord.id, remoteRecord);
}
// else: keep local (it's newer)
}
}
return Array.from(merged.values());
}
// ── Serialize for Sync (FULLY IMPLEMENTED) ────────────────────────────────────
/**
* Serializes local data into a SyncPayload for transmission.
*/
export function serializeForSync(
contacts: Contact[],
visits: Visit[],
territories: Territory[],
exportedBy: string
): SyncPayload {
return {
contacts,
visits,
territories,
exportedAt: Math.floor(Date.now() / 1000),
exportedBy,
};
}
// ── Apply Incoming Sync (FULLY IMPLEMENTED) ────────────────────────────────────
/**
* Applies a received SyncPayload to the local database.
* Merges records using updated_at conflict resolution.
* Returns a SyncResult with counts.
*/
export async function applyIncomingSync(
payload: SyncPayload,
localUserId: string
): Promise<SyncResult> {
const db = await getDatabase();
let received = 0;
let conflicts = 0;
// ── Territories ────────────────────────────────────────────────────────────
const localTerritories = await db.getAllAsync<Territory>(
'SELECT * FROM territories'
);
const mergedTerritories = mergeRecords(localTerritories, payload.territories);
for (const territory of mergedTerritories) {
const existing = localTerritories.find((t) => t.id === territory.id);
if (existing) {
if (territory.updated_at > existing.updated_at) {
conflicts++;
await db.runAsync(
`UPDATE territories SET
territory_code=?, municipality=?, barangay=?, area=?, block=?,
assigned_to=?, updated_at=?
WHERE id=?`,
[
territory.territory_code,
territory.municipality ?? null,
territory.barangay ?? null,
territory.area ?? null,
territory.block ?? null,
territory.assigned_to ?? null,
territory.updated_at,
territory.id,
]
);
received++;
}
} else {
await db.runAsync(
`INSERT OR IGNORE INTO territories
(id, territory_code, municipality, barangay, area, block, assigned_to, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?)`,
[
territory.id,
territory.territory_code,
territory.municipality ?? null,
territory.barangay ?? null,
territory.area ?? null,
territory.block ?? null,
territory.assigned_to ?? null,
territory.created_at,
territory.updated_at,
]
);
received++;
}
}
// ── Contacts ───────────────────────────────────────────────────────────────
const localContacts = await db.getAllAsync<Contact>(
'SELECT * FROM contacts'
);
const mergedContacts = mergeRecords(localContacts, payload.contacts);
for (const contact of mergedContacts) {
const existing = localContacts.find((c) => c.id === contact.id);
if (existing) {
if (contact.updated_at > existing.updated_at) {
conflicts++;
await db.runAsync(
`UPDATE contacts SET
owner_id=?, full_name=?, address=?, household_count=?, gender=?,
category=?, status=?, tags=?, notes=?, territory_code=?,
latitude=?, longitude=?, updated_at=?, deleted_at=?
WHERE id=?`,
[
contact.owner_id,
contact.full_name,
contact.address ?? null,
contact.household_count ?? 1,
contact.gender ?? null,
contact.category,
contact.status ?? 'Active',
contact.tags ?? '[]',
contact.notes ?? null,
contact.territory_code ?? null,
contact.latitude ?? null,
contact.longitude ?? null,
contact.updated_at,
contact.deleted_at ?? null,
contact.id,
]
);
received++;
}
} else {
await db.runAsync(
`INSERT OR IGNORE INTO contacts
(id, owner_id, full_name, address, household_count, gender, category,
status, tags, notes, territory_code, latitude, longitude,
created_at, updated_at, deleted_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
[
contact.id,
contact.owner_id,
contact.full_name,
contact.address ?? null,
contact.household_count ?? 1,
contact.gender ?? null,
contact.category,
contact.status ?? 'Active',
contact.tags ?? '[]',
contact.notes ?? null,
contact.territory_code ?? null,
contact.latitude ?? null,
contact.longitude ?? null,
contact.created_at,
contact.updated_at,
contact.deleted_at ?? null,
]
);
received++;
}
}
// ── Visits ─────────────────────────────────────────────────────────────────
const localVisits = await db.getAllAsync<Visit>(
'SELECT * FROM visits'
);
const mergedVisits = mergeRecords(
localVisits.map((v) => ({ ...v, deleted_at: undefined })),
payload.visits.map((v) => ({ ...v, deleted_at: undefined }))
);
for (const visit of mergedVisits) {
const existing = localVisits.find((v) => v.id === visit.id);
if (existing) {
if (visit.updated_at > existing.updated_at) {
conflicts++;
await db.runAsync(
`UPDATE visits SET
contact_id=?, visited_by_name=?, visited_by_id=?, visit_date=?,
topic=?, response=?, remarks=?, next_visit_date=?, updated_at=?
WHERE id=?`,
[
visit.contact_id,
visit.visited_by_name,
visit.visited_by_id,
visit.visit_date,
visit.topic ?? null,
visit.response ?? null,
visit.remarks ?? null,
visit.next_visit_date ?? null,
visit.updated_at,
visit.id,
]
);
received++;
}
} else {
await db.runAsync(
`INSERT OR IGNORE INTO visits
(id, contact_id, visited_by_name, visited_by_id, visit_date,
topic, response, remarks, next_visit_date, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
[
visit.id,
visit.contact_id,
visit.visited_by_name,
visit.visited_by_id,
visit.visit_date,
visit.topic ?? null,
visit.response ?? null,
visit.remarks ?? null,
visit.next_visit_date ?? null,
visit.created_at,
visit.updated_at,
]
);
received++;
}
}
return {
sent: 0, // sent is tracked by the caller
received,
conflicts,
};
}
// ── Local data fetch helpers ───────────────────────────────────────────────────
export async function getLocalSyncData(): Promise<{
contacts: Contact[];
visits: Visit[];
territories: Territory[];
}> {
const db = await getDatabase();
const contacts = await db.getAllAsync<Contact>('SELECT * FROM contacts WHERE deleted_at IS NULL');
const visits = await db.getAllAsync<Visit>('SELECT * FROM visits');
const territories = await db.getAllAsync<Territory>('SELECT * FROM territories');
return { contacts, visits, territories };
}
// ── Sync Log helpers ──────────────────────────────────────────────────────────
export interface SyncLogEntry {
id: string;
partner_id: string;
partner_name: string | null;
synced_at: number;
sent_count: number;
received_count: number;
}
export async function getSyncHistory(): Promise<SyncLogEntry[]> {
const db = await getDatabase();
return db.getAllAsync<SyncLogEntry>(
'SELECT * FROM sync_log ORDER BY synced_at DESC LIMIT 50'
);
}
export async function recordSync(
partnerId: string,
partnerName: string | null,
sentCount: number,
receivedCount: number
): Promise<void> {
const db = await getDatabase();
const id = `sync_${Date.now()}`;
await db.runAsync(
'INSERT INTO sync_log (id, partner_id, partner_name, synced_at, sent_count, received_count) VALUES (?,?,?,?,?,?)',
[id, partnerId, partnerName, Math.floor(Date.now() / 1000), sentCount, receivedCount]
);
}

15730
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -20,8 +20,10 @@
"expo-sharing": "~12.0.0",
"expo-document-picker": "~12.0.0",
"expo-file-system": "~18.0.0",
"react": "18.3.2",
"react-native": "0.76.0",
"react": "18.3.1",
"react-native": "0.76.7",
"expo-secure-store": "~14.0.1",
"react-native-qrcode-svg": "^6.3.0",
"react-native-safe-area-context": "4.12.0",
"react-native-screens": "~4.0.0",
"react-native-gesture-handler": "~2.20.0",