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

Generated by: LCOV version 2.0-1