diff --git a/App.js b/App.js index 45fc679..9c58dfc 100644 --- a/App.js +++ b/App.js @@ -128,6 +128,7 @@ export default function App() { onScanBarcode={scanProductByBarcode} preferences={preferences} productCache={productCache} + shoppingList={shoppingList} /> ); } @@ -460,6 +461,7 @@ export default function App() { onShowAlternatives={showAlternatives} preferences={preferences} product={routeProduct} + shoppingList={shoppingList} /> ); } @@ -471,6 +473,7 @@ export default function App() { onBack={goBackFromRoute} preferences={preferences} product={routeProduct} + shoppingList={shoppingList} /> ); } @@ -488,6 +491,7 @@ export default function App() { preferences={preferences} product={routeProduct} productCache={productCache} + shoppingList={shoppingList} /> ); } diff --git a/README.md b/README.md index f2c305c..9994c8b 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ 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: bessere Produktvorschläge aus dem lokalen Beispieldatensatz +- 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 @@ -88,7 +88,15 @@ Fehlt der Nutri-Score in Open Food Facts, berechnet die App die Note A–E aus d 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. -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 müssen eine deutlich bessere Gesamtwertung, mindestens eine belegte Verbesserung in einem Kriterium und mindestens dieselbe Datenabdeckung erreichen; die Punktschwellen sind App-Heuristiken und keine wissenschaftlich kalibrierten Unterschiede. +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 @@ -98,6 +106,8 @@ Wenn ein produktspezifischer Wert fehlt, sucht die App in der mitgelieferten [AG 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 diff --git a/src/components/product/AlternativeProductCard.js b/src/components/product/AlternativeProductCard.js index acf5cbd..9125c1e 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/screens/AlternativesScreen.js b/src/screens/AlternativesScreen.js index fbd0ff3..6e7c61b 100644 --- a/src/screens/AlternativesScreen.js +++ b/src/screens/AlternativesScreen.js @@ -1,27 +1,37 @@ import { useEffect, useState } from 'react'; import { StyleSheet, Text, View } from 'react-native'; +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 { colors } from '../utils/constants'; -const DISPLAY_ALTERNATIVE_LIMIT = 5; +const DISPLAY_ALTERNATIVE_LIMIT = 8; -export default function AlternativesScreen({ product, preferences, productCache, onBack, onChoose, onOpenProduct }) { +export default function AlternativesScreen({ product, preferences, productCache, shoppingList, onBack, onChoose, onOpenProduct }) { const [alternatives, setAlternatives] = useState([]); const [isLoading, setIsLoading] = useState(true); + const [searchError, setSearchError] = useState(''); + const [retryCount, setRetryCount] = useState(0); useEffect(() => { let isMounted = true; async function loadAlternatives() { setIsLoading(true); - const results = await findAlternatives(product, preferences, productCache); - if (isMounted) { - setAlternatives(results); - setIsLoading(false); + setSearchError(''); + try { + const results = await findAlternatives(product, preferences, productCache, { shoppingList }); + if (isMounted) setAlternatives(results); + } catch (error) { + if (isMounted) { + setAlternatives([]); + setSearchError('Open Food Facts ist gerade nicht erreichbar. Versuche es später erneut oder nutze den Offline-Modus.'); + } + } finally { + if (isMounted) setIsLoading(false); } } @@ -29,21 +39,30 @@ export default function AlternativesScreen({ product, preferences, productCache, return () => { isMounted = false; }; - }, [product, preferences, productCache]); + }, [product, preferences, productCache, shoppingList, retryCount]); return ( - {isLoading ? Alternativen werden berechnet... : null} - {!isLoading && alternatives.length === 0 ? ( + {isLoading ? {preferences.offlineModeEnabled + ? 'Gespeicherte Produkte werden verglichen...' + : 'Open Food Facts wird nach gesünderen Produkten derselben Kategorie durchsucht...'} : null} + {searchError ? {searchError} : null} + {searchError ? setRetryCount((count) => count + 1)} /> : null} + {!isLoading && alternatives.length > 0 ? ( + {alternatives.length} mögliche Alternative{alternatives.length === 1 ? '' : 'n'} gefunden. Die Ernährungswertung und weitere Kriterien stehen in den Produktdetails. + ) : null} + {!isLoading && !searchError && alternatives.length === 0 ? ( Keine Alternative gefunden - Für dieses Produkt wurde in ähnlichen Kategorien noch keine klar bessere Option 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.'} ) : null} @@ -52,7 +71,7 @@ export default function AlternativesScreen({ product, preferences, productCache, item={item} key={item.product.id} onChoose={() => { - if (typeof item.product.price === 'number') { + if (!item.requiresAllergenCheck && typeof item.product.price === 'number') { onChoose(item.product); return; } diff --git a/src/screens/HomeScreen.js b/src/screens/HomeScreen.js index 192eb86..200acb6 100644 --- a/src/screens/HomeScreen.js +++ b/src/screens/HomeScreen.js @@ -52,7 +52,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList, onOpenProduct(product)} /> {product.scanCount} Scans @@ -72,7 +72,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList, onOpenProduct(product)} /> )) diff --git a/src/screens/ProductDetailScreen.js b/src/screens/ProductDetailScreen.js index 5ea6200..8a5dc31 100644 --- a/src/screens/ProductDetailScreen.js +++ b/src/screens/ProductDetailScreen.js @@ -1,5 +1,5 @@ import { useMemo, useState } from 'react'; -import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { Alert, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; import PrimaryButton from '../components/PrimaryButton'; import SecondaryButton from '../components/SecondaryButton'; @@ -21,7 +21,8 @@ export default function ProductDetailScreen({ onOpenList, onSaveManualPrice, onShowRatingCriteria, - onShowAlternatives + onShowAlternatives, + shoppingList }) { const [savedMessage, setSavedMessage] = useState(''); const [manualPrice, setManualPrice] = useState(''); @@ -34,7 +35,7 @@ export default function ProductDetailScreen({ currency, price: hasProductPrice ? product.price : parsedManualPrice }), [currency, hasProductPrice, parsedManualPrice, product]); - const rating = useMemo(() => calculateProductRating(pricedProduct, preferences), [pricedProduct, preferences]); + const rating = useMemo(() => calculateProductRating(pricedProduct, preferences, { shoppingList }), [pricedProduct, preferences, shoppingList]); const footprint = product.sustainability?.footprint; const recommendation = rating.overallStatus === 'good' ? 'Passt gut zu dir' : rating.overallStatus === 'critical' ? 'Lieber meiden' @@ -47,6 +48,28 @@ export default function ProductDetailScreen({ return; } + if (rating.hasBlockedAllergen) { + setSavedMessage('Dieses Produkt enthält ein Allergen aus deinem Profil und wurde nicht hinzugefügt.'); + return; + } + + if (rating.allergenReviewRequired) { + const message = 'Die App kann Allergenfreiheit nicht bestätigen. Prüfe Zutaten und Spurenhinweise auf der Verpackung, bevor du das Produkt hinzufügst.'; + if (Platform.OS === 'web') { + if (window.confirm(`${message}\n\nVerpackung geprüft und trotzdem hinzufügen?`)) saveToList(); + return; + } + Alert.alert('Allergene prüfen', message, [ + { text: 'Abbrechen', style: 'cancel' }, + { text: 'Verpackung geprüft', onPress: saveToList } + ]); + return; + } + + saveToList(); + } + + function saveToList() { if (!hasProductPrice && typeof pricedProduct.price === 'number') { onSaveManualPrice(pricedProduct, pricedProduct.price); } @@ -77,17 +100,7 @@ export default function ProductDetailScreen({ {recommendation} - {rating.hasBlockedAllergen - ? rating.categoryScores.allergies.message - : rating.allergenReviewRequired - ? rating.allergenReviewMessage - : rating.staleDataReviewRequired - ? 'Gespeicherte Produktdaten sind veraltet. Prüfe vor dem Kauf die Verpackung.' - : rating.overallStatus === 'unknown' - ? 'Für eine Empfehlung fehlen belastbare Produktangaben.' - : rating.limitedByMissingData - ? 'Nur ein Teil der Kriterien ist belegt. Die Empfehlung ist deshalb auf „Prüfen“ begrenzt.' - : 'Tippe unten auf ein Kriterium, um die Bewertung nachzuvollziehen.'} + {recommendationMessage(rating)} Bewertbare Daten: {rating.dataCoverage}% der für dein Profil anwendbaren Kriterien (gewichtet). @@ -140,7 +153,7 @@ export default function ProductDetailScreen({ ) : null} - onShowAlternatives(product)} /> + onShowAlternatives(pricedProduct)} /> Bewertungskriterien {Object.entries(rating.categoryScores).map(([category, categoryRating]) => ( @@ -208,6 +221,18 @@ export default function ProductDetailScreen({ ); } +function recommendationMessage(rating) { + if (rating.hasBlockedAllergen) return rating.categoryScores.allergies.message; + 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.'; + return 'Tippe unten auf ein Kriterium, um die Bewertung nachzuvollziehen.'; +} + function parseManualPrice(value) { const normalizedValue = value.trim().replace(',', '.'); const parsedValue = Number(normalizedValue); diff --git a/src/screens/RatingCriteriaDetailScreen.js b/src/screens/RatingCriteriaDetailScreen.js index 77de50e..247820e 100644 --- a/src/screens/RatingCriteriaDetailScreen.js +++ b/src/screens/RatingCriteriaDetailScreen.js @@ -20,25 +20,25 @@ const defaultDetails = { 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 am Budget pro Zeitraum verbessert diese Bewertung.', - penalty: 'Ein hoher Preis relativ zu deinem Budget reduziert die Bewertung. Fehlende Preise werden als ungenaue Prüfung markiert.' + 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: 'Keine kritischen Zusatzstoffe, kein Palmöl und passende Vegan-/Vegetarisch-Analyse verbessern diese Bewertung.', - penalty: 'Kritische Zusatzstoffe, Palmöl, viele Zusatzstoffe oder ein Konflikt mit deinem Ernährungsziel reduzieren diese Bewertung.' + 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.' }, nutrition: { positive: 'Ein guter Nutri-Score und passende Werte für dein gewähltes Ernährungsziel verbessern diese Bewertung.', penalty: 'Ein schwacher Nutri-Score oder ein Konflikt mit deinem Zucker- oder Proteinziel reduziert diese Bewertung. Nährwerte im Nutri-Score werden nicht nochmals abgezogen.' }, sustainability: { - positive: 'Guter Eco-Score, niedriger CO2-Fussabdruck, regionale Herkunft, bessere Verpackung und Bio bei Bio-Präferenz verbessern diese Bewertung.', - penalty: 'Schwacher Eco-Score, hoher CO2-Fussabdruck, belastende Verpackung, weite Herkunft oder fehlendes Bio bei Bio-Präferenz reduzieren diese Bewertung.' + 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.' } }; -export default function RatingCriteriaDetailScreen({ product, preferences, category, onBack }) { - const rating = calculateProductRating(product, preferences); +export default function RatingCriteriaDetailScreen({ product, preferences, shoppingList, category, onBack }) { + const rating = calculateProductRating(product, preferences, { shoppingList }); const categoryRating = rating.categoryScores[category]; const title = labels[category] || category; const fallbackDetails = defaultDetails[category] || defaultDetails.ingredients; diff --git a/src/screens/ScanScreen.js b/src/screens/ScanScreen.js index bad14d0..76b4ff8 100644 --- a/src/screens/ScanScreen.js +++ b/src/screens/ScanScreen.js @@ -15,7 +15,7 @@ import { searchProducts } from '../services/productApi'; import { calculateProductRating } from '../services/ratingService'; import { colors } from '../utils/constants'; -export default function ScanScreen({ preferences, productCache, onScanBarcode, onOpenProduct }) { +export default function ScanScreen({ preferences, productCache, shoppingList, onScanBarcode, onOpenProduct }) { const [permission, requestPermission] = useCameraPermissions(); const [isScanning, setIsScanning] = useState(true); const [isLoadingProduct, setIsLoadingProduct] = useState(false); @@ -150,7 +150,7 @@ export default function ScanScreen({ preferences, productCache, onScanBarcode, o onOpenProduct(product)} /> ))} diff --git a/src/services/alternativesService.js b/src/services/alternativesService.js index cce6c15..22ce170 100644 --- a/src/services/alternativesService.js +++ b/src/services/alternativesService.js @@ -1,9 +1,11 @@ -import { searchProducts } from './productApi.js'; +import { searchProducts, searchProductsByCategory } from './productApi.js'; import { calculateProductRating } from './ratingService.js'; const MIN_SCORE_IMPROVEMENT = 10; 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 improvementLabels = { allergies: 'Besser passend bei Allergien', @@ -16,56 +18,112 @@ const improvementLabels = { const categoryGroups = [ { label: 'Getränke', + tag: 'en:beverages', terms: ['beverage', 'beverages', 'drink', 'drinks', 'getränk', 'getränke', 'soda', 'cola', 'juice', 'water', 'waters', 'non alcoholic', 'sodas'] }, { label: 'Snacks', + tag: 'en:snacks', terms: ['snack', 'snacks', 'bar', 'riegel', 'chocolate', 'chips', 'crisps'] }, { label: 'Milchprodukte', + tag: 'en:dairies', terms: ['dairy', 'milk', 'yogurt', 'joghurt', 'milch', 'milchprodukte', 'cheese'] }, { label: 'Fertiggerichte', + tag: 'en:meals', terms: ['meal', 'meals', 'ready meal', 'bowl', 'fertiggericht', 'prepared'] } ]; -export async function findAlternatives(product, preferences, productCache = {}) { - const productRating = calculateProductRating(product, preferences); +export async function findAlternatives(product, preferences, productCache = {}, context = {}) { + const productRating = calculateProductRating(product, preferences, context); if (productRating.overallScore === null) return []; const categoryTerms = categoryTermsForProduct(product); - const remoteCandidates = await loadRemoteCandidates(categoryTerms, productCache, preferences.offlineModeEnabled); - const candidates = uniqueProducts([ - ...remoteCandidates, - ...Object.values(productCache) - ]) + const candidates = [...Object.values(productCache)]; + let alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms); + if (preferences.offlineModeEnabled) return 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); + } + + let successfulRequests = 0; + for (const requestOptions of [ + { 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') { + successfulRequests += 1; + candidates.push(...result.value); + } + }); + alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms); + if (alternatives.length >= INTERNAL_ALTERNATIVE_LIMIT) break; + } + + if (successfulRequests === 0 && alternatives.length === 0 && searchTags.length > 0) { + throw new Error('Open Food Facts ist für die Alternativsuche nicht erreichbar.'); + } + return alternatives; +} + +function rankCandidates(product, productRating, products, preferences, context, categoryTerms) { + const candidates = uniqueProducts(products) .filter((candidate) => candidate.id !== product.id && candidate.barcode !== product.barcode) - .filter((candidate) => isSimilarCategory(product, candidate, categoryTerms)) + .filter((candidate) => isSimilarCategory(product, candidate)) .filter((candidate) => !hasAvoidedAllergen(candidate, preferences)); return candidates .map((candidate) => ({ product: candidate, - rating: calculateProductRating(candidate, preferences), + rating: calculateProductRating(candidate, preferences, context), dataQualityScore: knownDataScore(candidate) })) - .filter((item) => !item.rating.allergenReviewRequired) + .map((item) => { + const nutritionGain = nutritionImprovement(item.rating, productRating); + return { ...item, nutritionImprovement: nutritionGain, + healthEligible: nutritionGain >= HEALTH_IMPROVEMENT && !item.rating.goalReviewRequired }; + }) .filter((item) => productRating.overallScore !== null && item.rating.overallScore !== null - && item.rating.overallScore >= productRating.overallScore + MIN_SCORE_IMPROVEMENT - && item.rating.dataCoverage >= productRating.dataCoverage - && (strongestCategoryImprovement(item.rating, productRating)?.improvement || 0) >= MIN_CATEGORY_IMPROVEMENT) + && !item.rating.goalConflict + && (item.healthEligible || isOverallImprovement(item.rating, productRating))) .map((item) => ({ ...item, - reason: buildReason(item.rating, productRating, categoryTerms) + 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 + ? nutritionReason(item.rating, productRating) + : buildReason(item.rating, productRating, categoryTerms) })) .sort((left, right) => { + if (left.requiresAllergenCheck !== right.requiresAllergenCheck) { + return left.requiresAllergenCheck ? 1 : -1; + } + if (left.healthEligible !== right.healthEligible) { + return left.healthEligible ? -1 : 1; + } + if (right.nutritionImprovement !== left.nutritionImprovement) { + return right.nutritionImprovement - left.nutritionImprovement; + } if (right.rating.overallScore !== left.rating.overallScore) { return right.rating.overallScore - left.rating.overallScore; } + if (right.rating.dataCoverage !== left.rating.dataCoverage) { + return right.rating.dataCoverage - left.rating.dataCoverage; + } + const priceDiff = priceForSort(left.product) - priceForSort(right.product); if (priceDiff !== 0) { return priceDiff; @@ -77,13 +135,45 @@ export async function findAlternatives(product, preferences, productCache = {}) .slice(0, INTERNAL_ALTERNATIVE_LIMIT); } -async function loadRemoteCandidates(categoryTerms, productCache, offlineModeEnabled) { - const queries = categoryTerms.slice(0, 3); - const results = await Promise.all( - queries.map((query) => searchProducts(query, productCache, offlineModeEnabled).catch(() => [])) - ); +function isOverallImprovement(rating, sourceRating) { + const scoreImproved = rating.overallScore >= sourceRating.overallScore + MIN_SCORE_IMPROVEMENT + || (rating.allergenReviewRequired && sourceRating.allergenReviewRequired + && rating.uncappedScore >= sourceRating.uncappedScore + MIN_SCORE_IMPROVEMENT) + || (sourceRating.hasBlockedAllergen && !rating.hasBlockedAllergen + && rating.overallScore >= MIN_SCORE_IMPROVEMENT); + return scoreImproved && rating.dataCoverage >= sourceRating.dataCoverage + && ((strongestCategoryImprovement(rating, sourceRating)?.improvement || 0) >= MIN_CATEGORY_IMPROVEMENT + || (sourceRating.hasBlockedAllergen && !rating.hasBlockedAllergen)); +} - return results.flat(); +function nutritionImprovement(rating, sourceRating) { + const nutrition = rating.categoryScores.nutrition; + const sourceNutrition = sourceRating.categoryScores.nutrition; + return nutrition.hasKnownFacts !== false && sourceNutrition.hasKnownFacts !== false + ? Math.max(0, nutrition.score - sourceNutrition.score) : 0; +} + +function nutritionReason(rating, sourceRating) { + const nutrition = rating.categoryScores.nutrition; + const sourceNutrition = sourceRating.categoryScores.nutrition; + const grades = nutrition.nutriScore && sourceNutrition.nutriScore + ? `Nutri-Score ${nutrition.nutriScore} statt ${sourceNutrition.nutriScore}` + : `Ernährungswertung ${nutrition.score} statt ${sourceNutrition.score}`; + const coverageNote = rating.dataCoverage < sourceRating.dataCoverage + ? ' Andere Kriterien sind weniger vollständig dokumentiert.' : ''; + return `Bessere Ernährung: ${grades}.${coverageNote}`; +} + +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(), + broadTag, + ...rawTags.filter((tag) => !generic.has(tag)).slice(-1) + ].filter(Boolean)).slice(0, 3); } function categoryTermsForProduct(product) { @@ -93,9 +183,7 @@ function categoryTermsForProduct(product) { ] .map(normalizeTerm) .filter(Boolean); - const matchingGroup = categoryGroups.find((group) => - rawTerms.some((term) => group.terms.some((groupTerm) => term.includes(groupTerm))) - ); + const matchingGroup = categoryGroupForProduct(product); return uniqueStrings([ ...(matchingGroup?.terms || []), @@ -103,17 +191,22 @@ function categoryTermsForProduct(product) { ]); } -function isSimilarCategory(sourceProduct, candidate, categoryTerms) { +function isSimilarCategory(sourceProduct, candidate) { const sourceTerms = productTerms(sourceProduct); const candidateTerms = productTerms(candidate); - if (candidateTerms.some((term) => sourceTerms.includes(term))) { + if (candidateTerms.some((term) => !GENERIC_CATEGORY_TERMS.has(term) && sourceTerms.includes(term))) { return true; } - return candidateTerms.some((term) => - categoryTerms.some((categoryTerm) => term.includes(categoryTerm) || categoryTerm.includes(term)) - ); + const sourceGroup = categoryGroupForProduct(sourceProduct); + return Boolean(sourceGroup && sourceGroup === categoryGroupForProduct(candidate)); +} + +function categoryGroupForProduct(product) { + return categoryGroups.find((group) => productTerms(product).filter((term) => !GENERIC_CATEGORY_TERMS.has(term)).some((term) => + group.terms.some((groupTerm) => (` ${term} `).includes(` ${groupTerm} `)) + )); } function productTerms(product) { @@ -142,7 +235,7 @@ function buildReason(rating, sourceRating, categoryTerms) { function categoryLabelForTerms(terms) { const matchingGroup = categoryGroups.find((group) => - terms.some((term) => group.terms.some((groupTerm) => term.includes(groupTerm))) + terms.some((term) => group.terms.some((groupTerm) => (` ${term} `).includes(` ${groupTerm} `))) ); return matchingGroup?.label; @@ -210,16 +303,31 @@ function hasNutrientLevels(nutrition) { } function uniqueProducts(products) { - return Array.from(new Map(products.map((product) => [product.barcode || product.id, product])).values()); + const byProduct = new Map(); + 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); + }); + return Array.from(byProduct.values()); } function uniqueByProductName(item, index, items) { - const normalizedName = normalizeProductName(item.product.name); - if (!normalizedName) { + const identity = productVariantIdentity(item.product); + if (!identity) { return true; } - return items.findIndex((candidate) => normalizeProductName(candidate.product.name) === normalizedName) === index; + return items.findIndex((candidate) => productVariantIdentity(candidate.product) === identity) === index; +} + +function productVariantIdentity(product) { + const name = normalizeProductName(product.name); + return name ? [normalizeProductName(product.brand), name, normalizeProductName(product.packageQuantityLabel)].join('|') : ''; } function uniqueStrings(values) { diff --git a/src/services/productApi.js b/src/services/productApi.js index e7df4bc..d2d21d8 100644 --- a/src/services/productApi.js +++ b/src/services/productApi.js @@ -117,9 +117,10 @@ function cachedResult(product, stale = false) { }; } -export async function searchProducts(query, productCache = {}, offlineModeEnabled = false) { +export async function searchProducts(query, productCache = {}, offlineModeEnabled = false, { pageSize = 20 } = {}) { const normalizedQuery = query.trim().toLowerCase(); const cachedProducts = Object.values(productCache); + const safePageSize = Number.isInteger(pageSize) ? Math.max(1, Math.min(100, pageSize)) : 20; if (!normalizedQuery) { return []; @@ -131,7 +132,7 @@ export async function searchProducts(query, productCache = {}, offlineModeEnable try { const response = await fetch( - `${openFoodFactsBaseUrl}/cgi/search.pl?search_terms=${encodeURIComponent(query)}&search_simple=1&action=process&json=1&page_size=20&fields=${productFields}` + `${openFoodFactsBaseUrl}/cgi/search.pl?search_terms=${encodeURIComponent(query)}&search_simple=1&action=process&json=1&page_size=${safePageSize}&fields=${productFields}` ); if (!response.ok) { @@ -156,6 +157,32 @@ export async function searchProducts(query, productCache = {}, offlineModeEnable } } +export async function searchProductsByCategory(categoryTag, { page = 1, grades = 'a|b' } = {}) { + if (!/^en:[a-z0-9-]+$/.test(categoryTag) || !Number.isInteger(page) || page < 1 + || ![null, 'a|b', 'a|b|c'].includes(grades)) return []; + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 6000); + let response; + try { + response = await fetch( + `${openFoodFactsBaseUrl}/api/v2/search?categories_tags=${encodeURIComponent(categoryTag)}` + + (grades ? `&nutrition_grades_tags=${encodeURIComponent(grades)}` : '') + + '&sort_by=popularity_key' + + `&page=${page}&page_size=40&fields=${productFields}`, + { signal: controller.signal } + ); + } finally { + clearTimeout(timeout); + } + if (!response.ok) throw new Error('Open Food Facts category search failed.'); + + const payload = await response.json(); + return (Array.isArray(payload?.products) ? payload.products : []) + .filter((item) => item && typeof item === 'object' && item.code) + .map((item) => mapOpenFoodFactsProduct(item, item.code)); +} + export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { const barcode = normalizeBarcode(product.code || fallbackBarcode); const nutriments = product.nutriments || {}; @@ -218,7 +245,7 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) { ecoScoreSource: ecoScore ? 'Open Food Facts' : undefined, footprint, carbonFootprintKgCo2ePerKg: footprint.status === 'product-specific' ? footprint.valueKgCo2ePerKg : undefined, - isBio: Array.isArray(product.labels_tags) ? hasOrganicLabel(product.labels_tags) : undefined, + isBio: Array.isArray(product.labels_tags) && hasOrganicLabel(product.labels_tags) ? true : undefined, originCountry, originSource: originCountry ? 'ingredient-origin' : undefined, sellingCountries: normalizeTags(product.countries_tags), @@ -257,6 +284,7 @@ function filterProducts(products, normalizedQuery) { product.name, product.brand, product.category, + ...(product.categoryTags || []), product.barcode ].filter(Boolean).join(' ').toLowerCase(); diff --git a/src/services/ratingService.js b/src/services/ratingService.js index 4057190..2871b0d 100644 --- a/src/services/ratingService.js +++ b/src/services/ratingService.js @@ -121,10 +121,10 @@ function severityFromStatus(status) { return 'info'; } -export function calculateProductRating(product, preferences) { +export function calculateProductRating(product, preferences, context = {}) { const categoryScores = { allergies: rateAllergies(product, preferences), - budget: rateBudget(product, preferences), + budget: rateBudget(product, preferences, context), ingredients: rateIngredients(product, preferences), nutrition: rateNutrition(product, preferences), sustainability: rateSustainability(product, preferences) @@ -133,16 +133,23 @@ export function calculateProductRating(product, preferences) { const weights = ratingWeights(preferences); const hasBlockedAllergen = categoryScores.allergies.score === 0; const allergenReviewRequired = categoryScores.allergies.needsReview === true; - const criticalAdditiveCount = categoryScores.ingredients.criticalAdditiveCount || 0; - const { score: weightedScore, coverage } = weightedCategoryScore(categoryScores, weights, preferences); - const coverageCap = coverage < 0.3 ? 65 : coverage < 0.6 ? 77 : 100; + 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 ? 0 : weightedScore === null ? null : Math.min( - capOverallScoreForCriticalAdditives(weightedScore, criticalAdditiveCount), + weightedScore, + goalConflict ? 47 : 100, coverageCap, allergenReviewRequired ? 77 : 100, + goalReviewRequired ? 77 : 100, + budgetReviewRequired ? 77 : 100, product.cacheStale ? 77 : 100 ); const limitedByMissingData = !hasBlockedAllergen && weightedScore !== null @@ -151,10 +158,10 @@ export function calculateProductRating(product, preferences) { const scoreLimitReasons = []; if (hasBlockedAllergen) scoreLimitReasons.push('Ein vermiedenes Allergen ist angegeben.'); 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 (criticalAdditiveCount > 0 && weightedScore > capOverallScoreForCriticalAdditives(weightedScore, criticalAdditiveCount)) { - scoreLimitReasons.push('Die Regel für kritische Zusatzstoffe begrenzt die Gesamtwertung.'); - } if (limitedByMissingData) scoreLimitReasons.push('Fehlende Daten begrenzen die Gesamtwertung.'); const reasons = Object.entries(categoryScores).map(([category, value]) => ({ @@ -167,9 +174,13 @@ export function calculateProductRating(product, preferences) { productId: product.id, overallStatus, overallScore, + uncappedScore: weightedScore, limitedByMissingData, dataCoverage: Math.round(coverage * 100), allergenReviewRequired, + goalConflict, + goalReviewRequired, + budgetReviewRequired, staleDataReviewRequired: product.cacheStale === true, hasBlockedAllergen, allergenReviewMessage: categoryScores.allergies.reviewMessage, @@ -191,12 +202,15 @@ function ratingWeights(preferences) { }; } -function weightedCategoryScore(categoryScores, weights, preferences) { +function weightedCategoryScore(categoryScores, weights, preferences, product) { const applicableEntries = applicableCategoryEntries(categoryScores, preferences); const knownEntries = applicableEntries.filter(([, value]) => value.hasKnownFacts !== false); const totalWeight = knownEntries.reduce((sum, [category]) => sum + weights[category], 0); const applicableWeight = applicableEntries.reduce((sum, [category]) => sum + weights[category], 0); - const coverage = applicableWeight === 0 ? 0 : totalWeight / applicableWeight; + const coveredWeight = applicableEntries.reduce((sum, [category, value]) => ( + sum + weights[category] * (value.hasKnownFacts === false ? 0 : factCoverage(product, preferences, category, value)) + ), 0); + const coverage = applicableWeight === 0 ? 0 : coveredWeight / applicableWeight; if (totalWeight === 0) { return { score: null, coverage }; @@ -218,6 +232,50 @@ function applicableCategoryEntries(categoryScores, preferences) { )); } +function factCoverage(product, preferences, category, rating) { + const nutrition = product.nutrition || {}; + const sustainability = product.sustainability || {}; + const analysis = product.ingredientAnalysis || {}; + const ingredients = ingredientTerms(product); + + if (category === 'allergies' || category === 'budget') return 1; + + if (category === 'nutrition') { + const needsSugar = preferences.preferredDiet === 'lowSugar'; + const needsProtein = preferences.preferredDiet === 'highProtein' && !isBeverage(product); + const goalKnown = needsSugar ? Number.isFinite(nutrition.sugarPer100g) + : needsProtein ? Number.isFinite(nutrition.proteinPer100g) : true; + return (3 + ((needsSugar || needsProtein) && goalKnown ? 2 : 0)) + / (3 + (needsSugar || needsProtein ? 2 : 0)); + } + + if (category === 'ingredients') { + const palmKnown = typeof analysis.palmOil === 'boolean' + || ingredients.some((ingredient) => palmOilTerms().some((term) => ingredient.includes(term))); + const additivesKnown = harmfulAdditiveMatches(analysis.additives || [], ingredients).length > 0 + || (product.dataCompleteness?.additives === true && (ingredients.length > 0 || (analysis.additives || []).length > 0)); + const dietApplies = ['vegan', 'vegetarian'].includes(preferences.preferredDiet); + const dietKnown = dietApplies && (typeof analysis[preferences.preferredDiet] === 'boolean' + || hasAnimalIngredient(ingredients, preferences.preferredDiet === 'vegan')); + return (2 * Number(palmKnown) + Number(additivesKnown) + 3 * Number(dietKnown)) + / (3 + (dietApplies ? 3 : 0)); + } + + if (category === 'sustainability') { + const bioApplies = Boolean(bioPreferenceApplies(product, preferences)); + const bioKnown = bioApplies && typeof sustainability.isBio === 'boolean'; + if (ecoScoreValues[sustainability.ecoScore]) { + return (3 + Number(bioKnown)) / (3 + Number(bioApplies)); + } + const carbonKnown = typeof carbonFootprintValue(sustainability) === 'number'; + const carbonCoverage = carbonKnown ? sustainability.footprint?.status === 'estimated' ? 1 : 2 : 0; + return (carbonCoverage + Number(bioKnown)) + / (2 + Number(bioApplies)); + } + + return rating.hasKnownFacts === false ? 0 : 1; +} + function ratingFactors(categoryScores, weights, preferences) { return applicableCategoryEntries(categoryScores, preferences) .filter(([, value]) => value.hasKnownFacts !== false) @@ -232,22 +290,6 @@ function ratingFactors(categoryScores, weights, preferences) { .slice(0, 2); } -function capOverallScoreForCriticalAdditives(score, criticalAdditiveCount) { - if (criticalAdditiveCount >= 3) { - return Math.min(score, 35); - } - - if (criticalAdditiveCount === 2) { - return Math.min(score, 42); - } - - if (criticalAdditiveCount === 1) { - return Math.min(score, 47); - } - - return score; -} - function rateAllergies(product, preferences) { const avoidAllergens = preferences.avoidAllergens || []; const matchingAllergens = (product.allergens || []).filter((allergen) => @@ -316,7 +358,7 @@ function rateIngredients(product, preferences) { components.push(scoreComponent(vegan === true ? 100 : vegan === false ? 0 : null, 3)); if (vegan === false) { - return withScore(cappedHarmfulAdditiveScore(weightedKnownScore(components, 50), harmfulAdditives), 'Nicht vegan laut Zutatenanalyse.', missingData, { hasKnownFacts: hasKnownComponents(components), criticalAdditiveCount: harmfulAdditives.length, details: scoreDetails }); + return withScore(weightedKnownScore(components, 50), 'Nicht vegan laut Zutatenanalyse.', missingData, { hasKnownFacts: hasKnownComponents(components), goalConflict: true, details: scoreDetails }); } } @@ -324,20 +366,21 @@ function rateIngredients(product, preferences) { components.push(scoreComponent(vegetarian === true ? 100 : vegetarian === false ? 0 : null, 3)); if (vegetarian === false) { - return withScore(cappedHarmfulAdditiveScore(weightedKnownScore(components, 50), harmfulAdditives), 'Nicht vegetarisch laut Zutatenanalyse.', missingData, { hasKnownFacts: hasKnownComponents(components), criticalAdditiveCount: harmfulAdditives.length, details: scoreDetails }); + return withScore(weightedKnownScore(components, 50), 'Nicht vegetarisch laut Zutatenanalyse.', missingData, { hasKnownFacts: hasKnownComponents(components), goalConflict: true, details: scoreDetails }); } } - const score = cappedHarmfulAdditiveScore(weightedKnownScore(components, 50), harmfulAdditives); + const score = weightedKnownScore(components, 50); const hasKnownFacts = hasKnownComponents(components); - const ingredientOptions = { hasKnownFacts, criticalAdditiveCount: harmfulAdditives.length, details: scoreDetails }; + const ingredientOptions = { hasKnownFacts, goalReviewRequired: ['vegan', 'vegetarian'].includes(preferences.preferredDiet) + && (preferences.preferredDiet === 'vegan' ? vegan : vegetarian) === undefined, details: scoreDetails }; if (palmOil === true) { return withScore(score, 'Enthält Palmöl.', missingData, ingredientOptions); } if (harmfulAdditives.length > 0) { - return withScore(score, `Kritische Zusatzstoffe: ${formatAdditiveList(harmfulAdditives)}.`, missingData, ingredientOptions); + return withScore(score, `Zusatzstoffhinweise: ${formatAdditiveList(harmfulAdditives)}.`, missingData, ingredientOptions); } if (additives.length > 0) { @@ -353,7 +396,7 @@ function rateIngredients(product, preferences) { } return withScore(score, hasKnownFacts - ? 'Keine kritischen Zutatenhinweise gefunden.' + ? 'Keine auffälligen Zutatenhinweise gefunden.' : 'Zutatenangaben reichen für eine Bewertung nicht aus.', missingData, ingredientOptions); } @@ -379,6 +422,8 @@ function rateNutrition(product, preferences) { const options = { details, hasKnownFacts: Boolean(nutrition.nutriScore), + goalReviewRequired: (preferences.preferredDiet === 'lowSugar' && !Number.isFinite(nutrition.sugarPer100g)) + || (preferences.preferredDiet === 'highProtein' && !isBeverage(product) && !Number.isFinite(nutrition.proteinPer100g)), nutriScore: nutrition.nutriScore, nutriScoreSource: calculated ? 'calculated' : 'official' }; @@ -440,12 +485,9 @@ function rateSustainability(product, preferences) { const sustainability = product.sustainability || {}; const carbonFootprint = carbonFootprintValue(sustainability); const hasEcoScore = Boolean(ecoScoreValues[sustainability.ecoScore]); - const originCountry = scoredOriginCountry(product); const missingData = missingMessages([ [!sustainability.ecoScore, 'Eco-Score fehlt in Open Food Facts.'], - [!hasEcoScore && typeof carbonFootprint !== 'number', 'CO2-Fussabdruck ist nicht verfügbar.'], - [!hasEcoScore && !originCountry, 'Zutatenherkunft fehlt in Open Food Facts.'], - [!hasEcoScore && !sustainability.packaging, 'Verpackungsangabe fehlt in Open Food Facts.'] + [!hasEcoScore && typeof carbonFootprint !== 'number', 'CO2-Fussabdruck ist nicht verfügbar.'] ]); const components = sustainabilityScoreComponents(product, preferences); const score = weightedKnownScore(components, 50); @@ -470,10 +512,13 @@ function rateSustainability(product, preferences) { : options.hasKnownFacts ? 'Nachhaltigkeit anhand verfügbarer Angaben geschätzt.' : 'Nachhaltigkeitsangaben fehlen.', missingData, options); } -function rateBudget(product, preferences) { +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([ - [typeof product.price !== 'number', 'Produktpreis fehlt.'], - [typeof preferences.maxBudgetPerShoppingTrip !== 'number', 'Budgetlimit fehlt im Profil.'] + [!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) @@ -481,19 +526,31 @@ function rateBudget(product, preferences) { return withScore(55, 'Preis oder Budget fehlt für eine genaue Prüfung.', missingData, { hasKnownFacts: false }); } - const share = product.price / preferences.maxBudgetPerShoppingTrip; + 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, `Preis passt gut zu deinem Budget pro ${periodLabel}.`, missingData); + return withScore(score, `${contextText} nutzt nur einen kleinen Teil deines Budgets pro ${periodLabel}.`, missingData); } if (share <= 0.18) { - return withScore(score, `Preis ist für dein Budget pro ${periodLabel} spürbar, aber noch im Rahmen.`, missingData); + return withScore(score, `${contextText} nutzt einen spürbaren Teil deines Budgets pro ${periodLabel}.`, missingData); } - return withScore(score, `Preis belastet dein Budget pro ${periodLabel} stark.`, missingData); + return withScore(score, `${contextText} nutzt einen grossen Teil deines Budgets pro ${periodLabel}.`, missingData); } function nutritionScoreFromData(product, nutrition, nutrientLevels) { @@ -702,15 +759,15 @@ function proteinScore(proteinPer100g) { function additiveScore(additives, additivesKnown, harmfulAdditives = []) { if (harmfulAdditives.length >= 3) { - return 0; + return 25; } if (harmfulAdditives.length === 2) { - return 8; + return 40; } if (harmfulAdditives.length === 1) { - return 18; + return 55; } if (!additivesKnown) { @@ -732,39 +789,14 @@ function additiveScore(additives, additivesKnown, harmfulAdditives = []) { return 22; } -function cappedHarmfulAdditiveScore(score, harmfulAdditives) { - if (harmfulAdditives.length >= 3) { - return Math.min(score, 8); - } - - if (harmfulAdditives.length === 2) { - return Math.min(score, 14); - } - - if (harmfulAdditives.length === 1) { - return Math.min(score, 24); - } - - return score; -} - function ingredientScoreDetails({ additives, harmfulAdditives, palmOil, preferences, vegan, vegetarian }) { const details = harmfulAdditives.map((additive) => ({ type: 'penalty', - title: `Harter Abzug: ${additive.label}`, + title: `Hinweis zu ${additive.label}`, body: additive.reason, meta: `Typische Produkte: ${additive.examples}` })); - if (harmfulAdditives.length > 0) { - details.push({ - type: 'penalty', - title: 'Deckel für Gesamtbewertung', - body: 'Kritische Zusatzstoffe begrenzen nicht nur die Zutatenwertung, sondern auch den Gesamtscore, damit gute Werte in anderen Kategorien diese Stoffe nicht überdecken.', - meta: harmfulAdditives.length >= 3 ? 'Maximaler Gesamtscore: 35' : harmfulAdditives.length === 2 ? 'Maximaler Gesamtscore: 42' : 'Maximaler Gesamtscore: 47' - }); - } - if (palmOil === true) { details.push({ type: 'penalty', @@ -817,19 +849,13 @@ function ingredientScoreDetails({ additives, harmfulAdditives, palmOil, preferen return details; } -function sustainabilityScore(product, preferences) { - return weightedKnownScore(sustainabilityScoreComponents(product, preferences), 50); -} - function sustainabilityScoreComponents(product, preferences) { const sustainability = product.sustainability || {}; const ecoScore = ecoScoreValues[sustainability.ecoScore]; const components = ecoScore ? [scoreComponent(ecoScore, 3)] : [ - scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2), - scoreComponent(originScore(scoredOriginCountry(product)), 1), - scoreComponent(packagingScore(sustainability.packaging), 1) + scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2) ]; if (bioPreferenceApplies(product, preferences)) { @@ -992,48 +1018,6 @@ function carbonFootprintScore(carbonFootprint) { return clampScore(interpolate(Math.min(carbonFootprint, 10), 4, 10, 35, 5)); } -function originScore(originCountry) { - const origin = normalizeTerm(originCountry); - if (!origin) { - return null; - } - - if (['schweiz', 'switzerland', 'suisse', 'svizzera'].some((term) => origin.includes(term))) { - return 92; - } - - if (['deutschland', 'germany', 'france', 'frankreich', 'italy', 'italien', 'austria', 'österreich'].some((term) => origin.includes(term))) { - return 78; - } - - if (['european union', 'europa', 'europe'].some((term) => origin.includes(term)) || /\beu\b/.test(origin)) { - return 68; - } - - return 35; -} - -function packagingScore(packaging) { - const value = normalizeTerm(packaging); - if (!value) { - return null; - } - - if (['recycling', 'recycled', 'recyclable', 'mehrweg', 'returnable', 'pfand', 'glass', 'glas', 'paper', 'papier', 'cardboard', 'karton'].some((term) => value.includes(term))) { - return 88; - } - - if (['pet', 'tetra pak', 'carton', 'becher'].some((term) => value.includes(term))) { - return 58; - } - - if (['plastic', 'plastik', 'kunststoff', 'aluminium', 'aluminum', 'alu', 'dose', 'can'].some((term) => value.includes(term))) { - return 25; - } - - return 55; -} - function harmfulAdditiveMatches(additives, ingredients) { const additiveTexts = [ ...additives, @@ -1189,13 +1173,6 @@ function hasAnimalIngredient(ingredients, includeDairyAndEggs) { }); } -function scoredOriginCountry(product) { - const sustainability = product.sustainability || {}; - if (['open-food-facts', 'cache'].includes(product.dataSource) - && sustainability.originSource !== 'ingredient-origin') return undefined; - return sustainability.originCountry; -} - function isWaterLike(product) { const terms = productTerms(product); const nutrition = product.nutrition || {}; diff --git a/tests/ratingService.test.mjs b/tests/ratingService.test.mjs index 1f697dd..a43f1be 100644 --- a/tests/ratingService.test.mjs +++ b/tests/ratingService.test.mjs @@ -25,7 +25,8 @@ test('missing budget and allergen data do not contribute neutral placeholder sco }); test('profile priorities actually change the category weighting', () => { - const item = { nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'E' } }; + 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); @@ -124,10 +125,13 @@ test('missing values for personal goals do not invent a penalty', () => { assert.equal(highProtein.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score); }); -test('a critical additive in ingredient text counts without additive tags', () => { +test('a flagged additive in ingredient text counts without additive tags but has no global cap', () => { const rating = rate({ ingredients: ['Farbstoff E171'] }); assert.equal(rating.categoryScores.ingredients.hasKnownFacts, true); - assert.ok(rating.categoryScores.ingredients.score <= 24); + assert.equal(rating.categoryScores.ingredients.score, 55); + const complete = rate({ ingredients: ['Farbstoff E171'], nutrition: { nutriScore: 'A' }, + sustainability: { ecoScore: 'A' }, price: 1 }, { maxBudgetPerShoppingTrip: 100 }); + assert.ok(complete.overallScore > 47); }); test('flavoured water with sugar is not treated as plain water', () => { @@ -148,11 +152,11 @@ test('flavoured water with sugar is not treated as plain water', () => { assert.notEqual(rating.categoryScores.nutrition.score, 98); }); -test('country names containing eu are not mistaken for the EU', () => { +test('country of origin alone cannot establish sustainability', () => { const peru = rate({ sustainability: { originCountry: 'Peru' } }); const swiss = rate({ sustainability: { originCountry: 'Schweiz' } }); - assert.equal(peru.categoryScores.sustainability.score, 35); - assert.equal(swiss.categoryScores.sustainability.score, 92); + assert.equal(peru.categoryScores.sustainability.score, null); + assert.equal(swiss.categoryScores.sustainability.score, null); }); test('Eco-Score is not counted again through its environmental indicators', () => { @@ -163,7 +167,7 @@ test('Eco-Score is not counted again through its environmental indicators', () = assert.equal(rating.categoryScores.sustainability.score, 15); }); -test('alternatives exclude products whose allergens need review', async () => { +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'], allergens: ['Milch'], dataCompleteness: { allergens: true } @@ -179,5 +183,156 @@ test('alternatives exclude products whose allergens need review', async () => { const alternatives = await findAlternatives(source, { ...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true }, { unknown, verified }); - assert.deepEqual(alternatives.map((item) => item.product.id), ['verified']); + assert.deepEqual(alternatives.map((item) => item.product.id), ['verified', 'unknown']); + assert.equal(alternatives[0].requiresAllergenCheck, false); + assert.equal(alternatives[1].requiresAllergenCheck, true); + assert.match(alternatives[1].reason, /Allergenfreiheit ist nicht bestätigt/); +}); + +test('allergy-review alternatives remain discoverable when both displayed scores are capped', async () => { + const source = { id: 'source', barcode: '10', name: 'Original', categoryTags: ['en:snacks'], + nutrition: { nutriScore: 'C' }, sustainability: { ecoScore: 'A' }, allergens: [] }; + const candidate = { id: 'candidate', barcode: '11', name: 'Besser', categoryTags: ['en:snacks'], + nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'A' }, allergens: [] }; + const pref = { ...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true }; + const alternatives = await findAlternatives(source, pref, { candidate }); + assert.deepEqual(alternatives.map((item) => item.product.id), ['candidate']); + assert.equal(alternatives[0].requiresAllergenCheck, true); +}); + +test('a confirmed vegan conflict blocks a green recommendation', () => { + const rating = rate({ price: 1, ingredients: ['Milch', 'Hafer'], + ingredientAnalysis: { vegan: false, palmOil: false, additives: [] }, + dataCompleteness: { additives: true }, nutrition: { nutriScore: 'A' }, + sustainability: { ecoScore: 'A' } }, { preferredDiet: 'vegan', maxBudgetPerShoppingTrip: 100 }); + assert.equal(rating.goalConflict, true); + assert.equal(rating.overallStatus, 'critical'); + assert.ok(rating.overallScore <= 47); +}); + +test('missing sugar for a low-sugar goal limits the recommendation', () => { + const rating = rate({ nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'A' } }, + { preferredDiet: 'lowSugar' }); + assert.equal(rating.goalReviewRequired, true); + assert.notEqual(rating.overallStatus, 'good'); +}); + +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.notEqual(rating.overallStatus, 'good'); +}); + +test('budget includes open list prices and treats unknown prices as uncertainty', () => { + 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/); + const missing = calculateProductRating(item, { ...preferences, ...pref }, + { shoppingList: { items: [{ quantity: 1, checked: false }] } }); + assert.equal(missing.budgetReviewRequired, true); + assert.notEqual(missing.overallStatus, 'good'); +}); + +test('a category-average footprint has partial coverage', () => { + const rating = rate({ sustainability: { carbonFootprintKgCo2ePerKg: 0.5, + footprint: { status: 'estimated' } } }); + assert.ok(rating.dataCoverage > 0); + assert.ok(rating.dataCoverage < 50); +}); + +test('online alternatives search category pages for healthier drinks', async () => { + const source = { id: 'source', barcode: '100', name: 'Süsse Cola', + category: 'Sodas', categoryTags: ['en:beverages', 'en:sodas'], + nutrition: { nutriScore: 'D' }, sustainability: { ecoScore: 'A' }, price: 2 }; + const responses = { + 'en:sodas:1': [101, 102], + 'en:beverages:1': [103, 104, 105, 999], + 'en:sodas:2': [106, 107, 108] + }; + const requests = []; + const originalFetch = globalThis.fetch; + try { + globalThis.fetch = async (url) => { + const parsed = new URL(url); + requests.push(parsed); + const tag = parsed.searchParams.get('categories_tags'); + const page = parsed.searchParams.get('page'); + const products = (responses[`${tag}:${page}`] || []).map((code) => ({ + code: String(code), product_name: `Drink ${code}`, categories_tags: ['en:beverages', 'en:sodas'], + nutriscore_grade: 'a' + })); + const unrelated = products.find((item) => item.code === '999'); + if (unrelated) unrelated.categories_tags = ['en:plant-based-foods-and-beverages', 'en:snacks']; + return { ok: true, json: async () => ({ products }) }; + }; + const alternatives = await findAlternatives(source, + { ...preferences, maxBudgetPerShoppingTrip: 20, offlineModeEnabled: false }, {}); + assert.equal(alternatives.length, 8); + assert.ok(!alternatives.some((item) => item.product.barcode === '999')); + assert.ok(alternatives.every((item) => item.product.categoryTags.includes('en:beverages'))); + assert.ok(alternatives.every((item) => item.nutritionImprovement > 0)); + assert.ok(requests.some((url) => url.searchParams.get('page') === '2')); + assert.ok(requests.every((url) => url.pathname === '/api/v2/search' + && url.searchParams.get('nutrition_grades_tags') === 'a|b' + && Number(url.searchParams.get('page_size')) >= 40)); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test('offline alternatives use only saved products', async () => { + const source = { id: 'source', barcode: '1', categoryTags: ['en:beverages'], + nutrition: { nutriScore: 'E' } }; + const cached = { id: 'cached', barcode: '2', name: 'Wasser', categoryTags: ['en:beverages'], + nutrition: { nutriScore: 'A' } }; + const originalFetch = globalThis.fetch; + try { + globalThis.fetch = async () => { throw new Error('Network must not be used in offline mode.'); }; + const alternatives = await findAlternatives(source, + { ...preferences, offlineModeEnabled: true }, { cached }); + assert.deepEqual(alternatives.map((item) => item.product.id), ['cached']); + } 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'], + nutrition: { nutriScore: 'E' } }; + const first = { id: 'first', barcode: '2', name: 'Mineralwasser', brand: 'A', + categoryTags: ['en:beverages'], nutrition: { nutriScore: 'A' } }; + const second = { ...first, id: 'second', barcode: '3', brand: 'B' }; + const alternatives = await findAlternatives(source, + { ...preferences, offlineModeEnabled: true }, { first, second }); + assert.deepEqual(alternatives.map((item) => item.product.id), ['first', 'second']); +}); + +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'], + nutrition: { nutriScore: 'E' } }; + const originalFetch = globalThis.fetch; + const requests = []; + try { + globalThis.fetch = async (url) => { + 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'], + nutriscore_grade: 'a' }] }) }; + }; + const alternatives = await findAlternatives(source, { ...preferences, offlineModeEnabled: false }); + assert.deepEqual(alternatives.map((item) => item.product.barcode), ['2']); + assert.ok(requests.some((url) => !url.searchParams.has('nutrition_grades_tags'))); + + globalThis.fetch = async () => { throw new Error('offline'); }; + await assert.rejects(findAlternatives(source, { ...preferences, offlineModeEnabled: false }), + /nicht erreichbar/); + } finally { + globalThis.fetch = originalFetch; + } });