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
+2 -1
View File
@@ -12,6 +12,7 @@ import RatingCriteriaDetailScreen from './src/screens/RatingCriteriaDetailScreen
import ScanScreen from './src/screens/ScanScreen'; import ScanScreen from './src/screens/ScanScreen';
import ShoppingListScreen from './src/screens/ShoppingListScreen'; import ShoppingListScreen from './src/screens/ShoppingListScreen';
import { lookupProductByBarcode } from './src/services/productApi'; import { lookupProductByBarcode } from './src/services/productApi';
import { enrichEnvironmentalProduct } from './src/services/environmentalService';
import { storageService } from './src/services/storageService'; import { storageService } from './src/services/storageService';
import { colors, defaultPreferences } from './src/utils/constants'; import { colors, defaultPreferences } from './src/utils/constants';
@@ -204,7 +205,7 @@ export default function App() {
} }
function openProduct(product) { function openProduct(product) {
const pricedProduct = applyManualPrice(product); const pricedProduct = applyManualPrice(enrichEnvironmentalProduct(product));
addProductToCache(pricedProduct); addProductToCache(pricedProduct);
addRecentProduct(pricedProduct); addRecentProduct(pricedProduct);
setRoute({ name: 'productDetail', product: pricedProduct }); setRoute({ name: 'productDetail', product: pricedProduct });
+23
View File
@@ -84,6 +84,29 @@ Beispiel-Barcodes für Tests über Open Food Facts:
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`. Wenn ein Produkt bereits lokal gespeichert ist oder der Offline-Modus aktiv ist, wird zuerst der lokale Cache verwendet.
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.
## Umweltinformationen
Open Food Facts bleibt die Quelle für Barcode, Produktbeschreibung und den offiziellen Green-Score (auch unter den älteren `ecoscore_*`-Feldern). Eine auf dem Produkt angegebene CO₂-Bilanz aus `nutriments.carbon-footprint_100g` hat Vorrang. Der AGRIBALYSE-Wert im Green-Score-Datenblock ist dagegen ein **Lebensmittel-Kategoriewert**, keine Messung des Markenprodukts. Er wird nicht als produktspezifischer CO₂-Wert ausgegeben.
Wenn ein produktspezifischer Wert fehlt, sucht die App in der mitgelieferten [AGRIBALYSE-3.2-Synthese von ADEME](https://data.ademe.fr/datasets/agribalyse-31-synthese) für verzehrfertige Lebensmittel. Die Priorität ist: von Open Food Facts zugeordneter AGRIBALYSE-Lebensmittelcode, geprüfte Zuordnung einzelner OFF-Kategorietags in `src/services/environmentalService.js`, danach nur ein Name mit **vollständig übereinstimmenden normalisierten Wörtern** innerhalb einer passenden Oberkategorie. Die Namensschwelle und der Mindestabstand zum zweitbesten Treffer stehen in `MATCHING_CONFIG`. Der Namensabgleichwert beschreibt nur die Übereinstimmung der Wörter, keine statistische Sicherheit. Widersprüche bei Produktart oder Verarbeitung und mehrdeutige Treffer werden verworfen. Die kleine geprüfte Zuordnungstabelle ist bewusst konservativ und kann nach Prüfung weiterer Kategorien erweitert werden; die Regelversion `ENVIRONMENTAL_RULES_VERSION` muss dabei erhöht werden. Ein fehlender Wert bleibt „Nicht verfügbar“.
Die Anzeige nennt CO₂e in kg pro kg Lebensmittel sowie, nur bei eindeutigem Netto-Masseetikett in g oder kg, einen ungefähren Packungswert. Volumen und Abtropfgewicht werden nicht in Masse umgerechnet. Für AGRIBALYSE werden zusätzlich Landnutzung (Pt/kg), Wasserknappheit (m³ deprivation/kg) und der aggregierte EF-Indikator (mPt/kg) aufbewahrt und angezeigt. Die ADEME-Daten beziehen sich auf **1 kg verzehrbares Lebensmittel** und umfassen modellierte Schritte bis zum Verbraucher, einschließlich vereinfachter Verpackung und Transport; diese werden nicht nochmals addiert. Der Weg vom Geschäft nach Hause ist nicht enthalten. Ein AGRIBALYSE-Kategoriedurchschnitt kann als CO₂-Anhaltspunkt in die eigene Nachhaltigkeitswertung einfließen; er erzeugt **keinen offiziellen Green-Score**. Liegt ein offizieller Green-Score vor, verwendet die eigene Wertung diesen statt eines zweiten CO₂-Abzugs.
Die App lädt AGRIBALYSE bei Scans nicht aus dem Netz. `src/data/agribalyse.js` enthält einen lokalen, per Code indexierten Auszug aus 2.451 Einträgen der offiziellen öffentlichen Synthese. Für ein Update mit Netzwerkzugang:
```bash
node scripts/importAgribalyse.mjs
node --test --test-isolation=none tests/environmentalService.test.mjs tests/ratingService.test.mjs tests/nutriScoreService.test.mjs
```
Das Importskript prüft Version, Spalten, CO₂-Einheit, Vollständigkeit und eindeutige Kennungen, bevor es die Snapshot-Datei ersetzt. Nach einer Aktualisierung sind die Zuordnungstabelle und reale Beispiele in den Tests zu prüfen; bei Änderungen der Daten oder Regelversion werden gespeicherte Produktzuordnungen beim nächsten Scan neu aufgelöst. Es ist weder ein API-Schlüssel noch eine weitere Datenbank nötig. Der ADEME-Endpunkt hat ein Limit von [10 Anfragen pro Sekunde und IP](https://www.data.gouv.fr/dataservices/api-impacts-environnementaux-agribalyse-r); das Importskript fragt sequentiell ab. Bestehende Scans funktionieren bei ADEME-Ausfall mit dem enthaltenen Snapshot weiter.
**Datenhinweis und Lizenz:** Quelle ADEME, AGRIBALYSE v3.2, Datenstand 2025-02-27, [Licence Ouverte / Etalab](https://doc.agribalyse.fr/documentation-en/agribalyse-data/terms-of-use-and-environmental-communication). Open-Food-Facts-Produktdaten unterliegen den [OFF-Nutzungsbedingungen](https://openfoodfacts.github.io/documentation/docs/Product-Opener/api/). AGRIBALYSE repräsentiert Durchschnittsprodukte des französischen Marktes, nicht die tatsächliche Rezeptur oder Lieferkette einer Marke. Die Modellierung und geografische Übertragbarkeit können abweichen; ähnliche Lebensmittel können verschiedene Auswirkungen haben. CO₂e, Landnutzung, Wasserknappheit und EF-Gesamtwirkung sind verschiedene Indikatoren und dürfen nicht gleichgesetzt werden.
## Runbook ## Runbook
### Automatischer Android-Build mit Gitea Actions ### Automatischer Android-Build mit Gitea Actions
-10
View File
@@ -65,7 +65,6 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.29.7", "@babel/code-frame": "^7.29.7",
"@babel/generator": "^7.29.7", "@babel/generator": "^7.29.7",
@@ -1920,7 +1919,6 @@
"resolved": "https://registry.npmjs.org/@expo/metro-runtime/-/metro-runtime-6.1.2.tgz", "resolved": "https://registry.npmjs.org/@expo/metro-runtime/-/metro-runtime-6.1.2.tgz",
"integrity": "sha512-nvM+Qv45QH7pmYvP8JB1G8JpScrWND3KrMA6ZKe62cwwNiX/BjHU28Ear0v/4bQWXlOY0mv6B8CDIm8JxXde9g==", "integrity": "sha512-nvM+Qv45QH7pmYvP8JB1G8JpScrWND3KrMA6ZKe62cwwNiX/BjHU28Ear0v/4bQWXlOY0mv6B8CDIm8JxXde9g==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"anser": "^1.4.9", "anser": "^1.4.9",
"pretty-format": "^29.7.0", "pretty-format": "^29.7.0",
@@ -3488,7 +3486,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"baseline-browser-mapping": "^2.10.38", "baseline-browser-mapping": "^2.10.38",
"caniuse-lite": "^1.0.30001799", "caniuse-lite": "^1.0.30001799",
@@ -4110,7 +4107,6 @@
"resolved": "https://registry.npmjs.org/expo/-/expo-54.0.35.tgz", "resolved": "https://registry.npmjs.org/expo/-/expo-54.0.35.tgz",
"integrity": "sha512-E+tXpQwjGm5fK/uwa55p0Xx/kuo5dXDKfVJ95IargTNa5KiFt26lSTXXa9KnHbI4EDLwFD38/xTKZvzPTlGTdg==", "integrity": "sha512-E+tXpQwjGm5fK/uwa55p0Xx/kuo5dXDKfVJ95IargTNa5KiFt26lSTXXa9KnHbI4EDLwFD38/xTKZvzPTlGTdg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.20.0", "@babel/runtime": "^7.20.0",
"@expo/cli": "54.0.25", "@expo/cli": "54.0.25",
@@ -4463,7 +4459,6 @@
"resolved": "https://registry.npmjs.org/expo-font/-/expo-font-14.0.12.tgz", "resolved": "https://registry.npmjs.org/expo-font/-/expo-font-14.0.12.tgz",
"integrity": "sha512-QQzunE2Mxk45AsCWm3tK7OpVljbtVnKD58q4/qliev+cbye1IOduUnRIdD+P7DyButw17G9MTX795kgaQiz5hQ==", "integrity": "sha512-QQzunE2Mxk45AsCWm3tK7OpVljbtVnKD58q4/qliev+cbye1IOduUnRIdD+P7DyButw17G9MTX795kgaQiz5hQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"fontfaceobserver": "^2.1.0" "fontfaceobserver": "^2.1.0"
}, },
@@ -6940,7 +6935,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz",
"integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==", "integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@@ -6960,7 +6954,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz",
"integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==", "integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"scheduler": "^0.26.0" "scheduler": "^0.26.0"
}, },
@@ -6979,7 +6972,6 @@
"resolved": "https://registry.npmjs.org/react-native/-/react-native-0.81.5.tgz", "resolved": "https://registry.npmjs.org/react-native/-/react-native-0.81.5.tgz",
"integrity": "sha512-1w+/oSjEXZjMqsIvmkCRsOc8UBYv163bTWKTI8+1mxztvQPhCRYGTvZ/PL1w16xXHneIj/SLGfxWg2GWN2uexw==", "integrity": "sha512-1w+/oSjEXZjMqsIvmkCRsOc8UBYv163bTWKTI8+1mxztvQPhCRYGTvZ/PL1w16xXHneIj/SLGfxWg2GWN2uexw==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@jest/create-cache-key-function": "^29.7.0", "@jest/create-cache-key-function": "^29.7.0",
"@react-native/assets-registry": "0.81.5", "@react-native/assets-registry": "0.81.5",
@@ -7047,7 +7039,6 @@
"resolved": "https://registry.npmjs.org/react-native-web/-/react-native-web-0.21.2.tgz", "resolved": "https://registry.npmjs.org/react-native-web/-/react-native-web-0.21.2.tgz",
"integrity": "sha512-SO2t9/17zM4iEnFvlu2DA9jqNbzNhoUP+AItkoCOyFmDMOhUnBBznBDCYN92fGdfAkfQlWzPoez6+zLxFNsZEg==", "integrity": "sha512-SO2t9/17zM4iEnFvlu2DA9jqNbzNhoUP+AItkoCOyFmDMOhUnBBznBDCYN92fGdfAkfQlWzPoez6+zLxFNsZEg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.6", "@babel/runtime": "^7.18.6",
"@react-native/normalize-colors": "^0.74.1", "@react-native/normalize-colors": "^0.74.1",
@@ -7142,7 +7133,6 @@
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz",
"integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
+7 -2
View File
@@ -3,7 +3,8 @@ import { StyleSheet, Text, View } from 'react-native';
const labels = { const labels = {
good: 'Gut', good: 'Gut',
medium: 'Prüfen', medium: 'Prüfen',
critical: 'Meiden' critical: 'Meiden',
unknown: 'Daten fehlen'
}; };
const statusStyles = { const statusStyles = {
@@ -18,6 +19,10 @@ const statusStyles = {
critical: { critical: {
backgroundColor: '#fee4e2', backgroundColor: '#fee4e2',
color: '#b42318' color: '#b42318'
},
unknown: {
backgroundColor: '#edf1ee',
color: '#52665d'
} }
}; };
@@ -27,7 +32,7 @@ export default function ProductScoreBadge({ status, score }) {
return ( return (
<View style={[styles.badge, { backgroundColor: style.backgroundColor }]}> <View style={[styles.badge, { backgroundColor: style.backgroundColor }]}>
<Text style={[styles.text, { color: style.color }]}> <Text style={[styles.text, { color: style.color }]}>
{labels[status] || 'Prüfen'} · {score} {labels[status] || 'Prüfen'}{score === null || score === undefined ? '' : ` · ${score}`}
</Text> </Text>
</View> </View>
); );
+65 -3
View File
@@ -35,7 +35,10 @@ export default function ProductDetailScreen({
price: hasProductPrice ? product.price : parsedManualPrice price: hasProductPrice ? product.price : parsedManualPrice
}), [currency, hasProductPrice, parsedManualPrice, product]); }), [currency, hasProductPrice, parsedManualPrice, product]);
const rating = useMemo(() => calculateProductRating(pricedProduct, preferences), [pricedProduct, preferences]); 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() { function addToList() {
if (!hasProductPrice && manualPrice.trim() && parsedManualPrice === undefined) { if (!hasProductPrice && manualPrice.trim() && parsedManualPrice === undefined) {
@@ -75,7 +78,11 @@ export default function ProductDetailScreen({
<Text style={styles.recommendationCopy}> <Text style={styles.recommendationCopy}>
{rating.allergenReviewRequired {rating.allergenReviewRequired
? 'Allergenangaben fehlen oder sind nicht bestätigt. Prüfe vor dem Kauf die Verpackung.' ? '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> </Text>
</View> </View>
</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> <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}>Allergene: {(product.allergens || []).join(', ') || 'Keine Angaben'}</Text>
<Text style={styles.dataText}>Nutri-Score: {product.nutrition?.nutriScore || 'Keine Angabe'}</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> </View>
</ScreenContainer> </ScreenContainer>
@@ -161,6 +203,24 @@ function sourceLabel(source) {
return labels[source] || 'Quelle: unbekannt'; 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({ const styles = StyleSheet.create({
productPanel: { productPanel: {
backgroundColor: colors.surface, backgroundColor: colors.surface,
@@ -215,6 +275,7 @@ const styles = StyleSheet.create({
goodRecommendation: { backgroundColor: '#e4f4e9' }, goodRecommendation: { backgroundColor: '#e4f4e9' },
mediumRecommendation: { backgroundColor: '#fff3d7' }, mediumRecommendation: { backgroundColor: '#fff3d7' },
criticalRecommendation: { backgroundColor: '#fee9e7' }, criticalRecommendation: { backgroundColor: '#fee9e7' },
unknownRecommendation: { backgroundColor: '#edf1ee' },
recommendationTitle: { recommendationTitle: {
fontSize: 17, fontSize: 17,
fontWeight: '800' fontWeight: '800'
@@ -222,6 +283,7 @@ const styles = StyleSheet.create({
goodText: { color: colors.success }, goodText: { color: colors.success },
mediumText: { color: '#8a5914' }, mediumText: { color: '#8a5914' },
criticalText: { color: colors.danger }, criticalText: { color: colors.danger },
unknownText: { color: colors.muted },
recommendationCopy: { recommendationCopy: {
color: colors.text, color: colors.text,
fontSize: 13, 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> <Text style={styles.panelTitle}>So entsteht die Bewertung</Text>
{categoryRating.details.map((detail) => ( {categoryRating.details.map((detail) => (
<View key={`${detail.title}-${detail.meta || ''}`} style={styles.detailItem}> <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} {detail.title}
</Text> </Text>
<Text style={styles.detailBody}>{detail.body}</Text> <Text style={styles.detailBody}>{detail.body}</Text>
@@ -159,6 +160,11 @@ const styles = StyleSheet.create({
fontSize: 14, fontSize: 14,
fontWeight: '800' fontWeight: '800'
}, },
infoTitle: {
color: colors.muted,
fontSize: 14,
fontWeight: '800'
},
detailBody: { detailBody: {
color: colors.muted, color: colors.muted,
fontSize: 14, fontSize: 14,
+10 -4
View File
@@ -1,5 +1,5 @@
import { searchProducts } from './productApi'; import { searchProducts } from './productApi.js';
import { calculateProductRating } from './ratingService'; import { calculateProductRating } from './ratingService.js';
const MIN_SCORE_IMPROVEMENT = 5; const MIN_SCORE_IMPROVEMENT = 5;
const INTERNAL_ALTERNATIVE_LIMIT = 8; const INTERNAL_ALTERNATIVE_LIMIT = 8;
@@ -33,6 +33,7 @@ const categoryGroups = [
export async function findAlternatives(product, preferences, productCache = {}) { export async function findAlternatives(product, preferences, productCache = {}) {
const productRating = calculateProductRating(product, preferences); const productRating = calculateProductRating(product, preferences);
if (productRating.overallScore === null) return [];
const categoryTerms = categoryTermsForProduct(product); const categoryTerms = categoryTermsForProduct(product);
const remoteCandidates = await loadRemoteCandidates(categoryTerms, productCache, preferences.offlineModeEnabled); const remoteCandidates = await loadRemoteCandidates(categoryTerms, productCache, preferences.offlineModeEnabled);
const candidates = uniqueProducts([ const candidates = uniqueProducts([
@@ -49,7 +50,10 @@ export async function findAlternatives(product, preferences, productCache = {})
rating: calculateProductRating(candidate, preferences), rating: calculateProductRating(candidate, preferences),
dataQualityScore: knownDataScore(candidate) 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) => ({ .map((item) => ({
...item, ...item,
reason: buildReason(item.rating, productRating, categoryTerms) reason: buildReason(item.rating, productRating, categoryTerms)
@@ -179,7 +183,9 @@ function strongestCategoryImprovement(rating, sourceRating) {
category, category,
improvement: categoryScore(rating, category) - categoryScore(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]; .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 openFoodFactsBaseUrl = 'https://world.openfoodfacts.org';
const productFields = [ const productFields = [
'code', 'code',
'last_modified_datetime',
'product_name', 'product_name',
'product_name_de', 'product_name_de',
'product_name_en', 'product_name_en',
@@ -10,6 +13,10 @@ const productFields = [
'image_url', 'image_url',
'product_quantity', 'product_quantity',
'quantity', 'quantity',
'net_weight_value',
'net_weight_unit',
'drained_weight_value',
'drained_weight_unit',
'serving_quantity', 'serving_quantity',
'ingredients_text', 'ingredients_text',
'ingredients_text_de', 'ingredients_text_de',
@@ -21,8 +28,15 @@ const productFields = [
'nutriments', 'nutriments',
'nutrient_levels', 'nutrient_levels',
'nutriscore_grade', 'nutriscore_grade',
'nutrition_grades',
'ecoscore_grade', 'ecoscore_grade',
'ecoscore_score',
'ecoscore_data', 'ecoscore_data',
'environmental_score_score',
'environmental_score_grade',
'environmental_score_data',
'categories_properties',
'agribalyse',
'labels_tags', 'labels_tags',
'origins', 'origins',
'origins_tags', 'origins_tags',
@@ -35,7 +49,7 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline
const cachedProduct = productCache[normalizedBarcode] || productCache[barcode]; const cachedProduct = productCache[normalizedBarcode] || productCache[barcode];
if (cachedProduct) { if (cachedProduct) {
return { status: 'found', product: { ...cachedProduct, dataSource: 'cache' }, source: 'cache' }; return { status: 'found', product: { ...enrichEnvironmentalProduct(cachedProduct), dataSource: 'cache' }, source: 'cache' };
} }
if (offlineModeEnabled) { if (offlineModeEnabled) {
@@ -58,7 +72,7 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline
} }
const payload = await response.json(); 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 { return {
status: 'notFound', status: 'notFound',
errorMessage: 'Kein Produkt zu diesem Barcode in Open Food Facts gefunden.' errorMessage: 'Kein Produkt zu diesem Barcode in Open Food Facts gefunden.'
@@ -87,7 +101,7 @@ export async function searchProducts(query, productCache = {}, offlineModeEnable
} }
if (offlineModeEnabled) { if (offlineModeEnabled) {
return filterProducts(markProductsSource(cachedProducts, 'cache'), normalizedQuery); return filterProducts(markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache'), normalizedQuery);
} }
try { try {
@@ -97,42 +111,51 @@ export async function searchProducts(query, productCache = {}, offlineModeEnable
if (!response.ok) { if (!response.ok) {
return filterProducts([ return filterProducts([
...markProductsSource(cachedProducts, 'cache') ...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery); ], normalizedQuery);
} }
const payload = await response.json(); const payload = await response.json();
const apiProducts = (payload.products || []) const apiProducts = (Array.isArray(payload?.products) ? payload.products : [])
.filter((product) => product.code) .filter((product) => product && typeof product === 'object' && product.code)
.map((product) => mapOpenFoodFactsProduct(product, product.code)); .map((product) => mapOpenFoodFactsProduct(product, product.code));
return uniqueProducts(filterProducts([ return uniqueProducts(filterProducts([
...apiProducts, ...apiProducts,
...markProductsSource(cachedProducts, 'cache') ...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery)); ], normalizedQuery));
} catch (error) { } catch (error) {
return filterProducts([ return filterProducts([
...markProductsSource(cachedProducts, 'cache') ...markProductsSource(cachedProducts.map(enrichEnvironmentalProduct), 'cache')
], normalizedQuery); ], normalizedQuery);
} }
} }
function mapOpenFoodFactsProduct(product, fallbackBarcode) { export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
const barcode = normalizeBarcode(product.code || fallbackBarcode); const barcode = normalizeBarcode(product.code || fallbackBarcode);
const nutriments = product.nutriments || {}; 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(); const now = new Date().toISOString();
return { return enrichEnvironmentalProduct({
id: `off-${barcode}`, id: `off-${barcode}`,
barcode, barcode,
dataSource: 'open-food-facts', dataSource: 'open-food-facts',
name: product.product_name_de || product.product_name || product.product_name_en || `Produkt ${barcode}`, name: product.product_name_de || product.product_name || product.product_name_en || `Produkt ${barcode}`,
brand: firstTextValue(product.brands), brand: firstTextValue(product.brands),
category: firstCategory(product.categories, product.categories_tags), 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, imageUrl: product.image_url,
packageQuantityGrams: numberOrUndefined(product.product_quantity), packageQuantityGrams: numberOrUndefined(product.product_quantity),
packageQuantityLabel: firstTextValue(product.quantity), packageQuantityLabel: typeof product.quantity === 'string' ? product.quantity.trim() : undefined,
servingQuantityGrams: numberOrUndefined(product.serving_quantity), servingQuantityGrams: numberOrUndefined(product.serving_quantity),
price: undefined, price: undefined,
currency: 'CHF', currency: 'CHF',
@@ -146,33 +169,42 @@ function mapOpenFoodFactsProduct(product, fallbackBarcode) {
allergens: normalizeAllergens(product.allergens_tags || []), allergens: normalizeAllergens(product.allergens_tags || []),
nutrition: { nutrition: {
caloriesPer100g: numberOrUndefined(nutriments['energy-kcal_100g']), caloriesPer100g: numberOrUndefined(nutriments['energy-kcal_100g']),
energyKjPer100g: numberOrUndefined(nutriments['energy-kj_100g'] ?? nutriments.energy_100g),
sugarPer100g: numberOrUndefined(nutriments.sugars_100g), sugarPer100g: numberOrUndefined(nutriments.sugars_100g),
caffeineMgPer100g: normalizeCaffeineMg(nutriments.caffeine_100g), caffeineMgPer100g: normalizeCaffeineMg(nutriments.caffeine_100g),
fatPer100g: numberOrUndefined(nutriments.fat_100g), fatPer100g: numberOrUndefined(nutriments.fat_100g),
saturatedFatPer100g: numberOrUndefined(nutriments['saturated-fat_100g']), saturatedFatPer100g: numberOrUndefined(nutriments['saturated-fat_100g']),
proteinPer100g: numberOrUndefined(nutriments.proteins_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), 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), nutrientLevels: normalizeNutrientLevels(product.nutrient_levels),
nutriScore: normalizeGrade(product.nutriscore_grade) nutriScore
}, },
sustainability: { sustainability: {
ecoScore: normalizeGrade(product.ecoscore_grade), ecoScore,
carbonFootprintKgCo2ePerKg: numberOrUndefined(product.ecoscore_data?.agribalyse?.co2_total), ecoScoreScore: numberOrUndefined(product.environmental_score_score ?? product.ecoscore_score),
isBio: hasOrganicLabel(product.labels_tags || []), 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), originCountry: firstOrigin(product.origins, product.origins_tags, product.countries_tags),
packaging: firstTextValue(product.packaging) packaging: firstTextValue(product.packaging)
}, },
dataCompleteness: { dataCompleteness: {
allergens: Array.isArray(product.allergens_tags), allergens: Array.isArray(product.allergens_tags),
additives: Array.isArray(product.additives_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), 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) nutrition: Boolean(product.nutriments)
}, },
createdAt: now, createdAt: now,
updatedAt: now updatedAt: now
}; });
} }
function markProductsSource(products, source) { function markProductsSource(products, source) {
@@ -212,26 +244,27 @@ function firstCategory(categories, categoryTags = []) {
const category = firstTextValue(categories); const category = firstTextValue(categories);
if (category) return category; if (category) return category;
const tag = categoryTags.find(Boolean); const tag = (Array.isArray(categoryTags) ? categoryTags : []).find(Boolean);
return tag ? cleanTag(tag) : undefined; return tag ? cleanTag(tag) : undefined;
} }
function firstOrigin(origins, originTags = [], countryTags = []) { function firstOrigin(origins, originTags = [], countryTags = []) {
return firstTextValue(origins) return firstTextValue(origins)
|| cleanTag(originTags.find(Boolean)) || cleanTag((Array.isArray(originTags) ? originTags : []).find(Boolean))
|| cleanTag(countryTags.find(Boolean)); || cleanTag((Array.isArray(countryTags) ? countryTags : []).find(Boolean));
} }
function parseIngredients(ingredientsText) { function parseIngredients(ingredientsText) {
if (!ingredientsText) return []; if (typeof ingredientsText !== 'string') return [];
return ingredientsText return ingredientsText
.split(/[,;.]/) .split(/[,;.]/)
.map((ingredient) => ingredient.trim()) .map((ingredient) => ingredient.trim())
.filter(Boolean) .filter(Boolean)
.slice(0, 16); .slice(0, 100);
} }
function analysisStatus(analysisTags = [], diet) { function analysisStatus(analysisTags = [], diet) {
if (!Array.isArray(analysisTags)) return undefined;
if (analysisTags.includes(`en:${diet}`)) { if (analysisTags.includes(`en:${diet}`)) {
return true; return true;
} }
@@ -248,6 +281,8 @@ function analysisStatus(analysisTags = [], diet) {
} }
function palmOilStatus(analysisTags = [], palmOilTags = []) { function palmOilStatus(analysisTags = [], palmOilTags = []) {
if (!Array.isArray(analysisTags)) analysisTags = [];
if (!Array.isArray(palmOilTags)) palmOilTags = [];
if (analysisTags.includes('en:palm-oil') || palmOilTags.length > 0) { if (analysisTags.includes('en:palm-oil') || palmOilTags.length > 0) {
return true; return true;
} }
@@ -299,7 +334,7 @@ function normalizeAllergens(allergenTags) {
} }
function normalizeTags(tags) { function normalizeTags(tags) {
return tags return (Array.isArray(tags) ? tags : [])
.map((tag) => String(tag || '').trim().toLowerCase()) .map((tag) => String(tag || '').trim().toLowerCase())
.filter(Boolean); .filter(Boolean);
} }
@@ -331,6 +366,7 @@ function hasOrganicLabel(labelTags) {
} }
function numberOrUndefined(value) { function numberOrUndefined(value) {
if (value === null || value === undefined || value === '') return undefined;
const numberValue = Number(value); const numberValue = Number(value);
return Number.isFinite(numberValue) ? numberValue : undefined; return Number.isFinite(numberValue) ? numberValue : undefined;
} }
+153 -109
View File
@@ -1,3 +1,5 @@
import { calculateNutriScore } from './nutriScoreService.js';
const nutrientLevelLabels = { const nutrientLevelLabels = {
fat: 'Fett', fat: 'Fett',
saturatedFat: 'gesättigte Fettsäuren', saturatedFat: 'gesättigte Fettsäuren',
@@ -124,13 +126,19 @@ export function calculateProductRating(product, preferences) {
const hasBlockedAllergen = categoryScores.allergies.score === 0; const hasBlockedAllergen = categoryScores.allergies.score === 0;
const allergenReviewRequired = categoryScores.allergies.needsReview === true; const allergenReviewRequired = categoryScores.allergies.needsReview === true;
const criticalAdditiveCount = categoryScores.ingredients.criticalAdditiveCount || 0; 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 const overallScore = hasBlockedAllergen
? 0 ? 0
: weightedScore === null ? null
: Math.min( : Math.min(
capOverallScoreForCriticalAdditives(weightedCategoryScore(categoryScores, weights), criticalAdditiveCount), capOverallScoreForCriticalAdditives(weightedScore, criticalAdditiveCount),
coverageCap,
allergenReviewRequired ? 77 : 100 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]) => ({ const reasons = Object.entries(categoryScores).map(([category, value]) => ({
category, category,
@@ -142,35 +150,46 @@ export function calculateProductRating(product, preferences) {
productId: product.id, productId: product.id,
overallStatus, overallStatus,
overallScore, overallScore,
limitedByMissingData,
dataCoverage: Math.round(coverage * 100),
allergenReviewRequired, allergenReviewRequired,
reasons, reasons,
categoryScores categoryScores
}; };
} }
function ratingWeights() { function ratingWeights(preferences) {
const priorityFactors = { low: 0.5, medium: 0.75, high: 1 };
return { return {
allergies: 0.1, allergies: 0.1,
budget: 0.2, budget: 0.2,
ingredients: 0.15, ingredients: 0.15,
nutrition: 0.35, nutrition: 0.35 * (priorityFactors[preferences.nutritionPriority] ?? 1),
sustainability: 0.2 sustainability: 0.2 * (priorityFactors[preferences.sustainabilityPriority] ?? 0.75)
}; };
} }
function weightedCategoryScore(categoryScores, weights) { function weightedCategoryScore(categoryScores, weights, preferences) {
const knownEntries = Object.entries(categoryScores).filter(([, value]) => value.hasKnownFacts !== false); 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 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) { if (totalWeight === 0) {
return 50; return { score: null, coverage };
} }
return Math.round( return { score: Math.round(
knownEntries.reduce((sum, [category, value]) => ( knownEntries.reduce((sum, [category, value]) => (
sum + value.score * weights[category] sum + value.score * weights[category]
), 0) / totalWeight ), 0) / totalWeight
); ), coverage };
} }
function capOverallScoreForCriticalAdditives(score, criticalAdditiveCount) { function capOverallScoreForCriticalAdditives(score, criticalAdditiveCount) {
@@ -205,10 +224,12 @@ function rateAllergies(product, preferences) {
} }
if (avoidAllergens.length > 0 && allergenDataMissing) { 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) { function rateIngredients(product, preferences) {
@@ -218,12 +239,10 @@ function rateIngredients(product, preferences) {
const harmfulAdditives = harmfulAdditiveMatches(additives, ingredients); const harmfulAdditives = harmfulAdditiveMatches(additives, ingredients);
const completeness = product.dataCompleteness || {}; const completeness = product.dataCompleteness || {};
const hasIngredientText = ingredients.length > 0; const hasIngredientText = ingredients.length > 0;
const palmOil = ingredientFlag( const palmOil = ingredients.some((ingredient) => palmOilTerms().some((term) => ingredient.includes(term)))
analysis.palmOil, ? true : ingredientFlag(analysis.palmOil, undefined);
ingredients.some((ingredient) => palmOilTerms().some((term) => ingredient.includes(term))) const vegan = ingredientFlag(analysis.vegan, hasAnimalIngredient(ingredients, true) ? false : undefined);
); const vegetarian = ingredientFlag(analysis.vegetarian, hasAnimalIngredient(ingredients, false) ? false : undefined);
const vegan = ingredientFlag(analysis.vegan, hasIngredientText ? !hasAnimalIngredient(ingredients, true) : undefined);
const vegetarian = ingredientFlag(analysis.vegetarian, hasIngredientText ? !hasAnimalIngredient(ingredients, 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, 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, '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) { 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 nutrientLevels = nutrition.nutrientLevels || {};
const highLevels = nutrientLevelEntries(nutrientLevels, 'high'); const highLevels = nutrientLevelEntries(nutrientLevels, 'high');
const moderateLevels = nutrientLevelEntries(nutrientLevels, 'moderate'); const moderateLevels = nutrientLevelEntries(nutrientLevels, 'moderate');
const missingData = missingMessages([ 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.'], [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 === 'lowSugar' && typeof nutrition.sugarPer100g !== 'number', 'Zuckerwert pro 100 g fehlt.'],
[preferences.preferredDiet === 'highProtein' && !isBeverage(product) && typeof nutrition.proteinPer100g !== 'number', 'Proteinwert 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 nutrientLevelStatus = statusFromNutrientLevels(highLevels, moderateLevels);
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); const details = nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore, Boolean(calculated));
const options = { details }; 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') { 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) { if (score < 48) {
return withScore(score, nutrientLevelMessage || 'Sehr hoher Zuckergehalt für dein Ziel.', missingData, options); 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); 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) { if (score < 78) {
return withScore(score, nutrientLevelMessage || 'Proteinanteil ist eher niedrig.', missingData, options); return withScore(score, nutrientLevelMessage || 'Proteinanteil ist eher niedrig.', missingData, options);
} }
@@ -331,34 +368,35 @@ function rateNutrition(product, preferences) {
} }
if (nutrientLevelStatus !== 'good') { 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)) { 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') { 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) { 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 missingData = missingMessages([ const missingData = missingMessages([
[!sustainability.ecoScore, 'Eco-Score fehlt in Open Food Facts.'], [!sustainability.ecoScore, 'Eco-Score fehlt in Open Food Facts.'],
[typeof carbonFootprint !== 'number', 'CO2-Fussabdruck fehlt in Open Food Facts.'], [!hasEcoScore && typeof carbonFootprint !== 'number', 'CO2-Fussabdruck ist nicht verfügbar.'],
[!sustainability.originCountry, 'Herkunftsland fehlt in Open Food Facts.'], [!hasEcoScore && !sustainability.originCountry, 'Herkunftsland fehlt in Open Food Facts.'],
[!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);
const score = weightedKnownScore(components, 50); const score = weightedKnownScore(components, 50);
const options = { hasKnownFacts: hasKnownComponents(components) }; 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); 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 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) { function rateBudget(product, preferences) {
@@ -379,8 +421,9 @@ function rateBudget(product, preferences) {
[typeof preferences.maxBudgetPerShoppingTrip !== 'number', 'Budgetlimit fehlt im Profil.'] [typeof preferences.maxBudgetPerShoppingTrip !== 'number', 'Budgetlimit fehlt im Profil.']
]); ]);
if (typeof product.price !== 'number' || typeof preferences.maxBudgetPerShoppingTrip !== 'number') { if (!Number.isFinite(product.price) || !Number.isFinite(preferences.maxBudgetPerShoppingTrip)
return withScore(55, 'Preis oder Budget fehlt für eine genaue Prüfung.', missingData); || 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; const share = product.price / preferences.maxBudgetPerShoppingTrip;
@@ -399,38 +442,27 @@ function rateBudget(product, preferences) {
} }
function nutritionScoreFromData(product, nutrition, nutrientLevels) { function nutritionScoreFromData(product, nutrition, nutrientLevels) {
if (isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) { if (nutrition.nutriScore === 'A' && isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
return 98; return 98;
} }
if (isBeverage(product) && !nutrition.nutriScore && hasNoCriticalNutrients(nutrition, nutrientLevels)) { return nutriScoreValues[nutrition.nutriScore] ?? 50;
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);
} }
function nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore) { function nutritionScoreDetails(product, preferences, nutrition, nutrientLevels, baseScore, calculated) {
const details = []; const details = [];
if (nutrition.nutriScore) { if (nutrition.nutriScore) {
const nutriScoreValue = nutriScoreValues[nutrition.nutriScore] ?? 50; const nutriScoreValue = nutriScoreValues[nutrition.nutriScore] ?? 50;
details.push({ details.push({
type: nutriScoreValue >= 78 ? 'positive' : 'penalty', type: nutriScoreValue >= 78 ? 'positive' : 'penalty',
title: `Nutri-Score ${nutrition.nutriScore}`, title: `${calculated ? 'Berechneter ' : ''}Nutri-Score ${nutrition.nutriScore}`,
body: nutriScoreValue >= 78 body: nutriScoreValue >= 78
? 'Der Nutri-Score ist gut und erhöht die Ernährungswertung.' ? 'Der Nutri-Score ist gut und erhöht die Ernährungswertung.'
: nutriScoreValue >= 48 : nutriScoreValue >= 48
? 'Der Nutri-Score ist mittelmässig und begrenzt die Ernährungswertung.' ? 'Der Nutri-Score ist mittelmässig und begrenzt die Ernährungswertung.'
: 'Der Nutri-Score ist schwach und reduziert die Ernährungswertung deutlich.', : '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)); details.push(proteinGoalDetail(nutrition.proteinPer100g));
} }
if (isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) { if (nutrition.nutriScore === 'A' && isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
details.push({ details.push({
type: 'positive', type: 'positive',
title: 'Wasserähnliches Produkt', title: 'Wasserähnliches Produkt',
body: 'Wasserähnliche Produkte ohne kritische Nährwerte bekommen eine sehr gute Ernährungswertung.', 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.' 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({ details.push({
type: baseScore >= 78 ? 'positive' : 'penalty', type: nutrition.nutriScore ? baseScore >= 78 ? 'positive' : 'penalty' : 'info',
title: 'Ernährungsbasis', title: nutrition.nutriScore ? 'Ernährungsbasis' : 'Ernährungsbasis nicht verfügbar',
body: 'Die Basiswertung kombiniert Nutri-Score und Nährwert-Level. Hohe Level werden stärker abgezogen als mittlere Level.', body: nutrition.nutriScore
meta: `Aktueller Basiswert: ${Math.round(baseScore)} von 100` ? '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; return details;
@@ -477,36 +504,36 @@ function nutritionNutrientDetails(nutrition, nutrientLevels) {
label: 'Zucker', label: 'Zucker',
value: nutrition.sugarPer100g, value: nutrition.sugarPer100g,
unit: 'g pro 100 g', unit: 'g pro 100 g',
highText: 'Hoher Zuckerwert reduziert die Bewertung deutlich, besonders bei Low-Sugar-Ziel.', highText: 'Hoher Zuckerwert ist im Nutri-Score berücksichtigt und kann zusätzlich dein Low-Sugar-Ziel verfehlen.',
moderateText: 'Mittlerer Zuckerwert reduziert die Bewertung leicht bis moderat.', moderateText: 'Mittlerer Zuckerwert ist im Nutri-Score berücksichtigt.',
lowText: 'Niedriger Zuckerwert verbessert die Bewertung.' lowText: 'Zucker wird im Nutri-Score berücksichtigt.'
}, },
{ {
key: 'fat', key: 'fat',
label: 'Fett', label: 'Fett',
value: nutrition.fatPer100g, value: nutrition.fatPer100g,
unit: 'g pro 100 g', unit: 'g pro 100 g',
highText: 'Hoher Fettwert reduziert die Bewertung.', highText: 'Der Gesamtfettwert ist ein Hinweis, führt aber nicht zu einem zusätzlichen Abzug.',
moderateText: 'Mittlerer Fettwert reduziert die Bewertung leicht.', moderateText: 'Der Gesamtfettwert führt nicht zu einem zusätzlichen Abzug.',
lowText: 'Niedriger Fettwert ist positiv.' lowText: 'Der Gesamtfettwert führt nicht zu einem zusätzlichen Abzug.'
}, },
{ {
key: 'saturatedFat', key: 'saturatedFat',
label: 'Gesättigte Fettsäuren', label: 'Gesättigte Fettsäuren',
value: nutrition.saturatedFatPer100g, value: nutrition.saturatedFatPer100g,
unit: 'g pro 100 g', unit: 'g pro 100 g',
highText: 'Hohe gesättigte Fettsäuren reduzieren die Bewertung deutlich.', highText: 'Gesättigte Fettsäuren sind im Nutri-Score berücksichtigt.',
moderateText: 'Mittlere gesättigte Fettsäuren reduzieren die Bewertung.', moderateText: 'Gesättigte Fettsäuren sind im Nutri-Score berücksichtigt.',
lowText: 'Niedrige gesättigte Fettsäuren sind positiv.' lowText: 'Gesättigte Fettsäuren sind im Nutri-Score berücksichtigt.'
}, },
{ {
key: 'salt', key: 'salt',
label: 'Salz', label: 'Salz',
value: nutrition.saltPer100g, value: nutrition.saltPer100g,
unit: 'g pro 100 g', unit: 'g pro 100 g',
highText: 'Hoher Salzgehalt reduziert die Bewertung deutlich.', highText: 'Salz ist im Nutri-Score berücksichtigt.',
moderateText: 'Mittlerer Salzgehalt reduziert die Bewertung.', moderateText: 'Salz ist im Nutri-Score berücksichtigt.',
lowText: 'Niedriger Salzgehalt ist positiv.' lowText: 'Salz ist im Nutri-Score berücksichtigt.'
} }
]; ];
@@ -516,7 +543,7 @@ function nutritionNutrientDetails(nutrition, nutrientLevels) {
} }
function nutrientDetail(entry, level) { 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' const body = level === 'high'
? entry.highText ? entry.highText
: level === 'moderate' : level === 'moderate'
@@ -544,9 +571,10 @@ function sugarGoalDetail(sugarPer100g, sugarLevel) {
const score = sugarScore(sugarPer100g, sugarLevel); const score = sugarScore(sugarPer100g, sugarLevel);
return { return {
type: score >= 78 ? 'positive' : 'penalty', type: score === null ? 'info' : score >= 78 ? 'positive' : 'penalty',
title: 'Low-Sugar-Ziel', 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.' ? 'Der Zuckerwert passt zu deinem Low-Sugar-Ziel.'
: score >= 48 : score >= 48
? 'Der Zuckerwert liegt über dem idealen Bereich für dein Low-Sugar-Ziel.' ? 'Der Zuckerwert liegt über dem idealen Bereich für dein Low-Sugar-Ziel.'
@@ -561,9 +589,10 @@ function proteinGoalDetail(proteinPer100g) {
const score = proteinScore(proteinPer100g); const score = proteinScore(proteinPer100g);
return { return {
type: score >= 78 ? 'positive' : 'penalty', type: score === null ? 'info' : score >= 78 ? 'positive' : 'penalty',
title: 'Protein-Ziel', 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 passt gut zu deinem High-Protein-Ziel.'
: 'Der Proteinanteil ist für dein High-Protein-Ziel eher niedrig.', : 'Der Proteinanteil ist für dein High-Protein-Ziel eher niedrig.',
meta: typeof proteinPer100g === 'number' meta: typeof proteinPer100g === 'number'
@@ -596,7 +625,7 @@ function sugarScore(sugarPer100g, sugarLevel) {
} }
if (typeof sugarPer100g !== 'number') { if (typeof sugarPer100g !== 'number') {
return 55; return null;
} }
if (sugarPer100g <= 5) return 100; if (sugarPer100g <= 5) return 100;
@@ -607,7 +636,7 @@ function sugarScore(sugarPer100g, sugarLevel) {
function proteinScore(proteinPer100g) { function proteinScore(proteinPer100g) {
if (typeof proteinPer100g !== 'number') { if (typeof proteinPer100g !== 'number') {
return 55; return null;
} }
if (proteinPer100g >= 20) return 100; if (proteinPer100g >= 20) return 100;
@@ -617,10 +646,6 @@ function proteinScore(proteinPer100g) {
} }
function additiveScore(additives, additivesKnown, harmfulAdditives = []) { function additiveScore(additives, additivesKnown, harmfulAdditives = []) {
if (!additivesKnown) {
return null;
}
if (harmfulAdditives.length >= 3) { if (harmfulAdditives.length >= 3) {
return 0; return 0;
} }
@@ -633,6 +658,10 @@ function additiveScore(additives, additivesKnown, harmfulAdditives = []) {
return 18; return 18;
} }
if (!additivesKnown) {
return null;
}
if (additives.length === 0) { if (additives.length === 0) {
return 95; return 95;
} }
@@ -708,22 +737,24 @@ function ingredientScoreDetails({ additives, harmfulAdditives, palmOil, preferen
if (preferences.preferredDiet === 'vegan') { if (preferences.preferredDiet === 'vegan') {
details.push({ details.push({
type: vegan === true ? 'positive' : 'penalty', type: vegan === undefined ? 'info' : vegan === true ? 'positive' : 'penalty',
title: vegan === true ? 'Vegan kompatibel' : 'Nicht vegan oder unklar', title: vegan === true ? 'Vegan kompatibel' : vegan === false ? 'Nicht vegan' : 'Vegan unklar',
body: vegan === true body: vegan === true
? 'Die Zutatenanalyse passt zum veganen Ziel.' ? '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.' meta: 'Relevant wegen deinem Profilziel: Vegan.'
}); });
} }
if (preferences.preferredDiet === 'vegetarian') { if (preferences.preferredDiet === 'vegetarian') {
details.push({ details.push({
type: vegetarian === true ? 'positive' : 'penalty', type: vegetarian === undefined ? 'info' : vegetarian === true ? 'positive' : 'penalty',
title: vegetarian === true ? 'Vegetarisch kompatibel' : 'Nicht vegetarisch oder unklar', title: vegetarian === true ? 'Vegetarisch kompatibel' : vegetarian === false ? 'Nicht vegetarisch' : 'Vegetarisch unklar',
body: vegetarian === true body: vegetarian === true
? 'Die Zutatenanalyse passt zum vegetarischen Ziel.' ? '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.' meta: 'Relevant wegen deinem Profilziel: Vegetarisch.'
}); });
} }
@@ -737,15 +768,17 @@ function sustainabilityScore(product, preferences) {
function sustainabilityScoreComponents(product, preferences) { function sustainabilityScoreComponents(product, preferences) {
const sustainability = product.sustainability || {}; const sustainability = product.sustainability || {};
const components = [ const ecoScore = ecoScoreValues[sustainability.ecoScore];
scoreComponent(ecoScoreValues[sustainability.ecoScore], 3), const components = ecoScore
scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2), ? [scoreComponent(ecoScore, 3)]
scoreComponent(originScore(sustainability.originCountry), 1), : [
scoreComponent(packagingScore(sustainability.packaging), 1) scoreComponent(carbonFootprintScore(carbonFootprintValue(sustainability)), 2),
]; scoreComponent(originScore(sustainability.originCountry), 1),
scoreComponent(packagingScore(sustainability.packaging), 1)
];
if (bioPreferenceApplies(product, preferences)) { 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; return components;
@@ -814,9 +847,10 @@ function budgetPeriodLabel(period) {
function withScore(score, message, missingData = [], options = {}) { function withScore(score, message, missingData = [], options = {}) {
const roundedScore = Math.round(clampScore(score)); const roundedScore = Math.round(clampScore(score));
const hasKnownFacts = options.hasKnownFacts !== false;
return { return {
status: statusFromScore(roundedScore), status: hasKnownFacts ? statusFromScore(roundedScore) : 'unknown',
score: roundedScore, score: hasKnownFacts ? roundedScore : null,
message, message,
missingData, missingData,
...options ...options
@@ -869,7 +903,7 @@ function hasKnownComponents(components) {
} }
function carbonFootprintValue(sustainability) { function carbonFootprintValue(sustainability) {
if (typeof sustainability.carbonFootprintKgCo2ePerKg === 'number') { if (typeof sustainability.carbonFootprintKgCo2ePerKg === 'number' && Number.isFinite(sustainability.carbonFootprintKgCo2ePerKg) && sustainability.carbonFootprintKgCo2ePerKg >= 0) {
return sustainability.carbonFootprintKgCo2ePerKg; return sustainability.carbonFootprintKgCo2ePerKg;
} }
@@ -917,7 +951,7 @@ function originScore(originCountry) {
return 78; 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; return 68;
} }
@@ -1092,23 +1126,33 @@ function hasAnimalIngredient(ingredients, includeDairyAndEggs) {
? [...alwaysAnimalTerms, ...veganOnlyTerms] ? [...alwaysAnimalTerms, ...veganOnlyTerms]
: alwaysAnimalTerms; : alwaysAnimalTerms;
return ingredients.some((ingredient) => return ingredients.some((ingredient) => {
blockedTerms.some((term) => ingredient.includes(term)) 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) { function isWaterLike(product) {
const terms = productTerms(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) ['water', 'waters', 'wasser', 'mineral water', 'sparkling water', 'still water', 'eau'].includes(term)
|| term.includes('mineralwasser') || 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) { function isBeverage(product) {
const terms = productTerms(product); const terms = productTerms(product);
return terms.some((term) => 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('beverage')
|| term.includes('drink') || term.includes('drink')
|| term.includes('getränk') || term.includes('getränk')
+123
View File
@@ -0,0 +1,123 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { importAgribalyse } from '../scripts/importAgribalyse.mjs';
import { mapOpenFoodFactsProduct, lookupProductByBarcode, searchProducts } from '../src/services/productApi.js';
import { enrichEnvironmentalProduct, productSpecificFootprint, ENVIRONMENTAL_RULES_VERSION } from '../src/services/environmentalService.js';
const off = (overrides = {}) => mapOpenFoodFactsProduct({
code: '12345678', product_name: 'Banana', categories_tags: ['en:fruits', 'en:bananas'],
quantity: '500 g', ...overrides
});
test('product-specific OFF footprint and Green-Score take priority over category impact', () => {
const product = off({
environmental_score_grade: 'b', environmental_score_score: 70,
categories_properties: { 'agribalyse_food_code:en': '13005' },
nutriments: { 'carbon-footprint_100g': 120 }
});
assert.equal(product.sustainability.ecoScore, 'B');
assert.equal(product.sustainability.ecoScoreScore, 70);
assert.equal(product.sustainability.footprint.status, 'product-specific');
assert.equal(product.sustainability.footprint.valueKgCo2ePerKg, 1.2);
assert.equal(product.sustainability.footprint.packageKgCo2e, 0.6);
});
test('missing product footprint falls back to verified AGRIBALYSE entry with indicators', () => {
const product = off({ categories_properties: { 'agribalyse_food_code:en': '13005' } });
const footprint = product.sustainability.footprint;
assert.equal(footprint.status, 'estimated');
assert.equal(footprint.sourceId, '13005');
assert.equal(footprint.valueKgCo2ePerKg, 0.909);
assert.equal(footprint.matchMethod, 'off-category-code');
assert.equal(footprint.datasetVersion, '3.2');
assert.equal(footprint.packageKgCo2e, 0.4545);
assert.equal(footprint.sourceUnit, 'kg CO2 eq/kg de produit');
assert.equal(footprint.indicators.landUse.unit, 'Pt/kg de produit');
assert.equal(footprint.indicators.waterScarcity.unit, 'm3 depriv./kg de produit');
assert.equal(footprint.indicators.singleScore.unit, 'mPt/kg de produit');
});
test('CO2 estimate does not create an official Green-Score', () => {
const product = off();
assert.equal(product.sustainability.footprint.status, 'estimated');
assert.equal(product.sustainability.ecoScore, undefined);
});
test('unrelated, conflicting and ambiguous categories remain unavailable', () => {
assert.equal(off({ categories_tags: ['en:unknown-food'], product_name: 'Mystery bar' }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ categories_tags: ['en:apples', 'en:bananas'] }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ product_name: 'Dried banana' }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ product_name: 'Banana smoothie', categories_tags: ['en:bananas', 'en:smoothies'] }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ product_name: 'Banana', categories_properties: { 'agribalyse_food_code:en': '20009' } }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ ingredients_text: 'Banana, sugar' }).sustainability.footprint.status, 'unavailable');
});
test('similar names do not override structured categories', () => {
const banana = off();
const plantain = off({ product_name: 'Plantain banana', categories_tags: ['en:plantains'] });
const apple = off({ product_name: 'Apple', categories_tags: ['en:apples'] });
assert.equal(banana.sustainability.footprint.sourceId, '13005');
assert.equal(plantain.sustainability.footprint.status, 'unavailable');
assert.equal(apple.sustainability.footprint.sourceId, '13039');
});
test('exact name fallback is constrained by the food group and processing state', () => {
const tomato = off({ product_name: 'Tomato, raw', categories_tags: ['en:vegetables'] });
assert.equal(tomato.sustainability.footprint.sourceId, '20047_1');
assert.equal(tomato.sustainability.footprint.matchMethod, 'normalized-name-in-category');
assert.equal(off({ product_name: 'Tomato, raw', categories_tags: ['en:beverages'] }).sustainability.footprint.status, 'unavailable');
});
test('mass units and package reliability are handled without volume or drained-weight guesses', () => {
assert.equal(off({ quantity: '2 x 250 g' }).sustainability.footprint.packageQuantityGrams, 500);
assert.equal(off({ quantity: '1.5 kg' }).sustainability.footprint.packageQuantityGrams, 1500);
assert.equal(off({ quantity: '500 ml' }).sustainability.footprint.packageKgCo2e, undefined);
assert.equal(off({ quantity: '500 g, 350 g drained' }).sustainability.footprint.packageKgCo2e, undefined);
assert.equal(off({ quantity: 'unknown' }).sustainability.footprint.packageKgCo2e, undefined);
assert.equal(productSpecificFootprint({ 'carbon-footprint_100g': 0 }, '100 g').valueKgCo2ePerKg, 0);
assert.equal(productSpecificFootprint({ 'carbon-footprint_100g': 50 }, '500 ml').status, 'unavailable');
});
test('malformed and legacy OFF fields do not manufacture environmental values', () => {
assert.equal(productSpecificFootprint({ 'carbon-footprint_100g': 'bad' }, '100 g').status, 'unavailable');
const legacy = off({ ecoscore_grade: 'c', ecoscore_data: { agribalyse: { co2_total: 99 } }, categories_tags: [] });
assert.equal(legacy.sustainability.ecoScore, 'C');
assert.equal(legacy.sustainability.footprint.status, 'unavailable');
assert.equal(mapOpenFoodFactsProduct({ code: '9', categories_tags: null, ingredients_text: {}, ingredients_analysis_tags: null }).sustainability.footprint.status, 'unavailable');
});
test('cached product matches are reused and invalidated by rule/data version', () => {
const first = off();
assert.match(first.sustainability.environmentalCacheVersion, new RegExp(ENVIRONMENTAL_RULES_VERSION + '$'));
assert.strictEqual(enrichEnvironmentalProduct(first), first);
const stale = { ...first, sustainability: { ...first.sustainability, environmentalCacheVersion: 'old', footprint: { status: 'estimated', valueKgCo2ePerKg: 999 } } };
assert.equal(enrichEnvironmentalProduct(stale).sustainability.footprint.valueKgCo2ePerKg, 0.909);
const local = { id: 'sample-1', dataSource: 'local', sustainability: { carbonFootprintKgCo2ePerKg: 2 } };
assert.strictEqual(enrichEnvironmentalProduct(local), local);
});
test('offline cached scans work and OFF/network failures fail gracefully', async () => {
const cached = off();
const result = await lookupProductByBarcode(cached.barcode, { [cached.barcode]: cached }, true);
assert.equal(result.product.sustainability.footprint.status, 'estimated');
const originalFetch = globalThis.fetch;
try {
globalThis.fetch = async () => { throw new Error('offline'); };
assert.equal((await lookupProductByBarcode('987654321')).status, 'error');
assert.deepEqual(await searchProducts('banana', {}, false), []);
globalThis.fetch = async () => ({ ok: true, json: async () => null });
assert.equal((await lookupProductByBarcode('987654321')).status, 'notFound');
} finally {
globalThis.fetch = originalFetch;
}
});
test('ADEME import failure cannot replace the last good local snapshot', async () => {
let wrote = false;
await assert.rejects(importAgribalyse({
fetchJson: async () => { throw new Error('ADEME offline'); },
write: async () => { wrote = true; }
}), /ADEME offline/);
assert.equal(wrote, false);
});
+134
View File
@@ -0,0 +1,134 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { calculateNutriScore } from '../src/services/nutriScoreService.js';
import { calculateProductRating } from '../src/services/ratingService.js';
import { lookupProductByBarcode } from '../src/services/productApi.js';
const preferences = { avoidAllergens: [], preferredDiet: 'none' };
function product(nutrition, categoryTags = []) {
return { id: 'test', name: 'Testprodukt', categoryTags, nutrition };
}
test('calculates a good food grade from per-100g nutrients', () => {
const item = product({
energyKjPer100g: 500,
saturatedFatPer100g: 0,
sugarPer100g: 0,
saltPer100g: 0,
proteinPer100g: 10,
fiberPer100g: 10,
fruitVegetableLegumePercent: 0
});
assert.equal(calculateNutriScore(item)?.grade, 'A');
assert.match(calculateProductRating(item, preferences).categoryScores.nutrition.message, /Berechneter Nutri-Score A/);
});
test('high sugar, salt and saturated fat produce E even when positive data is absent', () => {
const item = product({
energyKjPer100g: 2000,
saturatedFatPer100g: 10,
sugarPer100g: 55,
saltPer100g: 5
});
assert.equal(calculateNutriScore(item)?.grade, 'E');
});
test('uses beverage thresholds and sweetener penalty', () => {
const nutrition = {
energyKjPer100g: 0,
saturatedFatPer100g: 0,
sugarPer100g: 0,
saltPer100g: 0,
proteinPer100g: 0,
fiberPer100g: 0,
fruitVegetableLegumePercent: 0,
hasNonNutritiveSweeteners: false
};
assert.equal(calculateNutriScore(product(nutrition), true, false)?.grade, 'B');
assert.equal(calculateNutriScore(product(nutrition), true, true)?.grade, 'A');
assert.equal(calculateNutriScore(product({ ...nutrition, hasNonNutritiveSweeteners: true }), true, false)?.grade, 'C');
});
test('does not apply cheese rules to a cheese sandwich', () => {
const nutrition = {
energyKjPer100g: 2000,
saturatedFatPer100g: 5,
sugarPer100g: 10,
saltPer100g: 0.5,
proteinPer100g: 20,
fiberPer100g: 0,
fruitVegetableLegumePercent: 0
};
assert.equal(calculateNutriScore(product(nutrition, ['en:cheese-sandwiches']))?.grade, 'D');
assert.equal(calculateNutriScore(product(nutrition, ['en:cheeses']))?.grade, 'C');
});
test('fat products use energy from saturated fat and do not need a total energy field', () => {
const item = product({
saturatedFatPer100g: 5, fatPer100g: 80, sugarPer100g: 0, saltPer100g: 0,
proteinPer100g: 0, fiberPer100g: 0, fruitVegetableLegumePercent: 0
}, ['en:vegetable-oils']);
assert.equal(calculateNutriScore(item)?.grade, 'B');
});
test('does not calculate a grade for excluded products', () => {
const item = product({
energyKjPer100g: 100, saturatedFatPer100g: 0, sugarPer100g: 0,
saltPer100g: 0, proteinPer100g: 0, fiberPer100g: 0,
fruitVegetableLegumePercent: 0
}, ['en:alcoholic-beverages']);
assert.equal(calculateNutriScore(item, true), null);
});
test('missing or ambiguous nutrient values do not create a grade or skew overall rating', () => {
const item = product({ sugarPer100g: 1 });
assert.equal(calculateNutriScore(item), null);
assert.equal(calculateProductRating(item, preferences).categoryScores.nutrition.hasKnownFacts, false);
const ambiguous = product({ energyKjPer100g: 500, saturatedFatPer100g: 0, sugarPer100g: 0, saltPer100g: 0 });
assert.equal(calculateNutriScore(ambiguous), null);
});
test('keeps a supplied Nutri-Score authoritative', () => {
const item = product({ nutriScore: 'D', sugarPer100g: 0 });
const nutritionRating = calculateProductRating(item, preferences).categoryScores.nutrition;
assert.match(nutritionRating.message, /Nutri-Score D/);
assert.doesNotMatch(nutritionRating.message, /Berechneter/);
});
test('maps the Open Food Facts fields required by the fallback', async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => ({
ok: true,
json: async () => ({ status: 1, product: {
code: '12345',
categories_tags: ['en:beverages'],
additives_tags: ['en:e955'],
nutrition_grades: 'b',
environmental_score_grade: 'a',
nutriments: {
energy_100g: 100,
sugars_100g: 2,
'saturated-fat_100g': 0,
salt_100g: 0,
proteins_100g: 0,
fiber_100g: 0,
'fruits-vegetables-legumes-estimate-from-ingredients_100g': 0
}
} })
});
try {
const result = await lookupProductByBarcode('12345');
assert.equal(result.product.nutrition.energyKjPer100g, 100);
assert.equal(result.product.nutrition.fiberPer100g, 0);
assert.equal(result.product.nutrition.hasNonNutritiveSweeteners, true);
assert.equal(result.product.nutrition.nutriScore, 'B');
assert.equal(result.product.sustainability.ecoScore, 'A');
assert.equal(calculateNutriScore(result.product, true)?.grade, 'D');
} finally {
globalThis.fetch = originalFetch;
}
});
+118
View File
@@ -0,0 +1,118 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { calculateProductRating } from '../src/services/ratingService.js';
import { findAlternatives } from '../src/services/alternativesService.js';
const preferences = { avoidAllergens: [], preferredDiet: 'none' };
const rate = (product, customPreferences = {}) => calculateProductRating(
{ id: 'test', ...product }, { ...preferences, ...customPreferences }
);
test('shows unknown when no category has reliable facts', () => {
const rating = rate({});
assert.equal(rating.overallScore, null);
assert.equal(rating.overallStatus, 'unknown');
});
test('missing budget and allergen data do not contribute neutral placeholder scores', () => {
const rating = rate({ nutrition: { nutriScore: 'A' } });
assert.equal(rating.categoryScores.budget.hasKnownFacts, false);
assert.equal(rating.categoryScores.allergies.hasKnownFacts, false);
assert.equal(rating.overallScore, 77);
assert.equal(rating.limitedByMissingData, true);
});
test('profile priorities actually change the category weighting', () => {
const item = { nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'E' } };
const nutritionFirst = rate(item, { nutritionPriority: 'high', sustainabilityPriority: 'low' });
const sustainabilityFirst = rate(item, { nutritionPriority: 'low', sustainabilityPriority: 'high' });
assert.ok(nutritionFirst.overallScore > sustainabilityFirst.overallScore);
});
test('ingredient text without animal terms is not treated as vegan proof', () => {
const rating = rate({ ingredients: ['Weizenmehl'] }, { preferredDiet: 'vegan' });
assert.equal(rating.categoryScores.ingredients.hasKnownFacts, false);
assert.equal(rating.overallStatus, 'unknown');
});
test('a confirmed avoided allergen still blocks the recommendation', () => {
const rating = rate({
allergens: ['Milch'], dataCompleteness: { allergens: true }, nutrition: { nutriScore: 'A' }
}, { avoidAllergens: ['Milch'] });
assert.equal(rating.overallScore, 0);
assert.equal(rating.overallStatus, 'critical');
assert.equal(rating.limitedByMissingData, false);
});
test('Nutri-Score nutrients are not penalized twice', () => {
const plain = rate({ nutrition: { nutriScore: 'C' } });
const flagged = rate({ nutrition: { nutriScore: 'C', nutrientLevels: { sugars: 'high' } } });
assert.equal(plain.categoryScores.nutrition.score, flagged.categoryScores.nutrition.score);
});
test('missing values for personal goals do not invent a penalty', () => {
const baseline = rate({ nutrition: { nutriScore: 'A' } });
const lowSugar = rate({ nutrition: { nutriScore: 'A' } }, { preferredDiet: 'lowSugar' });
const highProtein = rate({ nutrition: { nutriScore: 'A' } }, { preferredDiet: 'highProtein' });
assert.equal(lowSugar.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score);
assert.equal(highProtein.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score);
});
test('a critical additive in ingredient text counts without additive tags', () => {
const rating = rate({ ingredients: ['Farbstoff E171'] });
assert.equal(rating.categoryScores.ingredients.hasKnownFacts, true);
assert.ok(rating.categoryScores.ingredients.score <= 24);
});
test('flavoured water with sugar is not treated as plain water', () => {
const rating = rate({
name: 'Flavoured water',
categoryTags: ['en:waters', 'en:flavored-waters'],
nutrition: {
energyKjPer100g: 80,
sugarPer100g: 5,
saturatedFatPer100g: 0,
saltPer100g: 0,
proteinPer100g: 0,
fiberPer100g: 0,
fruitVegetableLegumePercent: 0,
hasNonNutritiveSweeteners: false
}
});
assert.notEqual(rating.categoryScores.nutrition.score, 98);
});
test('country names containing eu are not mistaken for the EU', () => {
const peru = rate({ sustainability: { originCountry: 'Peru' } });
const swiss = rate({ sustainability: { originCountry: 'Schweiz' } });
assert.equal(peru.categoryScores.sustainability.score, 35);
assert.equal(swiss.categoryScores.sustainability.score, 92);
});
test('Eco-Score is not counted again through its environmental indicators', () => {
const rating = rate({ sustainability: {
ecoScore: 'E', carbonFootprintKgCo2ePerKg: 0.1,
originCountry: 'Schweiz', packaging: 'Glas'
} });
assert.equal(rating.categoryScores.sustainability.score, 15);
});
test('alternatives exclude products whose allergens need review', async () => {
const source = {
id: 'source', barcode: '1', name: 'Original', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: ['Milch'], dataCompleteness: { allergens: true }
};
const unknown = {
id: 'unknown', barcode: '2', name: 'Unklar', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: [], dataCompleteness: { allergens: false }, nutrition: { nutriScore: 'A' }
};
const verified = {
id: 'verified', barcode: '3', name: 'Bestätigt', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: ['Soja'], dataCompleteness: { allergens: true }, nutrition: { nutriScore: 'A' }
};
const alternatives = await findAlternatives(source, {
...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true
}, { unknown, verified });
assert.deepEqual(alternatives.map((item) => item.product.id), ['verified']);
});