570 lines
19 KiB
JavaScript
570 lines
19 KiB
JavaScript
import { useEffect, useMemo, useState } from 'react';
|
|
import { BackHandler, SafeAreaView, StyleSheet, Text, View } from 'react-native';
|
|
import { StatusBar } from 'expo-status-bar';
|
|
|
|
import BottomTabBar from './src/components/layout/BottomTabBar';
|
|
import AlternativesScreen from './src/screens/AlternativesScreen';
|
|
import HomeScreen from './src/screens/HomeScreen';
|
|
import NutritionInsightsScreen from './src/screens/NutritionInsightsScreen';
|
|
import OnboardingScreen from './src/screens/OnboardingScreen';
|
|
import ProductDetailScreen from './src/screens/ProductDetailScreen';
|
|
import ProductEditScreen from './src/screens/ProductEditScreen';
|
|
import ProfileScreen from './src/screens/ProfileScreen';
|
|
import PrivacyScreen from './src/screens/PrivacyScreen';
|
|
import RatingCriteriaDetailScreen from './src/screens/RatingCriteriaDetailScreen';
|
|
import ScanScreen from './src/screens/ScanScreen';
|
|
import ShoppingListScreen from './src/screens/ShoppingListScreen';
|
|
import { lookupProductByBarcode, NUTRITION_SCHEMA_VERSION } from './src/services/productApi';
|
|
import { enrichEnvironmentalProduct } from './src/services/environmentalService';
|
|
import { createLocalProduct, saveManualProduct } from './src/services/manualProduct';
|
|
import { storageService } from './src/services/storageService';
|
|
import {
|
|
appendConsumptionEntry,
|
|
createConsumptionEntry,
|
|
editConsumptionEntry,
|
|
removeConsumptionEntry
|
|
} from './src/services/dailyNutritionService';
|
|
import { colors, defaultPreferences } from './src/utils/constants';
|
|
|
|
const initialShoppingList = {
|
|
id: 'active-list',
|
|
title: 'Aktueller Einkauf',
|
|
items: [],
|
|
status: 'active',
|
|
createdAt: new Date().toISOString()
|
|
};
|
|
|
|
export default function App() {
|
|
const [activeTab, setActiveTab] = useState('home');
|
|
const [route, setRoute] = useState({ name: 'tabs' });
|
|
const [preferences, setPreferences] = useState(defaultPreferences);
|
|
const [shoppingList, setShoppingList] = useState(initialShoppingList);
|
|
const [productCache, setProductCache] = useState({});
|
|
const [recentProducts, setRecentProducts] = useState([]);
|
|
const [dailyLog, setDailyLog] = useState([]);
|
|
const [lastDeletedListItem, setLastDeletedListItem] = useState(null);
|
|
const [isHydrated, setIsHydrated] = useState(false);
|
|
const [storageError, setStorageError] = useState('');
|
|
const [isClearingProductData, setIsClearingProductData] = useState(false);
|
|
|
|
useEffect(() => {
|
|
let isMounted = true;
|
|
|
|
async function hydrate() {
|
|
try {
|
|
const [storedPreferences, storedShoppingList, storedProductCache, storedRecentProducts, storedDailyLog] = await Promise.all([
|
|
storageService.loadPreferences(defaultPreferences),
|
|
storageService.loadShoppingList(initialShoppingList),
|
|
storageService.loadProductCache(),
|
|
storageService.loadRecentProducts(),
|
|
storageService.loadDailyLog()
|
|
]);
|
|
|
|
await storageService.clearDeprecatedPrices().catch(() => {});
|
|
|
|
if (isMounted) {
|
|
setPreferences({ ...defaultPreferences, ...stripLegacyPriceFields(storedPreferences) });
|
|
setShoppingList({ ...initialShoppingList, ...stripLegacyPriceFields(storedShoppingList), items: (storedShoppingList?.items || []).map(stripLegacyPriceFields) });
|
|
setProductCache(Object.fromEntries(Object.entries(storedProductCache || {}).map(([key, value]) => [key, stripLegacyPriceFields(value)])));
|
|
setRecentProducts(Array.isArray(storedRecentProducts) ? storedRecentProducts.map(stripLegacyPriceFields) : []);
|
|
setDailyLog(Array.isArray(storedDailyLog) ? storedDailyLog : []);
|
|
setIsHydrated(true);
|
|
}
|
|
} catch (error) {
|
|
if (isMounted) setStorageError('Deine lokalen Daten konnten nicht geladen werden.');
|
|
}
|
|
}
|
|
|
|
hydrate();
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, []);
|
|
|
|
function retryHydration() {
|
|
setStorageError('');
|
|
setIsHydrated(false);
|
|
// Reloading the app is not necessary for the normal path, but this keeps
|
|
// the retry action explicit if a storage adapter fails temporarily.
|
|
Promise.all([
|
|
storageService.loadPreferences(defaultPreferences),
|
|
storageService.loadShoppingList(initialShoppingList),
|
|
storageService.loadProductCache(),
|
|
storageService.loadRecentProducts(),
|
|
storageService.loadDailyLog()
|
|
]).then(async ([nextPreferences, nextList, nextCache, nextRecent, nextDailyLog]) => {
|
|
await storageService.clearDeprecatedPrices().catch(() => {});
|
|
setPreferences({ ...defaultPreferences, ...stripLegacyPriceFields(nextPreferences) });
|
|
setShoppingList({ ...initialShoppingList, ...stripLegacyPriceFields(nextList), items: (nextList?.items || []).map(stripLegacyPriceFields) });
|
|
setProductCache(Object.fromEntries(Object.entries(nextCache || {}).map(([key, value]) => [key, stripLegacyPriceFields(value)])));
|
|
setRecentProducts(Array.isArray(nextRecent) ? nextRecent.map(stripLegacyPriceFields) : []);
|
|
setDailyLog(Array.isArray(nextDailyLog) ? nextDailyLog : []);
|
|
setIsHydrated(true);
|
|
}).catch(() => setStorageError('Bitte starte Shoppinguin erneut, um die lokalen Daten zu laden.'));
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (isHydrated) storageService.savePreferences(preferences);
|
|
}, [isHydrated, preferences]);
|
|
|
|
useEffect(() => {
|
|
if (isHydrated) storageService.saveShoppingList(shoppingList);
|
|
}, [isHydrated, shoppingList]);
|
|
|
|
useEffect(() => {
|
|
if (isHydrated) storageService.saveProductCache(productCache);
|
|
}, [isHydrated, productCache]);
|
|
|
|
useEffect(() => {
|
|
if (isHydrated) storageService.saveRecentProducts(recentProducts);
|
|
}, [isHydrated, recentProducts]);
|
|
|
|
useEffect(() => {
|
|
if (isHydrated) storageService.saveDailyLog(dailyLog);
|
|
}, [isHydrated, dailyLog]);
|
|
|
|
const routeProduct = route.product;
|
|
|
|
useEffect(() => {
|
|
const subscription = BackHandler.addEventListener('hardwareBackPress', goBackFromRoute);
|
|
|
|
return () => subscription.remove();
|
|
}, [route]);
|
|
|
|
const tabScreen = useMemo(() => {
|
|
if (activeTab === 'scan') {
|
|
return (
|
|
<ScanScreen
|
|
onCreateLocalProduct={startLocalProduct}
|
|
onOpenProduct={openProduct}
|
|
onScanBarcode={scanProductByBarcode}
|
|
preferences={preferences}
|
|
productCache={productCache}
|
|
shoppingList={shoppingList}
|
|
dailyLog={dailyLog}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (activeTab === 'list') {
|
|
return (
|
|
<ShoppingListScreen
|
|
onCompleteList={completeShoppingList}
|
|
onDeleteItem={deleteListItem}
|
|
onUndoDelete={undoDeleteListItem}
|
|
onStartScan={() => setActiveTab('scan')}
|
|
onToggleItem={toggleListItem}
|
|
onChangeItemQuantity={changeListItemQuantity}
|
|
lastDeletedItem={lastDeletedListItem}
|
|
shoppingList={shoppingList}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (activeTab === 'profile') {
|
|
return (
|
|
<ProfileScreen
|
|
isClearingProductData={isClearingProductData}
|
|
onChangePreferences={setPreferences}
|
|
onClearProductData={clearProductHistoryAndCache}
|
|
onOpenPrivacy={() => setRoute({ name: 'privacy' })}
|
|
preferences={preferences}
|
|
/>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<HomeScreen
|
|
onOpenProduct={openProduct}
|
|
onOpenList={() => setActiveTab('list')}
|
|
onStartScan={() => setActiveTab('scan')}
|
|
preferences={preferences}
|
|
dailyLog={dailyLog}
|
|
onDeleteConsumption={deleteConsumption}
|
|
onUpdateConsumption={updateConsumption}
|
|
onOpenInsights={() => setRoute({ name: 'nutritionInsights' })}
|
|
recentProducts={recentProducts}
|
|
shoppingList={shoppingList}
|
|
/>
|
|
);
|
|
}, [activeTab, dailyLog, isClearingProductData, lastDeletedListItem, preferences, productCache, recentProducts, shoppingList]);
|
|
|
|
function recordConsumption(product, grams, date) {
|
|
const entry = createConsumptionEntry(product, grams, { date });
|
|
if (!entry) return false;
|
|
setDailyLog((current) => appendConsumptionEntry(current, entry));
|
|
return true;
|
|
}
|
|
|
|
function updateConsumption(entryId, grams) {
|
|
setDailyLog((current) => editConsumptionEntry(current, entryId, grams));
|
|
}
|
|
|
|
function deleteConsumption(entryId) {
|
|
setDailyLog((current) => removeConsumptionEntry(current, entryId));
|
|
}
|
|
|
|
async function clearProductHistoryAndCache() {
|
|
if (isClearingProductData) return;
|
|
setIsClearingProductData(true);
|
|
try {
|
|
await storageService.clearProductHistoryAndCache();
|
|
setProductCache({});
|
|
setRecentProducts([]);
|
|
return true;
|
|
} catch (error) {
|
|
return false;
|
|
} finally {
|
|
setIsClearingProductData(false);
|
|
}
|
|
}
|
|
|
|
async function scanProductByBarcode(barcode) {
|
|
const result = await lookupProductByBarcode(
|
|
barcode,
|
|
productCache,
|
|
preferences.offlineModeEnabled
|
|
);
|
|
|
|
if (result.status === 'found') {
|
|
openProduct(result.product);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
function openProduct(product) {
|
|
const enrichedProduct = enrichEnvironmentalProduct(product);
|
|
const needsSchemaRefresh = enrichedProduct.dataSource !== 'local'
|
|
&& /^\d{8,14}$/.test(enrichedProduct.barcode || '')
|
|
&& enrichedProduct.nutritionSchemaVersion !== NUTRITION_SCHEMA_VERSION;
|
|
const displayProduct = needsSchemaRefresh ? { ...enrichedProduct, cacheStale: true } : enrichedProduct;
|
|
addProductToCache(displayProduct);
|
|
addRecentProduct(displayProduct);
|
|
setRoute({ name: 'productDetail', product: displayProduct });
|
|
if (needsSchemaRefresh && !preferences.offlineModeEnabled) {
|
|
lookupProductByBarcode(displayProduct.barcode, { [displayProduct.barcode]: displayProduct })
|
|
.then((result) => {
|
|
if (result.status !== 'found') return;
|
|
const refreshed = enrichEnvironmentalProduct(result.product);
|
|
setProductCache((current) => ({ ...current, [refreshed.barcode]: refreshed }));
|
|
setRecentProducts((current) => current.map((item) => item.barcode === refreshed.barcode
|
|
? { ...item, ...refreshed } : item));
|
|
setRoute((current) => current.name === 'productDetail' && current.product === displayProduct
|
|
? { ...current, product: refreshed } : current);
|
|
});
|
|
}
|
|
}
|
|
|
|
function startLocalProduct(barcode) {
|
|
setRoute({ name: 'productEdit', product: createLocalProduct(barcode), isNew: true });
|
|
}
|
|
|
|
function editProduct(product) {
|
|
setRoute({ name: 'productEdit', product, isNew: false });
|
|
}
|
|
|
|
function saveProductEdits(changes) {
|
|
const updated = saveManualProduct(route.product, changes);
|
|
setProductCache((current) => ({ ...current, [updated.barcode]: updated }));
|
|
setRecentProducts((current) => current.map((item) =>
|
|
item.barcode === updated.barcode ? { ...item, ...updated } : item
|
|
));
|
|
setShoppingList((current) => ({
|
|
...current,
|
|
items: current.items.map((item) => item.barcode === updated.barcode
|
|
? { ...item, productName: updated.name, nutrition: updated.nutrition } : item)
|
|
}));
|
|
setRoute({ name: 'productDetail', product: updated });
|
|
}
|
|
|
|
function showAlternatives(product) {
|
|
setRoute({ name: 'alternatives', product });
|
|
}
|
|
|
|
function showRatingCriteria(product, category) {
|
|
setRoute({ name: 'ratingCriteria', product, category });
|
|
}
|
|
|
|
function addProductToCache(product) {
|
|
setProductCache((current) => ({
|
|
...current,
|
|
[product.barcode]: product
|
|
}));
|
|
}
|
|
|
|
function addRecentProduct(product) {
|
|
setRecentProducts((current) => {
|
|
const withoutDuplicate = current.filter((item) => item.id !== product.id);
|
|
const previous = current.find((item) => item.id === product.id);
|
|
const scanCount = (previous?.scanCount || 0) + 1;
|
|
return [{ ...product, scanCount, lastScannedAt: new Date().toISOString() }, ...withoutDuplicate].slice(0, 8);
|
|
});
|
|
}
|
|
|
|
function addProductToShoppingList(product) {
|
|
setShoppingList((current) => {
|
|
const existingItem = current.items.find((item) => item.productId === product.id);
|
|
const items = existingItem
|
|
? current.items.map((item) =>
|
|
item.productId === product.id
|
|
? {
|
|
...item,
|
|
quantity: item.quantity + 1,
|
|
checked: false,
|
|
packageQuantityGrams: item.packageQuantityGrams ?? product.packageQuantityGrams,
|
|
packageQuantityLabel: item.packageQuantityLabel ?? product.packageQuantityLabel,
|
|
servingQuantityGrams: item.servingQuantityGrams ?? product.servingQuantityGrams,
|
|
nutrition: item.nutrition ?? product.nutrition
|
|
}
|
|
: item
|
|
)
|
|
: [
|
|
...current.items,
|
|
{
|
|
id: `item-${Date.now()}`,
|
|
productId: product.id,
|
|
productName: product.name,
|
|
quantity: 1,
|
|
barcode: product.barcode,
|
|
packageQuantityGrams: product.packageQuantityGrams,
|
|
packageQuantityLabel: product.packageQuantityLabel,
|
|
servingQuantityGrams: product.servingQuantityGrams,
|
|
nutrition: product.nutrition,
|
|
checked: false,
|
|
addedAt: new Date().toISOString()
|
|
}
|
|
];
|
|
|
|
return {
|
|
...current,
|
|
items
|
|
};
|
|
});
|
|
}
|
|
|
|
function toggleListItem(itemId) {
|
|
setShoppingList((current) => ({
|
|
...current,
|
|
items: current.items.map((item) =>
|
|
item.id === itemId ? { ...item, checked: !item.checked } : item
|
|
)
|
|
}));
|
|
}
|
|
|
|
function changeListItemQuantity(itemId, change) {
|
|
setShoppingList((current) => {
|
|
const items = current.items.map((item) =>
|
|
item.id === itemId
|
|
? { ...item, quantity: Math.max(1, (item.quantity || 1) + change) }
|
|
: item
|
|
);
|
|
return { ...current, items };
|
|
});
|
|
}
|
|
|
|
function deleteListItem(itemId) {
|
|
const index = shoppingList.items.findIndex((item) => item.id === itemId);
|
|
if (index < 0) return;
|
|
setLastDeletedListItem({ item: shoppingList.items[index], index });
|
|
setShoppingList((current) => {
|
|
const items = current.items.filter((item) => item.id !== itemId);
|
|
return {
|
|
...current,
|
|
items
|
|
};
|
|
});
|
|
}
|
|
|
|
function undoDeleteListItem() {
|
|
if (!lastDeletedListItem) return;
|
|
setShoppingList((current) => {
|
|
if (current.items.some((item) => item.id === lastDeletedListItem.item.id)) return current;
|
|
const items = [...current.items];
|
|
items.splice(Math.min(lastDeletedListItem.index, items.length), 0, lastDeletedListItem.item);
|
|
return { ...current, items };
|
|
});
|
|
setLastDeletedListItem(null);
|
|
}
|
|
|
|
function completeShoppingList() {
|
|
setLastDeletedListItem(null);
|
|
setShoppingList({
|
|
...initialShoppingList,
|
|
createdAt: new Date().toISOString()
|
|
});
|
|
}
|
|
|
|
function goBackToTabs() {
|
|
setRoute({ name: 'tabs' });
|
|
}
|
|
|
|
function goBackFromRoute() {
|
|
if (route.name === 'productEdit' && routeProduct) {
|
|
setRoute(route.isNew ? { name: 'tabs' } : { name: 'productDetail', product: routeProduct });
|
|
return true;
|
|
}
|
|
if (route.name === 'privacy') {
|
|
setRoute({ name: 'tabs' });
|
|
return true;
|
|
}
|
|
|
|
if (route.name === 'nutritionInsights') {
|
|
setRoute({ name: 'tabs' });
|
|
return true;
|
|
}
|
|
|
|
if (route.name === 'ratingCriteria' && routeProduct) {
|
|
setRoute({ name: 'productDetail', product: routeProduct });
|
|
return true;
|
|
}
|
|
|
|
if (route.name === 'alternatives' && routeProduct) {
|
|
setRoute({ name: 'productDetail', product: routeProduct });
|
|
return true;
|
|
}
|
|
|
|
if (route.name === 'productDetail' && routeProduct) {
|
|
setRoute({ name: 'tabs' });
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
function renderRoute() {
|
|
if (!isHydrated) {
|
|
return (
|
|
<View style={styles.loading}>
|
|
<Text style={styles.loadingText}>{storageError || 'Shoppinguin wird geladen...'}</Text>
|
|
{storageError ? <Text onPress={retryHydration} style={styles.retryText}>Erneut versuchen</Text> : null}
|
|
</View>
|
|
);
|
|
}
|
|
|
|
if (!preferences.onboardingComplete) {
|
|
return <OnboardingScreen preferences={preferences} onSave={setPreferences} />;
|
|
}
|
|
|
|
if (route.name === 'privacy') {
|
|
return <PrivacyScreen onBack={goBackToTabs} />;
|
|
}
|
|
|
|
if (route.name === 'nutritionInsights') {
|
|
return (
|
|
<NutritionInsightsScreen
|
|
dailyLog={dailyLog}
|
|
onAddEntry={() => {
|
|
setActiveTab('scan');
|
|
setRoute({ name: 'tabs' });
|
|
}}
|
|
onBack={goBackToTabs}
|
|
preferences={preferences}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (route.name === 'productEdit' && routeProduct) {
|
|
return <ProductEditScreen key={routeProduct.id} product={routeProduct} isNew={route.isNew}
|
|
onBack={goBackFromRoute} onSave={saveProductEdits} />;
|
|
}
|
|
|
|
if (route.name === 'productDetail' && routeProduct) {
|
|
return (
|
|
<ProductDetailScreen
|
|
key={routeProduct.id}
|
|
onAddToList={addProductToShoppingList}
|
|
onEditProduct={editProduct}
|
|
onBack={goBackToTabs}
|
|
onOpenList={() => {
|
|
setActiveTab('list');
|
|
goBackToTabs();
|
|
}}
|
|
onShowRatingCriteria={showRatingCriteria}
|
|
onShowAlternatives={showAlternatives}
|
|
onOpenProduct={openProduct}
|
|
preferences={preferences}
|
|
dailyLog={dailyLog}
|
|
onRecordConsumption={recordConsumption}
|
|
product={routeProduct}
|
|
productCache={productCache}
|
|
shoppingList={shoppingList}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (route.name === 'ratingCriteria' && routeProduct) {
|
|
return (
|
|
<RatingCriteriaDetailScreen
|
|
category={route.category}
|
|
onBack={goBackFromRoute}
|
|
preferences={preferences}
|
|
dailyLog={dailyLog}
|
|
product={routeProduct}
|
|
shoppingList={shoppingList}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (route.name === 'alternatives' && routeProduct) {
|
|
return (
|
|
<AlternativesScreen
|
|
dailyLog={dailyLog}
|
|
onBack={goBackFromRoute}
|
|
onChoose={(product) => {
|
|
addProductToShoppingList(product);
|
|
setActiveTab('list');
|
|
setRoute({ name: 'tabs' });
|
|
}}
|
|
onOpenProduct={openProduct}
|
|
preferences={preferences}
|
|
product={routeProduct}
|
|
productCache={productCache}
|
|
shoppingList={shoppingList}
|
|
/>
|
|
);
|
|
}
|
|
|
|
return tabScreen;
|
|
}
|
|
|
|
return (
|
|
<SafeAreaView style={styles.container}>
|
|
<StatusBar style="dark" />
|
|
{renderRoute()}
|
|
{route.name === 'tabs' && isHydrated && preferences.onboardingComplete ? (
|
|
<BottomTabBar activeTab={activeTab} onChange={setActiveTab} />
|
|
) : null}
|
|
</SafeAreaView>
|
|
);
|
|
}
|
|
|
|
function stripLegacyPriceFields(value) {
|
|
const { price, estimatedPrice, estimatedTotal, currency, maxBudgetPerShoppingTrip, budgetPeriod, ...rest } = value || {};
|
|
return rest;
|
|
}
|
|
|
|
const styles = StyleSheet.create({
|
|
container: {
|
|
backgroundColor: colors.background,
|
|
flex: 1
|
|
},
|
|
loading: {
|
|
alignItems: 'center',
|
|
flex: 1,
|
|
justifyContent: 'center',
|
|
padding: 24
|
|
},
|
|
loadingText: {
|
|
color: colors.muted,
|
|
fontSize: 16,
|
|
fontWeight: '700'
|
|
},
|
|
retryText: {
|
|
color: colors.primary,
|
|
fontSize: 15,
|
|
fontWeight: '800',
|
|
marginTop: 16
|
|
}
|
|
});
|