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/up/up_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:app_finance/_classes/structure/invoice_app_data.dart';
9 : import 'package:flutter_currency_picker/flutter_currency_picker.dart';
10 : import 'package:uuid/uuid.dart';
11 :
12 : class UpImporter {
13 : final bool Function(String uuid) exists;
14 : final void Function(InterfaceAppData item, String uuid) add;
15 :
16 0 : const UpImporter({required this.exists, required this.add});
17 :
18 0 : static String uuidOf(String transactionId) => const Uuid().v5(Namespace.url.value, 'up:$transactionId');
19 :
20 : // A transfer between Up accounts is listed in both of them (with different ids). When both are linked to the
21 : // application's accounts, it is recorded once, by the receiving one: the sending side is left out. Round Ups
22 : // are listed only in the receiving saver, so they are recorded as transfers as well.
23 : // [links] maps Up account ids to the application's accounts.
24 0 : IntegrationImportResult run({
25 : required UpAccount source,
26 : required List<UpTransaction> transactions,
27 : required String account,
28 : required String category,
29 : Map<String, String> links = const {},
30 : BudgetPrediction? prediction,
31 : }) {
32 : var added = 0;
33 : var skipped = 0;
34 : var pending = 0;
35 0 : for (final transaction in transactions) {
36 0 : if (transaction.held) {
37 0 : pending++;
38 : continue;
39 : }
40 0 : final other = transaction.transferAccount != null ? links[transaction.transferAccount] : null;
41 0 : if (other != null && other != account && transaction.amount.value < 0) {
42 : continue;
43 : }
44 0 : final uuid = uuidOf(transaction.id);
45 0 : if (exists(uuid)) {
46 0 : skipped++;
47 : continue;
48 : }
49 0 : final value = transaction.amount;
50 0 : add(
51 0 : other != null && other != account
52 0 : ? InvoiceAppData(
53 0 : title: transaction.description,
54 : account: account,
55 : accountFrom: other,
56 0 : details: value.value.abs(),
57 0 : currency: CurrencyProvider.find(value.currency),
58 0 : createdAt: transaction.date,
59 0 : updatedAt: transaction.date,
60 : hidden: false,
61 : )
62 0 : : IntegrationRecord.toAppData(
63 : amount: value.value,
64 : currency: value.currency,
65 0 : date: transaction.date,
66 0 : title: transaction.description,
67 : account: account,
68 : category: category,
69 : prediction: prediction,
70 : ),
71 : uuid,
72 : );
73 0 : added++;
74 : }
75 : return (added: added, skipped: skipped, pending: pending);
76 : }
77 : }
|