This repository has been archived by the owner on Feb 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
importer.js
342 lines (285 loc) · 9.51 KB
/
importer.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
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
const fs = require('fs');
const os = require('os');
const { join } = require('path');
const d = require('date-fns');
const uuid = require('uuid');
const actual = require('@actual-app/api');
const { amountToInteger } = actual.utils;
function amountFromYnab(amount) {
// ynabs multiplies amount by 1000 and actual by 100
// so, this function divides by 10
return Math.round(amount/10);
}
function monthFromDate(date) {
let parts = date.split('-');
return parts[0] + '-' + parts[1];
}
function mapAccountType(type) {
switch (type) {
case 'cash':
case 'checking':
return 'checking';
case 'creditCard':
case 'lineOfCredit':
return 'credit';
case 'savings':
return 'savings';
case 'investmentAccount':
return 'investment';
case 'mortgage':
return 'mortgage';
default:
return 'other';
}
}
function sortByKey(arr, key) {
return [...arr].sort((item1, item2) => {
if (item1[key] < item2[key]) {
return -1;
} else if (item1[key] > item2[key]) {
return 1;
}
return 0;
});
}
function groupBy(arr, keyName) {
return arr.reduce(function(obj, item) {
var key = item[keyName];
if (!obj.hasOwnProperty(key)) {
obj[key] = [];
}
obj[key].push(item);
return obj;
}, {});
}
function importAccounts(data, entityIdMap) {
return Promise.all(
data.accounts.map(async account => {
if (!account.deleted) {
let id = await actual.createAccount({
type: mapAccountType(account.type),
name: account.name,
offbudget: account.on_budget ? false : true,
closed: account.closed
});
entityIdMap.set(account.id, id);
}
})
);
}
async function importCategories(data, entityIdMap) {
// Hidden categories are put in its own group by YNAB,
// so it's already handled.
const categories = await actual.getCategories();
const incomeCatId = categories.find(cat => cat.name === 'Income').id;
const ynabIncomeCategories = ["To be Budgeted", "Inflow: Ready to Assign"]
function checkSpecialCat(cat) {
if (cat.category_group_id ===
data.category_groups.find(group =>
group.name === "Internal Master Category").id) {
if (ynabIncomeCategories.includes(cat.name) ) {
return "income";
} else {
return "internal";
}
}
else if (cat.category_group_id ===
data.category_groups.find(group =>
group.name === "Credit Card Payments").id) {
return "creditCard";
}
}
// Can't be done in parallel to have
// correct sort order.
for (group of data.category_groups) {
if (!group.deleted) {
// Ignores internal category and credit cards
if (group.name !== "Internal Master Category" &&
group.name !== "Credit Card Payments") {
var groupId = await actual.createCategoryGroup({
name: group.name,
is_income: false
});
entityIdMap.set(group.id, groupId);
}
cats = data.categories.filter(cat => cat.category_group_id === group.id);
for (cat of cats.reverse()) {
if (!cat.deleted) {
newCategory = {};
newCategory.name = cat.name;
// Handles special categories. Starting balance is a payee
// in YNAB so it's handled in importTransactions
switch (checkSpecialCat(cat)) {
case "income": // doesn't create new category, only assigns id
id = incomeCatId;
entityIdMap.set(cat.id, id);
break;
case "creditCard": // ignores it
case "internal": // uncategorized is ignored too, handled by actual
break;
default:
newCategory.group_id = groupId;
id = await actual.createCategory(newCategory);
entityIdMap.set(cat.id, id);
break;
}
}
}
}
}
}
function importPayees(data, entityIdMap) {
return Promise.all(
data.payees.map(async payee => {
if (!payee.deleted) {
let id = await actual.createPayee({
name: payee.name,
});
entityIdMap.set(payee.id, id);
}
})
);
}
async function importTransactions(data, entityIdMap) {
// TODO: Handle subtransactions and imported transactions
const payees = await actual.getPayees();
const categories = await actual.getCategories();
const incomeCatId = categories.find(cat => cat.name === 'Income').id;
const startingBalanceCatId = categories.find(cat => cat.name === 'Starting Balances').id; //better way to do it?
const startingPayeeYNAB = data.payees.find(payee => payee.name === 'Starting Balance').id;
let transactionsGrouped = groupBy(data.transactions, 'account_id');
let subtransactionsGrouped = groupBy(data.subtransactions, 'transaction_id')
// Go ahead and generate ids for all of the transactions so we can
// reliably resolve transfers
for (let transaction of data.transactions) {
entityIdMap.set(transaction.id, uuid.v4());
}
await Promise.all(
Object.keys(transactionsGrouped).map(async accountId => {
let transactions = transactionsGrouped[accountId];
let toImport = transactions.map(transaction => {
if (transaction.deleted) {
return;
}
// Handle subtransactions
let subtransactions = subtransactionsGrouped[transaction.id];
if(subtransactions){
subtransactions = subtransactions.map(subtrans => {
return {
amount: amountFromYnab(subtrans.amount),
category: entityIdMap.get(subtrans.category_id) || null,
notes: subtrans.memo
}
})
}
// Add transaction
let newTransaction = {
id: entityIdMap.get(transaction.id),
account: entityIdMap.get(transaction.account_id),
date: transaction.date,
amount: amountFromYnab(transaction.amount),
category: entityIdMap.get(transaction.category_id) || null,
cleared: ["cleared", "reconciled"].includes(transaction.cleared),
notes: transaction.memo || null,
imported_id: transaction.import_id || null,
transfer_id: entityIdMap.get(transaction.transfer_transaction_id) || null,
subtransactions: subtransactions,
};
// Handle transfer payee
if (transaction.transfer_account_id) {
newTransaction.payee = payees.find(
p =>
p.transfer_acct === entityIdMap.get(transaction.transfer_account_id)
).id;
} else {
newTransaction.payee = entityIdMap.get(transaction.payee_id);
}
// Handle starting balances
if (transaction.payee_id === startingPayeeYNAB &&
entityIdMap.get(transaction.category_id) === incomeCatId
) {
newTransaction.category = startingBalanceCatId;
newTransaction.payee = null;
}
return newTransaction;
})
.filter(x => x);
await actual.addTransactions(entityIdMap.get(accountId), toImport);
})
);
}
async function importBudgets(data, entityIdMap) {
// There should be info in the docs to deal with
// no credit card category and how YNAB and Actual
// handle differently the amount To be Budgeted
// i.e. Actual considers the cc debt while YNAB doesn't
//
// Also, there could be a way to set rollover using
// Deferred Income Subcat and Immediate Income Subcat
let budgets = sortByKey(data.months, 'month');
const internalCatIdYnab = data.category_groups.find(
group =>
group.name === "Internal Master Category"
).id
const creditcardCatIdYnab = data.category_groups.find(
group =>
group.name === "Credit Card Payments"
).id
await actual.batchBudgetUpdates(async () => {
for (let budget of budgets) {
let month = monthFromDate(budget.month);
await Promise.all(
budget.categories.map(async catBudget => {
let catId = entityIdMap.get(catBudget.id);
let amount = catBudget.budgeted/10;
if (!catId ||
catBudget.category_group_id === internalCatIdYnab ||
catBudget.category_group_id === creditcardCatIdYnab
) {
return;
}
await actual.setBudgetAmount(month, catId, amount);
})
);
}
});
}
// Utils
async function doImport(data) {
const entityIdMap = new Map();
console.log('Importing Accounts...');
await importAccounts(data, entityIdMap);
console.log('Importing Categories...');
await importCategories(data, entityIdMap);
console.log('Importing Payees...');
await importPayees(data, entityIdMap);
console.log('Importing Transactions...');
await importTransactions(data, entityIdMap);
console.log('Importing Budgets...');
await importBudgets(data, entityIdMap);
console.log('Setting up...');
}
async function importYNAB5(filepath) {
if (!fs.existsSync(filepath)) {
throw new Error(`File not found at the provided path: ${filepath}`)
}
let contents;
try {
contents = fs.readFileSync(filepath, 'utf8');
} catch (e) {
throw new Error('Error reading file');
}
let data;
try {
data = JSON.parse(contents);
} catch (e) {
throw new Error('Error parsing file');
}
if(data.data) {
data = data.data;
}
return actual.runImport(data.budget.name, () =>
doImport(data.budget)
);
}
module.exports = { importYNAB5 };