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/controller/deep_link/deep_link_handler.dart';
5 : import 'package:app_finance/_classes/herald/app_design.dart';
6 : import 'package:app_finance/_classes/herald/app_locale.dart';
7 : import 'package:app_finance/_classes/integration/monzo/monzo_client.dart';
8 : import 'package:app_finance/_classes/integration/monzo/monzo_importer.dart';
9 : import 'package:app_finance/_classes/integration/monzo/monzo_settings.dart';
10 : import 'package:app_finance/_classes/storage/app_data.dart';
11 : import 'package:app_finance/_classes/storage/app_preferences.dart';
12 : import 'package:app_finance/_classes/storage/transaction_log.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/enablebanking_widget.dart' show UrlLauncher;
19 : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
20 : import 'package:http/http.dart' as http;
21 : import 'package:material_ui/material_ui.dart';
22 : import 'package:provider/provider.dart';
23 : import 'package:url_launcher/url_launcher.dart';
24 :
25 : class MonzoBankAccount extends IntegrationTarget {
26 : final MonzoAccount account;
27 : MonzoBalance? balance;
28 :
29 1 : MonzoBankAccount(this.account, {super.appAccount, super.category, required super.from});
30 : }
31 :
32 : class MonzoWidget extends StatefulWidget {
33 : final http.Client? httpClient;
34 : final UrlLauncher? launcher;
35 : final DateTime Function()? now;
36 :
37 3 : const MonzoWidget({super.key, this.httpClient, this.launcher, this.now});
38 :
39 1 : @override
40 1 : MonzoWidgetState createState() => MonzoWidgetState();
41 : }
42 :
43 : class MonzoWidgetState extends State<MonzoWidget> {
44 : late final MonzoSettings settings;
45 : late final TextEditingController clientId;
46 : late final TextEditingController redirectUrl;
47 : final clientSecret = TextEditingController();
48 : final code = TextEditingController();
49 : MonzoTokens? tokens;
50 : String? authorizationState;
51 : List<MonzoBankAccount> accounts = [];
52 : bool isLoading = false;
53 : String? error;
54 : String? notice;
55 :
56 4 : DateTime now() => (widget.now ?? DateTime.now)();
57 :
58 1 : @override
59 : void initState() {
60 1 : super.initState();
61 2 : settings = MonzoSettings.load();
62 2 : tokens = MonzoSettings.loadTokens();
63 4 : authorizationState = settings.authorizationState.isEmpty ? null : settings.authorizationState;
64 4 : clientId = TextEditingController(text: settings.clientId);
65 2 : redirectUrl = TextEditingController(
66 4 : text: settings.redirectUrl.isEmpty ? MonzoSettings.defaultRedirectUrl : settings.redirectUrl,
67 : );
68 3 : DeepLinkHandler.monzoCallback.addListener(onLink);
69 : // A callback that came before this section was open (e.g. the application was started by it)
70 4 : WidgetsBinding.instance.addPostFrameCallback((_) => onLink());
71 : }
72 :
73 1 : @override
74 : void dispose() {
75 3 : DeepLinkHandler.monzoCallback.removeListener(onLink);
76 6 : for (final controller in [clientId, redirectUrl, clientSecret, code]) {
77 1 : controller.dispose();
78 : }
79 1 : super.dispose();
80 : }
81 :
82 1 : Future<void> _run(Future<void> Function(MonzoClient client) callback) async {
83 2 : setState(() {
84 1 : isLoading = true;
85 1 : error = null;
86 1 : notice = null;
87 : });
88 : MonzoClient? client;
89 : try {
90 1 : await saveSettings();
91 1 : final secret = MonzoSettings.loadSecret();
92 6 : if (settings.clientId.isEmpty || secret == null || settings.redirectUrl.isEmpty) {
93 3 : throw MonzoException(AppLocale.labels.monzoIncomplete);
94 : }
95 1 : client = MonzoClient(
96 2 : clientId: settings.clientId,
97 : clientSecret: secret,
98 1 : tokens: tokens,
99 1 : onTokens: (value) async {
100 1 : tokens = value;
101 1 : await MonzoSettings.saveTokens(value);
102 : },
103 2 : client: widget.httpClient ?? http.Client(),
104 1 : now: now,
105 : );
106 1 : await callback(client);
107 1 : } on MonzoException catch (e) {
108 2 : error = e.message;
109 : // Neither the access token nor the refresh token is valid anymore: a new sign-in is needed
110 2 : if (e.statusCode == 401) {
111 0 : await _clearAccess();
112 : }
113 : } catch (e) {
114 0 : error = e.toString();
115 : } finally {
116 2 : if (widget.httpClient == null) {
117 0 : client?.close();
118 : }
119 1 : if (mounted) {
120 3 : setState(() => isLoading = false);
121 : }
122 : }
123 : }
124 :
125 1 : Future<void> _clearAccess() async {
126 1 : tokens = null;
127 2 : accounts = [];
128 2 : settings.approvedAt = null;
129 1 : await MonzoSettings.clearTokens();
130 2 : await settings.save();
131 : }
132 :
133 1 : Future<void> saveSettings() async {
134 3 : final secret = clientSecret.text.trim();
135 1 : if (secret.isNotEmpty) {
136 1 : await MonzoSettings.saveSecret(secret);
137 2 : clientSecret.clear();
138 : }
139 1 : settings
140 4 : ..clientId = clientId.text.trim()
141 4 : ..redirectUrl = redirectUrl.text.trim();
142 2 : await settings.save();
143 : }
144 :
145 1 : void onLink() {
146 4 : if (!mounted || DeepLinkHandler.monzoCallback.value == null || authorizationState == null) {
147 : return;
148 : }
149 1 : if (isLoading) {
150 0 : Future.delayed(const Duration(milliseconds: 300), onLink);
151 : return;
152 : }
153 3 : confirm(link: DeepLinkHandler.takeMonzoCallback().toString());
154 : }
155 :
156 1 : Future<void> _setAuthorizationState(String? state) async {
157 1 : authorizationState = state;
158 2 : settings.authorizationState = state ?? '';
159 2 : await settings.save();
160 : }
161 :
162 3 : Future<void> connect() => _run((client) async {
163 1 : if (tokens != null) {
164 1 : return _loadAccounts(client);
165 : }
166 1 : final state = MonzoSettings.newState();
167 3 : final url = client.authorizationUrl(redirectUrl: settings.redirectUrl, state: state);
168 1 : await _setAuthorizationState(state);
169 3 : await (widget.launcher ?? (uri) => launchUrl(uri, mode: LaunchMode.externalApplication))(url);
170 : });
171 :
172 : // [link] comes from Monzo's redirect (deep link) and has to return the pending state; the field is entered manually
173 3 : Future<void> confirm({String? link}) => _run((client) async {
174 1 : final value = MonzoClient.extractCode(
175 0 : link ?? code.text,
176 1 : state: authorizationState,
177 : requireState: link != null,
178 : );
179 3 : await client.exchange(value, redirectUrl: settings.redirectUrl);
180 2 : settings.approvedAt = null;
181 1 : await _setAuthorizationState(null);
182 2 : code.clear();
183 1 : await _loadAccounts(client);
184 : });
185 :
186 1 : Future<void> _loadAccounts(MonzoClient client) async {
187 : final List<MonzoAccount> items;
188 : try {
189 1 : items = await client.getAccounts();
190 1 : } on MonzoException catch (e) {
191 : // Expected right after the sign-in: the access is granted in the Monzo app
192 3 : if (e.code != null && e.code!.contains('insufficient_permissions')) {
193 2 : notice = e.message;
194 : return;
195 : }
196 : rethrow;
197 : }
198 2 : if (settings.approvedAt == null) {
199 3 : settings.approvedAt = now();
200 2 : await settings.save();
201 : }
202 1 : final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
203 2 : final monthAgo = now().subtract(const Duration(days: 30));
204 1 : accounts = items
205 3 : .where((account) => !account.isClosed)
206 3 : .map((account) => MonzoBankAccount(
207 : account,
208 4 : appAccount: settings.links[account.id],
209 : category: defaultBudget,
210 4 : from: settings.imported[account.id] ?? monthAgo,
211 : ))
212 1 : .toList();
213 2 : for (final item in accounts) {
214 : try {
215 4 : item.balance = await client.getBalance(item.account.id);
216 0 : } on MonzoException {
217 : // The balance is optional for the import
218 : }
219 : }
220 2 : final until = settings.fullHistoryUntil;
221 2 : if (accounts.isEmpty) {
222 0 : notice = AppLocale.labels.integrationNoAccounts;
223 2 : } else if (until != null && now().isBefore(until)) {
224 1 : final time = TimeOfDay.fromDateTime(until);
225 2 : notice = AppLocale.labels
226 8 : .monzoFullHistory('${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}');
227 : }
228 : }
229 :
230 0 : Future<void> disconnect() async => setState(() => accounts = []);
231 :
232 3 : Future<void> forget() => _run((client) async {
233 : try {
234 1 : await client.logout();
235 : } catch (_) {
236 : // The access is dropped locally in any case
237 : }
238 1 : await _clearAccess();
239 1 : await _setAuthorizationState(null);
240 : });
241 :
242 3 : Future<void> importTransactions(MonzoBankAccount item) => _run((client) async {
243 2 : if (item.appAccount == null || item.category == null) {
244 0 : throw MonzoException(AppLocale.labels.integrationSelectTarget);
245 : }
246 2 : final state = Provider.of<AppData>(context, listen: false);
247 2 : final id = item.account.id;
248 1 : var since = item.from;
249 : String? limited;
250 2 : final until = settings.fullHistoryUntil;
251 2 : final earliest = now().subtract(MonzoClient.historyLimit);
252 3 : if ((until == null || !now().isBefore(until)) && since.isBefore(earliest)) {
253 4 : since = DateTime(earliest.year, earliest.month, earliest.day);
254 4 : limited = AppLocale.labels.monzoHistoryLimited(since.toIso8601String().substring(0, 10));
255 : }
256 1 : final transactions = await client.getTransactions(id, since: since);
257 1 : final importer = MonzoImporter(
258 2 : exists: (uuid) => state.getByUuid(uuid) != null,
259 3 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
260 : );
261 1 : final summary = importer.run(
262 : accountId: id,
263 : transactions: transactions,
264 1 : account: item.appAccount!,
265 1 : category: item.category!,
266 1 : prediction: state.prediction,
267 : );
268 1 : await state.restate();
269 1 : final today = now();
270 4 : settings.links[id] = item.appAccount!;
271 7 : settings.imported[id] = DateTime(today.year, today.month, today.day);
272 2 : await settings.save();
273 2 : notice = [
274 1 : if (limited != null) limited,
275 2 : AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped),
276 1 : ].join('\n');
277 : });
278 :
279 2 : Widget buildSettings(BuildContext context) => Column(
280 1 : crossAxisAlignment: AppDesign.getAlignment(),
281 1 : children: [
282 5 : Text(AppLocale.labels.monzoSteps, key: const ValueKey('monzo_steps'), style: context.textTheme.bodyMedium),
283 : ThemeHelper.hIndent2x,
284 1 : InputWrapper.text(
285 2 : title: AppLocale.labels.monzoClientId,
286 1 : controller: clientId,
287 : isRequired: true,
288 : ),
289 1 : InputWrapper.text(
290 2 : title: AppLocale.labels.monzoClientSecret,
291 2 : tooltip: AppLocale.labels.monzoClientSecretTooltip,
292 1 : controller: clientSecret,
293 1 : isRequired: MonzoSettings.loadSecret() == null,
294 : ),
295 1 : InputWrapper.text(
296 2 : title: AppLocale.labels.monzoRedirect,
297 2 : tooltip: AppLocale.labels.monzoRedirectTooltip,
298 1 : controller: redirectUrl,
299 : isRequired: true,
300 : inputType: TextInputType.url,
301 : ),
302 : ],
303 : );
304 :
305 1 : Widget buildAccount(BuildContext context, MonzoBankAccount item, AppData state) {
306 1 : final balance = item.balance;
307 1 : return IntegrationAccountCard(
308 2 : title: item.account.title,
309 5 : subtitle: balance != null ? '${AppLocale.labels.balance}: ${balance.balance} ${balance.currency}' : null,
310 : target: item,
311 : state: state,
312 1 : isDisabled: isLoading,
313 0 : onChanged: () => setState(() {}),
314 2 : onImport: () => importTransactions(item),
315 : );
316 : }
317 :
318 1 : @override
319 : Widget build(BuildContext context) {
320 1 : final textTheme = context.textTheme;
321 1 : final colorScheme = context.colorScheme;
322 2 : return Consumer<AppData>(builder: (context, state, _) {
323 1 : return Column(
324 1 : crossAxisAlignment: AppDesign.getAlignment(),
325 1 : children: [
326 4 : Text(AppLocale.labels.monzoDescription, style: textTheme.bodyMedium),
327 : ThemeHelper.hIndent2x,
328 2 : if (tokens == null) buildSettings(context),
329 2 : if (authorizationState != null && tokens == null)
330 1 : InputWrapper.text(
331 2 : title: AppLocale.labels.monzoCode,
332 2 : tooltip: AppLocale.labels.monzoCodeTooltip,
333 1 : controller: code,
334 : isRequired: true,
335 : inputType: TextInputType.url,
336 : ),
337 1 : ThemeHelper.hIndent2x,
338 2 : if (error != null) ...[
339 5 : Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
340 : ThemeHelper.hIndent,
341 : ],
342 2 : if (notice != null) ...[
343 3 : Text(notice!, key: const ValueKey('monzo_notice'), style: textTheme.bodyLarge),
344 : ThemeHelper.hIndent,
345 : ],
346 1 : if (isLoading)
347 0 : const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
348 1 : else ...[
349 2 : if (accounts.isNotEmpty)
350 1 : FullSizedButtonWidget(
351 : key: const ValueKey('monzo_disconnect'),
352 : icon: Icons.logout,
353 1 : onPressed: disconnect,
354 2 : title: AppLocale.labels.integrationDisconnect,
355 : )
356 : else
357 1 : FullSizedButtonWidget(
358 : key: const ValueKey('monzo_connect'),
359 : icon: Icons.login,
360 4 : onPressed: authorizationState != null && tokens == null ? confirm : connect,
361 2 : title: AppLocale.labels.integrationConnect,
362 : ),
363 1 : if (tokens != null)
364 1 : Align(
365 : alignment: Alignment.centerRight,
366 1 : child: TextButton.icon(
367 : key: const ValueKey('monzo_forget'),
368 : icon: const Icon(Icons.link_off),
369 1 : onPressed: forget,
370 3 : label: Text(AppLocale.labels.integrationForget),
371 : ),
372 : ),
373 : ],
374 2 : for (final item in accounts) buildAccount(context, item, state),
375 : ],
376 : );
377 : });
378 : }
379 : }
|