Repository navigation
Expand file tree
/
Copy pathCode.js
More file actions
2694 lines (2477 loc) · 107 KB
/
Copy pathCode.js
File metadata and controls
2694 lines (2477 loc) · 107 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ============================================================================
* GOAL TRACKER - GOOGLE APPS SCRIPT BACKEND (JSON API)
* ============================================================================
* This file is the *server*. The PWA in /web is a static client that calls
* this endpoint. It never talks to Google or Gemini directly.
*
* Why Apps Script instead of Vercel?
* - 100% free, no build step, no environment variables to manage
* - Keeps the Gemini API key server-side (a Netlify/Vercel client would
* expose it to anyone who opens devtools)
*
* API shape (POST JSON, or GET with ?action= for reads):
* { action: 'state' } -> full dashboard payload
* { action: 'parse', text: '2 eggs and rice' }
* { action: 'log.food', items: [...] }
* { action: 'log.expense', amount, category, merchant, notes }
* { action: 'log.workout', name, exercises, durationMin, muscles[] }
* { action: 'log.study', subject, minutes }
* { action: 'task.add' | 'task.toggle' | 'task.delete' }
* { action: 'class.add' | 'class.delete' }
* { action: 'entry.delete', sheet, rowId }
* { action: 'goals.save', calories, protein, budget, currency }
* { action: 'gemini.test' }
* ============================================================================
*/
// ------------------------------------------------------------------------------
// CONFIG - only non-secret values live here
// ------------------------------------------------------------------------------
const CONFIG = {
DAILY_CALORIE_GOAL: 2000,
DAILY_PROTEIN_GOAL: 140,
DAILY_CARB_GOAL: 250,
DAILY_FAT_GOAL: 70,
DAILY_STUDY_GOAL_MIN: 120,
MONTHLY_SPEND_BUDGET: 30000000,
CURRENCY_SYMBOL: 'toman',
TIMEZONE: 'Asia/Tehran',
// Google retires model ids. gemini-2.5-flash now answers
// 404 "no longer available to new users", which the settings test showed as
// a broken key. An ordered list means a retirement, or a demand spike (503),
// falls through to the next model instead of taking the AI features down.
GEMINI_MODELS: ['gemini-3.8-flash', 'gemini-flash-latest', 'gemini-3.1-flash-lite'],
GEMINI_MODEL: 'gemini-3.8-flash',
DEFAULT_BODY_WEIGHT_KG: 70,
// Gemini inline images are billed as tokens; keep the upload budget small.
MAX_IMAGE_BYTES: 2200000,
// Rough token cost of one image part, used to keep vision prompts in budget.
IMAGE_TOKEN_ESTIMATE: 258
};
// Script Properties (Project Settings -> Script Properties):
// GEMINI_API_KEY = your AI Studio key (required for natural language logging)
// This object holds the property NAME, never the key itself.
// A key pasted here by mistake is still picked up by
// getGeminiKey(), but Script Properties keeps it out of git.
// APP_KEY = optional shared secret. If set, every request must send
// it, otherwise the URL is open to anyone who finds it.
const KEYS = {
GEMINI: "GEMINI_API_KEY",
APP: "APP_KEY",
GOALS: "tracker_goals",
};
const SHEETS = {
NUTRITION: 'Nutrition',
FOODS: 'Foods',
EXPENSES: 'Expenses',
WORKOUTS: 'Workouts',
STUDY: 'Study',
TASKS: 'Tasks',
CLASSES: 'Classes'
};
const SCHEMAS = [
{ name: SHEETS.NUTRITION, headers: ['Timestamp', 'Date', 'Food', 'Qty', 'Unit', 'Calories', 'Protein (g)', 'Carbs (g)', 'Fat (g)', 'Source'] },
{ name: SHEETS.FOODS, headers: ['Key', 'Name', 'Per Amount', 'Per Unit', 'Calories', 'Protein (g)', 'Carbs (g)', 'Fat (g)', 'Uses', 'Updated', 'Grams per Unit'] },
{ name: SHEETS.EXPENSES, headers: ['Timestamp', 'Date', 'Amount', 'Category', 'Merchant', 'Source', 'Notes'] },
{ name: SHEETS.WORKOUTS, headers: ['Timestamp', 'Date', 'Name', 'Exercises', 'Duration (min)', 'Muscles', 'Notes', 'Muscle Load (JSON)'] },
{ name: SHEETS.STUDY, headers: ['Timestamp', 'Date', 'Subject', 'Duration (min)', 'Notes'] },
{ name: SHEETS.TASKS, headers: ['Created', 'Task', 'Due', 'Status', 'Completed', 'Priority'] },
{ name: SHEETS.CLASSES, headers: ['Day', 'Time', 'Subject', 'Room', 'Notes'] }
];
/** Canonical muscle groups. Order matters: it drives the body map legend. */
const MUSCLES = [
'neck', 'traps', 'front-delts', 'side-delts', 'rear-delts',
'chest', 'back', 'biceps', 'triceps', 'forearms',
'abs', 'obliques', 'lower-back',
'glutes', 'quads', 'hamstrings', 'calves'
];
/** Old workout rows used one bucket per area; expand them for the new map. */
const LEGACY_MUSCLES = {
shoulders: ['front-delts', 'side-delts', 'rear-delts']
};
/** Expand legacy muscle names, keeping order and dropping duplicates. */
function expandMuscles(list) {
const out = [];
(list || []).forEach(function (m) {
const s = String(m).trim().toLowerCase();
const mapped = LEGACY_MUSCLES[s] || [s];
mapped.forEach(function (k) { if (out.indexOf(k) === -1) out.push(k); });
});
return out;
}
/** Exercise -> muscle keyword hints used by the local (non-AI) workout parser. */
const MUSCLE_KEYWORDS = {
neck: ['neck curl', 'neck extension', 'neck harness', 'neck'],
traps: ['shrug', 'trap', 'upright row', 'high pull', 'power clean'],
'front-delts': ['front raise', 'incline bench', 'arnold'],
'side-delts': ['shoulder', 'overhead press', 'military press', 'lateral raise', 'arnold', 'delt', 'pike push'],
'rear-delts': ['rear delt', 'face pull', 'reverse fly'],
chest: ['bench', 'chest', 'fly', 'pec', 'pushup', 'push-up', 'dip', 'cable fly', 'decline'],
back: ['lat', 'pull', 'row', 'pulldown', 'pull-up', 'pullup', 'chin', 'deadlift', 'back'],
biceps: ['bicep', 'curl', 'hammer', 'preacher'],
triceps: ['tricep', 'pushdown', 'push-down', 'skullcrusher', 'extension', 'dip'],
forearms: ['forearm', 'wrist', 'grip', 'farmer'],
abs: ['abs', 'crunch', 'sit-up', 'situp', 'plank', 'leg raise', 'toe touch', 'hollow', 'cable crunch'],
obliques: ['oblique', 'side plank', 'woodchop', 'russian', 'twist'],
'lower-back': ['back extension', 'rack pull', 'good morning', 'superman', 'lower back', 'deadlift'],
glutes: ['glute', 'glute bridge', 'hip thrust', 'squat', 'kettlebell swing', 'clamshell', 'lunge', 'split squat'],
quads: ['squat', 'leg press', 'lunge', 'leg extension', 'quad', 'hack squat', 'bulgarian'],
hamstrings: ['hamstring', 'rdl', 'romanian', 'leg curl', 'nordic', 'hip hinge', 'good morning'],
calves: ['calf', 'calves', 'raise', 'seated calf', 'standing calf']
};
/* ============================================================================
EXERCISE KNOWLEDGE BASE
----------------------------------------------------------------------------
Each row is [canonical name, MET, muscle weights]. MET is the standard
compendium value used for energy cost; muscle weights say how much of the
effort each group actually takes, and sum to roughly 1.
Training load for a muscle is:
load = sets x reps x MET x muscleWeight x loadFactor
where loadFactor rises with external weight, so 3x10 at 100kg scores far
harder than 3x10 bodyweight push-ups.
========================================================================== */
const EXERCISE_ROWS = [
// chest
['push-up', 8.0, { chest: 1.0, triceps: 0.85, 'front-delts': 0.45, 'side-delts': 0.15, abs: 0.2 }],
['pushup', 8.0, { chest: 1.0, triceps: 0.85, 'front-delts': 0.45, 'side-delts': 0.15, abs: 0.2 }],
['bench press', 6.0, { chest: 1.0, triceps: 0.7, 'front-delts': 0.4, 'side-delts': 0.1 }],
['incline bench press', 6.0, { chest: 0.9, 'front-delts': 0.55, 'side-delts': 0.15, triceps: 0.6 }],
['decline bench press', 6.5, { chest: 1.0, triceps: 0.6, 'front-delts': 0.3, 'side-delts': 0.1 }],
['dumbbell bench press', 6.0, { chest: 1.0, triceps: 0.7, 'front-delts': 0.4, 'side-delts': 0.1 }],
['chest fly', 4.5, { chest: 1.0 }],
['cable fly', 4.5, { chest: 1.0 }],
['pec deck', 4.0, { chest: 1.0 }],
['push-up variation', 7.0, { chest: 1.0, triceps: 0.8, 'front-delts': 0.45, 'side-delts': 0.15 }],
['clap push-up', 9.0, { chest: 1.0, triceps: 0.85, 'front-delts': 0.5, 'side-delts': 0.2, abs: 0.2 }],
// back
['pull-up', 8.0, { back: 1.0, biceps: 0.8, forearms: 0.5 }],
['pullup', 8.0, { back: 1.0, biceps: 0.8, forearms: 0.5 }],
['chin-up', 8.0, { back: 1.0, biceps: 0.9, forearms: 0.5 }],
['lat pulldown', 5.0, { back: 1.0, biceps: 0.7, forearms: 0.4 }],
['barbell row', 6.0, { back: 1.0, biceps: 0.6, hamstrings: 0.2 }],
['dumbbell row', 5.5, { back: 1.0, biceps: 0.7 }],
['seated cable row', 5.0, { back: 1.0, biceps: 0.6, forearms: 0.3 }],
['t-bar row', 6.0, { back: 1.0, forearms: 0.4 }],
['shrug', 4.0, { traps: 0.8, back: 0.3, forearms: 0.3 }],
['deadlift', 8.0, { back: 0.8, hamstrings: 0.8, glutes: 0.7, quads: 0.4, forearms: 0.5, abs: 0.4 }],
['romanian deadlift', 6.5, { hamstrings: 1.0, glutes: 0.7, back: 0.5 }],
['superset pulldown', 5.0, { back: 1.0, biceps: 0.7 }],
// shoulders (split into the three delt heads + traps)
['overhead press', 6.0, { 'side-delts': 0.6, 'front-delts': 0.5, triceps: 0.6, abs: 0.3 }],
['military press', 6.0, { 'side-delts': 0.6, 'front-delts': 0.5, triceps: 0.6 }],
['lateral raise', 4.0, { 'side-delts': 1.0 }],
['dumbbell lateral raise', 4.0, { 'side-delts': 1.0 }],
['front raise', 4.0, { 'front-delts': 1.0 }],
['arnold press', 5.0, { 'side-delts': 0.5, 'front-delts': 0.6, biceps: 0.4 }],
['face pull', 4.0, { 'rear-delts': 0.8, traps: 0.3, back: 0.4 }],
['upright row', 5.0, { traps: 0.5, 'side-delts': 0.5, biceps: 0.5 }],
['rear delt fly', 4.0, { 'rear-delts': 1.0, back: 0.3 }],
// neck + lower back
['neck curl', 3.0, { neck: 1.0 }],
['neck extension', 3.0, { neck: 1.0, traps: 0.2 }],
['back extension', 4.0, { 'lower-back': 1.0, glutes: 0.4, hamstrings: 0.3 }],
['rack pull', 7.5, { 'lower-back': 0.7, back: 0.6, traps: 0.5, glutes: 0.5, hamstrings: 0.4, forearms: 0.4 }],
// arms
['biceps curl', 4.0, { biceps: 1.0, forearms: 0.3 }],
['hammer curl', 4.0, { biceps: 1.0, forearms: 0.5 }],
['preacher curl', 4.0, { biceps: 1.0 }],
['incline curl', 4.0, { biceps: 1.0 }],
['triceps pushdown', 4.0, { triceps: 1.0 }],
['triceps extension', 4.0, { triceps: 1.0 }],
['skullcrusher', 4.5, { triceps: 1.0 }],
['dip', 7.5, { triceps: 1.0, chest: 0.9, 'front-delts': 0.4, 'side-delts': 0.1 }],
['bench dip', 7.0, { triceps: 1.0, chest: 0.7 }],
['close-grip bench press', 6.0, { triceps: 1.0, chest: 0.7 }],
['wrist curl', 3.0, { forearms: 1.0 }],
['farmer carry', 5.0, { forearms: 1.0, back: 0.2, 'side-delts': 0.2, abs: 0.2 }],
['grip squeeze', 3.0, { forearms: 1.0 }],
// core
['crunch', 3.8, { abs: 1.0 }],
['sit-up', 4.0, { abs: 1.0 }],
['leg raise', 4.0, { abs: 1.0 }],
['plank', 3.5, { abs: 1.0, obliques: 0.4, 'side-delts': 0.3 }],
['cable crunch', 4.0, { abs: 1.0 }],
['hollow hold', 4.0, { abs: 1.0 }],
['russian twist', 4.0, { obliques: 1.0, abs: 0.5 }],
['side plank', 3.5, { obliques: 1.0 }],
['woodchop', 4.5, { obliques: 1.0, abs: 0.4 }],
['hanging leg raise', 5.0, { abs: 1.0 }],
['leg raise crunch', 4.0, { abs: 1.0 }],
['tuck', 6.0, { abs: 1.0 }],
['toe touch', 3.8, { abs: 1.0 }],
// legs and glutes
['squat', 7.0, { quads: 1.0, glutes: 0.9, hamstrings: 0.4, calves: 0.2, abs: 0.4 }],
['back squat', 7.0, { quads: 1.0, glutes: 0.9, hamstrings: 0.4, calves: 0.2, abs: 0.4 }],
['front squat', 7.5, { quads: 1.0, glutes: 0.7, abs: 0.7 }],
['bulgarian split squat', 7.0, { quads: 1.0, glutes: 0.9, hamstrings: 0.3 }],
['leg press', 6.0, { quads: 1.0, glutes: 0.6, hamstrings: 0.4 }],
['leg extension', 4.0, { quads: 1.0 }],
['leg curl', 4.0, { hamstrings: 1.0 }],
['nordic curl', 6.0, { hamstrings: 1.0, glutes: 0.4 }],
['hip thrust', 6.0, { glutes: 1.0, hamstrings: 0.5 }],
['glute bridge', 4.5, { glutes: 1.0, hamstrings: 0.4 }],
['kettlebell swing', 8.5, { glutes: 1.0, hamstrings: 0.7, back: 0.4, abs: 0.3 }],
['lunge', 6.0, { quads: 1.0, glutes: 0.7, hamstrings: 0.4 }],
['walking lunge', 6.0, { quads: 1.0, glutes: 0.7, hamstrings: 0.4 }],
['step-up', 5.5, { quads: 1.0, glutes: 0.8 }],
['calf raise', 3.5, { calves: 1.0 }],
['seated calf raise', 3.5, { calves: 1.0 }],
['standing calf raise', 4.0, { calves: 1.0 }],
['jump squat', 8.5, { quads: 1.0, glutes: 0.9, calves: 0.6 }],
['box jump', 8.0, { quads: 0.7, glutes: 0.7, calves: 0.9, abs: 0.3 }],
['hip thrust machine', 6.0, { glutes: 1.0, hamstrings: 0.5 }],
// cardio / conditioning
['run', 9.0, { quads: 0.5, calves: 0.5, hamstrings: 0.4, glutes: 0.3, abs: 0.3 }],
['running', 9.0, { quads: 0.5, calves: 0.5, hamstrings: 0.4, glutes: 0.3, abs: 0.3 }],
['jogging', 7.0, { quads: 0.4, calves: 0.4, hamstrings: 0.3 }],
['sprint', 12.0, { quads: 0.6, calves: 0.7, hamstrings: 0.5, abs: 0.3 }],
['cycling', 7.5, { quads: 0.8, glutes: 0.5, calves: 0.3 }],
['bike', 7.5, { quads: 0.8, glutes: 0.5, calves: 0.3 }],
['rowing', 7.0, { back: 0.7, quads: 0.4, glutes: 0.3, calves: 0.3 }],
['rowing machine', 7.0, { back: 0.7, quads: 0.4, glutes: 0.3, calves: 0.3 }],
['swimming', 8.0, { back: 0.6, 'side-delts': 0.5, glutes: 0.4, quads: 0.4 }],
['jump rope', 10.0, { calves: 0.8, quads: 0.5, 'side-delts': 0.4, forearms: 0.4 }],
['burpee', 9.5, { quads: 0.7, chest: 0.7, 'side-delts': 0.4, 'front-delts': 0.2, abs: 0.6, calves: 0.4 }],
['mountain climber', 8.0, { abs: 0.9, 'side-delts': 0.5, quads: 0.4 }],
['pull-up bar hang', 4.0, { forearms: 0.8, back: 0.5 }],
['stretching', 2.3, {}],
['mobility', 2.5, {}],
['yoga', 3.0, { abs: 0.3, obliques: 0.3 }],
// compound lifts and machines with no exact match in the tables above, so an
// unfamiliar gym machine still scores against the muscles it actually works
['lat machine', 5.0, { back: 1.0, biceps: 0.6, forearms: 0.3 }],
['hammer strength row', 5.5, { back: 1.0, biceps: 0.6 }],
['pec deck machine', 4.0, { chest: 1.0 }],
['seated dip machine', 6.0, { triceps: 1.0, chest: 0.6 }],
['assault bike', 9.0, { quads: 0.7, 'side-delts': 0.5, back: 0.4, calves: 0.4 }],
['elliptical', 5.5, { quads: 0.4, glutes: 0.3, calves: 0.3, 'side-delts': 0.3 }],
['stair climber', 8.0, { quads: 0.8, glutes: 0.6, calves: 0.7 }],
['skier', 8.5, { quads: 0.7, calves: 0.5, hamstrings: 0.5, glutes: 0.5 }],
['rower', 7.0, { back: 0.7, quads: 0.4, glutes: 0.3, calves: 0.3 }],
['kettlebell', 6.0, { quads: 0.4, glutes: 0.4, back: 0.4, 'side-delts': 0.4, biceps: 0.3 }],
['dumbbell', 5.5, { back: 0.3, 'side-delts': 0.4, biceps: 0.3, triceps: 0.3 }],
['barbell', 5.5, { back: 0.3, quads: 0.3, glutes: 0.3, 'side-delts': 0.3 }]
];
/**
* Equipment words on their own. They are NOT exercises: they only carry a
* low, flat MET for energy estimation, because there is no movement to score.
* Keeping them separate stops "gym day" from matching a fake exercise.
*/
const EQUIPMENT_ROWS = [
['gym', 5.0],
['workout', 5.0],
['training', 5.0],
['weights', 5.0],
['session', 5.0]
];
/** Words that mean "a workout happened" without naming any movement. */
const WORKOUT_WORDS = /\b(workout|workouts|gym|training|train|trained|leg day|arm day|push day|pull day|session)\b/;
/** canonical name -> { met, muscles } */
const EXERCISES = {};
EXERCISE_ROWS.forEach(function (row) {
EXERCISES[row[0]] = { name: row[0], met: row[1], muscles: row[2] };
});
/** equipment word -> met (no muscle contribution) */
const EQUIPMENT = {};
EQUIPMENT_ROWS.forEach(function (row) { EQUIPMENT[row[0]] = row[1]; });
/**
* Alias table, longest first so "bench press" always wins over a shorter alias
* that happens to overlap it.
*
* Only the full exercise name plus safe spelling variants are auto-derived
* (hyphen/space/plural). Short or ambiguous stems such as "chest" or "push" are
* never generated, because they would match unrelated words and swallow the
* real match next to them. Extra everyday names are listed explicitly.
*/
const EXTRA_ALIASES = [
['push ups', 'push-up'], ['pushups', 'push-up'],
['pull ups', 'pull-up'], ['pullups', 'pull-up'],
['chin ups', 'chin-up'], ['chinups', 'chin-up'],
['sit ups', 'sit-up'], ['situps', 'sit-up'],
['dips', 'dip'], ['bench dips', 'bench dip'],
['crunches', 'crunch'], ['squats', 'squat'],
['lunges', 'lunge'], ['walking lunges', 'walking lunge'],
['deadlifts', 'deadlift'], ['rows', 'barbell row'], ['barbell rows', 'barbell row'],
['dumbbell rows', 'dumbbell row'], ['cable rows', 'seated cable row'],
['burpees', 'burpee'], ['mountain climbers', 'mountain climber'],
['leg raises', 'leg raise'], ['pull downs', 'lat pulldown'],
['pull-downs', 'lat pulldown'], ['pulldowns', 'lat pulldown'],
['curl', 'biceps curl'], ['dumbbell curl', 'biceps curl'],
['press', 'overhead press'], ['ohp', 'overhead press'],
['ohip', 'overhead press'], ['ohp press', 'overhead press'],
['bench', 'bench press'], ['flat bench', 'bench press'],
['squat', 'back squat'], ['back squats', 'back squat'],
['rdl', 'romanian deadlift'], ['romanian deadlifts', 'romanian deadlift'],
['leg press', 'leg press'],
['pushdown', 'triceps pushdown'], ['push downs', 'triceps pushdown'],
['triceps dips', 'dip'], ['skull crushers', 'skullcrusher'],
['hammer curls', 'hammer curl'], ['preacher curls', 'preacher curl'],
['lateral raises', 'lateral raise'], ['front raises', 'front raise'],
['face pulls', 'face pull'], ['upright rows', 'upright row'],
['run', 'run'], ['running', 'running'], ['jogging', 'jogging'],
['sprint', 'sprint'], ['sprinting', 'sprint'],
['bike', 'bike'], ['cycling', 'cycling'], ['biking', 'cycling'],
['rowing machine', 'rowing machine'], ['erg', 'rowing machine'],
['rower', 'rowing machine'],
['swim', 'swimming'], ['swimming', 'swimming'],
['jump rope', 'jump rope'], ['rope', 'jump rope'],
['calf raises', 'calf raise'], ['calves raise', 'calf raise'],
['hip thrusts', 'hip thrust'], ['glute bridges', 'glute bridge'],
['leg curls', 'leg curl'], ['nordic curls', 'nordic curl'],
['box jumps', 'box jump'], ['jump squats', 'jump squat'],
['split squat', 'bulgarian split squat'], ['split squats', 'bulgarian split squat'],
['leg extensions', 'leg extension'], ['step ups', 'step-up'],
['kettlebell swing', 'kettlebell swing'], ['kb swing', 'kettlebell swing'],
['plank', 'plank'], ['side planks', 'side plank'],
['russian twists', 'russian twist'], ['woodchops', 'woodchop'],
['hollow hold', 'hollow hold'], ['hanging leg raises', 'hanging leg raise'],
['cable crunch', 'cable crunch'], ['cable crunches', 'cable crunch'],
['leg raise', 'leg raise'], ['stretch', 'stretching'],
['stretching', 'stretching'], ['mobility', 'mobility'], ['yoga', 'yoga'],
['farmer carries', 'farmer carry'], ['farmer walk', 'farmer carry'],
['wrist curls', 'wrist curl'], ['grip squeeze', 'grip squeeze'],
['incline curl', 'incline curl'], ['hammer curl', 'hammer curl'],
['close grip bench', 'close-grip bench press'],
['close grip bench press', 'close-grip bench press'],
['cable fly', 'cable fly'], ['pec deck', 'pec deck'],
['clap push ups', 'clap push-up'], ['clap pushups', 'clap push-up']
];
const EXERCISE_LOOKUP = (function () {
const pairs = [];
Object.keys(EXERCISES).forEach(function (key) {
pairs.push([key, key]);
// Safe spelling variants of the complete name only.
const spaced = key.replace(/-/g, ' ');
const singularSpaced = spaced.replace(/s$/, '');
const spacedPlural = spaced.replace(/([^s])$/, '$1s');
[spaced, singularSpaced, spacedPlural].forEach(function (v) {
if (v && v !== key && v.length > 2) pairs.push([v, key]);
});
});
EXTRA_ALIASES.forEach(function (p) { pairs.push([p[0], p[1]]); });
// Longest alias first so the greedy scan prefers the most specific match.
pairs.sort(function (a, b) { return b[0].length - a[0].length; });
// Collapse duplicate surfaces, keeping the first (longest) target.
const seen = {};
const out = [];
pairs.forEach(function (p) {
if (seen[p[0]]) return;
if (!EXERCISES[p[1]]) return; // never alias to a missing exercise
seen[p[0]] = true;
out.push(p);
});
return out;
})();
/** alias -> canonical exercise key */
const EXERCISE_ALIAS_MAP = (function () {
const map = {};
EXERCISE_LOOKUP.forEach(function (p) { map[p[0]] = p[1]; });
return map;
})();
/** Muscles we can actually colour. Legacy names still count as paintable. */
function isPaintableMuscle(name) {
return MUSCLES.indexOf(name) >= 0 || Object.prototype.hasOwnProperty.call(LEGACY_MUSCLES, name);
}
/**
* External weight makes an exercise harder. Without a barbell the same movement
* is already scaled by MET, so only add weight when it was actually stated.
*/
function loadFactorFor(weightKg, bodyweightKg) {
const bw = bodyweightKg || 70;
if (!weightKg || weightKg <= 0) return 1;
// Ratio of external load to body weight, softened so bodyweight work stays 1.
const ratio = weightKg / bw;
return 1 + Math.min(1.6, ratio * 0.55);
}
// ============================================================================
// FREE-TEXT WORKOUT PARSER
// ----------------------------------------------------------------------------
// Understands the way people actually type a session:
// "10 push ups 10 dips" -> reps only, bodyweight
// "3x12 squats" -> sets x reps
// "60kg bench press x5" -> weight + reps
// "squats 4 sets of 8" -> spelled-out sets
// "plank 60sec" -> isometric hold
// Numbers are attached to the NEAREST exercise name, which is what makes both
// "3x12 squats" and "squats 60kg bench press" come out right.
// ============================================================================
const KG_PER_LB = 0.45359237;
/** Ordered so the most specific modifier wins a position. */
const MODIFIER_PATTERNS = [
{ kind: 'setrep', re: /(\d+(?:\.\d+)?)\s*[x*]\s*(\d+(?:\.\d+)?)/g },
{ kind: 'setsOfReps', re: /(\d+(?:\.\d+)?)\s*sets?\s*of\s*(\d+(?:\.\d+)?)/g },
{ kind: 'seconds', re: /(\d+(?:\.\d+)?)\s*(?:s|sec|secs|second|seconds)\b/g },
{ kind: 'minutes', re: /(\d+(?:\.\d+)?)\s*(?:m|min|mins|minute|minutes)\b/g },
{ kind: 'sets', re: /(\d+(?:\.\d+)?)\s*sets?\b/g },
{ kind: 'reps', re: /(\d+(?:\.\d+)?)\s*reps?\b/g },
{ kind: 'weight', re: /(\d+(?:\.\d+)?)\s*(kg|kgs|kilogram|kilograms|lb|lbs|pound|pounds)\b/g },
// Trailing "x5" / "*12" with no leading set count means reps only.
{ kind: 'repsOnly', re: /(?<![\d.])[x*]\s*(\d+(?:\.\d+)?)/g },
// Distance is a session-length cue for cardio, not a rep count.
{ kind: 'distance', re: /(\d+(?:\.\d+)?)\s*(km|kilometers?|kilometres?|miles?)\b/g },
{ kind: 'bare', re: /(?<![a-z0-9.])(\d{1,3})(?![a-z0-9.])/g }
];
/** Average running pace in minutes per km, used to turn a distance into time. */
const MIN_PER_KM = 6.5;
const KM_PER_MILE = 1.60934;
/**
* People separate movements with these words: "leg press 4x10 100kg then lateral
* raise 3x15". Splitting on them first means each chunk is parsed on its own, so
* a trailing weight can never leak into the next exercise.
*/
const SEGMENT_SPLIT = /\s+(?:then|and|then also|also|plus|after that|followed by)\s+|[;,+&]|\s*\/\s*/g;
/** Parse one movement segment: [exercise] sets/reps/weight -> structured entry. */
function parseWorkoutSegment(text, bodyweightKg) {
const normalised = normaliseWorkoutText(text);
const exSpans = findExerciseSpans(normalised);
if (!exSpans.length) {
return { exercises: [], muscles: [], load: {}, kcal: 0, durationSec: 0, matched: false };
}
const items = exSpans.map(function (span) {
return {
exercise: span.exercise,
alias: span.alias,
sets: 1,
reps: 0,
seconds: 0,
weightKg: 0,
distanceKm: 0,
_span: span
};
});
let durationSec = 0;
// Modifiers are applied in position order so "bare" numbers can fill in the
// remaining slot (reps first, then sets) the way a human reads the line.
findModifierSpans(normalised).sort(function (a, b) { return a.start - b.start; })
.forEach(function (mod) {
const idx = ownerOfModifier(mod, exSpans);
if (idx === null || !items[idx]) return;
const best = items[idx];
const a = mod.text[1];
const b = mod.text[2];
if (mod.kind === 'setrep') {
const s = parseFloat(a), r = parseFloat(b);
// "10x3" is far more likely reps x sets than sets x reps.
if (s > 20 && r <= 20) { best.reps = s; best.sets = r; }
else { best.sets = s; best.reps = r; }
} else if (mod.kind === 'setsOfReps') {
best.sets = parseFloat(a); best.reps = parseFloat(b);
} else if (mod.kind === 'sets') {
best.sets = parseFloat(a);
} else if (mod.kind === 'reps' || mod.kind === 'repsOnly') {
best.reps = parseFloat(a);
} else if (mod.kind === 'bare') {
if (best.reps === 0) best.reps = parseFloat(a);
else if (best.sets === 1) best.sets = parseFloat(a);
} else if (mod.kind === 'weight') {
const v = parseFloat(a);
best.weightKg = /^l(b|bs)/.test(b) ? round1(v * KG_PER_LB) : v;
} else if (mod.kind === 'seconds') {
best.seconds = parseFloat(a);
durationSec += parseFloat(a);
} else if (mod.kind === 'minutes') {
const secs = parseFloat(a) * 60;
best.seconds = secs;
durationSec += secs;
} else if (mod.kind === 'distance') {
// "5km" describes a cardio session's length; convert it to working time.
const km = /^mi/.test(b) ? parseFloat(a) * KM_PER_MILE : parseFloat(a);
const secs = Math.round(km * MIN_PER_KM * 60);
best.seconds = secs;
best.distanceKm = round1(km);
durationSec += secs;
}
});
const exercises = [];
const load = {};
let kcal = 0;
items.forEach(function (it) {
const def = EXERCISES[it.exercise];
if (!def) return;
const isTime = it.seconds > 0;
// A hold counts as ~10s per rep so a 60s plank is comparable to 6 reps.
const effectiveReps = isTime ? Math.max(1, it.seconds / 10) : (it.reps > 0 ? it.reps : 1);
const sets = it.sets > 0 ? it.sets : 1;
const factor = loadFactorFor(it.weightKg, bodyweightKg);
const mus = {};
Object.keys(def.muscles || {}).forEach(function (m) {
if (!isPaintableMuscle(m)) return;
const value = sets * effectiveReps * def.met * def.muscles[m] * factor;
if (value <= 0) return;
mus[m] = round1(value);
load[m] = round1((load[m] || 0) + value);
});
// Energy: kcal/min = MET * 3.5 * bodyweightKg / 200
const bw = bodyweightKg || 70;
const minutes = (sets * effectiveReps) / 60;
kcal += (def.met * 3.5 * bw / 200) * minutes;
exercises.push({
name: def.name,
sets: round1(sets),
reps: isTime ? 0 : round1(it.reps || 0),
seconds: isTime ? round1(it.seconds) : 0,
weightKg: it.weightKg ? round1(it.weightKg) : 0,
distanceKm: it.distanceKm || 0,
met: def.met,
muscles: Object.keys(mus),
load: mus
});
});
return {
exercises: exercises,
muscles: Object.keys(load).sort(),
load: load,
kcal: Math.round(kcal),
durationSec: Math.round(durationSec),
matched: exercises.length > 0
};
}
/**
* Turn one line of free text into structured exercises plus per-muscle load.
* Never throws: unrecognised text simply yields no exercises.
*/
function parseWorkoutLine(text, bodyweightKg) {
const raw = String(text || '');
const segments = raw.split(SEGMENT_SPLIT).map(function (s) { return s.trim(); })
.filter(function (s) { return s.length > 0; });
if (!segments.length) segments.push(raw);
const merged = {
exercises: [],
muscles: [],
load: {},
kcal: 0,
durationSec: 0,
matched: false
};
segments.forEach(function (seg) {
const part = parseWorkoutSegment(seg, bodyweightKg);
if (!part.matched) return;
merged.matched = true;
part.exercises.forEach(function (e) { merged.exercises.push(e); });
Object.keys(part.load).forEach(function (m) {
merged.load[m] = round1((merged.load[m] || 0) + part.load[m]);
});
merged.kcal += part.kcal;
merged.durationSec += part.durationSec;
});
merged.muscles = Object.keys(merged.load).sort();
merged.kcal = Math.round(merged.kcal);
merged.durationSec = Math.round(merged.durationSec);
merged.durationMin = Math.round(merged.durationSec / 60);
return merged;
}
function normaliseWorkoutText(text) {
return String(text || '')
.toLowerCase()
.replace(/[\u00d7\u2715\u22c5\u00b7]/g, ' x ') // × ✕ ⋅ ·
.replace(/[^a-z0-9.\sx]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
/**
* All exercise-name hits with their character span in the normalised text.
* Walks the text left to right, always taking the longest alias available at
* each position so "bench press" is never chopped into "bench" + "press".
*/
function findExerciseSpans(text) {
const spans = [];
let i = 0;
while (i < text.length) {
let hit = null;
for (let a = 0; a < EXERCISE_LOOKUP.length; a++) {
const alias = EXERCISE_LOOKUP[a][0];
if (text.substr(i, alias.length) !== alias) continue;
const before = i === 0 ? ' ' : text.charAt(i - 1);
const after = text.charAt(i + alias.length) || ' ';
// Word-boundary guard so "row" does not match "rowing" or "arrow".
if (!/[^a-z]/.test(before) || before.match(/[a-z]/)) continue;
if (after.match(/[a-z]/)) continue;
hit = { alias: alias, exercise: EXERCISE_LOOKUP[a][1], start: i, end: i + alias.length };
break;
}
if (hit) { spans.push(hit); i = hit.end; }
else i++;
}
return spans;
}
function findModifierSpans(text) {
const spans = [];
const taken = [];
MODIFIER_PATTERNS.forEach(function (p) {
const re = new RegExp(p.re.source, 'g');
let m;
while ((m = re.exec(text)) !== null) {
const span = {
kind: p.kind,
start: m.index,
end: m.index + m[0].length,
raw: m[0],
text: m
};
const clash = taken.some(function (t) { return span.start < t.end && t.start < span.end; });
if (!clash) { spans.push(span); taken.push(span); }
}
});
return spans;
}
function distanceToSpan(mod, span) {
if (mod.end <= span.start) return span.start - mod.end;
if (span.end <= mod.start) return mod.start - span.end;
return 0;
}
/**
* Which exercise does this modifier belong to?
*
* Nearest wins, and on a tie the exercise to the RIGHT wins, because people
* write the count before the movement: "10 push ups 10 dips" has both numbers
* one character from an exercise, and the first 10 belongs to push-ups while
* the second belongs to dips.
*/
function ownerOfModifier(mod, spans) {
let best = null, bestDist = Infinity;
for (let i = 0; i < spans.length; i++) {
const d = distanceToSpan(mod, spans[i]);
if (d < bestDist) { bestDist = d; best = i; }
else if (d === bestDist) best = i; // later span wins the tie
}
return best;
}
/**
* Per-muscle effort, used to colour the body map by how hard it was trained.
*
* intensity = (7-day load) / target weekly load
* 0 -> nothing in the last week
* 0.25 -> a light session
* 0.6 -> solid training
* 1.0 -> a hard week
* 1.6+ -> pushed hard / overreaching
*
* When a muscle has a long enough history we compare against its OWN average
* week, so someone who trains 3x a week is not permanently red while someone
* who trains once is never red either.
*/
const DEFAULT_WEEKLY_TARGET = 450;
const EFFORT_LEVELS = [0.25, 0.6, 1.0, 1.6];
function effortLevelFor(intensity) {
if (!intensity || intensity <= 0) return 0;
let level = 0;
for (let i = 0; i < EFFORT_LEVELS.length; i++) {
if (intensity >= EFFORT_LEVELS[i]) level = i + 1;
}
return level;
}
/**
* @param {Object} byDay { 'YYYY-MM-DD': { chest: 12.3, ... } }
* @returns per-muscle 7-day load, own-average weekly load, intensity, level
*/
function muscleEffort(byDay, today, totalLoad) {
const out = {};
const sevenDaysAgo = dateOffset(-6);
const totalDays = Object.keys(byDay).length || 0;
MUSCLES.forEach(function (m) {
const days = Object.keys(byDay).filter(function (d) {
return d >= sevenDaysAgo && d <= today && byDay[d] && byDay[d][m];
});
let load7 = 0;
days.forEach(function (d) { load7 += byDay[d][m]; });
load7 = round1(load7);
// Own average weekly load, or the default target until there is history.
const allTime = Object.keys(byDay).reduce(function (acc, d) {
return acc + (byDay[d] && byDay[d][m] ? byDay[d][m] : 0);
}, 0);
const weeklyAvg = totalDays >= 14 ? round1(allTime / (totalDays / 7)) : DEFAULT_WEEKLY_TARGET;
const target = weeklyAvg > 1 ? weeklyAvg : DEFAULT_WEEKLY_TARGET;
const intensity = round1(load7 / target);
out[m] = {
load7d: load7,
sessions7d: days.length,
weeklyAvg: weeklyAvg,
intensity: intensity,
level: effortLevelFor(intensity)
};
});
return out;
}
// ============================================================================
// SETUP
// ============================================================================
/** Run once from the Apps Script editor. Creates + formats all tabs. */
function setupSheets() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const added = [];
SCHEMAS.forEach(function (schema) {
let sheet = ss.getSheetByName(schema.name);
if (!sheet) sheet = ss.insertSheet(schema.name);
if (sheet.getLastRow() === 0) {
sheet.appendRow(schema.headers);
sheet.getRange(1, 1, 1, schema.headers.length).setFontWeight('bold');
sheet.getRange(1, 1, 1, schema.headers.length).setBackground('#F3F4F6');
sheet.setFrozenRows(1);
} else {
// Existing sheet from an older version: append any new columns by header
// name so stored rows keep their data and setup stays re-runnable.
const current = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
schema.headers.forEach(function (header, i) {
if (current.indexOf(header) >= 0) return;
const col = sheet.getLastColumn() + 1;
sheet.getRange(1, col).setValue(header);
sheet.getRange(1, col).setFontWeight('bold');
sheet.getRange(1, col).setBackground('#F3F4F6');
added.push(schema.name + ' -> ' + header);
});
}
});
SpreadsheetApp.flush();
return 'Sheets ready: ' + SCHEMAS.map(function (s) { return s.name; }).join(', ') +
(added.length ? ' | added columns: ' + added.join(', ') : '');
}
/** Health check. Open the /exec URL in a browser: you should see JSON. */
function doGet(e) {
const params = (e && e.parameter) || {};
return json(dispatch(params));
}
/**
* Main entry point. Accepts a JSON body. Answers with JSON and permissive CORS
* so the static PWA can call it from any origin.
*/
function doPost(e) {
let body = {};
try {
if (e && e.postData && e.postData.contents) body = JSON.parse(e.postData.contents);
} catch (err) {
return json({ ok: false, error: 'Invalid JSON body' });
}
if (e && e.parameter && e.parameter.action && !body.action) {
body = e.parameter;
}
return json(dispatch(body));
}
/** JSON response with CORS headers so the PWA on Netlify can read it. */
function json(payload) {
return ContentService.createTextOutput(JSON.stringify(payload))
.setMimeType(ContentService.MimeType.JSON);
}
// ============================================================================
// ROUTER
// ============================================================================
function dispatch(req) {
const action = String(req.action || 'state');
try {
if (action !== 'ping' && action !== 'gemini.test' && !isAuthorized(req)) {
return { ok: false, error: 'Unauthorized: bad or missing appKey' };
}
const handler = ROUTES[action];
if (!handler) return { ok: false, error: 'Unknown action: ' + action };
return handler(req);
} catch (err) {
return { ok: false, error: String(err && err.message ? err.message : err) };
}
}
const ROUTES = {
'ping': function () { return { ok: true, pong: true, now: new Date().toISOString() }; },
'state': getState,
'parse': parseAction,
'parse.workout': function (r) { return parseWorkoutAction(r); },
'parse.image': function (r) { return visionAction(r); },
'parse.workout.image': function (r) { return parseWorkoutImage(r); },
'chat': function (r) { return assistantAction(r); },
'gemini.test': function () { return geminiTest(); },
'log.food': function (r) { return logFood(r); },
'food.cache': function (r) { return cacheFood(r); },
'food.search': function (r) { return searchFoods(r); },
'log.expense': function (r) { return logExpense(r); },
'log.workout': function (r) { return logWorkout(r); },
'log.study': function (r) { return logStudy(r); },
'edit.food': function (r) { return editFood(r); },
'task.add': function (r) { return addTask(r); },
'task.toggle': function (r) { return toggleTask(r); },
'task.delete': function (r) { return deleteRow(SHEETS.TASKS, r.rowId); },
'class.add': function (r) { return addClass(r); },
'class.delete': function (r) { return deleteRow(SHEETS.CLASSES, r.rowId); },
'entry.delete': function (r) { return deleteEntry(r); },
'edit.workout': function (r) { return editWorkout(r); },
'goals.save': function (r) { return saveGoals(r); }
};
function isAuthorized(req) {
const expected = PropertiesService.getScriptProperties().getProperty(KEYS.APP);
if (!expected) return true; // key not configured -> open endpoint
return String(req.appKey || '') === expected;
}
// ============================================================================
// STATE - one call powers the whole dashboard
// ============================================================================
function getState() {
const goals = getGoals();
return {
ok: true,
now: new Date().toISOString(),
today: todayStr(),
goals: goals,
nutrition: nutritionState(),
foods: foodCache(),
expenses: expenseState(goals),
workouts: workoutState(),
study: studyState(),
tasks: taskState(),
classes: classState()
};
}
function nutritionState() {
const sheet = getSheet(SHEETS.NUTRITION);
const rows = sheet ? sheet.getDataRange().getValues() : [];
const today = todayStr();
let cal = 0, pro = 0, carb = 0, fat = 0;
const week = {};
for (let i = 7; i >= 0; i--) week[dateOffset(-i)] = { calories: 0, protein: 0, carbs: 0, fat: 0 };
const recent = [];
for (let i = rows.length - 1; i >= 1; i--) {
const d = rowDateStr(rows[i][1]);
const rec = {
rowId: i + 1,
date: d,
food: rows[i][2],
qty: num(rows[i][3]),
unit: rows[i][4],
calories: num(rows[i][5]),
protein: num(rows[i][6]),
carbs: num(rows[i][7]),
fat: num(rows[i][8])
};
if (d === today) {
cal += rec.calories; pro += rec.protein; carb += rec.carbs; fat += rec.fat;
}
if (week[d]) {
week[d].calories += rec.calories;
week[d].protein += rec.protein;
week[d].carbs += rec.carbs;
week[d].fat += rec.fat;
}
if (recent.length < 40) recent.push(rec);
}
return {
today: { calories: cal, protein: pro, carbs: carb, fat: fat },
week: week,
recent: recent
};
}
function foodCache() {
const sheet = getSheet(SHEETS.FOODS);
if (!sheet) return [];
const rows = sheet.getDataRange().getValues();
const out = [];
for (let i = rows.length - 1; i >= 1; i--) {
if (!rows[i][0]) continue;
out.push({
key: rows[i][0],
name: rows[i][1],
refAmount: num(rows[i][2]) || 100,
refUnit: rows[i][3] || 'g',
calories: num(rows[i][4]),
protein: num(rows[i][5]),
carbs: num(rows[i][6]),
fat: num(rows[i][7]),
uses: num(rows[i][8]),
// Edible weight of ONE reference unit, so the client can convert the
// library entry between "1 slice" and grams without another AI call.
gramsPerRef: num(rows[i][10])
});
}
return out;
}
function expenseState(goals) {
const sheet = getSheet(SHEETS.EXPENSES);
const rows = sheet ? sheet.getDataRange().getValues() : [];
const today = todayStr();
const month = today.slice(0, 7);
let todayTotal = 0, monthTotal = 0;
const byCategory = {};
const recent = [];
for (let i = rows.length - 1; i >= 1; i--) {
const d = rowDateStr(rows[i][1]);
const amount = num(rows[i][2]);
const category = rows[i][3] || 'Miscellaneous';
if (d === today) todayTotal += amount;
if (d.slice(0, 7) === month) {
monthTotal += amount;
byCategory[category] = (byCategory[category] || 0) + amount;
}
if (recent.length < 30) {
recent.push({ rowId: i + 1, date: d, amount: amount, category: category, merchant: rows[i][4] || '', source: rows[i][5] || '' });
}
}
return {
todayTotal: todayTotal,
monthTotal: monthTotal,
monthBudget: goals.monthBudget,
byCategory: byCategory,
recent: recent
};
}
function workoutState() {
const sheet = getSheet(SHEETS.WORKOUTS);
const rows = sheet ? sheet.getDataRange().getValues() : [];
const today = todayStr();
const todayList = [];
const recent = [];
const muscleLast = {};
const muscleCount7 = {};
const byDay = {};
MUSCLES.forEach(function (m) { muscleLast[m] = null; muscleCount7[m] = 0; });