This commit is contained in:
@@ -1,117 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
|
||||
import { budgetPeriodLabels, colors } from '../../utils/constants';
|
||||
|
||||
const budgetPeriods = ['day', 'week', 'month', 'shoppingTrip'];
|
||||
|
||||
export default function BudgetInput({ value, currency, period, onChangePeriod, onChangeValue }) {
|
||||
const [inputValue, setInputValue] = useState(String(value ?? ''));
|
||||
|
||||
function updateValue(text) {
|
||||
setInputValue(text);
|
||||
const parsedValue = Number(text.replace(',', '.'));
|
||||
onChangeValue(text.trim() && Number.isFinite(parsedValue) && parsedValue > 0 ? parsedValue : undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.wrap}>
|
||||
<Text style={styles.label}>Betrag (optional)</Text>
|
||||
<Text style={styles.hint}>Ohne Budget bleibt die Preisbewertung offen.</Text>
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.currency}>{currency}</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Budgetbetrag"
|
||||
keyboardType="decimal-pad"
|
||||
onChangeText={updateValue}
|
||||
placeholder="z. B. 45.00"
|
||||
placeholderTextColor={colors.muted}
|
||||
style={styles.input}
|
||||
value={inputValue}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.periodGrid}>
|
||||
{budgetPeriods.map((option) => {
|
||||
const isActive = period === option;
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: isActive }}
|
||||
key={option}
|
||||
onPress={() => onChangePeriod(option)}
|
||||
style={[styles.periodChip, isActive ? styles.activePeriodChip : null]}
|
||||
>
|
||||
<Text style={[styles.periodText, isActive ? styles.activePeriodText : null]}>
|
||||
pro {budgetPeriodLabels[option]}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
wrap: {
|
||||
gap: 10
|
||||
},
|
||||
hint: {
|
||||
color: colors.muted,
|
||||
fontSize: 13,
|
||||
lineHeight: 18
|
||||
},
|
||||
label: {
|
||||
color: colors.text,
|
||||
fontSize: 15,
|
||||
fontWeight: '800'
|
||||
},
|
||||
row: {
|
||||
alignItems: 'center',
|
||||
flexDirection: 'row',
|
||||
gap: 10
|
||||
},
|
||||
currency: {
|
||||
color: colors.muted,
|
||||
fontSize: 16,
|
||||
fontWeight: '800'
|
||||
},
|
||||
input: {
|
||||
borderColor: colors.border,
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
color: colors.text,
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 10
|
||||
},
|
||||
periodGrid: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8
|
||||
},
|
||||
periodChip: {
|
||||
alignItems: 'center',
|
||||
borderColor: colors.border,
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
flexGrow: 1,
|
||||
minHeight: 44,
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 9
|
||||
},
|
||||
activePeriodChip: {
|
||||
backgroundColor: colors.primary,
|
||||
borderColor: colors.primary
|
||||
},
|
||||
periodText: {
|
||||
color: colors.text,
|
||||
fontSize: 13,
|
||||
fontWeight: '800'
|
||||
},
|
||||
activePeriodText: {
|
||||
color: colors.surface
|
||||
}
|
||||
});
|
||||
@@ -1,30 +1,8 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import { colors } from '../../utils/constants';
|
||||
import { formatPrice } from '../../utils/formatPrice';
|
||||
|
||||
export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQuantity, onUpdatePrice }) {
|
||||
const [priceText, setPriceText] = useState(priceToInputValue(item.estimatedPrice));
|
||||
const [priceError, setPriceError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
setPriceText(priceToInputValue(item.estimatedPrice));
|
||||
}, [item.estimatedPrice]);
|
||||
|
||||
function savePrice() {
|
||||
if (!priceText.trim() && typeof item.estimatedPrice !== 'number') return;
|
||||
const parsedPrice = parsePrice(priceText);
|
||||
|
||||
if (parsedPrice === undefined) {
|
||||
setPriceError('Preis prüfen');
|
||||
return;
|
||||
}
|
||||
|
||||
setPriceError('');
|
||||
onUpdatePrice(item.id, parsedPrice);
|
||||
}
|
||||
|
||||
export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQuantity }) {
|
||||
return (
|
||||
<View style={[styles.row, item.checked && styles.completedRow]}>
|
||||
<Pressable accessibilityLabel={`${item.productName} ${item.checked ? 'als offen markieren' : 'abhaken'}`} accessibilityRole="checkbox" accessibilityState={{ checked: item.checked }} onPress={onToggle} style={[styles.checkbox, item.checked ? styles.checked : null]}>
|
||||
@@ -32,7 +10,7 @@ export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQua
|
||||
</Pressable>
|
||||
<View style={styles.copy}>
|
||||
<Text style={[styles.name, item.checked ? styles.done : null]}>{item.productName}</Text>
|
||||
<Text style={styles.meta}>{item.quantity} × {formatPrice(item.estimatedPrice, item.currency || 'CHF')}{item.quantity > 1 && typeof item.estimatedPrice === 'number' ? ` · ${formatPrice(item.estimatedPrice * item.quantity, item.currency || 'CHF')}` : ''}</Text>
|
||||
{item.packageQuantityLabel ? <Text style={styles.meta}>{item.packageQuantityLabel}</Text> : null}
|
||||
<View style={styles.quantityRow}>
|
||||
<Text style={styles.quantityLabel}>Menge</Text>
|
||||
<Pressable accessibilityLabel={`Menge von ${item.productName} verringern`} accessibilityRole="button" accessibilityState={{ disabled: item.quantity <= 1 }} disabled={item.quantity <= 1} onPress={() => onChangeQuantity(-1)} style={[styles.quantityButton, item.quantity <= 1 && styles.disabledButton]}>
|
||||
@@ -43,24 +21,6 @@ export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQua
|
||||
<Text style={styles.quantityButtonText}>+</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<View style={styles.priceRow}>
|
||||
<Text style={styles.currency}>{item.currency || 'CHF'}</Text>
|
||||
<TextInput
|
||||
accessibilityLabel={`Preis für ${item.productName}`}
|
||||
keyboardType="decimal-pad"
|
||||
onBlur={savePrice}
|
||||
onChangeText={(value) => {
|
||||
setPriceText(value);
|
||||
setPriceError('');
|
||||
}}
|
||||
onSubmitEditing={savePrice}
|
||||
placeholder="0.00"
|
||||
placeholderTextColor={colors.muted}
|
||||
style={styles.priceInput}
|
||||
value={priceText}
|
||||
/>
|
||||
</View>
|
||||
{priceError ? <Text style={styles.errorText}>{priceError}</Text> : null}
|
||||
</View>
|
||||
<Pressable accessibilityLabel={`${item.productName} löschen`} accessibilityRole="button" onPress={onDelete} style={styles.deleteButton}>
|
||||
<Text style={styles.deleteText}>Löschen</Text>
|
||||
@@ -69,21 +29,6 @@ export default function ShoppingListItem({ item, onToggle, onDelete, onChangeQua
|
||||
);
|
||||
}
|
||||
|
||||
function priceToInputValue(price) {
|
||||
return typeof price === 'number' ? price.toFixed(2) : '';
|
||||
}
|
||||
|
||||
function parsePrice(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;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
completedRow: { backgroundColor: '#f2f7f4' },
|
||||
quantityRow: { alignItems: 'center', flexDirection: 'row', gap: 8, marginTop: 10 },
|
||||
@@ -135,33 +80,6 @@ const styles = StyleSheet.create({
|
||||
fontSize: 13,
|
||||
marginTop: 3
|
||||
},
|
||||
priceRow: {
|
||||
alignItems: 'center',
|
||||
flexDirection: 'row',
|
||||
gap: 8,
|
||||
marginTop: 10
|
||||
},
|
||||
currency: {
|
||||
color: colors.muted,
|
||||
fontSize: 13,
|
||||
fontWeight: '800'
|
||||
},
|
||||
priceInput: {
|
||||
borderColor: colors.border,
|
||||
borderRadius: 10,
|
||||
borderWidth: 1,
|
||||
color: colors.text,
|
||||
fontSize: 14,
|
||||
minWidth: 92,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 7
|
||||
},
|
||||
errorText: {
|
||||
color: colors.danger,
|
||||
fontSize: 12,
|
||||
fontWeight: '800',
|
||||
marginTop: 4
|
||||
},
|
||||
deleteButton: {
|
||||
justifyContent: 'center',
|
||||
minHeight: 44,
|
||||
|
||||
@@ -10,7 +10,7 @@ export default function AlternativeProductCard({ item, onChoose, onOpen }) {
|
||||
<ProductCard product={item.product} rating={item.rating} onPress={onOpen} />
|
||||
<Text style={styles.reason}>{item.reason}</Text>
|
||||
<PrimaryButton
|
||||
label={item.requiresAllergenCheck ? 'Allergene prüfen' : typeof item.product.price === 'number' ? 'Zur Liste hinzufügen' : 'Produkt ansehen'}
|
||||
label={item.requiresAllergenCheck ? 'Allergene prüfen' : 'Zur Liste hinzufügen'}
|
||||
onPress={onChoose}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import { colors } from '../../utils/constants';
|
||||
import { formatPrice } from '../../utils/formatPrice';
|
||||
import ProductImage from './ProductImage';
|
||||
import ProductScoreBadge from './ProductScoreBadge';
|
||||
|
||||
@@ -13,7 +12,7 @@ export default function ProductCard({ product, rating, onPress }) {
|
||||
<View style={styles.copy}>
|
||||
<Text style={styles.name}>{product.name}</Text>
|
||||
<Text style={styles.meta}>
|
||||
{product.brand || 'Ohne Marke'} · {formatPrice(product.price, product.currency)}
|
||||
{product.brand || 'Ohne Marke'}
|
||||
</Text>
|
||||
<Text style={styles.note}>
|
||||
{product.category || 'Produkt'} · Barcode {product.barcode}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Image, StyleSheet, Text, View } from 'react-native';
|
||||
import { useState } from 'react';
|
||||
import { ActivityIndicator, Image, StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import { colors } from '../../utils/constants';
|
||||
|
||||
@@ -15,13 +16,30 @@ export default function ProductImage({ imageUrl, productName, size = 'card' }) {
|
||||
);
|
||||
}
|
||||
|
||||
return <RemoteProductImage key={imageUrl} imageUrl={imageUrl} productName={productName} size={size} style={style} />;
|
||||
}
|
||||
|
||||
function RemoteProductImage({ imageUrl, productName, size, style }) {
|
||||
const [status, setStatus] = useState('loading');
|
||||
|
||||
return (
|
||||
<Image
|
||||
accessibilityIgnoresInvertColors
|
||||
resizeMode="contain"
|
||||
source={{ uri: imageUrl }}
|
||||
style={[styles.image, style]}
|
||||
/>
|
||||
<View style={[styles.imageFrame, style]}>
|
||||
{status === 'error' ? (
|
||||
<Text style={[styles.placeholderText, size === 'large' ? styles.largePlaceholderText : null]}>
|
||||
{initialsFromName(productName)}
|
||||
</Text>
|
||||
) : (
|
||||
<Image
|
||||
accessibilityIgnoresInvertColors
|
||||
onError={() => setStatus('error')}
|
||||
onLoad={() => setStatus('loaded')}
|
||||
resizeMode="contain"
|
||||
source={{ uri: imageUrl }}
|
||||
style={[styles.image, status === 'loading' ? styles.hiddenImage : null]}
|
||||
/>
|
||||
)}
|
||||
{status === 'loading' ? <ActivityIndicator color={colors.primary} size="small" /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,10 +53,20 @@ function initialsFromName(name) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
image: {
|
||||
backgroundColor: colors.surface,
|
||||
imageFrame: {
|
||||
alignItems: 'center',
|
||||
backgroundColor: '#eef3ef',
|
||||
borderColor: colors.border,
|
||||
borderWidth: 1
|
||||
borderWidth: 1,
|
||||
justifyContent: 'center',
|
||||
overflow: 'hidden'
|
||||
},
|
||||
image: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: colors.surface
|
||||
},
|
||||
hiddenImage: {
|
||||
opacity: 0
|
||||
},
|
||||
card: {
|
||||
borderRadius: 8,
|
||||
|
||||
@@ -5,10 +5,10 @@ import ProductScoreBadge from './ProductScoreBadge';
|
||||
|
||||
const labels = {
|
||||
allergies: 'Allergien',
|
||||
budget: 'Budget',
|
||||
ingredients: 'Zutaten',
|
||||
nutrition: 'Ernährung',
|
||||
sustainability: 'Nachhaltigkeit'
|
||||
sustainability: 'Nachhaltigkeit',
|
||||
goals: 'Deine Ziele'
|
||||
};
|
||||
|
||||
export default function RatingCategoryRow({ category, rating, onPress }) {
|
||||
@@ -18,8 +18,10 @@ export default function RatingCategoryRow({ category, rating, onPress }) {
|
||||
<Container accessibilityRole={onPress ? 'button' : undefined} onPress={onPress} style={styles.row}>
|
||||
<View style={styles.copy}>
|
||||
<Text style={styles.title}>{labels[category] || category}</Text>
|
||||
<Text style={styles.message}>{rating.message}</Text>
|
||||
{(rating.missingData || []).map((message) => (
|
||||
<Text style={styles.message}>{rating.summary || rating.message}</Text>
|
||||
{category === 'goals' && rating.missingData?.length ? (
|
||||
<Text style={styles.missingData}>{rating.missingData.length} Nährwertangaben fehlen · Details ansehen</Text>
|
||||
) : (rating.missingData || []).map((message) => (
|
||||
<Text key={message} style={styles.missingData}>{message}</Text>
|
||||
))}
|
||||
</View>
|
||||
|
||||
@@ -5,12 +5,13 @@ import PrimaryButton from '../components/PrimaryButton';
|
||||
import AppHeader from '../components/layout/AppHeader';
|
||||
import ScreenContainer from '../components/layout/ScreenContainer';
|
||||
import AlternativeProductCard from '../components/product/AlternativeProductCard';
|
||||
import { findAlternatives } from '../services/alternativesService';
|
||||
import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService';
|
||||
import { calculateProductRating } from '../services/ratingService';
|
||||
import { colors } from '../utils/constants';
|
||||
|
||||
const DISPLAY_ALTERNATIVE_LIMIT = 8;
|
||||
|
||||
export default function AlternativesScreen({ product, preferences, productCache, shoppingList, onBack, onChoose, onOpenProduct }) {
|
||||
export default function AlternativesScreen({ product, preferences, productCache, shoppingList, dailyLog, onBack, onChoose, onOpenProduct }) {
|
||||
const [alternatives, setAlternatives] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [searchError, setSearchError] = useState('');
|
||||
@@ -23,7 +24,7 @@ export default function AlternativesScreen({ product, preferences, productCache,
|
||||
setIsLoading(true);
|
||||
setSearchError('');
|
||||
try {
|
||||
const results = await findAlternatives(product, preferences, productCache, { shoppingList });
|
||||
const results = await findAlternatives(product, preferences, productCache, { shoppingList, dailyLog });
|
||||
if (isMounted) setAlternatives(results);
|
||||
} catch (error) {
|
||||
if (isMounted) {
|
||||
@@ -39,19 +40,19 @@ export default function AlternativesScreen({ product, preferences, productCache,
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [product, preferences, productCache, shoppingList, retryCount]);
|
||||
}, [product, preferences, productCache, shoppingList, dailyLog, retryCount]);
|
||||
|
||||
return (
|
||||
<ScreenContainer>
|
||||
<AppHeader
|
||||
title="Alternativen"
|
||||
subtitle={`Gesündere Optionen für ${product.name}`}
|
||||
subtitle={`Ähnliche, besser bewertete Produkte für ${product.name}`}
|
||||
onBack={onBack}
|
||||
/>
|
||||
|
||||
{isLoading ? <Text style={styles.note}>{preferences.offlineModeEnabled
|
||||
? 'Gespeicherte Produkte werden verglichen...'
|
||||
: 'Open Food Facts wird nach gesünderen Produkten derselben Kategorie durchsucht...'}</Text> : null}
|
||||
: 'Open Food Facts wird nach besseren Produkten derselben Produktart durchsucht...'}</Text> : null}
|
||||
{searchError ? <Text style={styles.note}>{searchError}</Text> : null}
|
||||
{searchError ? <PrimaryButton label="Erneut suchen" onPress={() => setRetryCount((count) => count + 1)} /> : null}
|
||||
{!isLoading && alternatives.length > 0 ? (
|
||||
@@ -61,8 +62,9 @@ export default function AlternativesScreen({ product, preferences, productCache,
|
||||
<View style={styles.empty}>
|
||||
<Text style={styles.emptyTitle}>Keine Alternative gefunden</Text>
|
||||
<Text style={styles.emptyCopy}>{preferences.offlineModeEnabled
|
||||
? 'Im lokalen Cache ist noch keine gesündere Option aus derselben Kategorie gespeichert. Deaktiviere den Offline-Modus für die Online-Suche.'
|
||||
: 'In dieser Kategorie wurde keine gesündere oder insgesamt besser bewertete Option mit ausreichenden Angaben gefunden.'}</Text>
|
||||
? 'Im lokalen Cache ist noch keine bessere Option derselben Produktart gespeichert. Deaktiviere den Offline-Modus für die Online-Suche.'
|
||||
: alternativeSearchIssue(product, calculateProductRating(product, preferences, { shoppingList, dailyLog }))
|
||||
|| 'Unter den geprüften Open Food Facts Treffern war keine belegbar bessere Option derselben Produktart mit ausreichenden Angaben.'}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
@@ -71,7 +73,7 @@ export default function AlternativesScreen({ product, preferences, productCache,
|
||||
item={item}
|
||||
key={item.product.id}
|
||||
onChoose={() => {
|
||||
if (!item.requiresAllergenCheck && typeof item.product.price === 'number') {
|
||||
if (!item.requiresAllergenCheck) {
|
||||
onChoose(item.product);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@ import ScreenContainer from '../components/layout/ScreenContainer';
|
||||
import SectionTitle from '../components/layout/SectionTitle';
|
||||
import ProductCard from '../components/product/ProductCard';
|
||||
import { calculateProductRating } from '../services/ratingService';
|
||||
import { dailyTargets, dailyTotals } from '../services/dailyNutritionService';
|
||||
import { colors } from '../utils/constants';
|
||||
import { formatPrice } from '../utils/formatPrice';
|
||||
|
||||
export default function HomeScreen({ preferences, recentProducts, shoppingList, onStartScan, onOpenProduct, onOpenList }) {
|
||||
export default function HomeScreen({ preferences, recentProducts, shoppingList, dailyLog, onUndoConsumption, onStartScan, onOpenProduct, onOpenList }) {
|
||||
const totals = dailyTotals(dailyLog);
|
||||
const targets = dailyTargets(preferences);
|
||||
const frequentProducts = [...recentProducts]
|
||||
.filter((product) => (product.scanCount || 0) > 1)
|
||||
.sort((a, b) => (b.scanCount || 0) - (a.scanCount || 0))
|
||||
@@ -33,6 +35,20 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList,
|
||||
<PrimaryButton label="Produkt scannen" onPress={onStartScan} tone="light" />
|
||||
</View>
|
||||
|
||||
<View style={styles.emptyState}>
|
||||
<Text style={styles.emptyTitle}>Heute erfasst</Text>
|
||||
<Text style={styles.emptyCopy}>Protein: {Math.round(totals.protein)} g{targets.protein ? ` / ca. ${targets.protein} g` : ''}</Text>
|
||||
<Text style={styles.emptyCopy}>Zucker: {Math.round(totals.sugar)} g{targets.sugar ? ` / ${targets.sugar} g (dein Wert)` : ''}</Text>
|
||||
<Text style={styles.emptyCopy}>Salz: {totals.salt.toFixed(1)} g / weniger als {targets.salt} g</Text>
|
||||
<Text style={styles.emptyCopy}>Ballaststoffe: {totals.fiber.toFixed(1)} g / ca. {targets.fiber} g</Text>
|
||||
{preferences.exerciseGoal === 'endurance' ? <Text style={styles.emptyCopy}>Kohlenhydrate: {Math.round(totals.carbohydrates)} g erfasst (bedarf abhängig vom Training)</Text> : null}
|
||||
{targets.vitaminB12 !== null ? <Text style={styles.emptyCopy}>Vitamin B12: {totals.vitaminB12.toFixed(1)} µg / ca. {targets.vitaminB12} µg (nur angegebene Werte)</Text> : null}
|
||||
<Text style={styles.emptyCopy}>{totals.count} Portionen erfasst · Die Werte zeigen nur deine Einträge.</Text>
|
||||
{totals.count > 0 ? <Pressable accessibilityRole="button" onPress={onUndoConsumption}>
|
||||
<Text style={styles.scanCount}>Letzte Erfassung rückgängig machen</Text>
|
||||
</Pressable> : null}
|
||||
</View>
|
||||
|
||||
<Pressable accessibilityRole="button" onPress={onOpenList} style={styles.listShortcut}>
|
||||
<View style={styles.listShortcutText}>
|
||||
<Text style={styles.listShortcutTitle}>Dein Einkauf</Text>
|
||||
@@ -40,9 +56,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList,
|
||||
{shoppingList?.items?.length ? `${completedItems} von ${shoppingList.items.length} erledigt · ${openItems} noch offen` : 'Deine Liste ist noch leer'}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={styles.listShortcutTotal}>
|
||||
{shoppingList?.items?.length ? formatPrice(shoppingList.estimatedTotal, shoppingList.currency) : 'Liste öffnen'}
|
||||
</Text>
|
||||
<Text style={styles.listShortcutTotal}>Liste öffnen ›</Text>
|
||||
</Pressable>
|
||||
|
||||
{frequentProducts.length > 0 ? (
|
||||
@@ -52,7 +66,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList,
|
||||
<View key={`frequent-${product.id}`} style={styles.frequentWrap}>
|
||||
<ProductCard
|
||||
product={product}
|
||||
rating={calculateProductRating(product, preferences, { shoppingList })}
|
||||
rating={calculateProductRating(product, preferences, { shoppingList, dailyLog })}
|
||||
onPress={() => onOpenProduct(product)}
|
||||
/>
|
||||
<Text style={styles.scanCount}>{product.scanCount} Scans</Text>
|
||||
@@ -72,7 +86,7 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList,
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
product={product}
|
||||
rating={calculateProductRating(product, preferences, { shoppingList })}
|
||||
rating={calculateProductRating(product, preferences, { shoppingList, dailyLog })}
|
||||
onPress={() => onOpenProduct(product)}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useState } from 'react';
|
||||
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import PrimaryButton from '../components/PrimaryButton';
|
||||
import ScreenContainer from '../components/layout/ScreenContainer';
|
||||
import { colors, exerciseGoalLabels } from '../utils/constants';
|
||||
|
||||
export default function OnboardingScreen({ preferences, onSave }) {
|
||||
const [form, setForm] = useState(preferences);
|
||||
const [error, setError] = useState('');
|
||||
function save() {
|
||||
const age = Number(form.age), height = Number(form.heightCm), weight = Number(form.weightKg);
|
||||
if (!Number.isInteger(age) || age < 18 || age > 120 || height < 100 || height > 250 || weight < 20 || weight > 350) {
|
||||
setError('Bitte gib gültige Werte ein (Alter ab 18, Grösse 100–250 cm, Gewicht 20–350 kg).');
|
||||
return;
|
||||
}
|
||||
onSave({ ...form, age, heightCm: height, weightKg: weight, onboardingComplete: true });
|
||||
}
|
||||
return <ScreenContainer>
|
||||
<Text style={styles.title}>Willkommen bei Shoppinguin</Text>
|
||||
<Text style={styles.copy}>Erfahre beim Scannen, wie ein Lebensmittel zu deiner Ernährung und deinem Training passt. Dein Profil bleibt auf diesem Gerät.</Text>
|
||||
{[["Alter", 'age'], ['Grösse in cm', 'heightCm'], ['Gewicht in kg', 'weightKg']].map(([label, key]) =>
|
||||
<View key={key}><Text style={styles.label}>{label}</Text><TextInput accessibilityLabel={label} keyboardType="numeric" value={String(form[key] || '')}
|
||||
onChangeText={(value) => setForm({ ...form, [key]: value })} style={styles.input} /></View>)}
|
||||
<Text style={styles.label}>Dein Trainingsziel</Text>
|
||||
<View style={styles.options}>{Object.entries(exerciseGoalLabels).map(([key, label]) =>
|
||||
<Pressable key={key} accessibilityRole="button" accessibilityState={{ selected: form.exerciseGoal === key }}
|
||||
onPress={() => setForm({ ...form, exerciseGoal: key })} style={[styles.chip, form.exerciseGoal === key && styles.selected]}>
|
||||
<Text style={[styles.chipText, form.exerciseGoal === key && styles.selectedText]}>{label}</Text>
|
||||
</Pressable>)}</View>
|
||||
<Text style={styles.copy}>Richtwerte sind Orientierung, keine medizinische Empfehlung. Erfasste Lebensmittel sind nur so vollständig wie dein Tagesprotokoll.</Text>
|
||||
{error ? <Text accessibilityRole="alert" style={styles.error}>{error}</Text> : null}
|
||||
<PrimaryButton label="Profil speichern und starten" onPress={save} />
|
||||
</ScreenContainer>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
title: { color: colors.text, fontSize: 29, fontWeight: '800', marginTop: 20 },
|
||||
copy: { color: colors.muted, fontSize: 15, lineHeight: 22 },
|
||||
label: { color: colors.text, fontSize: 15, fontWeight: '700', marginBottom: 7, marginTop: 14 },
|
||||
input: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 12, borderWidth: 1, color: colors.text, fontSize: 17, padding: 12 },
|
||||
options: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
|
||||
chip: { borderColor: colors.border, borderRadius: 12, borderWidth: 1, padding: 12 },
|
||||
selected: { backgroundColor: colors.primary },
|
||||
chipText: { color: colors.text, fontWeight: '700' }, selectedText: { color: colors.surface },
|
||||
error: { color: colors.danger, fontSize: 14 }
|
||||
});
|
||||
@@ -15,8 +15,8 @@ const sections = [
|
||||
{
|
||||
title: 'Daten auf deinem Gerät',
|
||||
paragraphs: [
|
||||
'Shoppinguin speichert deine Einstellungen, ausgewählte Allergene und Ernährungsziele, Budgetangaben, die Einkaufsliste, manuell eingegebene Preise und Produktangaben sowie zuletzt angezeigte und zwischengespeicherte Produkte lokal auf deinem Gerät. Diese Angaben nutzt die App für Produktempfehlungen, Bewertungen und deine Einkaufsliste. Shoppinguin bietet derzeit kein Nutzerkonto. Die lokal gespeicherten Angaben werden nicht an einen Shoppinguin-Server übertragen.',
|
||||
'Verlauf und Produktcache kannst du in den Einstellungen der App löschen. Einkaufsliste, Einstellungen und manuelle Preise bleiben dabei erhalten. Alle lokalen App-Daten kannst du über die Einstellungen deines Geräts löschen oder durch Deinstallation entfernen. Shoppinguin bewahrt davon keine Kopie auf einem eigenen Server auf.'
|
||||
'Shoppinguin speichert Alter, Grösse, Gewicht, Trainingsziel, deinen Zucker-Tageswert und erfasste Portionen sowie Allergene, Einkaufsliste und Produktdaten lokal auf deinem Gerät. Diese Angaben nutzt die App für persönliche Produkthinweise. Shoppinguin bietet kein Nutzerkonto. Dein Profil und Tagesprotokoll werden nicht an einen Shoppinguin-Server übertragen.',
|
||||
'Verlauf und Produktcache kannst du in den Einstellungen der App löschen. Einkaufsliste und Einstellungen bleiben dabei erhalten. Frühere manuell gespeicherte Preise werden beim nächsten App-Start entfernt. Alle lokalen App-Daten kannst du über die Einstellungen deines Geräts löschen oder durch Deinstallation entfernen. Shoppinguin bewahrt davon keine Kopie auf einem eigenen Server auf.'
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -28,8 +28,8 @@ const sections = [
|
||||
{
|
||||
title: 'Online-Produktsuche',
|
||||
paragraphs: [
|
||||
'Für eine Online-Abfrage sendet Shoppinguin den gescannten Barcode oder deinen Suchbegriff an Open Food Facts und lädt Produktinformationen von dort. Bei einer solchen Internetverbindung können technisch bedingt auch Verbindungsdaten, insbesondere deine IP-Adresse, beim Anbieter anfallen. Deine lokalen Einstellungen, Allergenauswahl und Einkaufsliste werden bei diesen Abfragen nicht mitgesendet.',
|
||||
'Bei einem Barcode-Treffer aus einem frischen lokalen Produktcache, bei lokal erfassten Produkten und im Offline-Modus erfolgt keine Abfrage bei Open Food Facts. Die Namenssuche fragt bei aktivem Online-Modus zuerst Open Food Facts an und ergänzt die Treffer um lokal gespeicherte Produkte. Manuell ergänzte Produktangaben bleiben auf deinem Gerät und werden von Shoppinguin nicht an Open Food Facts gesendet. Wenn du den Produktlink zu Open Food Facts öffnest, verlässt du die App und kannst dort selbst Angaben ergänzen. Für diese Webseite gelten die Datenschutzhinweise von Open Food Facts.'
|
||||
'Für eine Online-Abfrage sendet Shoppinguin den gescannten Barcode oder deinen Suchbegriff an Open Food Facts und lädt Produktinformationen von dort. Beim Öffnen eines Produkts sucht die App automatisch anhand seiner Kategorietags nach ähnlichen Alternativen. Falls das nicht genügt, verwendet sie auch die Produktart, Kategorie oder Teile des Produktnamens als Suchbegriff. Bei einer solchen Internetverbindung können technisch bedingt auch Verbindungsdaten, insbesondere deine IP-Adresse, beim Anbieter anfallen. Deine lokalen Einstellungen, Allergenauswahl und Einkaufsliste werden bei diesen Abfragen nicht mitgesendet.',
|
||||
'Ein Barcode-Treffer aus einem frischen lokalen Produktcache benötigt für das Laden des Produkts keine Online-Abfrage. Im Offline-Modus erfolgt keine Abfrage bei Open Food Facts. Die Namenssuche fragt bei aktivem Online-Modus zuerst Open Food Facts an und ergänzt die Treffer um lokal gespeicherte Produkte. Manuell ergänzte Nährwerte, Zutaten und Allergene bleiben auf deinem Gerät; Produktname und Kategorie können für die Alternativsuche als Suchbegriffe gesendet werden. Wenn du den Produktlink zu Open Food Facts öffnest, verlässt du die App und kannst dort selbst Angaben ergänzen. Für diese Webseite gelten die Datenschutzhinweise von Open Food Facts.'
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -69,7 +69,7 @@ export default function PrivacyScreen({ onBack }) {
|
||||
</Pressable>
|
||||
) : null}
|
||||
{section.title === 'Online-Produktsuche' ? (
|
||||
<Pressable accessibilityRole="link" onPress={() => Linking.openURL('https://world.openfoodfacts.org/privacy')}>
|
||||
<Pressable accessibilityRole="link" onPress={() => Linking.openURL('https://ch.openfoodfacts.org/privacy')}>
|
||||
<Text style={styles.link}>Datenschutzhinweise von Open Food Facts ›</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useState } from 'react';
|
||||
import { StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import PrimaryButton from '../components/PrimaryButton';
|
||||
import AppHeader from '../components/layout/AppHeader';
|
||||
import ScreenContainer from '../components/layout/ScreenContainer';
|
||||
import { colors } from '../utils/constants';
|
||||
|
||||
const nutrientFields = [['Protein (g/100 g)', 'proteinPer100g'], ['Zucker (g/100 g)', 'sugarPer100g'],
|
||||
['Kohlenhydrate (g/100 g)', 'carbohydratesPer100g'], ['Ballaststoffe (g/100 g)', 'fiberPer100g'],
|
||||
['Vitamin B12 (µg/100 g)', 'vitaminB12MicrogramsPer100g'],
|
||||
['Energie (kJ/100 g)', 'energyKjPer100g'], ['Gesättigte Fettsäuren (g/100 g)', 'saturatedFatPer100g'],
|
||||
['Salz (g/100 g)', 'saltPer100g']];
|
||||
|
||||
export default function ProductEditScreen({ product, isNew, onBack, onSave }) {
|
||||
const [form, setForm] = useState({ name: product.name || '', brand: product.brand || '',
|
||||
category: product.category || '', ingredients: (product.ingredients || []).join(', '),
|
||||
allergens: (product.allergens || []).join(', '),
|
||||
...Object.fromEntries(nutrientFields.map(([, key]) => [key, String(product.nutrition?.[key] ?? '')])) });
|
||||
const [error, setError] = useState('');
|
||||
function save() {
|
||||
if (!form.name.trim()) { setError('Bitte gib einen Produktnamen ein.'); return; }
|
||||
const nutrition = {};
|
||||
for (const [, key] of nutrientFields) {
|
||||
if (!form[key].trim()) continue;
|
||||
const value = Number(form[key].replace(',', '.'));
|
||||
if (!Number.isFinite(value) || value < 0) { setError('Bitte gib gültige Nährwerte ein.'); return; }
|
||||
nutrition[key] = value;
|
||||
}
|
||||
const list = (value) => value.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
onSave({ name: form.name.trim(), brand: form.brand.trim(), category: form.category.trim(),
|
||||
ingredients: list(form.ingredients), allergens: list(form.allergens), nutrition });
|
||||
}
|
||||
return <ScreenContainer><AppHeader title={isNew ? 'Produkt erfassen' : 'Produkt korrigieren'} onBack={onBack} />
|
||||
<Text style={styles.hint}>Übertrage die Angaben von der Verpackung. Alle Änderungen bleiben lokal.</Text>
|
||||
{[["Name", 'name'], ['Marke', 'brand'], ['Kategorie', 'category'], ['Zutaten (kommagetrennt)', 'ingredients'],
|
||||
['Allergene (kommagetrennt)', 'allergens'], ...nutrientFields].map(([label, key]) =>
|
||||
<View key={key}><Text style={styles.label}>{label}</Text><TextInput accessibilityLabel={label} value={form[key]}
|
||||
keyboardType={nutrientFields.some(([, field]) => field === key) ? 'decimal-pad' : 'default'}
|
||||
onChangeText={(value) => setForm({ ...form, [key]: value })} style={styles.input} /></View>)}
|
||||
{error ? <Text accessibilityRole="alert" style={styles.error}>{error}</Text> : null}
|
||||
<PrimaryButton label="Angaben speichern" onPress={save} />
|
||||
</ScreenContainer>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
hint: { color: colors.muted, fontSize: 14, lineHeight: 20 },
|
||||
label: { color: colors.text, fontWeight: '700', marginBottom: 5, marginTop: 12 },
|
||||
input: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 10, borderWidth: 1, color: colors.text, fontSize: 16, padding: 10 },
|
||||
error: { color: colors.danger }
|
||||
});
|
||||
@@ -1,12 +1,11 @@
|
||||
import { useState } from 'react';
|
||||
import { Alert, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
|
||||
import BudgetInput from '../components/form/BudgetInput';
|
||||
import SettingsSwitchRow from '../components/form/SettingsSwitchRow';
|
||||
import AppHeader from '../components/layout/AppHeader';
|
||||
import ScreenContainer from '../components/layout/ScreenContainer';
|
||||
import { budgetPeriodLabels, colors, dietLabels } from '../utils/constants';
|
||||
import { formatPrice } from '../utils/formatPrice';
|
||||
import { dailyTargets, FREE_SUGAR_REFERENCE_GRAMS, sugarLimitWarning } from '../services/dailyNutritionService';
|
||||
import { colors, dietLabels, exerciseGoalLabels } from '../utils/constants';
|
||||
|
||||
const dietOptions = ['none', 'vegetarian', 'vegan', 'lowSugar', 'highProtein'];
|
||||
const allergenOptions = ['Erdnüsse', 'Milch', 'Hafer', 'Gluten'];
|
||||
@@ -24,7 +23,7 @@ export default function ProfileScreen({ preferences, onChangePreferences, onOpen
|
||||
}
|
||||
|
||||
function confirmClearProductData() {
|
||||
const message = 'Gespeicherte Produkte und letzte Scans werden entfernt. Einkaufsliste, Einstellungen und manuelle Preise bleiben erhalten.';
|
||||
const message = 'Gespeicherte Produkte und letzte Scans werden entfernt. Einkaufsliste und Einstellungen bleiben erhalten.';
|
||||
if (Platform.OS === 'web') {
|
||||
if (window.confirm(`Verlauf und Produktcache löschen?\n\n${message}`)) clearProductData();
|
||||
return;
|
||||
@@ -51,10 +50,7 @@ export default function ProfileScreen({ preferences, onChangePreferences, onOpen
|
||||
}
|
||||
|
||||
const allergenCount = preferences.avoidAllergens?.length || 0;
|
||||
const budget = preferences.maxBudgetPerShoppingTrip;
|
||||
const budgetSummary = typeof budget === 'number' && budget > 0
|
||||
? `${formatPrice(budget, preferences.currency)} pro ${budgetPeriodLabels[preferences.budgetPeriod] || 'Woche'}`
|
||||
: 'Kein Budget festgelegt';
|
||||
const targets = dailyTargets(preferences);
|
||||
|
||||
return (
|
||||
<ScreenContainer>
|
||||
@@ -100,40 +96,36 @@ export default function ProfileScreen({ preferences, onChangePreferences, onOpen
|
||||
</View>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Budget" summary={budgetSummary}>
|
||||
<BudgetInput
|
||||
currency={preferences.currency}
|
||||
onChangePeriod={(value) => updatePreference('budgetPeriod', value)}
|
||||
onChangeValue={(value) => updatePreference('maxBudgetPerShoppingTrip', value)}
|
||||
period={preferences.budgetPeriod || 'week'}
|
||||
value={budget}
|
||||
/>
|
||||
<SettingsSection title="Körper & Training" summary={`${exerciseGoalLabels[preferences.exerciseGoal] || 'Allgemeine Fitness'} · nur auf diesem Gerät`}>
|
||||
<Text style={styles.fieldHint}>Deine Angaben helfen bei der Einordnung. Die Richtwerte sind keine individuelle medizinische Beratung.</Text>
|
||||
{[["Alter", 'age'], ['Grösse (cm)', 'heightCm'], ['Gewicht (kg)', 'weightKg']].map(([label, key]) =>
|
||||
<View key={key}><Text style={styles.fieldLabel}>{label}</Text><TextInput accessibilityLabel={label} keyboardType="numeric"
|
||||
value={String(preferences[key] ?? '')} onChangeText={(value) => updatePreference(key, value)} style={styles.profileInput} /></View>)}
|
||||
<Text style={styles.fieldLabel}>Trainingsziel</Text>
|
||||
<View style={styles.optionGrid}>{Object.entries(exerciseGoalLabels).map(([key, label]) =>
|
||||
<SelectionChip key={key} label={label} active={preferences.exerciseGoal === key} onPress={() => updatePreference('exerciseGoal', key)} />)}</View>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Tageswerte" summary="Nährwerte für Gesundheit und Training">
|
||||
<Text style={styles.fieldLabel}>Protein: {targets.protein === null ? 'Gewicht fehlt' : `ca. ${targets.protein} g pro Tag`}</Text>
|
||||
<Text style={styles.fieldHint}>Aus Körpergewicht und Trainingsziel berechnet. Alter und Grösse ändern diesen Richtwert nicht; für einen persönlichen Energiebedarf fehlen weitere Angaben wie Aktivität und Körperzusammensetzung.</Text>
|
||||
<View style={styles.divider} />
|
||||
<SugarTargetInput value={preferences.dailySugarLimitGrams} onChange={(value) => updatePreference('dailySugarLimitGrams', value)} />
|
||||
<Text style={styles.fieldHint}>Die App zählt Gesamtzucker aus den Produktangaben. Die WHO-Orientierung von weniger als {FREE_SUGAR_REFERENCE_GRAMS} g bei 2.000 kcal gilt für freien Zucker und ist damit nicht direkt vergleichbar.</Text>
|
||||
<View style={styles.divider} />
|
||||
<Text style={styles.fieldLabel}>Salz: weniger als {targets.salt} g pro Tag</Text>
|
||||
<Text style={styles.fieldHint}>WHO-Orientierung für Erwachsene. Salz vom Kochen oder Nachsalzen ist im App-Protokoll nicht enthalten.</Text>
|
||||
<Text style={styles.fieldLabel}>Ballaststoffe: ca. {targets.fiber} g pro Tag</Text>
|
||||
<Text style={styles.fieldHint}>Allgemeiner EFSA-Richtwert für Erwachsene.</Text>
|
||||
{preferences.exerciseGoal === 'endurance' ? <Text style={styles.fieldHint}>Ausdauer: Kohlenhydrate werden pro Portion angezeigt. Ein Tagesziel hängt von Trainingsdauer und Intensität ab.</Text> : null}
|
||||
{targets.vitaminB12 !== null ? <Text style={styles.fieldHint}>Vegan: Vitamin B12 wird, wenn angegeben, mit dem EFSA-Richtwert von {targets.vitaminB12} µg pro Tag verglichen. Fehlende Produktwerte bedeuten nicht, dass kein B12 enthalten ist.</Text> : null}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Bewertung"
|
||||
summary={`Ernährung ${priorityLabels[preferences.nutritionPriority] || 'Mittel'} · Nachhaltigkeit ${priorityLabels[preferences.sustainabilityPriority] || 'Mittel'}`}
|
||||
summary="Ernährung und persönliche Ziele"
|
||||
>
|
||||
<SettingsSwitchRow
|
||||
description="Bio-Produkte erhalten in der Nachhaltigkeitsbewertung einen Vorteil."
|
||||
embedded
|
||||
label="Bio bevorzugen"
|
||||
onValueChange={(value) => updatePreference('preferBio', value)}
|
||||
value={preferences.preferBio}
|
||||
/>
|
||||
<View style={styles.divider} />
|
||||
<Text style={styles.fieldLabel}>Prioritäten</Text>
|
||||
<Text style={styles.fieldHint}>Hoch bedeutet, dass dieser Bereich stärker in die Gesamtbewertung einfliesst.</Text>
|
||||
<PrioritySelector
|
||||
label="Ernährung"
|
||||
onChange={(value) => updatePreference('nutritionPriority', value)}
|
||||
value={preferences.nutritionPriority}
|
||||
/>
|
||||
<PrioritySelector
|
||||
label="Nachhaltigkeit"
|
||||
onChange={(value) => updatePreference('sustainabilityPriority', value)}
|
||||
value={preferences.sustainabilityPriority}
|
||||
/>
|
||||
<Text style={styles.fieldHint}>Die Bewertung berücksichtigt Nährwerte, deine Tageswerte, Allergien und Zutaten. Umweltangaben bleiben als zusätzliche Produktinformation sichtbar.</Text>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
@@ -161,13 +153,43 @@ export default function ProfileScreen({ preferences, onChangePreferences, onOpen
|
||||
>
|
||||
<Text style={styles.deleteActionText}>{isClearingProductData ? 'Daten werden gelöscht...' : 'Verlauf und Produktcache löschen'}</Text>
|
||||
</Pressable>
|
||||
<Text style={styles.fieldHint}>Einkaufsliste, Einstellungen und manuelle Preise bleiben erhalten.</Text>
|
||||
<Text style={styles.fieldHint}>Einkaufsliste und Einstellungen bleiben erhalten.</Text>
|
||||
{dataMessage ? <Text accessibilityRole="alert" style={styles.fieldHint}>{dataMessage}</Text> : null}
|
||||
</SettingsSection>
|
||||
</ScreenContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function SugarTargetInput({ value, onChange }) {
|
||||
const [draft, setDraft] = useState(String(value ?? ''));
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => setDraft(String(value ?? '')), [value]);
|
||||
|
||||
function save() {
|
||||
const grams = Number(draft.trim().replace(',', '.'));
|
||||
if (!Number.isFinite(grams) || grams <= 0 || grams > 500) {
|
||||
setError('Bitte gib einen Wert zwischen 1 und 500 g ein.');
|
||||
return;
|
||||
}
|
||||
setError('');
|
||||
if (grams === Number(value)) return;
|
||||
onChange(grams);
|
||||
const warning = sugarLimitWarning(grams);
|
||||
if (warning) {
|
||||
if (Platform.OS === 'web') window.alert(warning);
|
||||
else Alert.alert('Zuckerwert über der WHO-Orientierung', warning, [{ text: 'Verstanden' }]);
|
||||
}
|
||||
}
|
||||
|
||||
return <View>
|
||||
<Text style={styles.fieldLabel}>Dein Tageswert für Gesamtzucker (g)</Text>
|
||||
<TextInput accessibilityLabel="Tageswert für Gesamtzucker" keyboardType="decimal-pad"
|
||||
value={draft} onChangeText={setDraft} onBlur={save} style={styles.profileInput} />
|
||||
{error ? <Text accessibilityRole="alert" style={styles.errorText}>{error}</Text> : null}
|
||||
</View>;
|
||||
}
|
||||
|
||||
function SettingsSection({ title, summary, children }) {
|
||||
return (
|
||||
<View style={styles.section}>
|
||||
@@ -257,6 +279,8 @@ const styles = StyleSheet.create({
|
||||
fontSize: 13,
|
||||
lineHeight: 19
|
||||
},
|
||||
profileInput: { borderColor: colors.border, borderRadius: 10, borderWidth: 1, color: colors.text, fontSize: 16, marginTop: 7, padding: 10 },
|
||||
errorText: { color: colors.danger, fontSize: 13, marginTop: 6 },
|
||||
divider: {
|
||||
backgroundColor: colors.border,
|
||||
height: 1
|
||||
|
||||
@@ -8,10 +8,10 @@ import { colors } from '../utils/constants';
|
||||
|
||||
const labels = {
|
||||
allergies: 'Allergien',
|
||||
budget: 'Budget',
|
||||
ingredients: 'Zutaten',
|
||||
nutrition: 'Ernährung',
|
||||
sustainability: 'Nachhaltigkeit'
|
||||
sustainability: 'Nachhaltigkeit',
|
||||
goals: 'Deine Ziele'
|
||||
};
|
||||
|
||||
const defaultDetails = {
|
||||
@@ -19,10 +19,6 @@ const defaultDetails = {
|
||||
positive: 'Eine ausdrücklich bestätigte Abwesenheit deiner vermiedenen Allergene verbessert diese Bewertung.',
|
||||
penalty: 'Ein angegebenes vermiedenes Allergen blockiert die Empfehlung. Mögliche Spuren und nicht bestätigte Abwesenheit erfordern eine Prüfung der Verpackung.'
|
||||
},
|
||||
budget: {
|
||||
positive: 'Ein niedriger Anteil der offenen Einkaufsliste inklusive dieses Produkts am Budget verbessert diese Bewertung.',
|
||||
penalty: 'Eine Überschreitung des Budgets reduziert die Bewertung. Fehlende Preise verhindern eine bestätigte Budgeteinhaltung.'
|
||||
},
|
||||
ingredients: {
|
||||
positive: 'Eine passende Vegan-/Vegetarisch-Analyse sowie Angaben zu Palmöl und Zusatzstoffen verbessern diese Bewertung.',
|
||||
penalty: 'Zusatzstoffhinweise und Palmöl senken die Zutatenwertung. Ein bestätigter Konflikt mit Vegan oder Vegetarisch begrenzt die Gesamtempfehlung.'
|
||||
@@ -34,14 +30,18 @@ const defaultDetails = {
|
||||
sustainability: {
|
||||
positive: 'Ein guter Green-Score oder ein niedriger CO2-Fussabdruck verbessert diese Bewertung; Bio zählt bei entsprechender Präferenz.',
|
||||
penalty: 'Ein schwacher Green-Score oder hoher CO2-Fussabdruck reduziert diese Bewertung. Herkunft und Verpackung werden angezeigt, aber nicht in Punkte übersetzt.'
|
||||
}
|
||||
},
|
||||
goals: { positive: 'Protein, Zucker und bei Ausdauer Kohlenhydrate beeinflussen die Zielwertung. Salz, Ballaststoffe und bei veganer Ernährung Vitamin B12 werden als Tageskontext gezeigt.', penalty: 'Viel Zucker im Verhältnis zu deinem Tageswert senkt die Zielwertung. Salz und Ballaststoffe stecken bereits im Nutri-Score und werden nicht nochmals als Punktabzug gewertet.' }
|
||||
};
|
||||
|
||||
export default function RatingCriteriaDetailScreen({ product, preferences, shoppingList, category, onBack }) {
|
||||
const rating = calculateProductRating(product, preferences, { shoppingList });
|
||||
export default function RatingCriteriaDetailScreen({ product, preferences, shoppingList, dailyLog, category, onBack }) {
|
||||
const rating = calculateProductRating(product, preferences, { shoppingList, dailyLog });
|
||||
const categoryRating = rating.categoryScores[category];
|
||||
const title = labels[category] || category;
|
||||
const fallbackDetails = defaultDetails[category] || defaultDetails.ingredients;
|
||||
const goalDetails = category === 'goals' ? categoryRating.details || [] : [];
|
||||
const goalScoreDetails = goalDetails.filter((detail) => ['Protein', 'Zucker', 'Kohlenhydrate für Ausdauer'].includes(detail.title));
|
||||
const goalContextDetails = goalDetails.filter((detail) => !['Protein', 'Zucker', 'Kohlenhydrate für Ausdauer'].includes(detail.title));
|
||||
|
||||
return (
|
||||
<ScreenContainer>
|
||||
@@ -67,7 +67,16 @@ export default function RatingCriteriaDetailScreen({ product, preferences, shopp
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{(categoryRating.details || []).length > 0 ? (
|
||||
{category === 'goals' ? <>
|
||||
{goalScoreDetails.length > 0 ? <View style={styles.panel}>
|
||||
<Text style={styles.panelTitle}>Für dein Ziel</Text>
|
||||
{goalScoreDetails.map((detail) => <GoalDetail key={detail.title} detail={detail} />)}
|
||||
</View> : null}
|
||||
{goalContextDetails.length > 0 ? <View style={styles.panel}>
|
||||
<Text style={styles.panelTitle}>Weitere Tageswerte</Text>
|
||||
{goalContextDetails.map((detail) => <GoalDetail key={detail.title} detail={detail} />)}
|
||||
</View> : null}
|
||||
</> : (categoryRating.details || []).length > 0 ? (
|
||||
<View style={styles.panel}>
|
||||
<Text style={styles.panelTitle}>So entsteht die Bewertung</Text>
|
||||
{categoryRating.details.map((detail) => (
|
||||
@@ -83,19 +92,28 @@ export default function RatingCriteriaDetailScreen({ product, preferences, shopp
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View style={styles.panel}>
|
||||
{category !== 'goals' ? <View style={styles.panel}>
|
||||
<Text style={styles.panelTitle}>Was die Bewertung verbessert</Text>
|
||||
<Text style={styles.detailBody}>{fallbackDetails.positive}</Text>
|
||||
</View>
|
||||
</View> : null}
|
||||
|
||||
<View style={styles.panel}>
|
||||
{category !== 'goals' ? <View style={styles.panel}>
|
||||
<Text style={styles.panelTitle}>Was die Bewertung senkt</Text>
|
||||
<Text style={styles.detailBody}>{fallbackDetails.penalty}</Text>
|
||||
</View>
|
||||
</View> : null}
|
||||
{category === 'goals' ? <Text style={styles.detailMeta}>Die Tageswerte zeigen nur deine erfassten Portionen. Salz und Ballaststoffe verändern die Zielpunktzahl nicht erneut.</Text> : null}
|
||||
</ScreenContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function GoalDetail({ detail }) {
|
||||
return <View style={styles.goalItem}>
|
||||
<Text style={detail.type === 'positive' ? styles.positiveTitle
|
||||
: detail.type === 'penalty' ? styles.penaltyTitle : styles.infoTitle}>{detail.title}</Text>
|
||||
<Text style={styles.detailBody}>{detail.body}</Text>
|
||||
</View>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
summaryPanel: {
|
||||
backgroundColor: colors.surface,
|
||||
@@ -150,6 +168,7 @@ const styles = StyleSheet.create({
|
||||
gap: 5,
|
||||
paddingTop: 10
|
||||
},
|
||||
goalItem: { backgroundColor: colors.background, borderRadius: 12, gap: 5, padding: 12 },
|
||||
positiveTitle: {
|
||||
color: colors.success,
|
||||
fontSize: 14,
|
||||
|
||||
@@ -7,35 +7,23 @@ import AppHeader from '../components/layout/AppHeader';
|
||||
import ScreenContainer from '../components/layout/ScreenContainer';
|
||||
import ShoppingListItem from '../components/list/ShoppingListItem';
|
||||
import { calculateShoppingListWarnings } from '../services/shoppingListWarningsService';
|
||||
import { budgetPeriodLabels, colors } from '../utils/constants';
|
||||
import { formatPrice } from '../utils/formatPrice';
|
||||
import { colors } from '../utils/constants';
|
||||
|
||||
export default function ShoppingListScreen({
|
||||
preferences,
|
||||
shoppingList,
|
||||
lastDeletedItem,
|
||||
onToggleItem,
|
||||
onChangeItemQuantity,
|
||||
onDeleteItem,
|
||||
onUndoDelete,
|
||||
onUpdateItemPrice,
|
||||
onStartScan,
|
||||
onOpenProfile,
|
||||
onCompleteList
|
||||
}) {
|
||||
const [isConfirming, setIsConfirming] = useState(false);
|
||||
const [wasCompleted, setWasCompleted] = useState(false);
|
||||
const openItems = shoppingList.items.filter((item) => !item.checked).length;
|
||||
const completedItems = shoppingList.items.length - openItems;
|
||||
const openTotal = shoppingList.items.reduce((sum, item) =>
|
||||
sum + (!item.checked && typeof item.estimatedPrice === 'number' ? item.estimatedPrice * item.quantity : 0), 0);
|
||||
const progress = shoppingList.items.length ? completedItems / shoppingList.items.length : 0;
|
||||
const itemsWithoutPrice = shoppingList.items.filter((item) => typeof item.estimatedPrice !== 'number').length;
|
||||
const openItemsWithoutPrice = shoppingList.items.filter((item) => !item.checked && typeof item.estimatedPrice !== 'number').length;
|
||||
const budget = preferences.maxBudgetPerShoppingTrip;
|
||||
const hasBudget = typeof budget === 'number' && budget > 0;
|
||||
const budgetShare = hasBudget ? shoppingList.estimatedTotal / budget : 0;
|
||||
const budgetStatus = budgetShare <= 0.75 ? 'good' : budgetShare <= 1 ? 'medium' : 'critical';
|
||||
const dailyWarnings = calculateShoppingListWarnings(shoppingList);
|
||||
|
||||
return (
|
||||
@@ -62,9 +50,7 @@ export default function ShoppingListScreen({
|
||||
|
||||
<View style={styles.summary}>
|
||||
<Text style={styles.summaryTitle}>Deine Liste</Text>
|
||||
<Text style={styles.totalLabel}>{itemsWithoutPrice ? 'Bekannte Summe' : 'Voraussichtliche Summe'}</Text>
|
||||
<Text style={styles.totalValue}>{formatPrice(shoppingList.estimatedTotal, shoppingList.currency)}</Text>
|
||||
{itemsWithoutPrice ? <Text style={styles.summaryCopy}>{itemsWithoutPrice} {itemsWithoutPrice === 1 ? 'Produkt ohne Preis ist' : 'Produkte ohne Preis sind'} nicht eingerechnet.</Text> : null}
|
||||
<Text style={styles.summaryCopy}>{openItems} offen · {completedItems} erledigt</Text>
|
||||
{shoppingList.items.length > 0 ? (
|
||||
<View style={styles.shoppingProgress}>
|
||||
<View style={styles.progressHeader}>
|
||||
@@ -74,30 +60,8 @@ export default function ShoppingListScreen({
|
||||
<View style={styles.progressTrack}>
|
||||
<View style={[styles.progressFill, styles.goodFill, { width: `${progress * 100}%` }]} />
|
||||
</View>
|
||||
<Text style={styles.remainingCopy}>Noch offen: {formatPrice(openTotal, shoppingList.currency)}{openItemsWithoutPrice ? ` plus ${openItemsWithoutPrice} Artikel ohne Preis` : ''}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{hasBudget ? <View style={styles.budgetBox}>
|
||||
<View style={styles.budgetHeader}>
|
||||
<Text style={styles.budgetLabel}>Anteil am Budget pro {budgetPeriodLabels[preferences.budgetPeriod] || 'Woche'}</Text>
|
||||
<Text style={[styles.budgetValue, styles[budgetStatus]]}>
|
||||
{formatPrice(shoppingList.estimatedTotal, shoppingList.currency)} von {formatPrice(budget, shoppingList.currency)}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.progressTrack}>
|
||||
<View
|
||||
style={[
|
||||
styles.progressFill,
|
||||
styles[`${budgetStatus}Fill`],
|
||||
{ width: `${Math.min(budgetShare * 100, 100)}%` }
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
</View> : (
|
||||
<Pressable accessibilityRole="button" onPress={onOpenProfile} style={styles.budgetLink}>
|
||||
<Text style={styles.budgetLinkText}>Budget im Profil festlegen ›</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{dailyWarnings.length > 0 ? (
|
||||
@@ -132,11 +96,11 @@ export default function ShoppingListScreen({
|
||||
<>
|
||||
{openItems > 0 ? <Text style={styles.groupTitle}>Noch einkaufen · {openItems}</Text> : null}
|
||||
{shoppingList.items.filter((item) => !item.checked).map((item) => (
|
||||
<ShoppingListItem item={item} key={item.id} onDelete={() => onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} onUpdatePrice={onUpdateItemPrice} />
|
||||
<ShoppingListItem item={item} key={item.id} onDelete={() => onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} />
|
||||
))}
|
||||
{completedItems > 0 ? <Text style={styles.groupTitle}>Erledigt · {completedItems}</Text> : null}
|
||||
{shoppingList.items.filter((item) => item.checked).map((item) => (
|
||||
<ShoppingListItem item={item} key={item.id} onDelete={() => onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} onUpdatePrice={onUpdateItemPrice} />
|
||||
<ShoppingListItem item={item} key={item.id} onDelete={() => onDeleteItem(item.id)} onToggle={() => onToggleItem(item.id)} onChangeQuantity={(change) => onChangeItemQuantity(item.id, change)} />
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
@@ -176,7 +140,6 @@ const styles = StyleSheet.create({
|
||||
shoppingProgress: { marginTop: 18 },
|
||||
progressHeader: { flexDirection: 'row', justifyContent: 'space-between' },
|
||||
progressLabel: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' },
|
||||
remainingCopy: { color: colors.muted, fontSize: 13, marginTop: 8 },
|
||||
groupTitle: { color: colors.text, fontSize: 16, fontWeight: '800', marginTop: 4 },
|
||||
summary: {
|
||||
backgroundColor: colors.surface,
|
||||
@@ -196,47 +159,6 @@ const styles = StyleSheet.create({
|
||||
lineHeight: 20,
|
||||
marginTop: 7
|
||||
},
|
||||
totalLabel: {
|
||||
color: colors.muted,
|
||||
fontSize: 13,
|
||||
fontWeight: '700',
|
||||
marginTop: 16
|
||||
},
|
||||
totalValue: {
|
||||
color: colors.text,
|
||||
fontSize: 30,
|
||||
fontWeight: '800',
|
||||
letterSpacing: -0.6,
|
||||
marginTop: 2
|
||||
},
|
||||
budgetBox: {
|
||||
marginTop: 14
|
||||
},
|
||||
budgetLink: {
|
||||
minHeight: 44,
|
||||
justifyContent: 'center',
|
||||
alignSelf: 'flex-start',
|
||||
marginTop: 8
|
||||
},
|
||||
budgetLinkText: {
|
||||
color: colors.primary,
|
||||
fontSize: 14,
|
||||
fontWeight: '800'
|
||||
},
|
||||
budgetHeader: {
|
||||
alignItems: 'flex-start',
|
||||
gap: 4,
|
||||
justifyContent: 'space-between'
|
||||
},
|
||||
budgetLabel: {
|
||||
color: colors.muted,
|
||||
fontSize: 13,
|
||||
fontWeight: '800'
|
||||
},
|
||||
budgetValue: {
|
||||
fontSize: 15,
|
||||
fontWeight: '800'
|
||||
},
|
||||
progressTrack: {
|
||||
backgroundColor: '#edf1ee',
|
||||
borderRadius: 999,
|
||||
|
||||
@@ -6,13 +6,32 @@ const MIN_CATEGORY_IMPROVEMENT = 10;
|
||||
const INTERNAL_ALTERNATIVE_LIMIT = 8;
|
||||
const HEALTH_IMPROVEMENT = 10;
|
||||
const GENERIC_CATEGORY_TERMS = new Set(['foods', 'plant based foods', 'plant based foods and beverages']);
|
||||
const BROAD_CATEGORY_TAGS = new Set(['en:foods', 'en:beverages', 'en:non-alcoholic-beverages', 'en:water-based-beverages',
|
||||
'en:snacks', 'en:dairies', 'en:meals', 'en:spreads', 'en:sweet-spreads',
|
||||
'en:plant-based-foods', 'en:plant-based-foods-and-beverages']);
|
||||
const PRODUCT_TYPES = [
|
||||
['water', /\b(water|waters|mineral water|flavored water|flavoured water|wasser|mineralwasser)\b/],
|
||||
['juice', /\b(juice|juices|fruit juice|nectar|saft|säfte|fruchtsaft)\b/],
|
||||
['energy-drink', /\b(energy drink|energy drinks|energydrink|energy-drinks)\b/],
|
||||
['sports-drink', /\b(sports drink|sports drinks|isotonic|isotonisch)\b/],
|
||||
['soda', /\b(soda|sodas|cola|colas|soft drink|soft drinks|limonade|süssgetränk|süßgetränk|carbonated drink|carbonated drinks)\b/],
|
||||
['tea', /\b(tea|teas|eistee|iced tea|tee)\b/],
|
||||
['coffee', /\b(coffee|kaffee|cafe)\b/],
|
||||
['milk-drink', /\b(milk drink|milk drinks|milchgetränk|milchgetränke)\b/],
|
||||
['spread', /\b(spread|spreads|aufstrich|aufstriche)\b/],
|
||||
['chocolate', /\b(chocolate|chocolates|schokolade)\b/],
|
||||
['chips', /\b(chips|crisps|kartoffelchips)\b/],
|
||||
['bars', /\b(bar|bars|riegel)\b/],
|
||||
['yogurt', /\b(yogurt|yogurts|joghurt)\b/],
|
||||
['cheese', /\b(cheese|käse)\b/],
|
||||
['milk', /\b(milk|milch)\b/]
|
||||
];
|
||||
|
||||
const improvementLabels = {
|
||||
allergies: 'Besser passend bei Allergien',
|
||||
ingredients: 'Bessere Zutaten',
|
||||
budget: 'Günstiger fürs Budget',
|
||||
nutrition: 'Bessere Ernährung',
|
||||
sustainability: 'Nachhaltiger'
|
||||
goals: 'Besser für deine Ziele'
|
||||
};
|
||||
|
||||
const categoryGroups = [
|
||||
@@ -38,27 +57,32 @@ const categoryGroups = [
|
||||
}
|
||||
];
|
||||
|
||||
export async function findAlternatives(product, preferences, productCache = {}, context = {}) {
|
||||
export async function findAlternatives(product, preferences, productCache = {}, context = {}, { preview = false } = {}) {
|
||||
const productRating = calculateProductRating(product, preferences, context);
|
||||
if (productRating.overallScore === null) return [];
|
||||
if (alternativeSearchIssue(product, productRating)) return [];
|
||||
const categoryTerms = categoryTermsForProduct(product);
|
||||
const candidates = [...Object.values(productCache)];
|
||||
let alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms);
|
||||
if (preferences.offlineModeEnabled) return alternatives;
|
||||
if (preferences.offlineModeEnabled) return preview ? alternatives.slice(0, 2) : alternatives;
|
||||
|
||||
const searchTags = categorySearchTags(product);
|
||||
if (searchTags.length === 0 && product.category) {
|
||||
const fallback = await searchProducts(product.category, productCache, false, { pageSize: 60 }).catch(() => []);
|
||||
return rankCandidates(product, productRating, [...candidates, ...fallback], preferences, context, categoryTerms);
|
||||
if (searchTags.length === 0) {
|
||||
const fallback = await searchFallbackProducts(product, productCache);
|
||||
const ranked = rankCandidates(product, productRating, [...candidates, ...fallback], preferences, context, categoryTerms);
|
||||
return preview ? ranked.slice(0, 2) : ranked;
|
||||
}
|
||||
|
||||
let successfulRequests = 0;
|
||||
for (const requestOptions of [
|
||||
for (const requestOptions of (preview ? [
|
||||
{ page: 1, grades: 'a|b|c' },
|
||||
{ page: 1, grades: null },
|
||||
{ page: 2, grades: null }
|
||||
] : [
|
||||
{ page: 1, grades: 'a|b' },
|
||||
{ page: 2, grades: 'a|b' },
|
||||
{ page: 1, grades: 'a|b|c' },
|
||||
{ page: 1, grades: null }
|
||||
]) {
|
||||
])) {
|
||||
const results = await Promise.allSettled(searchTags.map((tag) => searchProductsByCategory(tag, requestOptions)));
|
||||
results.forEach((result) => {
|
||||
if (result.status === 'fulfilled') {
|
||||
@@ -67,13 +91,47 @@ export async function findAlternatives(product, preferences, productCache = {},
|
||||
}
|
||||
});
|
||||
alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms);
|
||||
if (alternatives.length >= INTERNAL_ALTERNATIVE_LIMIT) break;
|
||||
if (alternatives.length >= (preview ? 2 : INTERNAL_ALTERNATIVE_LIMIT)) break;
|
||||
}
|
||||
|
||||
if (alternatives.length === 0) {
|
||||
const fallback = await searchFallbackProducts(product, productCache);
|
||||
candidates.push(...fallback);
|
||||
alternatives = rankCandidates(product, productRating, candidates, preferences, context, categoryTerms);
|
||||
}
|
||||
|
||||
if (successfulRequests === 0 && alternatives.length === 0 && searchTags.length > 0) {
|
||||
throw new Error('Open Food Facts ist für die Alternativsuche nicht erreichbar.');
|
||||
}
|
||||
return alternatives;
|
||||
return preview ? alternatives.slice(0, 2) : alternatives;
|
||||
}
|
||||
|
||||
export function alternativeSearchIssue(product, rating) {
|
||||
if (rating.overallScore === null) {
|
||||
return 'Für einen Vergleich fehlen auswertbare Produktangaben. Ergänze Nährwerte oder Zutaten.';
|
||||
}
|
||||
if (!productType(product) && specificCategoryTags(product).length === 0) {
|
||||
return 'Die Produktart ist nicht eindeutig. Ergänze eine konkrete Kategorie, um passende Alternativen zu suchen.';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
async function searchFallbackProducts(product, productCache) {
|
||||
const sourceType = productType(product);
|
||||
const typePattern = PRODUCT_TYPES.find(([type]) => type === sourceType)?.[1];
|
||||
const typeWordInName = typePattern ? normalizeTerm(product.name).match(typePattern)?.[0] : null;
|
||||
const category = normalizeTerm(product.category);
|
||||
const specificCategory = category && !BROAD_CATEGORY_TAGS.has(`en:${category.replace(/\s+/g, '-')}`)
|
||||
? product.category : null;
|
||||
const queries = uniqueStrings([
|
||||
typeWordInName,
|
||||
specificCategory,
|
||||
sourceType?.split('-')[0],
|
||||
product.name
|
||||
].filter(Boolean)).slice(0, 3);
|
||||
const results = await Promise.allSettled(queries.map((query) =>
|
||||
searchProducts(query, productCache, false, { pageSize: 100 })));
|
||||
return results.flatMap((result) => result.status === 'fulfilled' ? result.value : []);
|
||||
}
|
||||
|
||||
function rankCandidates(product, productRating, products, preferences, context, categoryTerms) {
|
||||
@@ -90,8 +148,13 @@ function rankCandidates(product, productRating, products, preferences, context,
|
||||
}))
|
||||
.map((item) => {
|
||||
const nutritionGain = nutritionImprovement(item.rating, productRating);
|
||||
return { ...item, nutritionImprovement: nutritionGain,
|
||||
healthEligible: nutritionGain >= HEALTH_IMPROVEMENT && !item.rating.goalReviewRequired };
|
||||
const sugarGain = sugarImprovement(product, item.product);
|
||||
return { ...item, nutritionImprovement: nutritionGain, sugarImprovement: sugarGain,
|
||||
healthEligible: (nutritionGain >= HEALTH_IMPROVEMENT || sugarGain >= 5)
|
||||
&& !item.rating.goalReviewRequired
|
||||
&& item.rating.categoryScores.nutrition.score >= productRating.categoryScores.nutrition.score - 5
|
||||
&& item.rating.overallScore !== null
|
||||
&& item.rating.overallScore >= productRating.overallScore - 5 };
|
||||
})
|
||||
.filter((item) => productRating.overallScore !== null
|
||||
&& item.rating.overallScore !== null
|
||||
@@ -101,9 +164,9 @@ function rankCandidates(product, productRating, products, preferences, context,
|
||||
...item,
|
||||
requiresAllergenCheck: item.rating.allergenReviewRequired,
|
||||
reason: item.rating.allergenReviewRequired
|
||||
? `${item.healthEligible ? nutritionReason(item.rating, productRating) : 'Mögliche Alternative.'} ${item.rating.allergenReviewMessage} Allergenfreiheit ist nicht bestätigt.`
|
||||
? `${item.healthEligible ? improvementReason(item, product, productRating) : 'Mögliche Alternative.'} ${item.rating.allergenReviewMessage} Allergenfreiheit ist nicht bestätigt.`
|
||||
: item.healthEligible
|
||||
? nutritionReason(item.rating, productRating)
|
||||
? improvementReason(item, product, productRating)
|
||||
: buildReason(item.rating, productRating, categoryTerms)
|
||||
}))
|
||||
.sort((left, right) => {
|
||||
@@ -124,11 +187,6 @@ function rankCandidates(product, productRating, products, preferences, context,
|
||||
return right.rating.dataCoverage - left.rating.dataCoverage;
|
||||
}
|
||||
|
||||
const priceDiff = priceForSort(left.product) - priceForSort(right.product);
|
||||
if (priceDiff !== 0) {
|
||||
return priceDiff;
|
||||
}
|
||||
|
||||
return right.dataQualityScore - left.dataQualityScore;
|
||||
})
|
||||
.filter(uniqueByProductName)
|
||||
@@ -153,6 +211,22 @@ function nutritionImprovement(rating, sourceRating) {
|
||||
? Math.max(0, nutrition.score - sourceNutrition.score) : 0;
|
||||
}
|
||||
|
||||
function sugarImprovement(source, candidate) {
|
||||
const sourceSugar = source.nutrition?.sugarPer100g;
|
||||
const candidateSugar = candidate.nutrition?.sugarPer100g;
|
||||
return Number.isFinite(sourceSugar) && Number.isFinite(candidateSugar)
|
||||
&& sourceSugar >= 10 && candidateSugar <= sourceSugar * 0.7
|
||||
? Math.max(0, sourceSugar - candidateSugar) : 0;
|
||||
}
|
||||
|
||||
function improvementReason(item, source, sourceRating) {
|
||||
if (item.sugarImprovement >= 5) {
|
||||
const unit = categoryGroupForProduct(source)?.tag === 'en:beverages' ? '100 ml' : '100 g';
|
||||
return `Weniger Zucker: ${item.product.nutrition.sugarPer100g} statt ${source.nutrition.sugarPer100g} g pro ${unit}.`;
|
||||
}
|
||||
return nutritionReason(item.rating, sourceRating);
|
||||
}
|
||||
|
||||
function nutritionReason(rating, sourceRating) {
|
||||
const nutrition = rating.categoryScores.nutrition;
|
||||
const sourceNutrition = sourceRating.categoryScores.nutrition;
|
||||
@@ -168,11 +242,10 @@ function categorySearchTags(product) {
|
||||
const rawTags = (product.categoryTags || [])
|
||||
.filter((tag) => /^en:[a-z0-9-]+$/.test(tag));
|
||||
const broadTag = categoryGroupForProduct(product)?.tag;
|
||||
const generic = new Set(['en:foods', 'en:plant-based-foods', 'en:plant-based-foods-and-beverages']);
|
||||
return uniqueStrings([
|
||||
...rawTags.filter((tag) => !generic.has(tag) && tag !== broadTag).slice(-2).reverse(),
|
||||
...rawTags.filter((tag) => !BROAD_CATEGORY_TAGS.has(tag) && tag !== broadTag).slice(-2).reverse(),
|
||||
broadTag,
|
||||
...rawTags.filter((tag) => !generic.has(tag)).slice(-1)
|
||||
...rawTags.filter((tag) => !BROAD_CATEGORY_TAGS.has(tag)).slice(-1)
|
||||
].filter(Boolean)).slice(0, 3);
|
||||
}
|
||||
|
||||
@@ -192,15 +265,27 @@ function categoryTermsForProduct(product) {
|
||||
}
|
||||
|
||||
function isSimilarCategory(sourceProduct, candidate) {
|
||||
const sourceTerms = productTerms(sourceProduct);
|
||||
const candidateTerms = productTerms(candidate);
|
||||
const sourceType = productType(sourceProduct);
|
||||
const candidateType = productType(candidate);
|
||||
const sourceTags = specificCategoryTags(sourceProduct);
|
||||
const sharedSpecificTag = sourceTags.some((tag) => specificCategoryTags(candidate).includes(tag));
|
||||
if (sourceType && candidateType && sourceType !== candidateType) return false;
|
||||
if (sharedSpecificTag) return true;
|
||||
return Boolean(sourceType && candidateType && sourceType === candidateType && sourceType !== 'spread');
|
||||
}
|
||||
|
||||
if (candidateTerms.some((term) => !GENERIC_CATEGORY_TERMS.has(term) && sourceTerms.includes(term))) {
|
||||
return true;
|
||||
}
|
||||
function productType(product) {
|
||||
const categoryText = [product.category, ...(product.categoryTags || [])
|
||||
.filter((tag) => !BROAD_CATEGORY_TAGS.has(tag))]
|
||||
.map(normalizeTerm).join(' ');
|
||||
const nameText = normalizeTerm(product.name);
|
||||
return PRODUCT_TYPES.find(([, pattern]) => pattern.test(categoryText))?.[0]
|
||||
|| PRODUCT_TYPES.find(([, pattern]) => pattern.test(nameText))?.[0];
|
||||
}
|
||||
|
||||
const sourceGroup = categoryGroupForProduct(sourceProduct);
|
||||
return Boolean(sourceGroup && sourceGroup === categoryGroupForProduct(candidate));
|
||||
function specificCategoryTags(product) {
|
||||
return (product.categoryTags || []).filter((tag) => /^en:[a-z0-9-]+$/.test(tag)
|
||||
&& !BROAD_CATEGORY_TAGS.has(tag));
|
||||
}
|
||||
|
||||
function categoryGroupForProduct(product) {
|
||||
@@ -258,7 +343,6 @@ function knownDataScore(product) {
|
||||
[completeness.ecoScore !== false, 1],
|
||||
[Boolean(sustainability.originCountry), 1],
|
||||
[Boolean(sustainability.packaging), 1],
|
||||
[typeof product.price === 'number', 1],
|
||||
[Boolean(product.imageUrl), 1]
|
||||
].reduce((score, [isKnown, weight]) => score + (isKnown ? weight : 0), 0);
|
||||
}
|
||||
@@ -289,10 +373,6 @@ function categoryScore(rating, category) {
|
||||
return rating.categoryScores?.[category]?.score || 0;
|
||||
}
|
||||
|
||||
function priceForSort(product) {
|
||||
return typeof product.price === 'number' ? product.price : Infinity;
|
||||
}
|
||||
|
||||
function hasKnownAllergens(product) {
|
||||
return Array.isArray(product.allergens) && product.dataCompleteness?.allergens !== false;
|
||||
}
|
||||
@@ -307,11 +387,7 @@ function uniqueProducts(products) {
|
||||
products.forEach((product) => {
|
||||
const key = product.barcode || product.id;
|
||||
const previous = byProduct.get(key);
|
||||
byProduct.set(key, previous ? {
|
||||
...product,
|
||||
price: product.price ?? previous.price,
|
||||
currency: product.currency || previous.currency
|
||||
} : product);
|
||||
byProduct.set(key, previous ? { ...previous, ...product } : product);
|
||||
});
|
||||
return Array.from(byProduct.values());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
export const FREE_SUGAR_REFERENCE_GRAMS = 50;
|
||||
|
||||
export function sugarLimitWarning(grams) {
|
||||
const value = Number(grams);
|
||||
if (!Number.isFinite(value) || value <= FREE_SUGAR_REFERENCE_GRAMS) return null;
|
||||
return `Du hast ${value} g pro Tag eingestellt. Die WHO empfiehlt bei 2.000 kcal weniger als ${FREE_SUGAR_REFERENCE_GRAMS} g freien Zucker pro Tag. Die App erfasst Gesamtzucker, auch natürlich enthaltenen Zucker. Deshalb ist dein Wert nicht direkt mit der WHO-Empfehlung vergleichbar.`;
|
||||
}
|
||||
|
||||
export function todayKey(date = new Date()) {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function dailyTargets(preferences) {
|
||||
const weight = Number(preferences.weightKg);
|
||||
const factor = preferences.exerciseGoal === 'muscle' ? 1.6
|
||||
: preferences.exerciseGoal === 'endurance' ? 1.2 : 0.83;
|
||||
return {
|
||||
protein: weight >= 20 && weight <= 350 ? Math.round(weight * factor) : null,
|
||||
sugar: Number(preferences.dailySugarLimitGrams) > 0 ? Number(preferences.dailySugarLimitGrams) : null,
|
||||
salt: 5,
|
||||
fiber: 25,
|
||||
vitaminB12: preferences.preferredDiet === 'vegan' ? 4 : null
|
||||
};
|
||||
}
|
||||
|
||||
export function nutritionForServing(product, grams) {
|
||||
const nutrition = product.nutrition || {};
|
||||
const amount = Number(grams);
|
||||
if (!Number.isFinite(amount) || amount <= 0) return { protein: null, sugar: null, salt: null, fiber: null, carbohydrates: null, vitaminB12: null };
|
||||
return {
|
||||
protein: Number.isFinite(nutrition.proteinPer100g) ? nutrition.proteinPer100g * amount / 100 : null,
|
||||
sugar: Number.isFinite(nutrition.sugarPer100g) ? nutrition.sugarPer100g * amount / 100 : null,
|
||||
salt: Number.isFinite(nutrition.saltPer100g) ? nutrition.saltPer100g * amount / 100 : null,
|
||||
fiber: Number.isFinite(nutrition.fiberPer100g) ? nutrition.fiberPer100g * amount / 100 : null,
|
||||
carbohydrates: Number.isFinite(nutrition.carbohydratesPer100g) ? nutrition.carbohydratesPer100g * amount / 100 : null,
|
||||
vitaminB12: Number.isFinite(nutrition.vitaminB12MicrogramsPer100g) ? nutrition.vitaminB12MicrogramsPer100g * amount / 100 : null
|
||||
};
|
||||
}
|
||||
|
||||
export function dailyTotals(entries, date = todayKey()) {
|
||||
return (entries || []).filter((entry) => entry.date === date).reduce((total, entry) => {
|
||||
for (const nutrient of ['protein', 'sugar', 'salt', 'fiber', 'carbohydrates', 'vitaminB12']) {
|
||||
if (Number.isFinite(entry[nutrient])) total[nutrient] += entry[nutrient];
|
||||
}
|
||||
total.count += 1;
|
||||
return total;
|
||||
}, { protein: 0, sugar: 0, salt: 0, fiber: 0, carbohydrates: 0, vitaminB12: 0, count: 0 });
|
||||
}
|
||||
|
||||
export function servingGrams(product) {
|
||||
const amount = Number(product.servingQuantityGrams || product.packageQuantityGrams);
|
||||
return Number.isFinite(amount) && amount > 0 ? amount : 100;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export function createLocalProduct(barcode) {
|
||||
const now = new Date().toISOString();
|
||||
return { id: `local-${barcode || Date.now()}`, barcode: barcode || `local-${Date.now()}`,
|
||||
name: '', brand: '', category: '', ingredients: [], allergens: [], allergenTraces: [],
|
||||
nutrition: {}, ingredientAnalysis: {}, sustainability: {}, dataCompleteness: {},
|
||||
dataSource: 'local', createdAt: now, updatedAt: now };
|
||||
}
|
||||
|
||||
export function saveManualProduct(product, changes) {
|
||||
const nutrition = { ...product.nutrition, ...changes.nutrition };
|
||||
if (Object.keys(changes.nutrition || {}).length) delete nutrition.nutriScore;
|
||||
return { ...product, ...changes, nutrition, manualOverrides: {
|
||||
...(product.manualOverrides || {}), ...changes,
|
||||
nutrition: { ...(product.manualOverrides?.nutrition || {}), ...(changes.nutrition || {}) }
|
||||
}, dataSource: product.dataSource || 'local', updatedAt: new Date().toISOString() };
|
||||
}
|
||||
|
||||
export function mergeManualOverrides(product, cached) {
|
||||
const overrides = cached?.manualOverrides;
|
||||
if (!overrides) return product;
|
||||
return { ...product, ...overrides, nutrition: { ...product.nutrition, ...overrides.nutrition },
|
||||
manualOverrides: overrides };
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { enrichEnvironmentalProduct, productSpecificFootprint } from './environmentalService.js';
|
||||
import { mergeManualOverrides } from './manualProduct.js';
|
||||
|
||||
const openFoodFactsBaseUrl = 'https://world.openfoodfacts.org';
|
||||
const openFoodFactsBaseUrl = 'https://ch.openfoodfacts.org';
|
||||
const CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
||||
export const NUTRITION_SCHEMA_VERSION = 2;
|
||||
const productFields = [
|
||||
'code',
|
||||
'last_modified_datetime',
|
||||
@@ -89,8 +90,6 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline
|
||||
status: 'found',
|
||||
product: mergeManualOverrides({
|
||||
...mapOpenFoodFactsProduct(payload.product, normalizedBarcode),
|
||||
price: cachedProduct?.price,
|
||||
currency: cachedProduct?.currency || 'CHF',
|
||||
createdAt: cachedProduct?.createdAt || new Date().toISOString()
|
||||
}, cachedProduct),
|
||||
source: 'open-food-facts'
|
||||
@@ -106,7 +105,8 @@ export async function lookupProductByBarcode(barcode, productCache = {}, offline
|
||||
|
||||
function isFreshCacheEntry(product) {
|
||||
const checkedAt = Date.parse(product.fetchedAt || '');
|
||||
return Number.isFinite(checkedAt) && Date.now() - checkedAt >= 0
|
||||
return product.nutritionSchemaVersion === NUTRITION_SCHEMA_VERSION
|
||||
&& Number.isFinite(checkedAt) && Date.now() - checkedAt >= 0
|
||||
&& Date.now() - checkedAt < CACHE_MAX_AGE_MS;
|
||||
}
|
||||
|
||||
@@ -199,6 +199,7 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
|
||||
id: `off-${barcode}`,
|
||||
barcode,
|
||||
dataSource: 'open-food-facts',
|
||||
nutritionSchemaVersion: NUTRITION_SCHEMA_VERSION,
|
||||
fetchedAt: now,
|
||||
name: product.product_name_de || product.product_name || product.product_name_en || `Produkt ${barcode}`,
|
||||
brand: firstTextValue(product.brands),
|
||||
@@ -212,8 +213,6 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
|
||||
packageQuantityGrams: numberOrUndefined(product.product_quantity),
|
||||
packageQuantityLabel: typeof product.quantity === 'string' ? product.quantity.trim() : undefined,
|
||||
servingQuantityGrams: numberOrUndefined(product.serving_quantity),
|
||||
price: undefined,
|
||||
currency: 'CHF',
|
||||
ingredients: parseIngredients(product.ingredients_text_de || product.ingredients_text || product.ingredients_text_en),
|
||||
ingredientAnalysis: {
|
||||
vegan: analysisStatus(product.ingredients_analysis_tags, 'vegan'),
|
||||
@@ -231,7 +230,10 @@ export function mapOpenFoodFactsProduct(product = {}, fallbackBarcode) {
|
||||
fatPer100g: numberOrUndefined(nutriments.fat_100g),
|
||||
saturatedFatPer100g: numberOrUndefined(nutriments['saturated-fat_100g']),
|
||||
proteinPer100g: numberOrUndefined(nutriments.proteins_100g),
|
||||
carbohydratesPer100g: numberOrUndefined(nutriments.carbohydrates_100g),
|
||||
fiberPer100g: numberOrUndefined(nutriments.fiber_100g),
|
||||
vitaminB12MicrogramsPer100g: numberOrUndefined(nutriments['vitamin-b12_100g']) === undefined
|
||||
? undefined : numberOrUndefined(nutriments['vitamin-b12_100g']) * 1000000,
|
||||
fruitVegetableLegumePercent: numberOrUndefined(nutriments['fruits-vegetables-legumes-estimate-from-ingredients_100g']),
|
||||
saltPer100g: numberOrUndefined(nutriments.salt_100g),
|
||||
hasNonNutritiveSweeteners: Array.isArray(product.additives_tags)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { calculateNutriScore } from './nutriScoreService.js';
|
||||
import { dailyTargets, dailyTotals, nutritionForServing, servingGrams } from './dailyNutritionService.js';
|
||||
|
||||
const nutrientLevelLabels = {
|
||||
fat: 'Fett',
|
||||
@@ -25,10 +26,10 @@ const ecoScoreValues = {
|
||||
|
||||
const categoryLabels = {
|
||||
allergies: 'Allergien',
|
||||
budget: 'Budget',
|
||||
ingredients: 'Zutaten',
|
||||
nutrition: 'Ernährung',
|
||||
sustainability: 'Nachhaltigkeit'
|
||||
sustainability: 'Nachhaltigkeit',
|
||||
goals: 'Deine Ziele'
|
||||
};
|
||||
|
||||
const additiveRiskGroups = [
|
||||
@@ -124,10 +125,9 @@ function severityFromStatus(status) {
|
||||
export function calculateProductRating(product, preferences, context = {}) {
|
||||
const categoryScores = {
|
||||
allergies: rateAllergies(product, preferences),
|
||||
budget: rateBudget(product, preferences, context),
|
||||
ingredients: rateIngredients(product, preferences),
|
||||
nutrition: rateNutrition(product, preferences),
|
||||
sustainability: rateSustainability(product, preferences)
|
||||
goals: rateGoals(product, preferences, context)
|
||||
};
|
||||
|
||||
const weights = ratingWeights(preferences);
|
||||
@@ -136,8 +136,6 @@ export function calculateProductRating(product, preferences, context = {}) {
|
||||
const goalConflict = categoryScores.ingredients.goalConflict === true;
|
||||
const goalReviewRequired = categoryScores.ingredients.goalReviewRequired === true
|
||||
|| categoryScores.nutrition.goalReviewRequired === true;
|
||||
const budgetReviewRequired = Number.isFinite(preferences.maxBudgetPerShoppingTrip)
|
||||
&& preferences.maxBudgetPerShoppingTrip > 0 && categoryScores.budget.hasKnownFacts === false;
|
||||
const { score: weightedScore, coverage } = weightedCategoryScore(categoryScores, weights, preferences, product);
|
||||
const coverageCap = coverage < 0.5 ? 65 : coverage < 0.8 ? 77 : 100;
|
||||
const overallScore = hasBlockedAllergen
|
||||
@@ -149,7 +147,6 @@ export function calculateProductRating(product, preferences, context = {}) {
|
||||
coverageCap,
|
||||
allergenReviewRequired ? 77 : 100,
|
||||
goalReviewRequired ? 77 : 100,
|
||||
budgetReviewRequired ? 77 : 100,
|
||||
product.cacheStale ? 77 : 100
|
||||
);
|
||||
const limitedByMissingData = !hasBlockedAllergen && weightedScore !== null
|
||||
@@ -160,7 +157,6 @@ export function calculateProductRating(product, preferences, context = {}) {
|
||||
if (allergenReviewRequired) scoreLimitReasons.push(categoryScores.allergies.reviewMessage);
|
||||
if (goalConflict) scoreLimitReasons.push('Das Produkt widerspricht deinem veganen oder vegetarischen Ziel.');
|
||||
if (goalReviewRequired) scoreLimitReasons.push('Für dein Ernährungsziel fehlen bestätigende Angaben.');
|
||||
if (budgetReviewRequired) scoreLimitReasons.push('Der Preis oder ein offener Listenpreis fehlt für die Budgetprüfung.');
|
||||
if (product.cacheStale) scoreLimitReasons.push('Gespeicherte Produktdaten sind veraltet. Verpackung prüfen.');
|
||||
if (limitedByMissingData) scoreLimitReasons.push('Fehlende Daten begrenzen die Gesamtwertung.');
|
||||
|
||||
@@ -180,7 +176,7 @@ export function calculateProductRating(product, preferences, context = {}) {
|
||||
allergenReviewRequired,
|
||||
goalConflict,
|
||||
goalReviewRequired,
|
||||
budgetReviewRequired,
|
||||
budgetReviewRequired: false,
|
||||
staleDataReviewRequired: product.cacheStale === true,
|
||||
hasBlockedAllergen,
|
||||
allergenReviewMessage: categoryScores.allergies.reviewMessage,
|
||||
@@ -192,13 +188,11 @@ export function calculateProductRating(product, preferences, context = {}) {
|
||||
}
|
||||
|
||||
function ratingWeights(preferences) {
|
||||
const priorityFactors = { low: 0.5, medium: 0.75, high: 1 };
|
||||
return {
|
||||
allergies: 0.1,
|
||||
budget: 0.2,
|
||||
allergies: 0.2,
|
||||
ingredients: 0.15,
|
||||
nutrition: 0.35 * (priorityFactors[preferences.nutritionPriority] ?? 1),
|
||||
sustainability: 0.2 * (priorityFactors[preferences.sustainabilityPriority] ?? 0.75)
|
||||
nutrition: 0.45,
|
||||
goals: 0.2
|
||||
};
|
||||
}
|
||||
|
||||
@@ -226,9 +220,6 @@ function weightedCategoryScore(categoryScores, weights, preferences, product) {
|
||||
function applicableCategoryEntries(categoryScores, preferences) {
|
||||
return Object.entries(categoryScores).filter(([category]) => (
|
||||
category !== 'allergies' || (preferences.avoidAllergens || []).length > 0
|
||||
) && (
|
||||
category !== 'budget' || Number.isFinite(preferences.maxBudgetPerShoppingTrip)
|
||||
&& preferences.maxBudgetPerShoppingTrip > 0
|
||||
));
|
||||
}
|
||||
|
||||
@@ -238,7 +229,15 @@ function factCoverage(product, preferences, category, rating) {
|
||||
const analysis = product.ingredientAnalysis || {};
|
||||
const ingredients = ingredientTerms(product);
|
||||
|
||||
if (category === 'allergies' || category === 'budget') return 1;
|
||||
if (category === 'allergies') return 1;
|
||||
|
||||
if (category === 'goals') {
|
||||
const targets = dailyTargets(preferences);
|
||||
const endurance = preferences.exerciseGoal === 'endurance';
|
||||
return (Number(targets.protein !== null && Number.isFinite(nutrition.proteinPer100g))
|
||||
+ Number(targets.sugar !== null && Number.isFinite(nutrition.sugarPer100g))
|
||||
+ Number(endurance && Number.isFinite(nutrition.carbohydratesPer100g))) / (endurance ? 3 : 2);
|
||||
}
|
||||
|
||||
if (category === 'nutrition') {
|
||||
const needsSugar = preferences.preferredDiet === 'lowSugar';
|
||||
@@ -283,13 +282,73 @@ function ratingFactors(categoryScores, weights, preferences) {
|
||||
category,
|
||||
label: categoryLabels[category],
|
||||
score: value.score,
|
||||
message: value.message,
|
||||
message: value.summary || value.message,
|
||||
impact: Math.round((100 - value.score) * weights[category])
|
||||
}))
|
||||
.sort((left, right) => right.impact - left.impact)
|
||||
.slice(0, 2);
|
||||
}
|
||||
|
||||
function rateGoals(product, preferences, context) {
|
||||
const grams = servingGrams(product);
|
||||
const serving = nutritionForServing(product, grams);
|
||||
const totals = dailyTotals(context.dailyLog);
|
||||
const targets = dailyTargets(preferences);
|
||||
const details = [];
|
||||
const components = [];
|
||||
if (targets.protein !== null && serving.protein !== null) {
|
||||
const remaining = Math.max(0, targets.protein - totals.protein);
|
||||
const useful = remaining > 0 && serving.protein >= 5;
|
||||
components.push(scoreComponent(useful ? 90 : remaining === 0 ? 60 : 70, 1));
|
||||
details.push({ type: useful ? 'positive' : 'info', title: 'Protein',
|
||||
body: `${Math.round(serving.protein)} g pro Portion · Heute: ${Math.round(totals.protein)} / ca. ${targets.protein} g. ${remaining === 0 ? 'Richtwert bereits erreicht.' : `Noch ca. ${Math.round(remaining)} g bis zum Richtwert.`}` });
|
||||
}
|
||||
if (targets.sugar !== null && serving.sugar !== null) {
|
||||
const remaining = Math.max(0, targets.sugar - totals.sugar);
|
||||
const exceeds = serving.sugar > remaining;
|
||||
components.push(scoreComponent(exceeds ? 35 : serving.sugar > 15 ? 65 : 95, 2));
|
||||
details.push({ type: exceeds ? 'penalty' : 'info', title: 'Zucker',
|
||||
body: `${Math.round(serving.sugar)} g pro Portion · Heute: ${Math.round(totals.sugar)} / ${targets.sugar} g. ${exceeds ? 'Mit dieser Portion über deinem eingestellten Wert.' : 'Mit dieser Portion innerhalb deines Werts.'}` });
|
||||
}
|
||||
if (serving.salt !== null) {
|
||||
const over = totals.salt + serving.salt >= targets.salt;
|
||||
details.push({ type: over ? 'penalty' : 'info', title: 'Salz',
|
||||
body: `${serving.salt.toFixed(1)} g pro Portion · Heute: ${totals.salt.toFixed(1)} g. WHO-Orientierung: unter 5 g täglich. ${over ? 'Mit dieser Portion erreicht oder überschritten.' : ''} Im Nutri-Score bereits berücksichtigt.` });
|
||||
}
|
||||
if (serving.fiber !== null) {
|
||||
details.push({ type: 'info', title: 'Ballaststoffe',
|
||||
body: `${serving.fiber.toFixed(1)} g pro Portion · Heute: ${totals.fiber.toFixed(1)} / ca. ${targets.fiber} g. Im Nutri-Score bereits berücksichtigt.` });
|
||||
}
|
||||
if (preferences.exerciseGoal === 'endurance' && serving.carbohydrates !== null) {
|
||||
const useful = serving.carbohydrates >= 15;
|
||||
components.push(scoreComponent(useful ? 90 : 70, 1));
|
||||
details.push({ type: useful ? 'positive' : 'info', title: 'Kohlenhydrate für Ausdauer',
|
||||
body: `${Math.round(serving.carbohydrates)} g pro Portion. ${useful ? 'Liefert Trainingsenergie.' : 'Liefert eher wenig Trainingsenergie.'} Der Tagesbedarf hängt vom Training ab.` });
|
||||
}
|
||||
if (targets.vitaminB12 !== null && serving.vitaminB12 !== null) {
|
||||
details.push({ type: serving.vitaminB12 > 0 ? 'positive' : 'info', title: 'Vitamin B12 bei veganer Ernährung',
|
||||
body: `${serving.vitaminB12.toFixed(1)} µg pro Portion · Heute: ${totals.vitaminB12.toFixed(1)} / ca. ${targets.vitaminB12} µg. Nur angegebene Werte werden gezählt.` });
|
||||
}
|
||||
if (!components.length) return withScore(50, 'Für eine persönliche Einschätzung fehlen Nährwerte oder Profilangaben.',
|
||||
['Protein- und Zuckerwerte pro 100 g sowie dein Profil prüfen.'], { hasKnownFacts: false, details });
|
||||
const score = weightedKnownScore(components, 50);
|
||||
const missingData = [
|
||||
targets.protein !== null && serving.protein === null ? 'Proteinwert pro 100 g fehlt.' : null,
|
||||
targets.sugar !== null && serving.sugar === null ? 'Zuckerwert pro 100 g fehlt.' : null,
|
||||
serving.salt === null ? 'Salzwert pro 100 g fehlt.' : null,
|
||||
serving.fiber === null ? 'Ballaststoffwert pro 100 g fehlt.' : null,
|
||||
preferences.exerciseGoal === 'endurance' && serving.carbohydrates === null
|
||||
? product.cacheStale ? 'Kohlenhydratwert im alten Cache nicht verfügbar. Online erneut scannen.' : 'Kohlenhydratwert pro 100 g fehlt.' : null,
|
||||
targets.vitaminB12 !== null && serving.vitaminB12 === null ? 'Vitamin-B12-Wert fehlt; kein Rückschluss auf den Vitamingehalt möglich.' : null
|
||||
].filter(Boolean);
|
||||
const summaryParts = [];
|
||||
if (serving.sugar !== null) summaryParts.push(`${Math.round(serving.sugar)} g Zucker pro Portion`);
|
||||
if (serving.protein !== null) summaryParts.push(`${Math.round(serving.protein)} g Protein`);
|
||||
if (preferences.exerciseGoal === 'endurance' && serving.carbohydrates !== null) summaryParts.push(`${Math.round(serving.carbohydrates)} g Kohlenhydrate`);
|
||||
const summary = summaryParts.join(' · ') || 'Tageswerte prüfen';
|
||||
return withScore(score, summary, missingData, { details, hasKnownFacts: true, summary });
|
||||
}
|
||||
|
||||
function rateAllergies(product, preferences) {
|
||||
const avoidAllergens = preferences.avoidAllergens || [];
|
||||
const matchingAllergens = (product.allergens || []).filter((allergen) =>
|
||||
@@ -512,47 +571,6 @@ function rateSustainability(product, preferences) {
|
||||
: options.hasKnownFacts ? 'Nachhaltigkeit anhand verfügbarer Angaben geschätzt.' : 'Nachhaltigkeitsangaben fehlen.', missingData, options);
|
||||
}
|
||||
|
||||
function rateBudget(product, preferences, context) {
|
||||
const openItems = context.shoppingList?.items?.filter((item) => !item.checked) || [];
|
||||
const unpricedItems = openItems.filter((item) => !Number.isFinite(item.estimatedPrice) || item.estimatedPrice < 0).length;
|
||||
const missingData = missingMessages([
|
||||
[!Number.isFinite(product.price) || product.price < 0, 'Produktpreis fehlt oder ist ungültig.'],
|
||||
[!Number.isFinite(preferences.maxBudgetPerShoppingTrip) || preferences.maxBudgetPerShoppingTrip <= 0, 'Budgetlimit fehlt im Profil.'],
|
||||
[unpricedItems > 0, `${unpricedItems} offene Listenartikel ohne Preis.`]
|
||||
]);
|
||||
|
||||
if (!Number.isFinite(product.price) || !Number.isFinite(preferences.maxBudgetPerShoppingTrip)
|
||||
|| preferences.maxBudgetPerShoppingTrip <= 0 || product.price < 0) {
|
||||
return withScore(55, 'Preis oder Budget fehlt für eine genaue Prüfung.', missingData, { hasKnownFacts: false });
|
||||
}
|
||||
|
||||
const existingTotal = openItems.reduce((sum, item) => sum +
|
||||
(Number.isFinite(item.estimatedPrice) && item.estimatedPrice >= 0 ? item.estimatedPrice * Math.max(1, item.quantity || 1) : 0), 0);
|
||||
const projectedTotal = existingTotal + product.price;
|
||||
const share = projectedTotal / preferences.maxBudgetPerShoppingTrip;
|
||||
const periodLabel = budgetPeriodLabel(preferences.budgetPeriod);
|
||||
const score = budgetScore(share);
|
||||
const contextText = openItems.length > 0 ? 'Offene Einkaufsliste inklusive dieses Produkts' : 'Dieses Produkt';
|
||||
|
||||
if (unpricedItems > 0 && share <= 1) {
|
||||
return withScore(55, 'Listenpreis unvollständig; Budgeteinhaltung ist nicht belegt.', missingData, { hasKnownFacts: false });
|
||||
}
|
||||
|
||||
if (share > 1) {
|
||||
return withScore(Math.min(score, 35), `${contextText} überschreitet dein Budget pro ${periodLabel}.`, missingData);
|
||||
}
|
||||
|
||||
if (share <= 0.08) {
|
||||
return withScore(score, `${contextText} nutzt nur einen kleinen Teil deines Budgets pro ${periodLabel}.`, missingData);
|
||||
}
|
||||
|
||||
if (share <= 0.18) {
|
||||
return withScore(score, `${contextText} nutzt einen spürbaren Teil deines Budgets pro ${periodLabel}.`, missingData);
|
||||
}
|
||||
|
||||
return withScore(score, `${contextText} nutzt einen grossen Teil deines Budgets pro ${periodLabel}.`, missingData);
|
||||
}
|
||||
|
||||
function nutritionScoreFromData(product, nutrition, nutrientLevels) {
|
||||
if (nutrition.nutriScore === 'A' && isWaterLike(product) && hasNoCriticalNutrients(nutrition, nutrientLevels)) {
|
||||
return 98;
|
||||
@@ -865,18 +883,6 @@ function sustainabilityScoreComponents(product, preferences) {
|
||||
return components;
|
||||
}
|
||||
|
||||
function budgetScore(share) {
|
||||
if (share <= 0.08) {
|
||||
return interpolate(share, 0, 0.08, 100, 86);
|
||||
}
|
||||
|
||||
if (share <= 0.18) {
|
||||
return interpolate(share, 0.08, 0.18, 86, 55);
|
||||
}
|
||||
|
||||
return clampScore(interpolate(Math.min(share, 0.4), 0.18, 0.4, 55, 0));
|
||||
}
|
||||
|
||||
function statusFromNutrientLevels(highLevels, moderateLevels) {
|
||||
if (highLevels.length >= 2 || highLevels.includes('sugars') || highLevels.includes('salt')) {
|
||||
return 'critical';
|
||||
@@ -915,23 +921,13 @@ function formatNutrientLevelList(keys) {
|
||||
return keys.map((key) => nutrientLevelLabels[key] || key).join(', ');
|
||||
}
|
||||
|
||||
function budgetPeriodLabel(period) {
|
||||
const labels = {
|
||||
day: 'Tag',
|
||||
week: 'Woche',
|
||||
month: 'Monat',
|
||||
shoppingTrip: 'Einkauf'
|
||||
};
|
||||
|
||||
return labels[period] || labels.week;
|
||||
}
|
||||
|
||||
function withScore(score, message, missingData = [], options = {}) {
|
||||
const roundedScore = Math.round(clampScore(score));
|
||||
const hasKnownFacts = options.hasKnownFacts !== false;
|
||||
return {
|
||||
status: hasKnownFacts ? statusFromScore(roundedScore) : 'unknown',
|
||||
score: hasKnownFacts ? roundedScore : null,
|
||||
summary: options.summary,
|
||||
message,
|
||||
missingData,
|
||||
...options
|
||||
|
||||
@@ -4,8 +4,8 @@ const keys = {
|
||||
preferences: 'shoppinguin.preferences',
|
||||
shoppingList: 'shoppinguin.shoppingList',
|
||||
productCache: 'shoppinguin.productCache',
|
||||
manualPrices: 'shoppinguin.manualPrices',
|
||||
recentProducts: 'shoppinguin.recentProducts'
|
||||
recentProducts: 'shoppinguin.recentProducts',
|
||||
dailyLog: 'shoppinguin.dailyLog'
|
||||
};
|
||||
|
||||
const legacyPrefix = 'shoppy.';
|
||||
@@ -52,10 +52,13 @@ export const storageService = {
|
||||
saveShoppingList: (shoppingList) => writeJson(keys.shoppingList, shoppingList),
|
||||
loadProductCache: () => readJson(keys.productCache, {}),
|
||||
saveProductCache: (cache) => writeJson(keys.productCache, cache),
|
||||
loadManualPrices: () => readJson(keys.manualPrices, {}),
|
||||
saveManualPrices: (prices) => writeJson(keys.manualPrices, prices),
|
||||
clearDeprecatedPrices: () => enqueueWrite(() => AsyncStorage.multiRemove([
|
||||
'shoppinguin.manualPrices', 'shoppy.manualPrices'
|
||||
])),
|
||||
loadRecentProducts: () => readJson(keys.recentProducts, []),
|
||||
saveRecentProducts: (products) => writeJson(keys.recentProducts, products),
|
||||
loadDailyLog: () => readJson(keys.dailyLog, []),
|
||||
saveDailyLog: (entries) => writeJson(keys.dailyLog, entries),
|
||||
clearProductHistoryAndCache: () => enqueueWrite(() => AsyncStorage.multiRemove([
|
||||
keys.productCache,
|
||||
keys.recentProducts,
|
||||
|
||||
+14
-11
@@ -17,12 +17,22 @@ export const defaultPreferences = {
|
||||
avoidAllergens: [],
|
||||
preferredDiet: 'none',
|
||||
preferBio: false,
|
||||
maxBudgetPerShoppingTrip: undefined,
|
||||
budgetPeriod: 'week',
|
||||
currency: 'CHF',
|
||||
offlineModeEnabled: false,
|
||||
sustainabilityPriority: 'medium',
|
||||
nutritionPriority: 'high'
|
||||
nutritionPriority: 'high',
|
||||
onboardingComplete: false,
|
||||
age: '',
|
||||
heightCm: '',
|
||||
weightKg: '',
|
||||
exerciseGoal: 'general',
|
||||
dailySugarLimitGrams: 50
|
||||
};
|
||||
|
||||
export const exerciseGoalLabels = {
|
||||
general: 'Allgemeine Fitness',
|
||||
muscle: 'Muskelaufbau',
|
||||
endurance: 'Ausdauer',
|
||||
maintenance: 'Wohlbefinden'
|
||||
};
|
||||
|
||||
export const dietLabels = {
|
||||
@@ -32,10 +42,3 @@ export const dietLabels = {
|
||||
lowSugar: 'Wenig Zucker',
|
||||
highProtein: 'Proteinreich'
|
||||
};
|
||||
|
||||
export const budgetPeriodLabels = {
|
||||
day: 'Tag',
|
||||
week: 'Woche',
|
||||
month: 'Monat',
|
||||
shoppingTrip: 'Einkauf'
|
||||
};
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
export function formatPrice(value, currency = 'CHF') {
|
||||
if (typeof value !== 'number') {
|
||||
return 'Preis offen';
|
||||
}
|
||||
|
||||
return `${currency} ${value.toFixed(2)}`;
|
||||
}
|
||||
Reference in New Issue
Block a user