LCOV - code coverage report
Current view: top level - lib/pages/integration/widgets - monzo_widget.dart Coverage Total Hit
Test: lcov.info Lines: 0.5 % 205 1
Test Date: 2026-12-05 10:54:13 Functions: - 0 0

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

Generated by: LCOV version 2.0-1