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/structure/interface_app_data.dart';
6 : import 'package:fints/fints.dart';
7 : import 'package:uuid/uuid.dart';
8 :
9 : typedef FinTsImportResult = IntegrationImportResult;
10 :
11 : class FinTsImporter {
12 : final bool Function(String uuid) exists;
13 : final void Function(InterfaceAppData item, String uuid) add;
14 :
15 1 : const FinTsImporter({required this.exists, required this.add});
16 :
17 1 : FinTsImportResult run({
18 : required String accountKey,
19 : required List<Transaction> transactions,
20 : required String account,
21 : required String category,
22 : }) {
23 : var added = 0;
24 : var skipped = 0;
25 : var pending = 0;
26 1 : final occurrences = <String, int>{};
27 2 : for (final transaction in transactions) {
28 1 : if (transaction.isPending) {
29 1 : pending++;
30 : continue;
31 : }
32 1 : final fingerprint = _fingerprint(accountKey, transaction);
33 2 : final index = occurrences.update(fingerprint, (value) => value + 1, ifAbsent: () => 0);
34 3 : final uuid = const Uuid().v5(Namespace.url.value, 'fints:$fingerprint#$index');
35 2 : if (exists(uuid)) {
36 1 : skipped++;
37 : continue;
38 : }
39 3 : add(convert(transaction, account: account, category: category), uuid);
40 1 : added++;
41 : }
42 : return (added: added, skipped: skipped, pending: pending);
43 : }
44 :
45 1 : static InterfaceAppData convert(Transaction transaction, {required String account, required String category}) =>
46 1 : IntegrationRecord.toAppData(
47 2 : amount: transaction.amount.value,
48 2 : currency: transaction.amount.currency,
49 2 : date: transaction.bookingDate ?? transaction.valueDate,
50 1 : title: getTitle(transaction),
51 : account: account,
52 : category: category,
53 : );
54 :
55 2 : static String getTitle(Transaction transaction) {
56 6 : final parts = [transaction.counterpartyName, transaction.purpose]
57 6 : .map((e) => e?.trim() ?? '')
58 6 : .where((e) => e.isNotEmpty)
59 2 : .toList();
60 4 : return parts.isNotEmpty ? parts.join(' — ') : (transaction.bookingText?.trim() ?? '');
61 : }
62 :
63 1 : static String _fingerprint(String accountKey, Transaction transaction) {
64 1 : final reference = transaction.endToEndId ?? transaction.bankReference ?? transaction.customerReference ?? '';
65 1 : return [
66 : accountKey,
67 3 : transaction.valueDate.toIso8601String().substring(0, 10),
68 2 : transaction.amount.minorUnits,
69 2 : transaction.amount.scale,
70 2 : transaction.amount.currency,
71 1 : reference == 'NOTPROVIDED' ? '' : reference,
72 1 : transaction.counterpartyIban ?? '',
73 1 : transaction.purpose ?? '',
74 1 : ].join('|');
75 : }
76 : }
|