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/akahu/akahu_client.dart';
7 : import 'package:app_finance/_classes/integration/akahu/akahu_importer.dart';
8 : import 'package:app_finance/_classes/integration/akahu/akahu_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/_classes/structure/budget_app_data.dart';
13 : import 'package:app_finance/_configs/theme_helper.dart';
14 : import 'package:app_finance/_ext/build_context_ext.dart';
15 : import 'package:app_finance/design/button/full_sized_button_widget.dart';
16 : import 'package:app_finance/design/generic/loading_widget.dart';
17 : import 'package:app_finance/design/wrapper/input_wrapper.dart';
18 : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
19 : import 'package:material_ui/material_ui.dart';
20 : import 'package:provider/provider.dart';
21 :
22 : class AkahuBankAccount extends IntegrationTarget {
23 : final AkahuAccount account;
24 :
25 0 : AkahuBankAccount(this.account, {super.appAccount, super.category, required super.from});
26 : }
27 :
28 : class AkahuWidget extends StatefulWidget {
29 : final AkahuClient? client;
30 :
31 1 : const AkahuWidget({super.key, this.client});
32 :
33 0 : @override
34 0 : AkahuWidgetState createState() => AkahuWidgetState();
35 : }
36 :
37 : class AkahuWidgetState extends State<AkahuWidget> {
38 : // Banks may change the date of a transaction in the days after it is posted: a repeated import looks back for them
39 : static const postingDelay = Duration(days: 10);
40 :
41 : late final AkahuClient client;
42 : late final AkahuSettings settings;
43 : final appToken = TextEditingController();
44 : final userToken = TextEditingController();
45 : AkahuTokens? tokens;
46 : List<AkahuBankAccount> accounts = [];
47 : bool isLoading = false;
48 : String? error;
49 : String? notice;
50 :
51 0 : @override
52 : void initState() {
53 0 : super.initState();
54 0 : client = widget.client ?? AkahuClient();
55 0 : settings = AkahuSettings.load();
56 0 : tokens = AkahuSettings.loadTokens();
57 : }
58 :
59 0 : @override
60 : void dispose() {
61 0 : appToken.dispose();
62 0 : userToken.dispose();
63 0 : if (widget.client == null) {
64 0 : client.close();
65 : }
66 0 : super.dispose();
67 : }
68 :
69 0 : Future<void> _run(Future<void> Function() callback) async {
70 0 : setState(() {
71 0 : isLoading = true;
72 0 : error = null;
73 0 : notice = null;
74 : });
75 : try {
76 0 : await callback();
77 0 : } on AkahuException catch (e) {
78 0 : error = e.message;
79 : } catch (e) {
80 0 : error = e.toString();
81 : } finally {
82 0 : if (mounted) {
83 0 : setState(() => isLoading = false);
84 : }
85 : }
86 : }
87 :
88 0 : Future<void> connect() => _run(() async {
89 0 : var current = tokens;
90 : if (current == null) {
91 0 : final entered = (appToken: appToken.text.trim(), userToken: userToken.text.trim());
92 0 : if (entered.appToken.isEmpty || entered.userToken.isEmpty) {
93 0 : throw AkahuException(AppLocale.labels.akahuIncomplete);
94 : }
95 : current = entered;
96 : }
97 0 : final items = await client.getAccounts(current);
98 : // Stored only after Akahu has accepted them
99 0 : if (tokens == null) {
100 0 : await AkahuSettings.saveTokens(current);
101 0 : tokens = current;
102 0 : appToken.clear();
103 0 : userToken.clear();
104 : }
105 0 : final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
106 0 : final monthAgo = DateTime.now().subtract(const Duration(days: 30));
107 0 : accounts = items
108 0 : .where((account) => account.hasTransactions)
109 0 : .map((account) => AkahuBankAccount(
110 : account,
111 0 : appAccount: settings.links[account.id],
112 : category: defaultBudget,
113 0 : from: settings.imported[account.id] ?? monthAgo,
114 : ))
115 0 : .toList();
116 0 : if (accounts.isEmpty) {
117 0 : notice = AppLocale.labels.integrationNoAccounts;
118 : }
119 : });
120 :
121 0 : Future<void> refresh() => _run(() async {
122 0 : final current = tokens;
123 : if (current == null) {
124 : return;
125 : }
126 0 : await client.refresh(current);
127 0 : notice = AppLocale.labels.akahuRefreshed;
128 : });
129 :
130 0 : Future<void> disconnect() => _run(() async => accounts = []);
131 :
132 0 : Future<void> forget() => _run(() async {
133 0 : await AkahuSettings.clearTokens();
134 0 : tokens = null;
135 0 : accounts = [];
136 : });
137 :
138 0 : String? _budgetOf(AppData state, String name) {
139 0 : final value = name.trim().toLowerCase();
140 : return state
141 0 : .getList(AppDataType.budgets, false)
142 0 : .whereType<BudgetAppData>()
143 0 : .where((e) => e.title.trim().toLowerCase() == value)
144 0 : .firstOrNull
145 0 : ?.uuid;
146 : }
147 :
148 0 : Future<void> importTransactions(AkahuBankAccount item) => _run(() async {
149 0 : final current = tokens;
150 : if (current == null) {
151 : return;
152 : }
153 0 : if (item.appAccount == null || item.category == null) {
154 0 : throw AkahuException(AppLocale.labels.integrationSelectTarget);
155 : }
156 0 : final state = Provider.of<AppData>(context, listen: false);
157 0 : final id = item.account.id;
158 0 : final last = settings.imported[id];
159 0 : final from = last != null && !item.from.isAfter(last) ? item.from.subtract(postingDelay) : item.from;
160 0 : final transactions = await client.getTransactions(current, id, from: from);
161 : var pending = 0;
162 : try {
163 0 : pending = await client.countPending(current, id);
164 0 : } on AkahuException {
165 : // Pending transactions are only reported
166 : }
167 0 : final importer = AkahuImporter(
168 0 : exists: (uuid) => state.getByUuid(uuid) != null,
169 0 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
170 0 : budgetOf: (name) => _budgetOf(state, name),
171 : );
172 0 : final summary = importer.run(
173 0 : source: item.account,
174 : transactions: transactions,
175 0 : account: item.appAccount!,
176 0 : category: item.category!,
177 : pending: pending,
178 0 : prediction: state.prediction,
179 : );
180 0 : await state.restate();
181 0 : final today = DateTime.now();
182 0 : settings.links[id] = item.appAccount!;
183 0 : settings.imported[id] = DateTime(today.year, today.month, today.day);
184 0 : await settings.save();
185 0 : notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
186 : });
187 :
188 0 : Widget buildAccount(BuildContext context, AkahuBankAccount item, AppData state) {
189 0 : final account = item.account;
190 0 : return IntegrationAccountCard(
191 0 : title: account.title,
192 0 : subtitle: account.balance != null ? '${AppLocale.labels.balance}: ${account.balance} ${account.currency}' : null,
193 : target: item,
194 : state: state,
195 0 : isDisabled: isLoading,
196 0 : onChanged: () => setState(() {}),
197 0 : onImport: () => importTransactions(item),
198 0 : children: [
199 0 : if (!account.isActive)
200 0 : Text(
201 0 : AppLocale.labels.akahuInactive,
202 0 : style: context.textTheme.bodyMedium?.copyWith(color: context.colorScheme.error),
203 : ),
204 : ],
205 : );
206 : }
207 :
208 0 : @override
209 : Widget build(BuildContext context) {
210 0 : final textTheme = context.textTheme;
211 0 : final colorScheme = context.colorScheme;
212 0 : return Consumer<AppData>(builder: (context, state, _) {
213 0 : return Column(
214 0 : crossAxisAlignment: AppDesign.getAlignment(),
215 0 : children: [
216 0 : Text(AppLocale.labels.akahuDescription, style: textTheme.bodyMedium),
217 : ThemeHelper.hIndent2x,
218 0 : if (tokens == null) ...[
219 0 : Text(AppLocale.labels.akahuSteps, key: const ValueKey('akahu_steps'), style: textTheme.bodyMedium),
220 : ThemeHelper.hIndent2x,
221 0 : InputWrapper.text(
222 0 : title: AppLocale.labels.akahuAppToken,
223 0 : tooltip: AppLocale.labels.akahuTokenTooltip,
224 0 : controller: appToken,
225 : isRequired: true,
226 : ),
227 0 : InputWrapper.text(
228 0 : title: AppLocale.labels.akahuUserToken,
229 0 : tooltip: AppLocale.labels.akahuTokenTooltip,
230 0 : controller: userToken,
231 : isRequired: true,
232 : ),
233 : ],
234 0 : ThemeHelper.hIndent2x,
235 0 : if (error != null) ...[
236 0 : Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
237 : ThemeHelper.hIndent,
238 : ],
239 0 : if (notice != null) ...[
240 0 : Text(notice!, style: textTheme.bodyLarge),
241 : ThemeHelper.hIndent,
242 : ],
243 0 : if (isLoading)
244 0 : const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
245 0 : else ...[
246 0 : accounts.isEmpty
247 0 : ? FullSizedButtonWidget(
248 : key: const ValueKey('akahu_connect'),
249 : icon: Icons.login,
250 0 : onPressed: connect,
251 0 : title: AppLocale.labels.integrationConnect,
252 : )
253 0 : : FullSizedButtonWidget(
254 : key: const ValueKey('akahu_disconnect'),
255 : icon: Icons.logout,
256 0 : onPressed: disconnect,
257 0 : title: AppLocale.labels.integrationDisconnect,
258 : ),
259 0 : if (tokens != null)
260 0 : Wrap(
261 : alignment: WrapAlignment.end,
262 0 : children: [
263 0 : TextButton.icon(
264 : key: const ValueKey('akahu_refresh'),
265 : icon: const Icon(Icons.sync),
266 0 : onPressed: refresh,
267 0 : label: Text(AppLocale.labels.akahuRefresh),
268 : ),
269 0 : TextButton.icon(
270 : key: const ValueKey('akahu_forget'),
271 : icon: const Icon(Icons.link_off),
272 0 : onPressed: forget,
273 0 : label: Text(AppLocale.labels.integrationForget),
274 : ),
275 : ],
276 : ),
277 : ],
278 0 : for (final item in accounts) buildAccount(context, item, state),
279 : ],
280 : );
281 : });
282 : }
283 : }
|