This commit is contained in:
@@ -5,6 +5,7 @@ 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 OnboardingScreen from './src/screens/OnboardingScreen';
|
||||
import ProductDetailScreen from './src/screens/ProductDetailScreen';
|
||||
import ProductEditScreen from './src/screens/ProductEditScreen';
|
||||
import ProfileScreen from './src/screens/ProfileScreen';
|
||||
@@ -12,18 +13,17 @@ 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 } from './src/services/productApi';
|
||||
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 { nutritionForServing, servingGrams, todayKey } from './src/services/dailyNutritionService';
|
||||
import { colors, defaultPreferences } from './src/utils/constants';
|
||||
|
||||
const initialShoppingList = {
|
||||
id: 'active-list',
|
||||
title: 'Aktueller Einkauf',
|
||||
items: [],
|
||||
estimatedTotal: 0,
|
||||
currency: 'CHF',
|
||||
status: 'active',
|
||||
createdAt: new Date().toISOString()
|
||||
};
|
||||
@@ -34,8 +34,8 @@ export default function App() {
|
||||
const [preferences, setPreferences] = useState(defaultPreferences);
|
||||
const [shoppingList, setShoppingList] = useState(initialShoppingList);
|
||||
const [productCache, setProductCache] = useState({});
|
||||
const [manualPrices, setManualPrices] = useState({});
|
||||
const [recentProducts, setRecentProducts] = useState([]);
|
||||
const [dailyLog, setDailyLog] = useState([]);
|
||||
const [lastDeletedListItem, setLastDeletedListItem] = useState(null);
|
||||
const [isHydrated, setIsHydrated] = useState(false);
|
||||
const [storageError, setStorageError] = useState('');
|
||||
@@ -46,20 +46,22 @@ export default function App() {
|
||||
|
||||
async function hydrate() {
|
||||
try {
|
||||
const [storedPreferences, storedShoppingList, storedProductCache, storedManualPrices, storedRecentProducts] = await Promise.all([
|
||||
const [storedPreferences, storedShoppingList, storedProductCache, storedRecentProducts, storedDailyLog] = await Promise.all([
|
||||
storageService.loadPreferences(defaultPreferences),
|
||||
storageService.loadShoppingList(initialShoppingList),
|
||||
storageService.loadProductCache(),
|
||||
storageService.loadManualPrices(),
|
||||
storageService.loadRecentProducts()
|
||||
storageService.loadRecentProducts(),
|
||||
storageService.loadDailyLog()
|
||||
]);
|
||||
|
||||
await storageService.clearDeprecatedPrices().catch(() => {});
|
||||
|
||||
if (isMounted) {
|
||||
setPreferences({ ...defaultPreferences, ...storedPreferences });
|
||||
setShoppingList({ ...initialShoppingList, ...storedShoppingList, items: storedShoppingList?.items || [] });
|
||||
setProductCache(storedProductCache || {});
|
||||
setManualPrices(storedManualPrices || {});
|
||||
setRecentProducts(Array.isArray(storedRecentProducts) ? storedRecentProducts : []);
|
||||
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) {
|
||||
@@ -82,14 +84,15 @@ export default function App() {
|
||||
storageService.loadPreferences(defaultPreferences),
|
||||
storageService.loadShoppingList(initialShoppingList),
|
||||
storageService.loadProductCache(),
|
||||
storageService.loadManualPrices(),
|
||||
storageService.loadRecentProducts()
|
||||
]).then(([nextPreferences, nextList, nextCache, nextPrices, nextRecent]) => {
|
||||
setPreferences({ ...defaultPreferences, ...nextPreferences });
|
||||
setShoppingList({ ...initialShoppingList, ...nextList, items: nextList?.items || [] });
|
||||
setProductCache(nextCache || {});
|
||||
setManualPrices(nextPrices || {});
|
||||
setRecentProducts(Array.isArray(nextRecent) ? nextRecent : []);
|
||||
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.'));
|
||||
}
|
||||
@@ -106,14 +109,14 @@ export default function App() {
|
||||
if (isHydrated) storageService.saveProductCache(productCache);
|
||||
}, [isHydrated, productCache]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isHydrated) storageService.saveManualPrices(manualPrices);
|
||||
}, [isHydrated, manualPrices]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isHydrated) storageService.saveRecentProducts(recentProducts);
|
||||
}, [isHydrated, recentProducts]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isHydrated) storageService.saveDailyLog(dailyLog);
|
||||
}, [isHydrated, dailyLog]);
|
||||
|
||||
const routeProduct = route.product;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -132,6 +135,7 @@ export default function App() {
|
||||
preferences={preferences}
|
||||
productCache={productCache}
|
||||
shoppingList={shoppingList}
|
||||
dailyLog={dailyLog}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -143,11 +147,8 @@ export default function App() {
|
||||
onDeleteItem={deleteListItem}
|
||||
onUndoDelete={undoDeleteListItem}
|
||||
onStartScan={() => setActiveTab('scan')}
|
||||
onOpenProfile={() => setActiveTab('profile')}
|
||||
onToggleItem={toggleListItem}
|
||||
onChangeItemQuantity={changeListItemQuantity}
|
||||
onUpdateItemPrice={updateListItemPrice}
|
||||
preferences={preferences}
|
||||
lastDeletedItem={lastDeletedListItem}
|
||||
shoppingList={shoppingList}
|
||||
/>
|
||||
@@ -172,11 +173,22 @@ export default function App() {
|
||||
onOpenList={() => setActiveTab('list')}
|
||||
onStartScan={() => setActiveTab('scan')}
|
||||
preferences={preferences}
|
||||
dailyLog={dailyLog}
|
||||
onUndoConsumption={() => setDailyLog((current) => current.slice(0, -1))}
|
||||
recentProducts={recentProducts}
|
||||
shoppingList={shoppingList}
|
||||
/>
|
||||
);
|
||||
}, [activeTab, isClearingProductData, lastDeletedListItem, manualPrices, preferences, productCache, recentProducts, shoppingList]);
|
||||
}, [activeTab, dailyLog, isClearingProductData, lastDeletedListItem, preferences, productCache, recentProducts, shoppingList]);
|
||||
|
||||
function recordConsumption(product) {
|
||||
const grams = servingGrams(product);
|
||||
const nutrients = nutritionForServing(product, grams);
|
||||
setDailyLog((current) => [...current.filter((entry) => entry.date === todayKey()), {
|
||||
id: `${Date.now()}-${Math.random()}`, date: todayKey(), productName: product.name,
|
||||
grams, ...nutrients
|
||||
}]);
|
||||
}
|
||||
|
||||
async function clearProductHistoryAndCache() {
|
||||
if (isClearingProductData) return;
|
||||
@@ -201,18 +213,33 @@ export default function App() {
|
||||
);
|
||||
|
||||
if (result.status === 'found') {
|
||||
const pricedProduct = applyManualPrice(result.product);
|
||||
openProduct(pricedProduct);
|
||||
openProduct(result.product);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function openProduct(product) {
|
||||
const pricedProduct = applyManualPrice(enrichEnvironmentalProduct(product));
|
||||
addProductToCache(pricedProduct);
|
||||
addRecentProduct(pricedProduct);
|
||||
setRoute({ name: 'productDetail', product: pricedProduct });
|
||||
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) {
|
||||
@@ -261,53 +288,6 @@ export default function App() {
|
||||
});
|
||||
}
|
||||
|
||||
function applyManualPrice(product) {
|
||||
const manualPrice = manualPrices[priceKey(product)];
|
||||
|
||||
if (typeof manualPrice !== 'number') {
|
||||
return product;
|
||||
}
|
||||
|
||||
return {
|
||||
...product,
|
||||
currency: product.currency || preferences.currency,
|
||||
price: manualPrice
|
||||
};
|
||||
}
|
||||
|
||||
function saveManualPriceForProduct(product, price) {
|
||||
const key = priceKey(product);
|
||||
|
||||
setManualPrices((current) => ({
|
||||
...current,
|
||||
[key]: price
|
||||
}));
|
||||
setProductCache((current) => {
|
||||
const cachedProduct = current[product.barcode];
|
||||
|
||||
if (!cachedProduct) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return {
|
||||
...current,
|
||||
[product.barcode]: {
|
||||
...cachedProduct,
|
||||
currency: product.currency || preferences.currency,
|
||||
price,
|
||||
updatedAt: new Date().toISOString()
|
||||
}
|
||||
};
|
||||
});
|
||||
setRecentProducts((current) =>
|
||||
current.map((item) =>
|
||||
item.id === product.id
|
||||
? { ...item, currency: product.currency || preferences.currency, price }
|
||||
: item
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function addProductToShoppingList(product) {
|
||||
setShoppingList((current) => {
|
||||
const existingItem = current.items.find((item) => item.productId === product.id);
|
||||
@@ -332,8 +312,6 @@ export default function App() {
|
||||
productId: product.id,
|
||||
productName: product.name,
|
||||
quantity: 1,
|
||||
estimatedPrice: product.price,
|
||||
currency: product.currency || current.currency,
|
||||
barcode: product.barcode,
|
||||
packageQuantityGrams: product.packageQuantityGrams,
|
||||
packageQuantityLabel: product.packageQuantityLabel,
|
||||
@@ -346,32 +324,6 @@ export default function App() {
|
||||
|
||||
return {
|
||||
...current,
|
||||
currency: product.currency || current.currency,
|
||||
estimatedTotal: calculateEstimatedTotal(items),
|
||||
items
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function updateListItemPrice(itemId, price) {
|
||||
const itemToUpdate = shoppingList.items.find((item) => item.id === itemId);
|
||||
|
||||
if (itemToUpdate) {
|
||||
saveManualPriceForProduct({
|
||||
id: itemToUpdate.productId,
|
||||
barcode: itemToUpdate.barcode,
|
||||
currency: itemToUpdate.currency || shoppingList.currency
|
||||
}, price);
|
||||
}
|
||||
|
||||
setShoppingList((current) => {
|
||||
const items = current.items.map((item) =>
|
||||
item.id === itemId ? { ...item, estimatedPrice: price } : item
|
||||
);
|
||||
|
||||
return {
|
||||
...current,
|
||||
estimatedTotal: calculateEstimatedTotal(items),
|
||||
items
|
||||
};
|
||||
});
|
||||
@@ -393,7 +345,7 @@ export default function App() {
|
||||
? { ...item, quantity: Math.max(1, (item.quantity || 1) + change) }
|
||||
: item
|
||||
);
|
||||
return { ...current, items, estimatedTotal: calculateEstimatedTotal(items) };
|
||||
return { ...current, items };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -405,7 +357,6 @@ export default function App() {
|
||||
const items = current.items.filter((item) => item.id !== itemId);
|
||||
return {
|
||||
...current,
|
||||
estimatedTotal: calculateEstimatedTotal(items),
|
||||
items
|
||||
};
|
||||
});
|
||||
@@ -417,7 +368,7 @@ export default function App() {
|
||||
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, estimatedTotal: calculateEstimatedTotal(items) };
|
||||
return { ...current, items };
|
||||
});
|
||||
setLastDeletedListItem(null);
|
||||
}
|
||||
@@ -472,6 +423,10 @@ export default function App() {
|
||||
);
|
||||
}
|
||||
|
||||
if (!preferences.onboardingComplete) {
|
||||
return <OnboardingScreen preferences={preferences} onSave={setPreferences} />;
|
||||
}
|
||||
|
||||
if (route.name === 'privacy') {
|
||||
return <PrivacyScreen onBack={goBackToTabs} />;
|
||||
}
|
||||
@@ -491,11 +446,14 @@ export default function App() {
|
||||
setActiveTab('list');
|
||||
goBackToTabs();
|
||||
}}
|
||||
onSaveManualPrice={saveManualPriceForProduct}
|
||||
onShowRatingCriteria={showRatingCriteria}
|
||||
onShowAlternatives={showAlternatives}
|
||||
onOpenProduct={openProduct}
|
||||
preferences={preferences}
|
||||
dailyLog={dailyLog}
|
||||
onRecordConsumption={recordConsumption}
|
||||
product={routeProduct}
|
||||
productCache={productCache}
|
||||
shoppingList={shoppingList}
|
||||
/>
|
||||
);
|
||||
@@ -507,6 +465,7 @@ export default function App() {
|
||||
category={route.category}
|
||||
onBack={goBackFromRoute}
|
||||
preferences={preferences}
|
||||
dailyLog={dailyLog}
|
||||
product={routeProduct}
|
||||
shoppingList={shoppingList}
|
||||
/>
|
||||
@@ -516,6 +475,7 @@ export default function App() {
|
||||
if (route.name === 'alternatives' && routeProduct) {
|
||||
return (
|
||||
<AlternativesScreen
|
||||
dailyLog={dailyLog}
|
||||
onBack={goBackFromRoute}
|
||||
onChoose={(product) => {
|
||||
addProductToShoppingList(product);
|
||||
@@ -538,22 +498,16 @@ export default function App() {
|
||||
<SafeAreaView style={styles.container}>
|
||||
<StatusBar style="dark" />
|
||||
{renderRoute()}
|
||||
{route.name === 'tabs' && isHydrated ? (
|
||||
{route.name === 'tabs' && isHydrated && preferences.onboardingComplete ? (
|
||||
<BottomTabBar activeTab={activeTab} onChange={setActiveTab} />
|
||||
) : null}
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
function calculateEstimatedTotal(items) {
|
||||
return items.reduce((sum, item) => {
|
||||
const price = typeof item.estimatedPrice === 'number' ? item.estimatedPrice : 0;
|
||||
return sum + price * item.quantity;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function priceKey(product) {
|
||||
return product.barcode || product.id;
|
||||
function stripLegacyPriceFields(value) {
|
||||
const { price, estimatedPrice, estimatedTotal, currency, maxBudgetPerShoppingTrip, budgetPeriod, ...rest } = value || {};
|
||||
return rest;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
|
||||
Reference in New Issue
Block a user