improve product details and shopping list guidance
Android Release Build / build-android (push) Failing after 7m11s

This commit is contained in:
2026-11-19 23:49:33 +01:00
parent 22c51c2e36
commit 460ca60914
5 changed files with 575 additions and 340 deletions
+25 -2
View File
@@ -156,6 +156,7 @@ export default function App() {
onToggleItem={toggleListItem} onToggleItem={toggleListItem}
onChangeItemQuantity={changeListItemQuantity} onChangeItemQuantity={changeListItemQuantity}
lastDeletedItem={lastDeletedListItem} lastDeletedItem={lastDeletedListItem}
preferences={preferences}
shoppingList={shoppingList} shoppingList={shoppingList}
/> />
); );
@@ -273,7 +274,12 @@ export default function App() {
setShoppingList((current) => ({ setShoppingList((current) => ({
...current, ...current,
items: current.items.map((item) => item.barcode === updated.barcode 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 }); setRoute({ name: 'productDetail', product: updated });
} }
@@ -315,7 +321,8 @@ export default function App() {
packageQuantityGrams: item.packageQuantityGrams ?? product.packageQuantityGrams, packageQuantityGrams: item.packageQuantityGrams ?? product.packageQuantityGrams,
packageQuantityLabel: item.packageQuantityLabel ?? product.packageQuantityLabel, packageQuantityLabel: item.packageQuantityLabel ?? product.packageQuantityLabel,
servingQuantityGrams: item.servingQuantityGrams ?? product.servingQuantityGrams, servingQuantityGrams: item.servingQuantityGrams ?? product.servingQuantityGrams,
nutrition: item.nutrition ?? product.nutrition nutrition: { ...(item.nutrition || {}), ...(product.nutrition || {}) },
productFacts: listProductFacts(product)
} }
: item : item
) )
@@ -331,6 +338,7 @@ export default function App() {
packageQuantityLabel: product.packageQuantityLabel, packageQuantityLabel: product.packageQuantityLabel,
servingQuantityGrams: product.servingQuantityGrams, servingQuantityGrams: product.servingQuantityGrams,
nutrition: product.nutrition, nutrition: product.nutrition,
productFacts: listProductFacts(product),
checked: false, checked: false,
addedAt: new Date().toISOString() addedAt: new Date().toISOString()
} }
@@ -544,6 +552,21 @@ function stripLegacyPriceFields(value) {
return rest; 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({ const styles = StyleSheet.create({
container: { container: {
backgroundColor: colors.background, backgroundColor: colors.background,
+4 -2
View File
@@ -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. 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. 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 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. 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 ## Run
+276 -230
View File
@@ -5,14 +5,18 @@ import PrimaryButton from '../components/PrimaryButton';
import SecondaryButton from '../components/SecondaryButton'; import SecondaryButton from '../components/SecondaryButton';
import PortionSelector from '../components/consumption/PortionSelector'; import PortionSelector from '../components/consumption/PortionSelector';
import AppHeader from '../components/layout/AppHeader'; import AppHeader from '../components/layout/AppHeader';
import DisclosureSection from '../components/layout/DisclosureSection';
import ScreenContainer from '../components/layout/ScreenContainer'; import ScreenContainer from '../components/layout/ScreenContainer';
import SectionTitle from '../components/layout/SectionTitle';
import ProductImage from '../components/product/ProductImage'; import ProductImage from '../components/product/ProductImage';
import ProductScoreBadge from '../components/product/ProductScoreBadge'; import ProductScoreBadge from '../components/product/ProductScoreBadge';
import RatingCategoryRow from '../components/product/RatingCategoryRow'; import RatingCategoryRow from '../components/product/RatingCategoryRow';
import { calculateProductRating } from '../services/ratingService';
import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService'; import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService';
import { todayKey } from '../services/dailyNutritionService'; import { todayKey } from '../services/dailyNutritionService';
import {
buildProductDetailPresentation,
shouldLoadAlternativePreview
} from '../services/productDetailPresentation';
import { calculateProductRating } from '../services/ratingService';
import { colors } from '../utils/constants'; import { colors } from '../utils/constants';
export default function ProductDetailScreen({ export default function ProductDetailScreen({
@@ -33,26 +37,50 @@ export default function ProductDetailScreen({
const [savedMessage, setSavedMessage] = useState(''); const [savedMessage, setSavedMessage] = useState('');
const [consumptionMessage, setConsumptionMessage] = useState(''); const [consumptionMessage, setConsumptionMessage] = useState('');
const [isChoosingPortion, setIsChoosingPortion] = useState(false); 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 [suggestions, setSuggestions] = useState([]);
const [suggestionsLoading, setSuggestionsLoading] = useState(true); const rating = useMemo(
const [suggestionsError, setSuggestionsError] = useState(false); () => calculateProductRating(product, preferences, { shoppingList, dailyLog }),
const rating = useMemo(() => calculateProductRating(product, preferences, { shoppingList, dailyLog }), [product, preferences, shoppingList, dailyLog]); [product, preferences, shoppingList, dailyLog]
);
const presentation = useMemo(
() => buildProductDetailPresentation(product, rating, preferences),
[product, rating, preferences]
);
const footprint = product.sustainability?.footprint; const footprint = product.sustainability?.footprint;
const missingFields = missingProductFields(product, preferences); const alternativeContextKey = useMemo(() => JSON.stringify({
const recommendation = rating.overallStatus === 'good' ? 'Passt gut zu dir' productId: product.id,
: rating.overallStatus === 'critical' ? 'Lieber meiden' preferences,
: rating.overallStatus === 'unknown' ? 'Zu wenig Daten' : 'Genauer prüfen'; dailyLog,
cachedProducts: Object.keys(productCache || {}).sort()
}), [product.id, preferences, dailyLog, productCache]);
useEffect(() => { useEffect(() => {
if (!shouldLoadAlternativePreview(
alternativesRequested,
alternativesLoadedKey === alternativeContextKey ? 'loaded' : 'idle'
)) return undefined;
let active = true; let active = true;
setSuggestionsLoading(true); setAlternativesStatus('loading');
setSuggestionsError(false);
findAlternatives(product, preferences, productCache, { dailyLog }, { preview: true }) findAlternatives(product, preferences, productCache, { dailyLog }, { preview: true })
.then((results) => { if (active) setSuggestions(results); }) .then((results) => {
.catch(() => { if (active) { setSuggestions([]); setSuggestionsError(true); } }) if (!active) return;
.finally(() => { if (active) setSuggestionsLoading(false); }); setSuggestions(results);
setAlternativesStatus('loaded');
setAlternativesLoadedKey(alternativeContextKey);
})
.catch(() => {
if (!active) return;
setSuggestions([]);
setAlternativesStatus('error');
setAlternativesLoadedKey(alternativeContextKey);
});
return () => { active = false; }; return () => { active = false; };
}, [product, preferences, productCache, dailyLog]); }, [alternativeContextKey, alternativesLoadedKey, alternativesRequested, dailyLog, preferences, product, productCache]);
function addToList() { function addToList() {
if (rating.hasBlockedAllergen) { if (rating.hasBlockedAllergen) {
@@ -81,6 +109,16 @@ export default function ProductDetailScreen({
setSavedMessage('Zur Einkaufsliste hinzugefügt.'); setSavedMessage('Zur Einkaufsliste hinzugefügt.');
} }
function toggleAlternatives(expanded) {
setAlternativesExpanded(expanded);
if (expanded) setAlternativesRequested(true);
}
function retryAlternatives() {
setAlternativesStatus('idle');
setAlternativesLoadedKey('');
}
return ( return (
<ScreenContainer> <ScreenContainer>
<AppHeader title="Produkt im Check" subtitle="Bewertung nach deinen Einstellungen" onBack={onBack} /> <AppHeader title="Produkt im Check" subtitle="Bewertung nach deinen Einstellungen" onBack={onBack} />
@@ -91,29 +129,45 @@ export default function ProductDetailScreen({
<View style={styles.copy}> <View style={styles.copy}>
<Text style={styles.brand}>{product.brand || 'Ohne Marke'}</Text> <Text style={styles.brand}>{product.brand || 'Ohne Marke'}</Text>
<Text style={styles.name}>{product.name}</Text> <Text style={styles.name}>{product.name}</Text>
<Text style={styles.meta}> <Text style={styles.meta}>{product.category || 'Produkt'}</Text>
{product.category || 'Produkt'}
</Text>
<Text style={styles.source}>{sourceLabel(product.dataSource)}{product.cacheStale ? ' · Veraltete Daten' : ''}</Text> <Text style={styles.source}>{sourceLabel(product.dataSource)}{product.cacheStale ? ' · Veraltete Daten' : ''}</Text>
{product.manualOverrides ? <Text style={styles.meta}>Angaben von dir ergänzt · lokal gespeichert</Text> : null}
{product.manualOverrides ? <Text style={styles.meta}>Etikettangaben: {manualFieldNames(product.manualOverrides).join(', ') || 'Produkttyp'}</Text> : null}
{['cache', 'open-food-facts'].includes(product.dataSource) ? <Text style={styles.meta}>Produktdaten geprüft: {formatCheckedDate(product.fetchedAt)}</Text> : null}
</View> </View>
<ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} /> <ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} />
</View> </View>
<View style={[styles.recommendation, styles[`${rating.overallStatus}Recommendation`]]}> <View style={[styles.recommendation, styles[`${rating.overallStatus}Recommendation`]]}>
<Text style={[styles.recommendationTitle, styles[`${rating.overallStatus}Text`]]}>{recommendation}</Text> <Text style={[styles.recommendationTitle, styles[`${rating.overallStatus}Text`]]}>
<Text style={styles.recommendationCopy}> {presentation.recommendation}
{recommendationMessage(rating)}
</Text> </Text>
<Text style={styles.recommendationCopy}>Bewertbare Daten: {rating.dataCoverage}% der für dein Profil anwendbaren Kriterien (gewichtet).</Text> <Text style={styles.recommendationCopy}>{presentation.recommendationMessage}</Text>
</View>
<View style={[styles.confidencePanel, styles[`${presentation.confidence.tone}Confidence`]]}>
<View style={styles.confidenceHeader}>
<Text style={styles.confidenceTitle}>{presentation.confidence.label}</Text>
<Text style={styles.confidenceValue}>{presentation.confidence.coverage}%</Text>
</View>
<View style={styles.confidenceTrack}>
<View style={[styles.confidenceFill, { width: `${presentation.confidence.coverage}%` }]} />
</View>
<Text style={styles.confidenceCopy}>{presentation.confidence.message}</Text>
</View> </View>
</View> </View>
{rating.mainFactors.length > 0 || rating.scoreLimitReasons.length > 0 ? ( {presentation.criticalNotices.map((notice) => (
<View style={styles.dataPanel}> <View key={notice.key} style={[
<Text style={styles.factorTitle}>Das beeinflusst die Bewertung</Text> styles.notice,
{rating.mainFactors.map((factor) => ( notice.tone === 'critical' ? styles.criticalNotice : styles.reviewNotice
]}>
<Text style={notice.tone === 'critical' ? styles.criticalText : styles.mediumText}>{notice.label}</Text>
<Text style={styles.noticeCopy}>{notice.message}</Text>
</View>
))}
{presentation.topFactors.length > 0 ? (
<View style={styles.decisionPanel}>
<Text style={styles.panelEyebrow}>DIE STÄRKSTEN EINFLÜSSE</Text>
{presentation.topFactors.map((factor) => (
<View key={factor.category} style={styles.factorRow}> <View key={factor.category} style={styles.factorRow}>
<View style={styles.factorHeader}> <View style={styles.factorHeader}>
<Text style={styles.factorLabel}>{factor.label}</Text> <Text style={styles.factorLabel}>{factor.label}</Text>
@@ -122,40 +176,58 @@ export default function ProductDetailScreen({
<Text style={styles.dataText}>{factor.message}</Text> <Text style={styles.dataText}>{factor.message}</Text>
</View> </View>
))} ))}
{rating.scoreLimitReasons.length > 0 ? <View style={styles.limitPanel}>
<Text style={styles.limitTitle}>Bitte beachten</Text>
{rating.scoreLimitReasons.map((reason) => <Text key={reason} style={styles.dataText}>• {reason}</Text>)}
</View> : null}
</View> </View>
) : null} ) : null}
<View style={styles.dataPanel}> <View style={styles.servingPanel}>
<Text style={styles.factorTitle}>Produktangaben ergänzen</Text> <View style={styles.servingHeader}>
<Text style={styles.dataText}>{missingFields.length <View style={styles.copy}>
? `Für eine genauere Bewertung fehlen: ${missingFields.join(', ')}.` <Text style={styles.panelTitle}>{presentation.serving.approximate ? 'Nährwerte zur Einordnung' : 'Pro Portion'}</Text>
: 'Die wichtigsten Angaben für die Bewertung sind vorhanden.'}</Text> <Text style={styles.servingBasis}>
<Text style={styles.dataText}>Fehlende Werte werden nicht geschätzt.</Text> {presentation.serving.amountLabel} · {presentation.serving.basisLabel}
<SecondaryButton label="Angaben ergänzen oder korrigieren" onPress={() => onEditProduct(product)} /> </Text>
{/^\d{8,14}$/.test(product.barcode || '') ? ( </View>
<Pressable accessibilityRole="link" onPress={() => Linking.openURL(`https://ch.openfoodfacts.org/product/${product.barcode}`)}> {presentation.serving.approximate ? <Text style={styles.approximateBadge}>Näherung</Text> : null}
<Text style={styles.savedLink}>Produkt auf Open Food Facts öffnen ›</Text> </View>
</Pressable> <View style={styles.nutrientGrid}>
{presentation.serving.rows.map((row) => (
<View key={row.key} style={styles.nutrientTile}>
<Text style={styles.nutrientLabel}>{row.label}</Text>
<Text style={[styles.nutrientValue, row.value === null ? styles.missingValue : null]}>
{row.value === null ? 'Keine Angabe' : `${formatNutrient(row.value)} ${row.unit}`}
</Text>
</View>
))}
</View>
{presentation.serving.approximate ? (
<Text style={styles.servingNote}>Keine verlässliche Portionsgrösse vorhanden. Die angezeigte Grundlage ist klar gekennzeichnet.</Text>
) : null} ) : null}
</View> </View>
<View style={styles.actionsPanel}>
<View style={styles.actionBlock}>
<Text style={styles.actionTitle}>Für deinen Einkauf</Text>
<Text style={styles.actionCopy}>Produkt auf die aktuelle Einkaufsliste setzen.</Text>
<PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} />
{savedMessage ? ( {savedMessage ? (
<View style={styles.savedPanel}> <View style={styles.savedPanel}>
<Text style={styles.saved}>{savedMessage}</Text> <Text style={rating.hasBlockedAllergen ? styles.savedError : styles.saved}>{savedMessage}</Text>
{!rating.hasBlockedAllergen ? (
<Pressable accessibilityRole="button" onPress={onOpenList}> <Pressable accessibilityRole="button" onPress={onOpenList}>
<Text style={styles.savedLink}>Einkaufsliste ansehen ›</Text> <Text style={styles.savedLink}>Einkaufsliste ansehen ›</Text>
</Pressable> </Pressable>
) : null}
</View> </View>
) : null} ) : null}
<PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} />
{consumptionMessage ? (
<View style={styles.savedPanel}>
<Text style={styles.saved}>{consumptionMessage}</Text>
</View> </View>
<View style={styles.actionDivider} />
<View style={styles.actionBlock}>
<Text style={styles.actionTitle}>Tagesprotokoll</Text>
<Text style={styles.actionCopy}>Nur verwenden, wenn du eine Portion tatsächlich gegessen hast.</Text>
{consumptionMessage ? (
<View style={styles.savedPanel}><Text style={styles.saved}>{consumptionMessage}</Text></View>
) : null} ) : null}
{isChoosingPortion ? ( {isChoosingPortion ? (
<PortionSelector <PortionSelector
@@ -170,20 +242,81 @@ export default function ProductDetailScreen({
product={product} product={product}
/> />
) : ( ) : (
<SecondaryButton label="Portion heute gegessen" onPress={() => { <SecondaryButton label="Gegessene Portion erfassen" onPress={() => {
setConsumptionMessage(''); setConsumptionMessage('');
setIsChoosingPortion(true); setIsChoosingPortion(true);
}} /> }} />
)} )}
</View>
</View>
<SectionTitle>Ähnliche, bessere Alternativen</SectionTitle> <DisclosureSection
{suggestionsLoading ? <Text style={styles.dataText}>Passende Produkte werden gesucht ...</Text> : null} summary={`${Object.keys(rating.categoryScores).length} Kriterien · Details und Begründungen`}
{!suggestionsLoading && suggestions.length === 0 ? <Text style={styles.dataText}> title="Bewertung im Detail"
{suggestionsError ? 'Alternativen konnten gerade nicht geladen werden.' >
: alternativeSearchIssue(product, rating) || 'Unter den geprüften Treffern war keine belegbar bessere Alternative derselben Produktart.'} {rating.scoreLimitReasons.length > 0 ? (
</Text> : null} <View style={styles.limitPanel}>
{suggestions.map((item) => <Pressable key={item.product.id} accessibilityRole="button" <Text style={styles.limitTitle}>Was die Empfehlung begrenzt</Text>
onPress={() => onOpenProduct(item.product)} style={styles.suggestionCard}> {rating.scoreLimitReasons.map((reason) => <Text key={reason} style={styles.dataText}>• {reason}</Text>)}
</View>
) : null}
{Object.entries(rating.categoryScores).map(([category, categoryRating]) => (
<RatingCategoryRow
category={category}
key={category}
onPress={() => onShowRatingCriteria(product, category)}
rating={categoryRating}
/>
))}
</DisclosureSection>
<DisclosureSection
summary={presentation.missingFields.length
? `${presentation.missingFields.length} Angaben fehlen oder müssen geprüft werden`
: 'Die wichtigsten Bewertungsangaben sind vorhanden'}
title="Datenqualität und Quellen"
>
<Text style={styles.dataText}>{presentation.missingFields.length
? `Für eine genauere Bewertung fehlen: ${presentation.missingFields.join(', ')}.`
: 'Die wichtigsten Angaben für die Bewertung sind vorhanden.'}</Text>
<Text style={styles.dataText}>Fehlende Werte werden nicht geschätzt.</Text>
{product.manualOverrides ? <Text style={styles.dataText}>Von dir ergänzt: {manualFieldNames(product.manualOverrides).join(', ') || 'Produkttyp'}.</Text> : null}
{['cache', 'open-food-facts'].includes(product.dataSource) ? <Text style={styles.dataText}>Produktdaten geprüft: {formatCheckedDate(product.fetchedAt)}</Text> : null}
<SecondaryButton label="Angaben ergänzen oder korrigieren" onPress={() => onEditProduct(product)} />
{/^\d{8,14}$/.test(product.barcode || '') ? (
<Pressable accessibilityRole="link" onPress={() => Linking.openURL(`https://ch.openfoodfacts.org/product/${product.barcode}`)}>
<Text style={styles.savedLink}>Produkt auf Open Food Facts öffnen ›</Text>
</Pressable>
) : null}
</DisclosureSection>
<DisclosureSection
expanded={alternativesExpanded}
onToggle={toggleAlternatives}
summary="Ähnliche Produkte werden erst beim Öffnen gesucht"
title="Bessere Alternativen"
>
{alternativesStatus === 'idle' || alternativesStatus === 'loading' ? (
<Text style={styles.dataText}>Passende Produkte werden gesucht ...</Text>
) : null}
{alternativesStatus === 'error' ? (
<>
<Text style={styles.dataText}>Alternativen konnten gerade nicht geladen werden.</Text>
<SecondaryButton label="Erneut versuchen" onPress={retryAlternatives} />
</>
) : null}
{alternativesStatus === 'loaded' && suggestions.length === 0 ? (
<Text style={styles.dataText}>
{alternativeSearchIssue(product, rating) || 'Unter den geprüften Treffern war keine belegbar bessere Alternative derselben Produktart.'}
</Text>
) : null}
{suggestions.map((item) => (
<Pressable
accessibilityRole="button"
key={item.product.id}
onPress={() => onOpenProduct(item.product)}
style={styles.suggestionCard}
>
<View style={styles.suggestionRow}> <View style={styles.suggestionRow}>
<ProductImage imageUrl={item.product.imageUrl} productName={item.product.name} /> <ProductImage imageUrl={item.product.imageUrl} productName={item.product.name} />
<View style={styles.suggestionBody}> <View style={styles.suggestionBody}>
@@ -195,34 +328,25 @@ export default function ProductDetailScreen({
<Text style={styles.suggestionLink}>Produkt ansehen ›</Text> <Text style={styles.suggestionLink}>Produkt ansehen ›</Text>
</View> </View>
</View> </View>
</Pressable>)} </Pressable>
<SecondaryButton label="Weitere Alternativen ansehen" onPress={() => onShowAlternatives(product)} />
<SectionTitle>Bewertungskriterien</SectionTitle>
{Object.entries(rating.categoryScores).map(([category, categoryRating]) => (
<RatingCategoryRow
category={category}
key={category}
onPress={() => onShowRatingCriteria(product, category)}
rating={categoryRating}
/>
))} ))}
<SecondaryButton label="Weitere Alternativen ansehen" onPress={() => onShowAlternatives(product)} />
</DisclosureSection>
<SectionTitle>Umweltwirkung</SectionTitle> <DisclosureSection
<View style={styles.dataPanel}> summary={footprint?.status === 'product-specific' ? 'Produktspezifische Umweltdaten'
: footprint?.status === 'estimated' ? 'Geschätzte Umweltwirkung' : 'Nur begrenzte Umweltdaten'}
title="Umweltwirkung"
>
{footprint?.status === 'product-specific' || footprint?.status === 'estimated' ? ( {footprint?.status === 'product-specific' || footprint?.status === 'estimated' ? (
<> <>
<Text style={styles.dataText}> <Text style={styles.dataText}>CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg</Text>
CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg
</Text>
<Text style={styles.dataText}> <Text style={styles.dataText}>
{footprint.status === 'product-specific' ? 'Produktspezifische Angabe aus Open Food Facts.' {footprint.status === 'product-specific' ? 'Produktspezifische Angabe aus Open Food Facts.'
: `Schätzung anhand vergleichbarer Lebensmittel: ${footprint.referenceCategory}. AGRIBALYSE-Durchschnitt, keine Messung dieses Markenprodukts.`} : `Schätzung anhand vergleichbarer Lebensmittel: ${footprint.referenceCategory}. AGRIBALYSE-Durchschnitt, keine Messung dieses Markenprodukts.`}
</Text> </Text>
{typeof footprint.packageKgCo2e === 'number' ? ( {typeof footprint.packageKgCo2e === 'number' ? (
<Text style={styles.dataText}> <Text style={styles.dataText}>Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e</Text>
Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e
</Text>
) : null} ) : null}
<Text style={styles.dataText}> <Text style={styles.dataText}>
Quelle: {footprint.source === 'AGRIBALYSE' ? 'ADEME / ' : ''}{footprint.source}{footprint.datasetVersion ? ` ${footprint.datasetVersion}` : ''} Quelle: {footprint.source === 'AGRIBALYSE' ? 'ADEME / ' : ''}{footprint.source}{footprint.datasetVersion ? ` ${footprint.datasetVersion}` : ''}
@@ -236,7 +360,7 @@ export default function ProductDetailScreen({
<Text style={styles.dataText}>Landnutzung: {formatIndicator(footprint.indicators?.landUse)}</Text> <Text style={styles.dataText}>Landnutzung: {formatIndicator(footprint.indicators?.landUse)}</Text>
<Text style={styles.dataText}>Wasserknappheit: {formatIndicator(footprint.indicators?.waterScarcity)}</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}>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> <Text style={styles.dataText}>Lebenszyklus bis zum verzehrbaren Lebensmittel; Transport und Verpackung sind enthalten. Diese Indikatoren sind keine CO₂-Werte.</Text>
</> </>
) : null} ) : null}
</> </>
@@ -246,10 +370,12 @@ export default function ProductDetailScreen({
{(product.sustainability?.sellingCountries || []).length > 0 ? ( {(product.sustainability?.sellingCountries || []).length > 0 ? (
<Text style={styles.dataText}>Verkaufsländer: {product.sustainability.sellingCountries.map(formatCountryTag).join(', ')}</Text> <Text style={styles.dataText}>Verkaufsländer: {product.sustainability.sellingCountries.map(formatCountryTag).join(', ')}</Text>
) : null} ) : null}
</View> </DisclosureSection>
<SectionTitle>Produktdaten</SectionTitle> <DisclosureSection
<View style={styles.dataPanel}> summary="Barcode, Zutaten, Allergene und Nutri-Score"
title="Produktdaten"
>
<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}>Angegebene Allergene: {(product.allergens || []).join(', ') || 'Keine Angaben'}</Text> <Text style={styles.dataText}>Angegebene Allergene: {(product.allergens || []).join(', ') || 'Keine Angaben'}</Text>
@@ -258,48 +384,11 @@ export default function ProductDetailScreen({
Nutri-Score: {rating.categoryScores.nutrition.nutriScore || 'Keine Angabe'} Nutri-Score: {rating.categoryScores.nutrition.nutriScore || 'Keine Angabe'}
{rating.categoryScores.nutrition.nutriScoreSource === 'calculated' ? ' (von der App berechnet)' : rating.categoryScores.nutrition.nutriScore ? ' (Open Food Facts)' : ''} {rating.categoryScores.nutrition.nutriScoreSource === 'calculated' ? ' (von der App berechnet)' : rating.categoryScores.nutrition.nutriScore ? ' (Open Food Facts)' : ''}
</Text> </Text>
</View> </DisclosureSection>
</ScreenContainer> </ScreenContainer>
); );
} }
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) { function manualFieldNames(overrides) {
const names = { name: 'Name', brand: 'Marke', ingredients: 'Zutaten', const names = { name: 'Name', brand: 'Marke', ingredients: 'Zutaten',
allergens: 'Allergene', allergenTraces: 'Spuren', drinkType: 'Produkttyp' }; allergens: 'Allergene', allergenTraces: 'Spuren', drinkType: 'Produkttyp' };
@@ -315,13 +404,8 @@ function manualFieldNames(overrides) {
} }
function sourceLabel(source) { function sourceLabel(source) {
const labels = { return { cache: 'Quelle: lokaler Cache', local: 'Quelle: lokal erfasst', 'open-food-facts': 'Quelle: Open Food Facts' }[source]
cache: 'Quelle: lokaler Cache', || 'Quelle: unbekannt';
local: 'Quelle: lokal erfasst',
'open-food-facts': 'Quelle: Open Food Facts'
};
return labels[source] || 'Quelle: unbekannt';
} }
function formatCheckedDate(value) { function formatCheckedDate(value) {
@@ -348,6 +432,10 @@ function formatAmount(value) {
return new Intl.NumberFormat('de-CH', { maximumFractionDigits: 1 }).format(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) { function formatEntryDate(dateKey) {
const date = new Date(`${dateKey}T12:00:00`); const date = new Date(`${dateKey}T12:00:00`);
return Number.isNaN(date.getTime()) ? dateKey : date.toLocaleDateString('de-CH'); return Number.isNaN(date.getTime()) ? dateKey : date.toLocaleDateString('de-CH');
@@ -368,112 +456,70 @@ function matchLabel(method) {
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
suggestionCard: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 16, borderWidth: 1, gap: 8, padding: 16 }, productPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 20, borderWidth: 1, gap: 14, padding: 18 },
suggestionRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 }, topRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 },
suggestionBody: { flex: 1, gap: 8 }, copy: { flex: 1 },
suggestionName: { color: colors.text, flex: 1, fontSize: 16, fontWeight: '800' }, brand: { color: colors.primary, fontSize: 13, fontWeight: '800', textTransform: 'uppercase' },
suggestionLink: { color: colors.primary, fontSize: 13, fontWeight: '800' }, name: { color: colors.text, fontSize: 25, fontWeight: '800', lineHeight: 31, marginTop: 4 },
factorTitle: { color: colors.text, fontSize: 16, fontWeight: '800' }, meta: { color: colors.muted, fontSize: 15, marginTop: 6 },
factorRow: { borderTopColor: colors.border, borderTopWidth: 1, gap: 4, paddingTop: 10 }, source: { alignSelf: 'flex-start', backgroundColor: '#eef3ef', borderRadius: 8, color: colors.primaryDark, fontSize: 12, fontWeight: '800', marginTop: 10, paddingHorizontal: 8, paddingVertical: 4 },
factorHeader: { alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between' }, recommendation: { borderRadius: 14, gap: 4, padding: 14 },
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
},
goodRecommendation: { backgroundColor: '#e4f4e9' }, goodRecommendation: { backgroundColor: '#e4f4e9' },
mediumRecommendation: { backgroundColor: '#fff3d7' }, mediumRecommendation: { backgroundColor: '#fff3d7' },
criticalRecommendation: { backgroundColor: '#fee9e7' }, criticalRecommendation: { backgroundColor: '#fee9e7' },
unknownRecommendation: { backgroundColor: '#edf1ee' }, unknownRecommendation: { backgroundColor: '#edf1ee' },
recommendationTitle: { recommendationTitle: { fontSize: 18, fontWeight: '800' },
fontSize: 17, recommendationCopy: { color: colors.text, fontSize: 13, lineHeight: 19 },
fontWeight: '800' goodText: { color: colors.success, fontWeight: '800' },
}, mediumText: { color: '#8a5914', fontWeight: '800' },
goodText: { color: colors.success }, criticalText: { color: colors.danger, fontWeight: '800' },
mediumText: { color: '#8a5914' }, unknownText: { color: colors.muted, fontWeight: '800' },
criticalText: { color: colors.danger }, confidencePanel: { borderRadius: 14, gap: 7, padding: 13 },
unknownText: { color: colors.muted }, highConfidence: { backgroundColor: '#f0f8f3' },
recommendationCopy: { reviewConfidence: { backgroundColor: '#fff8e8' },
color: colors.text, lowConfidence: { backgroundColor: '#f2f4f3' },
fontSize: 13, confidenceHeader: { flexDirection: 'row', justifyContent: 'space-between' },
lineHeight: 19 confidenceTitle: { color: colors.text, fontSize: 13, fontWeight: '800' },
}, confidenceValue: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' },
dataPanel: { confidenceTrack: { backgroundColor: '#dfe7e2', borderRadius: 999, height: 7, overflow: 'hidden' },
backgroundColor: colors.surface, confidenceFill: { backgroundColor: colors.primary, borderRadius: 999, height: '100%' },
borderColor: colors.border, confidenceCopy: { color: colors.muted, fontSize: 12, lineHeight: 17 },
borderRadius: 18, notice: { borderRadius: 16, borderWidth: 1, gap: 5, padding: 15 },
borderWidth: 1, criticalNotice: { backgroundColor: '#fff1f0', borderColor: colors.danger },
gap: 8, reviewNotice: { backgroundColor: '#fff9eb', borderColor: colors.warning },
padding: 14 noticeCopy: { color: colors.text, fontSize: 13, lineHeight: 19 },
}, decisionPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 12, padding: 16 },
dataText: { panelEyebrow: { color: colors.primary, fontSize: 11, fontWeight: '800', letterSpacing: 1 },
color: colors.muted, panelTitle: { color: colors.text, fontSize: 18, fontWeight: '800' },
fontSize: 14, factorRow: { borderTopColor: colors.border, borderTopWidth: 1, gap: 4, paddingTop: 10 },
lineHeight: 20 factorHeader: { alignItems: 'center', flexDirection: 'row', gap: 10, justifyContent: 'space-between' },
}, factorLabel: { color: colors.text, fontSize: 14, fontWeight: '800' },
saved: { factorScore: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' },
color: colors.success, servingPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 13, padding: 16 },
fontSize: 14, servingHeader: { alignItems: 'flex-start', flexDirection: 'row', gap: 10 },
fontWeight: '800' servingBasis: { color: colors.muted, fontSize: 12, marginTop: 4 },
}, approximateBadge: { backgroundColor: '#fff3d7', borderRadius: 999, color: '#8a5914', fontSize: 11, fontWeight: '800', paddingHorizontal: 9, paddingVertical: 5 },
savedPanel: { nutrientGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 9 },
backgroundColor: colors.surfaceTint, nutrientTile: { backgroundColor: colors.surfaceTint, borderRadius: 12, flexBasis: '47%', flexGrow: 1, gap: 3, minWidth: 130, padding: 11 },
borderRadius: 14, nutrientLabel: { color: colors.muted, fontSize: 11, fontWeight: '700' },
gap: 6, nutrientValue: { color: colors.text, fontSize: 15, fontWeight: '800' },
padding: 14 missingValue: { color: colors.warning, fontSize: 12 },
}, servingNote: { color: colors.warning, fontSize: 12, lineHeight: 17 },
savedLink: { actionsPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 16, padding: 16 },
color: colors.primary, actionBlock: { gap: 10 },
fontSize: 14, actionTitle: { color: colors.text, fontSize: 16, fontWeight: '800' },
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' }
}); });
+102 -19
View File
@@ -6,11 +6,15 @@ import SecondaryButton from '../components/SecondaryButton';
import AppHeader from '../components/layout/AppHeader'; import AppHeader from '../components/layout/AppHeader';
import ScreenContainer from '../components/layout/ScreenContainer'; import ScreenContainer from '../components/layout/ScreenContainer';
import ShoppingListItem from '../components/list/ShoppingListItem'; import ShoppingListItem from '../components/list/ShoppingListItem';
import { calculateShoppingListWarnings } from '../services/shoppingListWarningsService'; import {
calculateShoppingListNutritionSummary,
calculateShoppingListProductCautions
} from '../services/shoppingListWarningsService';
import { colors } from '../utils/constants'; import { colors } from '../utils/constants';
export default function ShoppingListScreen({ export default function ShoppingListScreen({
shoppingList, shoppingList,
preferences,
lastDeletedItem, lastDeletedItem,
onToggleItem, onToggleItem,
onChangeItemQuantity, onChangeItemQuantity,
@@ -24,7 +28,8 @@ export default function ShoppingListScreen({
const openItems = shoppingList.items.filter((item) => !item.checked).length; const openItems = shoppingList.items.filter((item) => !item.checked).length;
const completedItems = shoppingList.items.length - openItems; const completedItems = shoppingList.items.length - openItems;
const progress = shoppingList.items.length ? completedItems / shoppingList.items.length : 0; 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 ( return (
<ScreenContainer> <ScreenContainer>
@@ -64,23 +69,77 @@ export default function ShoppingListScreen({
) : null} ) : null}
</View> </View>
{dailyWarnings.length > 0 ? ( {shoppingList.items.length > 0 ? (
<View style={styles.warningList}> <View style={styles.nutritionPanel}>
{dailyWarnings.map((warning) => ( <Text style={styles.panelTitle}>Einordnung der Listenmengen</Text>
<View <Text style={styles.panelDisclaimer}>
key={warning.key} Die Summen verwenden nur bekannte Nährwerte und ganze Packungsmengen. Sie beschreiben den Einkaufskorb, nicht was du an einem Tag essen wirst.
style={[ </Text>
styles.warningBox, {nutritionSummary.map((summary) => (
warning.severity === 'critical' ? styles.criticalWarningBox : styles.mediumWarningBox <View key={summary.key} style={styles.nutrientSummary}>
]} <View style={styles.nutrientHeader}>
> <Text style={styles.nutrientTitle}>{summary.label}</Text>
<Text style={[styles.nutrientAmount, summary.exceedsReference ? styles.medium : null]}>
{summary.coverage.coveredItems > 0 ? formatAmount(summary.knownTotal, summary.unit) : 'Keine belastbare Summe'}
</Text>
</View>
{Number.isFinite(summary.limit) ? (
<Text style={styles.referenceText}>
Vergleich: {formatAmount(summary.limit, summary.unit)} ({summary.referenceLabel})
</Text>
) : null}
<View style={styles.coverageTrack}>
<View style={[styles.coverageFill, { width: `${summary.coverage.percentage}%` }]} />
</View>
<Text style={styles.coverageText}>
{summary.coverage.percentage}% Datenabdeckung · {summary.coverage.coveredItems} von {summary.coverage.totalItems} Listenpositionen mit Nährwert und Packungsmenge
</Text>
{summary.exceedsReference ? (
<Text style={styles.warningCopy}>
Die bereits bekannte Listenmenge liegt über dem Vergleichswert. Das ist keine Verzehrprognose.
</Text>
) : !summary.coverage.complete ? (
<Text style={styles.unknownCopy}>Die bekannte Summe ist ein Mindestwert, weil Angaben fehlen.</Text>
) : null}
{summary.missingQuantity.length > 0 ? (
<Text style={styles.unknownCopy}>Packungsmenge fehlt: {summary.missingQuantity.join(', ')}</Text>
) : null}
{summary.missingNutrition.length > 0 ? (
<Text style={styles.unknownCopy}>{summary.label}-Angabe fehlt: {summary.missingNutrition.join(', ')}</Text>
) : null}
{summary.contributors.length > 0 ? (
<View style={styles.contributors}>
<Text style={styles.contributorHeading}>Grösste bekannte Beiträge</Text>
{summary.contributors.slice(0, 3).map((contributor) => (
<View key={contributor.itemId} style={styles.contributorRow}>
<Text style={styles.contributorName}>
{contributor.productName}{contributor.quantity > 1 ? ` × ${contributor.quantity}` : ''}
</Text>
<Text style={styles.contributorAmount}>
{formatAmount(contributor.amount, summary.unit)} · {contributor.sharePercentage}%
</Text>
</View>
))}
</View>
) : null}
</View>
))}
</View>
) : null}
{productCautions.length > 0 ? (
<View style={styles.cautionList}>
<Text style={styles.panelTitle}>Produkte prüfen</Text>
{productCautions.map((caution) => (
<View key={caution.key} style={[
styles.cautionBox,
caution.severity === 'critical' ? styles.criticalWarningBox : styles.mediumWarningBox
]}>
<Text style={[ <Text style={[
styles.warningTitle, styles.warningTitle,
warning.severity === 'critical' ? styles.critical : styles.medium caution.severity === 'critical' ? styles.critical : styles.medium
]}> ]}>{caution.productName} · {caution.label}</Text>
{warning.label}: {formatAmount(warning.total, warning.unit)} von {formatAmount(warning.limit, warning.unit)} <Text style={styles.warningCopy}>{caution.message}</Text>
</Text>
<Text style={styles.warningCopy}>{warning.message}</Text>
</View> </View>
))} ))}
</View> </View>
@@ -188,10 +247,34 @@ const styles = StyleSheet.create({
criticalFill: { criticalFill: {
backgroundColor: colors.danger 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 gap: 10
}, },
warningBox: { cautionBox: {
backgroundColor: colors.surface, backgroundColor: colors.surface,
borderRadius: 16, borderRadius: 16,
borderWidth: 1, borderWidth: 1,
+125 -44
View File
@@ -1,68 +1,149 @@
const dailyLimitRules = [ import { dailyTargets } from './dailyNutritionService.js';
{ import { calculateProductRating } from './ratingService.js';
key: 'caffeine',
label: 'Koffein', export function calculateShoppingListNutritionSummary(shoppingList, preferences = {}) {
limit: 200, const items = shoppingList?.items || [];
unit: 'mg', const targets = dailyTargets(preferences);
nutritionKey: 'caffeineMgPer100g', const rules = [
severity: 'critical',
message: 'Mehr Koffein als der Tagesrichtwert in Shoppinguin. Auf mehrere Tage aufteilen.'
},
{ {
key: 'sugar', key: 'sugar',
label: 'Zucker', label: 'Gesamtzucker',
limit: 50, limit: targets.sugar,
unit: 'g', unit: 'g',
nutritionKey: 'sugarPer100g', nutritionKey: 'sugarPer100g',
severity: 'warning', referenceLabel: 'dein Tagesplanwert'
message: 'Mehr Zucker als der Tagesrichtwert in Shoppinguin. Auf mehrere Tage aufteilen.'
}, },
{ {
key: 'salt', key: 'salt',
label: 'Salz', label: 'Salz',
limit: 5, limit: targets.salt,
unit: 'g', unit: 'g',
nutritionKey: 'saltPer100g', nutritionKey: 'saltPer100g',
severity: 'warning', referenceLabel: 'Orientierungswert pro Tag'
message: 'Mehr Salz als der Tagesrichtwert in Shoppinguin. Auf mehrere Tage aufteilen.'
} }
]; ];
export function calculateShoppingListWarnings(shoppingList) { return rules.map((rule) => summarizeNutrient(items, rule));
return dailyLimitRules }
.map((rule) => {
const total = totalNutrientAmount(shoppingList.items || [], rule); export function calculateShoppingListWarnings(shoppingList, preferences = {}) {
return calculateShoppingListNutritionSummary(shoppingList, preferences)
.filter((summary) => summary.exceedsReference);
}
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.'
});
}
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 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
});
}
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 { return {
...rule, ...rule,
total, knownTotal,
percentage: Math.round((total / rule.limit) * 100) 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
}))
}; };
})
.filter((warning) => warning.total > warning.limit);
} }
function totalNutrientAmount(items, rule) { function reliablePackageGrams(item) {
return items.reduce((sum, item) => { const amount = Number(item.packageQuantityGrams);
const per100g = item.nutrition?.[rule.nutritionKey]; return Number.isFinite(amount) && amount > 0 ? amount : null;
const quantityGrams = itemQuantityGrams(item);
if (typeof per100g !== 'number' || typeof quantityGrams !== 'number') {
return sum;
} }
return sum + (per100g * quantityGrams * item.quantity) / 100; function productFromListItem(item) {
}, 0); return {
id: item.productId || item.id,
name: item.productName,
nutrition: item.nutrition || {},
...(item.productFacts || {})
};
} }
function itemQuantityGrams(item) { function unique(values) {
if (typeof item.packageQuantityGrams === 'number' && item.packageQuantityGrams > 0) { return [...new Set(values.filter(Boolean))];
return item.packageQuantityGrams;
}
if (typeof item.servingQuantityGrams === 'number' && item.servingQuantityGrams > 0) {
return item.servingQuantityGrams;
}
return 100;
} }