-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.js
More file actions
480 lines (416 loc) · 16 KB
/
Copy pathstorage.js
File metadata and controls
480 lines (416 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// Storage management for calorie tracker
const Storage = {
STORAGE_KEY: 'calorieTracker',
FAVOURITES_KEY: 'calorieTrackerFavourites',
// Default profile settings
defaultProfile: {
age: 24,
weightStart: 61.0,
weightTarget: 65.0,
calorieTarget: 2600,
proteinTarget: 120,
duration: 10, // weeks
startDate: null
},
// Initialize storage
init() {
const data = this.getData();
if (!data) {
this.setData({
profile: { ...this.defaultProfile, startDate: this.formatDate(new Date()) },
entries: {}
});
}
// Backwards compatibility: ensure entries key exists
if (data && !data.entries) {
data.entries = {};
this.setData(data);
}
return this.getData();
},
// Get all data
getData() {
try {
const data = localStorage.getItem(this.STORAGE_KEY);
return data ? JSON.parse(data) : null;
} catch (e) {
console.error('Error reading from localStorage:', e);
return null;
}
},
// Set all data
setData(data) {
try {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(data));
return true;
} catch (e) {
console.error('Error writing to localStorage:', e);
return false;
}
},
// Get profile
getProfile() {
const data = this.getData();
return data?.profile || this.defaultProfile;
},
// Update profile
updateProfile(updates) {
const data = this.getData();
data.profile = { ...data.profile, ...updates };
return this.setData(data);
},
// Get day entry
getDayEntry(date) {
const data = this.getData();
const dateStr = this.formatDate(date);
return data?.entries[dateStr] || {
weight: null,
meals: {
breakfast: [],
lunch: [],
dinner: []
},
targetsMet: {
calories: false,
protein: false
}
};
},
// Set day entry
setDayEntry(date, entry) {
const data = this.getData();
const dateStr = this.formatDate(date);
data.entries[dateStr] = entry;
return this.setData(data);
},
// Add meal entry
addMealEntry(date, meal, entry) {
const dayEntry = this.getDayEntry(date);
dayEntry.meals[meal].push(entry);
return this.setDayEntry(date, dayEntry);
},
// Update meal entry
updateMealEntry(date, meal, index, entry) {
const dayEntry = this.getDayEntry(date);
dayEntry.meals[meal][index] = entry;
return this.setDayEntry(date, dayEntry);
},
// Delete meal entry
deleteMealEntry(date, meal, index) {
const dayEntry = this.getDayEntry(date);
dayEntry.meals[meal].splice(index, 1);
return this.setDayEntry(date, dayEntry);
},
// Update weight
updateWeight(date, weight) {
const dayEntry = this.getDayEntry(date);
dayEntry.weight = weight;
return this.setDayEntry(date, dayEntry);
},
// Update targets met
updateTargetsMet(date, targetsMet) {
const dayEntry = this.getDayEntry(date);
dayEntry.targetsMet = targetsMet;
return this.setDayEntry(date, dayEntry);
},
// Get last N days of entries
getLast7Days(endDate) {
return this.getLastNDays(endDate, 7);
},
getLastNDays(endDate, n) {
const entries = [];
const data = this.getData();
for (let i = n - 1; i >= 0; i--) {
const date = new Date(endDate);
date.setDate(date.getDate() - i);
const dateStr = this.formatDate(date);
const entry = data?.entries[dateStr] || {
weight: null,
meals: { breakfast: [], lunch: [], dinner: [] },
targetsMet: { calories: false, protein: false }
};
entries.push({ date: dateStr, ...entry });
}
return entries;
},
// Get ALL entries sorted by date (for stats page)
getAllEntries() {
const data = this.getData();
if (!data?.entries) return [];
return Object.keys(data.entries)
.sort()
.map(dateStr => ({
date: dateStr,
...data.entries[dateStr]
}));
},
// Get entries for a custom date range
getEntriesInRange(startDate, endDate) {
const data = this.getData();
if (!data?.entries) return [];
const startStr = this.formatDate(startDate);
const endStr = this.formatDate(endDate);
return Object.keys(data.entries)
.filter(d => d >= startStr && d <= endStr)
.sort()
.map(dateStr => ({
date: dateStr,
...data.entries[dateStr]
}));
},
// Calculate totals for a day
calculateTotals(dayEntry) {
const allEntries = [
...(dayEntry.meals?.breakfast || []),
...(dayEntry.meals?.lunch || []),
...(dayEntry.meals?.dinner || [])
];
return allEntries.reduce((acc, entry) => {
acc.calories += Number(entry.calories) || 0;
acc.protein += Number(entry.protein) || 0;
acc.carbs += Number(entry.carbs) || 0;
acc.fats += Number(entry.fats) || 0;
return acc;
}, { calories: 0, protein: 0, carbs: 0, fats: 0 });
},
// Format date as YYYY-MM-DD
formatDate(date) {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
},
// Parse date string
parseDate(dateStr) {
return new Date(dateStr + 'T00:00:00');
},
// Calculate expected weight for a given date
calculateExpectedWeight(date) {
const profile = this.getProfile();
const startDate = this.parseDate(profile.startDate);
const targetDate = new Date(startDate);
targetDate.setDate(targetDate.getDate() + (profile.duration * 7));
const totalDays = Math.round((targetDate - startDate) / (1000 * 60 * 60 * 24));
const daysSinceStart = Math.round((date - startDate) / (1000 * 60 * 60 * 24));
if (daysSinceStart < 0) return null;
if (daysSinceStart > totalDays) return profile.weightTarget;
const weightGain = profile.weightTarget - profile.weightStart;
const expectedWeight = profile.weightStart + (weightGain / totalDays) * daysSinceStart;
return Math.round(expectedWeight * 10) / 10;
},
// Calculate streak
calculateStreak(endDate) {
let streak = 0;
const data = this.getData();
let currentDate = new Date(endDate);
while (true) {
const dateStr = this.formatDate(currentDate);
const entry = data?.entries[dateStr];
if (!entry || !entry.targetsMet || (!entry.targetsMet.calories && !entry.targetsMet.protein)) {
break;
}
streak++;
currentDate.setDate(currentDate.getDate() - 1);
if (streak > 30) break;
}
return streak;
},
// Calculate weekly compliance
calculateWeeklyCompliance(endDate) {
const last7Days = this.getLast7Days(endDate);
let compliantDays = 0;
last7Days.forEach(entry => {
if (entry.targetsMet?.calories && entry.targetsMet?.protein) {
compliantDays++;
}
});
return Math.round((compliantDays / 7) * 100);
},
// ─── FAVOURITES ───────────────────────────────────────────────
getFavourites() {
try {
const data = localStorage.getItem(this.FAVOURITES_KEY);
return data ? JSON.parse(data) : [];
} catch (e) {
return [];
}
},
saveFavourites(favs) {
try {
localStorage.setItem(this.FAVOURITES_KEY, JSON.stringify(favs));
return true;
} catch (e) {
return false;
}
},
addFavourite(favourite) {
const favs = this.getFavourites();
const newFav = {
id: Date.now(),
name: favourite.name,
calories: Number(favourite.calories),
protein: Number(favourite.protein),
carbs: Number(favourite.carbs),
fats: Number(favourite.fats),
createdAt: new Date().toISOString()
};
favs.push(newFav);
this.saveFavourites(favs);
return newFav;
},
updateFavourite(id, updates) {
const favs = this.getFavourites();
const idx = favs.findIndex(f => f.id === id);
if (idx === -1) return false;
favs[idx] = { ...favs[idx], ...updates };
return this.saveFavourites(favs);
},
deleteFavourite(id) {
const favs = this.getFavourites().filter(f => f.id !== id);
return this.saveFavourites(favs);
},
// ─── RESET FUNCTIONS ──────────────────────────────────────────
// Clear only food/weight entries (keep profile/goals)
clearEntries() {
try {
const data = this.getData();
data.entries = {};
return this.setData(data);
} catch (e) {
return false;
}
},
// Reset only profile/goals to defaults (keep entries)
resetProfile() {
try {
const data = this.getData();
data.profile = { ...this.defaultProfile, startDate: this.formatDate(new Date()) };
return this.setData(data);
} catch (e) {
return false;
}
},
// Wipe everything
clearAll() {
try {
localStorage.removeItem(this.STORAGE_KEY);
localStorage.removeItem(this.FAVOURITES_KEY);
return true;
} catch (e) {
return false;
}
},
// ─── EXPORT ───────────────────────────────────────────────────
exportData() {
return JSON.stringify(this.getData(), null, 2);
},
exportForAI() {
const profile = this.getProfile();
const allEntries = this.getAllEntries();
const today = new Date();
const todayEntry = this.getDayEntry(today);
const todayTotals = this.calculateTotals(todayEntry);
const streak = this.calculateStreak(today);
const compliance = this.calculateWeeklyCompliance(today);
const expectedWeight = this.calculateExpectedWeight(today);
const favourites = this.getFavourites();
// Aggregate stats across all entries with data
const daysWithData = allEntries.filter(e => {
const t = this.calculateTotals(e);
return t.calories > 0;
});
const avgCalories = daysWithData.length
? Math.round(daysWithData.reduce((s, e) => s + this.calculateTotals(e).calories, 0) / daysWithData.length)
: 0;
const avgProtein = daysWithData.length
? Math.round(daysWithData.reduce((s, e) => s + this.calculateTotals(e).protein, 0) / daysWithData.length)
: 0;
const weightEntries = allEntries.filter(e => e.weight);
const latestWeight = weightEntries.length ? weightEntries[weightEntries.length - 1].weight : null;
const earliestWeight = weightEntries.length ? weightEntries[0].weight : null;
const compliantDays = allEntries.filter(e => e.targetsMet?.calories && e.targetsMet?.protein).length;
const overallCompliance = allEntries.length
? Math.round((compliantDays / allEntries.length) * 100)
: 0;
const startDate = profile.startDate ? this.parseDate(profile.startDate) : today;
const durationSoFar = Math.round((today - startDate) / (1000 * 60 * 60 * 24));
const lines = [
`=== LEAN BULK TRACKER — AI PROGRESS EXPORT ===`,
`Generated: ${today.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}`,
``,
`--- PROFILE & GOALS ---`,
`Age: ${profile.age}`,
`Start Weight: ${profile.weightStart} kg`,
`Target Weight: ${profile.weightTarget} kg`,
`Daily Calorie Target: ${profile.calorieTarget} kcal`,
`Daily Protein Target: ${profile.proteinTarget} g`,
`Goal Duration: ${profile.duration} weeks`,
`Programme Start Date: ${profile.startDate || 'Not set'}`,
`Days Into Programme: ${durationSoFar}`,
``,
`--- TODAY (${this.formatDate(today)}) ---`,
`Calories: ${todayTotals.calories} / ${profile.calorieTarget} kcal`,
`Protein: ${Math.round(todayTotals.protein)} / ${profile.proteinTarget} g`,
`Carbs: ${Math.round(todayTotals.carbs)} g`,
`Fats: ${Math.round(todayTotals.fats)} g`,
`Weight Logged: ${todayEntry.weight ? todayEntry.weight + ' kg' : 'Not logged'}`,
`Expected Weight Today: ${expectedWeight !== null ? expectedWeight + ' kg' : 'N/A'}`,
todayEntry.weight && expectedWeight !== null
? `Weight vs Target: ${(todayEntry.weight - expectedWeight) >= 0 ? '+' : ''}${(todayEntry.weight - expectedWeight).toFixed(1)} kg`
: '',
``,
`--- OVERALL PROGRESS ---`,
`Total Days Tracked: ${allEntries.length}`,
`Days With Food Logged: ${daysWithData.length}`,
`Current Streak: ${streak} day(s)`,
`7-Day Compliance: ${compliance}%`,
`Overall Compliance (all time): ${overallCompliance}%`,
`Average Daily Calories: ${avgCalories} kcal`,
`Average Daily Protein: ${avgProtein} g`,
earliestWeight ? `Starting Logged Weight: ${earliestWeight} kg` : '',
latestWeight ? `Latest Logged Weight: ${latestWeight} kg` : '',
earliestWeight && latestWeight
? `Total Weight Change: ${(latestWeight - earliestWeight) >= 0 ? '+' : ''}${(latestWeight - earliestWeight).toFixed(1)} kg`
: '',
``,
`--- FAVOURITE MEALS (${favourites.length}) ---`,
...favourites.map(f =>
`• ${f.name}: ${f.calories} kcal | P: ${f.protein}g | C: ${f.carbs}g | F: ${f.fats}g`
),
favourites.length === 0 ? '(none saved)' : '',
``,
`--- LAST 30 DAYS DAILY LOG ---`,
...this.getLastNDays(today, 30).map(entry => {
const t = this.calculateTotals(entry);
const hasData = t.calories > 0 || entry.weight;
if (!hasData) return null;
const cal = t.calories > 0 ? `${t.calories} kcal` : 'no food logged';
const prot = t.protein > 0 ? ` | P: ${Math.round(t.protein)}g` : '';
const wt = entry.weight ? ` | Weight: ${entry.weight} kg` : '';
const hit = entry.targetsMet?.calories && entry.targetsMet?.protein ? ' ✓' : '';
return `${entry.date}: ${cal}${prot}${wt}${hit}`;
}).filter(Boolean),
``,
`=== END OF EXPORT ===`
];
return lines.filter(l => l !== null).join('\n');
},
importData(jsonString) {
try {
const data = JSON.parse(jsonString);
return this.setData(data);
} catch (e) {
console.error('Error importing data:', e);
return false;
}
},
clearData() {
try {
localStorage.removeItem(this.STORAGE_KEY);
return true;
} catch (e) {
return false;
}
}
};