-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
3955 lines (3593 loc) · 110 KB
/
Code.gs
File metadata and controls
3955 lines (3593 loc) · 110 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
// ============================================
// G-STACK ASSET COMMAND FREE STARTER KIT
// True North Data Strategies
// Version 1.0
// ============================================
/**
* Creates the Tools menu when the spreadsheet opens
*/
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu("🚗 Tools")
.addItem("🖥️ Open Dashboard", "showDashboard")
.addItem("🌐 Open Dashboard in Browser", "openDashboardInBrowser")
.addItem(
"🔐 Allow This Sheet for Web View",
"addCurrentSpreadsheetToAllowList",
)
.addItem("📝 Data Entry", "openDataEntrySidebar")
.addItem("📚 User Manual", "showUserManual")
.addSeparator()
.addItem("1. Build Complete Template", "buildAssetCommandTemplate")
.addItem("2. Setup Dashboard 2", "setupDashboard2")
.addItem("3. Add Test Data", "addTestData")
.addSeparator()
.addItem("Clear Test Data", "clearTestData")
.addItem("Refresh Dashboards", "refreshDashboards")
.addSeparator()
.addItem("Send Daily Digest", "sendDailyDigest")
.addItem("Check Maintenance Due", "checkMaintenanceDue")
.addSeparator()
.addSubMenu(
ui
.createMenu("🚛 Driver Compliance")
.addItem("Check Driver Credentials", "checkDriverCompliance")
.addItem("Check Fuel Anomalies", "checkFuelAnomaly")
.addSeparator()
.addItem("Add Driver Test Data", "addDriverTestData")
.addItem("Clear Driver Data", "clearDriverTestData"),
)
.addSeparator()
.addSubMenu(
ui
.createMenu("⚙️ Function Runner")
.addItem("Initialize Function Runner", "initializeFunctionRunnerSheet")
.addSeparator()
.addItem("Setup Trigger", "setupFunctionRunnerTrigger")
.addItem("Remove Trigger", "removeFunctionRunnerTrigger"),
)
.addToUi();
}
function doGet(e) {
try {
const spreadsheetId = e && e.parameter ? e.parameter.sid : "";
const ss = getAssetCommandSpreadsheet_(spreadsheetId);
const template = HtmlService.createTemplateFromFile("Dashboard");
template.spreadsheetId = ss.getId();
return template.evaluate().setTitle("G-Stack Asset Command Dashboard");
} catch (error) {
return HtmlService.createHtmlOutput(
"<h3>G-Stack Asset Command Setup Required</h3>" + "<p>" + error.message + "</p>",
);
}
}
/**
* Run this ONCE from the Script Editor after each new deployment.
* Paste your /exec URL inside the quotes below.
*/
function setWebAppUrl() {
PropertiesService.getScriptProperties().setProperty(
"ASSETCOMMAND_WEBAPP_URL",
"https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec",
);
SpreadsheetApp.getUi().alert("Web app URL saved.");
}
function openDashboardInBrowser() {
const url = PropertiesService.getScriptProperties().getProperty(
"ASSETCOMMAND_WEBAPP_URL",
);
if (!url) {
SpreadsheetApp.getUi().alert(
"Run setWebAppUrl() from Script Editor first.",
);
return;
}
const html = HtmlService.createHtmlOutput(
"<!DOCTYPE html><html><body>" +
'<p style="font-family:Arial;font-size:14px;">Click below to open your dashboard:</p>' +
'<input type="button" value="🚀 Open Dashboard" ' +
'style="background:#1a3a5c;color:white;border:none;padding:12px 24px;font-size:15px;border-radius:6px;cursor:pointer;" ' +
"onclick=\"window.open('" +
url +
"','_blank');\" />" +
"</body></html>",
)
.setWidth(400)
.setHeight(120);
SpreadsheetApp.getUi().showModalDialog(html, "G-Stack Asset Command Dashboard");
}
/**
* Adds the current spreadsheet ID to the allowed web-view list.
*/
function addCurrentSpreadsheetToAllowList() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (!ss) throw new Error("No active spreadsheet context.");
const allowed = getAllowedSpreadsheetIds_();
if (!allowed.includes(ss.getId())) {
allowed.push(ss.getId());
saveAllowedSpreadsheetIds_(allowed);
}
SpreadsheetApp.getUi().alert(
"This spreadsheet is now allowed for web dashboard viewing.",
);
}
/**
* Sets allowed spreadsheet IDs from a comma-separated string.
* Example: setAllowedSpreadsheetIds('id1,id2,id3')
*/
function setAllowedSpreadsheetIds(idsCsv) {
const ids = (idsCsv || "")
.toString()
.split(",")
.map((id) => id.trim())
.filter(Boolean);
saveAllowedSpreadsheetIds_(ids);
}
function getAllowedSpreadsheetIds_() {
const props = PropertiesService.getScriptProperties();
const raw = (
props.getProperty("ASSETCOMMAND_ALLOWED_SPREADSHEET_IDS") || ""
).trim();
return raw
? raw
.split(",")
.map((id) => id.trim())
.filter(Boolean)
: [];
}
function saveAllowedSpreadsheetIds_(ids) {
const unique = Array.from(
new Set((ids || []).map((id) => id.trim()).filter(Boolean)),
);
PropertiesService.getScriptProperties().setProperty(
"ASSETCOMMAND_ALLOWED_SPREADSHEET_IDS",
unique.join(","),
);
}
/**
* Resolves the spreadsheet in both bound-sheet and web-app contexts.
*/
function getAssetCommandSpreadsheet_(spreadsheetId) {
const requestedId = (spreadsheetId || "").toString().trim();
const allowedIds = getAllowedSpreadsheetIds_();
if (requestedId) {
if (!allowedIds.includes(requestedId)) {
throw new Error("Invalid spreadsheet context.");
}
return SpreadsheetApp.openById(requestedId);
}
const active = SpreadsheetApp.getActiveSpreadsheet();
if (active) {
const activeId = active.getId();
if (!allowedIds.includes(activeId)) {
allowedIds.push(activeId);
saveAllowedSpreadsheetIds_(allowedIds);
}
return active;
}
throw new Error(
"No spreadsheet context found. Open the sheet and run Allow This Sheet for Web View from the menu.",
);
}
/**
* Refreshes all dashboard formulas
*/
function refreshDashboards() {
SpreadsheetApp.flush();
SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Dashboard")
?.getRange("A1")
.getValue();
SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Dashboard 2")
?.getRange("A1")
.getValue();
SpreadsheetApp.getUi().alert("Dashboards refreshed!");
}
function fixAllowList() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const id = ss.getId();
const allowed = getAllowedSpreadsheetIds_();
if (!allowed.includes(id)) {
allowed.push(id);
saveAllowedSpreadsheetIds_(allowed);
}
PropertiesService.getScriptProperties().setProperty(
"ASSETCOMMAND_SPREADSHEET_ID",
id,
);
SpreadsheetApp.getUi().alert("Allow list updated. ID: " + id);
}
// ============================================
// TEMPLATE BUILDER
// ============================================
/**
* Builds the complete AssetCommand template with all sheets
*/
function buildAssetCommandTemplate() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
// Check if template already exists
if (ss.getSheetByName("Assets Master")) {
const response = ui.alert(
"Template Already Exists",
"This will delete existing sheets and rebuild. Continue?",
ui.ButtonSet.YES_NO,
);
if (response !== ui.Button.YES) return;
// Delete existing sheets
const sheetsToDelete = [
"Dashboard",
"Assets Master",
"Drivers",
"Activity Log",
"Maintenance Tracker",
"Cost Tracking",
"Config",
"Setup Instructions",
"Dashboard 2",
];
sheetsToDelete.forEach((name) => {
const sheet = ss.getSheetByName(name);
if (sheet) ss.deleteSheet(sheet);
});
}
// Create temporary sheet if needed
let tempSheet = ss.getSheetByName("Sheet1") || ss.insertSheet("Temp");
if (tempSheet.getName() !== "Temp") {
tempSheet.setName("Temp");
}
// === CREATE ALL SHEETS ===
const dashboard = ss.insertSheet("Dashboard");
const assets = ss.insertSheet("Assets Master");
const drivers = ss.insertSheet("Drivers");
const activity = ss.insertSheet("Activity Log");
const maint = ss.insertSheet("Maintenance Tracker");
const cost = ss.insertSheet("Cost Tracking");
const config = ss.insertSheet("Config");
const setup = ss.insertSheet("Setup Instructions");
// ============================================
// ASSETS MASTER SHEET
// ============================================
const assetHeaders = [
"Asset ID",
"Asset Name",
"Asset Type",
"Status",
"Current Location",
"Assigned To",
"Last Service Date",
"Next Service Due",
"Service Interval (Days)",
"Acquisition Date",
"Acquisition Cost",
"Notes",
];
assets
.getRange(1, 1, 1, assetHeaders.length)
.setValues([assetHeaders])
.setFontWeight("bold")
.setBackground("#1E3A5F")
.setFontColor("white");
// Data validation dropdowns
const assetTypes = ["Vehicle", "Equipment", "Tool", "Trailer", "Other"];
const statuses = ["Available", "In Use", "Maintenance", "Retired"];
assets
.getRange("C2:C100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(assetTypes, true)
.build(),
);
assets
.getRange("D2:D100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(statuses, true)
.build(),
);
// Auto-resize columns
assets.autoResizeColumns(1, assetHeaders.length);
// Freeze header row
assets.setFrozenRows(1);
// ============================================
// DRIVERS SHEET (DOT Compliance)
// ============================================
const driverHeaders = [
// Identity (cols A-E)
"Driver ID",
"Driver Name",
"Status",
"Phone",
"Email",
// License (cols F-I)
"License Number",
"License State",
"License Expiry",
"License Type",
// CDL (cols J-L)
"CDL Number",
"CDL Expiry",
"CDL Endorsements",
// Medical (cols M-O)
"Medical Card Expiry",
"Medical Examiner",
"Medical Exam Date",
// Background (cols P-R)
"Background Check Date",
"Clearinghouse Status",
"MVR Review Date",
// Drug Testing (cols S-T)
"Drug Test Date",
"Drug Test Result",
// HOS Compliance (cols U-X)
"Last HOS Audit",
"ELD Provider",
"ELD Device ID",
"ELD Compliant",
// Vehicle Inspections - DVIR (cols Y-AA)
"Last Pre-Trip Date",
"Last Post-Trip Date",
"Annual Inspection Due",
// Employment (cols AB-AD)
"Hire Date",
"Termination Date",
"Notes",
];
drivers
.getRange(1, 1, 1, driverHeaders.length)
.setValues([driverHeaders])
.setFontWeight("bold")
.setBackground("#1E3A5F")
.setFontColor("white");
// Data validation dropdowns for Drivers
const driverStatuses = ["Active", "On Leave", "Suspended", "Terminated"];
const licenseTypes = ["Class A", "Class B", "Class C", "Non-CDL"];
const testResults = ["Negative", "Positive", "Pending", "Refused"];
const clearinghouseStatus = ["Clear", "Violation", "Pending Query"];
const yesNo = ["Yes", "No", "Pending"];
const eldProviders = [
"KeepTruckin",
"Samsara",
"Omnitracs",
"PeopleNet",
"Geotab",
"Other",
];
// Status dropdown (col C)
drivers
.getRange("C2:C100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(driverStatuses, true)
.build(),
);
// License Type dropdown (col I)
drivers
.getRange("I2:I100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(licenseTypes, true)
.build(),
);
// Clearinghouse Status dropdown (col R)
drivers
.getRange("R2:R100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(clearinghouseStatus, true)
.build(),
);
// Drug Test Result dropdown (col T)
drivers
.getRange("T2:T100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(testResults, true)
.build(),
);
// ELD Provider dropdown (col V)
drivers
.getRange("V2:V100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(eldProviders, true)
.build(),
);
// ELD Compliant dropdown (col X)
drivers
.getRange("X2:X100")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(yesNo, true)
.build(),
);
// Date columns formatting (H=8, K=11, M=13, O=15, P=16, R=18, S=19, U=21, Y=25, Z=26, AA=27, AB=28, AC=29)
const dateColumns = [8, 11, 13, 15, 16, 18, 19, 21, 25, 26, 27, 28, 29];
dateColumns.forEach((col) => {
drivers.getRange(2, col, 99, 1).setNumberFormat("yyyy-mm-dd");
});
drivers.autoResizeColumns(1, driverHeaders.length);
drivers.setFrozenRows(1);
// ============================================
// ACTIVITY LOG SHEET
// ============================================
const actHeaders = [
"Timestamp",
"Asset ID",
"Asset Name",
"Action Type",
"Employee",
"Location",
"Odometer/Hours",
"Fuel Added (gal)",
"Fuel Cost",
"Condition Notes",
];
activity
.getRange(1, 1, 1, actHeaders.length)
.setValues([actHeaders])
.setFontWeight("bold")
.setBackground("#1E3A5F")
.setFontColor("white");
const actions = [
"Check-out",
"Check-in",
"Refuel",
"Maintenance",
"Incident",
"Location Update",
];
activity
.getRange("D2:D500")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(actions, true)
.build(),
);
activity.autoResizeColumns(1, actHeaders.length);
activity.setFrozenRows(1);
// ============================================
// MAINTENANCE TRACKER SHEET
// ============================================
const maintHeaders = [
"Maintenance ID",
"Asset ID",
"Asset Name",
"Service Type",
"Scheduled Date",
"Completed Date",
"Status",
"Parts Cost",
"Labor Cost",
"Total Cost",
"Vendor",
"Invoice Number",
"Notes",
];
maint
.getRange(1, 1, 1, maintHeaders.length)
.setValues([maintHeaders])
.setFontWeight("bold")
.setBackground("#1E3A5F")
.setFontColor("white");
const services = [
"Oil Change",
"Tire Rotation",
"Inspection",
"Repair",
"Blade Sharpening",
"Filter Replacement",
"Annual Inspection",
"DOT Physical",
"Other",
];
maint
.getRange("D2:D200")
.setDataValidation(
SpreadsheetApp.newDataValidation()
.requireValueInList(services, true)
.build(),
);
maint.autoResizeColumns(1, maintHeaders.length);
maint.setFrozenRows(1);
// ============================================
// COST TRACKING SHEET
// ============================================
const costHeaders = [
"Asset ID",
"Asset Name",
"Total Fuel Cost (30 days)",
"Total Maintenance Cost (YTD)",
"Number of Trips",
"Avg Cost Per Trip",
"Days Since Last Service",
];
cost
.getRange(1, 1, 1, costHeaders.length)
.setValues([costHeaders])
.setFontWeight("bold")
.setBackground("#1E3A5F")
.setFontColor("white");
cost.autoResizeColumns(1, costHeaders.length);
cost.setFrozenRows(1);
// ============================================
// CONFIG SHEET
// ============================================
const configData = [
["Setting", "Value"],
["Business Name", ""],
["Email Address", ""],
["Alert Threshold (days)", 7],
["Fuel Anomaly Threshold (%)", 20],
];
config.getRange(1, 1, configData.length, 2).setValues(configData);
config
.getRange(1, 1, 1, 2)
.setFontWeight("bold")
.setBackground("#1E3A5F")
.setFontColor("white");
config.getRange("A2:A5").setFontWeight("bold");
config.autoResizeColumns(1, 2);
// ============================================
// SETUP INSTRUCTIONS SHEET
// ============================================
const setupContent = [
["🚀 G-STACK ASSET COMMAND FREE STARTER KIT - SETUP GUIDE"],
[""],
["GETTING STARTED:"],
[""],
["Step 1: You just ran 'Build Complete Template' ✓"],
["Step 2: Run 🚗 Tools → Setup Dashboard 2"],
["Step 3: Run 🚗 Tools → Add Test Data (to see it working)"],
["Step 4: Go to Config sheet and enter your business name & email"],
["Step 5: Clear test data and add your own assets!"],
[""],
["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"],
[""],
["MENU REFERENCE (🚗 Tools menu in toolbar):"],
[""],
["• Build Complete Template - Creates all sheets (first time only)"],
["• Setup Dashboard 2 - Creates executive dashboard"],
["• Add Test Data - Adds sample data to test formulas"],
["• Clear Test Data - Removes sample data, keeps structure"],
["• Refresh Dashboards - Recalculates all formulas"],
["• Send Daily Digest - Emails asset summary"],
["• Check Maintenance Due - Emails maintenance alerts"],
[""],
["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"],
[""],
["COLOR GUIDE:"],
["🟢 Green = Good (Available, current)"],
["🟡 Yellow/Orange = Attention (In Use, due soon)"],
["🔴 Red = Action Required (Overdue, retired)"],
[""],
["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"],
[""],
["NEED HELP?"],
["Email: jacob@truenorthstrategyops.com"],
["Web: truenorthstrategyops.com/solutions/asset-command"],
[""],
["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"],
[""],
["© 2025 True North Data Strategies LLC"],
];
setup.getRange(1, 1, setupContent.length, 1).setValues(setupContent);
setup
.getRange("A1")
.setFontSize(16)
.setFontWeight("bold")
.setFontColor("#00B4D8");
setup.getRange("A3").setFontWeight("bold");
setup.getRange("A13").setFontWeight("bold");
setup.getRange("A24").setFontWeight("bold");
setup.getRange("A31").setFontWeight("bold");
setup.setColumnWidth(1, 500);
// ============================================
// DASHBOARD SHEET
// ============================================
dashboard
.getRange("A1")
.setValue("G-STACK ASSET COMMAND - FREE STARTER KIT")
.setFontSize(22)
.setFontWeight("bold")
.setFontColor("#00B4D8");
dashboard
.getRange("A2")
.setFormula('="Last Updated: "&TEXT(NOW(),"mmmm d, yyyy h:mm AM/PM")')
.setFontStyle("italic")
.setFontColor("#666666");
// KPI Section
dashboard
.getRange("A4")
.setValue("📊 QUICK STATS")
.setFontWeight("bold")
.setFontSize(14)
.setBackground("#E2E8F0");
// KPI Labels
dashboard.getRange("A5").setValue("Total Assets");
dashboard.getRange("A6").setValue("Available");
dashboard.getRange("A7").setValue("In Use");
dashboard.getRange("A8").setValue("Maintenance");
dashboard.getRange("A9").setValue("Retired");
dashboard.getRange("A5:A9").setFontWeight("bold");
// KPI Formulas
dashboard.getRange("B5").setFormula("=COUNTA('Assets Master'!A2:A)");
dashboard
.getRange("B6")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Available\")");
dashboard
.getRange("B7")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"In Use\")");
dashboard
.getRange("B8")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Maintenance\")");
dashboard
.getRange("B9")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Retired\")");
// KPI Formatting
dashboard
.getRange("B5:B9")
.setFontWeight("bold")
.setFontSize(16)
.setHorizontalAlignment("center");
dashboard.getRange("B5").setBackground("#3B82F6").setFontColor("white"); // Total - Blue
dashboard.getRange("B6").setBackground("#10B981").setFontColor("white"); // Available - Green
dashboard.getRange("B7").setBackground("#F59E0B").setFontColor("white"); // In Use - Orange
dashboard.getRange("B8").setBackground("#EF4444").setFontColor("white"); // Maintenance - Red
dashboard.getRange("B9").setBackground("#6B7280").setFontColor("white"); // Retired - Gray
// Status Summary for Chart
dashboard
.getRange("D4")
.setValue("📈 STATUS BREAKDOWN")
.setFontWeight("bold")
.setFontSize(14)
.setBackground("#E2E8F0");
dashboard
.getRange("D5:E5")
.setValues([["Status", "Count"]])
.setFontWeight("bold")
.setBackground("#CBD5E1");
dashboard.getRange("D6").setValue("Available");
dashboard.getRange("D7").setValue("In Use");
dashboard.getRange("D8").setValue("Maintenance");
dashboard.getRange("D9").setValue("Retired");
dashboard
.getRange("E6")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Available\")");
dashboard
.getRange("E7")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"In Use\")");
dashboard
.getRange("E8")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Maintenance\")");
dashboard
.getRange("E9")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Retired\")");
// Create Pie Chart
const chart = dashboard
.newChart()
.setChartType(Charts.ChartType.PIE)
.addRange(dashboard.getRange("D5:E9"))
.setPosition(11, 1, 0, 0)
.setOption("title", "Asset Status Distribution")
.setOption("pieSliceText", "percentage")
.setOption("legend", { position: "right" })
.setOption("colors", ["#10B981", "#F59E0B", "#EF4444", "#6B7280"])
.setOption("width", 450)
.setOption("height", 280)
.build();
dashboard.insertChart(chart);
// Maintenance Alerts Section
dashboard
.getRange("A24")
.setValue("⚠️ MAINTENANCE ALERTS")
.setFontWeight("bold")
.setFontSize(14)
.setBackground("#FEE2E2");
dashboard
.getRange("A25")
.setValue("Assets with maintenance due in next 7 days:")
.setFontStyle("italic");
dashboard
.getRange("A26")
.setFormula(
'=IFERROR(QUERY(\'Assets Master\'!A2:H,"SELECT A,B,H WHERE H <= date \'"&TEXT(TODAY()+7,"yyyy-mm-dd")&"\' AND H > date \'"&TEXT(TODAY(),"yyyy-mm-dd")&"\' ORDER BY H LIMIT 5"),"No upcoming maintenance")',
);
dashboard.autoResizeColumns(1, 5);
// Delete temporary sheet
const temp = ss.getSheetByName("Temp");
if (temp) ss.deleteSheet(temp);
ui.alert(
"✅ Template Built Successfully!\n\n" +
"Next Steps:\n" +
"1. Run: 🚗 Tools → Setup Dashboard 2\n" +
"2. Run: 🚗 Tools → Add Test Data\n" +
"3. Check both dashboards!",
);
Logger.log("AssetCommand template built successfully");
}
// ============================================
// DASHBOARD 2 (EXECUTIVE VIEW)
// ============================================
/**
* Creates Dashboard 2 with executive summary view
*/
function setupDashboard2() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
// Check if Assets Master exists
if (!ss.getSheetByName("Assets Master")) {
ui.alert('Please run "Build Complete Template" first.');
return;
}
// Delete existing Dashboard 2 if present
const existing = ss.getSheetByName("Dashboard 2");
if (existing) ss.deleteSheet(existing);
const dash = ss.insertSheet("Dashboard 2");
// === HEADER ===
dash
.getRange("A1")
.setValue("G-Stack Asset Command Free Starter Kit")
.setFontSize(20)
.setFontWeight("bold")
.setFontColor("white")
.setBackground("#0F172A");
dash.getRange("B1:H1").setBackground("#0F172A");
dash
.getRange("A2")
.setFormula(
'=IF(Config!B2<>"",Config!B2&" | Executive Summary","Executive Summary")',
)
.setFontSize(12)
.setBackground("#E2E8F0");
dash
.getRange("A3")
.setFormula('=TEXT(TODAY(),"dddd, mmmm d, yyyy")')
.setFontStyle("italic")
.setBackground("#E2E8F0");
// === KPI ROW ===
dash
.getRange("A5")
.setValue("📊 KEY METRICS")
.setFontWeight("bold")
.setFontSize(12);
// KPI Boxes
const kpiLabels = [
"Total Assets",
"Available",
"In Use",
"Maint. Due",
"Overdue",
];
dash
.getRange("A6:E6")
.setValues([kpiLabels])
.setFontWeight("bold")
.setHorizontalAlignment("center")
.setBackground("#CBD5E1");
dash.getRange("A7").setFormula("=COUNTA('Assets Master'!A2:A)");
dash
.getRange("B7")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Available\")");
dash.getRange("C7").setFormula("=COUNTIF('Assets Master'!D2:D,\"In Use\")");
dash
.getRange("D7")
.setFormula(
"=COUNTIFS('Assets Master'!H2:H,\"<=\"&TODAY()+7,'Assets Master'!H2:H,\">\"&TODAY())",
);
dash
.getRange("E7")
.setFormula("=COUNTIF('Maintenance Tracker'!G2:G,\"Overdue\")");
dash
.getRange("A7:E7")
.setFontWeight("bold")
.setFontSize(18)
.setHorizontalAlignment("center");
dash.getRange("A7").setBackground("#3B82F6").setFontColor("white");
dash.getRange("B7").setBackground("#10B981").setFontColor("white");
dash.getRange("C7").setBackground("#F59E0B").setFontColor("white");
dash.getRange("D7").setBackground("#F97316").setFontColor("white");
dash.getRange("E7").setBackground("#EF4444").setFontColor("white");
// === RECENT ACTIVITY ===
dash
.getRange("A9")
.setValue("🕒 RECENT ACTIVITY")
.setFontWeight("bold")
.setFontSize(12);
dash
.getRange("A10:D10")
.setValues([["Date", "Asset", "Name", "Action"]])
.setFontWeight("bold")
.setBackground("#CBD5E1");
dash
.getRange("A11")
.setFormula(
'=IFERROR(QUERY(\'Activity Log\'!A2:D,"SELECT A,B,C,D WHERE A IS NOT NULL ORDER BY A DESC LIMIT 8"),"No activity logged yet")',
);
// === STATUS SUMMARY TABLE FOR CHART ===
dash
.getRange("F9")
.setValue("📈 STATUS BREAKDOWN")
.setFontWeight("bold")
.setFontSize(12);
dash
.getRange("F10:G10")
.setValues([["Status", "Count"]])
.setFontWeight("bold")
.setBackground("#CBD5E1");
dash.getRange("F11").setValue("Available");
dash.getRange("F12").setValue("In Use");
dash.getRange("F13").setValue("Maintenance");
dash.getRange("F14").setValue("Retired");
dash
.getRange("G11")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Available\")");
dash.getRange("G12").setFormula("=COUNTIF('Assets Master'!D2:D,\"In Use\")");
dash
.getRange("G13")
.setFormula("=COUNTIF('Assets Master'!D2:D,\"Maintenance\")");
dash.getRange("G14").setFormula("=COUNTIF('Assets Master'!D2:D,\"Retired\")");
// === PIE CHART ===
const chart = dash
.newChart()
.setChartType(Charts.ChartType.PIE)
.addRange(dash.getRange("F10:G14"))
.setPosition(16, 6, 0, 0)
.setOption("title", "Asset Status")
.setOption("pieSliceText", "value")
.setOption("legend", { position: "labeled" })
.setOption("colors", ["#10B981", "#F59E0B", "#EF4444", "#6B7280"])
.setOption("width", 350)
.setOption("height", 220)
.build();
dash.insertChart(chart);
// === MAINTENANCE STATUS TABLE FOR CHART ===
dash
.getRange("F24")
.setValue("🔧 MAINTENANCE STATUS")
.setFontWeight("bold")
.setFontSize(12);
dash
.getRange("F25:G25")
.setValues([["Status", "Count"]])
.setFontWeight("bold")
.setBackground("#CBD5E1");
dash.getRange("F26").setValue("Scheduled");
dash.getRange("F27").setValue("Completed");
dash.getRange("F28").setValue("Overdue");
dash
.getRange("G26")
.setFormula("=COUNTIF('Maintenance Tracker'!G2:G,\"Scheduled\")");
dash
.getRange("G27")
.setFormula("=COUNTIF('Maintenance Tracker'!G2:G,\"Completed\")");
dash
.getRange("G28")
.setFormula("=COUNTIF('Maintenance Tracker'!G2:G,\"Overdue\")");
// === COLUMN CHART FOR MAINTENANCE ===
const chart2 = dash
.newChart()
.setChartType(Charts.ChartType.COLUMN)
.addRange(dash.getRange("F25:G28"))
.setPosition(30, 6, 0, 0)
.setOption("title", "Maintenance Overview")
.setOption("legend", { position: "none" })
.setOption("colors", ["#3B82F6"])
.setOption("width", 350)
.setOption("height", 200)
.build();
dash.insertChart(chart2);
// Auto-resize
dash.autoResizeColumns(1, 7);
ui.alert(
"✅ Dashboard 2 Created!\n\n" +
'Run "Add Test Data" to see charts populate.',
);
Logger.log("Dashboard 2 created successfully");
}
// ============================================
// TEST DATA FUNCTIONS
// ============================================
/**
* Adds sample test data to all sheets
*/
function addTestData() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
// Verify template exists
if (!ss.getSheetByName("Assets Master")) {
ui.alert('Please run "Build Complete Template" first.');
return;
}
const today = new Date();
// ============================================
// ASSETS MASTER DATA
// ============================================
const assets = ss.getSheetByName("Assets Master");
const assetData = [
[
"A-001",
"Red F-150",
"Vehicle",
"Available",
"Main Yard",
"John Smith",
new Date(2024, 10, 1),
null,
90,
new Date(2023, 5, 15),
35000,