add better eco ratings
Android Release Build / build-android (push) Failing after 7m36s

This commit is contained in:
Frederik Spirgi
2026-10-26 11:31:20 +01:00
parent b49d5aa171
commit 26a52658aa
14 changed files with 1020 additions and 155 deletions
+7 -2
View File
@@ -3,7 +3,8 @@ import { StyleSheet, Text, View } from 'react-native';
const labels = {
good: 'Gut',
medium: 'Prüfen',
critical: 'Meiden'
critical: 'Meiden',
unknown: 'Daten fehlen'
};
const statusStyles = {
@@ -18,6 +19,10 @@ const statusStyles = {
critical: {
backgroundColor: '#fee4e2',
color: '#b42318'
},
unknown: {
backgroundColor: '#edf1ee',
color: '#52665d'
}
};
@@ -27,7 +32,7 @@ export default function ProductScoreBadge({ status, score }) {
return (
<View style={[styles.badge, { backgroundColor: style.backgroundColor }]}>
<Text style={[styles.text, { color: style.color }]}>
{labels[status] || 'Prüfen'} · {score}
{labels[status] || 'Prüfen'}{score === null || score === undefined ? '' : ` · ${score}`}
</Text>
</View>
);
+65 -3
View File
@@ -35,7 +35,10 @@ export default function ProductDetailScreen({
price: hasProductPrice ? product.price : parsedManualPrice
}), [currency, hasProductPrice, parsedManualPrice, product]);
const rating = useMemo(() => calculateProductRating(pricedProduct, preferences), [pricedProduct, preferences]);
const recommendation = rating.overallStatus === 'good' ? 'Passt gut zu dir' : rating.overallStatus === 'medium' ? 'Genauer prüfen' : 'Lieber meiden';
const footprint = product.sustainability?.footprint;
const recommendation = rating.overallStatus === 'good' ? 'Passt gut zu dir'
: rating.overallStatus === 'critical' ? 'Lieber meiden'
: rating.overallStatus === 'unknown' ? 'Zu wenig Daten' : 'Genauer prüfen';
function addToList() {
if (!hasProductPrice && manualPrice.trim() && parsedManualPrice === undefined) {
@@ -75,7 +78,11 @@ export default function ProductDetailScreen({
<Text style={styles.recommendationCopy}>
{rating.allergenReviewRequired
? 'Allergenangaben fehlen oder sind nicht bestätigt. Prüfe vor dem Kauf die Verpackung.'
: 'Tippe unten auf ein Kriterium, um die Bewertung nachzuvollziehen.'}
: 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.'}
</Text>
</View>
</View>
@@ -127,13 +134,48 @@ export default function ProductDetailScreen({
/>
))}
<SectionTitle>Umweltwirkung</SectionTitle>
<View style={styles.dataPanel}>
{footprint?.status === 'product-specific' || footprint?.status === 'estimated' ? (
<>
<Text style={styles.dataText}>
CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg
</Text>
<Text style={styles.dataText}>
{footprint.status === 'product-specific' ? 'Produktspezifische Angabe aus Open Food Facts.'
: `Schätzung anhand vergleichbarer Lebensmittel: ${footprint.referenceCategory}. AGRIBALYSE-Durchschnitt, keine Messung dieses Markenprodukts.`}
</Text>
{typeof footprint.packageKgCo2e === 'number' ? (
<Text style={styles.dataText}>
Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e
</Text>
) : null}
<Text style={styles.dataText}>
Quelle: {footprint.source === 'AGRIBALYSE' ? 'ADEME / ' : ''}{footprint.source}{footprint.datasetVersion ? ` ${footprint.datasetVersion}` : ''}
{footprint.datasetUpdatedAt ? ` · Datenstand ${footprint.datasetUpdatedAt.slice(0, 10)}` : ''}
{footprint.sourceUpdatedAt ? ` · OFF-Stand ${footprint.sourceUpdatedAt.slice(0, 10)}` : ''}
{footprint.sourceId ? ` · Kennung ${footprint.sourceId}` : ''}
{footprint.matchMethod ? ` · Zuordnung: ${matchLabel(footprint.matchMethod)}` : ''}
</Text>
{footprint.status === 'estimated' ? (
<>
<Text style={styles.dataText}>Landnutzung: {formatIndicator(footprint.indicators?.landUse)}</Text>
<Text style={styles.dataText}>Wasserknappheit: {formatIndicator(footprint.indicators?.waterScarcity)}</Text>
<Text style={styles.dataText}>Gesamtwirkung (EF): {formatIndicator(footprint.indicators?.singleScore)}</Text>
<Text style={styles.dataText}>Lebenszyklus bis zum verzehrbaren Lebensmittel; Transport und Verpackung sind im Datensatz enthalten. Diese Indikatoren sind keine CO₂-Werte.</Text>
</>
) : null}
</>
) : <Text style={styles.dataText}>CO₂-Fussabdruck: Nicht verfügbar.</Text>}
<Text style={styles.dataText}>Green-Score (Open Food Facts): {product.sustainability?.ecoScore || 'Nicht verfügbar'}</Text>
</View>
<SectionTitle>Produktdaten</SectionTitle>
<View style={styles.dataPanel}>
<Text style={styles.dataText}>Barcode: {product.barcode}</Text>
<Text style={styles.dataText}>Zutaten: {(product.ingredients || []).join(', ') || 'Keine Angaben'}</Text>
<Text style={styles.dataText}>Allergene: {(product.allergens || []).join(', ') || 'Keine Angaben'}</Text>
<Text style={styles.dataText}>Nutri-Score: {product.nutrition?.nutriScore || 'Keine Angabe'}</Text>
<Text style={styles.dataText}>Eco-Score: {product.sustainability?.ecoScore || 'Keine Angabe'}</Text>
</View>
</ScreenContainer>
@@ -161,6 +203,24 @@ function sourceLabel(source) {
return labels[source] || 'Quelle: unbekannt';
}
function formatImpact(value, maximumFractionDigits = 2) {
return new Intl.NumberFormat('de-CH', { maximumFractionDigits, minimumFractionDigits: value < 0.01 ? 3 : 0 }).format(value);
}
function formatIndicator(indicator) {
if (typeof indicator?.value !== 'number') return 'Nicht verfügbar';
return `${new Intl.NumberFormat('de-CH', { maximumSignificantDigits: 3 }).format(indicator.value)} ${indicator.unit}`;
}
function matchLabel(method) {
return {
'off-category-code': 'OFF-Kategoriecode',
'off-category-proxy': 'OFF-Kategorieproxy',
'reviewed-category-map': 'geprüfte Kategoriezuordnung',
'normalized-name-in-category': 'normalisierter Name innerhalb der Kategorie'
}[method] || method;
}
const styles = StyleSheet.create({
productPanel: {
backgroundColor: colors.surface,
@@ -215,6 +275,7 @@ const styles = StyleSheet.create({
goodRecommendation: { backgroundColor: '#e4f4e9' },
mediumRecommendation: { backgroundColor: '#fff3d7' },
criticalRecommendation: { backgroundColor: '#fee9e7' },
unknownRecommendation: { backgroundColor: '#edf1ee' },
recommendationTitle: {
fontSize: 17,
fontWeight: '800'
@@ -222,6 +283,7 @@ const styles = StyleSheet.create({
goodText: { color: colors.success },
mediumText: { color: '#8a5914' },
criticalText: { color: colors.danger },
unknownText: { color: colors.muted },
recommendationCopy: {
color: colors.text,
fontSize: 13,
+7 -1
View File
@@ -72,7 +72,8 @@ export default function RatingCriteriaDetailScreen({ product, preferences, categ
<Text style={styles.panelTitle}>So entsteht die Bewertung</Text>
{categoryRating.details.map((detail) => (
<View key={`${detail.title}-${detail.meta || ''}`} style={styles.detailItem}>
<Text style={detail.type === 'positive' ? styles.positiveTitle : styles.penaltyTitle}>
<Text style={detail.type === 'positive' ? styles.positiveTitle
: detail.type === 'penalty' ? styles.penaltyTitle : styles.infoTitle}>
{detail.title}
</Text>
<Text style={styles.detailBody}>{detail.body}</Text>
@@ -159,6 +160,11 @@ const styles = StyleSheet.create({
fontSize: 14,
fontWeight: '800'
},
infoTitle: {
color: colors.muted,
fontSize: 14,
fontWeight: '800'
},
detailBody: {
color: colors.muted,
fontSize: 14,
+10 -4
View File
@@ -1,5 +1,5 @@
import { searchProducts } from './productApi';
import { calculateProductRating } from './ratingService';
import { searchProducts } from './productApi.js';
import { calculateProductRating } from './ratingService.js';
const MIN_SCORE_IMPROVEMENT = 5;
const INTERNAL_ALTERNATIVE_LIMIT = 8;
@@ -33,6 +33,7 @@ const categoryGroups = [
export async function findAlternatives(product, preferences, productCache = {}) {
const productRating = calculateProductRating(product, preferences);
if (productRating.overallScore === null) return [];
const categoryTerms = categoryTermsForProduct(product);
const remoteCandidates = await loadRemoteCandidates(categoryTerms, productCache, preferences.offlineModeEnabled);
const candidates = uniqueProducts([
@@ -49,7 +50,10 @@ export async function findAlternatives(product, preferences, productCache = {})
rating: calculateProductRating(candidate, preferences),
dataQualityScore: knownDataScore(candidate)
}))
.filter((item) => item.rating.overallScore >= productRating.overallScore + MIN_SCORE_IMPROVEMENT)
.filter((item) => !item.rating.allergenReviewRequired)
.filter((item) => productRating.overallScore !== null
&& item.rating.overallScore !== null
&& item.rating.overallScore >= productRating.overallScore + MIN_SCORE_IMPROVEMENT)
.map((item) => ({
...item,
reason: buildReason(item.rating, productRating, categoryTerms)
@@ -179,7 +183,9 @@ function strongestCategoryImprovement(rating, sourceRating) {
category,
improvement: categoryScore(rating, category) - categoryScore(sourceRating, category)
}))
.filter((item) => item.improvement > 0)
.filter((item) => item.improvement > 0
&& rating.categoryScores[item.category]?.hasKnownFacts !== false
&& sourceRating.categoryScores[item.category]?.hasKnownFacts !== false)
.sort((left, right) => right.improvement - left.improvement)[0];
}
+204
View File
@@ -0,0 +1,204 @@
import agribalyse from '../data/agribalyse.js';
export const ENVIRONMENTAL_RULES_VERSION = '1';
export const MATCHING_CONFIG = Object.freeze({ minNameTokenSimilarity: 1, minLeadOverNext: 0.15 });
const byId = new Map(agribalyse.products.map((entry) => [entry.id, entry]));
const resolved = new Map();
// Reviewed mappings from OFF taxonomy tags to exact AGRIBALYSE finished-food codes.
// Extend only after checking preparation, edible portion and product composition.
export const CATEGORY_MAPPINGS = Object.freeze({
'en:apples': '13039',
'en:bananas': '13005',
'en:oranges': '13034',
'en:strawberries': '13014_1',
'en:carrots': '20009',
'en:tomatoes': '20047_1',
'en:baguettes': '7001',
'en:eggs': '22000'
});
const incompatible = /\b(juices?|saft|jus|nectar|smoothie|dried|dry|getrocknet|seche|cooked|gekocht|cuit|frozen|gefroren|surgele|concentrat|puree|pulp|compote|sauce|suppe|soup|salad|salat|mixed|mischung|mix|flavour|flavor|aroma|stuffed|gefullt|sirop|syrup)\b/;
const composite = /\b(with|and|mit|und|avec|et)\b/;
const tagIdentity = {
'en:apples': 'apple', 'en:bananas': 'banana', 'en:oranges': 'orange',
'en:strawberries': 'strawberry', 'en:carrots': 'carrot',
'en:tomatoes': 'tomato', 'en:baguettes': 'baguette', 'en:eggs': 'egg'
};
const processing = {
juice: /\b(juice|juices|saft|jus)\b/,
smoothie: /\b(smoothie|smoothies)\b/,
dried: /\b(dried|dehydrated|getrocknet|seche|trocken)\b/,
frozen: /\b(frozen|gefroren|surgele|tiefkuhl)\b/,
cooked: /\b(cooked|gekocht|boiled|fried|roasted|gebraten|cuit)\b/,
sauce: /\b(sauce|sosse|soupe|soup)\b/
};
const statePatterns = {
cooked: /\b(cooked|gekocht|boiled|fried|roasted|gebraten|gerostet|cuit|grille)\b/,
dried: /\b(dried|dehydrated|getrocknet|seche|trocken)\b/,
frozen: /\b(frozen|gefroren|surgele|tiefkuhl)\b/,
concentrated: /\b(concentrat|concentrated|konzentrat)\b/,
raw: /\b(raw|roh|cru|fresh|frisch|frais)\b/
};
function normalize(value) {
return String(value || '').normalize('NFKD').replace(/[\u0300-\u036f]/g, '')
.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
}
function tokenSimilarity(left, right) {
const a = new Set(normalize(left).split(' ').filter(Boolean));
const b = new Set(normalize(right).split(' ').filter(Boolean));
if (!a.size || !b.size) return 0;
const intersection = [...a].filter((token) => b.has(token)).length;
return intersection / (a.size + b.size - intersection);
}
function state(value) {
const normalized = normalize(value);
return Object.entries(statePatterns).find(([, pattern]) => pattern.test(normalized))?.[0];
}
function statesCompatible(product, entry) {
const productState = state([product.name, product.category, ...(product.categoryTags || [])].join(' '));
const entryState = state(entry.nameEn);
if (productState && productState !== entryState) return false;
const productText = normalize([product.name, product.category, ...(product.categoryTags || [])].join(' '));
const entryText = normalize(entry.nameEn);
if ((product.ingredients || []).length > 1
&& (product.categoryTags || []).some((tag) => CATEGORY_MAPPINGS[tag])) return false;
if (Object.values(processing).some((pattern) => pattern.test(productText) !== pattern.test(entryText)
&& pattern.test(productText))) return false;
return (product.categoryTags || []).every((tag) => !tagIdentity[tag]
|| new RegExp(`\\b${tagIdentity[tag]}\\b`).test(entryText));
}
function validNonnegative(value) {
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
}
function massGrams(product) {
const label = String(product.packageQuantityLabel || '').trim().replace(',', '.');
const match = label.match(/^(?:(\d+)\s*[x×]\s*)?(\d+(?:\.\d+)?)\s*(kg|g)\b/i);
if (!match || /\b(drained|abtropf|égoutt)/i.test(label)) return undefined;
const count = Number(match[1] || 1);
const grams = count * Number(match[2]) * (match[3].toLowerCase() === 'kg' ? 1000 : 1);
// OFF product_quantity is sometimes a volume quantity. The label must confirm mass.
return Number.isFinite(grams) && grams > 0 && grams <= 100000 ? grams : undefined;
}
function unavailable(reason = 'no-reliable-match') {
return { status: 'unavailable', reason };
}
function candidate(product) {
const properties = product.agribalyseCodes || {};
const directCode = properties.foodCode;
const proxyCode = properties.proxyFoodCode;
for (const [code, method] of [[directCode, 'off-category-code'], [proxyCode, 'off-category-proxy']]) {
const entry = byId.get(String(code || ''));
if (entry && statesCompatible(product, entry)) return { entry, method, confidence: method === 'off-category-code' ? 'high' : 'medium' };
}
if (directCode || proxyCode) return null; // Do not override a conflicting OFF classification.
const tags = (product.categoryTags || []).filter((tag) => CATEGORY_MAPPINGS[tag]);
const codes = [...new Set(tags.map((tag) => CATEGORY_MAPPINGS[tag]))];
if (codes.length > 1) return null;
if (codes.length === 1) {
const description = normalize([product.name, product.category, ...(product.categoryTags || [])].join(' '));
if (incompatible.test(description) || composite.test(normalize(product.name))) return null;
const entry = byId.get(codes[0]);
if (entry && statesCompatible(product, entry)) return { entry, method: 'reviewed-category-map', confidence: 'medium' };
}
// Names are compared only within a compatible food group. The default
// threshold requires the full normalized token set to agree.
const groups = groupConstraints(product.categoryTags || []);
if (!groups.length) return null;
const name = normalize(product.name);
if (!name || composite.test(name)) return null;
const matches = agribalyse.products.filter((entry) =>
groups.some((group) => normalize(entry.group).includes(group)) && statesCompatible(product, entry)
).map((entry) => ({ entry, score: Math.max(tokenSimilarity(name, entry.nameEn), tokenSimilarity(name, entry.nameFr)) }))
.filter((item) => item.score >= MATCHING_CONFIG.minNameTokenSimilarity)
.sort((a, b) => b.score - a.score);
if (!matches.length || (matches[1] && matches[0].score - matches[1].score < MATCHING_CONFIG.minLeadOverNext)) return null;
return { entry: matches[0].entry, method: 'normalized-name-in-category', confidence: 'medium', matchScore: matches[0].score };
}
function groupConstraints(tags) {
const groups = {
'en:fruits': 'fruits legumes',
'en:vegetables': 'fruits legumes',
'en:breads': 'produits cerealiers',
'en:meats': 'viandes',
'en:cheeses': 'lait et produits laitiers',
'en:milk': 'lait et produits laitiers',
'en:beverages': 'boissons'
};
return tags.map((tag) => groups[tag]).filter(Boolean);
}
function estimate(match, product) {
const { entry, method, confidence, matchScore } = match;
const quantityGrams = massGrams(product);
return {
status: 'estimated', kind: 'category-average', valueKgCo2ePerKg: entry.climate,
unit: 'kg CO2e/kg', source: 'AGRIBALYSE', sourceId: entry.id,
datasetVersion: agribalyse.version, datasetUpdatedAt: agribalyse.dataUpdatedAt,
sourceUnit: agribalyse.units.climate, referenceCategory: entry.nameEn,
ciqualCode: entry.ciqualCode, matchMethod: method, confidence,
...(typeof matchScore === 'number' ? { matchScore } : {}),
calculation: 'Finished-food life-cycle impact per kg; no extra transport or packaging added.',
indicators: {
landUse: { value: entry.landUse, unit: agribalyse.units.landUse },
waterScarcity: { value: entry.waterScarcity, unit: agribalyse.units.waterScarcity },
singleScore: { value: entry.singleScore, unit: agribalyse.units.singleScore }
},
...(quantityGrams ? { packageKgCo2e: entry.climate * quantityGrams / 1000, packageQuantityGrams: quantityGrams } : {})
};
}
export function enrichEnvironmentalProduct(product) {
// Local sample/manual products can carry their own existing sustainability data.
if (!String(product.id || '').startsWith('off-') && product.dataSource !== 'open-food-facts') return product;
const sustainability = product.sustainability || {};
const current = sustainability.footprint;
const cacheVersion = `${agribalyse.version}:${agribalyse.dataUpdatedAt}:${ENVIRONMENTAL_RULES_VERSION}`;
if (current?.status === 'product-specific') return product;
if (current && sustainability.environmentalCacheVersion === cacheVersion) return product;
const cacheKey = JSON.stringify([product.barcode, product.name, product.category, product.categoryTags,
product.ingredients, product.agribalyseCodes, product.packageQuantityLabel, cacheVersion]);
let footprint = resolved.get(cacheKey);
if (!footprint) {
const match = candidate(product);
footprint = match ? estimate(match, product) : unavailable();
resolved.set(cacheKey, footprint);
}
return { ...product, sustainability: {
...sustainability, footprint,
carbonFootprintKgCo2ePerKg: footprint.status === 'estimated' ? footprint.valueKgCo2ePerKg : undefined,
environmentalCacheVersion: cacheVersion
} };
}
export function productSpecificFootprint(nutriments, quantityLabel, sourceUpdatedAt, categoryTags = []) {
// OFF's _100g fields are per 100 ml for liquids; no density is available here.
if (/\b(?:ml|cl|l)\b/i.test(String(quantityLabel || ''))
|| (Array.isArray(categoryTags) && categoryTags.some((tag) => /^(?:en:)?(?:beverages|drinks|juices|waters|milks)$/.test(tag)))) {
return unavailable('volume-needs-density');
}
const gramsPer100g = nutriments?.['carbon-footprint_100g'];
if (!validNonnegative(gramsPer100g)) return unavailable('no-product-footprint');
const value = gramsPer100g / 100; // g CO2e/100g -> kg CO2e/kg
const quantityGrams = massGrams({ packageQuantityLabel: quantityLabel });
return {
status: 'product-specific', kind: 'product-reported', source: 'Open Food Facts',
sourceId: 'nutriments.carbon-footprint_100g', sourceUnit: 'g CO2e/100g',
...(typeof sourceUpdatedAt === 'string' ? { sourceUpdatedAt } : {}),
valueKgCo2ePerKg: value, unit: 'kg CO2e/kg',
calculation: 'Reported product value converted from g CO2e/100g to kg CO2e/kg.',
...(quantityGrams ? { packageKgCo2e: value * quantityGrams / 1000, packageQuantityGrams: quantityGrams } : {})
};
}
+113
View File
@@ -0,0 +1,113 @@
// Updated Nutri-Score algorithm, exhibit 1-B (March 2025):
// https://www.santepubliquefrance.fr/sites/default/files/rdd/document/march2025CoU_EN.pdf
const FOOD_SUGAR = [3.4, 6.8, 10, 14, 17, 20, 24, 27, 31, 34, 37, 41, 44, 48, 51];
const SALT = [0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6, 2.8, 3, 3.2, 3.4, 3.6, 3.8, 4];
const FIBER = [3, 4.1, 5.2, 6.3, 7.4];
const PROTEIN = [2.4, 4.8, 7.2, 9.6, 12, 14, 17];
const DRINK_ENERGY = [30, 90, 150, 210, 240, 270, 300, 330, 360, 390];
const DRINK_SUGAR = [0.5, 2, 3.5, 5, 6, 7, 8, 9, 10, 11];
function known(value) {
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
}
function points(value, thresholds) {
return thresholds.reduce((count, threshold) => count + (value > threshold ? 1 : 0), 0);
}
function grade(score, type, water) {
if (type === 'beverage') {
if (water) return 'A';
if (score <= 2) return 'B';
if (score <= 6) return 'C';
if (score <= 9) return 'D';
return 'E';
}
if (score <= (type === 'fat' ? -6 : 0)) return 'A';
if (score <= 2) return 'B';
if (score <= 10) return 'C';
if (score <= 18) return 'D';
return 'E';
}
function productType(product, beverage) {
if (beverage) return 'beverage';
const fatCategories = new Set([
'fats', 'oils', 'vegetable-oils', 'animal-fats', 'butter', 'butters',
'margarine', 'margarines', 'nuts', 'seeds', 'nut-butters', 'peanut-butter',
'cream', 'creams', 'fresh-cream', 'sour-cream', 'creme-fraiche'
]);
return categoryNames(product).some((category) => fatCategories.has(category)) ? 'fat' : 'food';
}
function categoryNames(product) {
return [product.category, ...(product.categoryTags || [])]
.filter(Boolean)
.map((category) => String(category).toLowerCase().replace(/^[a-z]{2}:/, '').replace(/\s+/g, '-'));
}
export function calculateNutriScore(product, beverage = false, water = false) {
const categories = categoryNames(product);
const excludedCategories = new Set([
'alcoholic-beverages', 'beers', 'wines', 'spirits', 'baby-foods',
'infant-formulas', 'follow-on-formulas', 'sports-nutrition',
'meal-replacements', 'foods-for-special-medical-purposes'
]);
if (categories.some((category) => excludedCategories.has(category))) return null;
const nutrition = product.nutrition || {};
const type = productType(product, beverage);
const energy = known(nutrition.energyKjPer100g)
? nutrition.energyKjPer100g
: known(nutrition.caloriesPer100g) ? nutrition.caloriesPer100g * 4.184 : undefined;
const { saturatedFatPer100g: saturated, sugarPer100g: sugar, saltPer100g: salt } = nutrition;
if (!(type === 'fat' ? [saturated, sugar, salt, nutrition.fatPer100g]
: [energy, saturated, sugar, salt]).every(known)) return null;
if (type === 'fat' && (!known(nutrition.fatPer100g) || nutrition.fatPer100g === 0)) return null;
if (type === 'beverage' && typeof nutrition.hasNonNutritiveSweeteners !== 'boolean') return null;
const negative = type === 'beverage'
? points(energy, DRINK_ENERGY)
+ points(sugar, DRINK_SUGAR)
+ points(saturated, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+ points(salt, SALT)
+ (nutrition.hasNonNutritiveSweeteners ? 4 : 0)
: type === 'fat'
? points(saturated * 37, [120, 240, 360, 480, 600, 720, 840, 960, 1080, 1200])
+ points(sugar, FOOD_SUGAR)
+ [10, 16, 22, 28, 34, 40, 46, 52, 58, 64].reduce(
(count, threshold) => count + (saturated / nutrition.fatPer100g * 100 >= threshold ? 1 : 0), 0
)
+ points(salt, SALT)
: points(energy, [335, 670, 1005, 1340, 1675, 2010, 2345, 2680, 3015, 3350])
+ points(saturated, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
+ points(sugar, FOOD_SUGAR)
+ points(salt, SALT);
// Missing positive nutrients can change a grade. Only publish a fallback
// when every possible value of an unknown component gives the same letter.
const fiber = nutrition.fiberPer100g;
const protein = nutrition.proteinPer100g;
const fruit = nutrition.fruitVegetableLegumePercent;
const fiberMin = known(fiber) ? points(fiber, FIBER) : 0;
const fiberMax = known(fiber) ? fiberMin : 5;
const proteinThresholds = type === 'beverage' ? [1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3] : PROTEIN;
const redMeat = categories.some((category) => ['red-meat', 'beef', 'pork', 'lamb', 'veal'].includes(category));
const proteinCap = redMeat ? 2 : 7;
const proteinMin = known(protein) ? Math.min(points(protein, proteinThresholds), proteinCap) : 0;
const proteinMax = known(protein) ? proteinMin : proteinCap;
const fruitPoints = (value) => type === 'beverage'
? value > 80 ? 6 : value > 60 ? 4 : value > 40 ? 2 : 0
: value > 80 ? 5 : value > 60 ? 2 : value > 40 ? 1 : 0;
const fruitMin = known(fruit) ? fruitPoints(fruit) : 0;
const fruitMax = known(fruit) ? fruitMin : type === 'beverage' ? 6 : 5;
const cheese = categories.some((category) => ['cheese', 'cheeses', 'processed-cheeses', 'käse', 'kaese', 'fromage'].includes(category));
const includeProtein = type === 'beverage' || cheese || negative < (type === 'fat' ? 7 : 11);
const best = negative - fiberMax - fruitMax - (includeProtein ? proteinMax : 0);
const worst = negative - fiberMin - fruitMin - (includeProtein ? proteinMin : 0);
const bestGrade = grade(best, type, water);
if (bestGrade !== grade(worst, type, water)) return null;
return { grade: bestGrade, estimated: ![fiber, protein, fruit].every(known), score: worst };
}
+61 -25
View File
@@ -1,6 +1,9 @@
import { enrichEnvironmentalProduct, productSpecificFootprint } from './environmentalService.js';
const openFoodFactsBaseUrl = 'https://world.openfoodfacts.org';
const productFields = [
'code',
'last_modified_datetime',
'product_name',
'product_name_de',
'product_name_en',
@@ -10,6 +13,10 @@ const productFields = [
'image_url',
'product_quantity',
'quantity',
'net_weight_value',
'net_weight_unit',
'drained_weight_value',
'drained_weight_unit',
'serving_quantity',
'ingredients_text',
'ingredients_text_de',
@@ -21,8 +28,15 @@ const productFields = [
'nutriments',
'nutrient_levels',
'nutriscore_grade',
'nutrition_grades',
'ecoscore_grade',
'ecoscore_score',
'ecoscore_data',
'environmental_score_score',
'environmental_score_grade',
'environmental_score_data',
'categories_properties',
'agribalyse',
'labels_tags',
'origins',
'origins_tags',
@@ -35,7 +49,7 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline
const cachedProduct = productCache[normalizedBarcode] || productCache[barcode];
if (cachedProduct) {
return { status: 'found', product: { ...cachedProduct, dataSource: 'cache' }, source: 'cache' };
return { status: 'found', product: { ...enrichEnvironmentalProduct(cachedProduct), dataSource: 'cache' }, source: 'cache' };
}
if (offlineModeEnabled) {
@@ -58,7 +72,7 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline
}
const payload = await response.json();
if (payload.status !== 1 || !payload.product) {
if (payload?.status !== 1 || !payload.product || typeof payload.product !== 'object' || Array.isArray(payload.product)) {
return {
status: 'notFound',
errorMessage: 'Kein Produkt zu diesem Barcode in Open Food Facts gefunden.'
@@ -87,7 +101,7 @@ export async function searchProducts(query, productCache = {}, offlineModeEnable
}
if (offlineModeEnabled) {
return filterProducts(markProductsSource(cachedProducts, 'cache'), normalizedQuery);
return filterProducts(markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache'), normalizedQuery);
}
try {
@@ -97,42 +111,51 @@ export async function searchProducts(query, productCache = {}, offlineModeEnable
if (!response.ok) {
return filterProducts([
...markProductsSource(cachedProducts, 'cache')
...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery);
}
const payload = await response.json();
const apiProducts = (payload.products || [])
.filter((product) => product.code)
const apiProducts = (Array.isArray(payload?.products) ? payload.products : [])
.filter((product) => product && typeof product === 'object' && product.code)
.map((product) => mapOpenFoodFactsProduct(product, product.code));
return uniqueProducts(filterProducts([
...apiProducts,
...markProductsSource(cachedProducts, 'cache')
...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery));
} catch (error) {
return filterProducts([
...markProductsSource(cachedProducts, 'cache')
...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery);
}
}
function mapOpenFoodFactsProduct(product, fallbackBarcode) {
export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
const barcode = normalizeBarcode(product.code || fallbackBarcode);
const nutriments = product.nutriments || {};
const nutriScore = normalizeGrade(product.nutriscore_grade) || normalizeGrade(product.nutrition_grades);
const ecoScore = normalizeGrade(product.environmental_score_grade) || normalizeGrade(product.ecoscore_grade);
const agribalyseCode = product.environmental_score_data?.agribalyse?.code
|| product.ecoscore_data?.agribalyse?.code || product.agribalyse?.code;
const footprint = productSpecificFootprint(nutriments, product.quantity, product.last_modified_datetime, product.categories_tags);
const now = new Date().toISOString();
return {
return enrichEnvironmentalProduct({
id: `off-${barcode}`,
barcode,
dataSource: 'open-food-facts',
name: product.product_name_de || product.product_name || product.product_name_en || `Produkt ${barcode}`,
brand: firstTextValue(product.brands),
category: firstCategory(product.categories, product.categories_tags),
categoryTags: normalizeTags(product.categories_tags || []),
categoryTags: normalizeTags(product.categories_tags),
agribalyseCodes: {
foodCode: product.categories_properties?.['agribalyse_food_code:en'] || agribalyseCode,
proxyFoodCode: product.categories_properties?.['agribalyse_proxy_food_code:en']
},
imageUrl: product.image_url,
packageQuantityGrams: numberOrUndefined(product.product_quantity),
packageQuantityLabel: firstTextValue(product.quantity),
packageQuantityLabel: typeof product.quantity === 'string' ? product.quantity.trim() : undefined,
servingQuantityGrams: numberOrUndefined(product.serving_quantity),
price: undefined,
currency: 'CHF',
@@ -146,33 +169,42 @@ function mapOpenFoodFactsProduct(product, fallbackBarcode) {
allergens: normalizeAllergens(product.allergens_tags || []),
nutrition: {
caloriesPer100g: numberOrUndefined(nutriments['energy-kcal_100g']),
energyKjPer100g: numberOrUndefined(nutriments['energy-kj_100g'] ?? nutriments.energy_100g),
sugarPer100g: numberOrUndefined(nutriments.sugars_100g),
caffeineMgPer100g: normalizeCaffeineMg(nutriments.caffeine_100g),
fatPer100g: numberOrUndefined(nutriments.fat_100g),
saturatedFatPer100g: numberOrUndefined(nutriments['saturated-fat_100g']),
proteinPer100g: numberOrUndefined(nutriments.proteins_100g),
fiberPer100g: numberOrUndefined(nutriments.fiber_100g),
fruitVegetableLegumePercent: numberOrUndefined(nutriments['fruits-vegetables-legumes-estimate-from-ingredients_100g']),
saltPer100g: numberOrUndefined(nutriments.salt_100g),
hasNonNutritiveSweeteners: Array.isArray(product.additives_tags)
? product.additives_tags.some((tag) => /^en:e(?:950|951|952|954|955|957|959|960|961|962|969)(?:$|-)/.test(tag))
: undefined,
nutrientLevels: normalizeNutrientLevels(product.nutrient_levels),
nutriScore: normalizeGrade(product.nutriscore_grade)
nutriScore
},
sustainability: {
ecoScore: normalizeGrade(product.ecoscore_grade),
carbonFootprintKgCo2ePerKg: numberOrUndefined(product.ecoscore_data?.agribalyse?.co2_total),
isBio: hasOrganicLabel(product.labels_tags || []),
ecoScore,
ecoScoreScore: numberOrUndefined(product.environmental_score_score ?? product.ecoscore_score),
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,
originCountry: firstOrigin(product.origins, product.origins_tags, product.countries_tags),
packaging: firstTextValue(product.packaging)
},
dataCompleteness: {
allergens: Array.isArray(product.allergens_tags),
additives: Array.isArray(product.additives_tags),
ecoScore: Boolean(normalizeGrade(product.ecoscore_grade)),
ecoScore: Boolean(ecoScore),
ingredients: Boolean(product.ingredients_text_de || product.ingredients_text || product.ingredients_text_en),
nutriScore: Boolean(normalizeGrade(product.nutriscore_grade)),
nutriScore: Boolean(nutriScore),
nutrition: Boolean(product.nutriments)
},
createdAt: now,
updatedAt: now
};
});
}
function markProductsSource(products, source) {
@@ -212,26 +244,27 @@ function firstCategory(categories, categoryTags = []) {
const category = firstTextValue(categories);
if (category) return category;
const tag = categoryTags.find(Boolean);
const tag = (Array.isArray(categoryTags) ? categoryTags : []).find(Boolean);
return tag ? cleanTag(tag) : undefined;
}
function firstOrigin(origins, originTags = [], countryTags = []) {
return firstTextValue(origins)
|| cleanTag(originTags.find(Boolean))
|| cleanTag(countryTags.find(Boolean));
|| cleanTag((Array.isArray(originTags) ? originTags : []).find(Boolean))
|| cleanTag((Array.isArray(countryTags) ? countryTags : []).find(Boolean));
}
function parseIngredients(ingredientsText) {
if (!ingredientsText) return [];
if (typeof ingredientsText !== 'string') return [];
return ingredientsText
.split(/[,;.]/)
.map((ingredient) => ingredient.trim())
.filter(Boolean)
.slice(0, 16);
.slice(0, 100);
}
function analysisStatus(analysisTags = [], diet) {
if (!Array.isArray(analysisTags)) return undefined;
if (analysisTags.includes(`en:${diet}`)) {
return true;
}
@@ -248,6 +281,8 @@ function analysisStatus(analysisTags = [], diet) {
}
function palmOilStatus(analysisTags = [], palmOilTags = []) {
if (!Array.isArray(analysisTags)) analysisTags = [];
if (!Array.isArray(palmOilTags)) palmOilTags = [];
if (analysisTags.includes('en:palm-oil') || palmOilTags.length > 0) {
return true;
}
@@ -299,7 +334,7 @@ function normalizeAllergens(allergenTags) {
}
function normalizeTags(tags) {
return tags
return (Array.isArray(tags) ? tags : [])
.map((tag) => String(tag || '').trim().toLowerCase())
.filter(Boolean);
}
@@ -331,6 +366,7 @@ function hasOrganicLabel(labelTags) {
}
function numberOrUndefined(value) {
if (value === null || value === undefined || value === '') return undefined;
const numberValue = Number(value);
return Number.isFinite(numberValue) ? numberValue : undefined;
}
+153 -109
View File
@@ -1,3 +1,5 @@
import { calculateNutriScore } from './nutriScoreService.js';
const nutrientLevelLabels = {
fat: 'Fett',
saturatedFat: 'gesättigte Fettsäuren',
@@ -124,13 +126,19 @@ export function calculateProductRating(product, 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 overallScore = hasBlockedAllergen
? 0
: weightedScore === null ? null
: Math.min(
capOverallScoreForCriticalAdditives(weightedCategoryScore(categoryScores, weights), criticalAdditiveCount),
capOverallScoreForCriticalAdditives(weightedScore, criticalAdditiveCount),
coverageCap,
allergenReviewRequired ? 77 : 100
);
const overallStatus = statusFromScore(overallScore);
const limitedByMissingData = !hasBlockedAllergen && weightedScore !== null
&& weightedScore > coverageCap && overallScore === coverageCap;
const overallStatus = overallScore === null ? 'unknown' : statusFromScore(overallScore);
const reasons = Object.entries(categoryScores).map(([category, value]) => ({
category,
@@ -142,35 +150,46 @@ export function calculateProductRating(product, preferences) {
productId: product.id,
overallStatus,
overallScore,
limitedByMissingData,
dataCoverage: Math.round(coverage * 100),
allergenReviewRequired,
reasons,
categoryScores
};
}
function ratingWeights() {
function ratingWeights(preferences) {
const priorityFactors = { low: 0.5, medium: 0.75, high: 1 };
return {
allergies: 0.1,
budget: 0.2,
ingredients: 0.15,
nutrition: 0.35,
sustainability: 0.2
nutrition: 0.35 * (priorityFactors[preferences.nutritionPriority] ?? 1),
sustainability: 0.2 * (priorityFactors[preferences.sustainabilityPriority] ?? 0.75)
};
}
function weightedCategoryScore(categoryScores, weights) {
const knownEntries = Object.entries(categoryScores).filter(([, value]) => value.hasKnownFacts !== false);
function weightedCategoryScore(categoryScores, weights, preferences) {
const applicableEntries = Object.entries(categoryScores).filter(([category]) => (
category !== 'allergies' || (preferences.avoidAllergens || []).length > 0
) && (
category !== 'budget' || Number.isFinite(preferences.maxBudgetPerShoppingTrip)
&& preferences.maxBudgetPerShoppingTrip > 0
));
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;
if (totalWeight === 0) {
return 50;
return { score: null, coverage };
}
return Math.round(
return { score: Math.round(
knownEntries.reduce((sum, [category, value]) => (
sum + value.score * weights[category]
), 0) / totalWeight
);
), coverage };
}
function capOverallScoreForCriticalAdditives(score, criticalAdditiveCount) {
@@ -205,10 +224,12 @@ function rateAllergies(product, preferences) {
}
if (avoidAllergens.length > 0 && allergenDataMissing) {
return withScore(50, 'Allergenangaben fehlen – Verpackung prüfen.', missingData, { needsReview: true });
return withScore(50, 'Allergenangaben fehlen – Verpackung prüfen.', missingData, { needsReview: true, hasKnownFacts: false });
}
return withScore(100, 'Keine hinterlegten Allergene gefunden.', missingData);
return withScore(100, avoidAllergens.length > 0
? 'Keine vermiedenen Allergene angegeben.'
: 'Keine Allergene im Profil hinterlegt.', missingData, { hasKnownFacts: avoidAllergens.length > 0 });
}
function rateIngredients(product, preferences) {
@@ -218,12 +239,10 @@ function rateIngredients(product, preferences) {
const harmfulAdditives = harmfulAdditiveMatches(additives, ingredients);
const completeness = product.dataCompleteness || {};
const hasIngredientText = ingredients.length > 0;
const palmOil = ingredientFlag(
analysis.palmOil,
ingredients.some((ingredient) => palmOilTerms().some((term) => ingredient.includes(term)))
);
const vegan = ingredientFlag(analysis.vegan, hasIngredientText ? !hasAnimalIngredient(ingredients, true) : undefined);
const vegetarian = ingredientFlag(analysis.vegetarian, hasIngredientText ? !hasAnimalIngredient(ingredients, false) : undefined);
const palmOil = ingredients.some((ingredient) => palmOilTerms().some((term) => ingredient.includes(term)))
? true : ingredientFlag(analysis.palmOil, undefined);
const vegan = ingredientFlag(analysis.vegan, hasAnimalIngredient(ingredients, true) ? false : undefined);
const vegetarian = ingredientFlag(analysis.vegetarian, hasAnimalIngredient(ingredients, false) ? false : undefined);
const components = [
scoreComponent(palmOil === true ? 22 : palmOil === false ? 92 : null, 2),
scoreComponent(additiveScore(additives, completeness.additives, harmfulAdditives), harmfulAdditives.length > 0 ? 3 : 1)
@@ -284,16 +303,22 @@ function rateIngredients(product, preferences) {
return withScore(score, 'Vegetarisch laut Zutatenanalyse.', missingData, ingredientOptions);
}
return withScore(score, 'Keine kritischen Zutatenhinweise gefunden.', missingData, ingredientOptions);
return withScore(score, hasKnownFacts
? 'Keine kritischen Zutatenhinweise gefunden.'
: 'Zutatenangaben reichen für eine Bewertung nicht aus.', missingData, ingredientOptions);
}
function rateNutrition(product, preferences) {
const nutrition = product.nutrition || {};
const suppliedNutrition = product.nutrition || {};
const calculated = suppliedNutrition.nutriScore ? null : calculateNutriScore(
product, isBeverage(product), isWaterLike(product)
);
const nutrition = { ...suppliedNutrition, nutriScore: suppliedNutrition.nutriScore || calculated?.grade };
const nutrientLevels = nutrition.nutrientLevels || {};
const highLevels = nutrientLevelEntries(nutrientLevels, 'high');
const moderateLevels = nutrientLevelEntries(nutrientLevels, 'moderate');
const missingData = missingMessages([
[!nutrition.nutriScore, 'Nutri-Score fehlt in Open Food Facts.'],
[!nutrition.nutriScore, 'Nutri-Score kann wegen fehlender Nährwerte nicht berechnet werden.'],
[Object.keys(nutrientLevels).length === 0 || !Object.values(nutrientLevels).some(Boolean), 'Nährwert-Level fehlen in Open Food Facts.'],
[preferences.preferredDiet === 'lowSugar' && typeof nutrition.sugarPer100g !== 'number', 'Zuckerwert pro 100 g fehlt.'],
[preferences.preferredDiet === 'highProtein' && !isBeverage(product) && typeof nutrition.proteinPer100g !== 'number', 'Proteinwert pro 100 g fehlt.']
@@ -301,11 +326,19 @@ function rateNutrition(product, preferences) {
const nutrientLevelStatus = statusFromNutrientLevels(highLevels, moderateLevels);
const nutrientLevelMessage = messageFromNutrientLevels(highLevels, moderateLevels);
const baseScore = nutritionScoreFromData(product, nutrition, nutrientLevels);
const details = nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore);
const options = { details };
const details = nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore, Boolean(calculated));
const options = { details, hasKnownFacts: Boolean(nutrition.nutriScore) };
if (!nutrition.nutriScore) {
return withScore(50, 'Nutri-Score und ausreichende Nährwerte fehlen.', missingData, options);
}
if (preferences.preferredDiet === 'lowSugar') {
const score = Math.min(baseScore, sugarScore(nutrition.sugarPer100g, nutrientLevels.sugars));
const goalScore = sugarScore(nutrition.sugarPer100g, nutrientLevels.sugars);
if (goalScore === null) {
return withScore(baseScore, `Nutri-Score ${nutrition.nutriScore}; Zuckerwert für dein Ziel fehlt.`, missingData, options);
}
const score = Math.min(baseScore, goalScore);
if (score < 48) {
return withScore(score, nutrientLevelMessage || 'Sehr hoher Zuckergehalt für dein Ziel.', missingData, options);
}
@@ -322,7 +355,11 @@ function rateNutrition(product, preferences) {
return withScore(baseScore, nutrientLevelMessage || 'Getränk: Protein wird für diese Kategorie nicht abgewertet.', missingData, options);
}
const score = Math.min(baseScore, proteinScore(nutrition.proteinPer100g));
const goalScore = proteinScore(nutrition.proteinPer100g);
if (goalScore === null) {
return withScore(baseScore, `Nutri-Score ${nutrition.nutriScore}; Proteinwert für dein Ziel fehlt.`, missingData, options);
}
const score = Math.min(baseScore, goalScore);
if (score < 78) {
return withScore(score, nutrientLevelMessage || 'Proteinanteil ist eher niedrig.', missingData, options);
}
@@ -331,34 +368,35 @@ function rateNutrition(product, preferences) {
}
if (nutrientLevelStatus !== 'good') {
return withScore(baseScore, nutrientLevelMessage, missingData, options);
return withScore(baseScore, `${calculated ? 'Berechneter ' : ''}Nutri-Score ${nutrition.nutriScore}: ${nutrientLevelMessage}`, missingData, options);
}
if (['A', 'B'].includes(nutrition.nutriScore)) {
return withScore(baseScore, `Nutri-Score ${nutrition.nutriScore} ist positiv.`, missingData, options);
return withScore(baseScore, `${calculated ? 'Berechneter ' : ''}Nutri-Score ${nutrition.nutriScore} ist positiv.`, missingData, options);
}
if (nutrition.nutriScore === 'C') {
return withScore(baseScore, 'Nutri-Score C: in Ordnung, aber nicht optimal.', missingData, options);
return withScore(baseScore, `${calculated ? 'Berechneter ' : ''}Nutri-Score C: in Ordnung, aber nicht optimal.`, missingData, options);
}
return withScore(baseScore, `Nutri-Score ${nutrition.nutriScore || 'unbekannt'} ist kritisch.`, missingData, options);
return withScore(baseScore, `${calculated ? 'Berechneter ' : ''}Nutri-Score ${nutrition.nutriScore} ist kritisch.`, missingData, options);
}
function rateSustainability(product, preferences) {
const sustainability = product.sustainability || {};
const carbonFootprint = carbonFootprintValue(sustainability);
const hasEcoScore = Boolean(ecoScoreValues[sustainability.ecoScore]);
const missingData = missingMessages([
[!sustainability.ecoScore, 'Eco-Score fehlt in Open Food Facts.'],
[typeof carbonFootprint !== 'number', 'CO2-Fussabdruck fehlt in Open Food Facts.'],
[!sustainability.originCountry, 'Herkunftsland fehlt in Open Food Facts.'],
[!sustainability.packaging, 'Verpackungsangabe fehlt in Open Food Facts.']
[!hasEcoScore && typeof carbonFootprint !== 'number', 'CO2-Fussabdruck ist nicht verfügbar.'],
[!hasEcoScore && !sustainability.originCountry, 'Herkunftsland fehlt in Open Food Facts.'],
[!hasEcoScore && !sustainability.packaging, 'Verpackungsangabe fehlt in Open Food Facts.']
]);
const components = sustainabilityScoreComponents(product, preferences);
const score = weightedKnownScore(components, 50);
const options = { hasKnownFacts: hasKnownComponents(components) };
if (bioPreferenceApplies(product, preferences) && !sustainability.isBio) {
if (bioPreferenceApplies(product, preferences) && sustainability.isBio === false) {
return withScore(score, 'Nicht Bio, obwohl Bio bevorzugt wird.', missingData, options);
}
@@ -370,7 +408,11 @@ function rateSustainability(product, preferences) {
return withScore(score, 'Eco-Score C: akzeptabel, aber verbesserbar.', missingData, options);
}
return withScore(score, `Eco-Score ${sustainability.ecoScore || 'unbekannt'} ist schwach.`, missingData, options);
return withScore(score, sustainability.ecoScore
? `Eco-Score ${sustainability.ecoScore} ist schwach.`
: sustainability.footprint?.status === 'estimated'
? 'Nachhaltigkeit mit AGRIBALYSE-Kategoriedurchschnitt geschätzt.'
: options.hasKnownFacts ? 'Nachhaltigkeit anhand verfügbarer Angaben geschätzt.' : 'Nachhaltigkeitsangaben fehlen.', missingData, options);
}
function rateBudget(product, preferences) {
@@ -379,8 +421,9 @@ function rateBudget(product, preferences) {
[typeof preferences.maxBudgetPerShoppingTrip !== 'number', 'Budgetlimit fehlt im Profil.']
]);
if (typeof product.price !== 'number' || typeof preferences.maxBudgetPerShoppingTrip !== 'number') {
return withScore(55, 'Preis oder Budget fehlt für eine genaue Prüfung.', missingData);
if (!Number.isFinite(product.price) || !Number.isFinite(preferences.maxBudgetPerShoppingTrip)
|| preferences.maxBudgetPerShoppingTrip <= 0 || product.price < 0) {
return withScore(55, 'Preis oder Budget fehlt für eine genaue Prüfung.', missingData, { hasKnownFacts: false });
}
const share = product.price / preferences.maxBudgetPerShoppingTrip;
@@ -399,38 +442,27 @@ function rateBudget(product, preferences) {
}
function nutritionScoreFromData(product, nutrition, nutrientLevels) {
if (isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
if (nutrition.nutriScore === 'A' && isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
return 98;
}
if (isBeverage(product) && !nutrition.nutriScore && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
return 86;
}
const nutriScore = nutriScoreValues[nutrition.nutriScore] ?? 50;
const nutrientPenalty = Object.values(nutrientLevels || {}).reduce((penalty, level) => {
if (level === 'high') return penalty + 18;
if (level === 'moderate') return penalty + 8;
return penalty;
}, 0);
return clampScore(nutriScore - nutrientPenalty);
return nutriScoreValues[nutrition.nutriScore] ?? 50;
}
function nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore) {
function nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore, calculated) {
const details = [];
if (nutrition.nutriScore) {
const nutriScoreValue = nutriScoreValues[nutrition.nutriScore] ?? 50;
details.push({
type: nutriScoreValue >= 78 ? 'positive' : 'penalty',
title: `Nutri-Score ${nutrition.nutriScore}`,
title: `${calculated ? 'Berechneter ' : ''}Nutri-Score ${nutrition.nutriScore}`,
body: nutriScoreValue >= 78
? 'Der Nutri-Score ist gut und erhöht die Ernährungswertung.'
: nutriScoreValue >= 48
? 'Der Nutri-Score ist mittelmässig und begrenzt die Ernährungswertung.'
: 'Der Nutri-Score ist schwach und reduziert die Ernährungswertung deutlich.',
meta: `Basiswert: ${nutriScoreValue} von 100`
meta: `Basiswert: ${nutriScoreValue} von 100${calculated ? ' · aus Nährwerten berechnet' : ''}`
});
}
@@ -444,27 +476,22 @@ function nutritionScoreDetails(product, preferences, nutrition, nutrientLevels,
details.push(proteinGoalDetail(nutrition.proteinPer100g));
}
if (isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
if (nutrition.nutriScore === 'A' && isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
details.push({
type: 'positive',
title: 'Wasserähnliches Produkt',
body: 'Wasserähnliche Produkte ohne kritische Nährwerte bekommen eine sehr gute Ernährungswertung.',
meta: 'Keine hohe Zucker-, Salz-, Fett- oder gesättigte-Fettsäuren-Markierung erkannt.'
});
} else if (isBeverage(product) && !nutrition.nutriScore && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
details.push({
type: 'positive',
title: 'Getränk ohne kritische Nährwerte',
body: 'Bei Getränken ohne Nutri-Score wird nicht automatisch abgewertet, wenn keine kritischen Nährwerte vorliegen.',
meta: 'Ersatzwert: 86 von 100'
});
}
details.push({
type: baseScore >= 78 ? 'positive' : 'penalty',
title: 'Ernährungsbasis',
body: 'Die Basiswertung kombiniert Nutri-Score und Nährwert-Level. Hohe Level werden stärker abgezogen als mittlere Level.',
meta: `Aktueller Basiswert: ${Math.round(baseScore)} von 100`
type: nutrition.nutriScore ? baseScore >= 78 ? 'positive' : 'penalty' : 'info',
title: nutrition.nutriScore ? 'Ernährungsbasis' : 'Ernährungsbasis nicht verfügbar',
body: nutrition.nutriScore
? 'Die Basiswertung folgt dem Nutri-Score. Seine Nährwerte werden nicht ein zweites Mal abgezogen.'
: 'Für eine belastbare Ernährungswertung fehlen Nährwerte.',
meta: nutrition.nutriScore ? `Aktueller Basiswert: ${Math.round(baseScore)} von 100` : undefined
});
return details;
@@ -477,36 +504,36 @@ function nutritionNutrientDetails(nutrition, nutrientLevels) {
label: 'Zucker',
value: nutrition.sugarPer100g,
unit: 'g pro 100 g',
highText: 'Hoher Zuckerwert reduziert die Bewertung deutlich, besonders bei Low-Sugar-Ziel.',
moderateText: 'Mittlerer Zuckerwert reduziert die Bewertung leicht bis moderat.',
lowText: 'Niedriger Zuckerwert verbessert die Bewertung.'
highText: 'Hoher Zuckerwert ist im Nutri-Score berücksichtigt und kann zusätzlich dein Low-Sugar-Ziel verfehlen.',
moderateText: 'Mittlerer Zuckerwert ist im Nutri-Score berücksichtigt.',
lowText: 'Zucker wird im Nutri-Score berücksichtigt.'
},
{
key: 'fat',
label: 'Fett',
value: nutrition.fatPer100g,
unit: 'g pro 100 g',
highText: 'Hoher Fettwert reduziert die Bewertung.',
moderateText: 'Mittlerer Fettwert reduziert die Bewertung leicht.',
lowText: 'Niedriger Fettwert ist positiv.'
highText: 'Der Gesamtfettwert ist ein Hinweis, führt aber nicht zu einem zusätzlichen Abzug.',
moderateText: 'Der Gesamtfettwert führt nicht zu einem zusätzlichen Abzug.',
lowText: 'Der Gesamtfettwert führt nicht zu einem zusätzlichen Abzug.'
},
{
key: 'saturatedFat',
label: 'Gesättigte Fettsäuren',
value: nutrition.saturatedFatPer100g,
unit: 'g pro 100 g',
highText: 'Hohe gesättigte Fettsäuren reduzieren die Bewertung deutlich.',
moderateText: 'Mittlere gesättigte Fettsäuren reduzieren die Bewertung.',
lowText: 'Niedrige gesättigte Fettsäuren sind positiv.'
highText: 'Gesättigte Fettsäuren sind im Nutri-Score berücksichtigt.',
moderateText: 'Gesättigte Fettsäuren sind im Nutri-Score berücksichtigt.',
lowText: 'Gesättigte Fettsäuren sind im Nutri-Score berücksichtigt.'
},
{
key: 'salt',
label: 'Salz',
value: nutrition.saltPer100g,
unit: 'g pro 100 g',
highText: 'Hoher Salzgehalt reduziert die Bewertung deutlich.',
moderateText: 'Mittlerer Salzgehalt reduziert die Bewertung.',
lowText: 'Niedriger Salzgehalt ist positiv.'
highText: 'Salz ist im Nutri-Score berücksichtigt.',
moderateText: 'Salz ist im Nutri-Score berücksichtigt.',
lowText: 'Salz ist im Nutri-Score berücksichtigt.'
}
];
@@ -516,7 +543,7 @@ function nutritionNutrientDetails(nutrition, nutrientLevels) {
}
function nutrientDetail(entry, level) {
const type = level === 'high' || level === 'moderate' ? 'penalty' : 'positive';
const type = !level ? 'info' : level === 'high' || level === 'moderate' ? 'penalty' : 'positive';
const body = level === 'high'
? entry.highText
: level === 'moderate'
@@ -544,9 +571,10 @@ function sugarGoalDetail(sugarPer100g, sugarLevel) {
const score = sugarScore(sugarPer100g, sugarLevel);
return {
type: score >= 78 ? 'positive' : 'penalty',
type: score === null ? 'info' : score >= 78 ? 'positive' : 'penalty',
title: 'Low-Sugar-Ziel',
body: score >= 78
body: score === null ? 'Der Zuckerwert fehlt und wird für dieses Ziel nicht bewertet.'
: score >= 78
? 'Der Zuckerwert passt zu deinem Low-Sugar-Ziel.'
: score >= 48
? 'Der Zuckerwert liegt über dem idealen Bereich für dein Low-Sugar-Ziel.'
@@ -561,9 +589,10 @@ function proteinGoalDetail(proteinPer100g) {
const score = proteinScore(proteinPer100g);
return {
type: score >= 78 ? 'positive' : 'penalty',
type: score === null ? 'info' : score >= 78 ? 'positive' : 'penalty',
title: 'Protein-Ziel',
body: score >= 78
body: score === null ? 'Der Proteinwert fehlt und wird für dieses Ziel nicht bewertet.'
: score >= 78
? 'Der Proteinanteil passt gut zu deinem High-Protein-Ziel.'
: 'Der Proteinanteil ist für dein High-Protein-Ziel eher niedrig.',
meta: typeof proteinPer100g === 'number'
@@ -596,7 +625,7 @@ function sugarScore(sugarPer100g, sugarLevel) {
}
if (typeof sugarPer100g !== 'number') {
return 55;
return null;
}
if (sugarPer100g <= 5) return 100;
@@ -607,7 +636,7 @@ function sugarScore(sugarPer100g, sugarLevel) {
function proteinScore(proteinPer100g) {
if (typeof proteinPer100g !== 'number') {
return 55;
return null;
}
if (proteinPer100g >= 20) return 100;
@@ -617,10 +646,6 @@ function proteinScore(proteinPer100g) {
}
function additiveScore(additives, additivesKnown, harmfulAdditives = []) {
if (!additivesKnown) {
return null;
}
if (harmfulAdditives.length >= 3) {
return 0;
}
@@ -633,6 +658,10 @@ function additiveScore(additives, additivesKnown, harmfulAdditives = []) {
return 18;
}
if (!additivesKnown) {
return null;
}
if (additives.length === 0) {
return 95;
}
@@ -708,22 +737,24 @@ function ingredientScoreDetails({ additives, harmfulAdditives, palmOil, preferen
if (preferences.preferredDiet === 'vegan') {
details.push({
type: vegan === true ? 'positive' : 'penalty',
title: vegan === true ? 'Vegan kompatibel' : 'Nicht vegan oder unklar',
type: vegan === undefined ? 'info' : vegan === true ? 'positive' : 'penalty',
title: vegan === true ? 'Vegan kompatibel' : vegan === false ? 'Nicht vegan' : 'Vegan unklar',
body: vegan === true
? 'Die Zutatenanalyse passt zum veganen Ziel.'
: 'Tierische Bestandteile oder eine fehlende Vegan-Bestätigung belasten die Zutatenwertung für dein Profil.',
: vegan === false ? 'Tierische Bestandteile passen nicht zu deinem veganen Ziel.'
: 'Eine Vegan-Bestätigung fehlt. Dieser Punkt wird nicht bewertet.',
meta: 'Relevant wegen deinem Profilziel: Vegan.'
});
}
if (preferences.preferredDiet === 'vegetarian') {
details.push({
type: vegetarian === true ? 'positive' : 'penalty',
title: vegetarian === true ? 'Vegetarisch kompatibel' : 'Nicht vegetarisch oder unklar',
type: vegetarian === undefined ? 'info' : vegetarian === true ? 'positive' : 'penalty',
title: vegetarian === true ? 'Vegetarisch kompatibel' : vegetarian === false ? 'Nicht vegetarisch' : 'Vegetarisch unklar',
body: vegetarian === true
? 'Die Zutatenanalyse passt zum vegetarischen Ziel.'
: 'Fleisch-/Fischbestandteile oder eine fehlende Bestätigung belasten die Zutatenwertung für dein Profil.',
: vegetarian === false ? 'Fleisch- oder Fischbestandteile passen nicht zu deinem vegetarischen Ziel.'
: 'Eine Vegetarisch-Bestätigung fehlt. Dieser Punkt wird nicht bewertet.',
meta: 'Relevant wegen deinem Profilziel: Vegetarisch.'
});
}
@@ -737,15 +768,17 @@ function sustainabilityScore(product, preferences) {
function sustainabilityScoreComponents(product, preferences) {
const sustainability = product.sustainability || {};
const components = [
scoreComponent(ecoScoreValues[sustainability.ecoScore], 3),
scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2),
scoreComponent(originScore(sustainability.originCountry), 1),
scoreComponent(packagingScore(sustainability.packaging), 1)
];
const ecoScore = ecoScoreValues[sustainability.ecoScore];
const components = ecoScore
? [scoreComponent(ecoScore, 3)]
: [
scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2),
scoreComponent(originScore(sustainability.originCountry), 1),
scoreComponent(packagingScore(sustainability.packaging), 1)
];
if (bioPreferenceApplies(product, preferences)) {
components.push(scoreComponent(sustainability.isBio ? 92 : 32, 1));
components.push(scoreComponent(sustainability.isBio === true ? 92 : sustainability.isBio === false ? 32 : null, 1));
}
return components;
@@ -814,9 +847,10 @@ function budgetPeriodLabel(period) {
function withScore(score, message, missingData = [], options = {}) {
const roundedScore = Math.round(clampScore(score));
const hasKnownFacts = options.hasKnownFacts !== false;
return {
status: statusFromScore(roundedScore),
score: roundedScore,
status: hasKnownFacts ? statusFromScore(roundedScore) : 'unknown',
score: hasKnownFacts ? roundedScore : null,
message,
missingData,
...options
@@ -869,7 +903,7 @@ function hasKnownComponents(components) {
}
function carbonFootprintValue(sustainability) {
if (typeof sustainability.carbonFootprintKgCo2ePerKg === 'number') {
if (typeof sustainability.carbonFootprintKgCo2ePerKg === 'number' && Number.isFinite(sustainability.carbonFootprintKgCo2ePerKg) && sustainability.carbonFootprintKgCo2ePerKg >= 0) {
return sustainability.carbonFootprintKgCo2ePerKg;
}
@@ -917,7 +951,7 @@ function originScore(originCountry) {
return 78;
}
if (['european union', 'eu', 'europa', 'europe'].some((term) => origin.includes(term))) {
if (['european union', 'europa', 'europe'].some((term) => origin.includes(term)) || /\beu\b/.test(origin)) {
return 68;
}
@@ -1092,23 +1126,33 @@ function hasAnimalIngredient(ingredients, includeDairyAndEggs) {
? [...alwaysAnimalTerms, ...veganOnlyTerms]
: alwaysAnimalTerms;
return ingredients.some((ingredient) =>
blockedTerms.some((term) => ingredient.includes(term))
);
return ingredients.some((ingredient) => {
const words = ingredient.match(/[\p{L}]+/gu) || [];
return words.some((word) => blockedTerms.some((term) =>
word === term || (term.length >= 4 && word.startsWith(term))
));
});
}
function isWaterLike(product) {
const terms = productTerms(product);
return terms.some((term) =>
const nutrition = product.nutrition || {};
const isWater = terms.some((term) =>
['water', 'waters', 'wasser', 'mineral water', 'sparkling water', 'still water', 'eau'].includes(term)
|| term.includes('mineralwasser')
);
return isWater
&& !terms.some((term) => /flavou?r|aromatis|sweeten|gesüss|gezucker|soft drink/.test(term))
&& (typeof nutrition.sugarPer100g !== 'number' || nutrition.sugarPer100g === 0)
&& (typeof nutrition.caloriesPer100g !== 'number' || nutrition.caloriesPer100g === 0)
&& (typeof nutrition.energyKjPer100g !== 'number' || nutrition.energyKjPer100g === 0)
&& nutrition.hasNonNutritiveSweeteners !== true;
}
function isBeverage(product) {
const terms = productTerms(product);
return terms.some((term) =>
['beverage', 'beverages', 'drink', 'drinks', 'getränk', 'getränke', 'water', 'waters', 'wasser', 'juice', 'soda', 'cola', 'tea', 'coffee'].includes(term)
['beverage', 'beverages', 'drink', 'drinks', 'getränk', 'getränke', 'water', 'waters', 'wasser', 'juice', 'soda', 'cola', 'tea', 'coffee', 'milk', 'milks', 'milch', 'milchgetränk', 'milchgetränke'].includes(term)
|| term.includes('beverage')
|| term.includes('drink')
|| term.includes('getränk')