-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
371 lines (345 loc) · 12.6 KB
/
App.tsx
File metadata and controls
371 lines (345 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import React, { useState, useEffect } from 'react';
import { View, TouchableOpacity, Text, ScrollView, ActivityIndicator, Alert } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Toast from 'react-native-toast-message';
import { toastConfig } from './src/components/ToastConfig';
import { setupDeepLinkListener } from './src/utils/deepLinkHandler';
import { initializeNotifications, setupNotificationListeners, sendLowStockAlert } from './src/utils/notifications';
import { warningHaptic } from './src/utils/haptics';
import PantryHomePage from './src/screens/PantryHomePage';
import GroceryListPage from './src/screens/GroceryListPage';
import AccountPage from './src/screens/AccountPage';
import SignInScreen from './src/screens/SignInScreen';
import SignUpScreen from './src/screens/SignUpScreen';
import ForgotPasswordScreen from './src/screens/ForgotPasswordScreen';
import EmailVerificationScreen from './src/screens/EmailVerificationScreen';
import ProfileSetupScreen from './src/screens/ProfileSetupScreen';
import { AuthProvider, useAuth } from './src/contexts/AuthContext';
import { useCurrentUser } from './src/hooks/useCurrentUser';
import styles from './src/styles/homeStyles';
import { usePantryData } from './src/hooks/usePantryData';
import { useGroceryItems } from './src/hooks/useGroceryItems';
import { DEFAULT_CATEGORIES, Category } from './src/config/categories';
import { GroceryItem, CreateGroceryItemInput } from './src/types/grocery';
// Main app component with auth wrapper
function AppContent() {
const { session, loading: authLoading, resendVerificationEmail } = useAuth();
const { household, roommate: currentRoommate, currentUser, isLoading: userLoading, refresh: refreshUser } = useCurrentUser();
const [activeTab, setActiveTab] = useState<'pantry' | 'grocery' | 'account'>('pantry');
const [categories, setCategories] = useState<Category[]>(DEFAULT_CATEGORIES);
const [authScreen, setAuthScreen] = useState<'signin' | 'signup' | 'forgot' | 'verify' | 'profile-setup'>('signin');
const [verificationEmail, setVerificationEmail] = useState<string>('');
const [needsProfileSetup, setNeedsProfileSetup] = useState(false);
const householdId = household?.id || '';
const { isLoading, error } = usePantryData(householdId);
const { items: groceryItems, addItem: addGroceryItem } = useGroceryItems(householdId);
// Check if user needs to complete profile setup
useEffect(() => {
if (session && currentUser && !userLoading) {
// Check if user has a proper name (not just email prefix)
const hasCompletedProfile = currentUser.name &&
currentUser.name !== session.user.email?.split('@')[0];
if (!hasCompletedProfile) {
setNeedsProfileSetup(true);
} else {
setNeedsProfileSetup(false);
}
}
}, [session, currentUser, userLoading]);
// Set up deep link listener for email verification and password reset
useEffect(() => {
const cleanup = setupDeepLinkListener(
// On email verified
() => {
Alert.alert(
'Email Verified!',
'Your email has been verified. You can now sign in.',
[{ text: 'OK', onPress: () => setAuthScreen('signin') }]
);
},
// On password reset required
() => {
// Handle password reset flow - user will be automatically signed in
Alert.alert(
'Password Reset',
'You can now set a new password in your account settings.'
);
}
);
return cleanup;
}, []);
// Initialize notifications when user is signed in
useEffect(() => {
if (session) {
initializeNotifications();
}
}, [session]);
// Show auth loading screen
if (authLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff' }}>
<ActivityIndicator size="large" color="#000000" />
<Text style={{ marginTop: 16, fontSize: 16, color: '#666' }}>
Loading...
</Text>
</View>
);
}
// Show auth screens if not logged in
if (!session) {
return (
<>
{authScreen === 'signin' && (
<SignInScreen
onNavigateToSignUp={() => setAuthScreen('signup')}
onNavigateToForgotPassword={() => setAuthScreen('forgot')}
onNavigateToVerify={(email) => {
setVerificationEmail(email);
setAuthScreen('verify');
}}
/>
)}
{authScreen === 'signup' && (
<SignUpScreen
onNavigateToSignIn={() => setAuthScreen('signin')}
onNavigateToVerify={(email) => {
setVerificationEmail(email);
setAuthScreen('verify');
}}
/>
)}
{authScreen === 'forgot' && (
<ForgotPasswordScreen onNavigateBack={() => setAuthScreen('signin')} />
)}
{authScreen === 'verify' && (
<EmailVerificationScreen
email={verificationEmail}
onNavigateToSignIn={() => setAuthScreen('signin')}
onResendEmail={() => resendVerificationEmail(verificationEmail)}
/>
)}
</>
);
}
// Show profile setup screen if user is logged in but hasn't completed their profile
if (session && needsProfileSetup && !userLoading) {
return (
<ProfileSetupScreen
onComplete={() => {
setNeedsProfileSetup(false);
// Refresh user data to get updated profile
refreshUser();
}}
/>
);
}
// Function to delete a category
const handleDeleteCategory = (categoryId: string) => {
const categoryToDelete = categories.find(cat => cat.id === categoryId);
if (!categoryToDelete) return;
Alert.alert(
'Delete Category',
`Are you sure you want to delete "${categoryToDelete.name}"? Items in this category will be moved to "Other".`,
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: () => {
// Remove category from list
setCategories(categories.filter(cat => cat.id !== categoryId));
},
},
]
);
};
// Helper function to check if items are duplicates
const isDuplicateGroceryItem = (
pantryItem: {
name: string;
brand?: string;
packageSize?: string;
catalogProductId?: string;
},
groceryItem: GroceryItem
): boolean => {
// Level 1: Catalog Product ID match (most reliable)
if (pantryItem.catalogProductId && groceryItem.catalogProductId) {
return pantryItem.catalogProductId === groceryItem.catalogProductId;
}
// Level 2: Name + Brand + Package Size match
const nameMatch = pantryItem.name.toLowerCase() === groceryItem.name.toLowerCase();
const brandMatch = (pantryItem.brand || '').toLowerCase() === (groceryItem.brand || '').toLowerCase();
const sizeMatch = (pantryItem.packageSize || '').toLowerCase() === (groceryItem.packageSize || '').toLowerCase();
return nameMatch && brandMatch && sizeMatch;
};
// Function to add low-stock item to grocery list
const addLowStockToGroceryList = async (pantryItem: {
id: string;
name: string;
quantity: number;
unit: string;
location: string;
category?: string;
brand?: string;
packageSize?: string;
catalogProductId?: string;
}) => {
// Check if item already exists in grocery list using improved duplicate detection
const existingItem = groceryItems.find(item => isDuplicateGroceryItem(pantryItem, item));
if (existingItem) {
if (existingItem.checked) {
// Item was already purchased (checked off) but is low again
// Add a NEW unchecked item so user can buy more
const newGroceryItem: CreateGroceryItemInput = {
name: pantryItem.name,
quantity: pantryItem.quantity,
unit: pantryItem.unit,
addedBy: currentRoommate?.name || 'Auto (Low Stock)',
location: pantryItem.location,
checked: false,
isLowStock: true,
lowStockSource: 'pantry',
category: pantryItem.category,
brand: pantryItem.brand,
packageSize: pantryItem.packageSize,
catalogProductId: pantryItem.catalogProductId,
};
try {
await addGroceryItem(newGroceryItem);
await sendLowStockAlert(pantryItem.name);
warningHaptic();
} catch (error) {
console.error('Error adding low stock item to grocery list:', error);
}
} else {
// Item already on list and unchecked - skip to avoid duplicates
console.log('Item already on grocery list (unchecked):', existingItem.name);
}
} else {
// Not a duplicate - add new item to grocery list
const newGroceryItem: CreateGroceryItemInput = {
name: pantryItem.name,
quantity: pantryItem.quantity,
unit: pantryItem.unit,
addedBy: currentRoommate?.name || 'Auto (Low Stock)',
location: pantryItem.location,
checked: false,
isLowStock: true,
lowStockSource: 'pantry',
category: pantryItem.category,
brand: pantryItem.brand,
packageSize: pantryItem.packageSize,
catalogProductId: pantryItem.catalogProductId,
};
try {
await addGroceryItem(newGroceryItem);
await sendLowStockAlert(pantryItem.name);
warningHaptic();
} catch (error) {
console.error('Error adding low stock item to grocery list:', error);
}
}
};
const tabs = [
{ key: 'pantry', label: 'PANTRY' },
{ key: 'grocery', label: 'SHOPPING' },
{ key: 'account', label: 'ACCOUNT' },
] as const;
// Show loading screen while catalog initializes
if (isLoading) {
return (
<SafeAreaProvider>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff' }}>
<ActivityIndicator size="large" color="#007AFF" />
<Text style={{ marginTop: 16, fontSize: 16, color: '#666' }}>
Loading catalog...
</Text>
</View>
</SafeAreaProvider>
);
}
// Show error if catalog failed to initialize
if (error) {
return (
<SafeAreaProvider>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', padding: 20 }}>
<Text style={{ fontSize: 24, marginBottom: 12 }}>⚠️</Text>
<Text style={{ fontSize: 16, color: '#666', textAlign: 'center' }}>
Failed to load catalog
</Text>
<Text style={{ fontSize: 14, color: '#999', marginTop: 8, textAlign: 'center' }}>
{error}
</Text>
</View>
</SafeAreaProvider>
);
}
return (
<SafeAreaProvider>
<View style={{ flex: 1 }}>
{/* Render Active Screen */}
{activeTab === 'pantry' && (
<PantryHomePage
activeTab={activeTab}
setActiveTab={setActiveTab}
onLowStock={addLowStockToGroceryList}
categories={categories}
onDeleteCategory={handleDeleteCategory}
/>
)}
{activeTab === 'grocery' && (
<GroceryListPage
activeTab={activeTab}
setActiveTab={setActiveTab}
categories={categories}
onDeleteCategory={handleDeleteCategory}
/>
)}
{activeTab === 'account' && (
<AccountPage activeTab={activeTab} setActiveTab={setActiveTab} />
)}
{/* Bottom Navigation */}
<View style={styles.bottomNav}>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.navScrollContainer}
>
{tabs.map((tab) => (
<TouchableOpacity
key={tab.key}
style={styles.navTab}
onPress={() => setActiveTab(tab.key)}
activeOpacity={0.7}
>
{activeTab === tab.key && (
<View style={styles.navTabIndicator} />
)}
<Text
style={[
styles.navTabText,
activeTab === tab.key && styles.navTabTextActive,
]}
>
{tab.label}
</Text>
</TouchableOpacity>
))}
</ScrollView>
</View>
</View>
</SafeAreaProvider>
);
}
// Root App component with AuthProvider
export default function App() {
return (
<SafeAreaProvider>
<AuthProvider>
<AppContent />
<Toast config={toastConfig} />
</AuthProvider>
</SafeAreaProvider>
);
}