This repository has been archived by the owner on Mar 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcode.gs
720 lines (583 loc) · 23.2 KB
/
code.gs
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
/*
=============================================================================
Project Page: https://github.com/cmenon12/bank-account-to-sheets
Copyright: (c) 2021 by Christopher Menon
License: GNU General Public License, version 3 (GPL-3.0)
http://www.opensource.org/licenses/gpl-3.0.html
=============================================================================
*/
/**
* Make a request to the URL using the params.
*
* @param {string} url the URL to make the request to.
* @param {Object} params the params to use with the request.
* @return {string} the text of the response if successful.
* @throws {Error} response status code was not 200.
*/
function makeRequest(url, params) {
// Make the POST request
const response = UrlFetchApp.fetch(url, params);
const status = response.getResponseCode();
const responseText = response.getContentText();
// If successful then return the response text
if (status === 200) {
return responseText;
// Otherwise log and throw an error
} else {
Logger.log(`There was a ${status} error fetching ${url}.`);
Logger.log(responseText);
throw Error(`There was a ${status} error fetching ${url}.`);
}
}
/**
* Downloads and returns all transactions from Plaid.
*
* @return {Object} the result of transactions.get, with all transactions.
*/
function downloadAllTransactionsFromPlaid() {
/*// Force Plaid to refresh the transactions
let params = {
"contentType": "application/json",
"method": "post",
"payload": JSON.stringify({
"client_id": getSecrets().CLIENT_ID,
"secret": getSecrets().SECRET,
"access_token": getSecrets().ACCESS_TOKEN
}),
"muteHttpExceptions": true
};
makeRequest(`${getSecrets().URL}/transactions/refresh`, params);
*/
// Prepare the request body
const body = {
"client_id": getSecrets().CLIENT_ID,
"secret": getSecrets().SECRET,
"access_token": getSecrets().ACCESS_TOKEN,
"options": {
"count": 500,
"offset": 0
},
"start_date": "2017-01-01",
"end_date": "2030-01-01"
};
// Condense the above into a single object
params = {
"contentType": "application/json",
"method": "post",
"payload": JSON.stringify(body),
"muteHttpExceptions": true
};
// Make the first POST request
const result = JSON.parse(makeRequest(`${getSecrets().URL}/transactions/get`, params));
const total_count = result.total_transactions;
let offset = 0;
let r;
Logger.log(`There are ${total_count} transactions in Plaid.`);
// Make repeated requests
while (offset <= total_count - 1) {
offset = offset + 500;
body.options.offset = offset;
params.payload = JSON.stringify(body);
r = JSON.parse(makeRequest(`${getSecrets().URL}/transactions/get`, params));
result.transactions = result.transactions.concat(r.transactions);
}
// Replace the dates with JavaScript dates
for (const plaidTxn of result.transactions) plaidTxn.date = Date.parse(plaidTxn.date);
Logger.log(`We downloaded ${result.transactions.length} transactions from Plaid.`);
return result;
}
/**
* Fetch the transactions that are currently on the sheet.
*
* @param {SpreadsheetApp.Sheet} sheet the sheet to fetch the transactions from.
* @return {Object} the transactions.
*/
function getTransactionsFromSheet(sheet) {
const result = {};
result.transactions = [];
result.available = 0.0;
result.current = 0.0;
// Get the headers
result.headers = sheet.getRange(getHeaderRowNumber(sheet), 1, 1, sheet.getLastColumn()).getValues().flat();
result.headers = result.headers.map(item => item.replace("?", ""));
result.headers = result.headers.map(item => item.toLowerCase());
// Don't bother if it's empty
if (sheet.getLastRow() === getHeaderRowNumber(sheet)) {
Logger.log(`We fetched ${result.transactions.length} transactions from the sheet named ${sheet.getName()}.`);
return result;
}
// Get the transactions, starting with most recent
const values = sheet.getRange(getHeaderRowNumber(sheet) + 1, 1, sheet.getLastRow() - getHeaderRowNumber(sheet), sheet.getLastColumn()).getValues();
for (let i = 0; i < values.length; i++) {
const newSheetTxn = {};
for (let j = 0; j < result.headers.length; j++) {
newSheetTxn[result.headers[j].toLowerCase()] = values[i][j];
}
if (typeof newSheetTxn.date === "number") {
newSheetTxn.date = new Date(newSheetTxn.date)
}
result.transactions.push(newSheetTxn);
// Increment the balance(s)
result.current += Number(values[i][6]);
if (values[i][7] === false) {
result.available += Number(values[i][6]);
}
}
Logger.log(`We fetched ${result.transactions.length} transactions from the sheet named ${sheet.getName()}.`);
return result;
}
/**
* Convert a Plaid transaction to a transaction for the sheet.
*
* @param {Object} plaidTxn the transaction to convert.
* @param {Object} sheetTxn the existing sheet transaction to update.
* @return {Object} the converted transaction.
*/
function plaidToSheet(plaidTxn, sheetTxn = undefined) {
// Use existing values if we have them
let internal;
let notes;
let category;
let subcategory;
let channel;
if (sheetTxn === undefined) {
internal = false;
notes = "";
if (plaidTxn.category === null) {
category = "UNKNOWN";
subcategory = "UNKNOWN";
} else {
category = plaidTxn.category[0];
subcategory = "";
for (const subcat of plaidTxn.category.slice(1)) subcategory = subcategory + subcat + " ";
subcategory = subcategory.slice(0, -1);
}
channel = plaidTxn.payment_channel;
} else {
internal = sheetTxn.internal;
notes = sheetTxn.notes;
category = sheetTxn.category;
subcategory = sheetTxn.subcategory;
channel = sheetTxn.channel;
}
// Return the transaction for the sheet
return {
"id": plaidTxn.transaction_id,
"date": plaidTxn.date,
"name": plaidTxn.name,
"category": category,
"subcategory": subcategory,
"channel": channel,
"account": plaidTxn.account_name,
"amount": -plaidTxn.amount,
"pending": plaidTxn.pending,
"internal": internal,
"notes": notes
};
}
/**
* Searches the transactions from the sheet to see if a given Plaid transaction already exists.
* Painfully inefficient.
*
* @param {Object[]} sheetTxns the sheet transactions to search.
* @param {Object} plaidTxn the Plaid transaction to search for.
* @return {Number} the index of the plaidTxn, or -1 if it doesn't exist.
*/
function getIndexOfPlaidFromSheet(sheetTxns, plaidTxn) {
const sameDateAndAmount = [];
for (let i = 0; i < sheetTxns.length; i++) {
// Check the IDs
if (sheetTxns[i].id === plaidTxn.pending_transaction_id) {
return i;
} else if (sheetTxns[i].id === plaidTxn.transaction_id) {
return i;
}
/* Only enable when the ACCESS_TOKEN has been changed
// Check the date, name, and amount
let date = sheetTxns[i].date
if (typeof date === "number") {
date = new Date(date)
}
if (date.getTime() === plaidTxn.date &&
sheetTxns[i].name === plaidTxn.name &&
sheetTxns[i].amount === -plaidTxn.amount) {
return i;
}
// For if the name has changed
if (date.getTime() === plaidTxn.date &&
sheetTxns[i].amount === -plaidTxn.amount) {
sameDateAndAmount.push(i)
}
*/
}
// If there was only one with that date and amount
if (sameDateAndAmount.length === 1) {
return sameDateAndAmount[0];
}
return -1;
}
/**
* Searches the transactions from plaid for the transaction with the ID, and returns its index.
* Painfully inefficient.
*
* @param {Object[]} plaidTxns the Plaid transactions to search.
* @param {string} id ID to search for.
* @return {Number} the index of the transaction, or -1 if it doesn't exist.
*/
function getIndexOfIdFromPlaid(plaidTxns, id) {
for (let i = 0; i < plaidTxns.length; i++) {
if (plaidTxns[i].transaction_id === id) {
return i;
} else if (plaidTxns[i].pending_transaction_id === id) {
return i;
}
}
return -1;
}
/**
* Inserts the sheet transaction into the sheet transactions in the correct place.
*
* @param {Object[]} sheetTxns the list of transactions from the sheet.
* @param {Object} sheetTxn the sheet transaction to insert.
* @return {Object[]} the updated sheet transactions.
*/
function saveNewSheetTransaction(sheetTxns, sheetTxn) {
// Insert it when we first encounter an existing one with a smaller date
for (let i = 0; i < sheetTxns.length; i++) {
if (sheetTxn.date >= sheetTxns[i].date) {
sheetTxns.splice(i, 0, sheetTxn);
return sheetTxns;
}
}
// If the new transaction is the oldest then add it at the end
sheetTxns.push(sheetTxn);
return sheetTxns;
}
/**
* Writes the sheet transactions to the sheet.
*
* @param {SpreadsheetApp.Sheet} sheet the sheet to write the transactions to.
* @param {Object[]} sheetTxns the sheet transactions to write.
* @param {string[]} headers the headers of the sheet.
*/
function writeTransactionsToSheet(sheet, sheetTxns, headers) {
const result = [];
for (let i = 0; i < sheetTxns.length; i++) {
const row = headers.slice();
for (const [key, value] of Object.entries(sheetTxns[i])) {
if (key === "date") {
let date = new Date();
date.setTime(value);
row[row.indexOf(key)] = date;
} else {
row[row.indexOf(key)] = value;
}
}
result.push(row);
}
sheet.deleteRows(getHeaderRowNumber(sheet) + 2, sheet.getLastRow() - (getHeaderRowNumber(sheet) + 1));
sheet.insertRowsAfter(getHeaderRowNumber(sheet) + 1, result.length - 1);
sheet.getRange(getHeaderRowNumber(sheet) + 1, 1, result.length, sheet.getLastColumn()).setValues(result);
}
/**
* Formats the date as a nice string.
*
* @param {Date} date the date to parse.
* @return {string} the nicely formatted date.
*/
function formatDate(date) {
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
return `${days[date.getDay()]} ${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
}
/**
* Updates the transactions in the Transactions sheet.
*/
function updateTransactions() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Transactions");
const existing = getTransactionsFromSheet(sheet);
const plaid = downloadAllTransactionsFromPlaid();
// Prepare to determine changes
const changes = {
"added": [],
"removed": []
};
for (let i = 0; i < plaid.transactions.length; i++) {
// Add the account name, to save work later
let account_name = "?unknown?";
for (let j = 0; j < plaid.accounts.length; j++) {
if (plaid.accounts[j].account_id === plaid.transactions[i].account_id) {
account_name = plaid.accounts[j].name;
break;
}
}
plaid.transactions[i].account_name = account_name;
let existingTxn = undefined;
let existingIndex;
// Search for it in existing
existingIndex = getIndexOfPlaidFromSheet(existing.transactions, plaid.transactions[i]);
if (existingIndex >= 0) {
existingTxn = existing.transactions[existingIndex]
}
// Update existing with the transaction
const newSheetTxn = plaidToSheet(plaid.transactions[i], existingTxn);
if (existingIndex >= 0) {
existing.transactions[existingIndex] = newSheetTxn;
} else {
existing.transactions = saveNewSheetTransaction(existing.transactions, newSheetTxn);
changes.added.push(newSheetTxn);
}
}
Logger.log("Finished iterating through Plaid transactions.");
// Find which old transactions have been removed
for (const sheetTxn of existing.transactions) {
if (getIndexOfIdFromPlaid(plaid.transactions, sheetTxn.id) === -1) {
existing.transactions.splice(existing.transactions.indexOf(sheetTxn), 1);
changes.removed.push(sheetTxn);
}
}
if (changes.added.length === 0 && changes.removed.length === 0) {
Logger.log("No transactions were added or removed.");
// Tell the user that there were no new transactions
// An error is raised if this is called by the trigger
try {
SpreadsheetApp.getActiveSpreadsheet().toast("No new changes to the transactions were found.");
} catch (error) {
}
} else {
// Write the transactions to the sheet
Logger.log(`There are ${existing.transactions.length} transactions to write.`);
writeTransactionsToSheet(sheet, existing.transactions, existing.headers);
Logger.log(`Finished writing transactions to the sheet named ${sheet.getName()}.`)
// Format the sheet neatly
formatNeatlyTransactions(plaid);
Logger.log(`Finished formatting the sheet named ${sheet.getName()} neatly.`);
// Produce a message to tell the user of the changes
// An error is raised if this is called by the trigger
try {
const ui = SpreadsheetApp.getUi();
let message = "";
if (changes.added.length > 0) {
for (const sheetTxn of changes.added) {
let date = new Date();
date.setTime(sheetTxn.date);
message = `${message}ADDED: £${sheetTxn.amount} on ${formatDate(date)} from ${sheetTxn.name}.\r\n`
}
}
if (changes.removed.length > 0) {
for (const sheetTxn of changes.removed) {
let date = new Date();
date.setTime(sheetTxn.date);
message = `${message}REMOVED: £${sheetTxn.amount} on ${formatDate(date)} from ${sheetTxn.name}.\r\n`
}
}
ui.alert(`${changes.added.length} added | ${changes.removed.length} removed`, message, ui.ButtonSet.OK);
} catch (error) {
}
}
// Update when this script was last run
const range = sheet.getRange(getHeaderRowNumber(sheet) - 1, sheet.getLastColumn());
if (range !== undefined) {
const date = new Date();
let minutes = date.getMinutes().toString();
if (parseInt(minutes) < 10) minutes = "0" + minutes;
const dateString = `Last updated on ${formatDate(date)} at ${date.getHours()}:${minutes}.`;
range.setValue(dateString);
}
}
/**
* Extract and return the totals for the given account.
*
* @param {Object} account the account from Plaid.
* @return {Object} the totals.
*/
function getPlaidAccountTotals(account) {
const result = {};
// For a credit card account
if (account.type === "credit") {
result.available = -(account.balances.limit - account.balances.available);
result.current = -account.balances.current;
result.pending = result.available - result.current;
// For a depository (normal current) account, or anything else
} else {
if (account.balances.available === null) {
result.available = account.balances.current;
result.current = account.balances.current;
result.pending = 0;
} else {
result.available = account.balances.available;
result.current = account.balances.current;
result.pending = result.available - result.current;
}
}
return result;
}
/**
* Formats the 'Transactions' sheet neatly.
*
* @param {Object} plaidResult the result of transactions.get from Plaid.
*/
function formatNeatlyTransactions(plaidResult = undefined) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Transactions");
// Get the headers
let headers = sheet.getRange(getHeaderRowNumber(sheet), 1, 1, sheet.getLastColumn()).getValues().flat();
headers = headers.map(item => item.replace("?", ""));
headers = headers.map(item => item.toLowerCase());
// Get column letters (for A1 notation)
const amountColNum = headers.indexOf("amount") + 1;
// Create named ranges
for (let i = 0; i < headers.length; i++) {
const range = sheet.getRange(getHeaderRowNumber(sheet) + 1, i + 1, sheet.getLastRow() - getHeaderRowNumber(sheet), 1);
SpreadsheetApp.getActiveSpreadsheet().setNamedRange(`${headers[i]}s`, range);
}
if (plaidResult !== undefined) {
sheet.deleteRows(1, getHeaderRowNumber(sheet) - 2);
Logger.log(`There are ${plaidResult.accounts.length} account(s).`)
if (plaidResult.accounts.length === 1) {
sheet.insertRows(1, 2)
// Add the total titles and merge them
sheet.getRange(1, 2, 1, amountColNum - 2).setValue("CURRENT BALANCE");
sheet.getRange(2, 2, 1, amountColNum - 2).setValue("AMOUNT PENDING (UNACCOUNTED FOR)");
sheet.getRange(3, 2, 1, amountColNum - 2).setValue("AMOUNT PENDING (ACCOUNTED FOR)");
sheet.getRange(4, 2, 1, amountColNum - 2).setValue("AVAILABLE BALANCE");
sheet.getRange(1, 2, 4, amountColNum - 2).mergeAcross();
// Extract the totals
const totals = getPlaidAccountTotals(plaidResult.accounts[0]);
// Add the totals themselves
sheet.getRange(1, amountColNum).setValue(`${totals.current}`);
sheet.getRange(2, amountColNum).setValue(`=${totals.pending}-SUMIF(pendings, "=TRUE", amounts)`);
sheet.getRange(3, amountColNum).setValue(`=SUMIF(pendings, "=TRUE", amounts)`);
sheet.getRange(4, amountColNum).setValue(`=${totals.current}-${totals.pending}`);
} else {
sheet.insertRows(1, (plaidResult.accounts.length * 3) + 4);
// Prepare to track the grand totals
const grandTotals = {};
grandTotals.available = 0;
grandTotals.current = 0;
grandTotals.pending = 0;
// For each account
for (let i = 1; i <= plaidResult.accounts.length; i++) {
// Add the total titles and merge them
sheet.getRange((i * 3) - 2, 2, 1, amountColNum - 2).setValue(`${plaidResult.accounts[i - 1].name} CURRENT BALANCE`);
sheet.getRange((i * 3) - 1, 2, 1, amountColNum - 2).setValue(`${plaidResult.accounts[i - 1].name} AMOUNT PENDING`);
sheet.getRange(i * 3, 2, 1, amountColNum - 2).setValue(`${plaidResult.accounts[i - 1].name} AVAILABLE BALANCE`);
sheet.getRange((i * 3) - 2, 2, 3, amountColNum - 2).mergeAcross();
// Extract the totals, and accumulate the grand totals
const totals = getPlaidAccountTotals(plaidResult.accounts[i - 1]);
grandTotals.available = totals.available + grandTotals.available;
grandTotals.current = totals.current + grandTotals.current;
grandTotals.pending = totals.pending + grandTotals.pending;
// Add the totals themselves
sheet.getRange((i * 3) - 2, amountColNum).setValue(`=ROUND(${totals.current}, 2)`);
sheet.getRange((i * 3) - 1, amountColNum).setValue(`=ROUND(${totals.pending}, 2)`);
sheet.getRange(i * 3, amountColNum).setValue(`=ROUND(${totals.available}, 2)`);
}
// Hide the account breakdown, because it takes up too much space
const startingRow = (plaidResult.accounts.length * 3) + 2;
sheet.hideRows(1, startingRow - 1);
// Add the total titles and merge them
sheet.getRange(startingRow, 2, 1, amountColNum - 2).setValue("TOTAL CURRENT BALANCE");
sheet.getRange(startingRow + 1, 2, 1, amountColNum - 2).setValue("TOTAL AMOUNT PENDING (UNACCOUNTED FOR)");
sheet.getRange(startingRow + 2, 2, 1, amountColNum - 2).setValue("TOTAL AMOUNT PENDING (ACCOUNTED FOR)");
sheet.getRange(startingRow + 3, 2, 1, amountColNum - 2).setValue("TOTAL AVAILABLE BALANCE");
sheet.getRange(startingRow, 2, 4, amountColNum - 2).mergeAcross();
// Add the totals themselves
sheet.getRange(startingRow, amountColNum).setValue(`=ROUND(${grandTotals.current}, 2)`);
sheet.getRange(startingRow + 1, amountColNum).setValue(`=ROUND(${grandTotals.pending}, 2)-SUMIF(pendings, "=TRUE", amounts)`);
sheet.getRange(startingRow + 2, amountColNum).setValue(`=SUMIF(pendings, "=TRUE", amounts)`);
sheet.getRange(startingRow + 3, amountColNum).setValue(`=ROUND(${grandTotals.available}, 2)`);
}
}
// Convert the TRUE/FALSE columns to checkboxes
sheet.getRange(`pendings`).insertCheckboxes();
sheet.getRange(`internals`).insertCheckboxes();
// Add conditional formatting to the amount column
const amountRange = sheet.getRange(`amounts`);
const positiveRule = SpreadsheetApp.newConditionalFormatRule().setFontColor("#1B5E20").whenNumberGreaterThan(0).setRanges([amountRange]).build();
const negativeRule = SpreadsheetApp.newConditionalFormatRule().setFontColor("#B71C1C").whenNumberLessThan(0).setRanges([amountRange]).build();
sheet.setConditionalFormatRules([positiveRule, negativeRule]);
// Add data validation for the categories, subcategories, and channels
let range = sheet.getRange("categorys");
let values = sheet.getRange("Categories")
let rule = SpreadsheetApp.newDataValidation().requireValueInRange(values, true).setAllowInvalid(false).build();
range.setDataValidation(rule);
range = sheet.getRange("subcategorys");
values = sheet.getRange("Subcategories")
rule = SpreadsheetApp.newDataValidation().requireValueInRange(values, true).setAllowInvalid(false).build();
range.setDataValidation(rule);
range = sheet.getRange("channels");
values = sheet.getRange("ChannelsValues")
rule = SpreadsheetApp.newDataValidation().requireValueInRange(values, true).setAllowInvalid(false).build();
range.setDataValidation(rule);
// Freeze the top rows and hide two columns
sheet.setFrozenRows(getHeaderRowNumber(sheet));
sheet.hideColumn(sheet.getRange("ids"));
sheet.hideColumn(sheet.getRange("accounts"));
// Add protection for ranges that shouldn't be edited
for (const protection of sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)) protection.remove();
for (const name of ["ids", "dates", "names", "accounts", "amounts", "pendings"]) {
sheet.getRange(name).protect().setWarningOnly(true);
}
// Recreate the filter
amountRange.getFilter().remove();
sheet.getRange(getHeaderRowNumber(sheet), 1, sheet.getLastRow() - (getHeaderRowNumber(sheet) - 1), sheet.getLastColumn()).createFilter();
}
/**
* Formats the 'Weekly Summary' sheet neatly.
*/
function formatNeatlyWeeklySummary() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Weekly Summary");
// Hide rows in the future
sheet.showRows(1, sheet.getLastRow());
const now = new Date();
for (let i = 3; i < sheet.getLastRow() - 1; i++) {
if (sheet.getRange(i, 2).getValue().getTime() <= now.getTime()) {
sheet.hideRows(3, i - 3)
break;
}
}
}
/**
* Searches for and returns the row number of the header row.
*
* @param {SpreadsheetApp.Sheet} sheet the sheet to search.
* @return {number} the row number, or -1 if it can't be found.
*/
function getHeaderRowNumber(sheet) {
const range = sheet.getRange(1, 1, sheet.getLastRow()).getValues();
for (let i = 0; i < range.length; i++) {
if (range[i][0] === "ID") {
return i + 1;
}
}
return -1;
}
/**
* Runs all the formatNeatly functions.
*/
function formatAll() {
formatNeatlyTransactions()
formatNeatlyWeeklySummary()
}
/**
* Updates transactions and then formats everything neatly.
*/
function doEverything() {
updateTransactions()
formatNeatlyWeeklySummary()
}
/**
* Adds the Scripts menu to the menu bar at the top.
*/
function onOpen() {
const menu = SpreadsheetApp.getUi().createMenu("Scripts");
menu.addItem("Update Transactions", "updateTransactions");
menu.addItem("Format the Transactions sheet neatly", "formatNeatlyTransactions");
menu.addItem("Format the Weekly Summary sheet neatly", "formatNeatlyWeeklySummary");
menu.addSeparator();
menu.addItem("Format all sheets neatly", "formatAll");
menu.addSeparator();
menu.addItem("Do everything", "doEverything");
menu.addToUi();
}