feat: Expo scaffold + auth screens + core screens (#39-#46, #48)

This commit is contained in:
Nemo
2026-03-23 18:40:04 +08:00
commit 745321e5bd
45 changed files with 10557 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules/
.expo/
dist/
.env
*.log

20
App.tsx Normal file
View File

@@ -0,0 +1,20 @@
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.tsx to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

47
app.json Normal file
View File

@@ -0,0 +1,47 @@
{
"expo": {
"name": "FiberOps",
"slug": "fiberops-mobile",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"newArchEnabled": true,
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
"backgroundColor": "#2563EB"
},
"ios": {
"supportsTablet": false,
"bundleIdentifier": "com.fiberops.mobile"
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#2563EB"
},
"package": "com.fiberops.mobile"
},
"web": {
"favicon": "./assets/favicon.png"
},
"scheme": "fiberops",
"plugins": [
"expo-router",
"expo-secure-store",
[
"expo-camera",
{ "cameraPermission": "Allow FiberOps to access your camera for installation photos." }
],
[
"expo-location",
{ "locationAlwaysAndWhenInUsePermission": "Allow FiberOps to use your location for installation GPS." }
],
[
"expo-image-picker",
{ "photosPermission": "Allow FiberOps to access your photos." }
]
]
}
}

41
app/(app)/_layout.tsx Normal file
View File

@@ -0,0 +1,41 @@
import { Tabs } from 'expo-router';
import { Text } from 'react-native';
export default function AppLayout() {
return (
<Tabs
screenOptions={{
headerShown: false,
tabBarActiveTintColor: '#2563EB',
tabBarInactiveTintColor: '#6B7280',
tabBarStyle: { paddingBottom: 4 },
}}
>
<Tabs.Screen
name="dashboard"
options={{ title: 'Home', tabBarIcon: ({ color }) => <Text style={{ color, fontSize: 20 }}>🏠</Text> }}
/>
<Tabs.Screen
name="clients"
options={{ title: 'Clients', tabBarIcon: ({ color }) => <Text style={{ color, fontSize: 20 }}>👥</Text> }}
/>
<Tabs.Screen
name="payments"
options={{ title: 'Payments', tabBarIcon: ({ color }) => <Text style={{ color, fontSize: 20 }}>💰</Text> }}
/>
<Tabs.Screen
name="remittances"
options={{ title: 'Remit', tabBarIcon: ({ color }) => <Text style={{ color, fontSize: 20 }}>📋</Text> }}
/>
<Tabs.Screen
name="tickets"
options={{ title: 'Tickets', tabBarIcon: ({ color }) => <Text style={{ color, fontSize: 20 }}>🎫</Text> }}
/>
<Tabs.Screen
name="profile"
options={{ title: 'Profile', tabBarIcon: ({ color }) => <Text style={{ color, fontSize: 20 }}>👤</Text> }}
/>
<Tabs.Screen name="installations" options={{ href: null }} />
</Tabs>
);
}

112
app/(app)/clients/[id].tsx Normal file
View File

@@ -0,0 +1,112 @@
import { View, Text, ScrollView, ActivityIndicator, TouchableOpacity, Linking } from 'react-native';
import { useLocalSearchParams, router } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { api } from '../../../services/api';
export default function ClientDetailScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const [tab, setTab] = useState<'profile' | 'subscription' | 'invoices' | 'payments'>('profile');
const { data: client, isLoading } = useQuery({
queryKey: ['client', id],
queryFn: () => api.get(`/api/v1/clients/${id}`).then(r => r.data),
});
const { data: invoices } = useQuery({
queryKey: ['client-invoices', id],
queryFn: () => api.get(`/api/v1/invoices?clientId=${id}&limit=20`).then(r => r.data?.data ?? r.data),
enabled: tab === 'invoices',
});
const { data: payments } = useQuery({
queryKey: ['client-payments', id],
queryFn: () => api.get(`/api/v1/clients/${id}/payments`).then(r => r.data?.data ?? r.data),
enabled: tab === 'payments',
});
if (isLoading) return <View className="flex-1 items-center justify-center"><ActivityIndicator color="#2563EB" /></View>;
const TABS = ['profile', 'subscription', 'invoices', 'payments'] as const;
return (
<View className="flex-1 bg-gray-50">
<View className="px-4 pt-14 pb-3 bg-white border-b border-gray-100">
<TouchableOpacity onPress={() => router.back()} className="mb-2">
<Text className="text-primary"> Back</Text>
</TouchableOpacity>
<Text className="text-xl font-bold text-gray-900">{client?.firstName} {client?.lastName}</Text>
<Text className="text-gray-500 text-sm">{client?.accountNumber}</Text>
<View className="flex-row mt-3 gap-2">
{TABS.map(t => (
<TouchableOpacity key={t} onPress={() => setTab(t)}
className={`px-3 py-1.5 rounded-full ${tab === t ? 'bg-primary' : 'bg-gray-100'}`}>
<Text className={`text-xs font-medium capitalize ${tab === t ? 'text-white' : 'text-gray-600'}`}>{t}</Text>
</TouchableOpacity>
))}
</View>
</View>
<ScrollView className="flex-1 px-4 py-4">
{tab === 'profile' && (
<View className="bg-white rounded-2xl border border-gray-100">
{[
{ label: 'Full Name', value: `${client?.firstName} ${client?.lastName}` },
{ label: 'Phone', value: client?.phone, action: () => Linking.openURL(`tel:${client?.phone}`) },
{ label: 'Email', value: client?.email },
{ label: 'Address', value: client?.address },
{ label: 'Area', value: client?.area?.name },
{ label: 'Status', value: client?.status },
].map((row, i) => (
<TouchableOpacity key={row.label} onPress={row.action}
className={`px-4 py-3 ${i > 0 ? 'border-t border-gray-100' : ''}`}>
<Text className="text-gray-500 text-xs mb-0.5">{row.label}</Text>
<Text className={`text-gray-900 font-medium ${row.action ? 'text-primary' : ''}`}>{row.value ?? '—'}</Text>
</TouchableOpacity>
))}
</View>
)}
{tab === 'subscription' && (
<View className="bg-white rounded-2xl border border-gray-100 p-4">
<Text className="font-semibold text-gray-900 mb-3">Current Subscription</Text>
{client?.subscription ? (
<>
<Text className="text-gray-700">Plan: <Text className="font-medium">{client.subscription.plan?.name}</Text></Text>
<Text className="text-gray-700 mt-1">Status: <Text className="font-medium capitalize">{client.subscription.status}</Text></Text>
<Text className="text-gray-700 mt-1">Billing Day: <Text className="font-medium">{client.subscription.billingDay}</Text></Text>
<Text className="text-gray-700 mt-1">Monthly: <Text className="font-medium">{client.subscription.plan?.price?.toLocaleString()}</Text></Text>
</>
) : (
<Text className="text-gray-400">No active subscription</Text>
)}
</View>
)}
{tab === 'invoices' && (
<View>
{(invoices ?? []).map((inv: any) => (
<View key={inv.id} className="bg-white rounded-xl p-4 mb-2 border border-gray-100">
<Text className="font-medium text-gray-900">{inv.invoiceNumber}</Text>
<Text className="text-gray-500 text-sm">{inv.totalAmount?.toLocaleString()} · {inv.status}</Text>
</View>
))}
{!invoices?.length && <Text className="text-gray-400 text-center py-10">No invoices</Text>}
</View>
)}
{tab === 'payments' && (
<View>
{(payments ?? []).map((p: any) => (
<View key={p.id} className="bg-white rounded-xl p-4 mb-2 border border-gray-100">
<Text className="font-medium text-gray-900">{p.amount?.toLocaleString()}</Text>
<Text className="text-gray-500 text-sm">{p.paymentMethod} · {new Date(p.paymentDate).toLocaleDateString()}</Text>
</View>
))}
{!payments?.length && <Text className="text-gray-400 text-center py-10">No payments</Text>}
</View>
)}
</ScrollView>
</View>
);
}

View File

@@ -0,0 +1,71 @@
import { useState } from 'react';
import { View, Text, TextInput, FlatList, TouchableOpacity, ActivityIndicator } from 'react-native';
import { useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { api } from '../../../services/api';
const STATUS_COLOR: Record<string, string> = {
active: '#16A34A', suspended: '#DC2626', pending: '#D97706', cancelled: '#6B7280',
};
export default function ClientsScreen() {
const [search, setSearch] = useState('');
const { data, isLoading } = useQuery({
queryKey: ['clients'],
queryFn: () => api.get('/api/v1/clients?limit=100').then(r => r.data?.data ?? r.data),
});
const filtered = (data ?? []).filter((c: any) =>
[c.firstName, c.lastName, c.accountNumber, c.phone].join(' ').toLowerCase().includes(search.toLowerCase())
);
return (
<View className="flex-1 bg-gray-50">
<View className="px-4 pt-14 pb-3 bg-white border-b border-gray-100">
<Text className="text-xl font-bold text-gray-900 mb-3">Clients</Text>
<TextInput
className="bg-gray-100 rounded-xl px-4 py-2 text-base"
placeholder="Search name, account #, phone..."
value={search}
onChangeText={setSearch}
/>
</View>
{isLoading ? (
<View className="flex-1 items-center justify-center">
<ActivityIndicator color="#2563EB" />
</View>
) : (
<FlatList
data={filtered}
keyExtractor={(item) => item.id}
contentContainerStyle={{ padding: 16 }}
renderItem={({ item }) => (
<TouchableOpacity
className="bg-white rounded-xl p-4 mb-2 border border-gray-100 flex-row items-center"
onPress={() => router.push(`/(app)/clients/${item.id}`)}
>
<View className="w-10 h-10 rounded-full bg-blue-100 items-center justify-center mr-3">
<Text className="text-primary font-bold">{item.firstName?.[0]?.toUpperCase()}</Text>
</View>
<View className="flex-1">
<Text className="font-semibold text-gray-900">{item.firstName} {item.lastName}</Text>
<Text className="text-gray-500 text-sm">{item.accountNumber} · {item.phone}</Text>
</View>
<View className="px-2 py-1 rounded-full" style={{ backgroundColor: `${STATUS_COLOR[item.status] ?? '#6B7280'}20` }}>
<Text className="text-xs font-medium capitalize" style={{ color: STATUS_COLOR[item.status] ?? '#6B7280' }}>
{item.status}
</Text>
</View>
</TouchableOpacity>
)}
ListEmptyComponent={
<View className="items-center py-20">
<Text className="text-gray-400">No clients found</Text>
</View>
}
/>
)}
</View>
);
}

65
app/(app)/dashboard.tsx Normal file
View File

@@ -0,0 +1,65 @@
import { View, Text, ScrollView, RefreshControl, ActivityIndicator } from 'react-native';
import { useQuery } from '@tanstack/react-query';
import { api } from '../../services/api';
import { useAuthStore } from '../../stores/authStore';
function KpiCard({ label, value, color }: { label: string; value: string | number; color: string }) {
return (
<View className="bg-white rounded-2xl p-4 flex-1 mx-1 shadow-sm border border-gray-100">
<Text className="text-gray-500 text-xs mb-1">{label}</Text>
<Text className={`text-2xl font-bold`} style={{ color }}>{value}</Text>
</View>
);
}
export default function DashboardScreen() {
const { user } = useAuthStore();
const { data, isLoading, refetch, isRefetching } = useQuery({
queryKey: ['dashboard'],
queryFn: () => api.get('/api/v1/dashboard/summary').then(r => r.data),
});
return (
<ScrollView
className="flex-1 bg-gray-50"
refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
>
<View className="px-4 pt-14 pb-4 bg-primary">
<Text className="text-white text-sm opacity-80">Welcome back,</Text>
<Text className="text-white text-xl font-bold">{user?.firstName ?? 'Field Staff'}</Text>
</View>
{isLoading ? (
<View className="flex-1 items-center justify-center py-20">
<ActivityIndicator color="#2563EB" />
</View>
) : (
<View className="px-3 py-4">
<Text className="text-gray-700 font-semibold mb-3 px-1">Overview</Text>
<View className="flex-row mb-3">
<KpiCard label="Total Clients" value={data?.totalClients ?? 0} color="#2563EB" />
<KpiCard label="Active Subs" value={data?.activeSubscriptions ?? 0} color="#16A34A" />
</View>
<View className="flex-row mb-6">
<KpiCard label="Overdue" value={data?.overdueInvoices ?? 0} color="#DC2626" />
<KpiCard label="Today Collections" value={`${(data?.todayCollections ?? 0).toLocaleString()}`} color="#D97706" />
</View>
<Text className="text-gray-700 font-semibold mb-3 px-1">Recent Tickets</Text>
{(data?.recentTickets ?? []).length === 0 ? (
<View className="bg-white rounded-2xl p-6 items-center border border-gray-100">
<Text className="text-gray-400">No recent tickets</Text>
</View>
) : (
(data?.recentTickets ?? []).map((t: any) => (
<View key={t.id} className="bg-white rounded-xl p-4 mb-2 border border-gray-100">
<Text className="font-medium text-gray-900">{t.subject}</Text>
<Text className="text-gray-500 text-sm mt-1">{t.clientName} · {t.status}</Text>
</View>
))
)}
</View>
)}
</ScrollView>
);
}

View File

@@ -0,0 +1,18 @@
import { View, Text, TouchableOpacity } from 'react-native';
import { useRouter } from 'expo-router';
export default function PaymentsScreen() {
const router = useRouter();
return (
<View className="flex-1 bg-gray-50 pt-14 px-4">
<Text className="text-2xl font-bold text-gray-900 mb-6">Payments</Text>
<TouchableOpacity
className="bg-primary rounded-2xl p-5 items-center"
onPress={() => router.push('/(app)/payments/record')}
>
<Text className="text-white text-lg font-semibold">💳 Record Payment</Text>
<Text className="text-blue-100 text-sm mt-1">Accept cash, GCash, or bank transfer</Text>
</TouchableOpacity>
</View>
);
}

View File

@@ -0,0 +1,116 @@
import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { useRouter } from 'expo-router';
import { api } from '../../../services/api';
const METHODS = ['Cash', 'GCash', 'Maya', 'Bank Transfer'];
export default function RecordPaymentScreen() {
const router = useRouter();
const [accountNumber, setAccountNumber] = useState('');
const [client, setClient] = useState<any>(null);
const [amount, setAmount] = useState('');
const [method, setMethod] = useState('Cash');
const [reference, setReference] = useState('');
const [loading, setLoading] = useState(false);
const [searching, setSearching] = useState(false);
const searchClient = async () => {
if (!accountNumber.trim()) return;
setSearching(true);
try {
const res = await api.get(`/api/v1/clients?accountNumber=${accountNumber.trim()}`);
const clients = res.data?.data ?? res.data?.results ?? [];
setClient(clients[0] ?? null);
if (!clients[0]) Alert.alert('Not found', 'No client with that account number.');
} catch { Alert.alert('Error', 'Could not search clients.'); }
finally { setSearching(false); }
};
const submit = async () => {
if (!client || !amount) return Alert.alert('Required', 'Select a client and enter amount.');
setLoading(true);
try {
await api.post('/api/v1/payments', {
clientId: client.id,
amount: parseFloat(amount),
paymentMethod: method.toLowerCase().replace(' ', '_'),
referenceNumber: reference || undefined,
paymentDate: new Date().toISOString().split('T')[0],
});
Alert.alert('Success', 'Payment recorded!', [{ text: 'OK', onPress: () => router.back() }]);
} catch (e: any) {
Alert.alert('Failed', e?.response?.data?.message ?? 'Could not record payment.');
} finally { setLoading(false); }
};
return (
<ScrollView className="flex-1 bg-gray-50 pt-14">
<TouchableOpacity className="px-4 mb-4" onPress={() => router.back()}>
<Text className="text-primary"> Back</Text>
</TouchableOpacity>
<Text className="text-2xl font-bold text-gray-900 px-4 mb-6">Record Payment</Text>
<View className="bg-white mx-4 rounded-2xl p-5 border border-gray-100 mb-4">
<Text className="text-sm font-medium text-gray-700 mb-2">Account Number</Text>
<View className="flex-row gap-2">
<TextInput
className="flex-1 border border-gray-300 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
placeholder="e.g. 2024-0001"
value={accountNumber}
onChangeText={setAccountNumber}
/>
<TouchableOpacity className="bg-primary rounded-xl px-4 items-center justify-center" onPress={searchClient}>
{searching ? <ActivityIndicator color="#fff" size="small" /> : <Text className="text-white font-medium text-sm">Find</Text>}
</TouchableOpacity>
</View>
{client && (
<View className="mt-3 bg-blue-50 rounded-xl p-3">
<Text className="text-primary font-semibold">{client.name}</Text>
<Text className="text-gray-500 text-xs">{client.accountNumber} · {client.status}</Text>
</View>
)}
</View>
<View className="bg-white mx-4 rounded-2xl p-5 border border-gray-100 mb-4">
<Text className="text-sm font-medium text-gray-700 mb-2">Amount ()</Text>
<TextInput
className="border border-gray-300 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
placeholder="0.00"
value={amount}
onChangeText={setAmount}
keyboardType="decimal-pad"
/>
<Text className="text-sm font-medium text-gray-700 mt-4 mb-2">Payment Method</Text>
<View className="flex-row flex-wrap gap-2">
{METHODS.map(m => (
<TouchableOpacity
key={m}
className={`px-4 py-2 rounded-xl border ${method === m ? 'bg-primary border-primary' : 'border-gray-200 bg-white'}`}
onPress={() => setMethod(m)}
>
<Text className={`text-sm font-medium ${method === m ? 'text-white' : 'text-gray-700'}`}>{m}</Text>
</TouchableOpacity>
))}
</View>
<Text className="text-sm font-medium text-gray-700 mt-4 mb-2">Reference # (optional)</Text>
<TextInput
className="border border-gray-300 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
placeholder="GCash ref / OR number"
value={reference}
onChangeText={setReference}
/>
</View>
<TouchableOpacity
className={`mx-4 rounded-2xl py-4 items-center mb-8 ${loading ? 'bg-blue-400' : 'bg-primary'}`}
onPress={submit}
disabled={loading}
>
{loading ? <ActivityIndicator color="#fff" /> : <Text className="text-white font-semibold text-base">Record Payment</Text>}
</TouchableOpacity>
</ScrollView>
);
}

57
app/(app)/profile.tsx Normal file
View File

@@ -0,0 +1,57 @@
import { View, Text, TouchableOpacity, Alert, ScrollView } from 'react-native';
import { useAuthStore } from '../../stores/authStore';
import { router } from 'expo-router';
export default function ProfileScreen() {
const { user, logout, tenantSlug } = useAuthStore();
const handleLogout = () => {
Alert.alert('Sign Out', 'Are you sure you want to sign out?', [
{ text: 'Cancel', style: 'cancel' },
{
text: 'Sign Out', style: 'destructive',
onPress: async () => {
await logout();
router.replace('/(auth)/company-code');
}
}
]);
};
return (
<ScrollView className="flex-1 bg-gray-50">
<View className="px-4 pt-14 pb-6 bg-primary">
<View className="w-16 h-16 rounded-full bg-white/20 items-center justify-center mb-3">
<Text className="text-white text-2xl font-bold">
{user?.firstName?.[0]?.toUpperCase() ?? 'U'}
</Text>
</View>
<Text className="text-white text-xl font-bold">{user?.firstName} {user?.lastName}</Text>
<Text className="text-white/70 text-sm">{user?.role} · {tenantSlug}</Text>
</View>
<View className="px-4 py-6">
<View className="bg-white rounded-2xl border border-gray-100 mb-4">
{[
{ label: 'Username', value: user?.username },
{ label: 'Email', value: user?.email },
{ label: 'Role', value: user?.role },
{ label: 'Company', value: tenantSlug },
].map((item, i) => (
<View key={item.label} className={`px-4 py-3 ${i > 0 ? 'border-t border-gray-100' : ''}`}>
<Text className="text-gray-500 text-xs mb-0.5">{item.label}</Text>
<Text className="text-gray-900 font-medium">{item.value ?? '—'}</Text>
</View>
))}
</View>
<TouchableOpacity
className="bg-red-50 border border-red-200 rounded-2xl py-4 items-center"
onPress={handleLogout}
>
<Text className="text-red-600 font-semibold">Sign Out</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}

View File

@@ -0,0 +1,60 @@
import { View, Text, ScrollView, ActivityIndicator, TouchableOpacity, TextInput, Alert } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { api } from '../../../services/api';
export default function TicketDetailScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const router = useRouter();
const [reply, setReply] = useState('');
const { data: ticket, isLoading, refetch } = useQuery({
queryKey: ['ticket', id],
queryFn: () => api.get(`/api/v1/tickets/${id}`).then(r => r.data),
});
const sendReply = async () => {
if (!reply.trim()) return;
try {
await api.post(`/api/v1/tickets/${id}/messages`, { message: reply });
setReply('');
refetch();
} catch { Alert.alert('Error', 'Could not send reply.'); }
};
if (isLoading) return <ActivityIndicator color="#2563EB" className="flex-1 mt-20" />;
return (
<View className="flex-1 bg-gray-50">
<View className="pt-14 pb-4 px-4 bg-white border-b border-gray-100">
<TouchableOpacity onPress={() => router.back()} className="mb-2">
<Text className="text-primary text-sm"> Tickets</Text>
</TouchableOpacity>
<Text className="text-lg font-bold text-gray-900">{ticket?.subject}</Text>
<Text className="text-gray-500 text-xs">{ticket?.clientName} · {ticket?.status}</Text>
</View>
<ScrollView className="flex-1 px-4 py-4">
{(ticket?.messages ?? []).map((m: any) => (
<View key={m.id} className={`mb-3 p-3 rounded-xl max-w-xs ${m.senderType === 'staff' ? 'bg-primary self-end' : 'bg-white self-start border border-gray-100'}`}>
<Text className={m.senderType === 'staff' ? 'text-white text-sm' : 'text-gray-900 text-sm'}>{m.message}</Text>
<Text className={`text-xs mt-1 ${m.senderType === 'staff' ? 'text-blue-200' : 'text-gray-400'}`}>{m.senderName}</Text>
</View>
))}
</ScrollView>
<View className="px-4 py-3 bg-white border-t border-gray-100 flex-row gap-2">
<TextInput
className="flex-1 border border-gray-200 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
placeholder="Type a reply..."
value={reply}
onChangeText={setReply}
multiline
/>
<TouchableOpacity className="bg-primary rounded-xl px-4 items-center justify-center" onPress={sendReply}>
<Text className="text-white font-medium text-sm">Send</Text>
</TouchableOpacity>
</View>
</View>
);
}

View File

@@ -0,0 +1,50 @@
import { View, Text, FlatList, ActivityIndicator, TouchableOpacity, RefreshControl } from 'react-native';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'expo-router';
import { api } from '../../../services/api';
const STATUS_COLOR: Record<string, string> = {
open: 'bg-yellow-100 text-yellow-700',
in_progress: 'bg-blue-100 text-blue-700',
resolved: 'bg-green-100 text-green-700',
closed: 'bg-gray-100 text-gray-500',
};
export default function TicketsScreen() {
const router = useRouter();
const { data, isLoading, refetch, isRefetching } = useQuery({
queryKey: ['tickets'],
queryFn: () => api.get('/api/v1/tickets').then(r => r.data?.data ?? r.data?.results ?? r.data),
});
const tickets = Array.isArray(data) ? data : [];
return (
<View className="flex-1 bg-gray-50 pt-14">
<Text className="text-2xl font-bold text-gray-900 px-4 mb-4">Tickets</Text>
{isLoading ? <ActivityIndicator color="#2563EB" className="mt-10" /> : (
<FlatList
data={tickets}
keyExtractor={(item) => item.id}
refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 24 }}
renderItem={({ item }) => (
<TouchableOpacity
className="bg-white rounded-xl p-4 mb-2 border border-gray-100"
onPress={() => router.push(`/(app)/tickets/${item.id}`)}
>
<View className="flex-row justify-between items-start">
<Text className="flex-1 font-medium text-gray-900 mr-2">{item.subject}</Text>
<View className={`px-2 py-0.5 rounded-full ${STATUS_COLOR[item.status] ?? 'bg-gray-100 text-gray-500'}`}>
<Text className="text-xs font-medium">{item.status}</Text>
</View>
</View>
<Text className="text-gray-400 text-xs mt-1">{item.clientName} · {item.priority}</Text>
</TouchableOpacity>
)}
ListEmptyComponent={<Text className="text-gray-400 text-center mt-10">No tickets</Text>}
/>
)}
</View>
);
}

5
app/(auth)/_layout.tsx Normal file
View File

@@ -0,0 +1,5 @@
import { Stack } from 'expo-router';
export default function AuthLayout() {
return <Stack screenOptions={{ headerShown: false }} />;
}

View File

@@ -0,0 +1,68 @@
import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { router } from 'expo-router';
import { api } from '../../services/api';
export default function CompanyCodeScreen() {
const [slug, setSlug] = useState('');
const [loading, setLoading] = useState(false);
const handleContinue = async () => {
if (!slug.trim()) return Alert.alert('Required', 'Please enter your company code.');
setLoading(true);
try {
const res = await api.get(`/api/v1/auth/tenant/${slug.trim().toLowerCase()}/exists`);
if (res.data?.exists) {
router.push({ pathname: '/(auth)/login', params: { tenantSlug: slug.trim().toLowerCase() } });
} else {
Alert.alert('Not Found', 'Company code not found. Please check and try again.');
}
} catch {
Alert.alert('Error', 'Could not verify company code. Please try again.');
} finally {
setLoading(false);
}
};
return (
<KeyboardAvoidingView
className="flex-1 bg-white"
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<View className="flex-1 justify-center px-8">
<View className="mb-10 items-center">
<View className="w-16 h-16 rounded-2xl bg-primary items-center justify-center mb-4">
<Text className="text-white text-3xl font-bold">F</Text>
</View>
<Text className="text-3xl font-bold text-gray-900">FiberOps</Text>
<Text className="text-gray-500 mt-1">Field Operations</Text>
</View>
<Text className="text-xl font-semibold text-gray-900 mb-2">Enter Company Code</Text>
<Text className="text-gray-500 mb-6">Ask your admin for your company's unique code.</Text>
<TextInput
className="border border-gray-300 rounded-xl px-4 py-3 text-base text-gray-900 mb-4"
placeholder="e.g. mybusiness"
value={slug}
onChangeText={setSlug}
autoCapitalize="none"
autoCorrect={false}
autoFocus
/>
<TouchableOpacity
className="bg-primary rounded-xl py-4 items-center"
onPress={handleContinue}
disabled={loading}
>
{loading ? (
<ActivityIndicator color="white" />
) : (
<Text className="text-white font-semibold text-base">Continue</Text>
)}
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}

72
app/(auth)/login.tsx Normal file
View File

@@ -0,0 +1,72 @@
import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { useLocalSearchParams, router } from 'expo-router';
import { useAuthStore } from '../../stores/authStore';
export default function LoginScreen() {
const { tenantSlug } = useLocalSearchParams<{ tenantSlug: string }>();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { login, isLoading } = useAuthStore();
const handleLogin = async () => {
if (!username.trim() || !password) return Alert.alert('Required', 'Please enter username and password.');
try {
await login(tenantSlug, username.trim(), password);
router.replace('/(app)/dashboard');
} catch (e: any) {
const msg = e?.response?.data?.message ?? 'Login failed. Check your credentials.';
Alert.alert('Login Failed', Array.isArray(msg) ? msg.join('\n') : msg);
}
};
return (
<KeyboardAvoidingView
className="flex-1 bg-white"
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<View className="flex-1 justify-center px-8">
<TouchableOpacity className="mb-8" onPress={() => router.back()}>
<Text className="text-primary text-base"> Back</Text>
</TouchableOpacity>
<Text className="text-2xl font-bold text-gray-900 mb-1">Welcome back</Text>
<Text className="text-gray-500 mb-8">
Signing in to <Text className="font-semibold text-gray-700">{tenantSlug}</Text>
</Text>
<Text className="text-sm font-medium text-gray-700 mb-1">Username</Text>
<TextInput
className="border border-gray-300 rounded-xl px-4 py-3 text-base text-gray-900 mb-4"
placeholder="Enter username"
value={username}
onChangeText={setUsername}
autoCapitalize="none"
autoCorrect={false}
autoFocus
/>
<Text className="text-sm font-medium text-gray-700 mb-1">Password</Text>
<TextInput
className="border border-gray-300 rounded-xl px-4 py-3 text-base text-gray-900 mb-6"
placeholder="Enter password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<TouchableOpacity
className="bg-primary rounded-xl py-4 items-center"
onPress={handleLogin}
disabled={isLoading}
>
{isLoading ? (
<ActivityIndicator color="white" />
) : (
<Text className="text-white font-semibold text-base">Sign In</Text>
)}
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}

31
app/_layout.tsx Normal file
View File

@@ -0,0 +1,31 @@
import '../global.css';
import { useEffect } from 'react';
import { Stack, router } from 'expo-router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useAuthStore } from '../stores/authStore';
const queryClient = new QueryClient();
export default function RootLayout() {
const { hydrate, token, isLoading } = useAuthStore();
useEffect(() => {
hydrate();
}, []);
useEffect(() => {
if (!isLoading) {
if (token) {
router.replace('/(app)/dashboard');
} else {
router.replace('/(auth)/company-code');
}
}
}, [isLoading, token]);
return (
<QueryClientProvider client={queryClient}>
<Stack screenOptions={{ headerShown: false }} />
</QueryClientProvider>
);
}

5
app/index.tsx Normal file
View File

@@ -0,0 +1,5 @@
import { Redirect } from 'expo-router';
export default function Index() {
return <Redirect href="/(auth)/company-code" />;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
assets/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
assets/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

BIN
assets/splash-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

9
babel.config.js Normal file
View File

@@ -0,0 +1,9 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [
['babel-preset-expo', { jsxImportSource: 'nativewind' }],
'nativewind/babel',
],
};
};

49
components/AppButton.tsx Normal file
View File

@@ -0,0 +1,49 @@
import React from 'react';
import { TouchableOpacity, Text, ActivityIndicator, View } from 'react-native';
interface AppButtonProps {
title: string;
onPress: () => void;
variant?: 'primary' | 'secondary' | 'danger' | 'outline';
loading?: boolean;
disabled?: boolean;
className?: string;
}
export const AppButton: React.FC<AppButtonProps> = ({
title,
onPress,
variant = 'primary',
loading = false,
disabled = false,
className = '',
}) => {
const baseClasses = 'flex-row items-center justify-center rounded-xl px-6 py-3.5 active:opacity-80';
const variantClasses = {
primary: 'bg-blue-600',
secondary: 'bg-gray-200',
danger: 'bg-red-600',
outline: 'border-2 border-blue-600 bg-transparent',
};
const textClasses = {
primary: 'text-white font-semibold text-base',
secondary: 'text-gray-800 font-semibold text-base',
danger: 'text-white font-semibold text-base',
outline: 'text-blue-600 font-semibold text-base',
};
const disabledClass = disabled || loading ? 'opacity-50' : '';
return (
<TouchableOpacity
onPress={onPress}
disabled={disabled || loading}
className={`${baseClasses} ${variantClasses[variant]} ${disabledClass} ${className}`}
>
{loading ? (
<ActivityIndicator color={variant === 'outline' ? '#2563EB' : '#fff'} size="small" />
) : (
<Text className={textClasses[variant]}>{title}</Text>
)}
</TouchableOpacity>
);
};

31
components/AppCard.tsx Normal file
View File

@@ -0,0 +1,31 @@
import React from 'react';
import { View, ViewProps } from 'react-native';
interface AppCardProps extends ViewProps {
children: React.ReactNode;
className?: string;
padding?: 'sm' | 'md' | 'lg' | 'none';
}
export const AppCard: React.FC<AppCardProps> = ({
children,
className = '',
padding = 'md',
...props
}) => {
const paddingClasses = {
none: '',
sm: 'p-3',
md: 'p-4',
lg: 'p-6',
};
return (
<View
className={`bg-white rounded-2xl shadow-sm border border-gray-100 ${paddingClasses[padding]} ${className}`}
{...props}
>
{children}
</View>
);
};

48
components/AppInput.tsx Normal file
View File

@@ -0,0 +1,48 @@
import React, { useState } from 'react';
import { View, TextInput, Text, TouchableOpacity, TextInputProps } from 'react-native';
interface AppInputProps extends TextInputProps {
label?: string;
error?: string;
secureToggle?: boolean;
leftIcon?: React.ReactNode;
}
export const AppInput: React.FC<AppInputProps> = ({
label,
error,
secureToggle,
leftIcon,
...props
}) => {
const [showPassword, setShowPassword] = useState(false);
return (
<View className="mb-4">
{label && (
<Text className="text-sm font-medium text-gray-700 mb-1.5">{label}</Text>
)}
<View
className={`flex-row items-center bg-white border rounded-xl px-4 h-12 ${
error ? 'border-red-500' : 'border-gray-200'
}`}
>
{leftIcon && <View className="mr-2">{leftIcon}</View>}
<TextInput
className="flex-1 text-gray-900 text-base"
placeholderTextColor="#9CA3AF"
secureTextEntry={secureToggle ? !showPassword : props.secureTextEntry}
{...props}
/>
{secureToggle && (
<TouchableOpacity onPress={() => setShowPassword(!showPassword)}>
<Text className="text-blue-600 text-sm font-medium">
{showPassword ? 'Hide' : 'Show'}
</Text>
</TouchableOpacity>
)}
</View>
{error && <Text className="text-red-500 text-xs mt-1">{error}</Text>}
</View>
);
};

55
components/Avatar.tsx Normal file
View File

@@ -0,0 +1,55 @@
import React from 'react';
import { View, Text, Image } from 'react-native';
interface AvatarProps {
name?: string;
uri?: string;
size?: 'sm' | 'md' | 'lg' | 'xl';
}
const sizeClasses = {
sm: { container: 'w-8 h-8', text: 'text-xs' },
md: { container: 'w-10 h-10', text: 'text-sm' },
lg: { container: 'w-14 h-14', text: 'text-xl' },
xl: { container: 'w-20 h-20', text: 'text-3xl' },
};
const sizePx = { sm: 32, md: 40, lg: 56, xl: 80 };
function getInitials(name: string) {
return name
.split(' ')
.slice(0, 2)
.map((n) => n[0])
.join('')
.toUpperCase();
}
function hashColor(name: string) {
const colors = ['bg-blue-500', 'bg-purple-500', 'bg-green-500', 'bg-orange-500', 'bg-pink-500', 'bg-teal-500'];
let hash = 0;
for (const ch of name) hash = (hash * 31 + ch.charCodeAt(0)) & 0xffffffff;
return colors[Math.abs(hash) % colors.length];
}
export const Avatar: React.FC<AvatarProps> = ({ name = '', uri, size = 'md' }) => {
const { container, text } = sizeClasses[size];
const px = sizePx[size];
if (uri) {
return (
<Image
source={{ uri }}
className={`${container} rounded-full`}
style={{ width: px, height: px, borderRadius: px / 2 }}
/>
);
}
return (
<View className={`${container} ${hashColor(name)} rounded-full items-center justify-center`}
style={{ width: px, height: px, borderRadius: px / 2 }}>
<Text className={`${text} font-bold text-white`}>{getInitials(name) || '?'}</Text>
</View>
);
};

View File

@@ -0,0 +1,57 @@
import React from 'react';
import { Modal, View, Text, TouchableOpacity } from 'react-native';
import { AppButton } from './AppButton';
interface ConfirmModalProps {
visible: boolean;
title: string;
message: string;
confirmLabel?: string;
cancelLabel?: string;
confirmVariant?: 'primary' | 'danger';
onConfirm: () => void;
onCancel: () => void;
}
export const ConfirmModal: React.FC<ConfirmModalProps> = ({
visible,
title,
message,
confirmLabel = 'Confirm',
cancelLabel = 'Cancel',
confirmVariant = 'primary',
onConfirm,
onCancel,
}) => {
return (
<Modal visible={visible} transparent animationType="fade" onRequestClose={onCancel}>
<TouchableOpacity
className="flex-1 bg-black/50 items-center justify-center px-6"
activeOpacity={1}
onPress={onCancel}
>
<TouchableOpacity
className="w-full bg-white rounded-2xl p-6 shadow-lg"
activeOpacity={1}
>
<Text className="text-xl font-bold text-gray-900 mb-2">{title}</Text>
<Text className="text-gray-600 text-sm mb-6">{message}</Text>
<View className="flex-row gap-3">
<AppButton
title={cancelLabel}
onPress={onCancel}
variant="outline"
className="flex-1"
/>
<AppButton
title={confirmLabel}
onPress={onConfirm}
variant={confirmVariant}
className="flex-1"
/>
</View>
</TouchableOpacity>
</TouchableOpacity>
</Modal>
);
};

32
components/EmptyState.tsx Normal file
View File

@@ -0,0 +1,32 @@
import React from 'react';
import { View, Text } from 'react-native';
import { AppButton } from './AppButton';
interface EmptyStateProps {
title: string;
description?: string;
actionLabel?: string;
onAction?: () => void;
icon?: string;
}
export const EmptyState: React.FC<EmptyStateProps> = ({
title,
description,
actionLabel,
onAction,
icon = '📭',
}) => {
return (
<View className="flex-1 items-center justify-center px-8 py-16">
<Text className="text-5xl mb-4">{icon}</Text>
<Text className="text-lg font-semibold text-gray-800 text-center mb-2">{title}</Text>
{description && (
<Text className="text-sm text-gray-500 text-center mb-6">{description}</Text>
)}
{actionLabel && onAction && (
<AppButton title={actionLabel} onPress={onAction} className="min-w-[160px]" />
)}
</View>
);
};

View File

@@ -0,0 +1,34 @@
import React from 'react';
import { View, ActivityIndicator, Text } from 'react-native';
interface LoadingSpinnerProps {
message?: string;
fullScreen?: boolean;
size?: 'small' | 'large';
}
export const LoadingSpinner: React.FC<LoadingSpinnerProps> = ({
message,
fullScreen = false,
size = 'large',
}) => {
if (fullScreen) {
return (
<View className="flex-1 items-center justify-center bg-gray-50">
<ActivityIndicator size={size} color="#2563EB" />
{message && (
<Text className="mt-3 text-gray-500 text-sm">{message}</Text>
)}
</View>
);
}
return (
<View className="items-center justify-center py-8">
<ActivityIndicator size={size} color="#2563EB" />
{message && (
<Text className="mt-2 text-gray-500 text-sm">{message}</Text>
)}
</View>
);
};

View File

@@ -0,0 +1,47 @@
import React from 'react';
import { View, Text } from 'react-native';
type Status =
| 'active' | 'inactive' | 'suspended'
| 'open' | 'in_progress' | 'resolved' | 'closed'
| 'paid' | 'unpaid' | 'partial' | 'overdue'
| 'pending' | 'approved' | 'rejected'
| string;
interface StatusBadgeProps {
status: Status;
label?: string;
}
const statusConfig: Record<string, { bg: string; text: string; label: string }> = {
active: { bg: 'bg-green-100', text: 'text-green-700', label: 'Active' },
inactive: { bg: 'bg-gray-100', text: 'text-gray-600', label: 'Inactive' },
suspended: { bg: 'bg-red-100', text: 'text-red-700', label: 'Suspended' },
open: { bg: 'bg-blue-100', text: 'text-blue-700', label: 'Open' },
in_progress: { bg: 'bg-yellow-100',text: 'text-yellow-700',label: 'In Progress' },
resolved: { bg: 'bg-green-100', text: 'text-green-700', label: 'Resolved' },
closed: { bg: 'bg-gray-100', text: 'text-gray-600', label: 'Closed' },
paid: { bg: 'bg-green-100', text: 'text-green-700', label: 'Paid' },
unpaid: { bg: 'bg-red-100', text: 'text-red-700', label: 'Unpaid' },
partial: { bg: 'bg-orange-100',text: 'text-orange-700',label: 'Partial' },
overdue: { bg: 'bg-red-100', text: 'text-red-700', label: 'Overdue' },
pending: { bg: 'bg-yellow-100',text: 'text-yellow-700',label: 'Pending' },
approved: { bg: 'bg-green-100', text: 'text-green-700', label: 'Approved' },
rejected: { bg: 'bg-red-100', text: 'text-red-700', label: 'Rejected' },
};
export const StatusBadge: React.FC<StatusBadgeProps> = ({ status, label }) => {
const config = statusConfig[status] ?? {
bg: 'bg-gray-100',
text: 'text-gray-600',
label: status.replace(/_/g, ' '),
};
return (
<View className={`px-2.5 py-1 rounded-full self-start ${config.bg}`}>
<Text className={`text-xs font-medium capitalize ${config.text}`}>
{label ?? config.label}
</Text>
</View>
);
};

8
components/index.ts Normal file
View File

@@ -0,0 +1,8 @@
export { AppButton } from './AppButton';
export { AppInput } from './AppInput';
export { AppCard } from './AppCard';
export { StatusBadge } from './StatusBadge';
export { LoadingSpinner } from './LoadingSpinner';
export { EmptyState } from './EmptyState';
export { Avatar } from './Avatar';
export { ConfirmModal } from './ConfirmModal';

19
constants/index.ts Normal file
View File

@@ -0,0 +1,19 @@
export const API_URL = process.env.EXPO_PUBLIC_API_URL ?? 'http://192.168.1.167:3001';
export const COLORS = {
primary: '#2563EB',
primaryDark: '#1D4ED8',
danger: '#DC2626',
success: '#16A34A',
warning: '#D97706',
muted: '#6B7280',
background: '#F3F4F6',
white: '#FFFFFF',
black: '#111827',
border: '#E5E7EB',
};
export const STORAGE_KEYS = {
TOKEN: 'fiberops_token',
USER: 'fiberops_user',
};

3
global.css Normal file
View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

1
index.ts Normal file
View File

@@ -0,0 +1 @@
import 'expo-router/entry';

6
metro.config.js Normal file
View File

@@ -0,0 +1,6 @@
const { getDefaultConfig } = require('expo/metro-config');
const { withNativeWind } = require('nativewind/metro');
const config = getDefaultConfig(__dirname);
module.exports = withNativeWind(config, { input: './global.css' });

9054
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
package.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "fiberops-mobile",
"version": "1.0.0",
"main": "index.ts",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"@react-native-async-storage/async-storage": "^3.0.1",
"@tanstack/react-query": "^5.95.0",
"axios": "^1.13.6",
"expo": "~55.0.8",
"expo-camera": "^55.0.10",
"expo-constants": "^55.0.9",
"expo-image-picker": "^55.0.13",
"expo-linking": "^55.0.8",
"expo-location": "^55.1.4",
"expo-notifications": "^55.0.13",
"expo-router": "^55.0.7",
"expo-secure-store": "^55.0.9",
"expo-status-bar": "~55.0.4",
"nativewind": "^4.2.3",
"react": "19.2.0",
"react-native": "0.83.2",
"react-native-safe-area-context": "^5.7.0",
"react-native-screens": "^4.24.0",
"tailwindcss": "^4.2.2",
"zustand": "^5.0.12"
},
"devDependencies": {
"@types/react": "~19.2.2",
"typescript": "~5.9.2"
},
"private": true
}

32
services/api.ts Normal file
View File

@@ -0,0 +1,32 @@
import axios from 'axios';
import * as SecureStore from 'expo-secure-store';
import { API_URL, STORAGE_KEYS } from '../constants';
export const api = axios.create({
baseURL: API_URL,
timeout: 15000,
headers: {
'Content-Type': 'application/json',
},
});
api.interceptors.request.use(async (config) => {
const token = await SecureStore.getItemAsync(STORAGE_KEYS.TOKEN);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
await SecureStore.deleteItemAsync(STORAGE_KEYS.TOKEN);
await SecureStore.deleteItemAsync(STORAGE_KEYS.USER);
}
return Promise.reject(error);
}
);
export default api;

43
services/auth.service.ts Normal file
View File

@@ -0,0 +1,43 @@
import api from './api';
export interface LoginPayload {
tenant_slug: string;
username: string;
password: string;
}
export interface LoginResponse {
token: string;
user: {
id: number;
name: string;
username: string;
email: string;
role: string;
tenant_slug: string;
};
}
export const authService = {
async checkTenantExists(slug: string): Promise<boolean> {
const res = await api.get(`/api/v1/auth/tenant/${slug}/exists`);
return res.data?.exists === true;
},
async login(payload: LoginPayload): Promise<LoginResponse> {
const res = await api.post('/api/v1/auth/login', payload);
return res.data;
},
async getProfile(): Promise<LoginResponse['user']> {
const res = await api.get('/api/v1/auth/me');
return res.data;
},
async changePassword(currentPassword: string, newPassword: string): Promise<void> {
await api.post('/api/v1/auth/change-password', {
current_password: currentPassword,
new_password: newPassword,
});
},
};

64
stores/auth.store.ts Normal file
View File

@@ -0,0 +1,64 @@
import { create } from 'zustand';
import * as SecureStore from 'expo-secure-store';
import { STORAGE_KEYS } from '../constants';
interface User {
id: number;
name: string;
username: string;
email: string;
role: string;
tenant_slug: string;
}
interface AuthState {
token: string | null;
user: User | null;
tenantSlug: string | null;
isLoading: boolean;
isAuthenticated: boolean;
setAuth: (token: string, user: User) => Promise<void>;
setTenantSlug: (slug: string) => void;
logout: () => Promise<void>;
loadFromStorage: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set) => ({
token: null,
user: null,
tenantSlug: null,
isLoading: true,
isAuthenticated: false,
setAuth: async (token, user) => {
await SecureStore.setItemAsync(STORAGE_KEYS.TOKEN, token);
await SecureStore.setItemAsync(STORAGE_KEYS.USER, JSON.stringify(user));
set({ token, user, isAuthenticated: true, tenantSlug: user.tenant_slug });
},
setTenantSlug: (slug) => {
set({ tenantSlug: slug });
},
logout: async () => {
await SecureStore.deleteItemAsync(STORAGE_KEYS.TOKEN);
await SecureStore.deleteItemAsync(STORAGE_KEYS.USER);
set({ token: null, user: null, isAuthenticated: false });
},
loadFromStorage: async () => {
try {
const token = await SecureStore.getItemAsync(STORAGE_KEYS.TOKEN);
const userStr = await SecureStore.getItemAsync(STORAGE_KEYS.USER);
if (token && userStr) {
const user = JSON.parse(userStr) as User;
set({ token, user, isAuthenticated: true, tenantSlug: user.tenant_slug, isLoading: false });
} else {
set({ isLoading: false });
}
} catch {
set({ isLoading: false });
}
},
}));

51
stores/authStore.ts Normal file
View File

@@ -0,0 +1,51 @@
import { create } from 'zustand';
import * as SecureStore from 'expo-secure-store';
import { api } from '../services/api';
interface AuthState {
token: string | null;
tenantSlug: string | null;
user: any | null;
isLoading: boolean;
login: (tenantSlug: string, username: string, password: string) => Promise<void>;
logout: () => Promise<void>;
hydrate: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set) => ({
token: null,
tenantSlug: null,
user: null,
isLoading: true,
hydrate: async () => {
try {
const token = await SecureStore.getItemAsync('auth_token');
const tenantSlug = await SecureStore.getItemAsync('tenant_slug');
if (token && tenantSlug) {
const res = await api.get('/api/v1/auth/me');
set({ token, tenantSlug, user: res.data, isLoading: false });
} else {
set({ isLoading: false });
}
} catch {
await SecureStore.deleteItemAsync('auth_token');
await SecureStore.deleteItemAsync('tenant_slug');
set({ token: null, tenantSlug: null, user: null, isLoading: false });
}
},
login: async (tenantSlug, username, password) => {
const res = await api.post('/api/v1/auth/login', { tenantSlug, username, password });
const { token, user } = res.data;
await SecureStore.setItemAsync('auth_token', token);
await SecureStore.setItemAsync('tenant_slug', tenantSlug);
set({ token, tenantSlug, user });
},
logout: async () => {
await SecureStore.deleteItemAsync('auth_token');
await SecureStore.deleteItemAsync('tenant_slug');
set({ token: null, tenantSlug: null, user: null });
},
}));

18
tailwind.config.js Normal file
View File

@@ -0,0 +1,18 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./app/**/*.{js,jsx,ts,tsx}', './components/**/*.{js,jsx,ts,tsx}'],
presets: [require('nativewind/preset')],
theme: {
extend: {
colors: {
primary: '#2563EB',
'primary-dark': '#1D4ED8',
danger: '#DC2626',
success: '#16A34A',
warning: '#D97706',
muted: '#6B7280',
},
},
},
plugins: [],
};

15
tsconfig.json Normal file
View File

@@ -0,0 +1,15 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"baseUrl": ".",
"paths": {
"@/*": ["./*"],
"@/components/*": ["./components/*"],
"@/stores/*": ["./stores/*"],
"@/services/*": ["./services/*"],
"@/hooks/*": ["./hooks/*"],
"@/constants/*": ["./constants/*"]
}
}
}