-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdateSpreadsheet.js
160 lines (153 loc) · 5.55 KB
/
updateSpreadsheet.js
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
require('dotenv').config();
process.removeAllListeners('warning'); // used to remove punycode deprecation warning until google gets its shit together and upgrades node-fetch
const fs = require('fs');
const { google } = require('googleapis');
const serviceAuth = new google.auth.GoogleAuth({
keyFile: './.serviceCredentials.json',
scopes: [ 'https://www.googleapis.com/auth/spreadsheets' ]
});
google.options({ auth: serviceAuth });
const sheets = google.sheets({ version: 'v4' });
const TRANSACTIONCACHEFILE = './.transactionCache.json';
const getSheetsTransactions = async () => {
let sheetsResponse;
try {
sheetsResponse = await sheets.spreadsheets.values.get({
spreadsheetId: process.env.SPREADSHEETID,
range: process.env.SPREADSHEETNAME,
valueRenderOption: 'UNFORMATTED_VALUE',
dateTimeRenderOption: 'FORMATTED_STRING'
});
} catch(e) {
if (e.errors || e.response?.data?.error) {
return { errors: e.errors ? e.errors : e.response?.data?.error ? e.response.data.error : 'error' };
}
}
const localSheetTransactions = sheetsResponse.data.values;
if (!localSheetTransactions || localSheetTransactions.length === 0) {
console.log('No data found.');
return {};
}
const headers = localSheetTransactions[0];
let data = [];
for (i = 1; i < localSheetTransactions.length; i++) { // skip header row
let newRow = {};
headers.forEach((header, index) => {
if (localSheetTransactions[i][index]) {
newRow[header] = localSheetTransactions[i][index];
newRow['rowNum'] = i + 1;
}
});
data.push(newRow);
}
// transform sheet transactions into UUID objects
let sheetData = {};
data.forEach((row) => {
sheetData[row.UUID] = row;
});
return sheetData;
}
const go = async () => {
let transactions = {};
try {
transactions = JSON.parse(fs.readFileSync(TRANSACTIONCACHEFILE));
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
// transform transactions into UUID objects
let txData = {};
Object.keys(transactions).forEach((thisBlock) => {
const timestamp = Number(transactions[thisBlock].timestamp);
const dateParts = transactions[thisBlock].date.split('-');
const thisRationalDate = dateParts[1] + '-' + dateParts[0] + '-' + dateParts[2]; // change the date to mm-dd-yyyy
const closingPrice = transactions[thisBlock].closingPrice;
if (transactions[thisBlock].transactions) {
transactions[thisBlock].transactions.forEach((tx) => {
if (tx.taxable) { // exclude uniswap change transactions because sheets data doesn't know about swaps for tax purposes
txData[tx.UUID] = tx;
txData[tx.UUID].layer = 'EL';
txData[tx.UUID].timestamp = timestamp;
txData[tx.UUID].date = thisRationalDate;
txData[tx.UUID].closingPrice = closingPrice;
txData[tx.UUID].blockNumber = Number(thisBlock);
}
});
}
if (transactions[thisBlock].withdrawals) {
transactions[thisBlock].withdrawals.forEach((withdrawal) => {
txData[withdrawal.UUID] = withdrawal;
txData[withdrawal.UUID].layer = 'CL';
txData[withdrawal.UUID].timestamp = timestamp;
txData[withdrawal.UUID].date = thisRationalDate;
txData[withdrawal.UUID].closingPrice = closingPrice;
txData[withdrawal.UUID].blockNumber = Number(thisBlock);
});
}
});
transactions = txData;
txData = null;
const sheetTransactions = await getSheetsTransactions();
if (sheetTransactions.errors) {
console.log(sheetTransactions);
return;
}
let operations = { updateSheetUUIDs: [], appendSheetUUIDS: [], updates: [], appends: [] };
Object.keys(transactions).forEach((UUID) => {
if (!sheetTransactions[UUID]) {
operations.appendSheetUUIDS.push(UUID);
} else if (transactions[UUID].closingPrice > 0 && (!sheetTransactions[UUID]['USD Closing Price'] || sheetTransactions[UUID]['USD Closing Price'] === 0)) {
operations.updateSheetUUIDs.push(UUID);
}
});
if (operations.updateSheetUUIDs.length > 0) {
console.log('Updating', operations.updateSheetUUIDs.length, 'rows...');
operations.updateSheetUUIDs.forEach((UUID) => {
// console.log('update (' + sheetTransactions[UUID].rowNum + '):', sheetTransactions[UUID], transactions[UUID]);
operations.updates.push({
majorDimension: 'ROWS',
range: process.env.SPREADSHEETNAME + '!C' + sheetTransactions[UUID].rowNum + ':D' + sheetTransactions[UUID].rowNum,
values: [[transactions[UUID].closingPrice, transactions[UUID].usdValue]]
});
});
try {
sheetsResponse = await sheets.spreadsheets.values.batchUpdate({
spreadsheetId: process.env.SPREADSHEETID,
requestBody: {
valueInputOption: 'USER_ENTERED',
data: operations.updates,
},
});
} catch(e) {
console.log(e.errors);
return;
}
console.log('Updated', sheetsResponse.data.totalUpdatedRows, 'rows.');
}
if (operations.appendSheetUUIDS.length > 0) {
console.log('Appending', operations.appendSheetUUIDS.length, 'rows...');
operations.appendSheetUUIDS.forEach((UUID) => {
// console.log('append:', transactions[UUID]);
operations.appends.push(
[transactions[UUID].date, transactions[UUID].layer, transactions[UUID].closingPrice, transactions[UUID].usdValue, transactions[UUID].ethValue, transactions[UUID].blockNumber, transactions[UUID].hash ? transactions[UUID].hash : '', UUID]
);
});
try {
sheetsResponse = await sheets.spreadsheets.values.append({
spreadsheetId: process.env.SPREADSHEETID,
range: process.env.SPREADSHEETNAME,
valueInputOption: 'USER_ENTERED',
resource: {
majorDimension: 'ROWS',
values: operations.appends
}
});
} catch(e) {
console.log(e);
return;
}
console.log('Appended', sheetsResponse.data.updates.updatedRows, 'rows.');
}
}
go();