add better eco ratings
Android Release Build / build-android (push) Successful in 13m35s

This commit is contained in:
Frederik Spirgi
2026-10-26 11:42:28 +01:00
parent f12a9d47b6
commit 1d32aeaf29
9 changed files with 255 additions and 35 deletions
+4 -2
View File
@@ -82,11 +82,13 @@ Beispiel-Barcodes für Tests über Open Food Facts:
737628064502 - Open-Food-Facts-Beispielprodukt 737628064502 - Open-Food-Facts-Beispielprodukt
``` ```
Die App nutzt für Barcodes `https://world.openfoodfacts.org/api/v2/product/{barcode}.json`. Wenn ein Produkt bereits lokal gespeichert ist oder der Offline-Modus aktiv ist, wird zuerst der lokale Cache verwendet. Die App nutzt für Barcodes `https://world.openfoodfacts.org/api/v2/product/{barcode}.json`. Online werden gespeicherte Produktdaten nach 24 Stunden erneut von Open Food Facts geladen. Schlägt die Aktualisierung fehl oder ist der Offline-Modus aktiv, bleibt der lokale Cache nutzbar; veraltete Daten werden gekennzeichnet und die Empfehlung höchstens als „Prüfen“ angezeigt. Der Zeitpunkt des letzten erfolgreichen Abrufs wird angezeigt. Manuell erfasste Preise bleiben bei einer Aktualisierung erhalten.
Fehlt der Nutri-Score in Open Food Facts, berechnet die App die Note A–E aus den verfügbaren Nährwerten pro 100 g bzw. 100 ml nach dem [aktualisierten Nutri-Score-Algorithmus](https://www.santepubliquefrance.fr/sites/default/files/rdd/document/march2025CoU_EN.pdf). Die Berechnung berücksichtigt die Sonderregeln für Getränke sowie Fette, Nüsse und Samen. Wenn fehlende Angaben die Note verändern könnten, zeigt die App keine berechnete Note an und lässt die Ernährungswertung aus der Gesamtbewertung heraus. Eine berechnete Note wird in den Bewertungsdetails als solche gekennzeichnet. Fehlt der Nutri-Score in Open Food Facts, berechnet die App die Note A–E aus den verfügbaren Nährwerten pro 100 g bzw. 100 ml nach dem [aktualisierten Nutri-Score-Algorithmus](https://www.santepubliquefrance.fr/sites/default/files/rdd/document/march2025CoU_EN.pdf). Die Berechnung berücksichtigt die Sonderregeln für Getränke sowie Fette, Nüsse und Samen. Wenn fehlende Angaben die Note verändern könnten, zeigt die App keine berechnete Note an und lässt die Ernährungswertung aus der Gesamtbewertung heraus. Eine berechnete Note wird in den Bewertungsdetails als solche gekennzeichnet.
Die Gesamtwertung verwendet nur Kriterien mit belastbaren Angaben und berücksichtigt die im Profil gewählten Prioritäten für Ernährung und Nachhaltigkeit. Fehlende Preise, unklare Zutaten- oder Allergenangaben und unbekannte Nachhaltigkeitsdaten erzeugen keine Ersatzpunkte. Bei wenigen belegten Kriterien wird die Empfehlung auf „Prüfen“ begrenzt; sind alle unbekannt, erscheint „Daten fehlen“ statt einer Zahl. Bekannte Allergene bleiben ein Ausschlussgrund; bei fehlenden Allergenangaben fordert die App weiterhin zur Prüfung der Verpackung auf. Nährwerte, die bereits in den Nutri-Score eingehen, werden nicht nochmals abgezogen. Die Gesamtwertung verwendet nur Kriterien mit belastbaren Angaben und berücksichtigt die im Profil gewählten Prioritäten für Ernährung und Nachhaltigkeit. Fehlende Preise, unklare Zutaten- oder Allergenangaben und unbekannte Nachhaltigkeitsdaten erzeugen keine Ersatzpunkte. Bei wenigen belegten Kriterien wird die Empfehlung auf „Prüfen“ begrenzt; sind alle unbekannt, erscheint „Daten fehlen“ statt einer Zahl. Angegebene vermiedene Allergene bleiben ein Ausschlussgrund. Mögliche Spuren und das Fehlen eines Allergens in der Open-Food-Facts-Liste gelten nicht als bestätigte Allergenfreiheit: Die App fordert zur Prüfung der Verpackung auf und gibt dafür keine Allergiepunkte. Ebenso geben leere Zusatzstoff-Tags ohne Zutatenliste keine positiven Punkte. Nährwerte, die bereits in den Nutri-Score eingehen, werden nicht nochmals abgezogen.
Das Produktdetail zeigt die gewichtete Datenabdeckung, die wichtigsten bewerteten Faktoren und mögliche Begrenzungen der Gesamtwertung. Offizielle Noten und ein von der App berechneter Nutri-Score werden getrennt gekennzeichnet. Ein fehlendes Herkunftsland wird nicht aus den Ländern ersetzt, in denen ein Produkt verkauft wird. Alternativen müssen eine deutlich bessere Gesamtwertung, mindestens eine belegte Verbesserung in einem Kriterium und mindestens dieselbe Datenabdeckung erreichen; die Punktschwellen sind App-Heuristiken und keine wissenschaftlich kalibrierten Unterschiede.
## Umweltinformationen ## Umweltinformationen
+2 -1
View File
@@ -25,7 +25,8 @@ export default function ProductCard({ product, rating, onPress }) {
{rating ? <ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} /> : null} {rating ? <ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} /> : null}
<Text style={styles.openLabel}>Details ansehen ›</Text> <Text style={styles.openLabel}>Details ansehen ›</Text>
</View> </View>
{rating?.allergenReviewRequired ? <Text style={styles.allergenWarning}>Allergenangaben fehlen – Verpackung prüfen.</Text> : null} {rating?.allergenReviewRequired ? <Text style={styles.allergenWarning}>{rating.allergenReviewMessage}</Text> : null}
{rating?.staleDataReviewRequired ? <Text style={styles.allergenWarning}>Gespeicherte Produktdaten sind veraltet.</Text> : null}
</Pressable> </Pressable>
); );
} }
+48 -5
View File
@@ -69,24 +69,42 @@ export default function ProductDetailScreen({
<Text style={styles.meta}> <Text style={styles.meta}>
{product.category || 'Produkt'} · {formatPrice(pricedProduct.price, currency)} {product.category || 'Produkt'} · {formatPrice(pricedProduct.price, currency)}
</Text> </Text>
<Text style={styles.source}>{sourceLabel(product.dataSource)}</Text> <Text style={styles.source}>{sourceLabel(product.dataSource)}{product.cacheStale ? ' · Veraltete Daten' : ''}</Text>
{['cache', 'open-food-facts'].includes(product.dataSource) ? <Text style={styles.meta}>Produktdaten geprüft: {formatCheckedDate(product.fetchedAt)}</Text> : null}
</View> </View>
<ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} /> <ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} />
</View> </View>
<View style={[styles.recommendation, styles[`${rating.overallStatus}Recommendation`]]}> <View style={[styles.recommendation, styles[`${rating.overallStatus}Recommendation`]]}>
<Text style={[styles.recommendationTitle, styles[`${rating.overallStatus}Text`]]}>{recommendation}</Text> <Text style={[styles.recommendationTitle, styles[`${rating.overallStatus}Text`]]}>{recommendation}</Text>
<Text style={styles.recommendationCopy}> <Text style={styles.recommendationCopy}>
{rating.allergenReviewRequired {rating.hasBlockedAllergen
? 'Allergenangaben fehlen oder sind nicht bestätigt. Prüfe vor dem Kauf die Verpackung.' ? rating.categoryScores.allergies.message
: rating.allergenReviewRequired
? rating.allergenReviewMessage
: rating.staleDataReviewRequired
? 'Gespeicherte Produktdaten sind veraltet. Prüfe vor dem Kauf die Verpackung.'
: rating.overallStatus === 'unknown' : rating.overallStatus === 'unknown'
? 'Für eine Empfehlung fehlen belastbare Produktangaben.' ? 'Für eine Empfehlung fehlen belastbare Produktangaben.'
: rating.limitedByMissingData : rating.limitedByMissingData
? 'Nur ein Teil der Kriterien ist belegt. Die Empfehlung ist deshalb auf „Prüfen“ begrenzt.' ? 'Nur ein Teil der Kriterien ist belegt. Die Empfehlung ist deshalb auf „Prüfen“ begrenzt.'
: 'Tippe unten auf ein Kriterium, um die Bewertung nachzuvollziehen.'} : 'Tippe unten auf ein Kriterium, um die Bewertung nachzuvollziehen.'}
</Text> </Text>
<Text style={styles.recommendationCopy}>Bewertbare Daten: {rating.dataCoverage}% der für dein Profil anwendbaren Kriterien (gewichtet).</Text>
</View> </View>
</View> </View>
{rating.mainFactors.length > 0 || rating.scoreLimitReasons.length > 0 ? (
<View style={styles.dataPanel}>
<Text style={styles.factorTitle}>Wichtigste Einflüsse auf die App-Bewertung</Text>
{rating.scoreLimitReasons.map((reason) => <Text key={reason} style={styles.dataText}>{reason}</Text>)}
{rating.mainFactors.map((factor) => (
<Text key={factor.category} style={styles.dataText}>
{factor.label}: {factor.score}/100 · {factor.message}
</Text>
))}
</View>
) : null}
{!hasProductPrice ? ( {!hasProductPrice ? (
<View style={styles.pricePanel}> <View style={styles.pricePanel}>
<Text style={styles.priceTitle}>Ladenpreis ergänzen</Text> <Text style={styles.priceTitle}>Ladenpreis ergänzen</Text>
@@ -168,14 +186,22 @@ export default function ProductDetailScreen({
</> </>
) : <Text style={styles.dataText}>CO₂-Fussabdruck: Nicht verfügbar.</Text>} ) : <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> <Text style={styles.dataText}>Green-Score (Open Food Facts): {product.sustainability?.ecoScore || 'Nicht verfügbar'}</Text>
<Text style={styles.dataText}>Zutatenherkunft: {ingredientOriginLabel(product)}</Text>
{(product.sustainability?.sellingCountries || []).length > 0 ? (
<Text style={styles.dataText}>Verkaufsländer: {product.sustainability.sellingCountries.map(formatCountryTag).join(', ')}</Text>
) : null}
</View> </View>
<SectionTitle>Produktdaten</SectionTitle> <SectionTitle>Produktdaten</SectionTitle>
<View style={styles.dataPanel}> <View style={styles.dataPanel}>
<Text style={styles.dataText}>Barcode: {product.barcode}</Text> <Text style={styles.dataText}>Barcode: {product.barcode}</Text>
<Text style={styles.dataText}>Zutaten: {(product.ingredients || []).join(', ') || 'Keine Angaben'}</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}>Angegebene Allergene: {(product.allergens || []).join(', ') || 'Keine Angaben'}</Text>
<Text style={styles.dataText}>Nutri-Score: {product.nutrition?.nutriScore || 'Keine Angabe'}</Text> <Text style={styles.dataText}>Mögliche Allergenspuren: {(product.allergenTraces || []).join(', ') || 'Keine Angaben'}</Text>
<Text style={styles.dataText}>
Nutri-Score: {rating.categoryScores.nutrition.nutriScore || 'Keine Angabe'}
{rating.categoryScores.nutrition.nutriScoreSource === 'calculated' ? ' (von der App berechnet)' : rating.categoryScores.nutrition.nutriScore ? ' (Open Food Facts)' : ''}
</Text>
</View> </View>
</ScreenContainer> </ScreenContainer>
@@ -203,6 +229,22 @@ function sourceLabel(source) {
return labels[source] || 'Quelle: unbekannt'; return labels[source] || 'Quelle: unbekannt';
} }
function formatCheckedDate(value) {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? 'unbekannt' : date.toLocaleDateString('de-CH');
}
function ingredientOriginLabel(product) {
const sustainability = product.sustainability || {};
if (['cache', 'open-food-facts'].includes(product.dataSource)
&& sustainability.originSource !== 'ingredient-origin') return 'Nicht verfügbar';
return sustainability.originCountry || 'Nicht verfügbar';
}
function formatCountryTag(tag) {
return tag.replace(/^[a-z]{2}:/, '').replace(/-/g, ' ');
}
function formatImpact(value, maximumFractionDigits = 2) { function formatImpact(value, maximumFractionDigits = 2) {
return new Intl.NumberFormat('de-CH', { maximumFractionDigits, minimumFractionDigits: value < 0.01 ? 3 : 0 }).format(value); return new Intl.NumberFormat('de-CH', { maximumFractionDigits, minimumFractionDigits: value < 0.01 ? 3 : 0 }).format(value);
} }
@@ -222,6 +264,7 @@ function matchLabel(method) {
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
factorTitle: { color: colors.text, fontSize: 16, fontWeight: '800' },
productPanel: { productPanel: {
backgroundColor: colors.surface, backgroundColor: colors.surface,
borderColor: colors.border, borderColor: colors.border,
+4 -4
View File
@@ -16,8 +16,8 @@ const labels = {
const defaultDetails = { const defaultDetails = {
allergies: { allergies: {
positive: 'Keine blockierten Allergene und vollständige Allergenangaben verbessern diese Bewertung.', positive: 'Eine ausdrücklich bestätigte Abwesenheit deiner vermiedenen Allergene verbessert diese Bewertung.',
penalty: 'Treffer mit deinen vermiedenen Allergenen setzen diese Kategorie hart nach unten. Fehlende Allergenangaben werden als Unsicherheit markiert.' penalty: 'Ein angegebenes vermiedenes Allergen blockiert die Empfehlung. Mögliche Spuren und nicht bestätigte Abwesenheit erfordern eine Prüfung der Verpackung.'
}, },
budget: { budget: {
positive: 'Ein niedriger Anteil am Budget pro Zeitraum verbessert diese Bewertung.', positive: 'Ein niedriger Anteil am Budget pro Zeitraum verbessert diese Bewertung.',
@@ -28,8 +28,8 @@ const defaultDetails = {
penalty: 'Kritische Zusatzstoffe, Palmöl, viele Zusatzstoffe oder ein Konflikt mit deinem Ernährungsziel reduzieren diese Bewertung.' penalty: 'Kritische Zusatzstoffe, Palmöl, viele Zusatzstoffe oder ein Konflikt mit deinem Ernährungsziel reduzieren diese Bewertung.'
}, },
nutrition: { nutrition: {
positive: 'Guter Nutri-Score, niedrige kritische Nährwert-Level und passende Werte für dein Ernährungsziel verbessern diese Bewertung.', positive: 'Ein guter Nutri-Score und passende Werte für dein gewähltes Ernährungsziel verbessern diese Bewertung.',
penalty: 'Hohe Werte bei Zucker, Salz, Fett oder gesättigten Fettsäuren sowie Konflikte mit Low-Sugar- oder High-Protein-Zielen reduzieren 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: { sustainability: {
positive: 'Guter Eco-Score, niedriger CO2-Fussabdruck, regionale Herkunft, bessere Verpackung und Bio bei Bio-Präferenz verbessern diese Bewertung.', positive: 'Guter Eco-Score, niedriger CO2-Fussabdruck, regionale Herkunft, bessere Verpackung und Bio bei Bio-Präferenz verbessern diese Bewertung.',
+5 -2
View File
@@ -1,7 +1,8 @@
import { searchProducts } from './productApi.js'; import { searchProducts } from './productApi.js';
import { calculateProductRating } from './ratingService.js'; import { calculateProductRating } from './ratingService.js';
const MIN_SCORE_IMPROVEMENT = 5; const MIN_SCORE_IMPROVEMENT = 10;
const MIN_CATEGORY_IMPROVEMENT = 10;
const INTERNAL_ALTERNATIVE_LIMIT = 8; const INTERNAL_ALTERNATIVE_LIMIT = 8;
const improvementLabels = { const improvementLabels = {
@@ -53,7 +54,9 @@ export async function findAlternatives(product, preferences, productCache = {})
.filter((item) => !item.rating.allergenReviewRequired) .filter((item) => !item.rating.allergenReviewRequired)
.filter((item) => productRating.overallScore !== null .filter((item) => productRating.overallScore !== null
&& item.rating.overallScore !== null && item.rating.overallScore !== null
&& item.rating.overallScore >= productRating.overallScore + MIN_SCORE_IMPROVEMENT) && item.rating.overallScore >= productRating.overallScore + MIN_SCORE_IMPROVEMENT
&& item.rating.dataCoverage >= productRating.dataCoverage
&& (strongestCategoryImprovement(item.rating, productRating)?.improvement || 0) >= MIN_CATEGORY_IMPROVEMENT)
.map((item) => ({ .map((item) => ({
...item, ...item,
reason: buildReason(item.rating, productRating, categoryTerms) reason: buildReason(item.rating, productRating, categoryTerms)
+6 -4
View File
@@ -49,9 +49,10 @@ const productFields = [
export async function lookupProductByBarcode(barcode, productCache = {}, offlineModeEnabled = false) { export async function lookupProductByBarcode(barcode, productCache = {}, offlineModeEnabled = false) {
const normalizedBarcode = normalizeBarcode(barcode); const normalizedBarcode = normalizeBarcode(barcode);
const cachedProduct = productCache[normalizedBarcode] || productCache[barcode]; const cachedProduct = productCache[normalizedBarcode] || productCache[barcode];
const cacheIsFresh = cachedProduct && isFreshCacheEntry(cachedProduct);
if (cachedProduct && (offlineModeEnabled || isFreshCacheEntry(cachedProduct))) { if (cachedProduct && (offlineModeEnabled || cacheIsFresh)) {
return cachedResult(cachedProduct); return cachedResult(cachedProduct, !cacheIsFresh);
} }
if (offlineModeEnabled) { if (offlineModeEnabled) {
@@ -163,6 +164,7 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
const agribalyseCode = product.environmental_score_data?.agribalyse?.code const agribalyseCode = product.environmental_score_data?.agribalyse?.code
|| product.ecoscore_data?.agribalyse?.code || product.agribalyse?.code; || product.ecoscore_data?.agribalyse?.code || product.agribalyse?.code;
const footprint = productSpecificFootprint(nutriments, product.quantity, product.last_modified_datetime, product.categories_tags); const footprint = productSpecificFootprint(nutriments, product.quantity, product.last_modified_datetime, product.categories_tags);
const originCountry = firstOrigin(product.origins, product.origins_tags);
const now = new Date().toISOString(); const now = new Date().toISOString();
return enrichEnvironmentalProduct({ return enrichEnvironmentalProduct({
@@ -217,8 +219,8 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
footprint, footprint,
carbonFootprintKgCo2ePerKg: footprint.status === 'product-specific' ? footprint.valueKgCo2ePerKg : undefined, 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) : undefined,
originCountry: firstOrigin(product.origins, product.origins_tags), originCountry,
originSource: firstOrigin(product.origins, product.origins_tags) ? 'ingredient-origin' : undefined, originSource: originCountry ? 'ingredient-origin' : undefined,
sellingCountries: normalizeTags(product.countries_tags), sellingCountries: normalizeTags(product.countries_tags),
packaging: firstTextValue(product.packaging) packaging: firstTextValue(product.packaging)
}, },
+78 -16
View File
@@ -23,6 +23,14 @@ const ecoScoreValues = {
E: 15 E: 15
}; };
const categoryLabels = {
allergies: 'Allergien',
budget: 'Budget',
ingredients: 'Zutaten',
nutrition: 'Ernährung',
sustainability: 'Nachhaltigkeit'
};
const additiveRiskGroups = [ const additiveRiskGroups = [
{ {
id: 'nitrite-nitrate-curing-salts', id: 'nitrite-nitrate-curing-salts',
@@ -134,11 +142,20 @@ export function calculateProductRating(product, preferences) {
: Math.min( : Math.min(
capOverallScoreForCriticalAdditives(weightedScore, criticalAdditiveCount), capOverallScoreForCriticalAdditives(weightedScore, criticalAdditiveCount),
coverageCap, coverageCap,
allergenReviewRequired ? 77 : 100 allergenReviewRequired ? 77 : 100,
product.cacheStale ? 77 : 100
); );
const limitedByMissingData = !hasBlockedAllergen && weightedScore !== null const limitedByMissingData = !hasBlockedAllergen && weightedScore !== null
&& weightedScore > coverageCap && overallScore === coverageCap; && weightedScore > coverageCap && overallScore === coverageCap;
const overallStatus = overallScore === null ? 'unknown' : statusFromScore(overallScore); const overallStatus = overallScore === null ? 'unknown' : statusFromScore(overallScore);
const scoreLimitReasons = [];
if (hasBlockedAllergen) scoreLimitReasons.push('Ein vermiedenes Allergen ist angegeben.');
if (allergenReviewRequired) scoreLimitReasons.push(categoryScores.allergies.reviewMessage);
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]) => ({ const reasons = Object.entries(categoryScores).map(([category, value]) => ({
category, category,
@@ -153,6 +170,11 @@ export function calculateProductRating(product, preferences) {
limitedByMissingData, limitedByMissingData,
dataCoverage: Math.round(coverage * 100), dataCoverage: Math.round(coverage * 100),
allergenReviewRequired, allergenReviewRequired,
staleDataReviewRequired: product.cacheStale === true,
hasBlockedAllergen,
allergenReviewMessage: categoryScores.allergies.reviewMessage,
mainFactors: ratingFactors(categoryScores, weights, preferences),
scoreLimitReasons,
reasons, reasons,
categoryScores categoryScores
}; };
@@ -170,12 +192,7 @@ function ratingWeights(preferences) {
} }
function weightedCategoryScore(categoryScores, weights, preferences) { function weightedCategoryScore(categoryScores, weights, preferences) {
const applicableEntries = Object.entries(categoryScores).filter(([category]) => ( const applicableEntries = applicableCategoryEntries(categoryScores, preferences);
category !== 'allergies' || (preferences.avoidAllergens || []).length > 0
) && (
category !== 'budget' || Number.isFinite(preferences.maxBudgetPerShoppingTrip)
&& preferences.maxBudgetPerShoppingTrip > 0
));
const knownEntries = applicableEntries.filter(([, value]) => value.hasKnownFacts !== false); const knownEntries = applicableEntries.filter(([, value]) => value.hasKnownFacts !== false);
const totalWeight = knownEntries.reduce((sum, [category]) => sum + weights[category], 0); const totalWeight = knownEntries.reduce((sum, [category]) => sum + weights[category], 0);
const applicableWeight = applicableEntries.reduce((sum, [category]) => sum + weights[category], 0); const applicableWeight = applicableEntries.reduce((sum, [category]) => sum + weights[category], 0);
@@ -192,6 +209,29 @@ function weightedCategoryScore(categoryScores, weights, preferences) {
), coverage }; ), coverage };
} }
function applicableCategoryEntries(categoryScores, preferences) {
return Object.entries(categoryScores).filter(([category]) => (
category !== 'allergies' || (preferences.avoidAllergens || []).length > 0
) && (
category !== 'budget' || Number.isFinite(preferences.maxBudgetPerShoppingTrip)
&& preferences.maxBudgetPerShoppingTrip > 0
));
}
function ratingFactors(categoryScores, weights, preferences) {
return applicableCategoryEntries(categoryScores, preferences)
.filter(([, value]) => value.hasKnownFacts !== false)
.map(([category, value]) => ({
category,
label: categoryLabels[category],
score: value.score,
message: value.message,
impact: Math.round((100 - value.score) * weights[category])
}))
.sort((left, right) => right.impact - left.impact)
.slice(0, 2);
}
function capOverallScoreForCriticalAdditives(score, criticalAdditiveCount) { function capOverallScoreForCriticalAdditives(score, criticalAdditiveCount) {
if (criticalAdditiveCount >= 3) { if (criticalAdditiveCount >= 3) {
return Math.min(score, 35); return Math.min(score, 35);
@@ -213,18 +253,27 @@ function rateAllergies(product, preferences) {
const matchingAllergens = (product.allergens || []).filter((allergen) => const matchingAllergens = (product.allergens || []).filter((allergen) =>
avoidAllergens.some((blockedAllergen) => blockedAllergen.toLowerCase() === allergen.toLowerCase()) avoidAllergens.some((blockedAllergen) => blockedAllergen.toLowerCase() === allergen.toLowerCase())
); );
const matchingTraces = (product.allergenTraces || []).filter((allergen) =>
avoidAllergens.some((blockedAllergen) => blockedAllergen.toLowerCase() === allergen.toLowerCase())
);
const completeness = product.dataCompleteness || {}; const completeness = product.dataCompleteness || {};
const allergenDataMissing = completeness.allergens !== true || !Array.isArray(product.allergens) || product.allergens.length === 0; const allergenDataUnverified = completeness.allergensVerified !== true;
const missingData = missingMessages([ const missingData = missingMessages([
[avoidAllergens.length > 0 && allergenDataMissing, 'Allergenangaben fehlen oder sind nicht bestätigt. Verpackung prüfen.'] [avoidAllergens.length > 0 && allergenDataUnverified, 'Allergenfreiheit ist nicht bestätigt. Verpackung prüfen.']
]); ]);
if (matchingAllergens.length > 0) { if (matchingAllergens.length > 0) {
return withScore(0, `Enthält: ${matchingAllergens.join(', ')}.`, missingData); return withScore(0, `Enthält: ${matchingAllergens.join(', ')}.`, missingData);
} }
if (avoidAllergens.length > 0 && allergenDataMissing) { if (matchingTraces.length > 0) {
return withScore(50, 'Allergenangaben fehlen – Verpackung prüfen.', missingData, { needsReview: true, hasKnownFacts: false }); const reviewMessage = `Mögliche Spuren von ${matchingTraces.join(', ')}. Verpackung prüfen.`;
return withScore(50, reviewMessage, missingData, { needsReview: true, reviewMessage, hasKnownFacts: false });
}
if (avoidAllergens.length > 0 && allergenDataUnverified) {
const reviewMessage = 'Allergenfreiheit ist nicht bestätigt. Verpackung prüfen.';
return withScore(50, reviewMessage, missingData, { needsReview: true, reviewMessage, hasKnownFacts: false });
} }
return withScore(100, avoidAllergens.length > 0 return withScore(100, avoidAllergens.length > 0
@@ -245,14 +294,14 @@ function rateIngredients(product, preferences) {
const vegetarian = ingredientFlag(analysis.vegetarian, hasAnimalIngredient(ingredients, false) ? false : undefined); const vegetarian = ingredientFlag(analysis.vegetarian, hasAnimalIngredient(ingredients, false) ? false : undefined);
const components = [ const components = [
scoreComponent(palmOil === true ? 22 : palmOil === false ? 92 : null, 2), scoreComponent(palmOil === true ? 22 : palmOil === false ? 92 : null, 2),
scoreComponent(additiveScore(additives, completeness.additives, harmfulAdditives), harmfulAdditives.length > 0 ? 3 : 1) scoreComponent(additiveScore(additives, completeness.additives === true && (hasIngredientText || additives.length > 0), harmfulAdditives), harmfulAdditives.length > 0 ? 3 : 1)
]; ];
const missingData = missingMessages([ const missingData = missingMessages([
[!hasIngredientText, 'Zutatenliste fehlt in Open Food Facts.'], [!hasIngredientText, 'Zutatenliste fehlt in Open Food Facts.'],
[palmOil === undefined, 'Palmöl-Analyse fehlt in Open Food Facts.'], [palmOil === undefined, 'Palmöl-Analyse fehlt in Open Food Facts.'],
[preferences.preferredDiet === 'vegan' && vegan === undefined, 'Vegan-Analyse fehlt in Open Food Facts.'], [preferences.preferredDiet === 'vegan' && vegan === undefined, 'Vegan-Analyse fehlt in Open Food Facts.'],
[preferences.preferredDiet === 'vegetarian' && vegetarian === undefined, 'Vegetarisch-Analyse fehlt in Open Food Facts.'], [preferences.preferredDiet === 'vegetarian' && vegetarian === undefined, 'Vegetarisch-Analyse fehlt in Open Food Facts.'],
[completeness.additives === false, 'Zusatzstoffangaben fehlen in Open Food Facts.'] [completeness.additives !== true || (!hasIngredientText && additives.length === 0), 'Zusatzstoffangaben reichen für eine Bewertung nicht aus.']
]); ]);
const scoreDetails = ingredientScoreDetails({ const scoreDetails = ingredientScoreDetails({
additives, additives,
@@ -327,7 +376,12 @@ function rateNutrition(product, preferences) {
const nutrientLevelMessage = messageFromNutrientLevels(highLevels, moderateLevels); const nutrientLevelMessage = messageFromNutrientLevels(highLevels, moderateLevels);
const baseScore = nutritionScoreFromData(product, nutrition, nutrientLevels); const baseScore = nutritionScoreFromData(product, nutrition, nutrientLevels);
const details = nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore, Boolean(calculated)); const details = nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore, Boolean(calculated));
const options = { details, hasKnownFacts: Boolean(nutrition.nutriScore) }; const options = {
details,
hasKnownFacts: Boolean(nutrition.nutriScore),
nutriScore: nutrition.nutriScore,
nutriScoreSource: calculated ? 'calculated' : 'official'
};
if (!nutrition.nutriScore) { if (!nutrition.nutriScore) {
return withScore(50, 'Nutri-Score und ausreichende Nährwerte fehlen.', missingData, options); return withScore(50, 'Nutri-Score und ausreichende Nährwerte fehlen.', missingData, options);
@@ -386,10 +440,11 @@ function rateSustainability(product, preferences) {
const sustainability = product.sustainability || {}; const sustainability = product.sustainability || {};
const carbonFootprint = carbonFootprintValue(sustainability); const carbonFootprint = carbonFootprintValue(sustainability);
const hasEcoScore = Boolean(ecoScoreValues[sustainability.ecoScore]); const hasEcoScore = Boolean(ecoScoreValues[sustainability.ecoScore]);
const originCountry = scoredOriginCountry(product);
const missingData = missingMessages([ const missingData = missingMessages([
[!sustainability.ecoScore, 'Eco-Score fehlt in Open Food Facts.'], [!sustainability.ecoScore, 'Eco-Score fehlt in Open Food Facts.'],
[!hasEcoScore && typeof carbonFootprint !== 'number', 'CO2-Fussabdruck ist nicht verfügbar.'], [!hasEcoScore && typeof carbonFootprint !== 'number', 'CO2-Fussabdruck ist nicht verfügbar.'],
[!hasEcoScore && !sustainability.originCountry, 'Herkunftsland fehlt in Open Food Facts.'], [!hasEcoScore && !originCountry, 'Zutatenherkunft fehlt in Open Food Facts.'],
[!hasEcoScore && !sustainability.packaging, 'Verpackungsangabe fehlt in Open Food Facts.'] [!hasEcoScore && !sustainability.packaging, 'Verpackungsangabe fehlt in Open Food Facts.']
]); ]);
const components = sustainabilityScoreComponents(product, preferences); const components = sustainabilityScoreComponents(product, preferences);
@@ -773,7 +828,7 @@ function sustainabilityScoreComponents(product, preferences) {
? [scoreComponent(ecoScore, 3)] ? [scoreComponent(ecoScore, 3)]
: [ : [
scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2), scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2),
scoreComponent(originScore(sustainability.originCountry), 1), scoreComponent(originScore(scoredOriginCountry(product)), 1),
scoreComponent(packagingScore(sustainability.packaging), 1) scoreComponent(packagingScore(sustainability.packaging), 1)
]; ];
@@ -1134,6 +1189,13 @@ 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) { function isWaterLike(product) {
const terms = productTerms(product); const terms = productTerms(product);
const nutrition = product.nutrition || {}; const nutrition = product.nutrition || {};
+42
View File
@@ -113,6 +113,48 @@ test('offline cached scans work and OFF/network failures fail gracefully', async
} }
}); });
test('stale product data refreshes online and remains usable offline', async () => {
const stale = {
...off({ product_name: 'Old name', allergens_tags: ['en:soybeans'] }),
fetchedAt: '2020-01-01T00:00:00.000Z', price: 3.5,
sustainability: { originCountry: 'Schweiz' }
};
const originalFetch = globalThis.fetch;
let requests = 0;
try {
globalThis.fetch = async () => {
requests += 1;
return { ok: true, json: async () => ({ status: 1, product: {
code: stale.barcode, product_name: 'New name', allergens_tags: ['en:milk'],
origins: 'Frankreich', countries_tags: ['en:switzerland']
} }) };
};
const refreshed = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: stale });
assert.equal(requests, 1);
assert.equal(refreshed.product.name, 'New name');
assert.equal(refreshed.product.price, 3.5);
assert.equal(refreshed.product.sustainability.originCountry, 'Frankreich');
assert.equal(refreshed.product.sustainability.originSource, 'ingredient-origin');
assert.ok(Date.parse(refreshed.product.fetchedAt) > Date.parse(stale.fetchedAt));
const fresh = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: refreshed.product });
assert.equal(requests, 1);
assert.equal(fresh.product.name, 'New name');
const offline = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: stale }, true);
assert.equal(requests, 1);
assert.equal(offline.product.name, 'Old name');
assert.equal(offline.product.cacheStale, true);
globalThis.fetch = async () => { throw new Error('offline'); };
const fallback = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: stale });
assert.equal(fallback.product.cacheStale, true);
assert.equal(fallback.product.name, 'Old name');
} finally {
globalThis.fetch = originalFetch;
}
});
test('ADEME import failure cannot replace the last good local snapshot', async () => { test('ADEME import failure cannot replace the last good local snapshot', async () => {
let wrote = false; let wrote = false;
await assert.rejects(importAgribalyse({ await assert.rejects(importAgribalyse({
+66 -1
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { calculateProductRating } from '../src/services/ratingService.js'; import { calculateProductRating } from '../src/services/ratingService.js';
import { findAlternatives } from '../src/services/alternativesService.js'; import { findAlternatives } from '../src/services/alternativesService.js';
import { mapOpenFoodFactsProduct } from '../src/services/productApi.js';
const preferences = { avoidAllergens: [], preferredDiet: 'none' }; const preferences = { avoidAllergens: [], preferredDiet: 'none' };
const rate = (product, customPreferences = {}) => calculateProductRating( const rate = (product, customPreferences = {}) => calculateProductRating(
@@ -45,6 +46,70 @@ test('a confirmed avoided allergen still blocks the recommendation', () => {
assert.equal(rating.limitedByMissingData, false); assert.equal(rating.limitedByMissingData, false);
}); });
test('an OFF allergen list does not prove a different allergen is absent', () => {
const product = mapOpenFoodFactsProduct({
code: '123', allergens_tags: ['en:soybeans'], traces_tags: [], nutriscore_grade: 'a'
});
const rating = rate(product, { avoidAllergens: ['Milch'] });
assert.equal(rating.categoryScores.allergies.status, 'unknown');
assert.equal(rating.allergenReviewRequired, true);
assert.notEqual(rating.overallStatus, 'good');
});
test('possible traces of a selected allergen require review', () => {
const product = mapOpenFoodFactsProduct({
code: '124', allergens_tags: ['en:soybeans'], traces_tags: ['en:milk'], nutriscore_grade: 'a'
});
const rating = rate(product, { avoidAllergens: ['Milch'] });
assert.equal(rating.categoryScores.allergies.status, 'unknown');
assert.match(rating.allergenReviewMessage, /Spuren von Milch/);
assert.equal(rating.allergenReviewRequired, true);
});
test('a verified absence can contribute to the allergy score', () => {
const rating = rate({
allergens: ['Soja'], allergenTraces: [], dataCompleteness: { allergensVerified: true }
}, { avoidAllergens: ['Milch'] });
assert.equal(rating.categoryScores.allergies.score, 100);
assert.equal(rating.allergenReviewRequired, false);
});
test('empty additive tags without ingredients do not earn ingredient points', () => {
const product = mapOpenFoodFactsProduct({ code: '125', additives_tags: [] });
const rating = rate(product);
assert.equal(product.dataCompleteness.additives, false);
assert.equal(rating.categoryScores.ingredients.status, 'unknown');
});
test('selling countries do not stand in for ingredient origin', () => {
const product = mapOpenFoodFactsProduct({
code: '126', countries_tags: ['en:switzerland'], categories_tags: ['en:unknown-food']
});
const rating = rate(product);
assert.equal(product.sustainability.originCountry, undefined);
assert.deepEqual(product.sustainability.sellingCountries, ['en:switzerland']);
assert.equal(rating.categoryScores.sustainability.status, 'unknown');
const legacyCache = rate({
dataSource: 'cache', sustainability: { originCountry: 'Schweiz' }
});
assert.equal(legacyCache.categoryScores.sustainability.status, 'unknown');
});
test('stale cached facts cannot keep a green recommendation', () => {
const product = {
cacheStale: true,
nutrition: { nutriScore: 'A' },
ingredients: ['Hafer'],
ingredientAnalysis: { palmOil: false, additives: [] },
dataCompleteness: { additives: true },
sustainability: { ecoScore: 'A' }
};
assert.equal(rate({ ...product, cacheStale: false }).overallStatus, 'good');
const rating = rate(product);
assert.equal(rating.overallScore, 77);
assert.equal(rating.staleDataReviewRequired, true);
});
test('Nutri-Score nutrients are not penalized twice', () => { test('Nutri-Score nutrients are not penalized twice', () => {
const plain = rate({ nutrition: { nutriScore: 'C' } }); const plain = rate({ nutrition: { nutriScore: 'C' } });
const flagged = rate({ nutrition: { nutriScore: 'C', nutrientLevels: { sugars: 'high' } } }); const flagged = rate({ nutrition: { nutriScore: 'C', nutrientLevels: { sugars: 'high' } } });
@@ -109,7 +174,7 @@ test('alternatives exclude products whose allergens need review', async () => {
}; };
const verified = { const verified = {
id: 'verified', barcode: '3', name: 'Bestätigt', category: 'Snacks', categoryTags: ['en:snacks'], id: 'verified', barcode: '3', name: 'Bestätigt', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: ['Soja'], dataCompleteness: { allergens: true }, nutrition: { nutriScore: 'A' } allergens: ['Soja'], dataCompleteness: { allergens: true, allergensVerified: true }, nutrition: { nutriScore: 'A' }
}; };
const alternatives = await findAlternatives(source, { const alternatives = await findAlternatives(source, {
...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true ...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true