This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Alert, Linking, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, Linking, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import PrimaryButton from '../components/PrimaryButton';
|
||||
import SecondaryButton from '../components/SecondaryButton';
|
||||
@@ -10,8 +10,8 @@ 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 { colors } from '../utils/constants';
|
||||
import { formatPrice } from '../utils/formatPrice';
|
||||
|
||||
export default function ProductDetailScreen({
|
||||
product,
|
||||
@@ -19,37 +19,38 @@ export default function ProductDetailScreen({
|
||||
onBack,
|
||||
onAddToList,
|
||||
onOpenList,
|
||||
onSaveManualPrice,
|
||||
onEditProduct,
|
||||
onShowRatingCriteria,
|
||||
onShowAlternatives,
|
||||
shoppingList
|
||||
onOpenProduct,
|
||||
productCache,
|
||||
shoppingList,
|
||||
dailyLog,
|
||||
onRecordConsumption
|
||||
}) {
|
||||
const [savedMessage, setSavedMessage] = useState('');
|
||||
const [manualPrice, setManualPrice] = useState('');
|
||||
const [priceError, setPriceError] = useState('');
|
||||
const hasProductPrice = typeof product.price === 'number';
|
||||
const currency = product.currency || preferences.currency;
|
||||
const parsedManualPrice = parseManualPrice(manualPrice);
|
||||
const pricedProduct = useMemo(() => ({
|
||||
...product,
|
||||
currency,
|
||||
price: hasProductPrice ? product.price : parsedManualPrice
|
||||
}), [currency, hasProductPrice, parsedManualPrice, product]);
|
||||
const rating = useMemo(() => calculateProductRating(pricedProduct, preferences, { shoppingList }), [pricedProduct, preferences, shoppingList]);
|
||||
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 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';
|
||||
|
||||
function addToList() {
|
||||
if (!hasProductPrice && manualPrice.trim() && parsedManualPrice === undefined) {
|
||||
setSavedMessage('');
|
||||
setPriceError('Bitte gib einen gültigen Preis ein oder lasse das Feld leer.');
|
||||
return;
|
||||
}
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setSuggestionsLoading(true);
|
||||
setSuggestionsError(false);
|
||||
findAlternatives(product, preferences, productCache, { dailyLog }, { preview: true })
|
||||
.then((results) => { if (active) setSuggestions(results); })
|
||||
.catch(() => { if (active) { setSuggestions([]); setSuggestionsError(true); } })
|
||||
.finally(() => { if (active) setSuggestionsLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [product, preferences, productCache, dailyLog]);
|
||||
|
||||
function addToList() {
|
||||
if (rating.hasBlockedAllergen) {
|
||||
setSavedMessage('Dieses Produkt enthält ein Allergen aus deinem Profil und wurde nicht hinzugefügt.');
|
||||
return;
|
||||
@@ -72,12 +73,7 @@ export default function ProductDetailScreen({
|
||||
}
|
||||
|
||||
function saveToList() {
|
||||
if (!hasProductPrice && typeof pricedProduct.price === 'number') {
|
||||
onSaveManualPrice(pricedProduct, pricedProduct.price);
|
||||
}
|
||||
|
||||
onAddToList(pricedProduct);
|
||||
setPriceError('');
|
||||
onAddToList(product);
|
||||
setSavedMessage('Zur Einkaufsliste hinzugefügt.');
|
||||
}
|
||||
|
||||
@@ -92,7 +88,7 @@ export default function ProductDetailScreen({
|
||||
<Text style={styles.brand}>{product.brand || 'Ohne Marke'}</Text>
|
||||
<Text style={styles.name}>{product.name}</Text>
|
||||
<Text style={styles.meta}>
|
||||
{product.category || 'Produkt'} · {formatPrice(pricedProduct.price, currency)}
|
||||
{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}
|
||||
@@ -112,13 +108,20 @@ export default function ProductDetailScreen({
|
||||
|
||||
{rating.mainFactors.length > 0 || rating.scoreLimitReasons.length > 0 ? (
|
||||
<View style={styles.dataPanel}>
|
||||
<Text style={styles.factorTitle}>Wichtigste Einflüsse auf die App-Bewertung</Text>
|
||||
{rating.scoreLimitReasons.map((reason) => <Text key={reason} style={styles.dataText}>{reason}</Text>)}
|
||||
<Text style={styles.factorTitle}>Das beeinflusst die Bewertung</Text>
|
||||
{rating.mainFactors.map((factor) => (
|
||||
<Text key={factor.category} style={styles.dataText}>
|
||||
{factor.label}: {factor.score}/100 · {factor.message}
|
||||
</Text>
|
||||
<View key={factor.category} style={styles.factorRow}>
|
||||
<View style={styles.factorHeader}>
|
||||
<Text style={styles.factorLabel}>{factor.label}</Text>
|
||||
<Text style={styles.factorScore}>{factor.score}/100</Text>
|
||||
</View>
|
||||
<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}
|
||||
|
||||
@@ -130,38 +133,12 @@ export default function ProductDetailScreen({
|
||||
<Text style={styles.dataText}>Übertrage Werte von der Verpackung. Fehlende Werte werden nicht geschätzt.</Text>
|
||||
<SecondaryButton label="Angaben ergänzen oder korrigieren" onPress={() => onEditProduct(product)} />
|
||||
{/^\d{8,14}$/.test(product.barcode || '') ? (
|
||||
<Pressable accessibilityRole="link" onPress={() => Linking.openURL(`https://world.openfoodfacts.org/product/${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>
|
||||
|
||||
{!hasProductPrice ? (
|
||||
<View style={styles.pricePanel}>
|
||||
<Text style={styles.priceTitle}>Ladenpreis ergänzen</Text>
|
||||
<Text style={styles.priceCopy}>
|
||||
Optional. Ohne Preis kannst du das Produkt speichern; die Einkaufssumme bleibt dann unvollständig.
|
||||
</Text>
|
||||
<View style={styles.priceInputRow}>
|
||||
<Text style={styles.currency}>{currency}</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Ladenpreis"
|
||||
keyboardType="decimal-pad"
|
||||
onChangeText={(value) => {
|
||||
setManualPrice(value);
|
||||
setPriceError('');
|
||||
setSavedMessage('');
|
||||
}}
|
||||
placeholder="z. B. 3.50"
|
||||
placeholderTextColor={colors.muted}
|
||||
style={styles.priceInput}
|
||||
value={manualPrice}
|
||||
/>
|
||||
</View>
|
||||
{priceError ? <Text style={styles.errorText}>{priceError}</Text> : null}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{savedMessage ? (
|
||||
<View style={styles.savedPanel}>
|
||||
<Text style={styles.saved}>{savedMessage}</Text>
|
||||
@@ -171,14 +148,37 @@ export default function ProductDetailScreen({
|
||||
</View>
|
||||
) : null}
|
||||
<PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} />
|
||||
<SecondaryButton label="Bessere Alternativen suchen" onPress={() => onShowAlternatives(pricedProduct)} />
|
||||
<SecondaryButton label="Portion heute gegessen" onPress={() => { onRecordConsumption(product); setSavedMessage('Portion im Tagesprotokoll erfasst.'); }} />
|
||||
<Text style={styles.dataText}>Es wird die angegebene Portionsgrösse verwendet, sonst die Packungsmenge oder 100 g. Nur tatsächlich Gegessenes erfassen.</Text>
|
||||
|
||||
<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} />
|
||||
</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)} />
|
||||
|
||||
<SectionTitle>Bewertungskriterien</SectionTitle>
|
||||
{Object.entries(rating.categoryScores).map(([category, categoryRating]) => (
|
||||
<RatingCategoryRow
|
||||
category={category}
|
||||
key={category}
|
||||
onPress={() => onShowRatingCriteria(pricedProduct, category)}
|
||||
onPress={() => onShowRatingCriteria(product, category)}
|
||||
rating={categoryRating}
|
||||
/>
|
||||
))}
|
||||
@@ -244,7 +244,6 @@ function recommendationMessage(rating) {
|
||||
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.budgetReviewRequired) return 'Für die Budgetprüfung fehlen Preise. Ergänze den Ladenpreis oder offene Listenpreise.';
|
||||
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.';
|
||||
@@ -260,14 +259,20 @@ function missingProductFields(product, preferences) {
|
||||
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');
|
||||
}
|
||||
if (typeof product.price !== 'number' && Number.isFinite(preferences.maxBudgetPerShoppingTrip)) fields.push('Preis');
|
||||
return fields.slice(0, 6);
|
||||
return fields.slice(0, 8);
|
||||
}
|
||||
|
||||
function manualFieldNames(overrides) {
|
||||
@@ -276,24 +281,14 @@ function manualFieldNames(overrides) {
|
||||
return [
|
||||
...Object.keys(overrides).filter((key) => key !== 'nutrition').map((key) => names[key]).filter(Boolean),
|
||||
...Object.keys(overrides.nutrition || {}).map((key) =>
|
||||
({ energyKjPer100g: 'Energie', sugarPer100g: 'Zucker', saturatedFatPer100g: 'gesättigte Fettsäuren',
|
||||
({ energyKjPer100g: 'Energie', sugarPer100g: 'Zucker', carbohydratesPer100g: 'Kohlenhydrate',
|
||||
vitaminB12MicrogramsPer100g: 'Vitamin B12', saturatedFatPer100g: 'gesättigte Fettsäuren',
|
||||
saltPer100g: 'Salz', proteinPer100g: 'Protein', fiberPer100g: 'Ballaststoffe',
|
||||
fruitVegetableLegumePercent: 'Frucht- und Gemüseanteil', hasNonNutritiveSweeteners: 'Süssstoffe' })[key]
|
||||
).filter(Boolean)
|
||||
];
|
||||
}
|
||||
|
||||
function parseManualPrice(value) {
|
||||
const normalizedValue = value.trim().replace(',', '.');
|
||||
const parsedValue = Number(normalizedValue);
|
||||
|
||||
if (!normalizedValue || !Number.isFinite(parsedValue) || parsedValue <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return Math.round(parsedValue * 100) / 100;
|
||||
}
|
||||
|
||||
function sourceLabel(source) {
|
||||
const labels = {
|
||||
cache: 'Quelle: lokaler Cache',
|
||||
@@ -339,7 +334,18 @@ 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,
|
||||
@@ -407,49 +413,6 @@ const styles = StyleSheet.create({
|
||||
fontSize: 13,
|
||||
lineHeight: 19
|
||||
},
|
||||
pricePanel: {
|
||||
backgroundColor: colors.surface,
|
||||
borderColor: colors.border,
|
||||
borderRadius: 18,
|
||||
borderWidth: 1,
|
||||
gap: 10,
|
||||
padding: 16
|
||||
},
|
||||
priceTitle: {
|
||||
color: colors.text,
|
||||
fontSize: 17,
|
||||
fontWeight: '800'
|
||||
},
|
||||
priceCopy: {
|
||||
color: colors.muted,
|
||||
fontSize: 14,
|
||||
lineHeight: 20
|
||||
},
|
||||
priceInputRow: {
|
||||
alignItems: 'center',
|
||||
flexDirection: 'row',
|
||||
gap: 10
|
||||
},
|
||||
currency: {
|
||||
color: colors.muted,
|
||||
fontSize: 16,
|
||||
fontWeight: '800'
|
||||
},
|
||||
priceInput: {
|
||||
borderColor: colors.border,
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
color: colors.text,
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 10
|
||||
},
|
||||
errorText: {
|
||||
color: colors.danger,
|
||||
fontSize: 13,
|
||||
fontWeight: '800'
|
||||
},
|
||||
dataPanel: {
|
||||
backgroundColor: colors.surface,
|
||||
borderColor: colors.border,
|
||||
|
||||
Reference in New Issue
Block a user