Line data Source code
1 : // Copyright 2026 The terCAD team. All rights reserved.
2 : // Use of this source code is governed by a CC BY-NC-ND 4.0 license that can be found in the LICENSE file.
3 :
4 : import 'package:app_finance/_classes/integration/integration_record.dart';
5 : import 'package:app_finance/_classes/integration/investec/investec_client.dart';
6 : import 'package:app_finance/_classes/math/budget_prediction.dart';
7 : import 'package:app_finance/_classes/structure/interface_app_data.dart';
8 : import 'package:uuid/uuid.dart';
9 :
10 : class InvestecImporter {
11 : final bool Function(String uuid) exists;
12 : final void Function(InterfaceAppData item, String uuid) add;
13 :
14 0 : const InvestecImporter({required this.exists, required this.add});
15 :
16 : // Without an identifier of the bank, the transaction is recognized by its attributes
17 0 : static String referenceOf(InvestecTransaction transaction) =>
18 0 : transaction.uuid ??
19 0 : [
20 0 : transaction.postingDate?.toIso8601String().substring(0, 10),
21 0 : transaction.transactionDate?.toIso8601String().substring(0, 10),
22 0 : transaction.signedAmount,
23 0 : transaction.description,
24 0 : ].join('|');
25 :
26 0 : IntegrationImportResult run({
27 : required String accountId,
28 : required String currency,
29 : required List<InvestecTransaction> transactions,
30 : required String account,
31 : required String category,
32 : BudgetPrediction? prediction,
33 : }) {
34 : var added = 0;
35 : var skipped = 0;
36 : var pending = 0;
37 : // Equal transactions of the same day (e.g. two coffees) are told apart by their order
38 0 : final occurrences = <String, int>{};
39 0 : for (final transaction in transactions) {
40 0 : final date = transaction.date;
41 0 : if (transaction.pending || date == null) {
42 0 : pending++;
43 : continue;
44 : }
45 0 : final reference = referenceOf(transaction);
46 0 : final index = occurrences.update(reference, (value) => value + 1, ifAbsent: () => 0);
47 0 : final key = transaction.uuid != null ? reference : '$reference#$index';
48 0 : final uuid = const Uuid().v5(Namespace.url.value, 'investec:$accountId:$key');
49 0 : if (exists(uuid)) {
50 0 : skipped++;
51 : continue;
52 : }
53 0 : add(
54 0 : IntegrationRecord.toAppData(
55 0 : amount: transaction.signedAmount,
56 : currency: currency,
57 : date: date,
58 0 : title: transaction.description,
59 : account: account,
60 : category: category,
61 : prediction: prediction,
62 : ),
63 : uuid,
64 : );
65 0 : added++;
66 : }
67 : return (added: added, skipped: skipped, pending: pending);
68 : }
69 : }
|