This commit is contained in:
@@ -10,7 +10,7 @@ export default function AlternativeProductCard({ item, onChoose, onOpen }) {
|
||||
<ProductCard product={item.product} rating={item.rating} onPress={onOpen} />
|
||||
<Text style={styles.reason}>{item.reason}</Text>
|
||||
<PrimaryButton
|
||||
label={typeof item.product.price === 'number' ? 'Zur Liste hinzufügen' : 'Produkt ansehen'}
|
||||
label={item.requiresAllergenCheck ? 'Allergene prüfen' : typeof item.product.price === 'number' ? 'Zur Liste hinzufügen' : 'Produkt ansehen'}
|
||||
onPress={onChoose}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -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 (
|
||||
<ScreenContainer>
|
||||
<AppHeader
|
||||
title="Alternativen"
|
||||
subtitle={`Bessere Optionen für ${product.name}`}
|
||||
subtitle={`Gesündere Optionen für ${product.name}`}
|
||||
onBack={onBack}
|
||||
/>
|
||||
|
||||
{isLoading ? <Text style={styles.note}>Alternativen werden berechnet...</Text> : null}
|
||||
{!isLoading && alternatives.length === 0 ? (
|
||||
{isLoading ? <Text style={styles.note}>{preferences.offlineModeEnabled
|
||||
? 'Gespeicherte Produkte werden verglichen...'
|
||||
: 'Open Food Facts wird nach gesünderen Produkten derselben Kategorie durchsucht...'}</Text> : null}
|
||||
{searchError ? <Text style={styles.note}>{searchError}</Text> : null}
|
||||
{searchError ? <PrimaryButton label="Erneut suchen" onPress={() => setRetryCount((count) => count + 1)} /> : null}
|
||||
{!isLoading && alternatives.length > 0 ? (
|
||||
<Text style={styles.note}>{alternatives.length} mögliche Alternative{alternatives.length === 1 ? '' : 'n'} gefunden. Die Ernährungswertung und weitere Kriterien stehen in den Produktdetails.</Text>
|
||||
) : null}
|
||||
{!isLoading && !searchError && alternatives.length === 0 ? (
|
||||
<View style={styles.empty}>
|
||||
<Text style={styles.emptyTitle}>Keine Alternative gefunden</Text>
|
||||
<Text style={styles.emptyCopy}>Für dieses Produkt wurde in ähnlichen Kategorien noch keine klar bessere Option gefunden.</Text>
|
||||
<Text style={styles.emptyCopy}>{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.'}</Text>
|
||||
</View>
|
||||
) : 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;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList,
|
||||
<View key={`frequent-${product.id}`} style={styles.frequentWrap}>
|
||||
<ProductCard
|
||||
product={product}
|
||||
rating={calculateProductRating(product, preferences)}
|
||||
rating={calculateProductRating(product, preferences, { shoppingList })}
|
||||
onPress={() => onOpenProduct(product)}
|
||||
/>
|
||||
<Text style={styles.scanCount}>{product.scanCount} Scans</Text>
|
||||
@@ -72,7 +72,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList,
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
product={product}
|
||||
rating={calculateProductRating(product, preferences)}
|
||||
rating={calculateProductRating(product, preferences, { shoppingList })}
|
||||
onPress={() => onOpenProduct(product)}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -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({
|
||||
<View style={[styles.recommendation, styles[`${rating.overallStatus}Recommendation`]]}>
|
||||
<Text style={[styles.recommendationTitle, styles[`${rating.overallStatus}Text`]]}>{recommendation}</Text>
|
||||
<Text style={styles.recommendationCopy}>
|
||||
{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)}
|
||||
</Text>
|
||||
<Text style={styles.recommendationCopy}>Bewertbare Daten: {rating.dataCoverage}% der für dein Profil anwendbaren Kriterien (gewichtet).</Text>
|
||||
</View>
|
||||
@@ -140,7 +153,7 @@ export default function ProductDetailScreen({
|
||||
</View>
|
||||
) : null}
|
||||
<PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} />
|
||||
<SecondaryButton label="Bessere Alternativen suchen" onPress={() => onShowAlternatives(product)} />
|
||||
<SecondaryButton label="Bessere Alternativen suchen" onPress={() => onShowAlternatives(pricedProduct)} />
|
||||
|
||||
<SectionTitle>Bewertungskriterien</SectionTitle>
|
||||
{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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
product={product}
|
||||
rating={calculateProductRating(product, preferences)}
|
||||
rating={calculateProductRating(product, preferences, { shoppingList })}
|
||||
onPress={() => onOpenProduct(product)}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
+106
-129
@@ -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 || {};
|
||||
|
||||
Reference in New Issue
Block a user