-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathynab5.ts
More file actions
1193 lines (1061 loc) · 34.5 KB
/
Copy pathynab5.ts
File metadata and controls
1193 lines (1061 loc) · 34.5 KB
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-strict-ignore
import { v4 as uuidv4 } from 'uuid';
import { logger } from '#platform/server/log';
import { send } from '#server/main-app';
import { ruleModel } from '#server/transactions/transaction-rules';
import * as monthUtils from '#shared/months';
import { q } from '#shared/query';
import { groupBy, sortByKey } from '#shared/util';
import type { RecurConfig, RecurPattern, RuleEntity } from '#types/models';
import type {
Budget,
Payee,
ScheduledSubtransaction,
ScheduledTransaction,
Subtransaction,
Transaction,
} from './ynab5-types';
const MAX_RETRY = 20;
function normalizeError(e: unknown): string {
if (e instanceof Error) {
return e.message;
}
if (typeof e === 'string') {
return e;
}
return String(e);
}
type FlaggedTransaction = Pick<
Transaction | ScheduledTransaction,
'flag_name' | 'flag_color' | 'deleted'
>;
const flagColorMap: Record<string, string | null> = {
red: '#FF6666',
orange: '#F57C00',
yellow: '#FBC02D',
green: '#689F38',
blue: '#1976D2',
purple: '#512DA8',
null: null,
'': null,
};
function equalsIgnoreCase(stringa: string, stringb: string): boolean {
return (
stringa.localeCompare(stringb, undefined, {
sensitivity: 'base',
}) === 0
);
}
function findByNameIgnoreCase<T extends { name: string }>(
categories: T[],
name: string,
) {
return categories.find(cat => equalsIgnoreCase(cat.name, name));
}
function findIdByName<T extends { id: string; name: string }>(
categories: Array<T>,
name: string,
) {
return findByNameIgnoreCase<T>(categories, name)?.id;
}
function amountFromYnab(amount: number) {
// YNAB multiplies amount by 1000 and Actual by 100
// so, this function divides by 10
return Math.round(amount / 10);
}
function getDayOfMonth(date: string) {
return monthUtils.parseDate(date).getDate();
}
function getYnabMonthlyPatterns(dateFirst: string): RecurPattern[] {
if (getDayOfMonth(dateFirst) !== 31) {
return [];
}
return [
{
type: 'day',
value: -1,
},
];
}
// Use Actual's "specific days" to avoid drifting every 15 days.
// This approximates YNAB's "second occurrence is 15 days after the chosen day"
// by locking to two day-of-month values.
function getYnabTwiceMonthlyPatterns(dateFirst: string): RecurPattern[] {
const firstDay = getDayOfMonth(dateFirst);
// Compute the second occurrence as 15 calendar days after the first.
const secondDay = getDayOfMonth(monthUtils.addDays(dateFirst, 15));
return [
{ type: 'day', value: firstDay === 31 ? -1 : firstDay },
{ type: 'day', value: secondDay === 31 ? -1 : secondDay },
];
}
function mapYnabFrequency(
frequency: string,
dateFirst: string,
): {
frequency: RecurConfig['frequency'];
interval?: number;
patterns?: RecurPattern[];
} {
switch (frequency) {
case 'daily':
return { frequency: 'daily' };
case 'weekly':
return { frequency: 'weekly' };
case 'monthly':
return {
frequency: 'monthly',
patterns: getYnabMonthlyPatterns(dateFirst),
};
case 'yearly':
return { frequency: 'yearly' };
case 'everyOtherWeek':
return { frequency: 'weekly', interval: 2 };
case 'every4Weeks':
return { frequency: 'weekly', interval: 4 };
case 'everyOtherMonth':
return {
frequency: 'monthly',
interval: 2,
patterns: getYnabMonthlyPatterns(dateFirst),
};
case 'every3Months':
return {
frequency: 'monthly',
interval: 3,
patterns: getYnabMonthlyPatterns(dateFirst),
};
case 'every4Months':
return {
frequency: 'monthly',
interval: 4,
patterns: getYnabMonthlyPatterns(dateFirst),
};
case 'everyOtherYear':
return { frequency: 'yearly', interval: 2 };
case 'twiceAMonth': {
return {
frequency: 'monthly',
patterns: getYnabTwiceMonthlyPatterns(dateFirst),
};
}
case 'twiceAYear': {
return {
frequency: 'monthly',
interval: 6,
patterns: getYnabMonthlyPatterns(dateFirst),
};
}
default:
throw new Error(`Unsupported scheduled frequency: ${frequency}`);
}
}
function getScheduleDateValue(
scheduled: ScheduledTransaction,
): RecurConfig | string {
const dateFirst = scheduled.date_first;
const frequency = scheduled.frequency;
if (frequency === 'never') {
return scheduled.date_next;
}
const mapped = mapYnabFrequency(frequency, dateFirst);
return {
frequency: mapped.frequency,
interval: mapped.interval,
patterns: mapped.patterns,
skipWeekend: false,
weekendSolveMode: 'after',
endMode: 'never',
start: dateFirst,
};
}
function getFlaggedTransactions(data: Budget): FlaggedTransaction[] {
return [...data.transactions, ...data.scheduled_transactions];
}
function getFlagTag(
transaction: FlaggedTransaction,
flagNameConflicts: Set<string>,
): string {
const tagName = transaction.flag_name?.trim() ?? '';
const colorKey = transaction.flag_color?.trim() ?? '';
if (tagName.length === 0) {
return colorKey.length > 0 ? `#${colorKey}` : '';
}
if (flagNameConflicts.has(tagName)) {
return `#${tagName}-${colorKey}`;
}
return `#${tagName}`;
}
function getFlagNameConflicts(data: Budget): Set<string> {
const colorsByName = new Map<string, Set<string>>();
const flaggedTransactions = getFlaggedTransactions(data);
for (const transaction of flaggedTransactions) {
if (transaction.deleted) {
continue;
}
const tagName = transaction.flag_name?.trim() ?? '';
const colorKey = transaction.flag_color?.trim() ?? '';
if (tagName.length === 0 || !flagColorMap[colorKey]) {
continue;
}
let colors = colorsByName.get(tagName);
if (!colors) {
colors = new Set();
colorsByName.set(tagName, colors);
}
colors.add(colorKey);
}
const conflicts = new Set<string>();
colorsByName.forEach((colors, name) => {
if (colors.size > 1) {
conflicts.add(name);
}
});
return conflicts;
}
function buildTransactionNotes(
transaction: Transaction | ScheduledTransaction,
flagNameConflicts: Set<string>,
): string | null {
const normalizedMemo = transaction.memo?.trim() ?? '';
const tagText = getFlagTag(transaction, flagNameConflicts);
const notes = `${normalizedMemo} ${tagText}`.trim();
return notes.length > 0 ? notes : null;
}
function buildRuleUpdate(
rule: RuleEntity,
actions: RuleEntity['actions'],
): RuleEntity {
return {
id: rule.id,
stage: rule.stage ?? null,
conditionsOp: rule.conditionsOp ?? 'and',
conditions: rule.conditions,
actions,
};
}
function importAccounts(data: Budget, entityIdMap: Map<string, string>) {
return Promise.all(
data.accounts.map(async account => {
if (!account.deleted) {
const id = await send('api/account-create', {
account: {
name: account.name,
offbudget: account.on_budget ? false : true,
closed: account.closed,
},
});
entityIdMap.set(account.id, id);
}
}),
);
}
async function importCategories(
data: Budget,
entityIdMap: Map<string, string>,
) {
// Hidden categories are put in its own group by YNAB,
// so it's already handled.
const categories = await send('api/categories-get');
const incomeCatId = findIdByName(categories, 'Income');
const ynabIncomeCategories = ['To be Budgeted', 'Inflow: Ready to Assign'];
function checkSpecialCat(cat) {
if (
cat.category_group_id ===
findIdByName(data.category_groups, 'Internal Master Category')
) {
if (
ynabIncomeCategories.some(ynabIncomeCategory =>
equalsIgnoreCase(cat.name, ynabIncomeCategory),
)
) {
return 'income';
} else {
return 'internal';
}
} else if (
cat.category_group_id ===
findIdByName(data.category_groups, 'Credit Card Payments')
) {
return 'creditCard';
} else if (
cat.category_group_id === findIdByName(data.category_groups, 'Income')
) {
return 'income';
}
}
// Can't be done in parallel to have
// correct sort order.
async function createCategoryGroupWithUniqueName(params: {
name: string;
is_income: boolean;
hidden: boolean;
}) {
const baseName = params.hidden ? `${params.name} (hidden)` : params.name;
let count = 0;
while (true) {
const name = count === 0 ? baseName : `${baseName} (${count})`;
try {
const id = await send('api/category-group-create', {
group: { ...params, name },
});
return { id, name };
} catch (e) {
if (count >= MAX_RETRY) {
const errorMsg = normalizeError(e);
throw Error('Unable to create category group: ' + errorMsg);
}
count += 1;
}
}
}
async function createCategoryWithUniqueName(params: {
name: string;
group_id: string;
hidden: boolean;
}) {
const baseName = params.hidden ? `${params.name} (hidden)` : params.name;
let count = 0;
while (true) {
const name = count === 0 ? baseName : `${baseName} (${count})`;
try {
const id = await send('api/category-create', {
category: { ...params, name },
});
return { id, name };
} catch (e) {
if (count >= MAX_RETRY) {
const errorMsg = normalizeError(e);
throw Error('Unable to create category: ' + errorMsg);
}
count += 1;
}
}
}
for (const group of data.category_groups) {
if (!group.deleted) {
let groupId: string;
// Ignores internal category and credit cards
if (
!equalsIgnoreCase(group.name, 'Internal Master Category') &&
!equalsIgnoreCase(group.name, 'Credit Card Payments') &&
!equalsIgnoreCase(group.name, 'Hidden Categories') &&
!equalsIgnoreCase(group.name, 'Income')
) {
const createdGroup = await createCategoryGroupWithUniqueName({
name: group.name,
is_income: false,
hidden: group.hidden,
});
groupId = createdGroup.id;
entityIdMap.set(group.id, groupId);
if (group.note) {
void send('notes-save', {
id: groupId,
note: group.note,
});
}
}
if (equalsIgnoreCase(group.name, 'Income')) {
groupId = incomeCatId;
entityIdMap.set(group.id, groupId);
}
const cats = data.categories.filter(
cat => cat.category_group_id === group.id,
);
for (const cat of cats.reverse()) {
if (!cat.deleted) {
// 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
const id = incomeCatId;
entityIdMap.set(cat.id, id);
break;
}
case 'creditCard': // ignores it
case 'internal': // uncategorized is ignored too, handled by actual
break;
default: {
if (!groupId) {
break;
}
const createdCategory = await createCategoryWithUniqueName({
name: cat.name,
group_id: groupId,
hidden: cat.hidden,
});
entityIdMap.set(cat.id, createdCategory.id);
if (cat.note) {
void send('notes-save', {
id: createdCategory.id,
note: cat.note,
});
}
}
}
}
}
}
}
}
export function importPayees(data: Budget, entityIdMap: Map<string, string>) {
return Promise.all(
data.payees.map(async payee => {
if (!payee.deleted && !payee.transfer_account_id) {
const id = await send('api/payee-create', {
payee: { name: payee.name },
});
entityIdMap.set(payee.id, id);
}
}),
);
}
async function importPayeeLocations(
data: Budget,
entityIdMap: Map<string, string>,
) {
// If no payee locations data provided, skip import
if (!data?.payee_locations) {
logger.log('No payee locations data provided, skipping...');
return;
}
const payeeLocations = data.payee_locations;
for (const location of payeeLocations) {
// Skip deleted locations
if (location.deleted) {
continue;
}
// Get the mapped payee ID
const actualPayeeId = entityIdMap.get(location.payee_id);
if (!actualPayeeId) {
logger.log(`Skipping location for unknown payee: ${location.payee_id}`);
continue;
}
// Validate latitude/longitude before attempting import
const latitude = parseFloat(location.latitude);
const longitude = parseFloat(location.longitude);
if (isNaN(latitude) || isNaN(longitude)) {
logger.log(
`Skipping location with invalid coordinates for payee ${actualPayeeId}: lat=${location.latitude}, lng=${location.longitude}`,
);
continue;
}
try {
// Create the payee location in Actual
await send('payee-location-create', {
payeeId: actualPayeeId,
latitude,
longitude,
});
} catch (error) {
const errorMessage =
error instanceof Error
? error.message
: String(error ?? 'Unknown error');
logger.error(
`Failed to import location for payee ${actualPayeeId} at (${latitude}, ${longitude}): ${errorMessage}`,
);
}
}
}
async function importFlagsAsTags(
data: Budget,
flagNameConflicts: Set<string>,
): Promise<void> {
const tagsToCreate = new Map<string, string | null>();
const flaggedTransactions = getFlaggedTransactions(data);
for (const transaction of flaggedTransactions) {
if (transaction.deleted) {
continue;
}
const tagName = transaction.flag_name?.trim() ?? '';
const colorKey = transaction.flag_color?.trim() ?? '';
const tagColor = flagColorMap[colorKey] ?? null;
if (!tagColor) {
continue;
}
if (tagName.length === 0) {
if (!tagsToCreate.has(colorKey)) {
tagsToCreate.set(colorKey, tagColor);
}
continue;
}
const mappedName = flagNameConflicts.has(tagName)
? `${tagName}-${colorKey}`
: tagName;
if (!tagsToCreate.has(mappedName)) {
tagsToCreate.set(mappedName, tagColor);
}
}
if (tagsToCreate.size === 0) {
return;
}
await Promise.all(
[...tagsToCreate.entries()].map(async ([tag, color]) => {
await send('tags-create', {
tag,
color,
description: 'Imported from YNAB',
});
}),
);
}
export async function importTransactions(
data: Budget,
entityIdMap: Map<string, string>,
flagNameConflicts: Set<string>,
) {
const payees = await send('api/payees-get');
const categories = await send('api/categories-get');
const incomeCatId = findIdByName(categories, 'Income');
const startingBalanceCatId = findIdByName(categories, 'Starting Balances'); //better way to do it?
const startingPayeeYNAB = findIdByName(data.payees, 'Starting Balance');
const transactionsGrouped = groupBy(data.transactions, 'account_id');
const subtransactionsGrouped = groupBy(
data.subtransactions,
'transaction_id',
);
const payeesByTransferAcct = payees
.filter(payee => payee?.transfer_acct)
.map(payee => [payee.transfer_acct, payee] as [string, Payee]);
const payeeTransferAcctHashMap = new Map<string, Payee>(payeesByTransferAcct);
const orphanTransferMap = new Map<string, Transaction[]>();
const orphanSubtransfer = [] as Subtransaction[];
const orphanSubtransferTrxId = [] as string[];
const orphanSubtransferAcctIdByTrxIdMap = new Map<string, string>();
const orphanSubtransferDateByTrxIdMap = new Map<string, string>();
// Go ahead and generate ids for all of the transactions so we can
// reliably resolve transfers
// Also identify orphan transfer transactions and subtransactions.
for (const transaction of data.subtransactions) {
entityIdMap.set(transaction.id, uuidv4());
if (transaction.transfer_account_id) {
orphanSubtransfer.push(transaction);
orphanSubtransferTrxId.push(transaction.transaction_id);
}
}
for (const transaction of data.transactions) {
entityIdMap.set(transaction.id, uuidv4());
if (
transaction.transfer_account_id &&
!transaction.transfer_transaction_id
) {
const key =
transaction.account_id + '#' + transaction.transfer_account_id;
if (!orphanTransferMap.has(key)) {
orphanTransferMap.set(key, [transaction]);
} else {
orphanTransferMap.get(key).push(transaction);
}
}
if (orphanSubtransferTrxId.includes(transaction.id)) {
orphanSubtransferAcctIdByTrxIdMap.set(
transaction.id,
transaction.account_id,
);
orphanSubtransferDateByTrxIdMap.set(transaction.id, transaction.date);
}
}
// Compute link between subtransaction transfers and orphaned transaction
// transfers. The goal is to match each transfer subtransaction to the related
// transfer transaction according to the accounts, date, amount and memo.
const orphanSubtransferMap = orphanSubtransfer.reduce(
(map, subtransaction) => {
const key =
subtransaction.transfer_account_id +
'#' +
orphanSubtransferAcctIdByTrxIdMap.get(subtransaction.transaction_id);
if (!map.has(key)) {
map.set(key, [subtransaction]);
} else {
map.get(key).push(subtransaction);
}
return map;
},
new Map<string, Subtransaction[]>(),
);
// The comparator will be used to order transfer transactions and their
// corresponding tranfer subtransaction in two aligned list. Hopefully
// for every list index in the transactions list, the related subtransaction
// will be at the same index.
function orphanTransferComparator(
a: Transaction | Subtransaction,
b: Transaction | Subtransaction,
) {
// a and b can be a Transaction (having a date attribute) or a
// Subtransaction (missing that date attribute)
const date_a =
'date' in a
? a.date
: orphanSubtransferDateByTrxIdMap.get(a.transaction_id);
const date_b =
'date' in b
? b.date
: orphanSubtransferDateByTrxIdMap.get(b.transaction_id);
// A transaction and the related subtransaction have inverted amounts.
// To have those in the same order, the subtransaction has to be reversed
// to have the same amount.
const amount_a = 'date' in a ? a.amount : -a.amount;
const amount_b = 'date' in b ? b.amount : -b.amount;
// Transaction are ordered first by date, then by amount, and lastly by memo
if (date_a > date_b) return 1;
if (date_a < date_b) return -1;
if (amount_a > amount_b) return 1;
if (amount_a < amount_b) return -1;
if (a.memo > b.memo) return 1;
if (a.memo < b.memo) return -1;
return 0;
}
const orphanTrxIdSubtrxIdMap = new Map<string, string>();
orphanTransferMap.forEach((transactions, key) => {
const subtransactions = orphanSubtransferMap.get(key);
if (subtransactions) {
transactions.sort(orphanTransferComparator);
subtransactions.sort(orphanTransferComparator);
// Iterate on the two sorted lists transactions and subtransactions and
// find matching data to identify the related transaction ids.
let transactionIdx = 0;
let subtransactionIdx = 0;
do {
switch (
orphanTransferComparator(
transactions[transactionIdx],
subtransactions[subtransactionIdx],
)
) {
case 0:
// The current list indexes are matching: the transaction and
// subtransaction are related (same date, amount and memo)
orphanTrxIdSubtrxIdMap.set(
transactions[transactionIdx].id,
entityIdMap.get(subtransactions[subtransactionIdx].id),
);
orphanTrxIdSubtrxIdMap.set(
subtransactions[subtransactionIdx].id,
entityIdMap.get(transactions[transactionIdx].id),
);
transactionIdx++;
subtransactionIdx++;
break;
case -1:
// The current list indexes are not matching:
// The current transaction is "smaller" than the current subtransaction
// (earlier date, smaller amount, memo value sorted before)
// So we advance to the next transaction and see if it match with
// the current subtransaction
transactionIdx++;
break;
case 1:
// Inverse of the previous case:
// The current subtransaction is "smaller" than the current transaction
// So we advance to the next subtransaction
subtransactionIdx++;
break;
default:
throw new Error(`Unrecognized orphan transfer comparator result`);
}
} while (
transactionIdx < transactions.length &&
subtransactionIdx < subtransactions.length
);
}
});
await Promise.all(
[...transactionsGrouped.keys()].map(async accountId => {
const transactions = transactionsGrouped.get(accountId);
const toImport = transactions
.map(transaction => {
if (transaction.deleted) {
return null;
}
const subtransactions = subtransactionsGrouped.get(transaction.id);
// Add transaction
const 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),
reconciled: transaction.cleared === 'reconciled',
notes: buildTransactionNotes(transaction, flagNameConflicts),
imported_id: transaction.import_id || null,
transfer_id:
entityIdMap.get(transaction.transfer_transaction_id) ||
orphanTrxIdSubtrxIdMap.get(transaction.id) ||
null,
subtransactions: subtransactions
? subtransactions.map(subtrans => {
return {
id: entityIdMap.get(subtrans.id),
amount: amountFromYnab(subtrans.amount),
category: entityIdMap.get(subtrans.category_id) || null,
notes: subtrans.memo,
transfer_id:
orphanTrxIdSubtrxIdMap.get(subtrans.id) || null,
payee: null,
imported_payee: null,
};
})
: null,
payee: null,
imported_payee: null,
};
// Handle transactions and subtransactions payee
function transactionPayeeUpdate(
trx: Transaction | Subtransaction,
newTrx,
fallbackPayeeId?: string | null,
) {
if (trx.transfer_account_id) {
const mappedTransferAccountId = entityIdMap.get(
trx.transfer_account_id,
);
newTrx.payee = payeeTransferAcctHashMap.get(
mappedTransferAccountId,
)?.id;
} else if (trx.payee_id) {
newTrx.payee = entityIdMap.get(trx.payee_id);
newTrx.imported_payee = data.payees.find(
p => !p.deleted && p.id === trx.payee_id,
)?.name;
} else if (fallbackPayeeId) {
newTrx.payee = fallbackPayeeId;
}
}
transactionPayeeUpdate(transaction, newTransaction);
if (newTransaction.subtransactions) {
subtransactions.forEach(subtrans => {
const newSubtransaction = newTransaction.subtransactions.find(
newSubtrans => newSubtrans.id === entityIdMap.get(subtrans.id),
);
transactionPayeeUpdate(
subtrans,
newSubtransaction,
newTransaction.payee,
);
});
}
// 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 send('api/transactions-add', {
accountId: entityIdMap.get(accountId),
transactions: toImport,
learnCategories: true,
runTransfers: false,
});
}),
);
}
async function importScheduledTransactions(
data: Budget,
entityIdMap: Map<string, string>,
flagNameConflicts: Set<string>,
) {
const scheduledTransactions = data.scheduled_transactions;
const scheduledSubtransactionsGrouped = groupBy(
data.scheduled_subtransactions,
'scheduled_transaction_id',
);
if (scheduledTransactions.length === 0) {
return;
}
const payees = await send('api/payees-get');
const payeesByTransferAcct = payees
.filter(payee => payee?.transfer_acct)
.map(payee => [payee.transfer_acct, payee] as [string, Payee]);
const payeeTransferAcctHashMap = new Map<string, Payee>(payeesByTransferAcct);
const scheduleCategoryMap = new Map<string, string>();
const scheduleSplitsMap = new Map<string, ScheduledSubtransaction[]>();
const schedulePayeeMap = new Map<string, string>();
async function createScheduleWithUniqueName(params: {
name: string;
posts_transaction: boolean;
payee: string;
account: string;
amount: number;
amountOp: 'is';
date: RecurConfig | string;
}) {
const baseName = params.name;
let count = 1;
while (true) {
try {
return await send('api/schedule-create', {
...params,
name: params.name,
});
} catch (e) {
if (count >= MAX_RETRY) {
const errorMsg = normalizeError(e);
throw Error(errorMsg);
}
params.name = `${baseName} (${count})`;
count += 1;
}
}
}
async function getRuleForSchedule(
scheduleId: string,
): Promise<RuleEntity | null> {
const { data: ruleId } = (await send('api/query', {
query: q('schedules')
.filter({ id: scheduleId })
.calculate('rule')
.serialize(),
})) as { data: string | null };
if (!ruleId) {
return null;
}
const { data: ruleData } = (await send('api/query', {
query: q('rules').filter({ id: ruleId }).select('*').serialize(),
})) as { data: Array<Record<string, unknown>> };
const ruleRow = ruleData?.[0];
if (!ruleRow) {
return null;
}
return ruleModel.toJS(ruleRow);
}
for (const scheduled of scheduledTransactions) {
if (scheduled.deleted) {
continue;
}
const mappedAccountId = entityIdMap.get(scheduled.account_id);
if (!mappedAccountId) {
continue;
}
const scheduleDate = getScheduleDateValue(scheduled);
let mappedPayeeId: string | undefined;
if (scheduled.transfer_account_id) {
const mappedTransferAccountId = entityIdMap.get(
scheduled.transfer_account_id,
);
mappedPayeeId = mappedTransferAccountId
? payeeTransferAcctHashMap.get(mappedTransferAccountId)?.id
: undefined;
} else if (scheduled.payee_id) {
mappedPayeeId = entityIdMap.get(scheduled.payee_id);
}
if (!mappedPayeeId) {
continue;
}
const scheduleId = await createScheduleWithUniqueName({
name: scheduled.memo,
posts_transaction: false,
payee: mappedPayeeId,
account: mappedAccountId,
amount: amountFromYnab(scheduled.amount),
amountOp: 'is',
date: scheduleDate,
});
schedulePayeeMap.set(scheduleId, mappedPayeeId);
const scheduleNotes = buildTransactionNotes(scheduled, flagNameConflicts);
if (scheduleNotes) {
const rule = await getRuleForSchedule(scheduleId);
if (rule) {
const actions = rule.actions ? [...rule.actions] : [];
actions.push({
op: 'set',
field: 'notes',
value: scheduleNotes,
});
await send('api/rule-update', {
rule: buildRuleUpdate(rule, actions),
});
}
}
const scheduledSubtransactions =
scheduledSubtransactionsGrouped
.get(scheduled.id)
?.filter(subtransaction => !subtransaction.deleted) || [];
if (scheduledSubtransactions.length > 0) {
scheduleSplitsMap.set(scheduleId, scheduledSubtransactions);
} else if (!scheduled.transfer_account_id && scheduled.category_id) {
const mappedCategoryId = entityIdMap.get(scheduled.category_id);
if (mappedCategoryId) {
scheduleCategoryMap.set(scheduleId, mappedCategoryId);
}
}
}
if (scheduleCategoryMap.size > 0 || scheduleSplitsMap.size > 0) {
for (const [scheduleId, categoryId] of scheduleCategoryMap.entries()) {
const rule = await getRuleForSchedule(scheduleId);
if (!rule) {
continue;
}
const actions = rule.actions ? [...rule.actions] : [];