LCOV - code coverage report
Current view: top level - lib/pages/integration/widgets - monobank_widget.dart Coverage Total Hit
Test: lcov.info Lines: 0.5 % 189 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/monobank/monobank_client.dart';
       7              : import 'package:app_finance/_classes/integration/monobank/monobank_importer.dart';
       8              : import 'package:app_finance/_classes/integration/monobank/monobank_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/account_app_data.dart';
      13              : import 'package:app_finance/_classes/structure/bill_app_data.dart';
      14              : import 'package:app_finance/_configs/account_type.dart';
      15              : import 'package:app_finance/_configs/theme_helper.dart';
      16              : import 'package:app_finance/_ext/build_context_ext.dart';
      17              : import 'package:app_finance/design/button/full_sized_button_widget.dart';
      18              : import 'package:app_finance/design/generic/loading_widget.dart';
      19              : import 'package:app_finance/design/wrapper/input_wrapper.dart';
      20              : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
      21              : import 'package:flutter_currency_picker/flutter_currency_picker.dart';
      22              : import 'package:material_ui/material_ui.dart';
      23              : import 'package:provider/provider.dart';
      24              : 
      25              : class MonobankBankAccount extends IntegrationTarget {
      26              :   final MonobankAccount account;
      27              : 
      28            0 :   MonobankBankAccount(this.account, {super.appAccount, super.category, required super.from});
      29              : 
      30            0 :   String get title {
      31            0 :     final source = account;
      32            0 :     if (source.isJar) {
      33            0 :       return [AppLocale.labels.monobankJar, source.title ?? ''].where((e) => e.isNotEmpty).join(': ');
      34              :     }
      35            0 :     final type = source.type.isNotEmpty ? '${source.type[0].toUpperCase()}${source.type.substring(1)}' : '';
      36            0 :     final pan = source.maskedPan.isNotEmpty ? source.maskedPan.first : (source.iban ?? '');
      37            0 :     return [type, pan, source.currency].where((e) => e.isNotEmpty).join(' — ');
      38              :   }
      39              : 
      40            0 :   String get accountType {
      41            0 :     if (account.isJar) {
      42            0 :       return AppAccountType.deposit.toString();
      43              :     }
      44            0 :     if (account.type == 'fop') {
      45            0 :       return AppAccountType.account.toString();
      46              :     }
      47            0 :     return (account.creditLimit > 0 ? AppAccountType.creditCard : AppAccountType.debitCard).toString();
      48              :   }
      49              : }
      50              : 
      51              : class MonobankWidget extends StatefulWidget {
      52              :   final MonobankClient? client;
      53              : 
      54            1 :   const MonobankWidget({super.key, this.client});
      55              : 
      56            0 :   @override
      57            0 :   MonobankWidgetState createState() => MonobankWidgetState();
      58              : }
      59              : 
      60              : class MonobankWidgetState extends State<MonobankWidget> {
      61              :   late final MonobankClient client;
      62              :   late final MonobankSettings settings;
      63              :   final token = TextEditingController();
      64              :   String? access;
      65              :   List<MonobankBankAccount> accounts = [];
      66              :   bool isLoading = false;
      67              :   String? error;
      68              :   String? notice;
      69              :   MonobankCancelToken? cancelToken;
      70              :   String? progress;
      71              :   double? progressValue;
      72              : 
      73            0 :   @override
      74              :   void initState() {
      75            0 :     super.initState();
      76            0 :     client = widget.client ?? MonobankClient();
      77            0 :     settings = MonobankSettings.load();
      78            0 :     access = MonobankSettings.loadToken();
      79              :   }
      80              : 
      81            0 :   @override
      82              :   void dispose() {
      83            0 :     cancelToken?.cancel();
      84            0 :     token.dispose();
      85            0 :     if (widget.client == null) {
      86            0 :       client.close();
      87              :     }
      88            0 :     super.dispose();
      89              :   }
      90              : 
      91            0 :   Future<void> _run(Future<void> Function() callback) async {
      92            0 :     setState(() {
      93            0 :       isLoading = true;
      94            0 :       error = null;
      95            0 :       notice = null;
      96            0 :       progress = null;
      97            0 :       progressValue = null;
      98              :     });
      99              :     try {
     100            0 :       await callback();
     101            0 :     } on MonobankCanceledException {
     102              :       // Already imported windows are kept
     103            0 :     } on MonobankException catch (e) {
     104            0 :       error = e.message;
     105              :     } catch (e) {
     106            0 :       error = e.toString();
     107              :     } finally {
     108            0 :       cancelToken = null;
     109            0 :       if (mounted) {
     110            0 :         setState(() => isLoading = false);
     111              :       }
     112              :     }
     113              :   }
     114              : 
     115            0 :   void _progress(int done, int total, Duration? wait) {
     116            0 :     if (!mounted) {
     117              :       return;
     118              :     }
     119            0 :     setState(() {
     120            0 :       progressValue = total > 0 ? done / total : null;
     121            0 :       progress = [
     122            0 :         AppLocale.labels.monobankProgress(done, total),
     123            0 :         if (wait != null) AppLocale.labels.monobankRateLimit(wait.inSeconds),
     124            0 :       ].join('\n');
     125              :     });
     126              :   }
     127              : 
     128            0 :   void cancel() => cancelToken?.cancel();
     129              : 
     130            0 :   Future<void> connect() => _run(() async {
     131            0 :         final value = access ?? token.text.trim();
     132            0 :         if (value.isEmpty) {
     133            0 :           throw MonobankException(AppLocale.labels.monobankToken);
     134              :         }
     135            0 :         cancelToken = MonobankCancelToken();
     136            0 :         final info = await client.getClientInfo(value, cancel: cancelToken);
     137            0 :         if (access == null) {
     138            0 :           await MonobankSettings.saveToken(value);
     139            0 :           token.clear();
     140            0 :           access = value;
     141              :         }
     142            0 :         final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
     143            0 :         final monthAgo = DateTime.now().subtract(const Duration(days: 30));
     144            0 :         accounts = info.accounts
     145            0 :             .map((account) => MonobankBankAccount(
     146              :                   account,
     147            0 :                   appAccount: settings.links[account.id],
     148              :                   category: defaultBudget,
     149            0 :                   from: settings.imported[account.id] ?? monthAgo,
     150              :                 ))
     151            0 :             .toList();
     152            0 :         if (accounts.isEmpty) {
     153            0 :           notice = AppLocale.labels.integrationNoAccounts;
     154              :         }
     155              :       });
     156              : 
     157            0 :   Future<void> disconnect() => _run(() async => accounts = []);
     158              : 
     159            0 :   Future<void> forget() => _run(() async {
     160            0 :         await MonobankSettings.clearToken();
     161            0 :         access = null;
     162            0 :         accounts = [];
     163              :       });
     164              : 
     165            0 :   Future<void> createAccount(MonobankBankAccount item) => _run(() async {
     166            0 :         final state = Provider.of<AppData>(context, listen: false);
     167            0 :         final currency = CurrencyProvider.find(item.account.currency);
     168            0 :         final created = state.add(AccountAppData(
     169            0 :           title: item.title,
     170            0 :           type: item.accountType,
     171            0 :           details: item.account.amount,
     172              :           progress: 1.0,
     173              :           currency: currency,
     174              :           hidden: false,
     175              :         )) as AccountAppData;
     176            0 :         item.appAccount = created.uuid;
     177            0 :         settings.links[item.account.id] = created.uuid!;
     178            0 :         await settings.save();
     179              :       });
     180              : 
     181            0 :   Future<void> importTransactions(MonobankBankAccount item) => _run(() async {
     182            0 :         final current = access;
     183              :         if (current == null) {
     184              :           return;
     185              :         }
     186            0 :         if (item.appAccount == null || item.category == null) {
     187            0 :           throw MonobankException(AppLocale.labels.integrationSelectTarget);
     188              :         }
     189            0 :         final state = Provider.of<AppData>(context, listen: false);
     190            0 :         final id = item.account.id;
     191            0 :         final importer = MonobankImporter(
     192            0 :           exists: (uuid) => state.getByUuid(uuid) != null,
     193            0 :           add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
     194            0 :           categories: MonobankImporter.learn(settings.records, (uuid) {
     195            0 :             final bill = state.getByUuid(uuid);
     196            0 :             return bill is BillAppData && !bill.hidden ? bill.category : null;
     197              :           }),
     198              :         );
     199              :         var added = 0;
     200              :         var skipped = 0;
     201              :         var pending = 0;
     202            0 :         settings.links[id] = item.appAccount!;
     203            0 :         cancelToken = MonobankCancelToken();
     204              :         try {
     205            0 :           await client.getTransactions(
     206              :             current,
     207              :             id,
     208            0 :             from: item.from,
     209            0 :             cancel: cancelToken,
     210            0 :             onProgress: _progress,
     211            0 :             onWindow: (window, transactions) {
     212            0 :               final summary = importer.run(
     213              :                 id: id,
     214              :                 transactions: transactions,
     215            0 :                 account: item.appAccount!,
     216            0 :                 category: item.category!,
     217            0 :                 currency: item.account.currency,
     218            0 :                 prediction: state.prediction,
     219              :               );
     220            0 :               added += summary.added;
     221            0 :               skipped += summary.skipped;
     222            0 :               pending += summary.pending;
     223              :               // Transactions on hold are requested again on the next import
     224            0 :               final since = importer.pendingSince;
     225            0 :               final last = since != null && since.isBefore(window.to) ? since : window.to;
     226            0 :               settings.imported[id] = DateTime(last.year, last.month, last.day);
     227              :             },
     228              :           );
     229              :         } finally {
     230            0 :           settings.addRecords(importer.records);
     231            0 :           await settings.save();
     232            0 :           item.from = settings.imported[id] ?? item.from;
     233            0 :           await state.restate();
     234            0 :           notice = AppLocale.labels.integrationImported(added, pending, skipped);
     235              :         }
     236              :       });
     237              : 
     238            0 :   Widget buildAccount(BuildContext context, MonobankBankAccount item, AppData state) {
     239            0 :     final source = item.account;
     240            0 :     return IntegrationAccountCard(
     241            0 :       key: ValueKey('monobank_${source.id}'),
     242            0 :       title: item.title,
     243            0 :       subtitle: [
     244            0 :         '${AppLocale.labels.balance}: ${source.amount} ${source.currency}',
     245            0 :         if (source.creditLimit > 0) '${AppLocale.labels.creditCard}: ${source.limit} ${source.currency}',
     246            0 :       ].join('\n'),
     247              :       target: item,
     248              :       state: state,
     249            0 :       isDisabled: isLoading,
     250            0 :       onChanged: () => setState(() {}),
     251            0 :       onImport: () => importTransactions(item),
     252            0 :       children: [
     253            0 :         if (item.appAccount == null || state.getByUuid(item.appAccount!) == null)
     254            0 :           Align(
     255              :             alignment: Alignment.centerRight,
     256            0 :             child: TextButton.icon(
     257            0 :               key: ValueKey('monobank_create_${source.id}'),
     258              :               icon: const Icon(Icons.add),
     259            0 :               onPressed: isLoading ? null : () => createAccount(item),
     260            0 :               label: Text(AppLocale.labels.monobankCreateAccount),
     261              :             ),
     262              :           ),
     263              :       ],
     264              :     );
     265              :   }
     266              : 
     267            0 :   Widget buildProgress(BuildContext context) {
     268            0 :     final textTheme = context.textTheme;
     269            0 :     return Column(
     270              :       crossAxisAlignment: CrossAxisAlignment.stretch,
     271            0 :       children: [
     272            0 :         if (progress != null) ...[
     273            0 :           Text(progress!, key: const ValueKey('monobank_progress'), style: textTheme.bodyMedium),
     274              :           ThemeHelper.hIndent,
     275            0 :           LinearProgressIndicator(value: progressValue),
     276              :         ] else
     277            0 :           const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48))),
     278            0 :         if (cancelToken != null)
     279            0 :           Align(
     280              :             alignment: Alignment.centerRight,
     281            0 :             child: TextButton.icon(
     282              :               key: const ValueKey('monobank_cancel'),
     283              :               icon: const Icon(Icons.close),
     284            0 :               onPressed: cancel,
     285            0 :               label: Text(AppLocale.labels.btnCancel),
     286              :             ),
     287              :           ),
     288              :       ],
     289              :     );
     290              :   }
     291              : 
     292            0 :   @override
     293              :   Widget build(BuildContext context) {
     294            0 :     final textTheme = context.textTheme;
     295            0 :     final colorScheme = context.colorScheme;
     296            0 :     return Consumer<AppData>(builder: (context, state, _) {
     297            0 :       return Column(
     298            0 :         crossAxisAlignment: AppDesign.getAlignment(),
     299            0 :         children: [
     300            0 :           Text(AppLocale.labels.monobankDescription, style: textTheme.bodyMedium),
     301              :           ThemeHelper.hIndent2x,
     302            0 :           if (access == null) ...[
     303            0 :             Text(AppLocale.labels.monobankTokenSteps,
     304            0 :                 key: const ValueKey('monobank_steps'), style: textTheme.bodyMedium),
     305              :             ThemeHelper.hIndent2x,
     306            0 :             InputWrapper.text(
     307            0 :               title: AppLocale.labels.monobankToken,
     308            0 :               tooltip: AppLocale.labels.monobankTokenTooltip,
     309            0 :               controller: token,
     310              :               isRequired: true,
     311              :             ),
     312              :           ],
     313            0 :           ThemeHelper.hIndent2x,
     314            0 :           if (error != null) ...[
     315            0 :             Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
     316              :             ThemeHelper.hIndent,
     317              :           ],
     318            0 :           if (notice != null) ...[
     319            0 :             Text(notice!, style: textTheme.bodyLarge),
     320              :             ThemeHelper.hIndent,
     321              :           ],
     322            0 :           if (isLoading)
     323            0 :             buildProgress(context)
     324            0 :           else ...[
     325            0 :             accounts.isEmpty
     326            0 :                 ? FullSizedButtonWidget(
     327              :                     key: const ValueKey('monobank_connect'),
     328              :                     icon: Icons.login,
     329            0 :                     onPressed: connect,
     330            0 :                     title: AppLocale.labels.integrationConnect,
     331              :                   )
     332            0 :                 : FullSizedButtonWidget(
     333              :                     key: const ValueKey('monobank_disconnect'),
     334              :                     icon: Icons.logout,
     335            0 :                     onPressed: disconnect,
     336            0 :                     title: AppLocale.labels.integrationDisconnect,
     337              :                   ),
     338            0 :             if (access != null)
     339            0 :               Align(
     340              :                 alignment: Alignment.centerRight,
     341            0 :                 child: TextButton.icon(
     342              :                   key: const ValueKey('monobank_forget'),
     343              :                   icon: const Icon(Icons.link_off),
     344            0 :                   onPressed: forget,
     345            0 :                   label: Text(AppLocale.labels.integrationForget),
     346              :                 ),
     347              :               ),
     348              :           ],
     349            0 :           for (final item in accounts) buildAccount(context, item, state),
     350              :         ],
     351              :       );
     352              :     });
     353              :   }
     354              : }
        

Generated by: LCOV version 2.0-1