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 1 : const InvestecImporter({required this.exists, required this.add});
15 :
16 : // Without an identifier of the bank, the transaction is recognized by its attributes
17 1 : static String referenceOf(InvestecTransaction transaction) =>
18 1 : transaction.uuid ??
19 1 : [
20 3 : transaction.postingDate?.toIso8601String().substring(0, 10),
21 3 : transaction.transactionDate?.toIso8601String().substring(0, 10),
22 1 : transaction.signedAmount,
23 1 : transaction.description,
24 1 : ].join('|');
25 :
26 1 : 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 1 : final occurrences = <String, int>{};
39 2 : for (final transaction in transactions) {
40 1 : final date = transaction.date;
41 1 : if (transaction.pending || date == null) {
42 1 : pending++;
43 : continue;
44 : }
45 1 : final reference = referenceOf(transaction);
46 4 : final index = occurrences.update(reference, (value) => value + 1, ifAbsent: () => 0);
47 2 : final key = transaction.uuid != null ? reference : '$reference#$index';
48 3 : final uuid = const Uuid().v5(Namespace.url.value, 'investec:$accountId:$key');
49 2 : if (exists(uuid)) {
50 1 : skipped++;
51 : continue;
52 : }
53 2 : add(
54 1 : IntegrationRecord.toAppData(
55 1 : amount: transaction.signedAmount,
56 : currency: currency,
57 : date: date,
58 1 : title: transaction.description,
59 : account: account,
60 : category: category,
61 : prediction: prediction,
62 : ),
63 : uuid,
64 : );
65 1 : added++;
66 : }
67 : return (added: added, skipped: skipped, pending: pending);
68 : }
69 : }
|