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
+308 -262
View File
@@ -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 (
<ScreenContainer>
<AppHeader title="Produkt im Check" subtitle="Bewertung nach deinen Einstellungen" onBack={onBack} />
@@ -91,29 +129,45 @@ export default function ProductDetailScreen({
<View style={styles.copy}>
<Text style={styles.brand}>{product.brand || 'Ohne Marke'}</Text>
<Text style={styles.name}>{product.name}</Text>
<Text style={styles.meta}>
{product.category || 'Produkt'}
</Text>
<Text style={styles.meta}>{product.category || 'Produkt'}</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>
<ProductScoreBadge status={rating.overallStatus} score={rating.overallScore} />
</View>
<View style={[styles.recommendation, styles[`${rating.overallStatus}Recommendation`]]}>
<Text style={[styles.recommendationTitle, styles[`${rating.overallStatus}Text`]]}>{recommendation}</Text>
<Text style={styles.recommendationCopy}>
{recommendationMessage(rating)}
<Text style={[styles.recommendationTitle, styles[`${rating.overallStatus}Text`]]}>
{presentation.recommendation}
</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>
{rating.mainFactors.length > 0 || rating.scoreLimitReasons.length > 0 ? (
<View style={styles.dataPanel}>
<Text style={styles.factorTitle}>Das beeinflusst die Bewertung</Text>
{rating.mainFactors.map((factor) => (
{presentation.criticalNotices.map((notice) => (
<View key={notice.key} style={[
styles.notice,
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 style={styles.factorHeader}>
<Text style={styles.factorLabel}>{factor.label}</Text>
@@ -122,107 +176,177 @@ export default function ProductDetailScreen({
<Text style={styles.dataText}>{factor.message}</Text>
</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>
) : null}
<View style={styles.dataPanel}>
<Text style={styles.factorTitle}>Produktangaben ergänzen</Text>
<Text style={styles.dataText}>{missingFields.length
? `Für eine genauere Bewertung fehlen: ${missingFields.join(', ')}.`
<View style={styles.servingPanel}>
<View style={styles.servingHeader}>
<View style={styles.copy}>
<Text style={styles.panelTitle}>{presentation.serving.approximate ? 'Nährwerte zur Einordnung' : 'Pro Portion'}</Text>
<Text style={styles.servingBasis}>
{presentation.serving.amountLabel} · {presentation.serving.basisLabel}
</Text>
</View>
{presentation.serving.approximate ? <Text style={styles.approximateBadge}>Näherung</Text> : null}
</View>
<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}
</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 ? (
<View style={styles.savedPanel}>
<Text style={rating.hasBlockedAllergen ? styles.savedError : styles.saved}>{savedMessage}</Text>
{!rating.hasBlockedAllergen ? (
<Pressable accessibilityRole="button" onPress={onOpenList}>
<Text style={styles.savedLink}>Einkaufsliste ansehen ›</Text>
</Pressable>
) : null}
</View>
) : null}
</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}
{isChoosingPortion ? (
<PortionSelector
onCancel={() => 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}
/>
) : (
<SecondaryButton label="Gegessene Portion erfassen" onPress={() => {
setConsumptionMessage('');
setIsChoosingPortion(true);
}} />
)}
</View>
</View>
<DisclosureSection
summary={`${Object.keys(rating.categoryScores).length} Kriterien · Details und Begründungen`}
title="Bewertung im Detail"
>
{rating.scoreLimitReasons.length > 0 ? (
<View style={styles.limitPanel}>
<Text style={styles.limitTitle}>Was die Empfehlung begrenzt</Text>
{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}
</View>
</DisclosureSection>
{savedMessage ? (
<View style={styles.savedPanel}>
<Text style={styles.saved}>{savedMessage}</Text>
<Pressable accessibilityRole="button" onPress={onOpenList}>
<Text style={styles.savedLink}>Einkaufsliste ansehen ›</Text>
</Pressable>
</View>
) : null}
<PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} />
{consumptionMessage ? (
<View style={styles.savedPanel}>
<Text style={styles.saved}>{consumptionMessage}</Text>
</View>
) : null}
{isChoosingPortion ? (
<PortionSelector
onCancel={() => 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}
/>
) : (
<SecondaryButton label="Portion heute gegessen" onPress={() => {
setConsumptionMessage('');
setIsChoosingPortion(true);
}} />
)}
<SectionTitle>Ähnliche, bessere Alternativen</SectionTitle>
{suggestionsLoading ? <Text style={styles.dataText}>Passende Produkte werden gesucht ...</Text> : null}
{!suggestionsLoading && suggestions.length === 0 ? <Text style={styles.dataText}>
{suggestionsError ? 'Alternativen konnten gerade nicht geladen werden.'
: alternativeSearchIssue(product, rating) || 'Unter den geprüften Treffern war keine belegbar bessere Alternative derselben Produktart.'}
</Text> : null}
{suggestions.map((item) => <Pressable key={item.product.id} accessibilityRole="button"
onPress={() => onOpenProduct(item.product)} style={styles.suggestionCard}>
<View style={styles.suggestionRow}>
<ProductImage imageUrl={item.product.imageUrl} productName={item.product.name} />
<View style={styles.suggestionBody}>
<View style={styles.factorHeader}>
<Text style={styles.suggestionName}>{item.product.name}</Text>
<ProductScoreBadge status={item.rating.overallStatus} score={item.rating.overallScore} />
<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}>
<ProductImage imageUrl={item.product.imageUrl} productName={item.product.name} />
<View style={styles.suggestionBody}>
<View style={styles.factorHeader}>
<Text style={styles.suggestionName}>{item.product.name}</Text>
<ProductScoreBadge status={item.rating.overallStatus} score={item.rating.overallScore} />
</View>
<Text style={styles.dataText}>{item.reason}</Text>
<Text style={styles.suggestionLink}>Produkt ansehen ›</Text>
</View>
</View>
<Text style={styles.dataText}>{item.reason}</Text>
<Text style={styles.suggestionLink}>Produkt ansehen ›</Text>
</View>
</View>
</Pressable>)}
<SecondaryButton label="Weitere Alternativen ansehen" onPress={() => onShowAlternatives(product)} />
</Pressable>
))}
<SecondaryButton label="Weitere Alternativen ansehen" onPress={() => onShowAlternatives(product)} />
</DisclosureSection>
<SectionTitle>Bewertungskriterien</SectionTitle>
{Object.entries(rating.categoryScores).map(([category, categoryRating]) => (
<RatingCategoryRow
category={category}
key={category}
onPress={() => onShowRatingCriteria(product, category)}
rating={categoryRating}
/>
))}
<SectionTitle>Umweltwirkung</SectionTitle>
<View style={styles.dataPanel}>
<DisclosureSection
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' ? (
<>
<Text style={styles.dataText}>
CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg
</Text>
<Text style={styles.dataText}>CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg</Text>
<Text style={styles.dataText}>
{footprint.status === 'product-specific' ? 'Produktspezifische Angabe aus Open Food Facts.'
: `Schätzung anhand vergleichbarer Lebensmittel: ${footprint.referenceCategory}. AGRIBALYSE-Durchschnitt, keine Messung dieses Markenprodukts.`}
</Text>
{typeof footprint.packageKgCo2e === 'number' ? (
<Text style={styles.dataText}>
Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e
</Text>
<Text style={styles.dataText}>Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e</Text>
) : null}
<Text style={styles.dataText}>
Quelle: {footprint.source === 'AGRIBALYSE' ? 'ADEME / ' : ''}{footprint.source}{footprint.datasetVersion ? ` ${footprint.datasetVersion}` : ''}
@@ -236,7 +360,7 @@ export default function ProductDetailScreen({
<Text style={styles.dataText}>Landnutzung: {formatIndicator(footprint.indicators?.landUse)}</Text>
<Text style={styles.dataText}>Wasserknappheit: {formatIndicator(footprint.indicators?.waterScarcity)}</Text>
<Text style={styles.dataText}>Gesamtwirkung (EF): {formatIndicator(footprint.indicators?.singleScore)}</Text>
<Text style={styles.dataText}>Lebenszyklus bis zum verzehrbaren Lebensmittel; Transport und Verpackung sind im Datensatz enthalten. Diese Indikatoren sind keine CO₂-Werte.</Text>
<Text style={styles.dataText}>Lebenszyklus bis zum verzehrbaren Lebensmittel; Transport und Verpackung sind enthalten. Diese Indikatoren sind keine CO₂-Werte.</Text>
</>
) : null}
</>
@@ -246,10 +370,12 @@ export default function ProductDetailScreen({
{(product.sustainability?.sellingCountries || []).length > 0 ? (
<Text style={styles.dataText}>Verkaufsländer: {product.sustainability.sellingCountries.map(formatCountryTag).join(', ')}</Text>
) : null}
</View>
</DisclosureSection>
<SectionTitle>Produktdaten</SectionTitle>
<View style={styles.dataPanel}>
<DisclosureSection
summary="Barcode, Zutaten, Allergene und Nutri-Score"
title="Produktdaten"
>
<Text style={styles.dataText}>Barcode: {product.barcode}</Text>
<Text style={styles.dataText}>Zutaten: {(product.ingredients || []).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'}
{rating.categoryScores.nutrition.nutriScoreSource === 'calculated' ? ' (von der App berechnet)' : rating.categoryScores.nutrition.nutriScore ? ' (Open Food Facts)' : ''}
</Text>
</View>
</DisclosureSection>
</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) {
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' }
});
+102 -19
View File
@@ -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 (
<ScreenContainer>
@@ -64,23 +69,77 @@ export default function ShoppingListScreen({
) : null}
</View>
{dailyWarnings.length > 0 ? (
<View style={styles.warningList}>
{dailyWarnings.map((warning) => (
<View
key={warning.key}
style={[
styles.warningBox,
warning.severity === 'critical' ? styles.criticalWarningBox : styles.mediumWarningBox
]}
>
{shoppingList.items.length > 0 ? (
<View style={styles.nutritionPanel}>
<Text style={styles.panelTitle}>Einordnung der Listenmengen</Text>
<Text style={styles.panelDisclaimer}>
Die Summen verwenden nur bekannte Nährwerte und ganze Packungsmengen. Sie beschreiben den Einkaufskorb, nicht was du an einem Tag essen wirst.
</Text>
{nutritionSummary.map((summary) => (
<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={[
styles.warningTitle,
warning.severity === 'critical' ? styles.critical : styles.medium
]}>
{warning.label}: {formatAmount(warning.total, warning.unit)} von {formatAmount(warning.limit, warning.unit)}
</Text>
<Text style={styles.warningCopy}>{warning.message}</Text>
caution.severity === 'critical' ? styles.critical : styles.medium
]}>{caution.productName} · {caution.label}</Text>
<Text style={styles.warningCopy}>{caution.message}</Text>
</View>
))}
</View>
@@ -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,
+136 -55
View File
@@ -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))];
}