add editable nutrition log and 7-day insights
Android Release Build / build-android (push) Failing after 7m46s

This commit is contained in:
2026-11-19 23:06:12 +01:00
parent 4d257db42a
commit 22c51c2e36
6 changed files with 243 additions and 17 deletions
+43 -9
View File
@@ -5,6 +5,7 @@ import { StatusBar } from 'expo-status-bar';
import BottomTabBar from './src/components/layout/BottomTabBar'; import BottomTabBar from './src/components/layout/BottomTabBar';
import AlternativesScreen from './src/screens/AlternativesScreen'; import AlternativesScreen from './src/screens/AlternativesScreen';
import HomeScreen from './src/screens/HomeScreen'; import HomeScreen from './src/screens/HomeScreen';
import NutritionInsightsScreen from './src/screens/NutritionInsightsScreen';
import OnboardingScreen from './src/screens/OnboardingScreen'; import OnboardingScreen from './src/screens/OnboardingScreen';
import ProductDetailScreen from './src/screens/ProductDetailScreen'; import ProductDetailScreen from './src/screens/ProductDetailScreen';
import ProductEditScreen from './src/screens/ProductEditScreen'; 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 { enrichEnvironmentalProduct } from './src/services/environmentalService';
import { createLocalProduct, saveManualProduct } from './src/services/manualProduct'; import { createLocalProduct, saveManualProduct } from './src/services/manualProduct';
import { storageService } from './src/services/storageService'; 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'; import { colors, defaultPreferences } from './src/utils/constants';
const initialShoppingList = { const initialShoppingList = {
@@ -174,20 +180,28 @@ export default function App() {
onStartScan={() => setActiveTab('scan')} onStartScan={() => setActiveTab('scan')}
preferences={preferences} preferences={preferences}
dailyLog={dailyLog} dailyLog={dailyLog}
onUndoConsumption={() => setDailyLog((current) => current.slice(0, -1))} onDeleteConsumption={deleteConsumption}
onUpdateConsumption={updateConsumption}
onOpenInsights={() => setRoute({ name: 'nutritionInsights' })}
recentProducts={recentProducts} recentProducts={recentProducts}
shoppingList={shoppingList} shoppingList={shoppingList}
/> />
); );
}, [activeTab, dailyLog, isClearingProductData, lastDeletedListItem, preferences, productCache, recentProducts, shoppingList]); }, [activeTab, dailyLog, isClearingProductData, lastDeletedListItem, preferences, productCache, recentProducts, shoppingList]);
function recordConsumption(product) { function recordConsumption(product, grams, date) {
const grams = servingGrams(product); const entry = createConsumptionEntry(product, grams, { date });
const nutrients = nutritionForServing(product, grams); if (!entry) return false;
setDailyLog((current) => [...current.filter((entry) => entry.date === todayKey()), { setDailyLog((current) => appendConsumptionEntry(current, entry));
id: `${Date.now()}-${Math.random()}`, date: todayKey(), productName: product.name, return true;
grams, ...nutrients }
}]);
function updateConsumption(entryId, grams) {
setDailyLog((current) => editConsumptionEntry(current, entryId, grams));
}
function deleteConsumption(entryId) {
setDailyLog((current) => removeConsumptionEntry(current, entryId));
} }
async function clearProductHistoryAndCache() { async function clearProductHistoryAndCache() {
@@ -395,6 +409,11 @@ export default function App() {
return true; return true;
} }
if (route.name === 'nutritionInsights') {
setRoute({ name: 'tabs' });
return true;
}
if (route.name === 'ratingCriteria' && routeProduct) { if (route.name === 'ratingCriteria' && routeProduct) {
setRoute({ name: 'productDetail', product: routeProduct }); setRoute({ name: 'productDetail', product: routeProduct });
return true; return true;
@@ -431,6 +450,20 @@ export default function App() {
return <PrivacyScreen onBack={goBackToTabs} />; return <PrivacyScreen onBack={goBackToTabs} />;
} }
if (route.name === 'nutritionInsights') {
return (
<NutritionInsightsScreen
dailyLog={dailyLog}
onAddEntry={() => {
setActiveTab('scan');
setRoute({ name: 'tabs' });
}}
onBack={goBackToTabs}
preferences={preferences}
/>
);
}
if (route.name === 'productEdit' && routeProduct) { if (route.name === 'productEdit' && routeProduct) {
return <ProductEditScreen key={routeProduct.id} product={routeProduct} isNew={route.isNew} return <ProductEditScreen key={routeProduct.id} product={routeProduct} isNew={route.isNew}
onBack={goBackFromRoute} onSave={saveProductEdits} />; onBack={goBackFromRoute} onSave={saveProductEdits} />;
@@ -439,6 +472,7 @@ export default function App() {
if (route.name === 'productDetail' && routeProduct) { if (route.name === 'productDetail' && routeProduct) {
return ( return (
<ProductDetailScreen <ProductDetailScreen
key={routeProduct.id}
onAddToList={addProductToShoppingList} onAddToList={addProductToShoppingList}
onEditProduct={editProduct} onEditProduct={editProduct}
onBack={goBackToTabs} onBack={goBackToTabs}
+3 -1
View File
@@ -8,7 +8,7 @@ On first launch, users enter age, height, weight, and an exercise goal. The prof
Product ratings now use nutrition (45%), goal fit (20%), ingredients (15%), and allergies (20% when applicable). Only categories with known facts contribute to the numeric score. Missing information limits confidence. Confirmed avoided allergens still block a recommendation. Additives remain an ingredients signal; environmental impact is still displayed in product details but no longer affects the score. The shopping list remains available for planning and checking off products; price entry, totals and budget controls are no longer part of the app. Product ratings now use nutrition (45%), goal fit (20%), ingredients (15%), and allergies (20% when applicable). Only categories with known facts contribute to the numeric score. Missing information limits confidence. Confirmed avoided allergens still block a recommendation. Additives remain an ingredients signal; environmental impact is still displayed in product details but no longer affects the score. The shopping list remains available for planning and checking off products; price entry, totals and budget controls are no longer part of the app.
The product screen shows protein and total sugar per serving. Users can mark a portion as eaten; the local daily log then updates the Home screen and subsequent recommendations. A scan or a shopping-list addition **does not** count as consumption. The app uses the stated serving size, then package size, then 100 g when no amount is available. The last fallback is approximate. Daily totals cover only portions logged in the app. A product with missing nutrition values cannot fill those gaps. The product screen shows protein and total sugar per serving. Users can mark a portion as eaten and choose the stated serving, half or all of the package, 100 g, or a custom amount. The portion can be recorded for today or backdated to an earlier calendar day. The local daily log then updates the Home screen and subsequent recommendations. Entries can be edited or deleted, and earlier dates remain available in the expandable history. A seven-day view supports week-by-week navigation, shows nutrient-specific data coverage, and derives patterns only from logged days with complete data for the relevant nutrient. A scan or a shopping-list addition **does not** count as consumption. When the portion selector opens, it defaults to the stated serving size, then package size, then 100 g when no amount is available. The last fallback is approximate. Daily totals and insights cover only portions logged in the app. A product with missing nutrition values cannot fill those gaps and is never treated as zero.
The daily view also tracks salt and fibre for all goals. The product goal detail shows both without scoring them again because the Nutri-Score already considers them. For endurance goals, carbohydrates per serving contribute to goal fit; no daily carbohydrate prescription is inferred without training duration and intensity. For vegan diets, available vitamin B12 values are shown against the adult EFSA reference of 4 µg/day. Missing vitamin data stays unknown; a missing field never means zero or a diagnosed deficiency. OFF vitamin B12 is converted from grams to micrograms. Manual product editing can add these values from a label. The daily view also tracks salt and fibre for all goals. The product goal detail shows both without scoring them again because the Nutri-Score already considers them. For endurance goals, carbohydrates per serving contribute to goal fit; no daily carbohydrate prescription is inferred without training duration and intensity. For vegan diets, available vitamin B12 values are shown against the adult EFSA reference of 4 µg/day. Missing vitamin data stays unknown; a missing field never means zero or a diagnosed deficiency. OFF vitamin B12 is converted from grams to micrograms. Manual product editing can add these values from a label.
@@ -25,6 +25,8 @@ npm install
npm start npm start
``` ```
Run the automated service tests with `npm test`.
Scan testing barcodes: `3017620422003` and `737628064502`. Online product data comes from [Open Food Facts Switzerland](https://ch.openfoodfacts.org/); the Swiss subdomain supplies the country context for searches. Environmental context uses a bundled [AGRIBALYSE](https://data.ademe.fr/datasets/agribalyse-31-synthese) extract. The app does not upload the personal profile or food log. Barcode and search requests are sent to Open Food Facts when online. Scan testing barcodes: `3017620422003` and `737628064502`. Online product data comes from [Open Food Facts Switzerland](https://ch.openfoodfacts.org/); the Swiss subdomain supplies the country context for searches. Environmental context uses a bundled [AGRIBALYSE](https://data.ademe.fr/datasets/agribalyse-31-synthese) extract. The app does not upload the personal profile or food log. Barcode and search requests are sent to Open Food Facts when online.
Cached products created before carbohydrate mapping was added are refreshed on the next online scan, even if they were fetched within the usual 24-hour cache window. Opening one from recent products also refreshes its detail view. In offline mode the old entry remains available and is marked stale until it can be refreshed. Cached products created before carbohydrate mapping was added are refreshed on the next online scan, even if they were fetched within the usual 24-hour cache window. Opening one from recent products also refreshes its detail view. In offline mode the old entry remains available and is marked stale until it can be refreshed.
+1
View File
@@ -4,6 +4,7 @@
"private": true, "private": true,
"main": "node_modules/expo/AppEntry.js", "main": "node_modules/expo/AppEntry.js",
"scripts": { "scripts": {
"test": "node --test --test-isolation=none tests/*.test.mjs",
"start": "expo start", "start": "expo start",
"android": "expo run:android", "android": "expo run:android",
"ios": "expo run:ios", "ios": "expo run:ios",
+7 -4
View File
@@ -1,6 +1,8 @@
import { Pressable, StyleSheet, Text, View } from 'react-native'; import { Pressable, StyleSheet, Text, View } from 'react-native';
import PrimaryButton from '../components/PrimaryButton'; import PrimaryButton from '../components/PrimaryButton';
import SecondaryButton from '../components/SecondaryButton';
import DailyConsumptionLog from '../components/consumption/DailyConsumptionLog';
import AppHeader from '../components/layout/AppHeader'; import AppHeader from '../components/layout/AppHeader';
import ScreenContainer from '../components/layout/ScreenContainer'; import ScreenContainer from '../components/layout/ScreenContainer';
import SectionTitle from '../components/layout/SectionTitle'; import SectionTitle from '../components/layout/SectionTitle';
@@ -9,7 +11,7 @@ import { calculateProductRating } from '../services/ratingService';
import { dailyTargets, dailyTotals } from '../services/dailyNutritionService'; import { dailyTargets, dailyTotals } from '../services/dailyNutritionService';
import { colors } from '../utils/constants'; 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 totals = dailyTotals(dailyLog);
const targets = dailyTargets(preferences); const targets = dailyTargets(preferences);
const frequentProducts = [...recentProducts] 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} {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} {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> <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> </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}> <Pressable accessibilityRole="button" onPress={onOpenList} style={styles.listShortcut}>
<View style={styles.listShortcutText}> <View style={styles.listShortcutText}>
<Text style={styles.listShortcutTitle}>Dein Einkauf</Text> <Text style={styles.listShortcutTitle}>Dein Einkauf</Text>
+36 -2
View File
@@ -3,6 +3,7 @@ import { Alert, Linking, Platform, Pressable, StyleSheet, Text, View } from 'rea
import PrimaryButton from '../components/PrimaryButton'; import PrimaryButton from '../components/PrimaryButton';
import SecondaryButton from '../components/SecondaryButton'; import SecondaryButton from '../components/SecondaryButton';
import PortionSelector from '../components/consumption/PortionSelector';
import AppHeader from '../components/layout/AppHeader'; import AppHeader from '../components/layout/AppHeader';
import ScreenContainer from '../components/layout/ScreenContainer'; import ScreenContainer from '../components/layout/ScreenContainer';
import SectionTitle from '../components/layout/SectionTitle'; import SectionTitle from '../components/layout/SectionTitle';
@@ -11,6 +12,7 @@ import ProductScoreBadge from '../components/product/ProductScoreBadge';
import RatingCategoryRow from '../components/product/RatingCategoryRow'; import RatingCategoryRow from '../components/product/RatingCategoryRow';
import { calculateProductRating } from '../services/ratingService'; import { calculateProductRating } from '../services/ratingService';
import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService'; import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService';
import { todayKey } from '../services/dailyNutritionService';
import { colors } from '../utils/constants'; import { colors } from '../utils/constants';
export default function ProductDetailScreen({ export default function ProductDetailScreen({
@@ -29,6 +31,8 @@ export default function ProductDetailScreen({
onRecordConsumption onRecordConsumption
}) { }) {
const [savedMessage, setSavedMessage] = useState(''); const [savedMessage, setSavedMessage] = useState('');
const [consumptionMessage, setConsumptionMessage] = useState('');
const [isChoosingPortion, setIsChoosingPortion] = useState(false);
const [suggestions, setSuggestions] = useState([]); const [suggestions, setSuggestions] = useState([]);
const [suggestionsLoading, setSuggestionsLoading] = useState(true); const [suggestionsLoading, setSuggestionsLoading] = useState(true);
const [suggestionsError, setSuggestionsError] = useState(false); const [suggestionsError, setSuggestionsError] = useState(false);
@@ -148,8 +152,29 @@ export default function ProductDetailScreen({
</View> </View>
) : null} ) : null}
<PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} /> <PrimaryButton label="Zur Einkaufsliste hinzufügen" onPress={addToList} />
<SecondaryButton label="Portion heute gegessen" onPress={() => { onRecordConsumption(product); setSavedMessage('Portion im Tagesprotokoll erfasst.'); }} /> {consumptionMessage ? (
<Text style={styles.dataText}>Portionsgrösse laut Produkt, sonst Packungsmenge oder 100 g.</Text> <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> <SectionTitle>Ähnliche, bessere Alternativen</SectionTitle>
{suggestionsLoading ? <Text style={styles.dataText}>Passende Produkte werden gesucht ...</Text> : null} {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); 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) { function formatIndicator(indicator) {
if (typeof indicator?.value !== 'number') return 'Nicht verfügbar'; if (typeof indicator?.value !== 'number') return 'Nicht verfügbar';
return `${new Intl.NumberFormat('de-CH', { maximumSignificantDigits: 3 }).format(indicator.value)} ${indicator.unit}`; return `${new Intl.NumberFormat('de-CH', { maximumSignificantDigits: 3 }).format(indicator.value)} ${indicator.unit}`;
+153 -1
View File
@@ -1,5 +1,7 @@
export const FREE_SUGAR_REFERENCE_GRAMS = 50; export const FREE_SUGAR_REFERENCE_GRAMS = 50;
export const trackedNutrients = ['protein', 'sugar', 'salt', 'fiber', 'carbohydrates', 'vitaminB12'];
export function sugarLimitWarning(grams) { export function sugarLimitWarning(grams) {
const value = Number(grams); const value = Number(grams);
if (!Number.isFinite(value) || value <= FREE_SUGAR_REFERENCE_GRAMS) return null; 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')}`; 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) { export function dailyTargets(preferences) {
const weight = Number(preferences.weightKg); const weight = Number(preferences.weightKg);
const factor = preferences.exerciseGoal === 'muscle' ? 1.6 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()) { export function dailyTotals(entries, date = todayKey()) {
return (entries || []).filter((entry) => entry.date === date).reduce((total, entry) => { 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]; if (Number.isFinite(entry[nutrient])) total[nutrient] += entry[nutrient];
} }
total.count += 1; 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 }); }, { 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) { export function servingGrams(product) {
const amount = Number(product.servingQuantityGrams || product.packageQuantityGrams); const amount = Number(product.servingQuantityGrams || product.packageQuantityGrams);
return Number.isFinite(amount) && amount > 0 ? amount : 100; 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;
}