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/herald/app_design.dart';
5 : import 'package:app_finance/_classes/herald/app_locale.dart';
6 : import 'package:app_finance/_classes/integration/up/up_client.dart';
7 : import 'package:app_finance/_classes/integration/up/up_importer.dart';
8 : import 'package:app_finance/_classes/integration/up/up_settings.dart';
9 : import 'package:app_finance/_classes/storage/app_data.dart';
10 : import 'package:app_finance/_classes/storage/app_preferences.dart';
11 : import 'package:app_finance/_classes/storage/transaction_log.dart';
12 : import 'package:app_finance/_configs/theme_helper.dart';
13 : import 'package:app_finance/_ext/build_context_ext.dart';
14 : import 'package:app_finance/design/button/full_sized_button_widget.dart';
15 : import 'package:app_finance/design/generic/loading_widget.dart';
16 : import 'package:app_finance/design/wrapper/input_wrapper.dart';
17 : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
18 : import 'package:material_ui/material_ui.dart';
19 : import 'package:provider/provider.dart';
20 :
21 : class UpBankAccount extends IntegrationTarget {
22 : final UpAccount account;
23 :
24 1 : UpBankAccount(this.account, {super.appAccount, super.category, required super.from});
25 : }
26 :
27 : class UpWidget extends StatefulWidget {
28 : final UpClient? client;
29 :
30 3 : const UpWidget({super.key, this.client});
31 :
32 1 : @override
33 1 : UpWidgetState createState() => UpWidgetState();
34 : }
35 :
36 : class UpWidgetState extends State<UpWidget> {
37 : // Held transactions keep their date when settled: a repeated import looks back for them
38 : static const settlementDelay = Duration(days: 10);
39 :
40 : late final UpClient client;
41 : late final UpSettings settings;
42 : final token = TextEditingController();
43 : String? access;
44 : List<UpBankAccount> accounts = [];
45 : bool isLoading = false;
46 : String? error;
47 : String? notice;
48 :
49 1 : @override
50 : void initState() {
51 1 : super.initState();
52 4 : client = widget.client ?? UpClient();
53 2 : settings = UpSettings.load();
54 2 : access = UpSettings.loadToken();
55 : }
56 :
57 1 : @override
58 : void dispose() {
59 2 : token.dispose();
60 2 : if (widget.client == null) {
61 2 : client.close();
62 : }
63 1 : super.dispose();
64 : }
65 :
66 1 : Future<void> _run(Future<void> Function() callback) async {
67 2 : setState(() {
68 1 : isLoading = true;
69 1 : error = null;
70 1 : notice = null;
71 : });
72 : try {
73 1 : await callback();
74 1 : } on UpException catch (e) {
75 2 : error = e.message;
76 : } catch (e) {
77 0 : error = e.toString();
78 : } finally {
79 1 : if (mounted) {
80 3 : setState(() => isLoading = false);
81 : }
82 : }
83 : }
84 :
85 3 : Future<void> connect() => _run(() async {
86 4 : final value = access ?? token.text.trim();
87 1 : if (value.isEmpty) {
88 0 : throw UpException(AppLocale.labels.upToken);
89 : }
90 2 : await client.ping(value);
91 2 : final items = await client.getAccounts(value);
92 : // Stored only after Up has accepted it
93 1 : if (access == null) {
94 1 : await UpSettings.saveToken(value);
95 2 : token.clear();
96 1 : access = value;
97 : }
98 1 : final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
99 2 : final monthAgo = DateTime.now().subtract(const Duration(days: 30));
100 1 : accounts = items
101 3 : .map((account) => UpBankAccount(
102 : account,
103 4 : appAccount: settings.links[account.id],
104 : category: defaultBudget,
105 4 : from: settings.imported[account.id] ?? monthAgo,
106 : ))
107 1 : .toList();
108 2 : if (accounts.isEmpty) {
109 0 : notice = AppLocale.labels.integrationNoAccounts;
110 : }
111 : });
112 :
113 0 : Future<void> disconnect() => _run(() async => accounts = []);
114 :
115 3 : Future<void> forget() => _run(() async {
116 1 : await UpSettings.clearToken();
117 1 : access = null;
118 2 : accounts = [];
119 : });
120 :
121 3 : Future<void> importTransactions(UpBankAccount item) => _run(() async {
122 1 : final current = access;
123 : if (current == null) {
124 : return;
125 : }
126 2 : if (item.appAccount == null || item.category == null) {
127 0 : throw UpException(AppLocale.labels.integrationSelectTarget);
128 : }
129 2 : final state = Provider.of<AppData>(context, listen: false);
130 2 : final id = item.account.id;
131 3 : final last = settings.imported[id];
132 1 : final from = last != null && !item.from.isAfter(last) ? item.from.subtract(settlementDelay) : item.from;
133 2 : final transactions = await client.getTransactions(current, id, since: from);
134 1 : final importer = UpImporter(
135 2 : exists: (uuid) => state.getByUuid(uuid) != null,
136 3 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
137 : );
138 1 : final summary = importer.run(
139 1 : source: item.account,
140 : transactions: transactions,
141 1 : account: item.appAccount!,
142 1 : category: item.category!,
143 : // Other Up accounts linked to the application's accounts: transfers between them
144 1 : links: {
145 2 : ...settings.links,
146 1 : for (final other in accounts)
147 5 : if (other.appAccount != null) other.account.id: other.appAccount!,
148 : },
149 1 : prediction: state.prediction,
150 : );
151 1 : await state.restate();
152 1 : final today = DateTime.now();
153 4 : settings.links[id] = item.appAccount!;
154 7 : settings.imported[id] = DateTime(today.year, today.month, today.day);
155 2 : await settings.save();
156 3 : notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
157 : });
158 :
159 1 : Widget buildAccount(BuildContext context, UpBankAccount item, AppData state) {
160 2 : final balance = item.account.balance;
161 1 : return IntegrationAccountCard(
162 2 : title: item.account.name,
163 3 : subtitle: '${AppLocale.labels.balance}: ${balance.value} ${balance.currency}',
164 : target: item,
165 : state: state,
166 1 : isDisabled: isLoading,
167 0 : onChanged: () => setState(() {}),
168 2 : onImport: () => importTransactions(item),
169 : );
170 : }
171 :
172 1 : @override
173 : Widget build(BuildContext context) {
174 1 : final textTheme = context.textTheme;
175 1 : final colorScheme = context.colorScheme;
176 2 : return Consumer<AppData>(builder: (context, state, _) {
177 1 : return Column(
178 1 : crossAxisAlignment: AppDesign.getAlignment(),
179 1 : children: [
180 4 : Text(AppLocale.labels.upDescription, style: textTheme.bodyMedium),
181 : ThemeHelper.hIndent2x,
182 2 : if (access == null) ...[
183 4 : Text(AppLocale.labels.upTokenSteps, key: const ValueKey('up_steps'), style: textTheme.bodyMedium),
184 : ThemeHelper.hIndent2x,
185 1 : InputWrapper.text(
186 2 : title: AppLocale.labels.upToken,
187 2 : tooltip: AppLocale.labels.upTokenTooltip,
188 1 : controller: token,
189 : isRequired: true,
190 : ),
191 : ],
192 1 : ThemeHelper.hIndent2x,
193 2 : if (error != null) ...[
194 5 : Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
195 : ThemeHelper.hIndent,
196 : ],
197 2 : if (notice != null) ...[
198 3 : Text(notice!, style: textTheme.bodyLarge),
199 : ThemeHelper.hIndent,
200 : ],
201 1 : if (isLoading)
202 0 : const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
203 1 : else ...[
204 2 : accounts.isEmpty
205 1 : ? FullSizedButtonWidget(
206 : key: const ValueKey('up_connect'),
207 : icon: Icons.login,
208 1 : onPressed: connect,
209 2 : title: AppLocale.labels.integrationConnect,
210 : )
211 1 : : FullSizedButtonWidget(
212 : key: const ValueKey('up_disconnect'),
213 : icon: Icons.logout,
214 1 : onPressed: disconnect,
215 2 : title: AppLocale.labels.integrationDisconnect,
216 : ),
217 1 : if (access != null)
218 1 : Align(
219 : alignment: Alignment.centerRight,
220 1 : child: TextButton.icon(
221 : key: const ValueKey('up_forget'),
222 : icon: const Icon(Icons.link_off),
223 1 : onPressed: forget,
224 3 : label: Text(AppLocale.labels.integrationForget),
225 : ),
226 : ),
227 : ],
228 2 : for (final item in accounts) buildAccount(context, item, state),
229 : ],
230 : );
231 : });
232 : }
233 : }
|