-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
1351 lines (1230 loc) · 62.5 KB
/
Copy pathCode.gs
File metadata and controls
1351 lines (1230 loc) · 62.5 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
/**
* ============================================================
* Cashew Reports — Google Apps Script
* ============================================================
* Reads Cashew Outbox CSV from Google Drive, computes financial
* metrics, and serves an HTML dashboard via HtmlService.
*
* Widget Renderer Pattern: each widget's HTML is generated server-side
* by a function in WIDGET_RENDERERS. Dashboard.html is a thin shell
* that injects pre-rendered HTML via a for-loop.
*
* FILE STRUCTURE:
* 1. CONFIG — CSV path, widget layout, category lists
* 2. ENTRY POINTS — doGet(), exportPdfToSnapshots()
* 3. DATA PIPELINE — CSV loading, parsing, filtering, rendering
* 4. METRICS — Per-widget computation functions
* 5. HELPERS — Shared sum/filter/format utilities
* 6. RENDERING HELPERS — HTML formatting (fmt_, deltaChip_, etc.)
* 7. WIDGET RENDERERS — Per-widget HTML generators
* ============================================================
*/
// ============================================================
// 1. CONFIG
// ============================================================
var CONFIG = {
// --- Data Source ---
CSV_FOLDER_NAME: "Cashew",
CSV_FILENAME: "outbox.csv",
// --- Widget Layout (12-column grid) ---
// Array order = render order. Section titles are widgets (id: "section_title").
//
// Shared fields:
// id: matches key in WIDGET_RENDERERS
// visible: show (true) or hide (false)
//
// Content widget fields:
// size: "small" (3/12) | "third" (4/12) | "medium" (6/12) | "large" (12/12)
// col: optional grid-column-start (1-based). Valid positions per size:
// small→1,4,7,10 third→1,5,9 medium→1,7 large→1
// Omit for auto-placement. Ignored on tablet/mobile.
//
// Section title fields (always full-width, no size needed):
// title: displayed label; use {month} for current month
// (pageBreak removed — page breaks handled by section-block CSS)
//
// NOTE: Section titles auto-hide when all their widgets are hidden.
// Walkthrough order (top-down narrative):
// 1. Monthly Summary — 3 headline KPIs + lifestyle tax (how did this month go?)
// 2. Where Did It Go — full category table, then disc split + utility bills
// 3. Spending Patterns — burn trend chart + grocery trend chart
// 4. Deep Dives — biggest increases (QoQ) + top subcats (12-month) side by side
// 5. Income & Savings — investment, rewards, rent trend
// 6. Structural — household baseline, vehicle costs, people payments, data quality
WIDGETS: [
// --- 1. Monthly Summary: the headline numbers ---
{ id: "section_title", visible: true, title: "Monthly Summary \u2014 {month}" },
{ id: "burn_rate", visible: true, size: "small" },
{ id: "money_received", visible: true, size: "small" },
{ id: "savings_rate", visible: true, size: "small" },
{ id: "lifestyle_tax", visible: true, size: "small" },
// --- 2. Where Did It Go: full picture, then classification + bills ---
{ id: "section_title", visible: true, title: "Where Did It Go" },
{ id: "cat_breakdown", visible: true, size: "large" },
{ id: "disc_split", visible: true, size: "medium" },
{ id: "utility_bills", visible: true, size: "medium" },
// --- 3. Spending Patterns: trend charts ---
{ id: "section_title", visible: true, title: "Spending Patterns" },
{ id: "burn_trend", visible: true, size: "medium" },
{ id: "grocery_trend", visible: true, size: "medium" },
// --- 4. Deep Dives: QoQ increases (left) + 12-month top subcats (right) ---
{ id: "section_title", visible: true, title: "Deep Dives" },
{ id: "biggest_increases",visible: true, size: "medium" },
{ id: "top_subcats", visible: true, size: "medium" },
// --- 5. Income & Savings: what came in ---
{ id: "section_title", visible: true, title: "Income & Savings" },
{ id: "investment", visible: true, size: "third" },
{ id: "rewards_refunds", visible: true, size: "third" },
{ id: "rent_trend", visible: true, size: "third" },
// --- 6. Structural: non-negotiable baselines + data quality ---
{ id: "section_title", visible: true, title: "Structural Costs" },
{ id: "household_cost", visible: true, size: "medium" },
{ id: "vehicle_expenses", visible: true, size: "medium" },
{ id: "people_payments", visible: true, size: "medium" },
{ id: "data_quality", visible: true, size: "medium" }
],
// ===================================================================
// CATEGORY TAXONOMY — source of truth from privateUserConfig.js
// Mirrors FinalCategories.md (16 expense) + FinalIncome.md (8 income).
// Each category lists subcategories and which widget(s) cover it.
//
// Widget coverage key:
// burn_rate — included in burn total (all expense cats except BURN_RATE_EXCLUDED)
// cat_breakdown — full expense category table
// disc_split — Disc / Semi-Disc / Non-Disc classification
// lifestyle_tax — Food > Eating Out + Personal Purchases
// utility_bills — checklist for EXPECTED_UTILITY_BILLS subcats
// grocery_trend — Home Essentials > Groceries 6-month trend
// burn_trend — 6-month burn total trend
// top_subcats — 12-month rolling top subcategories
// biggest_increases — QoQ subcategory increases
// household_cost — 12-month Utility Bills + Home Essentials + Household Staff
// vehicle_expenses — Transit > Vehicle Fuel + Services > Vehicle Expenses + Toll + Parking
// people_payments — Household Staff + Family Transfer + Gifts + Donations
// data_quality — Misc Expense > Uncategorized + Untraced
// investment — Investment category breakdown
// money_received — all income except Misc Income + Balance Correction
// rewards_refunds — Rewards + Refunds
// rent_trend — Passive Income > Rent (AJH/NJH)
// savings_rate — (Core Income - Burn) / Core Income
// (none) — category has no dedicated widget beyond cat_breakdown/disc_split
// ===================================================================
EXPENSE_CATEGORIES: {
// cat: [subcategories] | widget coverage
"Utility Bills": ["Electricity (NJH)", "Electricity (AJH)", "Mobile Recharge",
"Cooking Gas", "Home Internet", "Society Maintenance",
"Digital Subscriptions"], // utility_bills, household_cost, disc_split(non-disc)
"Transit": ["Metro", "Cab", "Public Transport",
"Vehicle Fuel", "Toll", "Parking"], // vehicle_expenses(Fuel,Toll,Parking), disc_split(semi-disc). NOTE: Cab, Metro, Public Transport have no dedicated widget
"Investment": ["Mutual Funds", "Stocks (Domestic)", "Stocks (International)",
"Govt & Retirement Schemes", "Gold & Property",
"Deposits & Bonds", "Rent",
"Alternative Investments"], // investment (excluded from burn)
"Food": ["Eating Out", "Dairy", "Fruits & Vegetables",
"Non-Veg", "Other Food"], // lifestyle_tax(Eating Out), disc_split(semi-disc, Eating Out→disc)
"Home Essentials": ["Groceries", "Home Supplies",
"Other Household"], // grocery_trend(Groceries), household_cost, disc_split(non-disc)
"Personal Purchases": ["Clothing & Footwear", "Accessories",
"Entertainment", "Hobbies & Leisure"],// lifestyle_tax, disc_split(disc)
"Home Durables": ["Electronics", "Home Appliances", "Furniture",
"Furnishings & Decor", "Kitchenware",
"Hardware & Electricals",
"Other Durables"], // disc_split(disc). NOTE: no dedicated widget
"Services": ["Personal Care", "Vehicle Expenses", "Repairs",
"Household Staff", "Home Services",
"Family Transfer", "Other Services"], // vehicle_expenses(Vehicle Expenses), household_cost(Household Staff), people_payments(Household Staff, Family Transfer), disc_split(semi-disc, Household Staff→non-disc)
"Financial Admin": ["Insurance", "Tax & Compliance", "Bank Charges",
"Professional Fees", "Govt Fees",
"Loan EMI", "Penalty"], // disc_split(non-disc). NOTE: no dedicated widget
"Healthcare": ["Doctor & Hospital", "Medicines", "Diagnostics",
"Therapy & Wellness",
"Medical Equipment"], // disc_split(non-disc). NOTE: no dedicated widget
"Education": ["School Charges", "Tuition", "Courses",
"Books & Stationery", "School Gear",
"School Bus"], // disc_split(non-disc). NOTE: no dedicated widget
"Occasion": ["Gifts", "Pooja", "Event Hosting",
"Celebration Shopping", "Donations",
"Other Occasion"], // people_payments(Gifts, Donations), disc_split(disc)
"Vacation": ["Travel", "Meals", "Trip Shopping",
"Stay", "Activities"], // disc_split(disc). NOTE: no dedicated widget
"Misc Expense": ["Uncategorized Expense", "Untraced Expense",
"Rare Expense"], // data_quality(Uncategorized+Untraced), disc_split(semi-disc)
"Payroll Deductions": ["Income Tax", "EPF", "NPS",
"Other Deductions"], // excluded from burn, no widget
"Balance Correction": [] // excluded from everything
},
INCOME_CATEGORIES: {
// cat: [subcategories] | widget coverage
"Salary": ["Monthly Salary", "Bonus",
"Reimbursement", "Exit & Adjustments"], // money_received, savings_rate(core income)
"Passive Income": ["Interest", "Rent", "Dividend",
"Agricultural Income"], // money_received, rent_trend(Rent), savings_rate(core income)
"Capital Gains": ["Maturity & Withdrawal", "Market Sale",
"Asset Sale", "Personal Item Sale"], // money_received, savings_rate(core income)
"Rewards": ["CC Rewards", "App Cashback",
"Fuel Reversal"], // rewards_refunds
"Refunds": ["Merchant Refund", "Overpayment & Reversal",
"Deposit Return"], // rewards_refunds
"Ad Hoc Income": ["Side Income", "Govt Credit",
"Insurance & Compensation",
"Gifts & Transfers"], // money_received, savings_rate(core income)
"Misc Income": ["Uncategorized Income", "Untraced Income",
"Rare Income"], // excluded from money_received
"Balance Correction": [] // excluded from everything
},
// --- Widget-specific category slices (derived from taxonomy above) ---
EXPECTED_UTILITY_BILLS: [
"Electricity (NJH)", "Electricity (AJH)", "Mobile Recharge",
"Cooking Gas", "Home Internet", "Society Maintenance", "Digital Subscriptions"
],
BURN_RATE_EXCLUDED: ["Investment", "Balance Correction", "Payroll Deductions"],
DISC_CATEGORIES: ["Personal Purchases", "Occasion", "Vacation", "Home Durables"],
NON_DISC_CATEGORIES: ["Utility Bills", "Financial Admin", "Home Essentials", "Healthcare", "Education"],
SEMI_DISC_CATEGORIES: ["Food", "Transit", "Services", "Misc Expense"],
HOUSEHOLD_RUNNING_CATEGORIES: ["Utility Bills", "Home Essentials"],
CORE_INCOME_CATEGORIES: ["Salary", "Passive Income", "Capital Gains", "Ad Hoc Income"],
INVESTMENT_SUBCATEGORIES: ["Mutual Funds", "Govt & Retirement Schemes", "Stocks (Domestic)",
"Stocks (International)", "Gold & Property", "Deposits & Bonds",
"Rent", "Alternative Investments"],
REWARDS_SUBCATEGORIES: ["CC Rewards", "App Cashback", "Fuel Reversal"],
VEHICLE_EXPENSE_FILTERS: [
{ category: "Transit", subcategory: "Vehicle Fuel" },
{ category: "Services", subcategory: "Vehicle Expenses" },
{ category: "Transit", subcategory: "Toll" },
{ category: "Transit", subcategory: "Parking" }
],
PEOPLE_PAYMENT_FILTERS: [
{ category: "Services", subcategory: "Household Staff" },
{ category: "Services", subcategory: "Family Transfer" },
{ category: "Occasion", subcategory: "Gifts" },
{ category: "Occasion", subcategory: "Donations" }
]
};
// ============================================================
// 2. ENTRY POINTS
// ============================================================
/**
* Web app entry point. Serves the HTML dashboard for the requested month.
* URL param: ?month=YYYY-MM (defaults to latest month in data).
*/
function doGet(e) {
var requestedMonth = (e && e.parameter && e.parameter.month) ? e.parameter.month.trim() : "";
var result = loadAndCompute_(requestedMonth, false);
if (result.error) {
return HtmlService.createHtmlOutput(
'<div style="font-family:system-ui;color:#e1e4ed;background:#0f1117;padding:40px;">' +
'<h2>' + result.error + '</h2></div>'
).setTitle("Cashew Reports \u2014 Error");
}
return HtmlService.createHtmlOutput(result.html)
.setTitle("Cashew Reports \u2014 " + result.month)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
/**
* Server-side function called via google.script.run from the client.
* Generates a PDF snapshot and saves it to /Cashew/Snapshots/ on Drive.
*/
function exportPdfToSnapshots(month) {
var result = loadAndCompute_(month, true);
if (result.error) return { error: result.error };
var blob = Utilities.newBlob(result.html, "text/html", "report.html");
var pdfBlob = blob.getAs("application/pdf");
var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd");
var filename = "Monthly Report - " + month + " " + today + ".pdf";
pdfBlob.setName(filename);
var folders = DriveApp.getFoldersByName(CONFIG.CSV_FOLDER_NAME);
if (!folders.hasNext()) return { error: "Cashew folder not found" };
var cashewFolder = folders.next();
var snapFolders = cashewFolder.getFoldersByName("Snapshots");
var snapFolder = snapFolders.hasNext() ? snapFolders.next() : cashewFolder.createFolder("Snapshots");
var file = snapFolder.createFile(pdfBlob);
return { success: true, filename: filename, url: file.getUrl() };
}
// ============================================================
// 3. DATA PIPELINE — Shared by doGet and exportPdfToSnapshots
// ============================================================
/**
* Full pipeline: read CSV -> parse -> filter -> compute metrics -> render HTML.
* @param {string} requestedMonth YYYY-MM or "" for latest
* @param {boolean} pdfMode true = static PDF rendering (no JS charts, expanded sections)
* @returns {{ html:string, month:string } | { error:string }}
*/
function loadAndCompute_(requestedMonth, pdfMode) {
// --- Read CSV ---
var csvResult = readCSVFromDrive_();
if (!csvResult) return { error: "CSV file not found in /" + CONFIG.CSV_FOLDER_NAME + "/" };
// --- Parse & filter ---
var allRows = parseCSV_(csvResult.content);
var transactions = filterActual_(allRows);
var excludedRows = filterExcluded_(allRows);
transactions.sort(function(a, b) { return a.date - b.date; });
excludedRows.sort(function(a, b) { return a.date - b.date; });
// --- Resolve target month ---
var targetMonth;
if (requestedMonth && /^\d{4}-\d{2}$/.test(requestedMonth)) {
targetMonth = requestedMonth;
} else {
targetMonth = transactions.length > 0
? transactions[transactions.length - 1].month
: Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM");
}
// --- Compute all metrics ---
var metrics = computeMetrics_(transactions, excludedRows, targetMonth);
// --- Render widgets server-side, grouped into sections ---
// Output: renderedSections = [ { titleHtml, widgets: [{html},...] }, ... ]
// Each section = one title + its widgets, rendered as a block for PDF page-break control.
var COL_SPANS = { small: 3, third: 4, medium: 6, large: 12 };
var visibleWidgets = CONFIG.WIDGETS.filter(function(w) { return w.visible; });
var renderedSections = [];
var currentSection = null;
for (var i = 0; i < visibleWidgets.length; i++) {
var w = visibleWidgets[i];
if (w.id === "section_title") {
// Skip empty sections (next is also a title or end)
var next = visibleWidgets[i + 1];
if (!next || next.id === "section_title") continue;
// Start a new section
var titleRenderer = WIDGET_RENDERERS.section_title;
currentSection = { titleHtml: titleRenderer(metrics, w), widgets: [] };
renderedSections.push(currentSection);
continue;
}
var renderer = WIDGET_RENDERERS[w.id];
var html = renderer ? renderer(metrics, w) : "";
// Explicit column placement
if (w.col && html) {
var span = COL_SPANS[w.size] || 6;
var colCss = 'grid-column:' + w.col + ' / span ' + span + ';';
var styleIdx = html.indexOf('style="');
if (styleIdx >= 0 && styleIdx < html.indexOf('>')) {
html = html.substring(0, styleIdx + 7) + colCss + html.substring(styleIdx + 7);
} else {
var fi = html.indexOf('>');
if (fi > 0) html = html.substring(0, fi) + ' style="' + colCss + '"' + html.substring(fi);
}
}
if (currentSection) {
currentSection.widgets.push({ html: html });
}
}
// --- Pass lean meta + rendered widgets to shell template ---
var template = HtmlService.createTemplateFromFile("Dashboard");
template.renderedSections = renderedSections;
template.pdfMode = pdfMode;
template.m = {
generatedAt: metrics.generatedAt,
txnCount: metrics.txnCount,
dateRange: metrics.dateRange,
csvFilename: metrics.csvFilename,
csvSource: csvResult.source,
webAppUrl: ScriptApp.getService().getUrl(),
currentMonth: targetMonth,
prevMonth: metrics.prevMonth,
nextMonth: metrics.nextMonth,
monthLabel: fL_(targetMonth),
prevMonthLabel: sL_(metrics.prevMonth),
nextMonthLabel: sL_(metrics.nextMonth)
};
var html = template.evaluate().getContent();
return { html: html, month: targetMonth };
}
// --- CSV Reader ---
function readCSVFromDrive_() {
var folders = DriveApp.getFoldersByName(CONFIG.CSV_FOLDER_NAME);
if (folders.hasNext()) {
var folder = folders.next();
var files = folder.getFilesByName(CONFIG.CSV_FILENAME);
var latest = null;
while (files.hasNext()) {
var f = files.next();
if (!latest || f.getLastUpdated() > latest.getLastUpdated()) latest = f;
}
if (latest) {
return {
content: latest.getBlob().getDataAsString(),
source: "/" + CONFIG.CSV_FOLDER_NAME + "/" + latest.getName() +
" (updated " + Utilities.formatDate(latest.getLastUpdated(), Session.getScriptTimeZone(), "d MMM yyyy") + ")"
};
}
}
// Fallback: check root Drive for legacy filename
var rootFiles = DriveApp.getFilesByName("cashew_outbox.csv");
if (rootFiles.hasNext()) {
var rf = rootFiles.next();
return { content: rf.getBlob().getDataAsString(), source: rf.getName() };
}
return null;
}
// --- CSV Parser (17-column Cashew Outbox format) ---
function parseCSV_(csvText) {
var rows = Utilities.parseCsv(csvText);
if (rows.length < 2) return [];
var headers = rows[0].map(function(h) { return h.trim().toLowerCase(); });
var idx = {};
headers.forEach(function(h, i) { idx[h] = i; });
var out = [];
for (var i = 1; i < rows.length; i++) {
var r = rows[i];
var dateStr = val_(r, idx, "date");
var dt = new Date(dateStr);
if (isNaN(dt.getTime())) continue;
// Color: "0xffRRGGBB" or "0XFFRRGGBB" -> "#RRGGBB"
var rawColor = val_(r, idx, "color").toLowerCase();
var cssColor = (rawColor && rawColor.indexOf("0xff") === 0) ? "#" + rawColor.substring(4) : "";
// Cashew "include transaction" contract:
// amount filled → included (actual, counts in all metrics)
// amount empty → excluded (not included; amount unpaid is for display only)
// Examples from outbox.csv:
// 06cf0fe0 Salary 201618 amount filled → included (net salary)
// 71fff2af Salary (empty) unpaid 448200 → excluded (gross salary, not included)
// 64462fb4 Utility Bills unpaid -656.1 → excluded (upcoming Digital Subscriptions)
// dbeb2465 Payroll Ded. unpaid -1800 → excluded (EPF, not included)
var amtStr = val_(r, idx, "amount");
var amtUnpaidStr = val_(r, idx, "amount unpaid");
var isIncluded = amtStr !== "";
var amt = Math.abs(parseFloat(amtStr || amtUnpaidStr || "0"));
out.push({
amount: amt,
title: val_(r, idx, "title"),
isIncome: val_(r, idx, "income").toLowerCase() === "true",
date: dt,
month: Utilities.formatDate(dt, Session.getScriptTimeZone(), "yyyy-MM"),
category: val_(r, idx, "category name"),
subcategory: val_(r, idx, "subcategory name"),
color: cssColor,
isIncluded: isIncluded
});
}
return out;
}
// --- Filters ---
function filterActual_(rows) {
return rows.filter(function(t) { return t.isIncluded && t.category !== "Balance Correction"; });
}
function filterExcluded_(rows) {
return rows.filter(function(t) { return !t.isIncluded; });
}
// ============================================================
// 4. METRICS — Per-widget computation
// ============================================================
/**
* Master metric computation. Calls per-widget helpers and assembles
* the full metrics object passed to the Dashboard template.
*/
function computeMetrics_(txns, excludedRows, targetMonth) {
var parts = targetMonth.split("-");
var yr = parseInt(parts[0], 10), mo = parseInt(parts[1], 10) - 1;
var prevMonth = fmtMonth_(yr, mo - 1);
var nextMonth = fmtMonth_(yr, mo + 1);
var expenses = txns.filter(function(t) { return !t.isIncome; });
var incomes = txns.filter(function(t) { return t.isIncome; });
var allTxns = txns.concat(excludedRows);
// Shared color maps (used by multiple widgets)
var subcatColorMap = buildColorMap_(allTxns, "subcategory");
var catColorMap = buildColorMap_(allTxns, "category");
// Shared base values (burn_rate used by many widgets as denominator)
var burnCurr = sumBurn_(expenses, targetMonth);
var burnPrev = sumBurn_(expenses, prevMonth);
// --- Per-widget metrics ---
var ctx = { expenses: expenses, incomes: incomes, excludedRows: excludedRows,
yr: yr, mo: mo, currentMonth: targetMonth, prevMonth: prevMonth,
burnCurr: burnCurr, burnPrev: burnPrev, subcatColorMap: subcatColorMap };
// Pre-compute multi-value results to avoid calling functions twice
var grocResult = computeGroceryTrend_(ctx);
var savResult = computeSavingsRate_(ctx);
var subcatResult = computeSubcatAnalysis_(ctx);
return {
// Navigation & meta
currentMonth: targetMonth, prevMonth: prevMonth, nextMonth: nextMonth,
csvFilename: "/" + CONFIG.CSV_FOLDER_NAME + "/" + CONFIG.CSV_FILENAME,
txnCount: txns.length,
dateRange: txns.length > 0
? Utilities.formatDate(txns[0].date, Session.getScriptTimeZone(), "MMM yyyy") + " \u2014 "
+ Utilities.formatDate(txns[txns.length - 1].date, Session.getScriptTimeZone(), "MMM yyyy")
: "N/A",
generatedAt: Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "d MMM yyyy, h:mm a"),
// === WIDGET: burn_rate ===
burnRate: computeBurnRate_(ctx),
// === WIDGET: lifestyle_tax ===
lifestyleTax: computeLifestyleTax_(ctx),
// === WIDGET: disc_split ===
discSplit: computeDiscSplit_(ctx),
// === WIDGET: utility_bills ===
utilityBills: findUtilityBills_(ctx),
// === WIDGET: data_quality ===
miscExpense: computeDataQuality_(ctx),
// === WIDGET: money_received ===
income: computeIncome_(ctx),
// === WIDGET: investment ===
investment: computeInvestment_(ctx),
// === WIDGET: rewards_refunds ===
recovery: computeRecovery_(ctx),
// === WIDGET: people_payments ===
peoplePay: computePeoplePay_(ctx),
// === WIDGET: vehicle_expenses ===
vehicleExpenses: computeVehicleExpenses_(ctx),
// === WIDGET: burn_trend ===
burnTrend: computeBurnTrend_(ctx),
// === WIDGET: grocery_trend ===
groceryTrend: grocResult.trend,
groceryAvg: grocResult.avg,
// === WIDGET: savings_rate ===
savingsRate: { rate: savResult.rate, ppDelta: savResult.ppDelta },
// === WIDGET: top_subcats + biggest_increases (share computation) ===
allSubcats: subcatResult.subcats,
allIncreases: subcatResult.increases,
// === WIDGET: cat_breakdown ===
catBreakdown: computeCatBreakdown_(ctx, catColorMap),
// === WIDGET: household_cost ===
household: computeHousehold_(ctx),
// === WIDGET: rent_trend ===
rentTrend: computeRentTrend_(ctx)
};
}
// --- Widget: burn_rate ---
// Total monthly expenses excl. Investment, Balance Correction, Payroll Deductions
// Includes top 3 subcategories by amount
function computeBurnRate_(ctx) {
var delta = ctx.burnPrev > 0 ? ((ctx.burnCurr - ctx.burnPrev) / ctx.burnPrev * 100) : 0;
var subcats = {};
ctx.expenses.forEach(function(t) {
if (t.month === ctx.currentMonth && CONFIG.BURN_RATE_EXCLUDED.indexOf(t.category) === -1 && t.subcategory) {
subcats[t.subcategory] = (subcats[t.subcategory] || 0) + t.amount;
}
});
var sorted = [];
for (var k in subcats) sorted.push({ name: k, amount: subcats[k] });
sorted.sort(function(a, b) { return b.amount - a.amount; });
var top3 = {};
for (var i = 0; i < Math.min(3, sorted.length); i++) top3[sorted[i].name] = sorted[i].amount;
return { current: ctx.burnCurr, previous: ctx.burnPrev, delta: delta, top3: top3 };
}
// --- Widget: lifestyle_tax ---
// Eating Out + Personal Purchases as % of burn, with pp delta
function computeLifestyleTax_(ctx) {
var eo = sumFilter_(ctx.expenses, ctx.currentMonth, "Food", "Eating Out");
var pp = sumCat_(ctx.expenses, ctx.currentMonth, "Personal Purchases");
var tot = eo + pp;
var pct = ctx.burnCurr > 0 ? (tot / ctx.burnCurr * 100) : 0;
var eoPrev = sumFilter_(ctx.expenses, ctx.prevMonth, "Food", "Eating Out");
var ppPrev = sumCat_(ctx.expenses, ctx.prevMonth, "Personal Purchases");
var prevPct = ctx.burnPrev > 0 ? ((eoPrev + ppPrev) / ctx.burnPrev * 100) : 0;
return { total: tot, pct: pct, ppDelta: pct - prevPct, items: { "Eating Out": eo, "Personal Purchases": pp } };
}
// --- Widget: data_quality ---
// Uncategorized + Untraced as % of burn
function computeDataQuality_(ctx) {
var miscTxns = ctx.expenses.filter(function(t) {
return t.month === ctx.currentMonth && t.category === "Misc Expense" &&
(t.subcategory === "Uncategorized Expense" || t.subcategory === "Untraced Expense");
});
var total = sum_(miscTxns);
return { count: miscTxns.length, total: total, pct: ctx.burnCurr > 0 ? (total / ctx.burnCurr * 100) : 0 };
}
// --- Widget: money_received ---
// All income excl. Balance Correction and Misc Income, with category breakdown
function computeIncome_(ctx) {
var curr = sum_(ctx.incomes.filter(function(t) { return t.month === ctx.currentMonth && t.category !== "Misc Income"; }));
var prev = sum_(ctx.incomes.filter(function(t) { return t.month === ctx.prevMonth && t.category !== "Misc Income"; }));
var cats = {};
ctx.incomes.forEach(function(t) {
if (t.month === ctx.currentMonth && t.category !== "Misc Income") {
cats[t.category] = (cats[t.category] || 0) + t.amount;
}
});
return { current: curr, previous: prev, delta: prev > 0 ? ((curr - prev) / prev * 100) : 0, cats: cats };
}
// --- Widget: investment ---
// Monthly investment with subcategory breakdown (seeded with known subcats)
function computeInvestment_(ctx) {
var subcats = {};
CONFIG.INVESTMENT_SUBCATEGORIES.forEach(function(s) { subcats[s] = 0; });
var actual = subcatBreakdown_(ctx.expenses, ctx.currentMonth, "Investment");
for (var k in actual) subcats[k] = actual[k];
return {
current: sumCat_(ctx.expenses, ctx.currentMonth, "Investment"),
previous: sumCat_(ctx.expenses, ctx.prevMonth, "Investment"),
subcats: subcats
};
}
// --- Widget: rewards_refunds ---
// Cashback + refunds recovered as % of expenses (seeded with known subcats)
function computeRecovery_(ctx) {
var rewards = sum_(ctx.incomes.filter(function(t) { return t.month === ctx.currentMonth && t.category === "Rewards"; }));
var refunds = sum_(ctx.incomes.filter(function(t) { return t.month === ctx.currentMonth && t.category === "Refunds"; }));
var total = rewards + refunds;
var subcats = {};
CONFIG.REWARDS_SUBCATEGORIES.forEach(function(s) { subcats[s] = 0; });
var actual = subcatBreakdown_(ctx.incomes, ctx.currentMonth, "Rewards");
for (var k in actual) subcats[k] = actual[k];
subcats["Refunds"] = refunds;
return {
total: total, refunds: refunds,
pct: ctx.burnCurr > 0 ? (total / ctx.burnCurr * 100) : 0,
rewardsSubcats: subcats
};
}
// --- Widget: people_payments ---
// Household Staff + Family Transfer + Gifts + Donations
function computePeoplePay_(ctx) {
var items = {}, total = 0;
CONFIG.PEOPLE_PAYMENT_FILTERS.forEach(function(f) {
var amt = sumFilter_(ctx.expenses, ctx.currentMonth, f.category, f.subcategory);
items[f.subcategory] = amt;
total += amt;
});
return { total: total, items: items, pct: ctx.burnCurr > 0 ? (total / ctx.burnCurr * 100) : 0 };
}
// --- Widget: vehicle_expenses ---
// True cost of vehicle ownership: Fuel + Repairs/Service + Toll + Parking
function computeVehicleExpenses_(ctx) {
var fuel = sumFilter_(ctx.expenses, ctx.currentMonth, "Transit", "Vehicle Fuel");
var repairs = sumFilter_(ctx.expenses, ctx.currentMonth, "Services", "Vehicle Expenses");
var toll = sumFilter_(ctx.expenses, ctx.currentMonth, "Transit", "Toll");
var parking = sumFilter_(ctx.expenses, ctx.currentMonth, "Transit", "Parking");
var total = fuel + repairs + toll + parking;
var prevFuel = sumFilter_(ctx.expenses, ctx.prevMonth, "Transit", "Vehicle Fuel");
var prevRepairs = sumFilter_(ctx.expenses, ctx.prevMonth, "Services", "Vehicle Expenses");
var prevToll = sumFilter_(ctx.expenses, ctx.prevMonth, "Transit", "Toll");
var prevParking = sumFilter_(ctx.expenses, ctx.prevMonth, "Transit", "Parking");
var prevTotal = prevFuel + prevRepairs + prevToll + prevParking;
var delta = prevTotal > 0 ? ((total - prevTotal) / prevTotal * 100) : 0;
return {
fuel: fuel, repairs: repairs, toll: toll, parking: parking,
total: total, prevTotal: prevTotal, delta: delta,
fuelPct: total > 0 ? (fuel / total * 100) : 0
};
}
// --- Widget: burn_trend ---
// 6-month burn rate trend for area/line chart
function computeBurnTrend_(ctx) {
var trend = [];
for (var i = 5; i >= 0; i--) {
var m = fmtMonth_(ctx.yr, ctx.mo - i);
trend.push({ month: m, amount: sumBurn_(ctx.expenses, m) });
}
return trend;
}
// --- Widget: grocery_trend ---
// 6-month grocery spend trend with average
function computeGroceryTrend_(ctx) {
var trend = [], total = 0;
for (var i = 5; i >= 0; i--) {
var m = fmtMonth_(ctx.yr, ctx.mo - i);
var amt = sumFilter_(ctx.expenses, m, "Home Essentials", "Groceries");
trend.push({ month: m, amount: amt });
total += amt;
}
return { trend: trend, avg: total / 6 };
}
// --- Widget: savings_rate ---
// (Core Income - Burn) / Core Income, trailing 3 months with pp delta vs prev quarter
function computeSavingsRate_(ctx) {
var inc = 0, exp = 0, incPrev = 0, expPrev = 0;
for (var q = 0; q < 6; q++) {
var qm = fmtMonth_(ctx.yr, ctx.mo - q);
CONFIG.CORE_INCOME_CATEGORIES.forEach(function(cat) {
var amt = sum_(ctx.incomes.filter(function(t) { return t.month === qm && t.category === cat; }));
if (q < 3) inc += amt; else incPrev += amt;
});
if (q < 3) exp += sumBurn_(ctx.expenses, qm);
else expPrev += sumBurn_(ctx.expenses, qm);
}
var rate = inc > 0 ? ((inc - exp) / inc * 100) : 0;
var prevRate = incPrev > 0 ? ((incPrev - expPrev) / incPrev * 100) : 0;
return { rate: rate, ppDelta: rate - prevRate };
}
// --- Widget: top_subcats + biggest_increases ---
// Rolling 12-month subcategory analysis with QoQ trend
function computeSubcatAnalysis_(ctx) {
var rolling = {}, thisQ = {}, prevQ = {};
for (var r = 0; r < 12; r++) {
var rm = fmtMonth_(ctx.yr, ctx.mo - r);
ctx.expenses.forEach(function(t) {
if (t.month === rm && CONFIG.BURN_RATE_EXCLUDED.indexOf(t.category) === -1 && t.subcategory) {
rolling[t.subcategory] = (rolling[t.subcategory] || 0) + t.amount;
if (r < 3) thisQ[t.subcategory] = (thisQ[t.subcategory] || 0) + t.amount;
if (r >= 3 && r < 6) prevQ[t.subcategory] = (prevQ[t.subcategory] || 0) + t.amount;
}
});
}
var rollingTotal = 0;
for (var k in rolling) rollingTotal += rolling[k];
// Subcategories sorted by 12-month total
var subcats = [];
for (var sk in rolling) {
var tq = thisQ[sk] || 0, pq = prevQ[sk] || 0;
subcats.push({
name: sk, amount: rolling[sk],
pct: rollingTotal > 0 ? (rolling[sk] / rollingTotal * 100) : 0,
color: ctx.subcatColorMap[sk] || "",
trendPct: pq > 0 ? ((tq - pq) / pq * 100) : (tq > 0 ? 100 : 0)
});
}
subcats.sort(function(a, b) { return b.amount - a.amount; });
// Increases: subcategories where thisQ > prevQ
var increases = [];
for (var ik in thisQ) {
var diff = thisQ[ik] - (prevQ[ik] || 0);
if (diff > 0) {
increases.push({ name: ik, thisQ: thisQ[ik], prevQ: prevQ[ik] || 0, diff: diff });
}
}
increases.sort(function(a, b) { return b.diff - a.diff; });
return { subcats: subcats, increases: increases };
}
// --- Widget: cat_breakdown ---
// Category-level expense breakdown as sorted array with colors
function computeCatBreakdown_(ctx, catColorMap) {
var map = {};
ctx.expenses.forEach(function(t) {
if (t.month === ctx.currentMonth && CONFIG.BURN_RATE_EXCLUDED.indexOf(t.category) === -1) {
map[t.category] = (map[t.category] || 0) + t.amount;
}
});
var arr = [];
for (var k in map) arr.push({ name: k, amount: map[k], color: catColorMap[k] || "var(--accent)" });
arr.sort(function(a, b) { return b.amount - a.amount; });
return arr;
}
// --- Widget: household_cost ---
// 12-month running cost: Utility Bills + Home Essentials + Household Staff
function computeHousehold_(ctx) {
var total = 0, breakdown = {};
CONFIG.HOUSEHOLD_RUNNING_CATEGORIES.forEach(function(cat) { breakdown[cat] = 0; });
breakdown["Household Staff"] = 0;
for (var h = 0; h < 12; h++) {
var hm = fmtMonth_(ctx.yr, ctx.mo - h);
CONFIG.HOUSEHOLD_RUNNING_CATEGORIES.forEach(function(cat) {
var amt = sumCat_(ctx.expenses, hm, cat);
breakdown[cat] += amt; total += amt;
});
var hs = sumFilter_(ctx.expenses, hm, "Services", "Household Staff");
breakdown["Household Staff"] += hs; total += hs;
}
return { total: total, breakdown: breakdown, monthlyAvg: total / 12 };
}
// --- Widget: rent_trend ---
// 6-month trend of AJH and NJH rent income (matched by title)
function computeRentTrend_(ctx) {
var rentTxns = ctx.incomes.filter(function(t) {
return t.category === "Passive Income" && t.subcategory === "Rent";
});
var trend = [];
for (var i = 5; i >= 0; i--) {
var m = fmtMonth_(ctx.yr, ctx.mo - i);
var ajh = 0, njh = 0;
rentTxns.forEach(function(t) {
if (t.month !== m) return;
if (t.title && t.title.toUpperCase().indexOf("AJH") !== -1) ajh += t.amount;
else if (t.title && t.title.toUpperCase().indexOf("NJH") !== -1) njh += t.amount;
else ajh += t.amount;
});
trend.push({ month: m, ajh: ajh, njh: njh });
}
return trend;
}
// --- Widget: disc_split ---
// Non-Discretionary / Semi-Discretionary / Discretionary classification
// Returns totals + per-category breakdown for drill-down panels
function computeDiscSplit_(ctx) {
var disc = 0, nonDisc = 0, semiDisc = 0;
// Seed with known categories so drill-down always shows labels
var discItems = { "Eating Out": 0 };
CONFIG.DISC_CATEGORIES.forEach(function(c) { discItems[c] = 0; });
var nonDiscItems = { "Household Staff": 0 };
CONFIG.NON_DISC_CATEGORIES.forEach(function(c) { nonDiscItems[c] = 0; });
var semiDiscItems = {};
CONFIG.SEMI_DISC_CATEGORIES.forEach(function(c) { semiDiscItems[c] = 0; });
ctx.expenses.forEach(function(t) {
if (t.month !== ctx.currentMonth || CONFIG.BURN_RATE_EXCLUDED.indexOf(t.category) !== -1) return;
if (CONFIG.DISC_CATEGORIES.indexOf(t.category) !== -1 || (t.category === "Food" && t.subcategory === "Eating Out")) {
disc += t.amount;
var dk = (t.category === "Food") ? "Eating Out" : t.category;
discItems[dk] = (discItems[dk] || 0) + t.amount;
} else if (CONFIG.NON_DISC_CATEGORIES.indexOf(t.category) !== -1 || (t.category === "Services" && t.subcategory === "Household Staff")) {
nonDisc += t.amount;
var nk = (t.subcategory === "Household Staff") ? "Household Staff" : t.category;
nonDiscItems[nk] = (nonDiscItems[nk] || 0) + t.amount;
} else {
semiDisc += t.amount;
semiDiscItems[t.category] = (semiDiscItems[t.category] || 0) + t.amount;
}
});
var total = disc + nonDisc + semiDisc;
return {
discretionary: disc, nonDiscretionary: nonDisc, semiDiscretionary: semiDisc, total: total,
discPct: total > 0 ? (disc / total * 100) : 0,
nonDiscPct: total > 0 ? (nonDisc / total * 100) : 0,
semiDiscPct: total > 0 ? (semiDisc / total * 100) : 0,
discItems: discItems, nonDiscItems: nonDiscItems, semiDiscItems: semiDiscItems
};
}
// --- Widget: utility_bills ---
// Paid/upcoming/missing status + total amount for each expected monthly bill
function findUtilityBills_(ctx) {
var tz = Session.getScriptTimeZone();
var paidMap = {}, upcomingMap = {};
ctx.expenses.forEach(function(t) {
if (t.month === ctx.currentMonth && t.category === "Utility Bills") {
if (!paidMap[t.subcategory]) paidMap[t.subcategory] = { date: "", amount: 0 };
paidMap[t.subcategory].amount += t.amount;
paidMap[t.subcategory].date = Utilities.formatDate(t.date, tz, "d MMM");
}
});
// Upcoming: excluded rows for the current month only
ctx.excludedRows.forEach(function(t) {
if (t.month === ctx.currentMonth && t.category === "Utility Bills" && !paidMap[t.subcategory]) {
upcomingMap[t.subcategory] = { date: Utilities.formatDate(t.date, tz, "d MMM"), amount: t.amount };
}
});
return CONFIG.EXPECTED_UTILITY_BILLS.map(function(sub) {
if (paidMap[sub]) return { name: sub, status: "paid", date: paidMap[sub].date, amount: paidMap[sub].amount };
if (upcomingMap[sub]) return { name: sub, status: "upcoming", date: upcomingMap[sub].date, amount: upcomingMap[sub].amount };
return { name: sub, status: "missing", date: "", amount: 0 };
});
}
// ============================================================
// 5. HELPERS
// ============================================================
/** Format YYYY-MM from year and 0-based month (handles overflow/underflow) */
function fmtMonth_(yr, mo) {
return Utilities.formatDate(new Date(yr, mo, 1), Session.getScriptTimeZone(), "yyyy-MM");
}
/** Sum .amount across an array of transaction objects */
function sum_(arr) {
return arr.reduce(function(s, t) { return s + t.amount; }, 0);
}
/** Sum expenses for a month, excluding BURN_RATE_EXCLUDED categories */
function sumBurn_(expenses, month) {
return sum_(expenses.filter(function(t) {
return t.month === month && CONFIG.BURN_RATE_EXCLUDED.indexOf(t.category) === -1;
}));
}
/** Sum by month + category + subcategory */
function sumFilter_(arr, month, cat, subcat) {
return sum_(arr.filter(function(t) {
return t.month === month && t.category === cat && t.subcategory === subcat;
}));
}
/** Sum by month + category */
function sumCat_(arr, month, cat) {
return sum_(arr.filter(function(t) { return t.month === month && t.category === cat; }));
}
/** Subcategory breakdown { name: amount } for a given month + category */
function subcatBreakdown_(arr, month, cat) {
var out = {};
arr.forEach(function(t) {
if (t.month === month && t.category === cat && t.subcategory)
out[t.subcategory] = (out[t.subcategory] || 0) + t.amount;
});
return out;
}
/** Build a color map: { field_value: "#RRGGBB" } from first occurrence */
function buildColorMap_(txns, field) {
var map = {};
txns.forEach(function(t) {
if (t[field] && t.color && !map[t[field]]) map[t[field]] = t.color;
});
return map;
}
/** Safe column value extraction from parsed CSV row */
function val_(row, idx, col) {
return idx[col] !== undefined ? (row[idx[col]] || "").trim() : "";
}
// ============================================================
// 6. RENDERING HELPERS (used by widget renderers)
// ============================================================
var SN_ = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
function fmt_(n) {
n = Math.round(n || 0);
var neg = n < 0; if (neg) n = -n;
var s = n.toString();
var l = s.substring(s.length - 3);
var r = s.substring(0, s.length - 3);
if (r !== "") l = "," + l;
return (neg ? "-" : "") + "\u20b9" + r.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + l;
}
function fK_(n) { n = Math.round(n || 0); return n >= 1000 ? (n / 1000).toFixed(1) + "k" : n.toString(); }
function pct_(n) { return (n || 0).toFixed(1) + "%"; }
function sL_(ym) { var p = ym.split("-"); return SN_[parseInt(p[1], 10) - 1] + " '" + p[0].substring(2); }
function fL_(ym) { var p = ym.split("-"); return SN_[parseInt(p[1], 10) - 1] + " " + p[0]; }
function esc_(s) { return String(s).replace(/</g, "<").replace(/>/g, ">"); }
function deltaChip_(val, invert) {
if (Math.abs(val) < 0.5) return '<span class="d d-n">' + (val > 0 ? "+" : "") + val.toFixed(1) + "%</span>";
var cls = val > 0 ? (invert ? "d-down" : "d-up") : (invert ? "d-up" : "d-down");
return '<span class="d ' + cls + '">' + (val > 0 ? "+" : "") + val.toFixed(1) + "%</span>";
}
function ppChip_(val, invert) {
if (Math.abs(val) < 0.5) return '<span class="d d-n">' + (val > 0 ? "+" : "") + val.toFixed(1) + "pp</span>";
var cls = val > 0 ? (invert ? "d-down" : "d-up") : (invert ? "d-up" : "d-down");
return '<span class="d ' + cls + '">' + (val > 0 ? "+" : "") + val.toFixed(1) + "pp</span>";
}
function itemRows_(items) {
var html = "";
for (var k in items) {
html += '<div class="im"><span class="im-l">' + esc_(k) + '</span><span class="im-v">' + fmt_(items[k]) + '</span></div>';
}
return html;
}
function trendArrow_(pct) {
if (Math.abs(pct) < 3) return '<span style="color:#8b8fa3;">→ flat</span>';
if (pct > 10) return '<span style="color:#f87171;">↗ +' + Math.round(pct) + '%</span>';
if (pct > 0) return '<span style="color:#fbbf24;">↗ +' + Math.round(pct) + '%</span>';
if (pct < -10) return '<span style="color:#34d399;">↙ ' + Math.round(pct) + '%</span>';
return '<span style="color:#2dd4bf;">↙ ' + Math.round(pct) + '%</span>';
}
// ============================================================
// 7. WIDGET RENDERERS
// ============================================================
var WIDGET_RENDERERS = {
// --- Section Title (always full-width) ---
section_title: function(m, w) {
var title = (w.title || "").replace("{month}", fL_(m.currentMonth));
return `<div class="section-title">${title}</div>`;
},
// --- KPI: Burn Rate ---
burn_rate: function(m, w) {
var d = m.burnRate;
return `<div class="card ws-${w.size}" data-widget="burn_rate">
<div class="label" data-tip="All expenses excl. Investment, Balance Correction, Payroll Deductions">Burn Rate</div>
<div class="value">${fmt_(d.current)}</div>
<div class="sub">vs ${m.prevMonth} ${fmt_(d.previous)} ${deltaChip_(d.delta)}</div>
${itemRows_(d.top3)}
</div>`;
},
// --- KPI: Lifestyle Tax ---
lifestyle_tax: function(m, w) {
var d = m.lifestyleTax;
return `<div class="card ws-${w.size}" data-widget="lifestyle_tax">