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

Generated by: LCOV version 2.0-1