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/akahu/akahu_client.dart';
5 : import 'package:app_finance/_classes/integration/integration_record.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 AkahuImporter {
11 : final bool Function(String uuid) exists;
12 : final void Function(InterfaceAppData item, String uuid) add;
13 : // Budget category of the application named as the category of Akahu (e.g. "Supermarkets", "Food")
14 : final String? Function(String name)? budgetOf;
15 :
16 0 : const AkahuImporter({required this.exists, required this.add, this.budgetOf});
17 :
18 0 : static String uuidOf(String accountId, String transactionId) =>
19 0 : const Uuid().v5(Namespace.url.value, 'akahu:$accountId:$transactionId');
20 :
21 0 : IntegrationImportResult run({
22 : required AkahuAccount source,
23 : required List<AkahuTransaction> transactions,
24 : required String account,
25 : required String category,
26 : int pending = 0,
27 : BudgetPrediction? prediction,
28 : }) {
29 : var added = 0;
30 : var skipped = 0;
31 0 : for (final transaction in transactions) {
32 0 : final uuid = uuidOf(source.id, transaction.id);
33 0 : if (exists(uuid)) {
34 0 : skipped++;
35 : continue;
36 : }
37 0 : final matched = transaction.categories.map((e) => budgetOf?.call(e)).whereType<String>().firstOrNull;
38 0 : add(
39 0 : IntegrationRecord.toAppData(
40 0 : amount: transaction.amount,
41 0 : currency: source.currency,
42 0 : date: transaction.date,
43 0 : title: transaction.description,
44 : account: account,
45 : category: matched ?? category,
46 : // A matching budget category is preferred to the prediction
47 : prediction: matched == null ? prediction : null,
48 : ),
49 : uuid,
50 : );
51 0 : added++;
52 : }
53 : return (added: added, skipped: skipped, pending: pending);
54 : }
55 : }
|