diff --git a/App.js b/App.js
index 6e9ec17..94e8cbc 100644
--- a/App.js
+++ b/App.js
@@ -156,6 +156,7 @@ export default function App() {
onToggleItem={toggleListItem}
onChangeItemQuantity={changeListItemQuantity}
lastDeletedItem={lastDeletedListItem}
+ preferences={preferences}
shoppingList={shoppingList}
/>
);
@@ -273,7 +274,12 @@ export default function App() {
setShoppingList((current) => ({
...current,
items: current.items.map((item) => item.barcode === updated.barcode
- ? { ...item, productName: updated.name, nutrition: updated.nutrition } : item)
+ ? {
+ ...item,
+ productName: updated.name,
+ nutrition: updated.nutrition,
+ productFacts: listProductFacts(updated)
+ } : item)
}));
setRoute({ name: 'productDetail', product: updated });
}
@@ -315,7 +321,8 @@ export default function App() {
packageQuantityGrams: item.packageQuantityGrams ?? product.packageQuantityGrams,
packageQuantityLabel: item.packageQuantityLabel ?? product.packageQuantityLabel,
servingQuantityGrams: item.servingQuantityGrams ?? product.servingQuantityGrams,
- nutrition: item.nutrition ?? product.nutrition
+ nutrition: { ...(item.nutrition || {}), ...(product.nutrition || {}) },
+ productFacts: listProductFacts(product)
}
: item
)
@@ -331,6 +338,7 @@ export default function App() {
packageQuantityLabel: product.packageQuantityLabel,
servingQuantityGrams: product.servingQuantityGrams,
nutrition: product.nutrition,
+ productFacts: listProductFacts(product),
checked: false,
addedAt: new Date().toISOString()
}
@@ -544,6 +552,21 @@ function stripLegacyPriceFields(value) {
return rest;
}
+function listProductFacts(product) {
+ return {
+ brand: product.brand,
+ category: product.category,
+ categoryTags: product.categoryTags,
+ ingredients: product.ingredients,
+ ingredientAnalysis: product.ingredientAnalysis,
+ allergens: product.allergens,
+ allergenTraces: product.allergenTraces,
+ dataCompleteness: product.dataCompleteness,
+ cacheStale: product.cacheStale,
+ dataSource: product.dataSource
+ };
+}
+
const styles = StyleSheet.create({
container: {
backgroundColor: colors.background,
diff --git a/README.md b/README.md
index 9a1ab79..f94eb82 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@ Shoppinguin helps adults understand supermarket products in the context of their
On first launch, users enter age, height, weight, and an exercise goal. The profile stays in local app storage. The profile screen lets them edit these values, set a personal **total sugar** planning value, manage allergens and dietary preferences, and enable offline mode.
-Product ratings now use nutrition (45%), goal fit (20%), ingredients (15%), and allergies (20% when applicable). Only categories with known facts contribute to the numeric score. Missing information limits confidence. Confirmed avoided allergens still block a recommendation. Additives remain an ingredients signal; environmental impact is still displayed in product details but no longer affects the score. The shopping list remains available for planning and checking off products; price entry, totals and budget controls are no longer part of the app.
+Product ratings now use nutrition (45%), goal fit (20%), ingredients (15%), and allergies (20% when applicable). Only categories with known facts contribute to the numeric score. Missing information limits confidence. Confirmed avoided allergens still block a recommendation. Additives remain an ingredients signal; environmental impact is still displayed in product details but no longer affects the score. The shopping list remains available for planning and checking off products; price entry, totals and budget controls are no longer part of the app. Its nutrition summary uses only products with both a known per-100 g value and a known package mass, reports coverage and missing fields, and ranks the largest known contributors. Basket totals are explicitly not presented as a prediction of daily consumption. Sugar uses the user's planning value, while allergen and vegan or vegetarian cautions reuse the product-rating rules.
The product screen shows protein and total sugar per serving. Users can mark a portion as eaten and choose the stated serving, half or all of the package, 100 g, or a custom amount. The portion can be recorded for today or backdated to an earlier calendar day. The local daily log then updates the Home screen and subsequent recommendations. Entries can be edited or deleted, and earlier dates remain available in the expandable history. A seven-day view supports week-by-week navigation, shows nutrient-specific data coverage, and derives patterns only from logged days with complete data for the relevant nutrient. A scan or a shopping-list addition **does not** count as consumption. When the portion selector opens, it defaults to the stated serving size, then package size, then 100 g when no amount is available. The last fallback is approximate. Daily totals and insights cover only portions logged in the app. A product with missing nutrition values cannot fill those gaps and is never treated as zero.
@@ -14,9 +14,11 @@ The daily view also tracks salt and fibre for all goals. The product goal detail
The profile groups daily values in a separate **Tageswerte** section. Protein is calculated from body weight and exercise goal: approximately 0.83 g/kg for general goals, 1.2 g/kg for endurance, and 1.6 g/kg for muscle growth. These are broad adult reference values, not a prescription. The default 50 g total sugar value is an editable planning value, **not** a clinical limit or a WHO free-sugars target; product data generally reports total sugars, including naturally occurring sugars. Setting it above 50 g shows a short warning explaining that WHO's less-than-50-g example applies to **free sugars** at 2,000 kcal and cannot be directly compared with the app's total-sugar data. Age and height do not change these two calculations. A reliable personal calorie estimate would require more information, so the app does not infer one from the available profile. Do not use the score to manage a medical condition.
+The product detail leads with the recommendation, confidence and strongest influences, followed by a compact serving summary and clearly separated shopping-list and consumption actions. Rating details, data quality, alternatives, environmental context and raw product facts use expandable sections so critical information remains visible without forcing every supporting detail into the initial view.
+
Other useful features remain: manual product corrections, local product cache, offline scans of saved products, alternatives, shopping list, and environmental context.
-The product detail automatically previews up to two better alternatives of the same specific product type. Suggestions do not cross broad groups such as soda to water. A lower-sugar soda can qualify even if its Nutri-Score grade is unchanged, provided its overall rating is not materially worse. The search checks related category tags and additional result pages before giving up, then tries product-type or category search terms when needed. The full alternatives view remains available. In online mode the preview sends category tags and, when needed, product-type, category, or name search terms to Open Food Facts; offline it uses only saved products.
+When the alternatives section is opened, the product detail previews up to two better alternatives of the same specific product type. No alternatives request is made merely by opening the product. Suggestions do not cross broad groups such as soda to water. A lower-sugar soda can qualify even if its Nutri-Score grade is unchanged, provided its overall rating is not materially worse. The search checks related category tags and additional result pages before giving up, then tries product-type or category search terms when needed. The full alternatives view remains available. In online mode the preview sends category tags and, when needed, product-type, category, or name search terms to Open Food Facts; offline it uses only saved products.
## Run
diff --git a/src/screens/ProductDetailScreen.js b/src/screens/ProductDetailScreen.js
index 523631c..f51a7d1 100644
--- a/src/screens/ProductDetailScreen.js
+++ b/src/screens/ProductDetailScreen.js
@@ -5,14 +5,18 @@ import PrimaryButton from '../components/PrimaryButton';
import SecondaryButton from '../components/SecondaryButton';
import PortionSelector from '../components/consumption/PortionSelector';
import AppHeader from '../components/layout/AppHeader';
+import DisclosureSection from '../components/layout/DisclosureSection';
import ScreenContainer from '../components/layout/ScreenContainer';
-import SectionTitle from '../components/layout/SectionTitle';
import ProductImage from '../components/product/ProductImage';
import ProductScoreBadge from '../components/product/ProductScoreBadge';
import RatingCategoryRow from '../components/product/RatingCategoryRow';
-import { calculateProductRating } from '../services/ratingService';
import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService';
import { todayKey } from '../services/dailyNutritionService';
+import {
+ buildProductDetailPresentation,
+ shouldLoadAlternativePreview
+} from '../services/productDetailPresentation';
+import { calculateProductRating } from '../services/ratingService';
import { colors } from '../utils/constants';
export default function ProductDetailScreen({
@@ -33,26 +37,50 @@ export default function ProductDetailScreen({
const [savedMessage, setSavedMessage] = useState('');
const [consumptionMessage, setConsumptionMessage] = useState('');
const [isChoosingPortion, setIsChoosingPortion] = useState(false);
+ const [alternativesExpanded, setAlternativesExpanded] = useState(false);
+ const [alternativesRequested, setAlternativesRequested] = useState(false);
+ const [alternativesStatus, setAlternativesStatus] = useState('idle');
+ const [alternativesLoadedKey, setAlternativesLoadedKey] = useState('');
const [suggestions, setSuggestions] = useState([]);
- const [suggestionsLoading, setSuggestionsLoading] = useState(true);
- const [suggestionsError, setSuggestionsError] = useState(false);
- const rating = useMemo(() => calculateProductRating(product, preferences, { shoppingList, dailyLog }), [product, preferences, shoppingList, dailyLog]);
+ const rating = useMemo(
+ () => calculateProductRating(product, preferences, { shoppingList, dailyLog }),
+ [product, preferences, shoppingList, dailyLog]
+ );
+ const presentation = useMemo(
+ () => buildProductDetailPresentation(product, rating, preferences),
+ [product, rating, preferences]
+ );
const footprint = product.sustainability?.footprint;
- const missingFields = missingProductFields(product, preferences);
- const recommendation = rating.overallStatus === 'good' ? 'Passt gut zu dir'
- : rating.overallStatus === 'critical' ? 'Lieber meiden'
- : rating.overallStatus === 'unknown' ? 'Zu wenig Daten' : 'Genauer prüfen';
+ const alternativeContextKey = useMemo(() => JSON.stringify({
+ productId: product.id,
+ preferences,
+ dailyLog,
+ cachedProducts: Object.keys(productCache || {}).sort()
+ }), [product.id, preferences, dailyLog, productCache]);
useEffect(() => {
+ if (!shouldLoadAlternativePreview(
+ alternativesRequested,
+ alternativesLoadedKey === alternativeContextKey ? 'loaded' : 'idle'
+ )) return undefined;
+
let active = true;
- setSuggestionsLoading(true);
- setSuggestionsError(false);
+ setAlternativesStatus('loading');
findAlternatives(product, preferences, productCache, { dailyLog }, { preview: true })
- .then((results) => { if (active) setSuggestions(results); })
- .catch(() => { if (active) { setSuggestions([]); setSuggestionsError(true); } })
- .finally(() => { if (active) setSuggestionsLoading(false); });
+ .then((results) => {
+ if (!active) return;
+ setSuggestions(results);
+ setAlternativesStatus('loaded');
+ setAlternativesLoadedKey(alternativeContextKey);
+ })
+ .catch(() => {
+ if (!active) return;
+ setSuggestions([]);
+ setAlternativesStatus('error');
+ setAlternativesLoadedKey(alternativeContextKey);
+ });
return () => { active = false; };
- }, [product, preferences, productCache, dailyLog]);
+ }, [alternativeContextKey, alternativesLoadedKey, alternativesRequested, dailyLog, preferences, product, productCache]);
function addToList() {
if (rating.hasBlockedAllergen) {
@@ -81,6 +109,16 @@ export default function ProductDetailScreen({
setSavedMessage('Zur Einkaufsliste hinzugefügt.');
}
+ function toggleAlternatives(expanded) {
+ setAlternativesExpanded(expanded);
+ if (expanded) setAlternativesRequested(true);
+ }
+
+ function retryAlternatives() {
+ setAlternativesStatus('idle');
+ setAlternativesLoadedKey('');
+ }
+
return (
@@ -91,29 +129,45 @@ export default function ProductDetailScreen({
{product.brand || 'Ohne Marke'}
{product.name}
-
- {product.category || 'Produkt'}
-
+ {product.category || 'Produkt'}
{sourceLabel(product.dataSource)}{product.cacheStale ? ' · Veraltete Daten' : ''}
- {product.manualOverrides ? Angaben von dir ergänzt · lokal gespeichert : null}
- {product.manualOverrides ? Etikettangaben: {manualFieldNames(product.manualOverrides).join(', ') || 'Produkttyp'} : null}
- {['cache', 'open-food-facts'].includes(product.dataSource) ? Produktdaten geprüft: {formatCheckedDate(product.fetchedAt)} : null}
+
- {recommendation}
-
- {recommendationMessage(rating)}
+
+ {presentation.recommendation}
- Bewertbare Daten: {rating.dataCoverage}% der für dein Profil anwendbaren Kriterien (gewichtet).
+ {presentation.recommendationMessage}
+
+
+
+
+ {presentation.confidence.label}
+ {presentation.confidence.coverage}%
+
+
+
+
+ {presentation.confidence.message}
- {rating.mainFactors.length > 0 || rating.scoreLimitReasons.length > 0 ? (
-
- Das beeinflusst die Bewertung
- {rating.mainFactors.map((factor) => (
+ {presentation.criticalNotices.map((notice) => (
+
+ {notice.label}
+ {notice.message}
+
+ ))}
+
+ {presentation.topFactors.length > 0 ? (
+
+ DIE STÄRKSTEN EINFLÜSSE
+ {presentation.topFactors.map((factor) => (
{factor.label}
@@ -122,107 +176,177 @@ export default function ProductDetailScreen({
{factor.message}
))}
- {rating.scoreLimitReasons.length > 0 ?
- Bitte beachten
- {rating.scoreLimitReasons.map((reason) => • {reason})}
- : null}
) : null}
-
- Produktangaben ergänzen
- {missingFields.length
- ? `Für eine genauere Bewertung fehlen: ${missingFields.join(', ')}.`
+
+
+
+ {presentation.serving.approximate ? 'Nährwerte zur Einordnung' : 'Pro Portion'}
+
+ {presentation.serving.amountLabel} · {presentation.serving.basisLabel}
+
+
+ {presentation.serving.approximate ? Näherung : null}
+
+
+ {presentation.serving.rows.map((row) => (
+
+ {row.label}
+
+ {row.value === null ? 'Keine Angabe' : `${formatNutrient(row.value)} ${row.unit}`}
+
+
+ ))}
+
+ {presentation.serving.approximate ? (
+ Keine verlässliche Portionsgrösse vorhanden. Die angezeigte Grundlage ist klar gekennzeichnet.
+ ) : null}
+
+
+
+
+ Für deinen Einkauf
+ Produkt auf die aktuelle Einkaufsliste setzen.
+
+ {savedMessage ? (
+
+ {savedMessage}
+ {!rating.hasBlockedAllergen ? (
+
+ Einkaufsliste ansehen ›
+
+ ) : null}
+
+ ) : null}
+
+
+
+
+
+ Tagesprotokoll
+ Nur verwenden, wenn du eine Portion tatsächlich gegessen hast.
+ {consumptionMessage ? (
+ {consumptionMessage}
+ ) : null}
+ {isChoosingPortion ? (
+ setIsChoosingPortion(false)}
+ onConfirm={(grams, date) => {
+ onRecordConsumption(product, grams, date);
+ setConsumptionMessage(date === todayKey()
+ ? `${formatAmount(grams)} g heute im Tagesprotokoll erfasst.`
+ : `${formatAmount(grams)} g für ${formatEntryDate(date)} nachgetragen.`);
+ setIsChoosingPortion(false);
+ }}
+ product={product}
+ />
+ ) : (
+ {
+ setConsumptionMessage('');
+ setIsChoosingPortion(true);
+ }} />
+ )}
+
+
+
+
+ {rating.scoreLimitReasons.length > 0 ? (
+
+ Was die Empfehlung begrenzt
+ {rating.scoreLimitReasons.map((reason) => • {reason})}
+
+ ) : null}
+ {Object.entries(rating.categoryScores).map(([category, categoryRating]) => (
+ onShowRatingCriteria(product, category)}
+ rating={categoryRating}
+ />
+ ))}
+
+
+
+ {presentation.missingFields.length
+ ? `Für eine genauere Bewertung fehlen: ${presentation.missingFields.join(', ')}.`
: 'Die wichtigsten Angaben für die Bewertung sind vorhanden.'}
Fehlende Werte werden nicht geschätzt.
+ {product.manualOverrides ? Von dir ergänzt: {manualFieldNames(product.manualOverrides).join(', ') || 'Produkttyp'}. : null}
+ {['cache', 'open-food-facts'].includes(product.dataSource) ? Produktdaten geprüft: {formatCheckedDate(product.fetchedAt)} : null}
onEditProduct(product)} />
{/^\d{8,14}$/.test(product.barcode || '') ? (
Linking.openURL(`https://ch.openfoodfacts.org/product/${product.barcode}`)}>
Produkt auf Open Food Facts öffnen ›
) : null}
-
+
- {savedMessage ? (
-
- {savedMessage}
-
- Einkaufsliste ansehen ›
-
-
- ) : null}
-
- {consumptionMessage ? (
-
- {consumptionMessage}
-
- ) : null}
- {isChoosingPortion ? (
- setIsChoosingPortion(false)}
- onConfirm={(grams, date) => {
- onRecordConsumption(product, grams, date);
- setConsumptionMessage(date === todayKey()
- ? `${formatAmount(grams)} g heute im Tagesprotokoll erfasst.`
- : `${formatAmount(grams)} g für ${formatEntryDate(date)} nachgetragen.`);
- setIsChoosingPortion(false);
- }}
- product={product}
- />
- ) : (
- {
- setConsumptionMessage('');
- setIsChoosingPortion(true);
- }} />
- )}
-
- Ähnliche, bessere Alternativen
- {suggestionsLoading ? Passende Produkte werden gesucht ... : null}
- {!suggestionsLoading && suggestions.length === 0 ?
- {suggestionsError ? 'Alternativen konnten gerade nicht geladen werden.'
- : alternativeSearchIssue(product, rating) || 'Unter den geprüften Treffern war keine belegbar bessere Alternative derselben Produktart.'}
- : null}
- {suggestions.map((item) => onOpenProduct(item.product)} style={styles.suggestionCard}>
-
-
-
-
- {item.product.name}
-
+
+ {alternativesStatus === 'idle' || alternativesStatus === 'loading' ? (
+ Passende Produkte werden gesucht ...
+ ) : null}
+ {alternativesStatus === 'error' ? (
+ <>
+ Alternativen konnten gerade nicht geladen werden.
+
+ >
+ ) : null}
+ {alternativesStatus === 'loaded' && suggestions.length === 0 ? (
+
+ {alternativeSearchIssue(product, rating) || 'Unter den geprüften Treffern war keine belegbar bessere Alternative derselben Produktart.'}
+
+ ) : null}
+ {suggestions.map((item) => (
+ onOpenProduct(item.product)}
+ style={styles.suggestionCard}
+ >
+
+
+
+
+ {item.product.name}
+
+
+ {item.reason}
+ Produkt ansehen ›
+
- {item.reason}
- Produkt ansehen ›
-
-
- )}
- onShowAlternatives(product)} />
+
+ ))}
+ onShowAlternatives(product)} />
+
- Bewertungskriterien
- {Object.entries(rating.categoryScores).map(([category, categoryRating]) => (
- onShowRatingCriteria(product, category)}
- rating={categoryRating}
- />
- ))}
-
- Umweltwirkung
-
+
{footprint?.status === 'product-specific' || footprint?.status === 'estimated' ? (
<>
-
- CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg
-
+ CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg
{footprint.status === 'product-specific' ? 'Produktspezifische Angabe aus Open Food Facts.'
: `Schätzung anhand vergleichbarer Lebensmittel: ${footprint.referenceCategory}. AGRIBALYSE-Durchschnitt, keine Messung dieses Markenprodukts.`}
{typeof footprint.packageKgCo2e === 'number' ? (
-
- Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e
-
+ Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e
) : null}
Quelle: {footprint.source === 'AGRIBALYSE' ? 'ADEME / ' : ''}{footprint.source}{footprint.datasetVersion ? ` ${footprint.datasetVersion}` : ''}
@@ -236,7 +360,7 @@ export default function ProductDetailScreen({
Landnutzung: {formatIndicator(footprint.indicators?.landUse)}
Wasserknappheit: {formatIndicator(footprint.indicators?.waterScarcity)}
Gesamtwirkung (EF): {formatIndicator(footprint.indicators?.singleScore)}
- Lebenszyklus bis zum verzehrbaren Lebensmittel; Transport und Verpackung sind im Datensatz enthalten. Diese Indikatoren sind keine CO₂-Werte.
+ Lebenszyklus bis zum verzehrbaren Lebensmittel; Transport und Verpackung sind enthalten. Diese Indikatoren sind keine CO₂-Werte.
>
) : null}
>
@@ -246,10 +370,12 @@ export default function ProductDetailScreen({
{(product.sustainability?.sellingCountries || []).length > 0 ? (
Verkaufsländer: {product.sustainability.sellingCountries.map(formatCountryTag).join(', ')}
) : null}
-
+
- Produktdaten
-
+
Barcode: {product.barcode}
Zutaten: {(product.ingredients || []).join(', ') || 'Keine Angaben'}
Angegebene Allergene: {(product.allergens || []).join(', ') || 'Keine Angaben'}
@@ -258,48 +384,11 @@ export default function ProductDetailScreen({
Nutri-Score: {rating.categoryScores.nutrition.nutriScore || 'Keine Angabe'}
{rating.categoryScores.nutrition.nutriScoreSource === 'calculated' ? ' (von der App berechnet)' : rating.categoryScores.nutrition.nutriScore ? ' (Open Food Facts)' : ''}
-
-
+
);
}
-function recommendationMessage(rating) {
- if (rating.hasBlockedAllergen) return rating.categoryScores.allergies.message;
- if (rating.allergenReviewRequired) return rating.allergenReviewMessage;
- if (rating.goalConflict) return rating.categoryScores.ingredients.message;
- if (rating.goalReviewRequired) return 'Für dein Ernährungsziel fehlen Angaben. Prüfe die Zutaten oder Nährwerte auf der Verpackung.';
- if (rating.staleDataReviewRequired) return 'Gespeicherte Produktdaten sind veraltet. Prüfe vor dem Kauf die Verpackung.';
- if (rating.overallStatus === 'unknown') return 'Für eine Empfehlung fehlen belastbare Produktangaben.';
- if (rating.limitedByMissingData) return 'Nur ein Teil der Kriterien ist belegt. Die Empfehlung ist deshalb auf „Prüfen“ begrenzt.';
- return 'Tippe unten auf ein Kriterium, um die Bewertung nachzuvollziehen.';
-}
-
-function missingProductFields(product, preferences) {
- const nutrition = product.nutrition || {};
- const fields = [];
- const beverage = product.categoryTags?.includes('en:beverages') || product.dataSource === 'local';
- if (product.dataCompleteness?.name === false) fields.push('Produktname');
- if (!product.categoryTags?.length) fields.push('Produkttyp');
- if (!product.dataCompleteness?.ingredients) fields.push('Zutatenliste');
- if (preferences.avoidAllergens?.length && !product.dataCompleteness?.allergens) fields.push('Allergenangaben');
- if (!Number.isFinite(nutrition.sugarPer100g)) fields.push(`Zucker pro ${beverage ? '100 ml' : '100 g'}`);
- if (!Number.isFinite(nutrition.proteinPer100g)) fields.push('Protein');
- if (!Number.isFinite(nutrition.saltPer100g)) fields.push('Salz');
- if (!Number.isFinite(nutrition.fiberPer100g)) fields.push('Ballaststoffe');
- if (preferences.exerciseGoal === 'endurance' && !Number.isFinite(nutrition.carbohydratesPer100g)) {
- fields.push(product.cacheStale ? 'Kohlenhydrate im lokalen Cache (online erneut scannen)' : 'Kohlenhydrate');
- }
- if (preferences.preferredDiet === 'vegan' && !Number.isFinite(nutrition.vitaminB12MicrogramsPer100g)) fields.push('Vitamin B12');
- if (beverage && !nutrition.nutriScore) {
- if (!Number.isFinite(nutrition.energyKjPer100g) && !Number.isFinite(nutrition.caloriesPer100g)) fields.push('Energie');
- if (!Number.isFinite(nutrition.saturatedFatPer100g)) fields.push('gesättigte Fettsäuren');
- if (!Number.isFinite(nutrition.saltPer100g)) fields.push('Salz');
- if (typeof nutrition.hasNonNutritiveSweeteners !== 'boolean') fields.push('Süssstoffe');
- }
- return fields.slice(0, 8);
-}
-
function manualFieldNames(overrides) {
const names = { name: 'Name', brand: 'Marke', ingredients: 'Zutaten',
allergens: 'Allergene', allergenTraces: 'Spuren', drinkType: 'Produkttyp' };
@@ -315,13 +404,8 @@ function manualFieldNames(overrides) {
}
function sourceLabel(source) {
- const labels = {
- cache: 'Quelle: lokaler Cache',
- local: 'Quelle: lokal erfasst',
- 'open-food-facts': 'Quelle: Open Food Facts'
- };
-
- return labels[source] || 'Quelle: unbekannt';
+ return { cache: 'Quelle: lokaler Cache', local: 'Quelle: lokal erfasst', 'open-food-facts': 'Quelle: Open Food Facts' }[source]
+ || 'Quelle: unbekannt';
}
function formatCheckedDate(value) {
@@ -348,6 +432,10 @@ function formatAmount(value) {
return new Intl.NumberFormat('de-CH', { maximumFractionDigits: 1 }).format(value);
}
+function formatNutrient(value) {
+ return new Intl.NumberFormat('de-CH', { maximumFractionDigits: value < 10 ? 1 : 0 }).format(value);
+}
+
function formatEntryDate(dateKey) {
const date = new Date(`${dateKey}T12:00:00`);
return Number.isNaN(date.getTime()) ? dateKey : date.toLocaleDateString('de-CH');
@@ -368,112 +456,70 @@ function matchLabel(method) {
}
const styles = StyleSheet.create({
- suggestionCard: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 16, borderWidth: 1, gap: 8, padding: 16 },
- suggestionRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 },
- suggestionBody: { flex: 1, gap: 8 },
- suggestionName: { color: colors.text, flex: 1, fontSize: 16, fontWeight: '800' },
- suggestionLink: { color: colors.primary, fontSize: 13, fontWeight: '800' },
- factorTitle: { color: colors.text, fontSize: 16, fontWeight: '800' },
- factorRow: { borderTopColor: colors.border, borderTopWidth: 1, gap: 4, paddingTop: 10 },
- factorHeader: { alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between' },
- factorLabel: { color: colors.text, fontSize: 14, fontWeight: '800' },
- factorScore: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' },
- limitPanel: { backgroundColor: '#fff7e8', borderRadius: 12, gap: 5, padding: 12 },
- limitTitle: { color: colors.warning, fontSize: 13, fontWeight: '800' },
- productPanel: {
- backgroundColor: colors.surface,
- borderColor: colors.border,
- borderRadius: 20,
- borderWidth: 1,
- gap: 14,
- padding: 18
- },
- topRow: {
- alignItems: 'flex-start',
- flexDirection: 'row',
- gap: 12
- },
- copy: {
- flex: 1
- },
- brand: {
- color: colors.primary,
- fontSize: 13,
- fontWeight: '800',
- textTransform: 'uppercase'
- },
- name: {
- color: colors.text,
- fontSize: 25,
- fontWeight: '800',
- lineHeight: 31,
- marginTop: 4
- },
- meta: {
- color: colors.muted,
- fontSize: 15,
- marginTop: 6
- },
- source: {
- alignSelf: 'flex-start',
- backgroundColor: '#eef3ef',
- borderRadius: 8,
- color: colors.primaryDark,
- fontSize: 12,
- fontWeight: '800',
- marginTop: 10,
- paddingHorizontal: 8,
- paddingVertical: 4
- },
- recommendation: {
- borderRadius: 14,
- gap: 4,
- padding: 14
- },
+ productPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 20, borderWidth: 1, gap: 14, padding: 18 },
+ topRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 },
+ copy: { flex: 1 },
+ brand: { color: colors.primary, fontSize: 13, fontWeight: '800', textTransform: 'uppercase' },
+ name: { color: colors.text, fontSize: 25, fontWeight: '800', lineHeight: 31, marginTop: 4 },
+ meta: { color: colors.muted, fontSize: 15, marginTop: 6 },
+ source: { alignSelf: 'flex-start', backgroundColor: '#eef3ef', borderRadius: 8, color: colors.primaryDark, fontSize: 12, fontWeight: '800', marginTop: 10, paddingHorizontal: 8, paddingVertical: 4 },
+ recommendation: { borderRadius: 14, gap: 4, padding: 14 },
goodRecommendation: { backgroundColor: '#e4f4e9' },
mediumRecommendation: { backgroundColor: '#fff3d7' },
criticalRecommendation: { backgroundColor: '#fee9e7' },
unknownRecommendation: { backgroundColor: '#edf1ee' },
- recommendationTitle: {
- fontSize: 17,
- fontWeight: '800'
- },
- goodText: { color: colors.success },
- mediumText: { color: '#8a5914' },
- criticalText: { color: colors.danger },
- unknownText: { color: colors.muted },
- recommendationCopy: {
- color: colors.text,
- fontSize: 13,
- lineHeight: 19
- },
- dataPanel: {
- backgroundColor: colors.surface,
- borderColor: colors.border,
- borderRadius: 18,
- borderWidth: 1,
- gap: 8,
- padding: 14
- },
- dataText: {
- color: colors.muted,
- fontSize: 14,
- lineHeight: 20
- },
- saved: {
- color: colors.success,
- fontSize: 14,
- fontWeight: '800'
- },
- savedPanel: {
- backgroundColor: colors.surfaceTint,
- borderRadius: 14,
- gap: 6,
- padding: 14
- },
- savedLink: {
- color: colors.primary,
- fontSize: 14,
- fontWeight: '800'
- }
+ recommendationTitle: { fontSize: 18, fontWeight: '800' },
+ recommendationCopy: { color: colors.text, fontSize: 13, lineHeight: 19 },
+ goodText: { color: colors.success, fontWeight: '800' },
+ mediumText: { color: '#8a5914', fontWeight: '800' },
+ criticalText: { color: colors.danger, fontWeight: '800' },
+ unknownText: { color: colors.muted, fontWeight: '800' },
+ confidencePanel: { borderRadius: 14, gap: 7, padding: 13 },
+ highConfidence: { backgroundColor: '#f0f8f3' },
+ reviewConfidence: { backgroundColor: '#fff8e8' },
+ lowConfidence: { backgroundColor: '#f2f4f3' },
+ confidenceHeader: { flexDirection: 'row', justifyContent: 'space-between' },
+ confidenceTitle: { color: colors.text, fontSize: 13, fontWeight: '800' },
+ confidenceValue: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' },
+ confidenceTrack: { backgroundColor: '#dfe7e2', borderRadius: 999, height: 7, overflow: 'hidden' },
+ confidenceFill: { backgroundColor: colors.primary, borderRadius: 999, height: '100%' },
+ confidenceCopy: { color: colors.muted, fontSize: 12, lineHeight: 17 },
+ notice: { borderRadius: 16, borderWidth: 1, gap: 5, padding: 15 },
+ criticalNotice: { backgroundColor: '#fff1f0', borderColor: colors.danger },
+ reviewNotice: { backgroundColor: '#fff9eb', borderColor: colors.warning },
+ noticeCopy: { color: colors.text, fontSize: 13, lineHeight: 19 },
+ decisionPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 12, padding: 16 },
+ panelEyebrow: { color: colors.primary, fontSize: 11, fontWeight: '800', letterSpacing: 1 },
+ panelTitle: { color: colors.text, fontSize: 18, fontWeight: '800' },
+ factorRow: { borderTopColor: colors.border, borderTopWidth: 1, gap: 4, paddingTop: 10 },
+ factorHeader: { alignItems: 'center', flexDirection: 'row', gap: 10, justifyContent: 'space-between' },
+ factorLabel: { color: colors.text, fontSize: 14, fontWeight: '800' },
+ factorScore: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' },
+ servingPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 13, padding: 16 },
+ servingHeader: { alignItems: 'flex-start', flexDirection: 'row', gap: 10 },
+ servingBasis: { color: colors.muted, fontSize: 12, marginTop: 4 },
+ approximateBadge: { backgroundColor: '#fff3d7', borderRadius: 999, color: '#8a5914', fontSize: 11, fontWeight: '800', paddingHorizontal: 9, paddingVertical: 5 },
+ nutrientGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 9 },
+ nutrientTile: { backgroundColor: colors.surfaceTint, borderRadius: 12, flexBasis: '47%', flexGrow: 1, gap: 3, minWidth: 130, padding: 11 },
+ nutrientLabel: { color: colors.muted, fontSize: 11, fontWeight: '700' },
+ nutrientValue: { color: colors.text, fontSize: 15, fontWeight: '800' },
+ missingValue: { color: colors.warning, fontSize: 12 },
+ servingNote: { color: colors.warning, fontSize: 12, lineHeight: 17 },
+ actionsPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 16, padding: 16 },
+ actionBlock: { gap: 10 },
+ actionTitle: { color: colors.text, fontSize: 16, fontWeight: '800' },
+ actionCopy: { color: colors.muted, fontSize: 13, lineHeight: 18 },
+ actionDivider: { backgroundColor: colors.border, height: 1 },
+ savedPanel: { backgroundColor: colors.surfaceTint, borderRadius: 14, gap: 6, padding: 12 },
+ saved: { color: colors.success, fontSize: 13, fontWeight: '800' },
+ savedError: { color: colors.danger, fontSize: 13, fontWeight: '800' },
+ savedLink: { color: colors.primary, fontSize: 14, fontWeight: '800' },
+ limitPanel: { backgroundColor: '#fff7e8', borderRadius: 12, gap: 5, padding: 12 },
+ limitTitle: { color: colors.warning, fontSize: 13, fontWeight: '800' },
+ dataText: { color: colors.muted, fontSize: 14, lineHeight: 20 },
+ suggestionCard: { backgroundColor: colors.background, borderColor: colors.border, borderRadius: 16, borderWidth: 1, gap: 8, padding: 14 },
+ suggestionRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 },
+ suggestionBody: { flex: 1, gap: 8 },
+ suggestionName: { color: colors.text, flex: 1, fontSize: 15, fontWeight: '800' },
+ suggestionLink: { color: colors.primary, fontSize: 13, fontWeight: '800' }
});
diff --git a/src/screens/ShoppingListScreen.js b/src/screens/ShoppingListScreen.js
index 32a6a4a..073eaed 100644
--- a/src/screens/ShoppingListScreen.js
+++ b/src/screens/ShoppingListScreen.js
@@ -6,11 +6,15 @@ import SecondaryButton from '../components/SecondaryButton';
import AppHeader from '../components/layout/AppHeader';
import ScreenContainer from '../components/layout/ScreenContainer';
import ShoppingListItem from '../components/list/ShoppingListItem';
-import { calculateShoppingListWarnings } from '../services/shoppingListWarningsService';
+import {
+ calculateShoppingListNutritionSummary,
+ calculateShoppingListProductCautions
+} from '../services/shoppingListWarningsService';
import { colors } from '../utils/constants';
export default function ShoppingListScreen({
shoppingList,
+ preferences,
lastDeletedItem,
onToggleItem,
onChangeItemQuantity,
@@ -24,7 +28,8 @@ export default function ShoppingListScreen({
const openItems = shoppingList.items.filter((item) => !item.checked).length;
const completedItems = shoppingList.items.length - openItems;
const progress = shoppingList.items.length ? completedItems / shoppingList.items.length : 0;
- const dailyWarnings = calculateShoppingListWarnings(shoppingList);
+ const nutritionSummary = calculateShoppingListNutritionSummary(shoppingList, preferences);
+ const productCautions = calculateShoppingListProductCautions(shoppingList, preferences);
return (
@@ -64,23 +69,77 @@ export default function ShoppingListScreen({
) : null}
- {dailyWarnings.length > 0 ? (
-
- {dailyWarnings.map((warning) => (
-
+ {shoppingList.items.length > 0 ? (
+
+ Einordnung der Listenmengen
+
+ Die Summen verwenden nur bekannte Nährwerte und ganze Packungsmengen. Sie beschreiben den Einkaufskorb, nicht was du an einem Tag essen wirst.
+
+ {nutritionSummary.map((summary) => (
+
+
+ {summary.label}
+
+ {summary.coverage.coveredItems > 0 ? formatAmount(summary.knownTotal, summary.unit) : 'Keine belastbare Summe'}
+
+
+ {Number.isFinite(summary.limit) ? (
+
+ Vergleich: {formatAmount(summary.limit, summary.unit)} ({summary.referenceLabel})
+
+ ) : null}
+
+
+
+
+ {summary.coverage.percentage}% Datenabdeckung · {summary.coverage.coveredItems} von {summary.coverage.totalItems} Listenpositionen mit Nährwert und Packungsmenge
+
+ {summary.exceedsReference ? (
+
+ Die bereits bekannte Listenmenge liegt über dem Vergleichswert. Das ist keine Verzehrprognose.
+
+ ) : !summary.coverage.complete ? (
+ Die bekannte Summe ist ein Mindestwert, weil Angaben fehlen.
+ ) : null}
+ {summary.missingQuantity.length > 0 ? (
+ Packungsmenge fehlt: {summary.missingQuantity.join(', ')}
+ ) : null}
+ {summary.missingNutrition.length > 0 ? (
+ {summary.label}-Angabe fehlt: {summary.missingNutrition.join(', ')}
+ ) : null}
+ {summary.contributors.length > 0 ? (
+
+ Grösste bekannte Beiträge
+ {summary.contributors.slice(0, 3).map((contributor) => (
+
+
+ {contributor.productName}{contributor.quantity > 1 ? ` × ${contributor.quantity}` : ''}
+
+
+ {formatAmount(contributor.amount, summary.unit)} · {contributor.sharePercentage}%
+
+
+ ))}
+
+ ) : null}
+
+ ))}
+
+ ) : null}
+
+ {productCautions.length > 0 ? (
+
+ Produkte prüfen
+ {productCautions.map((caution) => (
+
- {warning.label}: {formatAmount(warning.total, warning.unit)} von {formatAmount(warning.limit, warning.unit)}
-
- {warning.message}
+ caution.severity === 'critical' ? styles.critical : styles.medium
+ ]}>{caution.productName} · {caution.label}
+ {caution.message}
))}
@@ -188,10 +247,34 @@ const styles = StyleSheet.create({
criticalFill: {
backgroundColor: colors.danger
},
- warningList: {
+ nutritionPanel: {
+ backgroundColor: colors.surface,
+ borderColor: colors.border,
+ borderRadius: 20,
+ borderWidth: 1,
+ gap: 16,
+ padding: 18
+ },
+ panelTitle: { color: colors.text, fontSize: 18, fontWeight: '800' },
+ panelDisclaimer: { color: colors.muted, fontSize: 13, lineHeight: 19 },
+ nutrientSummary: { borderTopColor: colors.border, borderTopWidth: 1, gap: 8, paddingTop: 15 },
+ nutrientHeader: { alignItems: 'baseline', flexDirection: 'row', gap: 10, justifyContent: 'space-between' },
+ nutrientTitle: { color: colors.text, fontSize: 16, fontWeight: '800' },
+ nutrientAmount: { color: colors.primaryDark, flexShrink: 1, fontSize: 14, fontWeight: '800', textAlign: 'right' },
+ referenceText: { color: colors.muted, fontSize: 12 },
+ coverageTrack: { backgroundColor: '#edf1ee', borderRadius: 999, height: 8, overflow: 'hidden' },
+ coverageFill: { backgroundColor: colors.primary, borderRadius: 999, height: '100%' },
+ coverageText: { color: colors.muted, fontSize: 12, lineHeight: 17 },
+ unknownCopy: { color: colors.warning, fontSize: 12, lineHeight: 17 },
+ contributors: { gap: 6, marginTop: 2 },
+ contributorHeading: { color: colors.text, fontSize: 13, fontWeight: '800' },
+ contributorRow: { flexDirection: 'row', gap: 8, justifyContent: 'space-between' },
+ contributorName: { color: colors.muted, flex: 1, fontSize: 12 },
+ contributorAmount: { color: colors.text, fontSize: 12, fontWeight: '700', textAlign: 'right' },
+ cautionList: {
gap: 10
},
- warningBox: {
+ cautionBox: {
backgroundColor: colors.surface,
borderRadius: 16,
borderWidth: 1,
diff --git a/src/services/shoppingListWarningsService.js b/src/services/shoppingListWarningsService.js
index afb5c31..39f5d29 100644
--- a/src/services/shoppingListWarningsService.js
+++ b/src/services/shoppingListWarningsService.js
@@ -1,68 +1,149 @@
-const dailyLimitRules = [
- {
- key: 'caffeine',
- label: 'Koffein',
- limit: 200,
- unit: 'mg',
- nutritionKey: 'caffeineMgPer100g',
- severity: 'critical',
- message: 'Mehr Koffein als der Tagesrichtwert in Shoppinguin. Auf mehrere Tage aufteilen.'
- },
- {
- key: 'sugar',
- label: 'Zucker',
- limit: 50,
- unit: 'g',
- nutritionKey: 'sugarPer100g',
- severity: 'warning',
- message: 'Mehr Zucker als der Tagesrichtwert in Shoppinguin. Auf mehrere Tage aufteilen.'
- },
- {
- key: 'salt',
- label: 'Salz',
- limit: 5,
- unit: 'g',
- nutritionKey: 'saltPer100g',
- severity: 'warning',
- message: 'Mehr Salz als der Tagesrichtwert in Shoppinguin. Auf mehrere Tage aufteilen.'
- }
-];
+import { dailyTargets } from './dailyNutritionService.js';
+import { calculateProductRating } from './ratingService.js';
-export function calculateShoppingListWarnings(shoppingList) {
- return dailyLimitRules
- .map((rule) => {
- const total = totalNutrientAmount(shoppingList.items || [], rule);
+export function calculateShoppingListNutritionSummary(shoppingList, preferences = {}) {
+ const items = shoppingList?.items || [];
+ const targets = dailyTargets(preferences);
+ const rules = [
+ {
+ key: 'sugar',
+ label: 'Gesamtzucker',
+ limit: targets.sugar,
+ unit: 'g',
+ nutritionKey: 'sugarPer100g',
+ referenceLabel: 'dein Tagesplanwert'
+ },
+ {
+ key: 'salt',
+ label: 'Salz',
+ limit: targets.salt,
+ unit: 'g',
+ nutritionKey: 'saltPer100g',
+ referenceLabel: 'Orientierungswert pro Tag'
+ }
+ ];
- return {
- ...rule,
- total,
- percentage: Math.round((total / rule.limit) * 100)
- };
- })
- .filter((warning) => warning.total > warning.limit);
+ return rules.map((rule) => summarizeNutrient(items, rule));
}
-function totalNutrientAmount(items, rule) {
- return items.reduce((sum, item) => {
- const per100g = item.nutrition?.[rule.nutritionKey];
- const quantityGrams = itemQuantityGrams(item);
+export function calculateShoppingListWarnings(shoppingList, preferences = {}) {
+ return calculateShoppingListNutritionSummary(shoppingList, preferences)
+ .filter((summary) => summary.exceedsReference);
+}
- if (typeof per100g !== 'number' || typeof quantityGrams !== 'number') {
- return sum;
+export function calculateShoppingListProductCautions(shoppingList, preferences = {}) {
+ return (shoppingList?.items || []).flatMap((item) => {
+ const product = productFromListItem(item);
+ const rating = calculateProductRating(product, preferences);
+ const cautions = [];
+
+ if (rating.hasBlockedAllergen) {
+ cautions.push({
+ key: `${item.id}-allergen`,
+ itemId: item.id,
+ productName: item.productName,
+ severity: 'critical',
+ label: 'Allergenkonflikt',
+ message: rating.categoryScores.allergies.message
+ });
+ } else if (rating.allergenReviewRequired) {
+ cautions.push({
+ key: `${item.id}-allergen-review`,
+ itemId: item.id,
+ productName: item.productName,
+ severity: 'review',
+ label: 'Allergene prüfen',
+ message: rating.allergenReviewMessage || 'Allergenfreiheit ist nicht bestätigt. Verpackung prüfen.'
+ });
}
- return sum + (per100g * quantityGrams * item.quantity) / 100;
- }, 0);
+ if (rating.goalConflict) {
+ cautions.push({
+ key: `${item.id}-diet`,
+ itemId: item.id,
+ productName: item.productName,
+ severity: 'critical',
+ label: 'Ernährungsziel',
+ message: rating.categoryScores.ingredients.message
+ });
+ } else if (rating.goalReviewRequired && ['vegan', 'vegetarian'].includes(preferences.preferredDiet)) {
+ cautions.push({
+ key: `${item.id}-diet-review`,
+ itemId: item.id,
+ productName: item.productName,
+ severity: 'review',
+ label: 'Ernährungsziel prüfen',
+ message: 'Die gespeicherten Produktangaben bestätigen dein Ernährungsziel nicht. Verpackung prüfen.'
+ });
+ }
+
+ return cautions;
+ });
}
-function itemQuantityGrams(item) {
- if (typeof item.packageQuantityGrams === 'number' && item.packageQuantityGrams > 0) {
- return item.packageQuantityGrams;
+function summarizeNutrient(items, rule) {
+ const contributors = [];
+ const missingQuantity = [];
+ const missingNutrition = [];
+
+ for (const item of items) {
+ const per100g = item.nutrition?.[rule.nutritionKey];
+ const packageGrams = reliablePackageGrams(item);
+ if (!Number.isFinite(per100g)) missingNutrition.push(item.productName);
+ if (packageGrams === null) missingQuantity.push(item.productName);
+ if (!Number.isFinite(per100g) || packageGrams === null) continue;
+
+ const quantity = Number.isFinite(item.quantity) && item.quantity > 0 ? item.quantity : 1;
+ contributors.push({
+ itemId: item.id,
+ productName: item.productName,
+ quantity,
+ amount: per100g * packageGrams * quantity / 100
+ });
}
- if (typeof item.servingQuantityGrams === 'number' && item.servingQuantityGrams > 0) {
- return item.servingQuantityGrams;
- }
+ contributors.sort((a, b) => b.amount - a.amount);
+ const knownTotal = contributors.reduce((sum, contributor) => sum + contributor.amount, 0);
+ const coveredItems = contributors.length;
+ const totalItems = items.length;
+ const coveragePercentage = totalItems ? Math.round(coveredItems / totalItems * 100) : 0;
- return 100;
+ return {
+ ...rule,
+ knownTotal,
+ percentageOfReference: Number.isFinite(rule.limit) && rule.limit > 0
+ ? Math.round(knownTotal / rule.limit * 100)
+ : null,
+ exceedsReference: Number.isFinite(rule.limit) && knownTotal > rule.limit,
+ coverage: {
+ coveredItems,
+ totalItems,
+ percentage: coveragePercentage,
+ complete: totalItems > 0 && coveredItems === totalItems
+ },
+ missingQuantity: unique(missingQuantity),
+ missingNutrition: unique(missingNutrition),
+ contributors: contributors.map((contributor) => ({
+ ...contributor,
+ sharePercentage: knownTotal > 0 ? Math.round(contributor.amount / knownTotal * 100) : 0
+ }))
+ };
+}
+
+function reliablePackageGrams(item) {
+ const amount = Number(item.packageQuantityGrams);
+ return Number.isFinite(amount) && amount > 0 ? amount : null;
+}
+
+function productFromListItem(item) {
+ return {
+ id: item.productId || item.id,
+ name: item.productName,
+ nutrition: item.nutrition || {},
+ ...(item.productFacts || {})
+ };
+}
+
+function unique(values) {
+ return [...new Set(values.filter(Boolean))];
}