-
-
Notifications
You must be signed in to change notification settings - Fork 194
/
googleIntegration.ts
363 lines (321 loc) Β· 13.9 KB
/
googleIntegration.ts
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
import { google, sheets_v4 } from 'googleapis'
import { Config, updateConfig } from '../../common/config'
import { IntegrationId } from '../../types/integrations'
import { GoogleConfig } from '../../types/integrations/google'
import { OAuth2Client, Credentials } from 'google-auth-library'
import { logInfo, logError } from '../../common/logging'
import { Account } from '../../types/account'
import { sortBy, groupBy } from 'lodash'
import { startOfMonth, format, formatISO, parseISO } from 'date-fns'
export interface Range {
sheet: string
start: string
end: string
}
export interface DataRange {
range: Range
data: any[][]
}
export class GoogleIntegration {
config: Config
googleConfig: GoogleConfig
client: OAuth2Client
sheets: sheets_v4.Resource$Spreadsheets
constructor(config: Config) {
this.config = config
this.googleConfig = config.integrations[IntegrationId.Google] as GoogleConfig
this.client = new google.auth.OAuth2(
this.googleConfig.credentials.clientId,
this.googleConfig.credentials.clientSecret,
this.googleConfig.credentials.redirectUri
)
this.client.setCredentials({
access_token: this.googleConfig.credentials.accessToken,
refresh_token: this.googleConfig.credentials.refreshToken,
token_type: this.googleConfig.credentials.tokenType,
expiry_date: this.googleConfig.credentials.expiryDate
})
this.sheets = google.sheets({
version: 'v4',
auth: this.client
}).spreadsheets
}
public getAuthURL = (): string =>
this.client.generateAuthUrl({
scope: this.googleConfig.credentials.scope
})
public getAccessTokens = (authCode: string): Promise<Credentials> =>
this.client.getToken(authCode).then(response => response.tokens)
public saveAccessTokens = (tokens: Credentials): void => {
updateConfig(config => {
let googleConfig = config.integrations[IntegrationId.Google] as GoogleConfig
googleConfig.credentials.accessToken = tokens.access_token
googleConfig.credentials.refreshToken = tokens.refresh_token
googleConfig.credentials.tokenType = tokens.token_type
googleConfig.credentials.expiryDate = tokens.expiry_date
config.integrations[IntegrationId.Google] = googleConfig
return config
})
}
public getSheets = (documentId?: string): Promise<sheets_v4.Schema$Sheet[]> => {
return this.sheets
.get({ spreadsheetId: documentId || this.googleConfig.documentId })
.then(res => {
logInfo(`Fetched ${res.data.sheets.length} sheets.`, res.data.sheets)
return res.data.sheets
})
.catch(error => {
logError(`Error fetching sheets for spreadsheet ${this.googleConfig.documentId}.`, error)
return []
})
}
public copySheet = async (title: string, sourceDocumentId?: string): Promise<sheets_v4.Schema$SheetProperties> => {
const sheets = await this.getSheets(sourceDocumentId || this.googleConfig.documentId)
let sourceSheetId
try {
sourceSheetId = sheets.find(sheet => sheet.properties.title === title).properties.sheetId
} catch (error) {
logError(`Error finding template sheet ${title} in document ${sourceDocumentId}.`, { error, sheets })
}
return this.sheets.sheets
.copyTo({
spreadsheetId: sourceDocumentId || this.googleConfig.documentId,
sheetId: sourceSheetId,
requestBody: { destinationSpreadsheetId: this.googleConfig.documentId }
})
.then(res => {
logInfo(`Copied sheet ${title}.`, res.data)
return res.data
})
.catch(error => {
logError(`Error copying sheet ${title}.`, error)
return {}
})
}
public addSheet = (title: string): Promise<sheets_v4.Schema$SheetProperties> => {
return this.sheets
.batchUpdate({
spreadsheetId: this.googleConfig.documentId,
requestBody: { requests: [{ addSheet: { properties: { title } } }] }
})
.then(res => {
logInfo(`Added sheet ${title}.`, res.data)
return res.data.replies[0].addSheet.properties
})
.catch(error => {
logError(`Error adding sheet ${title}.`, error)
return {}
})
}
public renameSheet = async (oldTitle: string, newTitle: string): Promise<sheets_v4.Schema$Response[]> => {
const sheets = await this.getSheets()
const sheetId = sheets.find(sheet => sheet.properties.title === oldTitle).properties.sheetId
return this.sheets
.batchUpdate({
spreadsheetId: this.googleConfig.documentId,
requestBody: {
requests: [
{
updateSheetProperties: {
properties: { sheetId: sheetId, title: newTitle },
fields: 'title'
}
}
]
}
})
.then(res => {
logInfo(`Renamed sheet ${oldTitle} to ${newTitle}.`, res.data)
return res.data.replies
})
.catch(error => {
logError(`Error renaming sheet ${oldTitle} to ${newTitle}.`, error)
return []
})
}
public translateRange = (range: Range): string =>
`'${range.sheet}'!${range.start.toUpperCase()}:${range.end.toUpperCase()}`
public translateRanges = (ranges: Range[]): string[] => ranges.map(this.translateRange)
public clearRanges = (ranges: Range[]): Promise<sheets_v4.Schema$BatchClearValuesResponse> => {
const translatedRanges = this.translateRanges(ranges)
return this.sheets.values
.batchClear({
spreadsheetId: this.googleConfig.documentId,
requestBody: { ranges: translatedRanges }
})
.then(res => {
logInfo(`Cleared ${ranges.length} range(s): ${translatedRanges}.`, res.data)
return res.data
})
.catch(error => {
logError(`Error clearing ${ranges.length} range(s): ${translatedRanges}.`, error)
return {}
})
}
public updateRanges = (dataRanges: DataRange[]): Promise<sheets_v4.Schema$BatchUpdateValuesResponse> => {
const data = dataRanges.map(dataRange => ({
range: this.translateRange(dataRange.range),
values: dataRange.data
}))
return this.sheets.values
.batchUpdate({
spreadsheetId: this.googleConfig.documentId,
requestBody: {
valueInputOption: `USER_ENTERED`,
data: data
}
})
.then(res => {
logInfo(`Updated ${data.length} range(s): ${data.map(r => r.range)}.`, res.data)
return res.data
})
.catch(error => {
logError(`Error updating ${data.length} range(s): ${data.map(r => r.range)}.`, error)
return {}
})
}
public sortSheets = async (): Promise<sheets_v4.Schema$BatchUpdateSpreadsheetResponse> => {
const sheets = await this.getSheets()
const ordered = sortBy(sheets, sheet => sheet.properties.title).reverse()
return this.sheets
.batchUpdate({
spreadsheetId: this.googleConfig.documentId,
requestBody: {
requests: ordered.map((sheet, i) => ({
updateSheetProperties: {
properties: { sheetId: sheet.properties.sheetId, index: i },
fields: 'index'
}
}))
}
})
.then(res => {
logInfo(`Updated indices for ${sheets.length} sheets.`, res.data)
return res.data
})
.catch(error => {
logError(`Error updating indices for ${sheets.length} sheets.`, error)
return {}
})
}
public formatSheets = async (): Promise<sheets_v4.Schema$BatchUpdateSpreadsheetResponse> => {
const sheets = await this.getSheets()
return this.sheets
.batchUpdate({
spreadsheetId: this.googleConfig.documentId,
requestBody: {
requests: sheets
.map(sheet => [
{
repeatCell: {
range: { sheetId: sheet.properties.sheetId, startRowIndex: 0, endRowIndex: 1 },
cell: {
userEnteredFormat: {
backgroundColor: { red: 0.2, green: 0.2, blue: 0.2 },
horizontalAlignment: 'CENTER',
textFormat: {
foregroundColor: { red: 1.0, green: 1.0, blue: 1.0 },
bold: true
}
}
},
fields: 'userEnteredFormat(backgroundColor,textFormat,horizontalAlignment)'
}
},
{
updateSheetProperties: {
properties: {
sheetId: sheet.properties.sheetId,
gridProperties: { frozenRowCount: 1 }
},
fields: 'gridProperties.frozenRowCount'
}
},
{
autoResizeDimensions: {
dimensions: {
sheetId: sheet.properties.sheetId,
dimension: 'COLUMNS',
startIndex: 0,
endIndex: sheet.properties.gridProperties.columnCount
}
}
}
])
.flat(10)
}
})
.then(res => {
logInfo(`Updated formatting for ${sheets.length} sheets.`, res.data)
return res.data
})
.catch(error => {
logError(`Error updating formatting for ${sheets.length} sheets.`, error)
return {}
})
}
public getRowWithDefaults = (row: { [key: string]: any }, columns: string[], defaultValue: any = null): any[] => {
return columns.map(key => {
if (row && row.hasOwnProperty(key)) {
if (key === 'date') {
return format(row[key], this.googleConfig.dateFormat || 'yyyy.MM.dd')
}
return row[key]
}
return defaultValue
})
}
public updateSheet = async (
sheetTitle: string,
rows: { [key: string]: any }[],
columns?: string[],
useTemplate?: boolean
): Promise<sheets_v4.Schema$BatchUpdateValuesResponse> => {
const sheets = await this.getSheets()
const existing = sheets.find(sheet => sheet.properties.title === sheetTitle)
if (existing === undefined) {
if (this.googleConfig.template && useTemplate === true) {
const copied = await this.copySheet(
this.googleConfig.template.sheetTitle,
this.googleConfig.template.documentId
)
await this.renameSheet(copied.title, sheetTitle)
} else {
await this.addSheet(sheetTitle)
}
}
columns = columns || Object.keys(rows[0])
const columnHeaders = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
const range = {
sheet: sheetTitle,
start: `A1`,
end: `${columnHeaders[columns.length]}${rows.length + 1}`
}
const data = [columns].concat(rows.map(row => this.getRowWithDefaults(row, columns)))
await this.clearRanges([range])
return this.updateRanges([{ range, data }])
}
public updateAccounts = async (accounts: Account[]) => {
// Update Account Balances Sheets
await this.updateSheet('Balances', accounts, this.config.balances.properties)
// Sort transactions by date
const transactions = sortBy(accounts.map(account => account.transactions).flat(10), 'date')
// Split transactions by month
const groupedTransactions = groupBy(transactions, transaction => formatISO(startOfMonth(transaction.date)))
// Write transactions by month, copying template sheet if necessary
for (const month in groupedTransactions) {
await this.updateSheet(
format(parseISO(month), this.googleConfig.dateFormat || 'yyyy.MM'),
groupedTransactions[month],
this.config.transactions.properties,
true
)
}
// Sort Sheets
await this.sortSheets()
// Format, etc.
await this.formatSheets()
logInfo('You can view your sheet at the below link:\n')
console.log(`https://docs.google.com/spreadsheets/d/${this.googleConfig.documentId}`)
}
}