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