LCOV - code coverage report
Current view: top level - lib/pages/integration/widgets - wise_widget.dart Coverage Total Hit
Test: lcov.info Lines: 0.7 % 152 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/herald/app_design.dart';
       5              : import 'package:app_finance/_classes/herald/app_locale.dart';
       6              : import 'package:app_finance/_classes/integration/wise/wise_client.dart';
       7              : import 'package:app_finance/_classes/integration/wise/wise_importer.dart';
       8              : import 'package:app_finance/_classes/integration/wise/wise_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/form/list_selector_item.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 WiseBankAccount extends IntegrationTarget {
      23              :   final WiseBalance balance;
      24              : 
      25            0 :   WiseBankAccount(this.balance, {super.appAccount, super.category, required super.from});
      26              : 
      27            0 :   String get title => [balance.currency, balance.name ?? ''].where((e) => e.isNotEmpty).join(' — ');
      28              : }
      29              : 
      30              : class WiseWidget extends StatefulWidget {
      31              :   final WiseClient? client;
      32              : 
      33            1 :   const WiseWidget({super.key, this.client});
      34              : 
      35            0 :   @override
      36            0 :   WiseWidgetState createState() => WiseWidgetState();
      37              : }
      38              : 
      39              : class WiseWidgetState extends State<WiseWidget> {
      40              :   late final WiseClient client;
      41              :   late final WiseSettings settings;
      42              :   final token = TextEditingController();
      43              :   String? access;
      44              :   List<WiseProfile> profiles = [];
      45              :   List<WiseBankAccount> accounts = [];
      46              :   bool isLoading = false;
      47              :   String? error;
      48              :   String? notice;
      49              : 
      50            0 :   @override
      51              :   void initState() {
      52            0 :     super.initState();
      53            0 :     client = widget.client ?? WiseClient();
      54            0 :     settings = WiseSettings.load();
      55            0 :     access = WiseSettings.loadToken();
      56              :   }
      57              : 
      58            0 :   @override
      59              :   void dispose() {
      60            0 :     token.dispose();
      61            0 :     if (widget.client == null) {
      62            0 :       client.close();
      63              :     }
      64            0 :     super.dispose();
      65              :   }
      66              : 
      67            0 :   Future<void> _run(Future<void> Function() callback) async {
      68            0 :     setState(() {
      69            0 :       isLoading = true;
      70            0 :       error = null;
      71            0 :       notice = null;
      72              :     });
      73              :     try {
      74            0 :       await callback();
      75            0 :     } on WiseException catch (e) {
      76            0 :       error = e.message;
      77              :     } catch (e) {
      78            0 :       error = e.toString();
      79              :     } finally {
      80            0 :       if (mounted) {
      81            0 :         setState(() => isLoading = false);
      82              :       }
      83              :     }
      84              :   }
      85              : 
      86            0 :   Future<void> _loadBalances() async {
      87            0 :     final profile = settings.profile;
      88            0 :     if (access == null || profile == null) {
      89              :       return;
      90              :     }
      91            0 :     final balances = await client.getBalances(access!, profile);
      92            0 :     final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
      93            0 :     final monthAgo = DateTime.now().subtract(const Duration(days: 30));
      94            0 :     accounts = balances
      95            0 :         .map((balance) => WiseBankAccount(
      96              :               balance,
      97            0 :               appAccount: settings.links['${balance.id}'],
      98              :               category: defaultBudget,
      99            0 :               from: settings.imported['${balance.id}'] ?? monthAgo,
     100              :             ))
     101            0 :         .toList();
     102            0 :     if (accounts.isEmpty) {
     103            0 :       notice = AppLocale.labels.integrationNoAccounts;
     104              :     }
     105              :   }
     106              : 
     107            0 :   Future<void> connect() => _run(() async {
     108            0 :         final value = access ?? token.text.trim();
     109            0 :         if (value.isEmpty) {
     110            0 :           throw WiseException(AppLocale.labels.wiseToken);
     111              :         }
     112            0 :         profiles = await client.getProfiles(value);
     113            0 :         if (access == null) {
     114            0 :           await WiseSettings.saveToken(value);
     115            0 :           token.clear();
     116            0 :           access = value;
     117              :         }
     118            0 :         if (profiles.isEmpty) {
     119            0 :           notice = AppLocale.labels.wiseNoProfiles;
     120              :           return;
     121              :         }
     122            0 :         if (!profiles.any((e) => e.id == settings.profile)) {
     123            0 :           settings.profile = profiles.first.id;
     124            0 :           await settings.save();
     125              :         }
     126            0 :         await _loadBalances();
     127              :       });
     128              : 
     129            0 :   Future<void> selectProfile(String? value) => _run(() async {
     130            0 :         final profile = int.tryParse(value ?? '');
     131            0 :         if (profile == null || profile == settings.profile) {
     132              :           return;
     133              :         }
     134            0 :         settings.profile = profile;
     135            0 :         await settings.save();
     136            0 :         accounts = [];
     137            0 :         await _loadBalances();
     138              :       });
     139              : 
     140            0 :   Future<void> disconnect() => _run(() async {
     141            0 :         profiles = [];
     142            0 :         accounts = [];
     143              :       });
     144              : 
     145            0 :   Future<void> forget() => _run(() async {
     146            0 :         await WiseSettings.clearToken();
     147            0 :         access = null;
     148            0 :         profiles = [];
     149            0 :         accounts = [];
     150              :       });
     151              : 
     152            0 :   Map<String, WiseCounterpart> _counterparts(WiseBankAccount item) => {
     153            0 :         for (final other in accounts)
     154            0 :           if (other != item && other.appAccount != null)
     155            0 :             other.balance.currency: (balanceId: '${other.balance.id}', account: other.appAccount!),
     156              :       };
     157              : 
     158            0 :   Future<void> importTransactions(WiseBankAccount item) => _run(() async {
     159            0 :         final current = access;
     160            0 :         final profile = settings.profile;
     161              :         if (current == null || profile == null) {
     162              :           return;
     163              :         }
     164            0 :         if (item.appAccount == null || item.category == null) {
     165            0 :           throw WiseException(AppLocale.labels.integrationSelectTarget);
     166              :         }
     167            0 :         final state = Provider.of<AppData>(context, listen: false);
     168            0 :         final transactions = await client.getStatement(
     169              :           current,
     170              :           profileId: profile,
     171            0 :           balance: item.balance,
     172            0 :           start: item.from,
     173              :         );
     174            0 :         final importer = WiseImporter(
     175            0 :           exists: (uuid) => state.getByUuid(uuid) != null,
     176            0 :           add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
     177            0 :           setRate: (rate) {
     178            0 :             state.update(rate.uuid, rate, true);
     179            0 :             TransactionLog.save(rate);
     180              :           },
     181              :         );
     182            0 :         final summary = importer.run(
     183              :           profileId: profile,
     184            0 :           balance: item.balance,
     185              :           transactions: transactions,
     186            0 :           account: item.appAccount!,
     187            0 :           category: item.category!,
     188            0 :           prediction: state.prediction,
     189            0 :           counterparts: _counterparts(item),
     190              :         );
     191            0 :         await state.restate();
     192            0 :         final today = DateTime.now();
     193            0 :         final id = '${item.balance.id}';
     194            0 :         settings.links[id] = item.appAccount!;
     195            0 :         settings.imported[id] = DateTime(today.year, today.month, today.day);
     196            0 :         await settings.save();
     197            0 :         notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
     198              :       });
     199              : 
     200            0 :   Widget buildAccount(BuildContext context, WiseBankAccount item, AppData state) {
     201            0 :     final balance = item.balance;
     202            0 :     return IntegrationAccountCard(
     203            0 :       title: item.title,
     204            0 :       subtitle: '${AppLocale.labels.balance}: ${balance.amount} ${balance.currency}',
     205              :       target: item,
     206              :       state: state,
     207            0 :       isDisabled: isLoading,
     208            0 :       onChanged: () => setState(() {}),
     209            0 :       onImport: () => importTransactions(item),
     210              :     );
     211              :   }
     212              : 
     213            0 :   @override
     214              :   Widget build(BuildContext context) {
     215            0 :     final textTheme = context.textTheme;
     216            0 :     final colorScheme = context.colorScheme;
     217            0 :     return Consumer<AppData>(builder: (context, state, _) {
     218            0 :       return Column(
     219            0 :         crossAxisAlignment: AppDesign.getAlignment(),
     220            0 :         children: [
     221            0 :           Text(AppLocale.labels.wiseDescription, style: textTheme.bodyMedium),
     222              :           ThemeHelper.hIndent2x,
     223            0 :           if (access == null) ...[
     224            0 :             Text(AppLocale.labels.wiseTokenSteps, key: const ValueKey('wise_steps'), style: textTheme.bodyMedium),
     225              :             ThemeHelper.hIndent2x,
     226              :           ],
     227            0 :           if (access == null)
     228            0 :             InputWrapper.text(
     229            0 :               title: AppLocale.labels.wiseToken,
     230            0 :               tooltip: AppLocale.labels.wiseTokenTooltip,
     231            0 :               controller: token,
     232              :               isRequired: true,
     233              :             ),
     234            0 :           if (profiles.length > 1)
     235            0 :             InputWrapper.select(
     236            0 :               title: AppLocale.labels.wiseProfile,
     237            0 :               value: settings.profile?.toString(),
     238              :               isRequired: true,
     239            0 :               options: <ListSelectorItem>[
     240            0 :                 for (final profile in profiles) ListSelectorItem(id: '${profile.id}', name: profile.title),
     241              :               ],
     242            0 :               onChange: selectProfile,
     243              :             ),
     244            0 :           ThemeHelper.hIndent2x,
     245            0 :           if (error != null) ...[
     246            0 :             Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
     247              :             ThemeHelper.hIndent,
     248              :           ],
     249            0 :           if (notice != null) ...[
     250            0 :             Text(notice!, style: textTheme.bodyLarge),
     251              :             ThemeHelper.hIndent,
     252              :           ],
     253            0 :           if (isLoading)
     254            0 :             const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
     255            0 :           else ...[
     256            0 :             profiles.isEmpty
     257            0 :                 ? FullSizedButtonWidget(
     258              :                     key: const ValueKey('wise_connect'),
     259              :                     icon: Icons.login,
     260            0 :                     onPressed: connect,
     261            0 :                     title: AppLocale.labels.integrationConnect,
     262              :                   )
     263            0 :                 : FullSizedButtonWidget(
     264              :                     key: const ValueKey('wise_disconnect'),
     265              :                     icon: Icons.logout,
     266            0 :                     onPressed: disconnect,
     267            0 :                     title: AppLocale.labels.integrationDisconnect,
     268              :                   ),
     269            0 :             if (access != null)
     270            0 :               Align(
     271              :                 alignment: Alignment.centerRight,
     272            0 :                 child: TextButton.icon(
     273              :                   key: const ValueKey('wise_forget'),
     274              :                   icon: const Icon(Icons.link_off),
     275            0 :                   onPressed: forget,
     276            0 :                   label: Text(AppLocale.labels.integrationForget),
     277              :                 ),
     278              :               ),
     279              :           ],
     280            0 :           for (final item in accounts) buildAccount(context, item, state),
     281              :         ],
     282              :       );
     283              :     });
     284              :   }
     285              : }
        

Generated by: LCOV version 2.0-1