diff --git a/App.js b/App.js index 6f09a18..6cd006b 100644 --- a/App.js +++ b/App.js @@ -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 ; + } + if (route.name === 'privacy') { return ; } @@ -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 ( { addProductToShoppingList(product); @@ -538,22 +498,16 @@ export default function App() { {renderRoute()} - {route.name === 'tabs' && isHydrated ? ( + {route.name === 'tabs' && isHydrated && preferences.onboardingComplete ? ( ) : null} ); } -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({ diff --git a/README.md b/README.md index 6501389..77014dc 100644 --- a/README.md +++ b/README.md @@ -1,173 +1,40 @@ # Shoppinguin -Smart Shopping Companion +Shoppinguin helps adults understand supermarket products in the context of their nutrition and exercise goals. Scan a barcode or search Open Food Facts, then see a product rating, the reasons behind it, and how a serving relates to today's recorded protein and sugar. -## App-Idee +## How it works -Shoppinguin ist eine mobile Einkaufshilfe für den Supermarkt. Nutzerinnen und Nutzer scannen Produkte per Smartphone-Kamera oder Barcode, erhalten direkt eine persönliche Einschätzung und treffen dadurch bessere Kaufentscheidungen. +On first launch, users enter age, height, weight, and an exercise goal. The profile stays in local app storage. The profile screen lets them edit these values, set a personal **total sugar** planning value, manage allergens and dietary preferences, and enable offline mode. -Die Bewertung berücksichtigt Zutaten, Preis, Nachhaltigkeitsmerkmale und individuelle Ziele wie Allergien, Ernährung, Budget und Nachhaltigkeit. +Product ratings now use nutrition (45%), goal fit (20%), ingredients (15%), and allergies (20% when applicable). Only categories with known facts contribute to the numeric score. Missing information limits confidence. Confirmed avoided allergens still block a recommendation. Additives remain an ingredients signal; environmental impact is still displayed in product details but no longer affects the score. The shopping list remains available for planning and checking off products; price entry, totals and budget controls are no longer part of the app. -## Zielgruppe +The product screen shows protein and total sugar per serving. Users can mark a portion as eaten; the local daily log then updates the Home screen and subsequent recommendations. A scan or a shopping-list addition **does not** count as consumption. The app uses the stated serving size, then package size, then 100 g when no amount is available. The last fallback is approximate. Daily totals cover only portions logged in the app. A product with missing nutrition values cannot fill those gaps. -Die App richtet sich an Privatpersonen, die im Supermarkt schnell bessere Kaufentscheidungen treffen möchten. Besonders relevant ist Shoppinguin für Menschen mit Allergien oder Unverträglichkeiten, ernährungsbewusste Käuferinnen und Käufer, Studierende und Familien mit Budgetfokus sowie Konsumentinnen und Konsumenten mit Nachhaltigkeitsanspruch. +The daily view also tracks salt and fibre for all goals. The product goal detail shows both without scoring them again because the Nutri-Score already considers them. For endurance goals, carbohydrates per serving contribute to goal fit; no daily carbohydrate prescription is inferred without training duration and intensity. For vegan diets, available vitamin B12 values are shown against the adult EFSA reference of 4 µg/day. Missing vitamin data stays unknown; a missing field never means zero or a diagnosed deficiency. OFF vitamin B12 is converted from grams to micrograms. Manual product editing can add these values from a label. -## Wichtigste Funktionen +The profile groups daily values in a separate **Tageswerte** section. Protein is calculated from body weight and exercise goal: approximately 0.83 g/kg for general goals, 1.2 g/kg for endurance, and 1.6 g/kg for muscle growth. These are broad adult reference values, not a prescription. The default 50 g total sugar value is an editable planning value, **not** a clinical limit or a WHO free-sugars target; product data generally reports total sugars, including naturally occurring sugars. Setting it above 50 g shows a short warning explaining that WHO's less-than-50-g example applies to **free sugars** at 2,000 kcal and cannot be directly compared with the app's total-sugar data. Age and height do not change these two calculations. A reliable personal calorie estimate would require more information, so the app does not infer one from the available profile. Do not use the score to manage a medical condition. -- Produkte per Barcode-Scan erfassen -- Produktdaten direkt im Laden auswerten -- Persönliche Empfehlung anzeigen: kaufen, prüfen oder meiden -- Nutzerprofil mit Allergien, Ernährungszielen, Budget und Nachhaltigkeitspräferenzen -- Kurze Begründung zur Bewertung und mögliche Alternativhinweise -- Manuelle Produktsuche, falls der Barcode nicht erkannt wird -- Lokale Einkaufsliste mit Menge, Preis, Abhaken und Löschen -- Manuelle Preiseingabe, wenn Open Food Facts keinen Artikelpreis liefert -- Lokaler Produktcache und Offline-Modus für gespeicherte Produkte -- Produktdaten per Barcode aus der Open-Food-Facts-API -- Später geplant: erweiterte Profile, Budgettracking, Nachhaltigkeitsfilter und Rezeptvorschläge +Other useful features remain: manual product corrections, local product cache, offline scans of saved products, alternatives, shopping list, and environmental context. -## One-Pager +The product detail automatically previews up to two better alternatives of the same specific product type. Suggestions do not cross broad groups such as soda to water. A lower-sugar soda can qualify even if its Nutri-Score grade is unchanged, provided its overall rating is not materially worse. The search checks related category tags and additional result pages before giving up, then tries product-type or category search terms when needed. The full alternatives view remains available. In online mode the preview sends category tags and, when needed, product-type, category, or name search terms to Open Food Facts; offline it uses only saved products. -Der One-Pager aus Aufgabe 6.1 beschreibt das Go-to-Market-Konzept: - -- Projekt: Smart Shopping Companion - Mobile App mit React Native -- Kernidee: Produkte im Supermarkt per Smartphone scannen, direkt bewerten und bessere Kaufentscheidungen treffen -- Unique Value Proposition: Produktdaten werden direkt am Regal in eine klare persönliche Empfehlung übersetzt -- Preisstrategie: Freemium mit kostenlosen Basisfunktionen und optionalen Premium-Funktionen -- Distribution: Apple App Store, Google Play Store und zusätzliche Sichtbarkeit über QR-Codes, Hochschulen, Fitnessstudios, Nachhaltigkeits-Communities und lokale Supermärkte - -## Geplanter Tech-Stack - -- Expo -- React Native -- JavaScript -- Smartphone-Kamera und Barcode-Scanner -- Open Food Facts API für Barcode-Produktdaten -- Lokale Speicherung persönlicher Präferenzen -- GitHub oder GitLab für Versionsverwaltung und Abgabe - -## Ordnerstruktur - -```text -Shoppinguin/ -|-- assets/ -|-- src/ -| |-- assets/ -| |-- components/ -| | `-- PrimaryButton.js -| `-- screens/ -| `-- HomeScreen.js -|-- App.js -|-- app.json -|-- babel.config.js -|-- package.json -`-- README.md -``` - -## Beispiel-Screen - -Die App enthält jetzt einen MVP-Flow mit Bottom-Tabs: - -- Home: Startseite und letzte Scans -- Scan: Kamera-Scanner mit Open Food Facts, Beispiel-Barcodes und manuelle Suche -- Produktdetail: Ampelbewertung nach Allergien, Budget, Ernährung und Nachhaltigkeit -- Alternativen: Online-Suche nach gesünderen Produkten derselben Kategorie; offline nur gespeicherte Produkte -- Einkaufsliste: Produkte hinzufügen, abhaken, löschen und Gesamtsumme sehen -- Profil: Präferenzen, Allergien, Budget mit Zeitraum, Bio-Vorliebe und Offline-Modus verwalten - -Beispiel-Barcodes für Tests über Open Food Facts: - -```text -3017620422003 - Nutella -737628064502 - Open-Food-Facts-Beispielprodukt -``` - -Die App nutzt für Barcodes `https://world.openfoodfacts.org/api/v2/product/{barcode}.json`. Online werden gespeicherte Produktdaten nach 24 Stunden erneut von Open Food Facts geladen. Schlägt die Aktualisierung fehl oder ist der Offline-Modus aktiv, bleibt der lokale Cache nutzbar; veraltete Daten werden gekennzeichnet und die Empfehlung höchstens als „Prüfen“ angezeigt. Der Zeitpunkt des letzten erfolgreichen Abrufs wird angezeigt. Manuell erfasste Preise bleiben bei einer Aktualisierung erhalten. - -Unbekannte Barcodes können als lokale Produkte erfasst werden, auch im Offline-Modus. Im Produktdetail zeigt Shoppinguin fehlende Angaben und bietet ein Formular für Name, Marke, Produkttyp, Zutaten, Allergene, Spuren und Nährwerte. Getränkeangaben werden pro 100 ml eingegeben. Manuelle Korrekturen werden gekennzeichnet, lokal gespeichert und bei einer späteren Open-Food-Facts-Aktualisierung beibehalten; neue OFF-Felder ergänzen die übrigen Angaben. Wird ein Nährwert oder der Getränketyp korrigiert, wird eine zuvor gelieferte offizielle Nutri-Score-Note für dieses lokale Produkt nicht weiterverwendet. Der Produktlink öffnet Open Food Facts im Browser, wo Nutzende Angaben selbst beitragen können. Shoppinguin lädt keine manuell erfassten Werte oder Bilder hoch. - -Fehlt der Nutri-Score in Open Food Facts, berechnet die App die Note A–E aus den verfügbaren Nährwerten pro 100 g bzw. 100 ml nach dem [aktualisierten Nutri-Score-Algorithmus](https://www.santepubliquefrance.fr/sites/default/files/rdd/document/march2025CoU_EN.pdf). Die Berechnung berücksichtigt die Sonderregeln für Getränke sowie Fette, Nüsse und Samen. Wenn fehlende Angaben die Note verändern könnten, zeigt die App keine berechnete Note an und lässt die Ernährungswertung aus der Gesamtbewertung heraus. Eine berechnete Note wird in den Bewertungsdetails als solche gekennzeichnet. - -Die Gesamtwertung verwendet nur Kriterien mit belastbaren Angaben und berücksichtigt die im Profil gewählten Prioritäten für Ernährung und Nachhaltigkeit. Fehlende Preise, unklare Zutaten- oder Allergenangaben und unbekannte Nachhaltigkeitsdaten erzeugen keine Ersatzpunkte. Bei wenigen belegten Kriterien wird die Empfehlung auf „Prüfen“ begrenzt; sind alle unbekannt, erscheint „Daten fehlen“ statt einer Zahl. Angegebene vermiedene Allergene bleiben ein Ausschlussgrund. Mögliche Spuren und das Fehlen eines Allergens in der Open-Food-Facts-Liste gelten nicht als bestätigte Allergenfreiheit: Die App fordert zur Prüfung der Verpackung auf und gibt dafür keine Allergiepunkte. Ebenso geben leere Zusatzstoff-Tags ohne Zutatenliste keine positiven Punkte. Nährwerte, die bereits in den Nutri-Score eingehen, werden nicht nochmals abgezogen. - -Die Datenabdeckung zählt die tatsächlich belegten Eingaben innerhalb jedes Kriteriums. Eine einzelne Angabe füllt nicht mehr eine ganze Kategorie aus; AGRIBALYSE-Kategoriedurchschnitte zählen nur als teilweise CO₂-Abdeckung. Unter 50 % Abdeckung wird die Gesamtwertung auf 65, unter 80 % auf 77 Punkte begrenzt. Ein bestätigter Konflikt mit dem veganen oder vegetarischen Ziel begrenzt sie auf 47 Punkte. Fehlen für ein gewähltes Zucker- oder Proteinziel die nötigen Werte oder ist die Vegan-/Vegetarisch-Analyse unklar, bleibt die Empfehlung höchstens „Prüfen“. Dasselbe gilt bei einem gesetzten Budget, wenn Produkt- oder offene Listenpreise fehlen. Für die Budgetwertung zählt die Summe der offenen Einkaufsliste zuzüglich eines weiteren Exemplars des betrachteten Produkts; die Liste ist eine Momentaufnahme und kann einen Tag, eine Woche oder einen Monat nur annähernd abbilden. - -Das Produktdetail zeigt die gewichtete Datenabdeckung, die wichtigsten bewerteten Faktoren und mögliche Begrenzungen der Gesamtwertung. Offizielle Noten und ein von der App berechneter Nutri-Score werden getrennt gekennzeichnet. Ein fehlendes Herkunftsland wird nicht aus den Ländern ersetzt, in denen ein Produkt verkauft wird. Alternativen können entweder eine belegte Verbesserung der Ernährungswertung haben oder eine deutlich bessere Gesamtwertung bei mindestens gleicher Datenabdeckung und einer belegten Verbesserung in einem Kriterium. Bei einer reinen Ernährungsverbesserung weist die Begründung auf eine geringere Datenabdeckung anderer Kriterien hin; die Gesamtwertung muss dann nicht ebenfalls höher sein. Wenn bei beiden Produkten die Allergenprüfung die angezeigte Wertung deckelt, wird für den Gesamtvergleich die Wertung vor diesem Deckel verwendet. Bei einem bestätigten Allergenkonflikt des Ausgangsprodukts gilt die unten beschriebene Ausnahme. Die Punktschwellen sind App-Heuristiken und keine wissenschaftlich kalibrierten Unterschiede. - -Bei aktivem Online-Modus nutzt die Alternativsuche die [kategoriebasierte Open-Food-Facts-Suche](https://openfoodfacts.github.io/documentation/docs/Product-Opener/v2/search/get-search/) mit den konkreten Kategorietags des Produkts und einer passenden Oberkategorie. Sie lädt zunächst populäre Produkte mit Nutri-Score A oder B, danach bei Bedarf weitere Seiten, C-Produkte und zuletzt Produkte ohne Notenfilter. Die App bewertet alle Treffer mit dem Profil, verwirft andere Produktgruppen und bekannte vermiedene Allergene und zeigt bis zu acht unterschiedliche Produktvarianten. Bessere Ernährungswerte stehen in der Sortierung vorn. Sind keine brauchbaren Kategorietags vorhanden, dient die bisherige Textsuche als Fallback. Im Offline-Modus erfolgt kein Netzaufruf; die Suche bleibt auf gespeicherte Produkte begrenzt. - -Bei einem ausdrücklich angegebenen vermiedenen Allergen bleibt das Produkt ausgeschlossen und kann nicht zur Liste hinzugefügt werden. Bei Alternativen mit unbestätigter Allergenfreiheit zeigt die App einen deutlichen Prüfhinweis und öffnet zunächst das Produktdetail; sie fügt solche Kandidaten nicht direkt zur Liste hinzu. Im Produktdetail erfordert das Hinzufügen dann eine ausdrückliche Bestätigung der Verpackungsprüfung. Bestätigte Alternativen stehen zuerst. Open Food Facts liefert keine bestätigte Allergenfreiheit, daher ersetzt dieser Prüfpfad niemals die Kontrolle der Verpackung. Wenn das Ausgangsprodukt ein vermiedenes Allergen enthält, darf eine mögliche Alternative auch ohne bereits vergleichbaren Kriteriumsgewinn erscheinen; sie wird ausdrücklich nur als mögliche Alternative bezeichnet. - -Zusatzstoffgruppen sind vorsorgliche App-Hinweise mit unterschiedlich starker Evidenz. Sie senken die Zutatenwertung abgestuft, setzen aber keine harte Obergrenze mehr für die Gesamtwertung. Die Zuordnung und ihre Begründungen stehen in `src/services/ratingService.js`; neue Gruppen oder stärkere Abzüge erfordern eine Prüfung der Quellen, der Formulierungen und realer Produktbeispiele in den Tests. Weder die Punktwerte noch die Abstände zwischen ihnen sind medizinisch oder wissenschaftlich kalibriert. - -## Umweltinformationen - -Open Food Facts bleibt die Quelle für Barcode, Produktbeschreibung und den offiziellen Green-Score (auch unter den älteren `ecoscore_*`-Feldern). Eine auf dem Produkt angegebene CO₂-Bilanz aus `nutriments.carbon-footprint_100g` hat Vorrang. Der AGRIBALYSE-Wert im Green-Score-Datenblock ist dagegen ein **Lebensmittel-Kategoriewert**, keine Messung des Markenprodukts. Er wird nicht als produktspezifischer CO₂-Wert ausgegeben. - -Wenn ein produktspezifischer Wert fehlt, sucht die App in der mitgelieferten [AGRIBALYSE-3.2-Synthese von ADEME](https://data.ademe.fr/datasets/agribalyse-31-synthese) für verzehrfertige Lebensmittel. Die Priorität ist: von Open Food Facts zugeordneter AGRIBALYSE-Lebensmittelcode, geprüfte Zuordnung einzelner OFF-Kategorietags in `src/services/environmentalService.js`, danach nur ein Name mit **vollständig übereinstimmenden normalisierten Wörtern** innerhalb einer passenden Oberkategorie. Die Namensschwelle und der Mindestabstand zum zweitbesten Treffer stehen in `MATCHING_CONFIG`. Der Namensabgleichwert beschreibt nur die Übereinstimmung der Wörter, keine statistische Sicherheit. Widersprüche bei Produktart oder Verarbeitung und mehrdeutige Treffer werden verworfen. Die kleine geprüfte Zuordnungstabelle ist bewusst konservativ und kann nach Prüfung weiterer Kategorien erweitert werden; die Regelversion `ENVIRONMENTAL_RULES_VERSION` muss dabei erhöht werden. Ein fehlender Wert bleibt „Nicht verfügbar“. - -Die Anzeige nennt CO₂e in kg pro kg Lebensmittel sowie, nur bei eindeutigem Netto-Masseetikett in g oder kg, einen ungefähren Packungswert. Volumen und Abtropfgewicht werden nicht in Masse umgerechnet. Für AGRIBALYSE werden zusätzlich Landnutzung (Pt/kg), Wasserknappheit (m³ deprivation/kg) und der aggregierte EF-Indikator (mPt/kg) aufbewahrt und angezeigt. Die ADEME-Daten beziehen sich auf **1 kg verzehrbares Lebensmittel** und umfassen modellierte Schritte bis zum Verbraucher, einschließlich vereinfachter Verpackung und Transport; diese werden nicht nochmals addiert. Der Weg vom Geschäft nach Hause ist nicht enthalten. Ein AGRIBALYSE-Kategoriedurchschnitt kann als CO₂-Anhaltspunkt in die eigene Nachhaltigkeitswertung einfließen; er erzeugt **keinen offiziellen Green-Score**. Liegt ein offizieller Green-Score vor, verwendet die eigene Wertung diesen statt eines zweiten CO₂-Abzugs. - -Herkunftsland und Verpackung bleiben Kontextangaben und geben keine Nachhaltigkeitspunkte. Ohne Green-Score zählt nur ein verfügbarer CO₂-Wert sowie, wenn ausdrücklich bevorzugt und belegt, ein Bio-Label. Ein fehlendes Bio-Label gilt nicht als Beweis, dass ein Produkt nicht Bio ist. Die festen CO₂-Punktschwellen sind eine App-Heuristik und kein Vergleich innerhalb einer Lebensmittelkategorie. - -Die App lädt AGRIBALYSE bei Scans nicht aus dem Netz. `src/data/agribalyse.js` enthält einen lokalen, per Code indexierten Auszug aus 2.451 Einträgen der offiziellen öffentlichen Synthese. Für ein Update mit Netzwerkzugang: - -```bash -node scripts/importAgribalyse.mjs -node --test --test-isolation=none tests/environmentalService.test.mjs tests/ratingService.test.mjs tests/nutriScoreService.test.mjs -``` - -Das Importskript prüft Version, Spalten, CO₂-Einheit, Vollständigkeit und eindeutige Kennungen, bevor es die Snapshot-Datei ersetzt. Nach einer Aktualisierung sind die Zuordnungstabelle und reale Beispiele in den Tests zu prüfen; bei Änderungen der Daten oder Regelversion werden gespeicherte Produktzuordnungen beim nächsten Scan neu aufgelöst. Es ist weder ein API-Schlüssel noch eine weitere Datenbank nötig. Der ADEME-Endpunkt hat ein Limit von [10 Anfragen pro Sekunde und IP](https://www.data.gouv.fr/dataservices/api-impacts-environnementaux-agribalyse-r); das Importskript fragt sequentiell ab. Bestehende Scans funktionieren bei ADEME-Ausfall mit dem enthaltenen Snapshot weiter. - -**Datenhinweis und Lizenz:** Quelle ADEME, AGRIBALYSE v3.2, Datenstand 2025-02-27, [Licence Ouverte / Etalab](https://doc.agribalyse.fr/documentation-en/agribalyse-data/terms-of-use-and-environmental-communication). Open-Food-Facts-Produktdaten unterliegen den [OFF-Nutzungsbedingungen](https://openfoodfacts.github.io/documentation/docs/Product-Opener/api/). AGRIBALYSE repräsentiert Durchschnittsprodukte des französischen Marktes, nicht die tatsächliche Rezeptur oder Lieferkette einer Marke. Die Modellierung und geografische Übertragbarkeit können abweichen; ähnliche Lebensmittel können verschiedene Auswirkungen haben. CO₂e, Landnutzung, Wasserknappheit und EF-Gesamtwirkung sind verschiedene Indikatoren und dürfen nicht gleichgesetzt werden. - -## Runbook - -### Automatischer Android-Build mit Gitea Actions - -Der Workflow in `.gitea/workflows/android-release.yml` startet bei jedem Push -in ein Gitea-Repository. Er installiert die Abhängigkeiten mit `npm ci`, -erzeugt das nicht versionierte Android-Projekt per Expo und kompiliert mit -Gradle eine Release-APK. Die APK ist im jeweiligen Gitea-Actions-Lauf als -Artefakt `shoppinguin-android-release-` herunterladbar. - -Voraussetzungen: Gitea Actions ist für das Repository aktiviert und ein -Linux-Runner mit dem Label `ubuntu-latest` ist registriert. Der Runner benötigt -Netzwerkzugang für npm, Gradle und das Android SDK sowie ausreichend Speicher -für einen Android-Build. `origin` zeigt auf das Gitea-Repository; der Workflow -startet, sobald die Änderungen dorthin gepusht werden. - -Die APK wird derzeit im Release-Modus mit dem von Expo erzeugten Debug-Schlüssel -signiert. Sie eignet sich zum Testen, aber nicht als Store-Release. Für eine -Veröffentlichung muss ein eigener Release-Schlüssel sicher in Gitea hinterlegt -und die Android-Signierung entsprechend konfiguriert werden. - -Projekt installieren: +## Run ```bash npm install -``` - -Projekt starten: - -```bash npm start ``` -Alternativ direkt mit Expo: +Scan testing barcodes: `3017620422003` and `737628064502`. Online product data comes from [Open Food Facts Switzerland](https://ch.openfoodfacts.org/); the Swiss subdomain supplies the country context for searches. Environmental context uses a bundled [AGRIBALYSE](https://data.ademe.fr/datasets/agribalyse-31-synthese) extract. The app does not upload the personal profile or food log. Barcode and search requests are sent to Open Food Facts when online. -```bash -npx expo start -``` +Cached products created before carbohydrate mapping was added are refreshed on the next online scan, even if they were fetched within the usual 24-hour cache window. Opening one from recent products also refreshes its detail view. In offline mode the old entry remains available and is marked stale until it can be refreshed. -Danach kann die App mit Expo Go auf einem Smartphone oder in einem Emulator gestartet werden. +## Reference values -Für den Barcode-Scan muss die Kamera-Berechtigung erlaubt werden. Auf Web oder ohne Kamera kann der Scanner über die Beispiel-Barcodes und die manuelle Suche getestet werden. - -## Repository teilen - -Repository-Link für den Kursleiter: - -```text -https://git.bachmannj.ch/Fretux/Shoppy -``` +- [EFSA dietary reference values for protein](https://www.efsa.europa.eu/en/efsajournal/pub/2557) +- [NIH Office of Dietary Supplements: exercise and athletic performance](https://ods.od.nih.gov/factsheets/ExerciseAndAthleticPerformance-HealthProfessional/) +- [WHO healthy diet: free sugars](https://www.who.int/news-room/fact-sheets/detail/healthy-diet) +- [WHO healthy diet: salt](https://www.who.int/news-room/fact-sheets/detail/healthy-diet) +- [EFSA dietary reference values: fibre](https://www.efsa.europa.eu/sites/default/files/2017_09_DRVs_summary_report.pdf) +- [EFSA vitamin B12 reference intake](https://www.efsa.europa.eu/en/press/news/150709) +- [NIH ODS: vitamin B12 and vegan diets](https://ods.od.nih.gov/factsheets/Vitaminb12-HealthProfessional/) diff --git a/src/components/form/BudgetInput.js b/src/components/form/BudgetInput.js deleted file mode 100644 index 3f7f245..0000000 --- a/src/components/form/BudgetInput.js +++ /dev/null @@ -1,117 +0,0 @@ -import { useState } from 'react'; -import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; - -import { budgetPeriodLabels, colors } from '../../utils/constants'; - -const budgetPeriods = ['day', 'week', 'month', 'shoppingTrip']; - -export default function BudgetInput({ value, currency, period, onChangePeriod, onChangeValue }) { - const [inputValue, setInputValue] = useState(String(value ?? '')); - - function updateValue(text) { - setInputValue(text); - const parsedValue = Number(text.replace(',', '.')); - onChangeValue(text.trim() && Number.isFinite(parsedValue) && parsedValue > 0 ? parsedValue : undefined); - } - - return ( - - Betrag (optional) - Ohne Budget bleibt die Preisbewertung offen. - - {currency} - - - - {budgetPeriods.map((option) => { - const isActive = period === option; - return ( - onChangePeriod(option)} - style={[styles.periodChip, isActive ? styles.activePeriodChip : null]} - > - - pro {budgetPeriodLabels[option]} - - - ); - })} - - - ); -} - -const styles = StyleSheet.create({ - wrap: { - gap: 10 - }, - hint: { - color: colors.muted, - fontSize: 13, - lineHeight: 18 - }, - label: { - color: colors.text, - fontSize: 15, - fontWeight: '800' - }, - row: { - alignItems: 'center', - flexDirection: 'row', - gap: 10 - }, - currency: { - color: colors.muted, - fontSize: 16, - fontWeight: '800' - }, - input: { - borderColor: colors.border, - borderRadius: 12, - borderWidth: 1, - color: colors.text, - flex: 1, - fontSize: 16, - paddingHorizontal: 12, - paddingVertical: 10 - }, - periodGrid: { - flexDirection: 'row', - flexWrap: 'wrap', - gap: 8 - }, - periodChip: { - alignItems: 'center', - borderColor: colors.border, - borderRadius: 12, - borderWidth: 1, - flexGrow: 1, - minHeight: 44, - justifyContent: 'center', - paddingHorizontal: 10, - paddingVertical: 9 - }, - activePeriodChip: { - backgroundColor: colors.primary, - borderColor: colors.primary - }, - periodText: { - color: colors.text, - fontSize: 13, - fontWeight: '800' - }, - activePeriodText: { - color: colors.surface - } -}); diff --git a/src/components/list/ShoppingListItem.js b/src/components/list/ShoppingListItem.js index acfec97..1a2c642 100644 --- a/src/components/list/ShoppingListItem.js +++ b/src/components/list/ShoppingListItem.js @@ -1,30 +1,8 @@ -import { useEffect, useState } from 'react'; -import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { Pressable, StyleSheet, Text, View } from 'react-native'; import { colors } from '../../utils/constants'; -import { formatPrice } from '../../utils/formatPrice'; - -export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQuantity, onUpdatePrice }) { - const [priceText, setPriceText] = useState(priceToInputValue(item.estimatedPrice)); - const [priceError, setPriceError] = useState(''); - - useEffect(() => { - setPriceText(priceToInputValue(item.estimatedPrice)); - }, [item.estimatedPrice]); - - function savePrice() { - if (!priceText.trim() && typeof item.estimatedPrice !== 'number') return; - const parsedPrice = parsePrice(priceText); - - if (parsedPrice === undefined) { - setPriceError('Preis prüfen'); - return; - } - - setPriceError(''); - onUpdatePrice(item.id, parsedPrice); - } +export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQuantity }) { return ( @@ -32,7 +10,7 @@ export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQua {item.productName} - {item.quantity} × {formatPrice(item.estimatedPrice, item.currency || 'CHF')}{item.quantity > 1 && typeof item.estimatedPrice === 'number' ? ` · ${formatPrice(item.estimatedPrice * item.quantity, item.currency || 'CHF')}` : ''} + {item.packageQuantityLabel ? {item.packageQuantityLabel} : null} Menge onChangeQuantity(-1)} style={[styles.quantityButton, item.quantity <= 1 && styles.disabledButton]}> @@ -43,24 +21,6 @@ export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQua + - - {item.currency || 'CHF'} - { - setPriceText(value); - setPriceError(''); - }} - onSubmitEditing={savePrice} - placeholder="0.00" - placeholderTextColor={colors.muted} - style={styles.priceInput} - value={priceText} - /> - - {priceError ? {priceError} : null} Löschen @@ -69,21 +29,6 @@ export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQua ); } -function priceToInputValue(price) { - return typeof price === 'number' ? price.toFixed(2) : ''; -} - -function parsePrice(value) { - const normalizedValue = value.trim().replace(',', '.'); - const parsedValue = Number(normalizedValue); - - if (!normalizedValue || !Number.isFinite(parsedValue) || parsedValue < 0) { - return undefined; - } - - return Math.round(parsedValue * 100) / 100; -} - const styles = StyleSheet.create({ completedRow: { backgroundColor: '#f2f7f4' }, quantityRow: { alignItems: 'center', flexDirection: 'row', gap: 8, marginTop: 10 }, @@ -135,33 +80,6 @@ const styles = StyleSheet.create({ fontSize: 13, marginTop: 3 }, - priceRow: { - alignItems: 'center', - flexDirection: 'row', - gap: 8, - marginTop: 10 - }, - currency: { - color: colors.muted, - fontSize: 13, - fontWeight: '800' - }, - priceInput: { - borderColor: colors.border, - borderRadius: 10, - borderWidth: 1, - color: colors.text, - fontSize: 14, - minWidth: 92, - paddingHorizontal: 10, - paddingVertical: 7 - }, - errorText: { - color: colors.danger, - fontSize: 12, - fontWeight: '800', - marginTop: 4 - }, deleteButton: { justifyContent: 'center', minHeight: 44, diff --git a/src/components/product/AlternativeProductCard.js b/src/components/product/AlternativeProductCard.js index 9125c1e..f975092 100644 --- a/src/components/product/AlternativeProductCard.js +++ b/src/components/product/AlternativeProductCard.js @@ -10,7 +10,7 @@ export default function AlternativeProductCard({ item, onChoose, onOpen }) { {item.reason} diff --git a/src/components/product/ProductCard.js b/src/components/product/ProductCard.js index 495d12e..4c14ccd 100644 --- a/src/components/product/ProductCard.js +++ b/src/components/product/ProductCard.js @@ -1,7 +1,6 @@ import { Pressable, StyleSheet, Text, View } from 'react-native'; import { colors } from '../../utils/constants'; -import { formatPrice } from '../../utils/formatPrice'; import ProductImage from './ProductImage'; import ProductScoreBadge from './ProductScoreBadge'; @@ -13,7 +12,7 @@ export default function ProductCard({ product, rating, onPress }) { {product.name} - {product.brand || 'Ohne Marke'} · {formatPrice(product.price, product.currency)} + {product.brand || 'Ohne Marke'} {product.category || 'Produkt'} · Barcode {product.barcode} diff --git a/src/components/product/ProductImage.js b/src/components/product/ProductImage.js index 4b4a477..a5203ff 100644 --- a/src/components/product/ProductImage.js +++ b/src/components/product/ProductImage.js @@ -1,4 +1,5 @@ -import { Image, StyleSheet, Text, View } from 'react-native'; +import { useState } from 'react'; +import { ActivityIndicator, Image, StyleSheet, Text, View } from 'react-native'; import { colors } from '../../utils/constants'; @@ -15,13 +16,30 @@ export default function ProductImage({ imageUrl, productName, size = 'card' }) { ); } + return ; +} + +function RemoteProductImage({ imageUrl, productName, size, style }) { + const [status, setStatus] = useState('loading'); + return ( - + + {status === 'error' ? ( + + {initialsFromName(productName)} + + ) : ( + setStatus('error')} + onLoad={() => setStatus('loaded')} + resizeMode="contain" + source={{ uri: imageUrl }} + style={[styles.image, status === 'loading' ? styles.hiddenImage : null]} + /> + )} + {status === 'loading' ? : null} + ); } @@ -35,10 +53,20 @@ function initialsFromName(name) { } const styles = StyleSheet.create({ - image: { - backgroundColor: colors.surface, + imageFrame: { + alignItems: 'center', + backgroundColor: '#eef3ef', borderColor: colors.border, - borderWidth: 1 + borderWidth: 1, + justifyContent: 'center', + overflow: 'hidden' + }, + image: { + ...StyleSheet.absoluteFillObject, + backgroundColor: colors.surface + }, + hiddenImage: { + opacity: 0 }, card: { borderRadius: 8, diff --git a/src/components/product/RatingCategoryRow.js b/src/components/product/RatingCategoryRow.js index 241e2ce..52335ba 100644 --- a/src/components/product/RatingCategoryRow.js +++ b/src/components/product/RatingCategoryRow.js @@ -5,10 +5,10 @@ import ProductScoreBadge from './ProductScoreBadge'; const labels = { allergies: 'Allergien', - budget: 'Budget', ingredients: 'Zutaten', nutrition: 'Ernährung', - sustainability: 'Nachhaltigkeit' + sustainability: 'Nachhaltigkeit', + goals: 'Deine Ziele' }; export default function RatingCategoryRow({ category, rating, onPress }) { @@ -18,8 +18,10 @@ export default function RatingCategoryRow({ category, rating, onPress }) { {labels[category] || category} - {rating.message} - {(rating.missingData || []).map((message) => ( + {rating.summary || rating.message} + {category === 'goals' && rating.missingData?.length ? ( + {rating.missingData.length} Nährwertangaben fehlen · Details ansehen + ) : (rating.missingData || []).map((message) => ( {message} ))} diff --git a/src/screens/AlternativesScreen.js b/src/screens/AlternativesScreen.js index 6e7c61b..dad0c22 100644 --- a/src/screens/AlternativesScreen.js +++ b/src/screens/AlternativesScreen.js @@ -5,12 +5,13 @@ import PrimaryButton from '../components/PrimaryButton'; import AppHeader from '../components/layout/AppHeader'; import ScreenContainer from '../components/layout/ScreenContainer'; import AlternativeProductCard from '../components/product/AlternativeProductCard'; -import { findAlternatives } from '../services/alternativesService'; +import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService'; +import { calculateProductRating } from '../services/ratingService'; import { colors } from '../utils/constants'; const DISPLAY_ALTERNATIVE_LIMIT = 8; -export default function AlternativesScreen({ product, preferences, productCache, shoppingList, onBack, onChoose, onOpenProduct }) { +export default function AlternativesScreen({ product, preferences, productCache, shoppingList, dailyLog, onBack, onChoose, onOpenProduct }) { const [alternatives, setAlternatives] = useState([]); const [isLoading, setIsLoading] = useState(true); const [searchError, setSearchError] = useState(''); @@ -23,7 +24,7 @@ export default function AlternativesScreen({ product, preferences, productCache, setIsLoading(true); setSearchError(''); try { - const results = await findAlternatives(product, preferences, productCache, { shoppingList }); + const results = await findAlternatives(product, preferences, productCache, { shoppingList, dailyLog }); if (isMounted) setAlternatives(results); } catch (error) { if (isMounted) { @@ -39,19 +40,19 @@ export default function AlternativesScreen({ product, preferences, productCache, return () => { isMounted = false; }; - }, [product, preferences, productCache, shoppingList, retryCount]); + }, [product, preferences, productCache, shoppingList, dailyLog, retryCount]); return ( {isLoading ? {preferences.offlineModeEnabled ? 'Gespeicherte Produkte werden verglichen...' - : 'Open Food Facts wird nach gesünderen Produkten derselben Kategorie durchsucht...'} : null} + : 'Open Food Facts wird nach besseren Produkten derselben Produktart durchsucht...'} : null} {searchError ? {searchError} : null} {searchError ? setRetryCount((count) => count + 1)} /> : null} {!isLoading && alternatives.length > 0 ? ( @@ -61,8 +62,9 @@ export default function AlternativesScreen({ product, preferences, productCache, Keine Alternative gefunden {preferences.offlineModeEnabled - ? 'Im lokalen Cache ist noch keine gesündere Option aus derselben Kategorie gespeichert. Deaktiviere den Offline-Modus für die Online-Suche.' - : 'In dieser Kategorie wurde keine gesündere oder insgesamt besser bewertete Option mit ausreichenden Angaben gefunden.'} + ? 'Im lokalen Cache ist noch keine bessere Option derselben Produktart gespeichert. Deaktiviere den Offline-Modus für die Online-Suche.' + : alternativeSearchIssue(product, calculateProductRating(product, preferences, { shoppingList, dailyLog })) + || 'Unter den geprüften Open Food Facts Treffern war keine belegbar bessere Option derselben Produktart mit ausreichenden Angaben.'} ) : null} @@ -71,7 +73,7 @@ export default function AlternativesScreen({ product, preferences, productCache, item={item} key={item.product.id} onChoose={() => { - if (!item.requiresAllergenCheck && typeof item.product.price === 'number') { + if (!item.requiresAllergenCheck) { onChoose(item.product); return; } diff --git a/src/screens/HomeScreen.js b/src/screens/HomeScreen.js index 200acb6..6a9209e 100644 --- a/src/screens/HomeScreen.js +++ b/src/screens/HomeScreen.js @@ -6,10 +6,12 @@ import ScreenContainer from '../components/layout/ScreenContainer'; import SectionTitle from '../components/layout/SectionTitle'; import ProductCard from '../components/product/ProductCard'; import { calculateProductRating } from '../services/ratingService'; +import { dailyTargets, dailyTotals } from '../services/dailyNutritionService'; import { colors } from '../utils/constants'; -import { formatPrice } from '../utils/formatPrice'; -export default function HomeScreen({ preferences, recentProducts, shoppingList, onStartScan, onOpenProduct, onOpenList }) { +export default function HomeScreen({ preferences, recentProducts, shoppingList, dailyLog, onUndoConsumption, onStartScan, onOpenProduct, onOpenList }) { + const totals = dailyTotals(dailyLog); + const targets = dailyTargets(preferences); const frequentProducts = [...recentProducts] .filter((product) => (product.scanCount || 0) > 1) .sort((a, b) => (b.scanCount || 0) - (a.scanCount || 0)) @@ -33,6 +35,20 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList, + + Heute erfasst + Protein: {Math.round(totals.protein)} g{targets.protein ? ` / ca. ${targets.protein} g` : ''} + Zucker: {Math.round(totals.sugar)} g{targets.sugar ? ` / ${targets.sugar} g (dein Wert)` : ''} + Salz: {totals.salt.toFixed(1)} g / weniger als {targets.salt} g + Ballaststoffe: {totals.fiber.toFixed(1)} g / ca. {targets.fiber} g + {preferences.exerciseGoal === 'endurance' ? Kohlenhydrate: {Math.round(totals.carbohydrates)} g erfasst (bedarf abhängig vom Training) : null} + {targets.vitaminB12 !== null ? Vitamin B12: {totals.vitaminB12.toFixed(1)} µg / ca. {targets.vitaminB12} µg (nur angegebene Werte) : null} + {totals.count} Portionen erfasst · Die Werte zeigen nur deine Einträge. + {totals.count > 0 ? + Letzte Erfassung rückgängig machen + : null} + + Dein Einkauf @@ -40,9 +56,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList, {shoppingList?.items?.length ? `${completedItems} von ${shoppingList.items.length} erledigt · ${openItems} noch offen` : 'Deine Liste ist noch leer'} - - {shoppingList?.items?.length ? formatPrice(shoppingList.estimatedTotal, shoppingList.currency) : 'Liste öffnen'} - + Liste öffnen › {frequentProducts.length > 0 ? ( @@ -52,7 +66,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList, onOpenProduct(product)} /> {product.scanCount} Scans @@ -72,7 +86,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList, onOpenProduct(product)} /> )) diff --git a/src/screens/OnboardingScreen.js b/src/screens/OnboardingScreen.js new file mode 100644 index 0000000..632e2cb --- /dev/null +++ b/src/screens/OnboardingScreen.js @@ -0,0 +1,46 @@ +import { useState } from 'react'; +import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import PrimaryButton from '../components/PrimaryButton'; +import ScreenContainer from '../components/layout/ScreenContainer'; +import { colors, exerciseGoalLabels } from '../utils/constants'; + +export default function OnboardingScreen({ preferences, onSave }) { + const [form, setForm] = useState(preferences); + const [error, setError] = useState(''); + function save() { + const age = Number(form.age), height = Number(form.heightCm), weight = Number(form.weightKg); + if (!Number.isInteger(age) || age < 18 || age > 120 || height < 100 || height > 250 || weight < 20 || weight > 350) { + setError('Bitte gib gültige Werte ein (Alter ab 18, Grösse 100–250 cm, Gewicht 20–350 kg).'); + return; + } + onSave({ ...form, age, heightCm: height, weightKg: weight, onboardingComplete: true }); + } + return + Willkommen bei Shoppinguin + Erfahre beim Scannen, wie ein Lebensmittel zu deiner Ernährung und deinem Training passt. Dein Profil bleibt auf diesem Gerät. + {[["Alter", 'age'], ['Grösse in cm', 'heightCm'], ['Gewicht in kg', 'weightKg']].map(([label, key]) => + {label} setForm({ ...form, [key]: value })} style={styles.input} />)} + Dein Trainingsziel + {Object.entries(exerciseGoalLabels).map(([key, label]) => + setForm({ ...form, exerciseGoal: key })} style={[styles.chip, form.exerciseGoal === key && styles.selected]}> + {label} + )} + Richtwerte sind Orientierung, keine medizinische Empfehlung. Erfasste Lebensmittel sind nur so vollständig wie dein Tagesprotokoll. + {error ? {error} : null} + + ; +} + +const styles = StyleSheet.create({ + title: { color: colors.text, fontSize: 29, fontWeight: '800', marginTop: 20 }, + copy: { color: colors.muted, fontSize: 15, lineHeight: 22 }, + label: { color: colors.text, fontSize: 15, fontWeight: '700', marginBottom: 7, marginTop: 14 }, + input: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 12, borderWidth: 1, color: colors.text, fontSize: 17, padding: 12 }, + options: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }, + chip: { borderColor: colors.border, borderRadius: 12, borderWidth: 1, padding: 12 }, + selected: { backgroundColor: colors.primary }, + chipText: { color: colors.text, fontWeight: '700' }, selectedText: { color: colors.surface }, + error: { color: colors.danger, fontSize: 14 } +}); diff --git a/src/screens/PrivacyScreen.js b/src/screens/PrivacyScreen.js index 30c915d..a790929 100644 --- a/src/screens/PrivacyScreen.js +++ b/src/screens/PrivacyScreen.js @@ -15,8 +15,8 @@ const sections = [ { title: 'Daten auf deinem Gerät', paragraphs: [ - 'Shoppinguin speichert deine Einstellungen, ausgewählte Allergene und Ernährungsziele, Budgetangaben, die Einkaufsliste, manuell eingegebene Preise und Produktangaben sowie zuletzt angezeigte und zwischengespeicherte Produkte lokal auf deinem Gerät. Diese Angaben nutzt die App für Produktempfehlungen, Bewertungen und deine Einkaufsliste. Shoppinguin bietet derzeit kein Nutzerkonto. Die lokal gespeicherten Angaben werden nicht an einen Shoppinguin-Server übertragen.', - 'Verlauf und Produktcache kannst du in den Einstellungen der App löschen. Einkaufsliste, Einstellungen und manuelle Preise bleiben dabei erhalten. Alle lokalen App-Daten kannst du über die Einstellungen deines Geräts löschen oder durch Deinstallation entfernen. Shoppinguin bewahrt davon keine Kopie auf einem eigenen Server auf.' + 'Shoppinguin speichert Alter, Grösse, Gewicht, Trainingsziel, deinen Zucker-Tageswert und erfasste Portionen sowie Allergene, Einkaufsliste und Produktdaten lokal auf deinem Gerät. Diese Angaben nutzt die App für persönliche Produkthinweise. Shoppinguin bietet kein Nutzerkonto. Dein Profil und Tagesprotokoll werden nicht an einen Shoppinguin-Server übertragen.', + 'Verlauf und Produktcache kannst du in den Einstellungen der App löschen. Einkaufsliste und Einstellungen bleiben dabei erhalten. Frühere manuell gespeicherte Preise werden beim nächsten App-Start entfernt. Alle lokalen App-Daten kannst du über die Einstellungen deines Geräts löschen oder durch Deinstallation entfernen. Shoppinguin bewahrt davon keine Kopie auf einem eigenen Server auf.' ] }, { @@ -28,8 +28,8 @@ const sections = [ { title: 'Online-Produktsuche', paragraphs: [ - 'Für eine Online-Abfrage sendet Shoppinguin den gescannten Barcode oder deinen Suchbegriff an Open Food Facts und lädt Produktinformationen von dort. Bei einer solchen Internetverbindung können technisch bedingt auch Verbindungsdaten, insbesondere deine IP-Adresse, beim Anbieter anfallen. Deine lokalen Einstellungen, Allergenauswahl und Einkaufsliste werden bei diesen Abfragen nicht mitgesendet.', - 'Bei einem Barcode-Treffer aus einem frischen lokalen Produktcache, bei lokal erfassten Produkten und im Offline-Modus erfolgt keine Abfrage bei Open Food Facts. Die Namenssuche fragt bei aktivem Online-Modus zuerst Open Food Facts an und ergänzt die Treffer um lokal gespeicherte Produkte. Manuell ergänzte Produktangaben bleiben auf deinem Gerät und werden von Shoppinguin nicht an Open Food Facts gesendet. Wenn du den Produktlink zu Open Food Facts öffnest, verlässt du die App und kannst dort selbst Angaben ergänzen. Für diese Webseite gelten die Datenschutzhinweise von Open Food Facts.' + 'Für eine Online-Abfrage sendet Shoppinguin den gescannten Barcode oder deinen Suchbegriff an Open Food Facts und lädt Produktinformationen von dort. Beim Öffnen eines Produkts sucht die App automatisch anhand seiner Kategorietags nach ähnlichen Alternativen. Falls das nicht genügt, verwendet sie auch die Produktart, Kategorie oder Teile des Produktnamens als Suchbegriff. Bei einer solchen Internetverbindung können technisch bedingt auch Verbindungsdaten, insbesondere deine IP-Adresse, beim Anbieter anfallen. Deine lokalen Einstellungen, Allergenauswahl und Einkaufsliste werden bei diesen Abfragen nicht mitgesendet.', + 'Ein Barcode-Treffer aus einem frischen lokalen Produktcache benötigt für das Laden des Produkts keine Online-Abfrage. Im Offline-Modus erfolgt keine Abfrage bei Open Food Facts. Die Namenssuche fragt bei aktivem Online-Modus zuerst Open Food Facts an und ergänzt die Treffer um lokal gespeicherte Produkte. Manuell ergänzte Nährwerte, Zutaten und Allergene bleiben auf deinem Gerät; Produktname und Kategorie können für die Alternativsuche als Suchbegriffe gesendet werden. Wenn du den Produktlink zu Open Food Facts öffnest, verlässt du die App und kannst dort selbst Angaben ergänzen. Für diese Webseite gelten die Datenschutzhinweise von Open Food Facts.' ] }, { @@ -69,7 +69,7 @@ export default function PrivacyScreen({ onBack }) { ) : null} {section.title === 'Online-Produktsuche' ? ( - Linking.openURL('https://world.openfoodfacts.org/privacy')}> + Linking.openURL('https://ch.openfoodfacts.org/privacy')}> Datenschutzhinweise von Open Food Facts › ) : null} diff --git a/src/screens/ProductDetailScreen.js b/src/screens/ProductDetailScreen.js index 7860958..6bb96d9 100644 --- a/src/screens/ProductDetailScreen.js +++ b/src/screens/ProductDetailScreen.js @@ -1,5 +1,5 @@ -import { useMemo, useState } from 'react'; -import { Alert, Linking, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { useEffect, useMemo, useState } from 'react'; +import { Alert, Linking, Platform, Pressable, StyleSheet, Text, View } from 'react-native'; import PrimaryButton from '../components/PrimaryButton'; import SecondaryButton from '../components/SecondaryButton'; @@ -10,8 +10,8 @@ import ProductImage from '../components/product/ProductImage'; import ProductScoreBadge from '../components/product/ProductScoreBadge'; import RatingCategoryRow from '../components/product/RatingCategoryRow'; import { calculateProductRating } from '../services/ratingService'; +import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService'; import { colors } from '../utils/constants'; -import { formatPrice } from '../utils/formatPrice'; export default function ProductDetailScreen({ product, @@ -19,37 +19,38 @@ export default function ProductDetailScreen({ onBack, onAddToList, onOpenList, - onSaveManualPrice, onEditProduct, onShowRatingCriteria, onShowAlternatives, - shoppingList + onOpenProduct, + productCache, + shoppingList, + dailyLog, + onRecordConsumption }) { const [savedMessage, setSavedMessage] = useState(''); - const [manualPrice, setManualPrice] = useState(''); - const [priceError, setPriceError] = useState(''); - const hasProductPrice = typeof product.price === 'number'; - const currency = product.currency || preferences.currency; - const parsedManualPrice = parseManualPrice(manualPrice); - const pricedProduct = useMemo(() => ({ - ...product, - currency, - price: hasProductPrice ? product.price : parsedManualPrice - }), [currency, hasProductPrice, parsedManualPrice, product]); - const rating = useMemo(() => calculateProductRating(pricedProduct, preferences, { shoppingList }), [pricedProduct, preferences, shoppingList]); + const [suggestions, setSuggestions] = useState([]); + const [suggestionsLoading, setSuggestionsLoading] = useState(true); + const [suggestionsError, setSuggestionsError] = useState(false); + const rating = useMemo(() => calculateProductRating(product, preferences, { shoppingList, dailyLog }), [product, preferences, shoppingList, dailyLog]); const footprint = product.sustainability?.footprint; const missingFields = missingProductFields(product, preferences); const recommendation = rating.overallStatus === 'good' ? 'Passt gut zu dir' : rating.overallStatus === 'critical' ? 'Lieber meiden' : rating.overallStatus === 'unknown' ? 'Zu wenig Daten' : 'Genauer prüfen'; - function addToList() { - if (!hasProductPrice && manualPrice.trim() && parsedManualPrice === undefined) { - setSavedMessage(''); - setPriceError('Bitte gib einen gültigen Preis ein oder lasse das Feld leer.'); - return; - } + useEffect(() => { + let active = true; + setSuggestionsLoading(true); + setSuggestionsError(false); + findAlternatives(product, preferences, productCache, { dailyLog }, { preview: true }) + .then((results) => { if (active) setSuggestions(results); }) + .catch(() => { if (active) { setSuggestions([]); setSuggestionsError(true); } }) + .finally(() => { if (active) setSuggestionsLoading(false); }); + return () => { active = false; }; + }, [product, preferences, productCache, dailyLog]); + function addToList() { if (rating.hasBlockedAllergen) { setSavedMessage('Dieses Produkt enthält ein Allergen aus deinem Profil und wurde nicht hinzugefügt.'); return; @@ -72,12 +73,7 @@ export default function ProductDetailScreen({ } function saveToList() { - if (!hasProductPrice && typeof pricedProduct.price === 'number') { - onSaveManualPrice(pricedProduct, pricedProduct.price); - } - - onAddToList(pricedProduct); - setPriceError(''); + onAddToList(product); setSavedMessage('Zur Einkaufsliste hinzugefügt.'); } @@ -92,7 +88,7 @@ export default function ProductDetailScreen({ {product.brand || 'Ohne Marke'} {product.name} - {product.category || 'Produkt'} · {formatPrice(pricedProduct.price, currency)} + {product.category || 'Produkt'} {sourceLabel(product.dataSource)}{product.cacheStale ? ' · Veraltete Daten' : ''} {product.manualOverrides ? Angaben von dir ergänzt · lokal gespeichert : null} @@ -112,13 +108,20 @@ export default function ProductDetailScreen({ {rating.mainFactors.length > 0 || rating.scoreLimitReasons.length > 0 ? ( - Wichtigste Einflüsse auf die App-Bewertung - {rating.scoreLimitReasons.map((reason) => {reason})} + Das beeinflusst die Bewertung {rating.mainFactors.map((factor) => ( - - {factor.label}: {factor.score}/100 · {factor.message} - + + + {factor.label} + {factor.score}/100 + + {factor.message} + ))} + {rating.scoreLimitReasons.length > 0 ? + Bitte beachten + {rating.scoreLimitReasons.map((reason) => • {reason})} + : null} ) : null} @@ -130,38 +133,12 @@ export default function ProductDetailScreen({ Übertrage Werte von der Verpackung. Fehlende Werte werden nicht geschätzt. onEditProduct(product)} /> {/^\d{8,14}$/.test(product.barcode || '') ? ( - Linking.openURL(`https://world.openfoodfacts.org/product/${product.barcode}`)}> + Linking.openURL(`https://ch.openfoodfacts.org/product/${product.barcode}`)}> Produkt auf Open Food Facts öffnen › ) : null} - {!hasProductPrice ? ( - - Ladenpreis ergänzen - - Optional. Ohne Preis kannst du das Produkt speichern; die Einkaufssumme bleibt dann unvollständig. - - - {currency} - { - setManualPrice(value); - setPriceError(''); - setSavedMessage(''); - }} - placeholder="z. B. 3.50" - placeholderTextColor={colors.muted} - style={styles.priceInput} - value={manualPrice} - /> - - {priceError ? {priceError} : null} - - ) : null} - {savedMessage ? ( {savedMessage} @@ -171,14 +148,37 @@ export default function ProductDetailScreen({ ) : null} - onShowAlternatives(pricedProduct)} /> + { onRecordConsumption(product); setSavedMessage('Portion im Tagesprotokoll erfasst.'); }} /> + Es wird die angegebene Portionsgrösse verwendet, sonst die Packungsmenge oder 100 g. Nur tatsächlich Gegessenes erfassen. + + Ähnliche, bessere Alternativen + {suggestionsLoading ? Passende Produkte werden gesucht ... : null} + {!suggestionsLoading && suggestions.length === 0 ? + {suggestionsError ? 'Alternativen konnten gerade nicht geladen werden.' + : alternativeSearchIssue(product, rating) || 'Unter den geprüften Treffern war keine belegbar bessere Alternative derselben Produktart.'} + : null} + {suggestions.map((item) => onOpenProduct(item.product)} style={styles.suggestionCard}> + + + + + {item.product.name} + + + {item.reason} + Produkt ansehen › + + + )} + onShowAlternatives(product)} /> Bewertungskriterien {Object.entries(rating.categoryScores).map(([category, categoryRating]) => ( onShowRatingCriteria(pricedProduct, category)} + onPress={() => onShowRatingCriteria(product, category)} rating={categoryRating} /> ))} @@ -244,7 +244,6 @@ function recommendationMessage(rating) { if (rating.allergenReviewRequired) return rating.allergenReviewMessage; if (rating.goalConflict) return rating.categoryScores.ingredients.message; if (rating.goalReviewRequired) return 'Für dein Ernährungsziel fehlen Angaben. Prüfe die Zutaten oder Nährwerte auf der Verpackung.'; - if (rating.budgetReviewRequired) return 'Für die Budgetprüfung fehlen Preise. Ergänze den Ladenpreis oder offene Listenpreise.'; if (rating.staleDataReviewRequired) return 'Gespeicherte Produktdaten sind veraltet. Prüfe vor dem Kauf die Verpackung.'; if (rating.overallStatus === 'unknown') return 'Für eine Empfehlung fehlen belastbare Produktangaben.'; if (rating.limitedByMissingData) return 'Nur ein Teil der Kriterien ist belegt. Die Empfehlung ist deshalb auf „Prüfen“ begrenzt.'; @@ -260,14 +259,20 @@ function missingProductFields(product, preferences) { if (!product.dataCompleteness?.ingredients) fields.push('Zutatenliste'); if (preferences.avoidAllergens?.length && !product.dataCompleteness?.allergens) fields.push('Allergenangaben'); if (!Number.isFinite(nutrition.sugarPer100g)) fields.push(`Zucker pro ${beverage ? '100 ml' : '100 g'}`); + if (!Number.isFinite(nutrition.proteinPer100g)) fields.push('Protein'); + if (!Number.isFinite(nutrition.saltPer100g)) fields.push('Salz'); + if (!Number.isFinite(nutrition.fiberPer100g)) fields.push('Ballaststoffe'); + if (preferences.exerciseGoal === 'endurance' && !Number.isFinite(nutrition.carbohydratesPer100g)) { + fields.push(product.cacheStale ? 'Kohlenhydrate im lokalen Cache (online erneut scannen)' : 'Kohlenhydrate'); + } + if (preferences.preferredDiet === 'vegan' && !Number.isFinite(nutrition.vitaminB12MicrogramsPer100g)) fields.push('Vitamin B12'); if (beverage && !nutrition.nutriScore) { if (!Number.isFinite(nutrition.energyKjPer100g) && !Number.isFinite(nutrition.caloriesPer100g)) fields.push('Energie'); if (!Number.isFinite(nutrition.saturatedFatPer100g)) fields.push('gesättigte Fettsäuren'); if (!Number.isFinite(nutrition.saltPer100g)) fields.push('Salz'); if (typeof nutrition.hasNonNutritiveSweeteners !== 'boolean') fields.push('Süssstoffe'); } - if (typeof product.price !== 'number' && Number.isFinite(preferences.maxBudgetPerShoppingTrip)) fields.push('Preis'); - return fields.slice(0, 6); + return fields.slice(0, 8); } function manualFieldNames(overrides) { @@ -276,24 +281,14 @@ function manualFieldNames(overrides) { return [ ...Object.keys(overrides).filter((key) => key !== 'nutrition').map((key) => names[key]).filter(Boolean), ...Object.keys(overrides.nutrition || {}).map((key) => - ({ energyKjPer100g: 'Energie', sugarPer100g: 'Zucker', saturatedFatPer100g: 'gesättigte Fettsäuren', + ({ energyKjPer100g: 'Energie', sugarPer100g: 'Zucker', carbohydratesPer100g: 'Kohlenhydrate', + vitaminB12MicrogramsPer100g: 'Vitamin B12', saturatedFatPer100g: 'gesättigte Fettsäuren', saltPer100g: 'Salz', proteinPer100g: 'Protein', fiberPer100g: 'Ballaststoffe', fruitVegetableLegumePercent: 'Frucht- und Gemüseanteil', hasNonNutritiveSweeteners: 'Süssstoffe' })[key] ).filter(Boolean) ]; } -function parseManualPrice(value) { - const normalizedValue = value.trim().replace(',', '.'); - const parsedValue = Number(normalizedValue); - - if (!normalizedValue || !Number.isFinite(parsedValue) || parsedValue <= 0) { - return undefined; - } - - return Math.round(parsedValue * 100) / 100; -} - function sourceLabel(source) { const labels = { cache: 'Quelle: lokaler Cache', @@ -339,7 +334,18 @@ function matchLabel(method) { } const styles = StyleSheet.create({ + suggestionCard: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 16, borderWidth: 1, gap: 8, padding: 16 }, + suggestionRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 }, + suggestionBody: { flex: 1, gap: 8 }, + suggestionName: { color: colors.text, flex: 1, fontSize: 16, fontWeight: '800' }, + suggestionLink: { color: colors.primary, fontSize: 13, fontWeight: '800' }, factorTitle: { color: colors.text, fontSize: 16, fontWeight: '800' }, + factorRow: { borderTopColor: colors.border, borderTopWidth: 1, gap: 4, paddingTop: 10 }, + factorHeader: { alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between' }, + factorLabel: { color: colors.text, fontSize: 14, fontWeight: '800' }, + factorScore: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' }, + limitPanel: { backgroundColor: '#fff7e8', borderRadius: 12, gap: 5, padding: 12 }, + limitTitle: { color: colors.warning, fontSize: 13, fontWeight: '800' }, productPanel: { backgroundColor: colors.surface, borderColor: colors.border, @@ -407,49 +413,6 @@ const styles = StyleSheet.create({ fontSize: 13, lineHeight: 19 }, - pricePanel: { - backgroundColor: colors.surface, - borderColor: colors.border, - borderRadius: 18, - borderWidth: 1, - gap: 10, - padding: 16 - }, - priceTitle: { - color: colors.text, - fontSize: 17, - fontWeight: '800' - }, - priceCopy: { - color: colors.muted, - fontSize: 14, - lineHeight: 20 - }, - priceInputRow: { - alignItems: 'center', - flexDirection: 'row', - gap: 10 - }, - currency: { - color: colors.muted, - fontSize: 16, - fontWeight: '800' - }, - priceInput: { - borderColor: colors.border, - borderRadius: 12, - borderWidth: 1, - color: colors.text, - flex: 1, - fontSize: 16, - paddingHorizontal: 12, - paddingVertical: 10 - }, - errorText: { - color: colors.danger, - fontSize: 13, - fontWeight: '800' - }, dataPanel: { backgroundColor: colors.surface, borderColor: colors.border, diff --git a/src/screens/ProductEditScreen.js b/src/screens/ProductEditScreen.js new file mode 100644 index 0000000..223463c --- /dev/null +++ b/src/screens/ProductEditScreen.js @@ -0,0 +1,50 @@ +import { useState } from 'react'; +import { StyleSheet, Text, TextInput, View } from 'react-native'; +import PrimaryButton from '../components/PrimaryButton'; +import AppHeader from '../components/layout/AppHeader'; +import ScreenContainer from '../components/layout/ScreenContainer'; +import { colors } from '../utils/constants'; + +const nutrientFields = [['Protein (g/100 g)', 'proteinPer100g'], ['Zucker (g/100 g)', 'sugarPer100g'], + ['Kohlenhydrate (g/100 g)', 'carbohydratesPer100g'], ['Ballaststoffe (g/100 g)', 'fiberPer100g'], + ['Vitamin B12 (µg/100 g)', 'vitaminB12MicrogramsPer100g'], + ['Energie (kJ/100 g)', 'energyKjPer100g'], ['Gesättigte Fettsäuren (g/100 g)', 'saturatedFatPer100g'], + ['Salz (g/100 g)', 'saltPer100g']]; + +export default function ProductEditScreen({ product, isNew, onBack, onSave }) { + const [form, setForm] = useState({ name: product.name || '', brand: product.brand || '', + category: product.category || '', ingredients: (product.ingredients || []).join(', '), + allergens: (product.allergens || []).join(', '), + ...Object.fromEntries(nutrientFields.map(([, key]) => [key, String(product.nutrition?.[key] ?? '')])) }); + const [error, setError] = useState(''); + function save() { + if (!form.name.trim()) { setError('Bitte gib einen Produktnamen ein.'); return; } + const nutrition = {}; + for (const [, key] of nutrientFields) { + if (!form[key].trim()) continue; + const value = Number(form[key].replace(',', '.')); + if (!Number.isFinite(value) || value < 0) { setError('Bitte gib gültige Nährwerte ein.'); return; } + nutrition[key] = value; + } + const list = (value) => value.split(',').map((part) => part.trim()).filter(Boolean); + onSave({ name: form.name.trim(), brand: form.brand.trim(), category: form.category.trim(), + ingredients: list(form.ingredients), allergens: list(form.allergens), nutrition }); + } + return + Übertrage die Angaben von der Verpackung. Alle Änderungen bleiben lokal. + {[["Name", 'name'], ['Marke', 'brand'], ['Kategorie', 'category'], ['Zutaten (kommagetrennt)', 'ingredients'], + ['Allergene (kommagetrennt)', 'allergens'], ...nutrientFields].map(([label, key]) => + {label} field === key) ? 'decimal-pad' : 'default'} + onChangeText={(value) => setForm({ ...form, [key]: value })} style={styles.input} />)} + {error ? {error} : null} + + ; +} + +const styles = StyleSheet.create({ + hint: { color: colors.muted, fontSize: 14, lineHeight: 20 }, + label: { color: colors.text, fontWeight: '700', marginBottom: 5, marginTop: 12 }, + input: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 10, borderWidth: 1, color: colors.text, fontSize: 16, padding: 10 }, + error: { color: colors.danger } +}); diff --git a/src/screens/ProfileScreen.js b/src/screens/ProfileScreen.js index 4343edb..86a8c7a 100644 --- a/src/screens/ProfileScreen.js +++ b/src/screens/ProfileScreen.js @@ -1,12 +1,11 @@ -import { useState } from 'react'; -import { Alert, Platform, Pressable, StyleSheet, Text, View } from 'react-native'; +import { useEffect, useState } from 'react'; +import { Alert, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; -import BudgetInput from '../components/form/BudgetInput'; import SettingsSwitchRow from '../components/form/SettingsSwitchRow'; import AppHeader from '../components/layout/AppHeader'; import ScreenContainer from '../components/layout/ScreenContainer'; -import { budgetPeriodLabels, colors, dietLabels } from '../utils/constants'; -import { formatPrice } from '../utils/formatPrice'; +import { dailyTargets, FREE_SUGAR_REFERENCE_GRAMS, sugarLimitWarning } from '../services/dailyNutritionService'; +import { colors, dietLabels, exerciseGoalLabels } from '../utils/constants'; const dietOptions = ['none', 'vegetarian', 'vegan', 'lowSugar', 'highProtein']; const allergenOptions = ['Erdnüsse', 'Milch', 'Hafer', 'Gluten']; @@ -24,7 +23,7 @@ export default function ProfileScreen({ preferences, onChangePreferences, onOpen } function confirmClearProductData() { - const message = 'Gespeicherte Produkte und letzte Scans werden entfernt. Einkaufsliste, Einstellungen und manuelle Preise bleiben erhalten.'; + const message = 'Gespeicherte Produkte und letzte Scans werden entfernt. Einkaufsliste und Einstellungen bleiben erhalten.'; if (Platform.OS === 'web') { if (window.confirm(`Verlauf und Produktcache löschen?\n\n${message}`)) clearProductData(); return; @@ -51,10 +50,7 @@ export default function ProfileScreen({ preferences, onChangePreferences, onOpen } const allergenCount = preferences.avoidAllergens?.length || 0; - const budget = preferences.maxBudgetPerShoppingTrip; - const budgetSummary = typeof budget === 'number' && budget > 0 - ? `${formatPrice(budget, preferences.currency)} pro ${budgetPeriodLabels[preferences.budgetPeriod] || 'Woche'}` - : 'Kein Budget festgelegt'; + const targets = dailyTargets(preferences); return ( @@ -100,40 +96,36 @@ export default function ProfileScreen({ preferences, onChangePreferences, onOpen - - updatePreference('budgetPeriod', value)} - onChangeValue={(value) => updatePreference('maxBudgetPerShoppingTrip', value)} - period={preferences.budgetPeriod || 'week'} - value={budget} - /> + + Deine Angaben helfen bei der Einordnung. Die Richtwerte sind keine individuelle medizinische Beratung. + {[["Alter", 'age'], ['Grösse (cm)', 'heightCm'], ['Gewicht (kg)', 'weightKg']].map(([label, key]) => + {label} updatePreference(key, value)} style={styles.profileInput} />)} + Trainingsziel + {Object.entries(exerciseGoalLabels).map(([key, label]) => + updatePreference('exerciseGoal', key)} />)} + + + + Protein: {targets.protein === null ? 'Gewicht fehlt' : `ca. ${targets.protein} g pro Tag`} + Aus Körpergewicht und Trainingsziel berechnet. Alter und Grösse ändern diesen Richtwert nicht; für einen persönlichen Energiebedarf fehlen weitere Angaben wie Aktivität und Körperzusammensetzung. + + updatePreference('dailySugarLimitGrams', value)} /> + Die App zählt Gesamtzucker aus den Produktangaben. Die WHO-Orientierung von weniger als {FREE_SUGAR_REFERENCE_GRAMS} g bei 2.000 kcal gilt für freien Zucker und ist damit nicht direkt vergleichbar. + + Salz: weniger als {targets.salt} g pro Tag + WHO-Orientierung für Erwachsene. Salz vom Kochen oder Nachsalzen ist im App-Protokoll nicht enthalten. + Ballaststoffe: ca. {targets.fiber} g pro Tag + Allgemeiner EFSA-Richtwert für Erwachsene. + {preferences.exerciseGoal === 'endurance' ? Ausdauer: Kohlenhydrate werden pro Portion angezeigt. Ein Tagesziel hängt von Trainingsdauer und Intensität ab. : null} + {targets.vitaminB12 !== null ? Vegan: Vitamin B12 wird, wenn angegeben, mit dem EFSA-Richtwert von {targets.vitaminB12} µg pro Tag verglichen. Fehlende Produktwerte bedeuten nicht, dass kein B12 enthalten ist. : null} - updatePreference('preferBio', value)} - value={preferences.preferBio} - /> - - Prioritäten - Hoch bedeutet, dass dieser Bereich stärker in die Gesamtbewertung einfliesst. - updatePreference('nutritionPriority', value)} - value={preferences.nutritionPriority} - /> - updatePreference('sustainabilityPriority', value)} - value={preferences.sustainabilityPriority} - /> + Die Bewertung berücksichtigt Nährwerte, deine Tageswerte, Allergien und Zutaten. Umweltangaben bleiben als zusätzliche Produktinformation sichtbar. {isClearingProductData ? 'Daten werden gelöscht...' : 'Verlauf und Produktcache löschen'} - Einkaufsliste, Einstellungen und manuelle Preise bleiben erhalten. + Einkaufsliste und Einstellungen bleiben erhalten. {dataMessage ? {dataMessage} : null} ); } +function SugarTargetInput({ value, onChange }) { + const [draft, setDraft] = useState(String(value ?? '')); + const [error, setError] = useState(''); + + useEffect(() => setDraft(String(value ?? '')), [value]); + + function save() { + const grams = Number(draft.trim().replace(',', '.')); + if (!Number.isFinite(grams) || grams <= 0 || grams > 500) { + setError('Bitte gib einen Wert zwischen 1 und 500 g ein.'); + return; + } + setError(''); + if (grams === Number(value)) return; + onChange(grams); + const warning = sugarLimitWarning(grams); + if (warning) { + if (Platform.OS === 'web') window.alert(warning); + else Alert.alert('Zuckerwert über der WHO-Orientierung', warning, [{ text: 'Verstanden' }]); + } + } + + return + Dein Tageswert für Gesamtzucker (g) + + {error ? {error} : null} + ; +} + function SettingsSection({ title, summary, children }) { return ( @@ -257,6 +279,8 @@ const styles = StyleSheet.create({ fontSize: 13, lineHeight: 19 }, + profileInput: { borderColor: colors.border, borderRadius: 10, borderWidth: 1, color: colors.text, fontSize: 16, marginTop: 7, padding: 10 }, + errorText: { color: colors.danger, fontSize: 13, marginTop: 6 }, divider: { backgroundColor: colors.border, height: 1 diff --git a/src/screens/RatingCriteriaDetailScreen.js b/src/screens/RatingCriteriaDetailScreen.js index 247820e..0c1ba42 100644 --- a/src/screens/RatingCriteriaDetailScreen.js +++ b/src/screens/RatingCriteriaDetailScreen.js @@ -8,10 +8,10 @@ import { colors } from '../utils/constants'; const labels = { allergies: 'Allergien', - budget: 'Budget', ingredients: 'Zutaten', nutrition: 'Ernährung', - sustainability: 'Nachhaltigkeit' + sustainability: 'Nachhaltigkeit', + goals: 'Deine Ziele' }; const defaultDetails = { @@ -19,10 +19,6 @@ const defaultDetails = { positive: 'Eine ausdrücklich bestätigte Abwesenheit deiner vermiedenen Allergene verbessert diese Bewertung.', penalty: 'Ein angegebenes vermiedenes Allergen blockiert die Empfehlung. Mögliche Spuren und nicht bestätigte Abwesenheit erfordern eine Prüfung der Verpackung.' }, - budget: { - positive: 'Ein niedriger Anteil der offenen Einkaufsliste inklusive dieses Produkts am Budget verbessert diese Bewertung.', - penalty: 'Eine Überschreitung des Budgets reduziert die Bewertung. Fehlende Preise verhindern eine bestätigte Budgeteinhaltung.' - }, ingredients: { positive: 'Eine passende Vegan-/Vegetarisch-Analyse sowie Angaben zu Palmöl und Zusatzstoffen verbessern diese Bewertung.', penalty: 'Zusatzstoffhinweise und Palmöl senken die Zutatenwertung. Ein bestätigter Konflikt mit Vegan oder Vegetarisch begrenzt die Gesamtempfehlung.' @@ -34,14 +30,18 @@ const defaultDetails = { sustainability: { positive: 'Ein guter Green-Score oder ein niedriger CO2-Fussabdruck verbessert diese Bewertung; Bio zählt bei entsprechender Präferenz.', penalty: 'Ein schwacher Green-Score oder hoher CO2-Fussabdruck reduziert diese Bewertung. Herkunft und Verpackung werden angezeigt, aber nicht in Punkte übersetzt.' - } + }, + goals: { positive: 'Protein, Zucker und bei Ausdauer Kohlenhydrate beeinflussen die Zielwertung. Salz, Ballaststoffe und bei veganer Ernährung Vitamin B12 werden als Tageskontext gezeigt.', penalty: 'Viel Zucker im Verhältnis zu deinem Tageswert senkt die Zielwertung. Salz und Ballaststoffe stecken bereits im Nutri-Score und werden nicht nochmals als Punktabzug gewertet.' } }; -export default function RatingCriteriaDetailScreen({ product, preferences, shoppingList, category, onBack }) { - const rating = calculateProductRating(product, preferences, { shoppingList }); +export default function RatingCriteriaDetailScreen({ product, preferences, shoppingList, dailyLog, category, onBack }) { + const rating = calculateProductRating(product, preferences, { shoppingList, dailyLog }); const categoryRating = rating.categoryScores[category]; const title = labels[category] || category; const fallbackDetails = defaultDetails[category] || defaultDetails.ingredients; + const goalDetails = category === 'goals' ? categoryRating.details || [] : []; + const goalScoreDetails = goalDetails.filter((detail) => ['Protein', 'Zucker', 'Kohlenhydrate für Ausdauer'].includes(detail.title)); + const goalContextDetails = goalDetails.filter((detail) => !['Protein', 'Zucker', 'Kohlenhydrate für Ausdauer'].includes(detail.title)); return ( @@ -67,7 +67,16 @@ export default function RatingCriteriaDetailScreen({ product, preferences, shopp ) : null} - {(categoryRating.details || []).length > 0 ? ( + {category === 'goals' ? <> + {goalScoreDetails.length > 0 ? + Für dein Ziel + {goalScoreDetails.map((detail) => )} + : null} + {goalContextDetails.length > 0 ? + Weitere Tageswerte + {goalContextDetails.map((detail) => )} + : null} + : (categoryRating.details || []).length > 0 ? ( So entsteht die Bewertung {categoryRating.details.map((detail) => ( @@ -83,19 +92,28 @@ export default function RatingCriteriaDetailScreen({ product, preferences, shopp ) : null} - + {category !== 'goals' ? Was die Bewertung verbessert {fallbackDetails.positive} - + : null} - + {category !== 'goals' ? Was die Bewertung senkt {fallbackDetails.penalty} - + : null} + {category === 'goals' ? Die Tageswerte zeigen nur deine erfassten Portionen. Salz und Ballaststoffe verändern die Zielpunktzahl nicht erneut. : null} ); } +function GoalDetail({ detail }) { + return + {detail.title} + {detail.body} + ; +} + const styles = StyleSheet.create({ summaryPanel: { backgroundColor: colors.surface, @@ -150,6 +168,7 @@ const styles = StyleSheet.create({ gap: 5, paddingTop: 10 }, + goalItem: { backgroundColor: colors.background, borderRadius: 12, gap: 5, padding: 12 }, positiveTitle: { color: colors.success, fontSize: 14, diff --git a/src/screens/ShoppingListScreen.js b/src/screens/ShoppingListScreen.js index 8d9dfd8..32a6a4a 100644 --- a/src/screens/ShoppingListScreen.js +++ b/src/screens/ShoppingListScreen.js @@ -7,35 +7,23 @@ import AppHeader from '../components/layout/AppHeader'; import ScreenContainer from '../components/layout/ScreenContainer'; import ShoppingListItem from '../components/list/ShoppingListItem'; import { calculateShoppingListWarnings } from '../services/shoppingListWarningsService'; -import { budgetPeriodLabels, colors } from '../utils/constants'; -import { formatPrice } from '../utils/formatPrice'; +import { colors } from '../utils/constants'; export default function ShoppingListScreen({ - preferences, shoppingList, lastDeletedItem, onToggleItem, onChangeItemQuantity, onDeleteItem, onUndoDelete, - onUpdateItemPrice, onStartScan, - onOpenProfile, onCompleteList }) { const [isConfirming, setIsConfirming] = useState(false); const [wasCompleted, setWasCompleted] = useState(false); const openItems = shoppingList.items.filter((item) => !item.checked).length; const completedItems = shoppingList.items.length - openItems; - const openTotal = shoppingList.items.reduce((sum, item) => - sum + (!item.checked && typeof item.estimatedPrice === 'number' ? item.estimatedPrice * item.quantity : 0), 0); const progress = shoppingList.items.length ? completedItems / shoppingList.items.length : 0; - const itemsWithoutPrice = shoppingList.items.filter((item) => typeof item.estimatedPrice !== 'number').length; - const openItemsWithoutPrice = shoppingList.items.filter((item) => !item.checked && typeof item.estimatedPrice !== 'number').length; - const budget = preferences.maxBudgetPerShoppingTrip; - const hasBudget = typeof budget === 'number' && budget > 0; - const budgetShare = hasBudget ? shoppingList.estimatedTotal / budget : 0; - const budgetStatus = budgetShare <= 0.75 ? 'good' : budgetShare <= 1 ? 'medium' : 'critical'; const dailyWarnings = calculateShoppingListWarnings(shoppingList); return ( @@ -62,9 +50,7 @@ export default function ShoppingListScreen({ Deine Liste - {itemsWithoutPrice ? 'Bekannte Summe' : 'Voraussichtliche Summe'} - {formatPrice(shoppingList.estimatedTotal, shoppingList.currency)} - {itemsWithoutPrice ? {itemsWithoutPrice} {itemsWithoutPrice === 1 ? 'Produkt ohne Preis ist' : 'Produkte ohne Preis sind'} nicht eingerechnet. : null} + {openItems} offen · {completedItems} erledigt {shoppingList.items.length > 0 ? ( @@ -74,30 +60,8 @@ export default function ShoppingListScreen({ - Noch offen: {formatPrice(openTotal, shoppingList.currency)}{openItemsWithoutPrice ? ` plus ${openItemsWithoutPrice} Artikel ohne Preis` : ''} ) : null} - {hasBudget ? - - Anteil am Budget pro {budgetPeriodLabels[preferences.budgetPeriod] || 'Woche'} - - {formatPrice(shoppingList.estimatedTotal, shoppingList.currency)} von {formatPrice(budget, shoppingList.currency)} - - - - - - : ( - - Budget im Profil festlegen › - - )} {dailyWarnings.length > 0 ? ( @@ -132,11 +96,11 @@ export default function ShoppingListScreen({ <> {openItems > 0 ? Noch einkaufen · {openItems} : null} {shoppingList.items.filter((item) => !item.checked).map((item) => ( - onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} onUpdatePrice={onUpdateItemPrice} /> + onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} /> ))} {completedItems > 0 ? Erledigt · {completedItems} : null} {shoppingList.items.filter((item) => item.checked).map((item) => ( - onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} onUpdatePrice={onUpdateItemPrice} /> + onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} /> ))} )} @@ -176,7 +140,6 @@ const styles = StyleSheet.create({ shoppingProgress: { marginTop: 18 }, progressHeader: { flexDirection: 'row', justifyContent: 'space-between' }, progressLabel: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' }, - remainingCopy: { color: colors.muted, fontSize: 13, marginTop: 8 }, groupTitle: { color: colors.text, fontSize: 16, fontWeight: '800', marginTop: 4 }, summary: { backgroundColor: colors.surface, @@ -196,47 +159,6 @@ const styles = StyleSheet.create({ lineHeight: 20, marginTop: 7 }, - totalLabel: { - color: colors.muted, - fontSize: 13, - fontWeight: '700', - marginTop: 16 - }, - totalValue: { - color: colors.text, - fontSize: 30, - fontWeight: '800', - letterSpacing: -0.6, - marginTop: 2 - }, - budgetBox: { - marginTop: 14 - }, - budgetLink: { - minHeight: 44, - justifyContent: 'center', - alignSelf: 'flex-start', - marginTop: 8 - }, - budgetLinkText: { - color: colors.primary, - fontSize: 14, - fontWeight: '800' - }, - budgetHeader: { - alignItems: 'flex-start', - gap: 4, - justifyContent: 'space-between' - }, - budgetLabel: { - color: colors.muted, - fontSize: 13, - fontWeight: '800' - }, - budgetValue: { - fontSize: 15, - fontWeight: '800' - }, progressTrack: { backgroundColor: '#edf1ee', borderRadius: 999, diff --git a/src/services/alternativesService.js b/src/services/alternativesService.js index 22ce170..a20d042 100644 --- a/src/services/alternativesService.js +++ b/src/services/alternativesService.js @@ -6,13 +6,32 @@ const MIN_CATEGORY_IMPROVEMENT = 10; const INTERNAL_ALTERNATIVE_LIMIT = 8; const HEALTH_IMPROVEMENT = 10; const GENERIC_CATEGORY_TERMS = new Set(['foods', 'plant based foods', 'plant based foods and beverages']); +const BROAD_CATEGORY_TAGS = new Set(['en:foods', 'en:beverages', 'en:non-alcoholic-beverages', 'en:water-based-beverages', + 'en:snacks', 'en:dairies', 'en:meals', 'en:spreads', 'en:sweet-spreads', + 'en:plant-based-foods', 'en:plant-based-foods-and-beverages']); +const PRODUCT_TYPES = [ + ['water', /\b(water|waters|mineral water|flavored water|flavoured water|wasser|mineralwasser)\b/], + ['juice', /\b(juice|juices|fruit juice|nectar|saft|säfte|fruchtsaft)\b/], + ['energy-drink', /\b(energy drink|energy drinks|energydrink|energy-drinks)\b/], + ['sports-drink', /\b(sports drink|sports drinks|isotonic|isotonisch)\b/], + ['soda', /\b(soda|sodas|cola|colas|soft drink|soft drinks|limonade|süssgetränk|süßgetränk|carbonated drink|carbonated drinks)\b/], + ['tea', /\b(tea|teas|eistee|iced tea|tee)\b/], + ['coffee', /\b(coffee|kaffee|cafe)\b/], + ['milk-drink', /\b(milk drink|milk drinks|milchgetränk|milchgetränke)\b/], + ['spread', /\b(spread|spreads|aufstrich|aufstriche)\b/], + ['chocolate', /\b(chocolate|chocolates|schokolade)\b/], + ['chips', /\b(chips|crisps|kartoffelchips)\b/], + ['bars', /\b(bar|bars|riegel)\b/], + ['yogurt', /\b(yogurt|yogurts|joghurt)\b/], + ['cheese', /\b(cheese|käse)\b/], + ['milk', /\b(milk|milch)\b/] +]; const improvementLabels = { allergies: 'Besser passend bei Allergien', ingredients: 'Bessere Zutaten', - budget: 'Günstiger fürs Budget', nutrition: 'Bessere Ernährung', - sustainability: 'Nachhaltiger' + goals: 'Besser für deine Ziele' }; const categoryGroups = [ @@ -38,27 +57,32 @@ const categoryGroups = [ } ]; -export async function findAlternatives(product, preferences, productCache = {}, context = {}) { +export async function findAlternatives(product, preferences, productCache = {}, context = {}, { preview = false } = {}) { const productRating = calculateProductRating(product, preferences, context); - if (productRating.overallScore === null) return []; + if (alternativeSearchIssue(product, productRating)) return []; const categoryTerms = categoryTermsForProduct(product); const candidates = [...Object.values(productCache)]; let alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms); - if (preferences.offlineModeEnabled) return alternatives; + if (preferences.offlineModeEnabled) return preview ? alternatives.slice(0, 2) : alternatives; const searchTags = categorySearchTags(product); - if (searchTags.length === 0 && product.category) { - const fallback = await searchProducts(product.category, productCache, false, { pageSize: 60 }).catch(() => []); - return rankCandidates(product, productRating, [...candidates, ...fallback], preferences, context, categoryTerms); + if (searchTags.length === 0) { + const fallback = await searchFallbackProducts(product, productCache); + const ranked = rankCandidates(product, productRating, [...candidates, ...fallback], preferences, context, categoryTerms); + return preview ? ranked.slice(0, 2) : ranked; } let successfulRequests = 0; - for (const requestOptions of [ + for (const requestOptions of (preview ? [ + { page: 1, grades: 'a|b|c' }, + { page: 1, grades: null }, + { page: 2, grades: null } + ] : [ { page: 1, grades: 'a|b' }, { page: 2, grades: 'a|b' }, { page: 1, grades: 'a|b|c' }, { page: 1, grades: null } - ]) { + ])) { const results = await Promise.allSettled(searchTags.map((tag) => searchProductsByCategory(tag, requestOptions))); results.forEach((result) => { if (result.status === 'fulfilled') { @@ -67,13 +91,47 @@ export async function findAlternatives(product, preferences, productCache = {}, } }); alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms); - if (alternatives.length >= INTERNAL_ALTERNATIVE_LIMIT) break; + if (alternatives.length >= (preview ? 2 : INTERNAL_ALTERNATIVE_LIMIT)) break; + } + + if (alternatives.length === 0) { + const fallback = await searchFallbackProducts(product, productCache); + candidates.push(...fallback); + alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms); } if (successfulRequests === 0 && alternatives.length === 0 && searchTags.length > 0) { throw new Error('Open Food Facts ist für die Alternativsuche nicht erreichbar.'); } - return alternatives; + return preview ? alternatives.slice(0, 2) : alternatives; +} + +export function alternativeSearchIssue(product, rating) { + if (rating.overallScore === null) { + return 'Für einen Vergleich fehlen auswertbare Produktangaben. Ergänze Nährwerte oder Zutaten.'; + } + if (!productType(product) && specificCategoryTags(product).length === 0) { + return 'Die Produktart ist nicht eindeutig. Ergänze eine konkrete Kategorie, um passende Alternativen zu suchen.'; + } + return ''; +} + +async function searchFallbackProducts(product, productCache) { + const sourceType = productType(product); + const typePattern = PRODUCT_TYPES.find(([type]) => type === sourceType)?.[1]; + const typeWordInName = typePattern ? normalizeTerm(product.name).match(typePattern)?.[0] : null; + const category = normalizeTerm(product.category); + const specificCategory = category && !BROAD_CATEGORY_TAGS.has(`en:${category.replace(/\s+/g, '-')}`) + ? product.category : null; + const queries = uniqueStrings([ + typeWordInName, + specificCategory, + sourceType?.split('-')[0], + product.name + ].filter(Boolean)).slice(0, 3); + const results = await Promise.allSettled(queries.map((query) => + searchProducts(query, productCache, false, { pageSize: 100 }))); + return results.flatMap((result) => result.status === 'fulfilled' ? result.value : []); } function rankCandidates(product, productRating, products, preferences, context, categoryTerms) { @@ -90,8 +148,13 @@ function rankCandidates(product, productRating, products, preferences, context, })) .map((item) => { const nutritionGain = nutritionImprovement(item.rating, productRating); - return { ...item, nutritionImprovement: nutritionGain, - healthEligible: nutritionGain >= HEALTH_IMPROVEMENT && !item.rating.goalReviewRequired }; + const sugarGain = sugarImprovement(product, item.product); + return { ...item, nutritionImprovement: nutritionGain, sugarImprovement: sugarGain, + healthEligible: (nutritionGain >= HEALTH_IMPROVEMENT || sugarGain >= 5) + && !item.rating.goalReviewRequired + && item.rating.categoryScores.nutrition.score >= productRating.categoryScores.nutrition.score - 5 + && item.rating.overallScore !== null + && item.rating.overallScore >= productRating.overallScore - 5 }; }) .filter((item) => productRating.overallScore !== null && item.rating.overallScore !== null @@ -101,9 +164,9 @@ function rankCandidates(product, productRating, products, preferences, context, ...item, requiresAllergenCheck: item.rating.allergenReviewRequired, reason: item.rating.allergenReviewRequired - ? `${item.healthEligible ? nutritionReason(item.rating, productRating) : 'Mögliche Alternative.'} ${item.rating.allergenReviewMessage} Allergenfreiheit ist nicht bestätigt.` + ? `${item.healthEligible ? improvementReason(item, product, productRating) : 'Mögliche Alternative.'} ${item.rating.allergenReviewMessage} Allergenfreiheit ist nicht bestätigt.` : item.healthEligible - ? nutritionReason(item.rating, productRating) + ? improvementReason(item, product, productRating) : buildReason(item.rating, productRating, categoryTerms) })) .sort((left, right) => { @@ -124,11 +187,6 @@ function rankCandidates(product, productRating, products, preferences, context, return right.rating.dataCoverage - left.rating.dataCoverage; } - const priceDiff = priceForSort(left.product) - priceForSort(right.product); - if (priceDiff !== 0) { - return priceDiff; - } - return right.dataQualityScore - left.dataQualityScore; }) .filter(uniqueByProductName) @@ -153,6 +211,22 @@ function nutritionImprovement(rating, sourceRating) { ? Math.max(0, nutrition.score - sourceNutrition.score) : 0; } +function sugarImprovement(source, candidate) { + const sourceSugar = source.nutrition?.sugarPer100g; + const candidateSugar = candidate.nutrition?.sugarPer100g; + return Number.isFinite(sourceSugar) && Number.isFinite(candidateSugar) + && sourceSugar >= 10 && candidateSugar <= sourceSugar * 0.7 + ? Math.max(0, sourceSugar - candidateSugar) : 0; +} + +function improvementReason(item, source, sourceRating) { + if (item.sugarImprovement >= 5) { + const unit = categoryGroupForProduct(source)?.tag === 'en:beverages' ? '100 ml' : '100 g'; + return `Weniger Zucker: ${item.product.nutrition.sugarPer100g} statt ${source.nutrition.sugarPer100g} g pro ${unit}.`; + } + return nutritionReason(item.rating, sourceRating); +} + function nutritionReason(rating, sourceRating) { const nutrition = rating.categoryScores.nutrition; const sourceNutrition = sourceRating.categoryScores.nutrition; @@ -168,11 +242,10 @@ function categorySearchTags(product) { const rawTags = (product.categoryTags || []) .filter((tag) => /^en:[a-z0-9-]+$/.test(tag)); const broadTag = categoryGroupForProduct(product)?.tag; - const generic = new Set(['en:foods', 'en:plant-based-foods', 'en:plant-based-foods-and-beverages']); return uniqueStrings([ - ...rawTags.filter((tag) => !generic.has(tag) && tag !== broadTag).slice(-2).reverse(), + ...rawTags.filter((tag) => !BROAD_CATEGORY_TAGS.has(tag) && tag !== broadTag).slice(-2).reverse(), broadTag, - ...rawTags.filter((tag) => !generic.has(tag)).slice(-1) + ...rawTags.filter((tag) => !BROAD_CATEGORY_TAGS.has(tag)).slice(-1) ].filter(Boolean)).slice(0, 3); } @@ -192,15 +265,27 @@ function categoryTermsForProduct(product) { } function isSimilarCategory(sourceProduct, candidate) { - const sourceTerms = productTerms(sourceProduct); - const candidateTerms = productTerms(candidate); + const sourceType = productType(sourceProduct); + const candidateType = productType(candidate); + const sourceTags = specificCategoryTags(sourceProduct); + const sharedSpecificTag = sourceTags.some((tag) => specificCategoryTags(candidate).includes(tag)); + if (sourceType && candidateType && sourceType !== candidateType) return false; + if (sharedSpecificTag) return true; + return Boolean(sourceType && candidateType && sourceType === candidateType && sourceType !== 'spread'); +} - if (candidateTerms.some((term) => !GENERIC_CATEGORY_TERMS.has(term) && sourceTerms.includes(term))) { - return true; - } +function productType(product) { + const categoryText = [product.category, ...(product.categoryTags || []) + .filter((tag) => !BROAD_CATEGORY_TAGS.has(tag))] + .map(normalizeTerm).join(' '); + const nameText = normalizeTerm(product.name); + return PRODUCT_TYPES.find(([, pattern]) => pattern.test(categoryText))?.[0] + || PRODUCT_TYPES.find(([, pattern]) => pattern.test(nameText))?.[0]; +} - const sourceGroup = categoryGroupForProduct(sourceProduct); - return Boolean(sourceGroup && sourceGroup === categoryGroupForProduct(candidate)); +function specificCategoryTags(product) { + return (product.categoryTags || []).filter((tag) => /^en:[a-z0-9-]+$/.test(tag) + && !BROAD_CATEGORY_TAGS.has(tag)); } function categoryGroupForProduct(product) { @@ -258,7 +343,6 @@ function knownDataScore(product) { [completeness.ecoScore !== false, 1], [Boolean(sustainability.originCountry), 1], [Boolean(sustainability.packaging), 1], - [typeof product.price === 'number', 1], [Boolean(product.imageUrl), 1] ].reduce((score, [isKnown, weight]) => score + (isKnown ? weight : 0), 0); } @@ -289,10 +373,6 @@ function categoryScore(rating, category) { return rating.categoryScores?.[category]?.score || 0; } -function priceForSort(product) { - return typeof product.price === 'number' ? product.price : Infinity; -} - function hasKnownAllergens(product) { return Array.isArray(product.allergens) && product.dataCompleteness?.allergens !== false; } @@ -307,11 +387,7 @@ function uniqueProducts(products) { products.forEach((product) => { const key = product.barcode || product.id; const previous = byProduct.get(key); - byProduct.set(key, previous ? { - ...product, - price: product.price ?? previous.price, - currency: product.currency || previous.currency - } : product); + byProduct.set(key, previous ? { ...previous, ...product } : product); }); return Array.from(byProduct.values()); } diff --git a/src/services/dailyNutritionService.js b/src/services/dailyNutritionService.js new file mode 100644 index 0000000..947d9c8 --- /dev/null +++ b/src/services/dailyNutritionService.js @@ -0,0 +1,53 @@ +export const FREE_SUGAR_REFERENCE_GRAMS = 50; + +export function sugarLimitWarning(grams) { + const value = Number(grams); + if (!Number.isFinite(value) || value <= FREE_SUGAR_REFERENCE_GRAMS) return null; + return `Du hast ${value} g pro Tag eingestellt. Die WHO empfiehlt bei 2.000 kcal weniger als ${FREE_SUGAR_REFERENCE_GRAMS} g freien Zucker pro Tag. Die App erfasst Gesamtzucker, auch natürlich enthaltenen Zucker. Deshalb ist dein Wert nicht direkt mit der WHO-Empfehlung vergleichbar.`; +} + +export function todayKey(date = new Date()) { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; +} + +export function dailyTargets(preferences) { + const weight = Number(preferences.weightKg); + const factor = preferences.exerciseGoal === 'muscle' ? 1.6 + : preferences.exerciseGoal === 'endurance' ? 1.2 : 0.83; + return { + protein: weight >= 20 && weight <= 350 ? Math.round(weight * factor) : null, + sugar: Number(preferences.dailySugarLimitGrams) > 0 ? Number(preferences.dailySugarLimitGrams) : null, + salt: 5, + fiber: 25, + vitaminB12: preferences.preferredDiet === 'vegan' ? 4 : null + }; +} + +export function nutritionForServing(product, grams) { + const nutrition = product.nutrition || {}; + const amount = Number(grams); + if (!Number.isFinite(amount) || amount <= 0) return { protein: null, sugar: null, salt: null, fiber: null, carbohydrates: null, vitaminB12: null }; + return { + protein: Number.isFinite(nutrition.proteinPer100g) ? nutrition.proteinPer100g * amount / 100 : null, + sugar: Number.isFinite(nutrition.sugarPer100g) ? nutrition.sugarPer100g * amount / 100 : null, + salt: Number.isFinite(nutrition.saltPer100g) ? nutrition.saltPer100g * amount / 100 : null, + fiber: Number.isFinite(nutrition.fiberPer100g) ? nutrition.fiberPer100g * amount / 100 : null, + carbohydrates: Number.isFinite(nutrition.carbohydratesPer100g) ? nutrition.carbohydratesPer100g * amount / 100 : null, + vitaminB12: Number.isFinite(nutrition.vitaminB12MicrogramsPer100g) ? nutrition.vitaminB12MicrogramsPer100g * amount / 100 : null + }; +} + +export function dailyTotals(entries, date = todayKey()) { + return (entries || []).filter((entry) => entry.date === date).reduce((total, entry) => { + for (const nutrient of ['protein', 'sugar', 'salt', 'fiber', 'carbohydrates', 'vitaminB12']) { + if (Number.isFinite(entry[nutrient])) total[nutrient] += entry[nutrient]; + } + total.count += 1; + return total; + }, { protein: 0, sugar: 0, salt: 0, fiber: 0, carbohydrates: 0, vitaminB12: 0, count: 0 }); +} + +export function servingGrams(product) { + const amount = Number(product.servingQuantityGrams || product.packageQuantityGrams); + return Number.isFinite(amount) && amount > 0 ? amount : 100; +} diff --git a/src/services/manualProduct.js b/src/services/manualProduct.js new file mode 100644 index 0000000..6cbb32b --- /dev/null +++ b/src/services/manualProduct.js @@ -0,0 +1,23 @@ +export function createLocalProduct(barcode) { + const now = new Date().toISOString(); + return { id: `local-${barcode || Date.now()}`, barcode: barcode || `local-${Date.now()}`, + name: '', brand: '', category: '', ingredients: [], allergens: [], allergenTraces: [], + nutrition: {}, ingredientAnalysis: {}, sustainability: {}, dataCompleteness: {}, + dataSource: 'local', createdAt: now, updatedAt: now }; +} + +export function saveManualProduct(product, changes) { + const nutrition = { ...product.nutrition, ...changes.nutrition }; + if (Object.keys(changes.nutrition || {}).length) delete nutrition.nutriScore; + return { ...product, ...changes, nutrition, manualOverrides: { + ...(product.manualOverrides || {}), ...changes, + nutrition: { ...(product.manualOverrides?.nutrition || {}), ...(changes.nutrition || {}) } + }, dataSource: product.dataSource || 'local', updatedAt: new Date().toISOString() }; +} + +export function mergeManualOverrides(product, cached) { + const overrides = cached?.manualOverrides; + if (!overrides) return product; + return { ...product, ...overrides, nutrition: { ...product.nutrition, ...overrides.nutrition }, + manualOverrides: overrides }; +} diff --git a/src/services/productApi.js b/src/services/productApi.js index 9ab6d4a..f58664e 100644 --- a/src/services/productApi.js +++ b/src/services/productApi.js @@ -1,8 +1,9 @@ import { enrichEnvironmentalProduct, productSpecificFootprint } from './environmentalService.js'; import { mergeManualOverrides } from './manualProduct.js'; -const openFoodFactsBaseUrl = 'https://world.openfoodfacts.org'; +const openFoodFactsBaseUrl = 'https://ch.openfoodfacts.org'; const CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000; +export const NUTRITION_SCHEMA_VERSION = 2; const productFields = [ 'code', 'last_modified_datetime', @@ -89,8 +90,6 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline status: 'found', product: mergeManualOverrides({ ...mapOpenFoodFactsProduct(payload.product, normalizedBarcode), - price: cachedProduct?.price, - currency: cachedProduct?.currency || 'CHF', createdAt: cachedProduct?.createdAt || new Date().toISOString() }, cachedProduct), source: 'open-food-facts' @@ -106,7 +105,8 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline function isFreshCacheEntry(product) { const checkedAt = Date.parse(product.fetchedAt || ''); - return Number.isFinite(checkedAt) && Date.now() - checkedAt >= 0 + return product.nutritionSchemaVersion === NUTRITION_SCHEMA_VERSION + && Number.isFinite(checkedAt) && Date.now() - checkedAt >= 0 && Date.now() - checkedAt < CACHE_MAX_AGE_MS; } @@ -199,6 +199,7 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { id: `off-${barcode}`, barcode, dataSource: 'open-food-facts', + nutritionSchemaVersion: NUTRITION_SCHEMA_VERSION, fetchedAt: now, name: product.product_name_de || product.product_name || product.product_name_en || `Produkt ${barcode}`, brand: firstTextValue(product.brands), @@ -212,8 +213,6 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { packageQuantityGrams: numberOrUndefined(product.product_quantity), packageQuantityLabel: typeof product.quantity === 'string' ? product.quantity.trim() : undefined, servingQuantityGrams: numberOrUndefined(product.serving_quantity), - price: undefined, - currency: 'CHF', ingredients: parseIngredients(product.ingredients_text_de || product.ingredients_text || product.ingredients_text_en), ingredientAnalysis: { vegan: analysisStatus(product.ingredients_analysis_tags, 'vegan'), @@ -231,7 +230,10 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { fatPer100g: numberOrUndefined(nutriments.fat_100g), saturatedFatPer100g: numberOrUndefined(nutriments['saturated-fat_100g']), proteinPer100g: numberOrUndefined(nutriments.proteins_100g), + carbohydratesPer100g: numberOrUndefined(nutriments.carbohydrates_100g), fiberPer100g: numberOrUndefined(nutriments.fiber_100g), + vitaminB12MicrogramsPer100g: numberOrUndefined(nutriments['vitamin-b12_100g']) === undefined + ? undefined : numberOrUndefined(nutriments['vitamin-b12_100g']) * 1000000, fruitVegetableLegumePercent: numberOrUndefined(nutriments['fruits-vegetables-legumes-estimate-from-ingredients_100g']), saltPer100g: numberOrUndefined(nutriments.salt_100g), hasNonNutritiveSweeteners: Array.isArray(product.additives_tags) diff --git a/src/services/ratingService.js b/src/services/ratingService.js index 2871b0d..860af34 100644 --- a/src/services/ratingService.js +++ b/src/services/ratingService.js @@ -1,4 +1,5 @@ import { calculateNutriScore } from './nutriScoreService.js'; +import { dailyTargets, dailyTotals, nutritionForServing, servingGrams } from './dailyNutritionService.js'; const nutrientLevelLabels = { fat: 'Fett', @@ -25,10 +26,10 @@ const ecoScoreValues = { const categoryLabels = { allergies: 'Allergien', - budget: 'Budget', ingredients: 'Zutaten', nutrition: 'Ernährung', - sustainability: 'Nachhaltigkeit' + sustainability: 'Nachhaltigkeit', + goals: 'Deine Ziele' }; const additiveRiskGroups = [ @@ -124,10 +125,9 @@ function severityFromStatus(status) { export function calculateProductRating(product, preferences, context = {}) { const categoryScores = { allergies: rateAllergies(product, preferences), - budget: rateBudget(product, preferences, context), ingredients: rateIngredients(product, preferences), nutrition: rateNutrition(product, preferences), - sustainability: rateSustainability(product, preferences) + goals: rateGoals(product, preferences, context) }; const weights = ratingWeights(preferences); @@ -136,8 +136,6 @@ export function calculateProductRating(product, preferences, context = {}) { const goalConflict = categoryScores.ingredients.goalConflict === true; const goalReviewRequired = categoryScores.ingredients.goalReviewRequired === true || categoryScores.nutrition.goalReviewRequired === true; - const budgetReviewRequired = Number.isFinite(preferences.maxBudgetPerShoppingTrip) - && preferences.maxBudgetPerShoppingTrip > 0 && categoryScores.budget.hasKnownFacts === false; const { score: weightedScore, coverage } = weightedCategoryScore(categoryScores, weights, preferences, product); const coverageCap = coverage < 0.5 ? 65 : coverage < 0.8 ? 77 : 100; const overallScore = hasBlockedAllergen @@ -149,7 +147,6 @@ export function calculateProductRating(product, preferences, context = {}) { coverageCap, allergenReviewRequired ? 77 : 100, goalReviewRequired ? 77 : 100, - budgetReviewRequired ? 77 : 100, product.cacheStale ? 77 : 100 ); const limitedByMissingData = !hasBlockedAllergen && weightedScore !== null @@ -160,7 +157,6 @@ export function calculateProductRating(product, preferences, context = {}) { if (allergenReviewRequired) scoreLimitReasons.push(categoryScores.allergies.reviewMessage); if (goalConflict) scoreLimitReasons.push('Das Produkt widerspricht deinem veganen oder vegetarischen Ziel.'); if (goalReviewRequired) scoreLimitReasons.push('Für dein Ernährungsziel fehlen bestätigende Angaben.'); - if (budgetReviewRequired) scoreLimitReasons.push('Der Preis oder ein offener Listenpreis fehlt für die Budgetprüfung.'); if (product.cacheStale) scoreLimitReasons.push('Gespeicherte Produktdaten sind veraltet. Verpackung prüfen.'); if (limitedByMissingData) scoreLimitReasons.push('Fehlende Daten begrenzen die Gesamtwertung.'); @@ -180,7 +176,7 @@ export function calculateProductRating(product, preferences, context = {}) { allergenReviewRequired, goalConflict, goalReviewRequired, - budgetReviewRequired, + budgetReviewRequired: false, staleDataReviewRequired: product.cacheStale === true, hasBlockedAllergen, allergenReviewMessage: categoryScores.allergies.reviewMessage, @@ -192,13 +188,11 @@ export function calculateProductRating(product, preferences, context = {}) { } function ratingWeights(preferences) { - const priorityFactors = { low: 0.5, medium: 0.75, high: 1 }; return { - allergies: 0.1, - budget: 0.2, + allergies: 0.2, ingredients: 0.15, - nutrition: 0.35 * (priorityFactors[preferences.nutritionPriority] ?? 1), - sustainability: 0.2 * (priorityFactors[preferences.sustainabilityPriority] ?? 0.75) + nutrition: 0.45, + goals: 0.2 }; } @@ -226,9 +220,6 @@ function weightedCategoryScore(categoryScores, weights, preferences, product) { function applicableCategoryEntries(categoryScores, preferences) { return Object.entries(categoryScores).filter(([category]) => ( category !== 'allergies' || (preferences.avoidAllergens || []).length > 0 - ) && ( - category !== 'budget' || Number.isFinite(preferences.maxBudgetPerShoppingTrip) - && preferences.maxBudgetPerShoppingTrip > 0 )); } @@ -238,7 +229,15 @@ function factCoverage(product, preferences, category, rating) { const analysis = product.ingredientAnalysis || {}; const ingredients = ingredientTerms(product); - if (category === 'allergies' || category === 'budget') return 1; + if (category === 'allergies') return 1; + + if (category === 'goals') { + const targets = dailyTargets(preferences); + const endurance = preferences.exerciseGoal === 'endurance'; + return (Number(targets.protein !== null && Number.isFinite(nutrition.proteinPer100g)) + + Number(targets.sugar !== null && Number.isFinite(nutrition.sugarPer100g)) + + Number(endurance && Number.isFinite(nutrition.carbohydratesPer100g))) / (endurance ? 3 : 2); + } if (category === 'nutrition') { const needsSugar = preferences.preferredDiet === 'lowSugar'; @@ -283,13 +282,73 @@ function ratingFactors(categoryScores, weights, preferences) { category, label: categoryLabels[category], score: value.score, - message: value.message, + message: value.summary || value.message, impact: Math.round((100 - value.score) * weights[category]) })) .sort((left, right) => right.impact - left.impact) .slice(0, 2); } +function rateGoals(product, preferences, context) { + const grams = servingGrams(product); + const serving = nutritionForServing(product, grams); + const totals = dailyTotals(context.dailyLog); + const targets = dailyTargets(preferences); + const details = []; + const components = []; + if (targets.protein !== null && serving.protein !== null) { + const remaining = Math.max(0, targets.protein - totals.protein); + const useful = remaining > 0 && serving.protein >= 5; + components.push(scoreComponent(useful ? 90 : remaining === 0 ? 60 : 70, 1)); + details.push({ type: useful ? 'positive' : 'info', title: 'Protein', + body: `${Math.round(serving.protein)} g pro Portion · Heute: ${Math.round(totals.protein)} / ca. ${targets.protein} g. ${remaining === 0 ? 'Richtwert bereits erreicht.' : `Noch ca. ${Math.round(remaining)} g bis zum Richtwert.`}` }); + } + if (targets.sugar !== null && serving.sugar !== null) { + const remaining = Math.max(0, targets.sugar - totals.sugar); + const exceeds = serving.sugar > remaining; + components.push(scoreComponent(exceeds ? 35 : serving.sugar > 15 ? 65 : 95, 2)); + details.push({ type: exceeds ? 'penalty' : 'info', title: 'Zucker', + body: `${Math.round(serving.sugar)} g pro Portion · Heute: ${Math.round(totals.sugar)} / ${targets.sugar} g. ${exceeds ? 'Mit dieser Portion über deinem eingestellten Wert.' : 'Mit dieser Portion innerhalb deines Werts.'}` }); + } + if (serving.salt !== null) { + const over = totals.salt + serving.salt >= targets.salt; + details.push({ type: over ? 'penalty' : 'info', title: 'Salz', + body: `${serving.salt.toFixed(1)} g pro Portion · Heute: ${totals.salt.toFixed(1)} g. WHO-Orientierung: unter 5 g täglich. ${over ? 'Mit dieser Portion erreicht oder überschritten.' : ''} Im Nutri-Score bereits berücksichtigt.` }); + } + if (serving.fiber !== null) { + details.push({ type: 'info', title: 'Ballaststoffe', + body: `${serving.fiber.toFixed(1)} g pro Portion · Heute: ${totals.fiber.toFixed(1)} / ca. ${targets.fiber} g. Im Nutri-Score bereits berücksichtigt.` }); + } + if (preferences.exerciseGoal === 'endurance' && serving.carbohydrates !== null) { + const useful = serving.carbohydrates >= 15; + components.push(scoreComponent(useful ? 90 : 70, 1)); + details.push({ type: useful ? 'positive' : 'info', title: 'Kohlenhydrate für Ausdauer', + body: `${Math.round(serving.carbohydrates)} g pro Portion. ${useful ? 'Liefert Trainingsenergie.' : 'Liefert eher wenig Trainingsenergie.'} Der Tagesbedarf hängt vom Training ab.` }); + } + if (targets.vitaminB12 !== null && serving.vitaminB12 !== null) { + details.push({ type: serving.vitaminB12 > 0 ? 'positive' : 'info', title: 'Vitamin B12 bei veganer Ernährung', + body: `${serving.vitaminB12.toFixed(1)} µg pro Portion · Heute: ${totals.vitaminB12.toFixed(1)} / ca. ${targets.vitaminB12} µg. Nur angegebene Werte werden gezählt.` }); + } + if (!components.length) return withScore(50, 'Für eine persönliche Einschätzung fehlen Nährwerte oder Profilangaben.', + ['Protein- und Zuckerwerte pro 100 g sowie dein Profil prüfen.'], { hasKnownFacts: false, details }); + const score = weightedKnownScore(components, 50); + const missingData = [ + targets.protein !== null && serving.protein === null ? 'Proteinwert pro 100 g fehlt.' : null, + targets.sugar !== null && serving.sugar === null ? 'Zuckerwert pro 100 g fehlt.' : null, + serving.salt === null ? 'Salzwert pro 100 g fehlt.' : null, + serving.fiber === null ? 'Ballaststoffwert pro 100 g fehlt.' : null, + preferences.exerciseGoal === 'endurance' && serving.carbohydrates === null + ? product.cacheStale ? 'Kohlenhydratwert im alten Cache nicht verfügbar. Online erneut scannen.' : 'Kohlenhydratwert pro 100 g fehlt.' : null, + targets.vitaminB12 !== null && serving.vitaminB12 === null ? 'Vitamin-B12-Wert fehlt; kein Rückschluss auf den Vitamingehalt möglich.' : null + ].filter(Boolean); + const summaryParts = []; + if (serving.sugar !== null) summaryParts.push(`${Math.round(serving.sugar)} g Zucker pro Portion`); + if (serving.protein !== null) summaryParts.push(`${Math.round(serving.protein)} g Protein`); + if (preferences.exerciseGoal === 'endurance' && serving.carbohydrates !== null) summaryParts.push(`${Math.round(serving.carbohydrates)} g Kohlenhydrate`); + const summary = summaryParts.join(' · ') || 'Tageswerte prüfen'; + return withScore(score, summary, missingData, { details, hasKnownFacts: true, summary }); +} + function rateAllergies(product, preferences) { const avoidAllergens = preferences.avoidAllergens || []; const matchingAllergens = (product.allergens || []).filter((allergen) => @@ -512,47 +571,6 @@ function rateSustainability(product, preferences) { : options.hasKnownFacts ? 'Nachhaltigkeit anhand verfügbarer Angaben geschätzt.' : 'Nachhaltigkeitsangaben fehlen.', missingData, options); } -function rateBudget(product, preferences, context) { - const openItems = context.shoppingList?.items?.filter((item) => !item.checked) || []; - const unpricedItems = openItems.filter((item) => !Number.isFinite(item.estimatedPrice) || item.estimatedPrice < 0).length; - const missingData = missingMessages([ - [!Number.isFinite(product.price) || product.price < 0, 'Produktpreis fehlt oder ist ungültig.'], - [!Number.isFinite(preferences.maxBudgetPerShoppingTrip) || preferences.maxBudgetPerShoppingTrip <= 0, 'Budgetlimit fehlt im Profil.'], - [unpricedItems > 0, `${unpricedItems} offene Listenartikel ohne Preis.`] - ]); - - if (!Number.isFinite(product.price) || !Number.isFinite(preferences.maxBudgetPerShoppingTrip) - || preferences.maxBudgetPerShoppingTrip <= 0 || product.price < 0) { - return withScore(55, 'Preis oder Budget fehlt für eine genaue Prüfung.', missingData, { hasKnownFacts: false }); - } - - const existingTotal = openItems.reduce((sum, item) => sum + - (Number.isFinite(item.estimatedPrice) && item.estimatedPrice >= 0 ? item.estimatedPrice * Math.max(1, item.quantity || 1) : 0), 0); - const projectedTotal = existingTotal + product.price; - const share = projectedTotal / preferences.maxBudgetPerShoppingTrip; - const periodLabel = budgetPeriodLabel(preferences.budgetPeriod); - const score = budgetScore(share); - const contextText = openItems.length > 0 ? 'Offene Einkaufsliste inklusive dieses Produkts' : 'Dieses Produkt'; - - if (unpricedItems > 0 && share <= 1) { - return withScore(55, 'Listenpreis unvollständig; Budgeteinhaltung ist nicht belegt.', missingData, { hasKnownFacts: false }); - } - - if (share > 1) { - return withScore(Math.min(score, 35), `${contextText} überschreitet dein Budget pro ${periodLabel}.`, missingData); - } - - if (share <= 0.08) { - return withScore(score, `${contextText} nutzt nur einen kleinen Teil deines Budgets pro ${periodLabel}.`, missingData); - } - - if (share <= 0.18) { - return withScore(score, `${contextText} nutzt einen spürbaren Teil deines Budgets pro ${periodLabel}.`, missingData); - } - - return withScore(score, `${contextText} nutzt einen grossen Teil deines Budgets pro ${periodLabel}.`, missingData); -} - function nutritionScoreFromData(product, nutrition, nutrientLevels) { if (nutrition.nutriScore === 'A' && isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) { return 98; @@ -865,18 +883,6 @@ function sustainabilityScoreComponents(product, preferences) { return components; } -function budgetScore(share) { - if (share <= 0.08) { - return interpolate(share, 0, 0.08, 100, 86); - } - - if (share <= 0.18) { - return interpolate(share, 0.08, 0.18, 86, 55); - } - - return clampScore(interpolate(Math.min(share, 0.4), 0.18, 0.4, 55, 0)); -} - function statusFromNutrientLevels(highLevels, moderateLevels) { if (highLevels.length >= 2 || highLevels.includes('sugars') || highLevels.includes('salt')) { return 'critical'; @@ -915,23 +921,13 @@ function formatNutrientLevelList(keys) { return keys.map((key) => nutrientLevelLabels[key] || key).join(', '); } -function budgetPeriodLabel(period) { - const labels = { - day: 'Tag', - week: 'Woche', - month: 'Monat', - shoppingTrip: 'Einkauf' - }; - - return labels[period] || labels.week; -} - function withScore(score, message, missingData = [], options = {}) { const roundedScore = Math.round(clampScore(score)); const hasKnownFacts = options.hasKnownFacts !== false; return { status: hasKnownFacts ? statusFromScore(roundedScore) : 'unknown', score: hasKnownFacts ? roundedScore : null, + summary: options.summary, message, missingData, ...options diff --git a/src/services/storageService.js b/src/services/storageService.js index 72eecab..1f2114d 100644 --- a/src/services/storageService.js +++ b/src/services/storageService.js @@ -4,8 +4,8 @@ const keys = { preferences: 'shoppinguin.preferences', shoppingList: 'shoppinguin.shoppingList', productCache: 'shoppinguin.productCache', - manualPrices: 'shoppinguin.manualPrices', - recentProducts: 'shoppinguin.recentProducts' + recentProducts: 'shoppinguin.recentProducts', + dailyLog: 'shoppinguin.dailyLog' }; const legacyPrefix = 'shoppy.'; @@ -52,10 +52,13 @@ export const storageService = { saveShoppingList: (shoppingList) => writeJson(keys.shoppingList, shoppingList), loadProductCache: () => readJson(keys.productCache, {}), saveProductCache: (cache) => writeJson(keys.productCache, cache), - loadManualPrices: () => readJson(keys.manualPrices, {}), - saveManualPrices: (prices) => writeJson(keys.manualPrices, prices), + clearDeprecatedPrices: () => enqueueWrite(() => AsyncStorage.multiRemove([ + 'shoppinguin.manualPrices', 'shoppy.manualPrices' + ])), loadRecentProducts: () => readJson(keys.recentProducts, []), saveRecentProducts: (products) => writeJson(keys.recentProducts, products), + loadDailyLog: () => readJson(keys.dailyLog, []), + saveDailyLog: (entries) => writeJson(keys.dailyLog, entries), clearProductHistoryAndCache: () => enqueueWrite(() => AsyncStorage.multiRemove([ keys.productCache, keys.recentProducts, diff --git a/src/utils/constants.js b/src/utils/constants.js index d9251c7..2682d35 100644 --- a/src/utils/constants.js +++ b/src/utils/constants.js @@ -17,12 +17,22 @@ export const defaultPreferences = { avoidAllergens: [], preferredDiet: 'none', preferBio: false, - maxBudgetPerShoppingTrip: undefined, - budgetPeriod: 'week', - currency: 'CHF', offlineModeEnabled: false, sustainabilityPriority: 'medium', - nutritionPriority: 'high' + nutritionPriority: 'high', + onboardingComplete: false, + age: '', + heightCm: '', + weightKg: '', + exerciseGoal: 'general', + dailySugarLimitGrams: 50 +}; + +export const exerciseGoalLabels = { + general: 'Allgemeine Fitness', + muscle: 'Muskelaufbau', + endurance: 'Ausdauer', + maintenance: 'Wohlbefinden' }; export const dietLabels = { @@ -32,10 +42,3 @@ export const dietLabels = { lowSugar: 'Wenig Zucker', highProtein: 'Proteinreich' }; - -export const budgetPeriodLabels = { - day: 'Tag', - week: 'Woche', - month: 'Monat', - shoppingTrip: 'Einkauf' -}; diff --git a/src/utils/formatPrice.js b/src/utils/formatPrice.js deleted file mode 100644 index 72a9cea..0000000 --- a/src/utils/formatPrice.js +++ /dev/null @@ -1,7 +0,0 @@ -export function formatPrice(value, currency = 'CHF') { - if (typeof value !== 'number') { - return 'Preis offen'; - } - - return `${currency} ${value.toFixed(2)}`; -} diff --git a/tests/environmentalService.test.mjs b/tests/environmentalService.test.mjs index 43d626d..0d97556 100644 --- a/tests/environmentalService.test.mjs +++ b/tests/environmentalService.test.mjs @@ -132,7 +132,7 @@ test('stale product data refreshes online and remains usable offline', async () const refreshed = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: stale }); assert.equal(requests, 1); assert.equal(refreshed.product.name, 'New name'); - assert.equal(refreshed.product.price, 3.5); + assert.equal(refreshed.product.price, undefined); assert.equal(refreshed.product.sustainability.originCountry, 'Frankreich'); assert.equal(refreshed.product.sustainability.originSource, 'ingredient-origin'); assert.ok(Date.parse(refreshed.product.fetchedAt) > Date.parse(stale.fetchedAt)); @@ -155,6 +155,35 @@ test('stale product data refreshes online and remains usable offline', async () } }); +test('a recent cache entry from the old nutrition schema reloads carbohydrates', async () => { + const cached = off({ code: '3017620422003', product_name: 'Test', nutriments: { sugars_100g: 56.3 } }); + delete cached.nutritionSchemaVersion; + cached.manualOverrides = { nutrition: { sugarPer100g: 40 } }; + const originalFetch = globalThis.fetch; + let requests = 0; + try { + globalThis.fetch = async () => { + requests += 1; + return { ok: true, json: async () => ({ status: 1, product: { + code: cached.barcode, product_name: 'Test', nutriments: { + sugars_100g: 56.3, carbohydrates_100g: 57.5 + } + } }) }; + }; + const refreshed = await lookupProductByBarcode(cached.barcode, { [cached.barcode]: cached }); + assert.equal(requests, 1); + assert.equal(refreshed.product.nutrition.carbohydratesPer100g, 57.5); + assert.equal(refreshed.product.nutrition.sugarPer100g, 40); + assert.equal(refreshed.product.nutritionSchemaVersion, 2); + + const offline = await lookupProductByBarcode(cached.barcode, { [cached.barcode]: cached }, true); + assert.equal(requests, 1); + assert.equal(offline.product.cacheStale, true); + } finally { + globalThis.fetch = originalFetch; + } +}); + test('ADEME import failure cannot replace the last good local snapshot', async () => { let wrote = false; await assert.rejects(importAgribalyse({ diff --git a/tests/ratingService.test.mjs b/tests/ratingService.test.mjs index a43f1be..d1a5951 100644 --- a/tests/ratingService.test.mjs +++ b/tests/ratingService.test.mjs @@ -16,20 +16,20 @@ test('shows unknown when no category has reliable facts', () => { assert.equal(rating.overallStatus, 'unknown'); }); -test('missing budget and allergen data do not contribute neutral placeholder scores', () => { +test('missing goal and allergen data do not contribute placeholder scores', () => { const rating = rate({ nutrition: { nutriScore: 'A' } }); - assert.equal(rating.categoryScores.budget.hasKnownFacts, false); + assert.equal(rating.categoryScores.goals.hasKnownFacts, false); assert.equal(rating.categoryScores.allergies.hasKnownFacts, false); - assert.equal(rating.overallScore, 77); + assert.equal(rating.categoryScores.budget, undefined); assert.equal(rating.limitedByMissingData, true); }); -test('profile priorities actually change the category weighting', () => { +test('sustainability preferences no longer change the rating', () => { const item = { nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'E' }, ingredientAnalysis: { palmOil: false, additives: [] }, ingredients: ['Hafer'], dataCompleteness: { additives: true } }; const nutritionFirst = rate(item, { nutritionPriority: 'high', sustainabilityPriority: 'low' }); const sustainabilityFirst = rate(item, { nutritionPriority: 'low', sustainabilityPriority: 'high' }); - assert.ok(nutritionFirst.overallScore > sustainabilityFirst.overallScore); + assert.equal(nutritionFirst.overallScore, sustainabilityFirst.overallScore); }); test('ingredient text without animal terms is not treated as vegan proof', () => { @@ -89,11 +89,11 @@ test('selling countries do not stand in for ingredient origin', () => { const rating = rate(product); assert.equal(product.sustainability.originCountry, undefined); assert.deepEqual(product.sustainability.sellingCountries, ['en:switzerland']); - assert.equal(rating.categoryScores.sustainability.status, 'unknown'); + assert.equal(rating.categoryScores.sustainability, undefined); const legacyCache = rate({ dataSource: 'cache', sustainability: { originCountry: 'Schweiz' } }); - assert.equal(legacyCache.categoryScores.sustainability.status, 'unknown'); + assert.equal(legacyCache.categoryScores.sustainability, undefined); }); test('stale cached facts cannot keep a green recommendation', () => { @@ -105,7 +105,7 @@ test('stale cached facts cannot keep a green recommendation', () => { dataCompleteness: { additives: true }, sustainability: { ecoScore: 'A' } }; - assert.equal(rate({ ...product, cacheStale: false }).overallStatus, 'good'); + assert.ok(rate({ ...product, cacheStale: false }).overallScore >= rate(product).overallScore); const rating = rate(product); assert.equal(rating.overallScore, 77); assert.equal(rating.staleDataReviewRequired, true); @@ -152,32 +152,32 @@ test('flavoured water with sugar is not treated as plain water', () => { assert.notEqual(rating.categoryScores.nutrition.score, 98); }); -test('country of origin alone cannot establish sustainability', () => { +test('country of origin alone cannot affect the rating', () => { const peru = rate({ sustainability: { originCountry: 'Peru' } }); const swiss = rate({ sustainability: { originCountry: 'Schweiz' } }); - assert.equal(peru.categoryScores.sustainability.score, null); - assert.equal(swiss.categoryScores.sustainability.score, null); + assert.equal(peru.overallScore, swiss.overallScore); }); -test('Eco-Score is not counted again through its environmental indicators', () => { +test('Eco-Score does not affect the health rating', () => { const rating = rate({ sustainability: { ecoScore: 'E', carbonFootprintKgCo2ePerKg: 0.1, originCountry: 'Schweiz', packaging: 'Glas' } }); - assert.equal(rating.categoryScores.sustainability.score, 15); + assert.equal(rating.categoryScores.sustainability, undefined); + assert.equal(rating.overallScore, null); }); test('alternatives present unverified allergens only with a clear review path', async () => { const source = { - id: 'source', barcode: '1', name: 'Original', category: 'Snacks', categoryTags: ['en:snacks'], + id: 'source', barcode: '1', name: 'Schokolade', category: 'Snacks', categoryTags: ['en:snacks', 'en:chocolates'], allergens: ['Milch'], dataCompleteness: { allergens: true } }; const unknown = { - id: 'unknown', barcode: '2', name: 'Unklar', category: 'Snacks', categoryTags: ['en:snacks'], + id: 'unknown', barcode: '2', name: 'Schokolade A', category: 'Snacks', categoryTags: ['en:snacks', 'en:chocolates'], allergens: [], dataCompleteness: { allergens: false }, nutrition: { nutriScore: 'A' } }; const verified = { - id: 'verified', barcode: '3', name: 'Bestätigt', category: 'Snacks', categoryTags: ['en:snacks'], + id: 'verified', barcode: '3', name: 'Schokolade B', category: 'Snacks', categoryTags: ['en:snacks', 'en:chocolates'], allergens: ['Soja'], dataCompleteness: { allergens: true, allergensVerified: true }, nutrition: { nutriScore: 'A' } }; const alternatives = await findAlternatives(source, { @@ -190,9 +190,9 @@ test('alternatives present unverified allergens only with a clear review path', }); test('allergy-review alternatives remain discoverable when both displayed scores are capped', async () => { - const source = { id: 'source', barcode: '10', name: 'Original', categoryTags: ['en:snacks'], + const source = { id: 'source', barcode: '10', name: 'Schokolade', categoryTags: ['en:snacks', 'en:chocolates'], nutrition: { nutriScore: 'C' }, sustainability: { ecoScore: 'A' }, allergens: [] }; - const candidate = { id: 'candidate', barcode: '11', name: 'Besser', categoryTags: ['en:snacks'], + const candidate = { id: 'candidate', barcode: '11', name: 'Bessere Schokolade', categoryTags: ['en:snacks', 'en:chocolates'], nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'A' }, allergens: [] }; const pref = { ...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true }; const alternatives = await findAlternatives(source, pref, { candidate }); @@ -221,28 +221,26 @@ test('coverage counts underlying facts and ignores packaging as a score', () => const rating = rate({ nutrition: { nutriScore: 'A' }, ingredientAnalysis: { palmOil: false }, sustainability: { packaging: 'Glas' } }); assert.ok(rating.dataCoverage < 80); - assert.equal(rating.categoryScores.sustainability.score, null); + assert.equal(rating.categoryScores.sustainability, undefined); assert.notEqual(rating.overallStatus, 'good'); }); -test('budget includes open list prices and treats unknown prices as uncertainty', () => { +test('budget and open list prices do not affect the rating', () => { const item = { price: 5, nutrition: { nutriScore: 'A' } }; const pref = { maxBudgetPerShoppingTrip: 20, budgetPeriod: 'shoppingTrip' }; const list = { items: [{ estimatedPrice: 18, quantity: 1, checked: false }] }; const exceeded = calculateProductRating(item, { ...preferences, ...pref }, { shoppingList: list }); - assert.equal(exceeded.categoryScores.budget.status, 'critical'); - assert.match(exceeded.categoryScores.budget.message, /überschreitet/); + assert.equal(exceeded.categoryScores.budget, undefined); const missing = calculateProductRating(item, { ...preferences, ...pref }, { shoppingList: { items: [{ quantity: 1, checked: false }] } }); - assert.equal(missing.budgetReviewRequired, true); - assert.notEqual(missing.overallStatus, 'good'); + assert.equal(missing.budgetReviewRequired, false); + assert.equal(exceeded.overallScore, missing.overallScore); }); -test('a category-average footprint has partial coverage', () => { +test('a category-average footprint does not create health coverage', () => { const rating = rate({ sustainability: { carbonFootprintKgCo2ePerKg: 0.5, footprint: { status: 'estimated' } } }); - assert.ok(rating.dataCoverage > 0); - assert.ok(rating.dataCoverage < 50); + assert.equal(rating.dataCoverage, 0); }); test('online alternatives search category pages for healthier drinks', async () => { @@ -285,10 +283,10 @@ test('online alternatives search category pages for healthier drinks', async () } }); -test('offline alternatives use only saved products', async () => { - const source = { id: 'source', barcode: '1', categoryTags: ['en:beverages'], +test('offline alternatives use only saved products of the same type', async () => { + const source = { id: 'source', barcode: '1', name: 'Cola', categoryTags: ['en:beverages', 'en:sodas'], nutrition: { nutriScore: 'E' } }; - const cached = { id: 'cached', barcode: '2', name: 'Wasser', categoryTags: ['en:beverages'], + const cached = { id: 'cached', barcode: '2', name: 'Cola light', categoryTags: ['en:beverages', 'en:sodas'], nutrition: { nutriScore: 'A' } }; const originalFetch = globalThis.fetch; try { @@ -301,11 +299,81 @@ test('offline alternatives use only saved products', async () => { } }); +test('a sweet soda suggests a lower-sugar soda but never water', async () => { + const source = { id: 'source', barcode: '1', name: 'Süsse Cola', + categoryTags: ['en:beverages', 'en:sodas'], + nutrition: { nutriScore: 'D', sugarPer100g: 20 } }; + const lowerSugar = { id: 'lower-sugar', barcode: '2', name: 'Cola mit weniger Zucker', + categoryTags: ['en:beverages', 'en:sodas'], + nutrition: { nutriScore: 'D', sugarPer100g: 8 } }; + const water = { id: 'water', barcode: '3', name: 'Wasser', + categoryTags: ['en:beverages', 'en:waters'], + nutrition: { nutriScore: 'A', sugarPer100g: 0 } }; + const alternatives = await findAlternatives(source, { ...preferences, offlineModeEnabled: true }, + { lowerSugar, water }, {}, { preview: true }); + assert.deepEqual(alternatives.map((item) => item.product.id), ['lower-sugar']); + assert.match(alternatives[0].reason, /8 statt 20 g/); +}); + +test('automatic preview continues to a related category when the first tag is empty', async () => { + const source = { id: 'spread', barcode: '1', name: 'Haselnussaufstrich', + category: 'Sweet spreads', + categoryTags: ['en:spreads', 'en:sweet-spreads', 'en:chocolate-spreads', 'en:hazelnut-spreads'], + nutrition: { nutriScore: 'E', sugarPer100g: 45 } }; + const requests = []; + const originalFetch = globalThis.fetch; + try { + globalThis.fetch = async (url) => { + const parsed = new URL(url); + const tag = parsed.searchParams.get('categories_tags'); + requests.push(tag); + return { ok: true, json: async () => ({ products: tag === 'en:chocolate-spreads' + && !parsed.searchParams.has('nutrition_grades_tags') + ? [{ code: '2', product_name: 'Schokoaufstrich mit weniger Zucker', + categories_tags: ['en:spreads', 'en:chocolate-spreads'], nutriscore_grade: 'c', + nutriments: { sugars_100g: 15 } }] : [] }) }; + }; + const alternatives = await findAlternatives(source, { ...preferences, offlineModeEnabled: false }, + {}, {}, { preview: true }); + assert.deepEqual(alternatives.map((item) => item.product.barcode), ['2']); + assert.ok(requests.includes('en:hazelnut-spreads')); + assert.ok(requests.includes('en:chocolate-spreads')); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test('automatic preview searches by product type when only a broad category is available', async () => { + const source = { id: 'cola', barcode: '1', name: 'Cola Original', + category: 'Beverages', categoryTags: ['en:beverages'], + nutrition: { nutriScore: 'D', sugarPer100g: 20 } }; + const queries = []; + const originalFetch = globalThis.fetch; + try { + globalThis.fetch = async (url) => { + const parsed = new URL(url); + if (parsed.pathname.endsWith('/cgi/search.pl')) { + queries.push(parsed.searchParams.get('search_terms')); + return { ok: true, json: async () => ({ products: [{ code: '2', + product_name: 'Cola mit weniger Zucker', categories_tags: ['en:beverages', 'en:sodas'], + nutriscore_grade: 'd', nutriments: { sugars_100g: 8 } }] }) }; + } + return { ok: true, json: async () => ({ products: [] }) }; + }; + const alternatives = await findAlternatives(source, { ...preferences, offlineModeEnabled: false }, + {}, {}, { preview: true }); + assert.ok(queries.includes('cola')); + assert.deepEqual(alternatives.map((item) => item.product.barcode), ['2']); + } finally { + globalThis.fetch = originalFetch; + } +}); + test('different brands with the same product name remain separate alternatives', async () => { - const source = { id: 'source', barcode: '1', categoryTags: ['en:beverages'], + const source = { id: 'source', barcode: '1', name: 'Cola', categoryTags: ['en:beverages', 'en:sodas'], nutrition: { nutriScore: 'E' } }; - const first = { id: 'first', barcode: '2', name: 'Mineralwasser', brand: 'A', - categoryTags: ['en:beverages'], nutrition: { nutriScore: 'A' } }; + const first = { id: 'first', barcode: '2', name: 'Cola light', brand: 'A', + categoryTags: ['en:beverages', 'en:sodas'], nutrition: { nutriScore: 'A' } }; const second = { ...first, id: 'second', barcode: '3', brand: 'B' }; const alternatives = await findAlternatives(source, { ...preferences, offlineModeEnabled: true }, { first, second }); @@ -313,7 +381,7 @@ test('different brands with the same product name remain separate alternatives', }); test('online search broadens to products without an official grade and reports a complete outage', async () => { - const source = { id: 'source', barcode: '1', categoryTags: ['en:beverages'], + const source = { id: 'source', barcode: '1', name: 'Cola', categoryTags: ['en:beverages', 'en:sodas'], nutrition: { nutriScore: 'E' } }; const originalFetch = globalThis.fetch; const requests = []; @@ -322,7 +390,7 @@ test('online search broadens to products without an official grade and reports a const parsed = new URL(url); requests.push(parsed); return { ok: true, json: async () => ({ products: parsed.searchParams.has('nutrition_grades_tags') - ? [] : [{ code: '2', product_name: 'Wasser', categories_tags: ['en:beverages'], + ? [] : [{ code: '2', product_name: 'Cola light', categories_tags: ['en:beverages', 'en:sodas'], nutriscore_grade: 'a' }] }) }; }; const alternatives = await findAlternatives(source, { ...preferences, offlineModeEnabled: false });