feat: Sprint 3 — Territory management (list, add, edit, delete, detail), GPS tagging, territory tab
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
// app/(tabs)/_layout.tsx
|
||||
import { Tabs, router } from 'expo-router';
|
||||
import { useEffect } from 'react';
|
||||
import { Home, Users, Map, Settings } from 'lucide-react-native';
|
||||
import { Home, Users, Map, Settings, MapPin } from 'lucide-react-native';
|
||||
import { useUserStore } from '@/store/useUserStore';
|
||||
|
||||
export default function TabLayout() {
|
||||
@@ -23,6 +23,7 @@ export default function TabLayout() {
|
||||
>
|
||||
<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>
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ContactsScreen() {
|
||||
const { contacts, setContacts } = useContactStore();
|
||||
const [search, setSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<string>('All');
|
||||
const [territoryFilter, setTerritoryFilter] = useState<string>('All');
|
||||
const [territories, setTerritories] = useState<string[]>([]);
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
|
||||
const statusOptions = ['All', 'Active', 'Return Visit', 'Bible Study', 'Not Interested', 'Do Not Call'];
|
||||
@@ -23,6 +25,10 @@ export default function ContactsScreen() {
|
||||
'SELECT * FROM contacts WHERE deleted_at IS NULL ORDER BY full_name ASC'
|
||||
);
|
||||
setContacts(rows.map(dbToContact));
|
||||
|
||||
// Load territory codes for filter
|
||||
const tRows = await db.getAllAsync<any>('SELECT territory_code FROM territories ORDER BY territory_code ASC');
|
||||
setTerritories(tRows.map((r: any) => r.territory_code));
|
||||
}
|
||||
|
||||
useFocusEffect(useCallback(() => { loadContacts(); }, []));
|
||||
@@ -31,7 +37,8 @@ export default function ContactsScreen() {
|
||||
const matchSearch = c.fullName.toLowerCase().includes(search.toLowerCase()) ||
|
||||
(c.address?.toLowerCase().includes(search.toLowerCase()) ?? false);
|
||||
const matchStatus = statusFilter === 'All' || c.status === statusFilter;
|
||||
return matchSearch && matchStatus;
|
||||
const matchTerritory = territoryFilter === 'All' || c.territoryCode === territoryFilter;
|
||||
return matchSearch && matchStatus && matchTerritory;
|
||||
});
|
||||
|
||||
return (
|
||||
@@ -59,7 +66,7 @@ export default function ContactsScreen() {
|
||||
</View>
|
||||
|
||||
{/* Status Filter */}
|
||||
<View className="py-2">
|
||||
<View className="pt-2">
|
||||
<FlatList
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
@@ -77,6 +84,27 @@ export default function ContactsScreen() {
|
||||
/>
|
||||
</View>
|
||||
|
||||
{/* Territory Filter */}
|
||||
{territories.length > 0 && (
|
||||
<View className="pb-2">
|
||||
<FlatList
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={{ paddingHorizontal: 12, gap: 8, paddingTop: 6 }}
|
||||
data={['All', ...territories]}
|
||||
keyExtractor={(item) => `t-${item}`}
|
||||
renderItem={({ item }) => (
|
||||
<TouchableOpacity
|
||||
onPress={() => setTerritoryFilter(item)}
|
||||
className={`px-3 py-1 rounded-full border ${territoryFilter === item ? 'bg-accent border-accent' : 'bg-white border-gray-200'}`}
|
||||
>
|
||||
<Text className={`text-xs font-medium ${territoryFilter === item ? 'text-white' : 'text-gray-500'}`}>{item === 'All' ? 'All Territories' : item}</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* List */}
|
||||
<FlatList
|
||||
data={filtered}
|
||||
|
||||
82
app/(tabs)/territories.tsx
Normal file
82
app/(tabs)/territories.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import { View, Text, FlatList, TouchableOpacity, TextInput } from 'react-native';
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useFocusEffect } from 'expo-router';
|
||||
import { Plus, Search, X, ChevronRight } from 'lucide-react-native';
|
||||
import { getDatabase } from '@/lib/database';
|
||||
import { Territory, dbToTerritory } from '@/lib/territoryHelpers';
|
||||
import { AddTerritorySheet } from '@/components/territories/AddTerritorySheet';
|
||||
import { router } from 'expo-router';
|
||||
|
||||
export default function TerritoriesScreen() {
|
||||
const [territories, setTerritories] = useState<Territory[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
|
||||
async function loadTerritories() {
|
||||
const db = await getDatabase();
|
||||
const rows = await db.getAllAsync<any>('SELECT * FROM territories ORDER BY territory_code ASC');
|
||||
setTerritories(rows.map(dbToTerritory));
|
||||
}
|
||||
|
||||
useFocusEffect(useCallback(() => { loadTerritories(); }, []));
|
||||
|
||||
const filtered = territories.filter((t) =>
|
||||
t.territoryCode.toLowerCase().includes(search.toLowerCase()) ||
|
||||
(t.barangay?.toLowerCase().includes(search.toLowerCase()) ?? false) ||
|
||||
(t.municipality?.toLowerCase().includes(search.toLowerCase()) ?? false)
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-secondary">
|
||||
<View className="bg-primary pt-14 pb-4 px-4">
|
||||
<View className="flex-row justify-between items-center mb-3">
|
||||
<Text className="text-white text-2xl font-bold">Territories</Text>
|
||||
<TouchableOpacity onPress={() => setShowAdd(true)} className="bg-white/20 rounded-full p-2">
|
||||
<Plus size={22} color="white" />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<View className="flex-row items-center bg-white/20 rounded-xl px-3 py-2">
|
||||
<Search size={16} color="rgba(255,255,255,0.7)" />
|
||||
<TextInput
|
||||
className="flex-1 text-white ml-2"
|
||||
placeholder="Search territories..."
|
||||
placeholderTextColor="rgba(255,255,255,0.6)"
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
/>
|
||||
{search ? <TouchableOpacity onPress={() => setSearch('')}><X size={16} color="rgba(255,255,255,0.7)" /></TouchableOpacity> : null}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<FlatList
|
||||
data={filtered}
|
||||
keyExtractor={(item) => item.id}
|
||||
contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 100, paddingTop: 12, gap: 8 }}
|
||||
renderItem={({ item }) => (
|
||||
<TouchableOpacity
|
||||
onPress={() => router.push({ pathname: '/territory/[id]', params: { id: item.id } })}
|
||||
className="bg-white rounded-2xl p-4 flex-row items-center shadow-sm"
|
||||
>
|
||||
<View className="w-12 h-12 rounded-full bg-primary/10 items-center justify-center mr-3">
|
||||
<Text className="text-primary font-bold text-sm">{item.territoryCode}</Text>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<Text className="text-charcoal font-semibold">{item.territoryCode}</Text>
|
||||
{item.barangay && <Text className="text-gray-500 text-sm">{item.barangay}{item.municipality ? `, ${item.municipality}` : ''}</Text>}
|
||||
{item.area && <Text className="text-gray-400 text-xs">Area: {item.area}{item.block ? ` • Block: ${item.block}` : ''}</Text>}
|
||||
</View>
|
||||
<ChevronRight size={18} color="#9CA3AF" />
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
ListEmptyComponent={() => (
|
||||
<View className="items-center justify-center py-20">
|
||||
<Text className="text-gray-400 text-lg">{search ? 'No territories found' : 'No territories yet'}</Text>
|
||||
{!search && <Text className="text-gray-400 mt-1">Tap + to add your first territory</Text>}
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
|
||||
<AddTerritorySheet visible={showAdd} onClose={() => setShowAdd(false)} onSaved={() => { setShowAdd(false); loadTerritories(); }} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
112
app/territory/[id].tsx
Normal file
112
app/territory/[id].tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import { View, Text, ScrollView, TouchableOpacity, Alert } from 'react-native';
|
||||
import { useLocalSearchParams, router, useFocusEffect } from 'expo-router';
|
||||
import { useState, useCallback } from 'react';
|
||||
import { ArrowLeft, Edit2, Trash2, ChevronRight } from 'lucide-react-native';
|
||||
import { getDatabase } from '@/lib/database';
|
||||
import { Territory, dbToTerritory } from '@/lib/territoryHelpers';
|
||||
import { Contact } from '@/store/useContactStore';
|
||||
import { dbToContact } from '@/lib/contactHelpers';
|
||||
import { EditTerritorySheet } from '@/components/territories/EditTerritorySheet';
|
||||
|
||||
export default function TerritoryDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const [territory, setTerritory] = useState<Territory | null>(null);
|
||||
const [contacts, setContacts] = useState<Contact[]>([]);
|
||||
const [showEdit, setShowEdit] = useState(false);
|
||||
|
||||
async function loadData() {
|
||||
const db = await getDatabase();
|
||||
const row = await db.getFirstAsync<any>('SELECT * FROM territories WHERE id = ?', [id]);
|
||||
if (row) {
|
||||
const t = dbToTerritory(row);
|
||||
setTerritory(t);
|
||||
const contactRows = await db.getAllAsync<any>(
|
||||
'SELECT * FROM contacts WHERE territory_code = ? AND deleted_at IS NULL ORDER BY full_name ASC',
|
||||
[t.territoryCode]
|
||||
);
|
||||
setContacts(contactRows.map(dbToContact));
|
||||
}
|
||||
}
|
||||
|
||||
useFocusEffect(useCallback(() => { loadData(); }, [id]));
|
||||
|
||||
async function handleDelete() {
|
||||
Alert.alert('Delete Territory', `Delete territory ${territory?.territoryCode}? Contacts will keep their territory code but it won't link to a territory record.`, [
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{ text: 'Delete', style: 'destructive', onPress: async () => {
|
||||
const db = await getDatabase();
|
||||
await db.runAsync('DELETE FROM territories WHERE id = ?', [id]);
|
||||
router.back();
|
||||
}}
|
||||
]);
|
||||
}
|
||||
|
||||
if (!territory) return <View className="flex-1 bg-secondary" />;
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-secondary">
|
||||
<View className="bg-primary pt-14 pb-6 px-4">
|
||||
<View className="flex-row items-center justify-between mb-4">
|
||||
<TouchableOpacity onPress={() => router.back()} className="bg-white/20 rounded-full p-2">
|
||||
<ArrowLeft size={20} color="white" />
|
||||
</TouchableOpacity>
|
||||
<View className="flex-row gap-2">
|
||||
<TouchableOpacity onPress={() => setShowEdit(true)} className="bg-white/20 rounded-full p-2">
|
||||
<Edit2 size={18} color="white" />
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity onPress={handleDelete} className="bg-white/20 rounded-full p-2">
|
||||
<Trash2 size={18} color="white" />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
<View className="items-center">
|
||||
<View className="w-20 h-20 rounded-full bg-white/20 items-center justify-center mb-3">
|
||||
<Text className="text-white text-2xl font-bold">{territory.territoryCode}</Text>
|
||||
</View>
|
||||
<Text className="text-white text-xl font-bold">{territory.territoryCode}</Text>
|
||||
{territory.barangay && <Text className="text-white/70 text-sm mt-1">{territory.barangay}{territory.municipality ? `, ${territory.municipality}` : ''}</Text>}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<ScrollView className="flex-1 px-4 pt-4" contentContainerStyle={{ gap: 12, paddingBottom: 40 }}>
|
||||
<View className="bg-white rounded-2xl p-4">
|
||||
<Text className="text-charcoal font-semibold mb-3">Details</Text>
|
||||
{territory.municipality && <InfoRow label="Municipality" value={territory.municipality} />}
|
||||
{territory.barangay && <InfoRow label="Barangay" value={territory.barangay} />}
|
||||
{territory.area && <InfoRow label="Area" value={territory.area} />}
|
||||
{territory.block && <InfoRow label="Block" value={territory.block} />}
|
||||
</View>
|
||||
|
||||
<View className="bg-white rounded-2xl p-4">
|
||||
<Text className="text-charcoal font-semibold mb-3">Contacts in this territory ({contacts.length})</Text>
|
||||
{contacts.length === 0 ? (
|
||||
<Text className="text-gray-400 text-sm">No contacts assigned to this territory</Text>
|
||||
) : (
|
||||
contacts.map((c) => (
|
||||
<TouchableOpacity
|
||||
key={c.id}
|
||||
onPress={() => router.push({ pathname: '/contact/[id]', params: { id: c.id } })}
|
||||
className="flex-row items-center py-2 border-b border-gray-50"
|
||||
>
|
||||
<Text className="flex-1 text-charcoal font-medium">{c.fullName}</Text>
|
||||
<Text className="text-gray-400 text-xs mr-2">{c.status}</Text>
|
||||
<ChevronRight size={14} color="#9CA3AF" />
|
||||
</TouchableOpacity>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
<EditTerritorySheet territory={territory} visible={showEdit} onClose={() => setShowEdit(false)} onSaved={() => { setShowEdit(false); loadData(); }} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<View className="flex-row justify-between py-2 border-b border-gray-50">
|
||||
<Text className="text-gray-500 text-sm">{label}</Text>
|
||||
<Text className="text-charcoal text-sm font-medium">{value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { View, Text, Modal, ScrollView, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native';
|
||||
import { useState } from 'react';
|
||||
import { X } from 'lucide-react-native';
|
||||
import * as Location from 'expo-location';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { useUserStore } from '@/store/useUserStore';
|
||||
@@ -23,12 +24,15 @@ export function AddContactSheet({ visible, onClose, onSaved }: Props) {
|
||||
const [status, setStatus] = useState('Active');
|
||||
const [category, setCategory] = useState('Adult');
|
||||
const [notes, setNotes] = useState('');
|
||||
const [territoryCode, setTerritoryCode] = useState('');
|
||||
const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
function reset() {
|
||||
setFullName(''); setAddress(''); setStatus('Active');
|
||||
setCategory('Adult'); setNotes(''); setErrors({});
|
||||
setTerritoryCode(''); setCoords(null);
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
@@ -42,9 +46,9 @@ export function AddContactSheet({ visible, onClose, onSaved }: Props) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const id = newContactId();
|
||||
await db.runAsync(
|
||||
`INSERT INTO contacts (id, owner_id, full_name, address, category, status, tags, notes, household_count, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, '[]', ?, 1, ?, ?)`,
|
||||
[id, user?.id ?? 'unknown', fullName.trim(), address.trim() || null, category, status, notes.trim() || null, now, now]
|
||||
`INSERT INTO contacts (id, owner_id, full_name, address, category, status, tags, notes, territory_code, latitude, longitude, household_count, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?, 1, ?, ?)`,
|
||||
[id, user?.id ?? 'unknown', fullName.trim(), address.trim() || null, category, status, notes.trim() || null, territoryCode.trim().toUpperCase() || null, coords?.lat ?? null, coords?.lng ?? null, now, now]
|
||||
);
|
||||
reset();
|
||||
onSaved();
|
||||
@@ -92,6 +96,25 @@ export function AddContactSheet({ visible, onClose, onSaved }: Props) {
|
||||
))}
|
||||
</View>
|
||||
|
||||
{/* Territory Code */}
|
||||
<Input label="Territory Code" placeholder="e.g. T-01" value={territoryCode} onChangeText={setTerritoryCode} autoCapitalize="characters" />
|
||||
|
||||
{/* GPS Tag */}
|
||||
<TouchableOpacity
|
||||
onPress={async () => {
|
||||
const { status } = await Location.requestForegroundPermissionsAsync();
|
||||
if (status !== 'granted') { alert('Location permission denied'); return; }
|
||||
const loc = await Location.getCurrentPositionAsync({});
|
||||
setCoords({ lat: loc.coords.latitude, lng: loc.coords.longitude });
|
||||
}}
|
||||
className={`flex-row items-center border rounded-xl px-4 py-3 mb-4 ${coords ? 'border-primary bg-primary/5' : 'border-gray-200 bg-white'}`}
|
||||
>
|
||||
<Text className="text-lg mr-2">📍</Text>
|
||||
<Text className={coords ? 'text-primary font-medium' : 'text-gray-400'}>
|
||||
{coords ? `GPS: ${coords.lat.toFixed(5)}, ${coords.lng.toFixed(5)}` : 'Tag GPS Location (optional)'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<Input label="Notes" placeholder="Any additional notes..." value={notes} onChangeText={setNotes} multiline numberOfLines={3} />
|
||||
<View className="h-8" />
|
||||
</ScrollView>
|
||||
|
||||
@@ -22,6 +22,7 @@ export function EditContactSheet({ contact, visible, onClose, onSaved }: Props)
|
||||
const [status, setStatus] = useState(contact.status);
|
||||
const [category, setCategory] = useState(contact.category);
|
||||
const [notes, setNotes] = useState(contact.notes ?? '');
|
||||
const [territoryCode, setTerritoryCode] = useState(contact.territoryCode ?? '');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -30,6 +31,7 @@ export function EditContactSheet({ contact, visible, onClose, onSaved }: Props)
|
||||
setStatus(contact.status);
|
||||
setCategory(contact.category);
|
||||
setNotes(contact.notes ?? '');
|
||||
setTerritoryCode(contact.territoryCode ?? '');
|
||||
}, [contact]);
|
||||
|
||||
async function handleSave() {
|
||||
@@ -39,8 +41,8 @@ export function EditContactSheet({ contact, visible, onClose, onSaved }: Props)
|
||||
const db = await getDatabase();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
await db.runAsync(
|
||||
'UPDATE contacts SET full_name=?, address=?, status=?, category=?, notes=?, updated_at=? WHERE id=?',
|
||||
[fullName.trim(), address.trim() || null, status, category, notes.trim() || null, now, contact.id]
|
||||
'UPDATE contacts SET full_name=?, address=?, status=?, category=?, notes=?, territory_code=?, updated_at=? WHERE id=?',
|
||||
[fullName.trim(), address.trim() || null, status, category, notes.trim() || null, territoryCode.trim().toUpperCase() || null, now, contact.id]
|
||||
);
|
||||
onSaved();
|
||||
} finally {
|
||||
@@ -76,6 +78,8 @@ export function EditContactSheet({ contact, visible, onClose, onSaved }: Props)
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
{/* Territory Code */}
|
||||
<Input label="Territory Code" placeholder="e.g. T-01" value={territoryCode} onChangeText={setTerritoryCode} autoCapitalize="characters" />
|
||||
<Input label="Notes" value={notes} onChangeText={setNotes} multiline numberOfLines={3} />
|
||||
<View className="h-8" />
|
||||
</ScrollView>
|
||||
|
||||
72
components/territories/AddTerritorySheet.tsx
Normal file
72
components/territories/AddTerritorySheet.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { View, Text, Modal, ScrollView, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native';
|
||||
import { useState } from 'react';
|
||||
import { X } from 'lucide-react-native';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { getDatabase } from '@/lib/database';
|
||||
import { newTerritoryId } from '@/lib/territoryHelpers';
|
||||
|
||||
interface Props {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}
|
||||
|
||||
export function AddTerritorySheet({ visible, onClose, onSaved }: Props) {
|
||||
const [code, setCode] = useState('');
|
||||
const [municipality, setMunicipality] = useState('');
|
||||
const [barangay, setBarangay] = useState('');
|
||||
const [area, setArea] = useState('');
|
||||
const [block, setBlock] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
function reset() { setCode(''); setMunicipality(''); setBarangay(''); setArea(''); setBlock(''); setErrors({}); }
|
||||
|
||||
async function handleSave() {
|
||||
const errs: Record<string, string> = {};
|
||||
if (!code.trim()) errs.code = 'Territory code is required';
|
||||
if (Object.keys(errs).length) { setErrors(errs); return; }
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const db = await getDatabase();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
await db.runAsync(
|
||||
'INSERT INTO territories (id, territory_code, municipality, barangay, area, block, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
[newTerritoryId(), code.trim().toUpperCase(), municipality.trim() || null, barangay.trim() || null, area.trim() || null, block.trim() || null, now, now]
|
||||
);
|
||||
reset();
|
||||
onSaved();
|
||||
} catch (e: any) {
|
||||
if (e?.message?.includes('UNIQUE')) setErrors({ code: 'Territory code already exists' });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal visible={visible} animationType="slide" presentationStyle="pageSheet" onRequestClose={() => { reset(); onClose(); }}>
|
||||
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} className="flex-1">
|
||||
<View className="flex-1 bg-secondary">
|
||||
<View className="flex-row items-center justify-between px-4 py-4 border-b border-gray-200 bg-white">
|
||||
<TouchableOpacity onPress={() => { reset(); onClose(); }}><X size={22} color="#2C3E50" /></TouchableOpacity>
|
||||
<Text className="text-charcoal font-semibold text-lg">New Territory</Text>
|
||||
<View style={{ width: 22 }} />
|
||||
</View>
|
||||
<ScrollView className="flex-1 px-4 pt-4" keyboardShouldPersistTaps="handled">
|
||||
<Input label="Territory Code *" placeholder="e.g. T-01, A-12" value={code} onChangeText={(t) => { setCode(t); setErrors((e) => ({ ...e, code: '' })); }} error={errors.code} autoCapitalize="characters" />
|
||||
<Input label="Municipality" placeholder="e.g. San Pedro" value={municipality} onChangeText={setMunicipality} />
|
||||
<Input label="Barangay" placeholder="e.g. Barangay 1" value={barangay} onChangeText={setBarangay} />
|
||||
<Input label="Area" placeholder="e.g. Zone A" value={area} onChangeText={setArea} />
|
||||
<Input label="Block" placeholder="e.g. Block 3" value={block} onChangeText={setBlock} />
|
||||
<View className="h-8" />
|
||||
</ScrollView>
|
||||
<View className="px-4 py-4 border-t border-gray-200 bg-white">
|
||||
<Button label="Save Territory" onPress={handleSave} loading={loading} />
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
64
components/territories/EditTerritorySheet.tsx
Normal file
64
components/territories/EditTerritorySheet.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import { View, Text, Modal, ScrollView, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { X } from 'lucide-react-native';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { getDatabase } from '@/lib/database';
|
||||
import { Territory } from '@/lib/territoryHelpers';
|
||||
|
||||
interface Props { territory: Territory; visible: boolean; onClose: () => void; onSaved: () => void; }
|
||||
|
||||
export function EditTerritorySheet({ territory, visible, onClose, onSaved }: Props) {
|
||||
const [municipality, setMunicipality] = useState(territory.municipality ?? '');
|
||||
const [barangay, setBarangay] = useState(territory.barangay ?? '');
|
||||
const [area, setArea] = useState(territory.area ?? '');
|
||||
const [block, setBlock] = useState(territory.block ?? '');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMunicipality(territory.municipality ?? '');
|
||||
setBarangay(territory.barangay ?? '');
|
||||
setArea(territory.area ?? '');
|
||||
setBlock(territory.block ?? '');
|
||||
}, [territory]);
|
||||
|
||||
async function handleSave() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const db = await getDatabase();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
await db.runAsync(
|
||||
'UPDATE territories SET municipality=?, barangay=?, area=?, block=?, updated_at=? WHERE id=?',
|
||||
[municipality.trim() || null, barangay.trim() || null, area.trim() || null, block.trim() || null, now, territory.id]
|
||||
);
|
||||
onSaved();
|
||||
} finally { setLoading(false); }
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal visible={visible} animationType="slide" presentationStyle="pageSheet" onRequestClose={onClose}>
|
||||
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} className="flex-1">
|
||||
<View className="flex-1 bg-secondary">
|
||||
<View className="flex-row items-center justify-between px-4 py-4 border-b border-gray-200 bg-white">
|
||||
<TouchableOpacity onPress={onClose}><X size={22} color="#2C3E50" /></TouchableOpacity>
|
||||
<Text className="text-charcoal font-semibold text-lg">Edit Territory</Text>
|
||||
<View style={{ width: 22 }} />
|
||||
</View>
|
||||
<ScrollView className="flex-1 px-4 pt-4" keyboardShouldPersistTaps="handled">
|
||||
<View className="mb-4 bg-gray-100 rounded-xl px-4 py-3">
|
||||
<Text className="text-gray-500 text-sm">Territory Code</Text>
|
||||
<Text className="text-charcoal font-bold text-lg">{territory.territoryCode}</Text>
|
||||
</View>
|
||||
<Input label="Municipality" value={municipality} onChangeText={setMunicipality} />
|
||||
<Input label="Barangay" value={barangay} onChangeText={setBarangay} />
|
||||
<Input label="Area" value={area} onChangeText={setArea} />
|
||||
<Input label="Block" value={block} onChangeText={setBlock} />
|
||||
</ScrollView>
|
||||
<View className="px-4 py-4 border-t border-gray-200 bg-white">
|
||||
<Button label="Save Changes" onPress={handleSave} loading={loading} />
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
31
lib/territoryHelpers.ts
Normal file
31
lib/territoryHelpers.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as Crypto from 'expo-crypto';
|
||||
|
||||
export interface Territory {
|
||||
id: string;
|
||||
territoryCode: string;
|
||||
municipality?: string;
|
||||
barangay?: string;
|
||||
area?: string;
|
||||
block?: string;
|
||||
assignedTo?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export function dbToTerritory(row: any): Territory {
|
||||
return {
|
||||
id: row.id,
|
||||
territoryCode: row.territory_code,
|
||||
municipality: row.municipality,
|
||||
barangay: row.barangay,
|
||||
area: row.area,
|
||||
block: row.block,
|
||||
assignedTo: row.assigned_to,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
export function newTerritoryId(): string {
|
||||
return Crypto.randomUUID();
|
||||
}
|
||||
Reference in New Issue
Block a user