diff --git a/App.js b/App.js
index 6cd006b..6e9ec17 100644
--- a/App.js
+++ b/App.js
@@ -5,6 +5,7 @@ import { StatusBar } from 'expo-status-bar';
import BottomTabBar from './src/components/layout/BottomTabBar';
import AlternativesScreen from './src/screens/AlternativesScreen';
import HomeScreen from './src/screens/HomeScreen';
+import NutritionInsightsScreen from './src/screens/NutritionInsightsScreen';
import OnboardingScreen from './src/screens/OnboardingScreen';
import ProductDetailScreen from './src/screens/ProductDetailScreen';
import ProductEditScreen from './src/screens/ProductEditScreen';
@@ -17,7 +18,12 @@ import { lookupProductByBarcode, NUTRITION_SCHEMA_VERSION } from './src/services
import { enrichEnvironmentalProduct } from './src/services/environmentalService';
import { createLocalProduct, saveManualProduct } from './src/services/manualProduct';
import { storageService } from './src/services/storageService';
-import { nutritionForServing, servingGrams, todayKey } from './src/services/dailyNutritionService';
+import {
+ appendConsumptionEntry,
+ createConsumptionEntry,
+ editConsumptionEntry,
+ removeConsumptionEntry
+} from './src/services/dailyNutritionService';
import { colors, defaultPreferences } from './src/utils/constants';
const initialShoppingList = {
@@ -174,20 +180,28 @@ export default function App() {
onStartScan={() => setActiveTab('scan')}
preferences={preferences}
dailyLog={dailyLog}
- onUndoConsumption={() => setDailyLog((current) => current.slice(0, -1))}
+ onDeleteConsumption={deleteConsumption}
+ onUpdateConsumption={updateConsumption}
+ onOpenInsights={() => setRoute({ name: 'nutritionInsights' })}
recentProducts={recentProducts}
shoppingList={shoppingList}
/>
);
}, [activeTab, dailyLog, isClearingProductData, lastDeletedListItem, preferences, productCache, recentProducts, shoppingList]);
- function recordConsumption(product) {
- const grams = servingGrams(product);
- const nutrients = nutritionForServing(product, grams);
- setDailyLog((current) => [...current.filter((entry) => entry.date === todayKey()), {
- id: `${Date.now()}-${Math.random()}`, date: todayKey(), productName: product.name,
- grams, ...nutrients
- }]);
+ function recordConsumption(product, grams, date) {
+ const entry = createConsumptionEntry(product, grams, { date });
+ if (!entry) return false;
+ setDailyLog((current) => appendConsumptionEntry(current, entry));
+ return true;
+ }
+
+ function updateConsumption(entryId, grams) {
+ setDailyLog((current) => editConsumptionEntry(current, entryId, grams));
+ }
+
+ function deleteConsumption(entryId) {
+ setDailyLog((current) => removeConsumptionEntry(current, entryId));
}
async function clearProductHistoryAndCache() {
@@ -395,6 +409,11 @@ export default function App() {
return true;
}
+ if (route.name === 'nutritionInsights') {
+ setRoute({ name: 'tabs' });
+ return true;
+ }
+
if (route.name === 'ratingCriteria' && routeProduct) {
setRoute({ name: 'productDetail', product: routeProduct });
return true;
@@ -431,6 +450,20 @@ export default function App() {
return ;
}
+ if (route.name === 'nutritionInsights') {
+ return (
+ {
+ setActiveTab('scan');
+ setRoute({ name: 'tabs' });
+ }}
+ onBack={goBackToTabs}
+ preferences={preferences}
+ />
+ );
+ }
+
if (route.name === 'productEdit' && routeProduct) {
return ;
@@ -439,6 +472,7 @@ export default function App() {
if (route.name === 'productDetail' && routeProduct) {
return (
Kohlenhydrate: {Math.round(totals.carbohydrates)} g erfasst (bedarf abhängig vom Training) : null}
{targets.vitaminB12 !== null ? Vitamin B12: {totals.vitaminB12.toFixed(1)} µg / ca. {targets.vitaminB12} µg (nur angegebene Werte) : null}
{totals.count} Portionen erfasst
- {totals.count > 0 ?
- Letzte Erfassung rückgängig machen
- : null}
+ Tagesprotokoll
+
+
+
Dein Einkauf
diff --git a/src/screens/ProductDetailScreen.js b/src/screens/ProductDetailScreen.js
index 1c5ccf0..523631c 100644
--- a/src/screens/ProductDetailScreen.js
+++ b/src/screens/ProductDetailScreen.js
@@ -3,6 +3,7 @@ import { Alert, Linking, Platform, Pressable, StyleSheet, Text, View } from 'rea
import PrimaryButton from '../components/PrimaryButton';
import SecondaryButton from '../components/SecondaryButton';
+import PortionSelector from '../components/consumption/PortionSelector';
import AppHeader from '../components/layout/AppHeader';
import ScreenContainer from '../components/layout/ScreenContainer';
import SectionTitle from '../components/layout/SectionTitle';
@@ -11,6 +12,7 @@ import ProductScoreBadge from '../components/product/ProductScoreBadge';
import RatingCategoryRow from '../components/product/RatingCategoryRow';
import { calculateProductRating } from '../services/ratingService';
import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService';
+import { todayKey } from '../services/dailyNutritionService';
import { colors } from '../utils/constants';
export default function ProductDetailScreen({
@@ -29,6 +31,8 @@ export default function ProductDetailScreen({
onRecordConsumption
}) {
const [savedMessage, setSavedMessage] = useState('');
+ const [consumptionMessage, setConsumptionMessage] = useState('');
+ const [isChoosingPortion, setIsChoosingPortion] = useState(false);
const [suggestions, setSuggestions] = useState([]);
const [suggestionsLoading, setSuggestionsLoading] = useState(true);
const [suggestionsError, setSuggestionsError] = useState(false);
@@ -148,8 +152,29 @@ export default function ProductDetailScreen({
) : null}
- { onRecordConsumption(product); setSavedMessage('Portion im Tagesprotokoll erfasst.'); }} />
- Portionsgrösse laut Produkt, sonst Packungsmenge oder 100 g.
+ {consumptionMessage ? (
+
+ {consumptionMessage}
+
+ ) : null}
+ {isChoosingPortion ? (
+ setIsChoosingPortion(false)}
+ onConfirm={(grams, date) => {
+ onRecordConsumption(product, grams, date);
+ setConsumptionMessage(date === todayKey()
+ ? `${formatAmount(grams)} g heute im Tagesprotokoll erfasst.`
+ : `${formatAmount(grams)} g für ${formatEntryDate(date)} nachgetragen.`);
+ setIsChoosingPortion(false);
+ }}
+ product={product}
+ />
+ ) : (
+ {
+ setConsumptionMessage('');
+ setIsChoosingPortion(true);
+ }} />
+ )}
Ähnliche, bessere Alternativen
{suggestionsLoading ? Passende Produkte werden gesucht ... : null}
@@ -319,6 +344,15 @@ function formatImpact(value, maximumFractionDigits = 2) {
return new Intl.NumberFormat('de-CH', { maximumFractionDigits, minimumFractionDigits: value < 0.01 ? 3 : 0 }).format(value);
}
+function formatAmount(value) {
+ return new Intl.NumberFormat('de-CH', { maximumFractionDigits: 1 }).format(value);
+}
+
+function formatEntryDate(dateKey) {
+ const date = new Date(`${dateKey}T12:00:00`);
+ return Number.isNaN(date.getTime()) ? dateKey : date.toLocaleDateString('de-CH');
+}
+
function formatIndicator(indicator) {
if (typeof indicator?.value !== 'number') return 'Nicht verfügbar';
return `${new Intl.NumberFormat('de-CH', { maximumSignificantDigits: 3 }).format(indicator.value)} ${indicator.unit}`;
diff --git a/src/services/dailyNutritionService.js b/src/services/dailyNutritionService.js
index 947d9c8..bc14a8d 100644
--- a/src/services/dailyNutritionService.js
+++ b/src/services/dailyNutritionService.js
@@ -1,5 +1,7 @@
export const FREE_SUGAR_REFERENCE_GRAMS = 50;
+export const trackedNutrients = ['protein', 'sugar', 'salt', 'fiber', 'carbohydrates', 'vitaminB12'];
+
export function sugarLimitWarning(grams) {
const value = Number(grams);
if (!Number.isFinite(value) || value <= FREE_SUGAR_REFERENCE_GRAMS) return null;
@@ -10,6 +12,22 @@ export function todayKey(date = new Date()) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}
+export function isValidConsumptionDate(value, maximumDate = todayKey()) {
+ return parseDateKey(value) !== null && value <= maximumDate;
+}
+
+export function shiftDateKey(value, days) {
+ const date = parseDateKey(value);
+ if (!date || !Number.isInteger(days)) return null;
+ date.setDate(date.getDate() + days);
+ return todayKey(date);
+}
+
+export function sevenDayDateKeys(endDate = todayKey()) {
+ const validEndDate = parseDateKey(endDate) ? endDate : todayKey();
+ return Array.from({ length: 7 }, (_, index) => shiftDateKey(validEndDate, index - 6));
+}
+
export function dailyTargets(preferences) {
const weight = Number(preferences.weightKg);
const factor = preferences.exerciseGoal === 'muscle' ? 1.6
@@ -37,9 +55,62 @@ export function nutritionForServing(product, grams) {
};
}
+export function createConsumptionEntry(product, grams, options = {}) {
+ const amount = Number(grams);
+ if (!Number.isFinite(amount) || amount <= 0) return null;
+
+ const recordedAt = options.recordedAt || new Date().toISOString();
+ return {
+ id: options.id || `consumption-${Date.now()}-${Math.random().toString(36).slice(2)}`,
+ date: options.date || todayKey(),
+ recordedAt,
+ productId: product.id,
+ barcode: product.barcode,
+ productName: product.name || 'Produkt',
+ grams: amount,
+ nutrition: { ...(product.nutrition || {}) },
+ ...nutritionForServing(product, amount)
+ };
+}
+
+export function updateConsumptionEntry(entry, grams) {
+ const amount = Number(grams);
+ if (!Number.isFinite(amount) || amount <= 0) return entry;
+
+ if (entry.nutrition) {
+ return {
+ ...entry,
+ grams: amount,
+ ...nutritionForServing({ nutrition: entry.nutrition }, amount)
+ };
+ }
+
+ const previousAmount = Number(entry.grams);
+ if (!Number.isFinite(previousAmount) || previousAmount <= 0) return { ...entry, grams: amount };
+ const factor = amount / previousAmount;
+ return trackedNutrients.reduce((updated, nutrient) => ({
+ ...updated,
+ [nutrient]: Number.isFinite(entry[nutrient]) ? entry[nutrient] * factor : entry[nutrient]
+ }), { ...entry, grams: amount });
+}
+
+export function appendConsumptionEntry(entries, entry) {
+ return [...(Array.isArray(entries) ? entries : []), entry];
+}
+
+export function editConsumptionEntry(entries, entryId, grams) {
+ return (Array.isArray(entries) ? entries : []).map((entry) =>
+ entry.id === entryId ? updateConsumptionEntry(entry, grams) : entry
+ );
+}
+
+export function removeConsumptionEntry(entries, entryId) {
+ return (Array.isArray(entries) ? entries : []).filter((entry) => entry.id !== entryId);
+}
+
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']) {
+ for (const nutrient of trackedNutrients) {
if (Number.isFinite(entry[nutrient])) total[nutrient] += entry[nutrient];
}
total.count += 1;
@@ -47,7 +118,88 @@ export function dailyTotals(entries, date = todayKey()) {
}, { protein: 0, sugar: 0, salt: 0, fiber: 0, carbohydrates: 0, vitaminB12: 0, count: 0 });
}
+export function consumptionDates(entries) {
+ return [...new Set((entries || []).map((entry) => entry.date).filter(Boolean))]
+ .sort((a, b) => b.localeCompare(a));
+}
+
+export function nutritionCoverage(entries) {
+ const relevantEntries = Array.isArray(entries) ? entries : [];
+ return trackedNutrients.reduce((coverage, nutrient) => {
+ const knownEntries = relevantEntries.filter((entry) => Number.isFinite(entry[nutrient])).length;
+ coverage[nutrient] = {
+ knownEntries,
+ totalEntries: relevantEntries.length,
+ percentage: relevantEntries.length ? Math.round(knownEntries / relevantEntries.length * 100) : 0
+ };
+ return coverage;
+ }, {});
+}
+
+export function sevenDayNutritionSummary(entries, preferences, endDate = todayKey()) {
+ const dates = sevenDayDateKeys(endDate);
+ const dateSet = new Set(dates);
+ const weekEntries = (entries || []).filter((entry) => dateSet.has(entry.date));
+ const targets = dailyTargets(preferences);
+ const days = dates.map((date) => {
+ const dayEntries = weekEntries.filter((entry) => entry.date === date);
+ return {
+ date,
+ entries: dayEntries,
+ totals: dailyTotals(dayEntries, date),
+ coverage: nutritionCoverage(dayEntries)
+ };
+ });
+ const totals = trackedNutrients.reduce((result, nutrient) => {
+ result[nutrient] = weekEntries.reduce((sum, entry) =>
+ sum + (Number.isFinite(entry[nutrient]) ? entry[nutrient] : 0), 0);
+ return result;
+ }, {});
+
+ return {
+ startDate: dates[0],
+ endDate: dates[dates.length - 1],
+ dates,
+ days,
+ entries: weekEntries,
+ loggedDays: days.filter((day) => day.entries.length > 0).length,
+ totals,
+ coverage: nutritionCoverage(weekEntries),
+ patterns: targetPatterns(days, targets)
+ };
+}
+
export function servingGrams(product) {
const amount = Number(product.servingQuantityGrams || product.packageQuantityGrams);
return Number.isFinite(amount) && amount > 0 ? amount : 100;
}
+
+function targetPatterns(days, targets) {
+ const directions = { protein: 'minimum', sugar: 'maximum', salt: 'maximum', fiber: 'minimum', vitaminB12: 'minimum' };
+ return Object.entries(directions).reduce((patterns, [nutrient, direction]) => {
+ const target = targets[nutrient];
+ if (!Number.isFinite(target)) return patterns;
+ const completeDays = days.filter((day) =>
+ day.entries.length > 0 && day.coverage[nutrient].percentage === 100
+ );
+ const meetingDays = completeDays.filter((day) => direction === 'maximum'
+ ? day.totals[nutrient] <= target
+ : day.totals[nutrient] >= target);
+ patterns[nutrient] = {
+ target,
+ direction,
+ completeDays: completeDays.length,
+ meetingDays: meetingDays.length,
+ missedDays: completeDays.length - meetingDays.length
+ };
+ return patterns;
+ }, {});
+}
+
+function parseDateKey(value) {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value));
+ if (!match) return null;
+ const [, year, month, day] = match;
+ const date = new Date(Number(year), Number(month) - 1, Number(day), 12);
+ return todayKey(date) === value ? date : null;
+}