add editable nutrition log and 7-day insights
Android Release Build / build-android (push) Failing after 7m46s
Android Release Build / build-android (push) Failing after 7m46s
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import PrimaryButton from '../components/PrimaryButton';
|
||||
import SecondaryButton from '../components/SecondaryButton';
|
||||
import DailyConsumptionLog from '../components/consumption/DailyConsumptionLog';
|
||||
import AppHeader from '../components/layout/AppHeader';
|
||||
import ScreenContainer from '../components/layout/ScreenContainer';
|
||||
import SectionTitle from '../components/layout/SectionTitle';
|
||||
@@ -9,7 +11,7 @@ import { calculateProductRating } from '../services/ratingService';
|
||||
import { dailyTargets, dailyTotals } from '../services/dailyNutritionService';
|
||||
import { colors } from '../utils/constants';
|
||||
|
||||
export default function HomeScreen({ preferences, recentProducts, shoppingList, dailyLog, onUndoConsumption, onStartScan, onOpenProduct, onOpenList }) {
|
||||
export default function HomeScreen({ preferences, recentProducts, shoppingList, dailyLog, onDeleteConsumption, onUpdateConsumption, onOpenInsights, onStartScan, onOpenProduct, onOpenList }) {
|
||||
const totals = dailyTotals(dailyLog);
|
||||
const targets = dailyTargets(preferences);
|
||||
const frequentProducts = [...recentProducts]
|
||||
@@ -44,11 +46,12 @@ export default function HomeScreen({ preferences, recentProducts, shoppingList,
|
||||
{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</Text>
|
||||
{totals.count > 0 ? <Pressable accessibilityRole="button" onPress={onUndoConsumption}>
|
||||
<Text style={styles.scanCount}>Letzte Erfassung rückgängig machen</Text>
|
||||
</Pressable> : null}
|
||||
</View>
|
||||
|
||||
<SectionTitle>Tagesprotokoll</SectionTitle>
|
||||
<DailyConsumptionLog entries={dailyLog} onDelete={onDeleteConsumption} onUpdate={onUpdateConsumption} />
|
||||
<SecondaryButton label="7-Tage-Übersicht öffnen" onPress={onOpenInsights} />
|
||||
|
||||
<Pressable accessibilityRole="button" onPress={onOpenList} style={styles.listShortcut}>
|
||||
<View style={styles.listShortcutText}>
|
||||
<Text style={styles.listShortcutTitle}>Dein Einkauf</Text>
|
||||
|
||||
@@ -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({
|
||||
</View>
|
||||
) : null}
|
||||
<PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} />
|
||||
<SecondaryButton label="Portion heute gegessen" onPress={() => { onRecordConsumption(product); setSavedMessage('Portion im Tagesprotokoll erfasst.'); }} />
|
||||
<Text style={styles.dataText}>Portionsgrösse laut Produkt, sonst Packungsmenge oder 100 g.</Text>
|
||||
{consumptionMessage ? (
|
||||
<View style={styles.savedPanel}>
|
||||
<Text style={styles.saved}>{consumptionMessage}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{isChoosingPortion ? (
|
||||
<PortionSelector
|
||||
onCancel={() => setIsChoosingPortion(false)}
|
||||
onConfirm={(grams, date) => {
|
||||
onRecordConsumption(product, grams, date);
|
||||
setConsumptionMessage(date === todayKey()
|
||||
? `${formatAmount(grams)} g heute im Tagesprotokoll erfasst.`
|
||||
: `${formatAmount(grams)} g für ${formatEntryDate(date)} nachgetragen.`);
|
||||
setIsChoosingPortion(false);
|
||||
}}
|
||||
product={product}
|
||||
/>
|
||||
) : (
|
||||
<SecondaryButton label="Portion heute gegessen" onPress={() => {
|
||||
setConsumptionMessage('');
|
||||
setIsChoosingPortion(true);
|
||||
}} />
|
||||
)}
|
||||
|
||||
<SectionTitle>Ähnliche, bessere Alternativen</SectionTitle>
|
||||
{suggestionsLoading ? <Text style={styles.dataText}>Passende Produkte werden gesucht ...</Text> : 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}`;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user