-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.ts
270 lines (248 loc) · 8.11 KB
/
api.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
import {
type Account,
type CategoryGroupWithCategories,
GetTransactionsTypeEnum,
type Payee,
type api
} from "ynab";
import { IS_DEV } from "./constants";
import type { CachedPayee } from "./types";
/** Fetch budgets from the YNAB API */
export async function fetchBudgets(ynabAPI: api) {
const {
data: { budgets }
} = await ynabAPI.budgets.getBudgets();
// Sort budgets by last modified
budgets.sort((a, b) =>
a.last_modified_on &&
b.last_modified_on &&
new Date(a.last_modified_on).valueOf() < new Date(b.last_modified_on).valueOf()
? 1
: -1
);
IS_DEV && console.log("Fetched budgets!", budgets);
return budgets.map((budgetSummary) => ({
id: budgetSummary.id,
name: budgetSummary.name,
currencyFormat: budgetSummary.currency_format || undefined
}));
}
/** Use a delta request for categories & accounts if cached data is fresher than this (6 hours) */
const DELTA_REQUEST_TIME = 6 * 60 * 60 * 1000;
/** Fetch category groups for this budget from the YNAB API */
export async function fetchCategoryGroupsForBudget(
ynabAPI: api,
selectedBudgetId: string,
cache?: {
data?: {
serverKnowledge: number;
categoryGroups: CategoryGroupWithCategories[];
};
dataUpdatedAt: number;
}
) {
const usingDeltaRequest =
!!cache?.data && cache.dataUpdatedAt > Date.now() - DELTA_REQUEST_TIME;
const response = await ynabAPI.categories.getCategories(
selectedBudgetId,
usingDeltaRequest ? cache.data?.serverKnowledge : undefined
);
let categoryGroups: CategoryGroupWithCategories[];
if (usingDeltaRequest && cache.data) {
categoryGroups = mergeCategoryGroupsDataFromDelta(
cache.data.categoryGroups,
response.data.category_groups
);
} else {
categoryGroups = response.data.category_groups;
}
// filter out hidden groups and categories
categoryGroups = categoryGroups.filter((group) => !group.hidden);
categoryGroups.forEach(
(cg) => (cg.categories = cg.categories.filter((c) => !c.hidden))
);
IS_DEV &&
console.log("Fetched categories!", {
categoryGroups,
usingDeltaRequest,
serverKnowledge: response.data.server_knowledge
});
return { categoryGroups, serverKnowledge: response.data.server_knowledge };
}
export function mergeCategoryGroupsDataFromDelta(
existingData: CategoryGroupWithCategories[],
deltaResponse: CategoryGroupWithCategories[]
) {
let categoryGroups = structuredClone(existingData);
for (const categoryGroupDelta of deltaResponse) {
if (categoryGroupDelta.deleted) {
categoryGroups = categoryGroups.filter((cg) => cg.id !== categoryGroupDelta.id);
continue;
}
const categoryGroupIdx = categoryGroups.findIndex(
(cg) => cg.id === categoryGroupDelta.id
);
if (categoryGroupIdx === -1) {
categoryGroups.push(categoryGroupDelta); // new category group
} else {
// update existing category group
categoryGroups[categoryGroupIdx].name = categoryGroupDelta.name;
categoryGroups[categoryGroupIdx].hidden = categoryGroupDelta.hidden;
const categories = categoryGroups[categoryGroupIdx].categories;
for (const categoryDelta of categoryGroupDelta.categories) {
const categoryIdx = categories.findIndex((c) => c.id === categoryDelta.id);
if (categoryIdx === -1) {
categories.push(categoryDelta); // new category
} else if (categoryDelta.deleted) {
categories.splice(categoryIdx, 1); // deleted category
} else {
categories.splice(categoryIdx, 1, categoryDelta); // update existing category
}
}
}
}
return categoryGroups;
}
/** Fetch accounts for this budget from the YNAB API */
export async function fetchAccountsForBudget(
ynabAPI: api,
selectedBudgetId: string,
cache?: {
data?: {
serverKnowledge: number;
accounts: Account[];
};
dataUpdatedAt: number;
}
) {
const usingDeltaRequest =
!!cache?.data && cache.dataUpdatedAt > Date.now() - DELTA_REQUEST_TIME;
const response = await ynabAPI.accounts.getAccounts(
selectedBudgetId,
usingDeltaRequest ? cache.data?.serverKnowledge : undefined
);
let accounts: Account[];
if (usingDeltaRequest && cache.data) {
accounts = mergeAccountsDataFromDelta(cache.data.accounts, response.data.accounts);
} else {
accounts = response.data.accounts;
}
// filter out closed accounts, and sort with Budget accounts first
accounts = accounts
.filter((a) => a.closed === false)
.sort((a, b) =>
a.on_budget && !b.on_budget ? -1 : !a.on_budget && b.on_budget ? 1 : 0
);
IS_DEV &&
console.log("Fetched accounts!", {
accounts,
usingDeltaRequest,
serverKnowledge: response.data.server_knowledge
});
return { accounts, serverKnowledge: response.data.server_knowledge };
}
export function mergeAccountsDataFromDelta(
existingData: Account[],
deltaResponse: Account[]
) {
const accounts = [...existingData];
for (const accountDelta of deltaResponse) {
const accountIdx = accounts.findIndex((a) => a.id === accountDelta.id);
if (accountIdx === -1) {
accounts.push(accountDelta); // new account
} else if (accountDelta.deleted) {
accounts.splice(accountIdx, 1); // deleted account
} else {
accounts.splice(accountIdx, 1, accountDelta); // update existing account
}
}
return accounts;
}
export const payeeCollator = Intl.Collator();
/** Fetch payees for this budget from the YNAB API */
export async function fetchPayeesForBudget(
ynabAPI: api,
selectedBudgetId: string,
cache?: {
data?: {
serverKnowledge: number;
payees: CachedPayee[];
};
dataUpdatedAt: number;
}
) {
const usingDeltaRequest = !!cache?.data;
const response = await ynabAPI.payees.getPayees(
selectedBudgetId,
usingDeltaRequest ? cache.data?.serverKnowledge : undefined
);
let payees: CachedPayee[];
if (usingDeltaRequest && cache.data) {
payees = mergePayeesDataFromDelta(cache.data.payees, response.data.payees);
} else {
payees = response.data.payees
.map(formatPayee)
.sort((a, b) => payeeCollator.compare(a.name, b.name));
}
IS_DEV &&
console.log("Fetched payees!", {
payees,
usingDeltaRequest,
serverKnowledge: response.data.server_knowledge
});
return { payees, serverKnowledge: response.data.server_knowledge };
}
export function mergePayeesDataFromDelta(
existingData: CachedPayee[],
deltaResponse: Payee[]
) {
const payees = [...existingData];
for (const payeeDelta of deltaResponse) {
const payeeIdx = payees.findIndex((p) => p.id === payeeDelta.id);
if (payeeIdx === -1) {
const sortedIdx = findSortedIndex(payees, payeeDelta, (a, b) =>
payeeCollator.compare(a.name, b.name)
);
payees.splice(sortedIdx, 0, formatPayee(payeeDelta)); // new payee
} else if (payeeDelta.deleted) {
payees.splice(payeeIdx, 1); // deleted payee
} else {
payees.splice(payeeIdx, 1, formatPayee(payeeDelta)); // update existing payee
}
}
return payees;
}
export function formatPayee(payee: Payee): CachedPayee {
return {
id: payee.id,
name: payee.name,
...(payee.transfer_account_id && { transferId: payee.transfer_account_id })
};
}
function findSortedIndex<T>(array: T[], value: T, compare: (x: T, y: T) => number) {
let low = 0;
let high = array.length;
while (low < high) {
const mid = (low + high) >>> 1;
if (compare(array[mid], value) < 0) low = mid + 1;
else high = mid;
}
return low;
}
/** Check for new unapproved transactions in this budget */
export async function checkUnapprovedTxsForBudget(ynabAPI: api, budgetId: string) {
const {
data: { transactions }
} = await ynabAPI.transactions.getTransactions(
budgetId,
getNDaysAgoISO(14), // fetch unapproved transactions from up to 2 weeks ago
GetTransactionsTypeEnum.Unapproved
);
IS_DEV && console.log("Checked for new imports!", transactions);
return transactions;
}
function getNDaysAgoISO(days: number) {
const date = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return date.toISOString().substring(0, 10);
}