LCOV - code coverage report
Current view: top level - lib/pages/integration/widgets - up_widget.dart Coverage Total Hit
Test: lcov.info Lines: 0.8 % 119 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/up/up_client.dart';
       7              : import 'package:app_finance/_classes/integration/up/up_importer.dart';
       8              : import 'package:app_finance/_classes/integration/up/up_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 UpBankAccount extends IntegrationTarget {
      22              :   final UpAccount account;
      23              : 
      24            0 :   UpBankAccount(this.account, {super.appAccount, super.category, required super.from});
      25              : }
      26              : 
      27              : class UpWidget extends StatefulWidget {
      28              :   final UpClient? client;
      29              : 
      30            1 :   const UpWidget({super.key, this.client});
      31              : 
      32            0 :   @override
      33            0 :   UpWidgetState createState() => UpWidgetState();
      34              : }
      35              : 
      36              : class UpWidgetState extends State<UpWidget> {
      37              :   // Held transactions keep their date when settled: a repeated import looks back for them
      38              :   static const settlementDelay = Duration(days: 10);
      39              : 
      40              :   late final UpClient client;
      41              :   late final UpSettings settings;
      42              :   final token = TextEditingController();
      43              :   String? access;
      44              :   List<UpBankAccount> accounts = [];
      45              :   bool isLoading = false;
      46              :   String? error;
      47              :   String? notice;
      48              : 
      49            0 :   @override
      50              :   void initState() {
      51            0 :     super.initState();
      52            0 :     client = widget.client ?? UpClient();
      53            0 :     settings = UpSettings.load();
      54            0 :     access = UpSettings.loadToken();
      55              :   }
      56              : 
      57            0 :   @override
      58              :   void dispose() {
      59            0 :     token.dispose();
      60            0 :     if (widget.client == null) {
      61            0 :       client.close();
      62              :     }
      63            0 :     super.dispose();
      64              :   }
      65              : 
      66            0 :   Future<void> _run(Future<void> Function() callback) async {
      67            0 :     setState(() {
      68            0 :       isLoading = true;
      69            0 :       error = null;
      70            0 :       notice = null;
      71              :     });
      72              :     try {
      73            0 :       await callback();
      74            0 :     } on UpException catch (e) {
      75            0 :       error = e.message;
      76              :     } catch (e) {
      77            0 :       error = e.toString();
      78              :     } finally {
      79            0 :       if (mounted) {
      80            0 :         setState(() => isLoading = false);
      81              :       }
      82              :     }
      83              :   }
      84              : 
      85            0 :   Future<void> connect() => _run(() async {
      86            0 :         final value = access ?? token.text.trim();
      87            0 :         if (value.isEmpty) {
      88            0 :           throw UpException(AppLocale.labels.upToken);
      89              :         }
      90            0 :         await client.ping(value);
      91            0 :         final items = await client.getAccounts(value);
      92              :         // Stored only after Up has accepted it
      93            0 :         if (access == null) {
      94            0 :           await UpSettings.saveToken(value);
      95            0 :           token.clear();
      96            0 :           access = value;
      97              :         }
      98            0 :         final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
      99            0 :         final monthAgo = DateTime.now().subtract(const Duration(days: 30));
     100            0 :         accounts = items
     101            0 :             .map((account) => UpBankAccount(
     102              :                   account,
     103            0 :                   appAccount: settings.links[account.id],
     104              :                   category: defaultBudget,
     105            0 :                   from: settings.imported[account.id] ?? monthAgo,
     106              :                 ))
     107            0 :             .toList();
     108            0 :         if (accounts.isEmpty) {
     109            0 :           notice = AppLocale.labels.integrationNoAccounts;
     110              :         }
     111              :       });
     112              : 
     113            0 :   Future<void> disconnect() => _run(() async => accounts = []);
     114              : 
     115            0 :   Future<void> forget() => _run(() async {
     116            0 :         await UpSettings.clearToken();
     117            0 :         access = null;
     118            0 :         accounts = [];
     119              :       });
     120              : 
     121            0 :   Future<void> importTransactions(UpBankAccount item) => _run(() async {
     122            0 :         final current = access;
     123              :         if (current == null) {
     124              :           return;
     125              :         }
     126            0 :         if (item.appAccount == null || item.category == null) {
     127            0 :           throw UpException(AppLocale.labels.integrationSelectTarget);
     128              :         }
     129            0 :         final state = Provider.of<AppData>(context, listen: false);
     130            0 :         final id = item.account.id;
     131            0 :         final last = settings.imported[id];
     132            0 :         final from = last != null && !item.from.isAfter(last) ? item.from.subtract(settlementDelay) : item.from;
     133            0 :         final transactions = await client.getTransactions(current, id, since: from);
     134            0 :         final importer = UpImporter(
     135            0 :           exists: (uuid) => state.getByUuid(uuid) != null,
     136            0 :           add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
     137              :         );
     138            0 :         final summary = importer.run(
     139            0 :           source: item.account,
     140              :           transactions: transactions,
     141            0 :           account: item.appAccount!,
     142            0 :           category: item.category!,
     143              :           // Other Up accounts linked to the application's accounts: transfers between them
     144            0 :           links: {
     145            0 :             ...settings.links,
     146            0 :             for (final other in accounts)
     147            0 :               if (other.appAccount != null) other.account.id: other.appAccount!,
     148              :           },
     149            0 :           prediction: state.prediction,
     150              :         );
     151            0 :         await state.restate();
     152            0 :         final today = DateTime.now();
     153            0 :         settings.links[id] = item.appAccount!;
     154            0 :         settings.imported[id] = DateTime(today.year, today.month, today.day);
     155            0 :         await settings.save();
     156            0 :         notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
     157              :       });
     158              : 
     159            0 :   Widget buildAccount(BuildContext context, UpBankAccount item, AppData state) {
     160            0 :     final balance = item.account.balance;
     161            0 :     return IntegrationAccountCard(
     162            0 :       title: item.account.name,
     163            0 :       subtitle: '${AppLocale.labels.balance}: ${balance.value} ${balance.currency}',
     164              :       target: item,
     165              :       state: state,
     166            0 :       isDisabled: isLoading,
     167            0 :       onChanged: () => setState(() {}),
     168            0 :       onImport: () => importTransactions(item),
     169              :     );
     170              :   }
     171              : 
     172            0 :   @override
     173              :   Widget build(BuildContext context) {
     174            0 :     final textTheme = context.textTheme;
     175            0 :     final colorScheme = context.colorScheme;
     176            0 :     return Consumer<AppData>(builder: (context, state, _) {
     177            0 :       return Column(
     178            0 :         crossAxisAlignment: AppDesign.getAlignment(),
     179            0 :         children: [
     180            0 :           Text(AppLocale.labels.upDescription, style: textTheme.bodyMedium),
     181              :           ThemeHelper.hIndent2x,
     182            0 :           if (access == null) ...[
     183            0 :             Text(AppLocale.labels.upTokenSteps, key: const ValueKey('up_steps'), style: textTheme.bodyMedium),
     184              :             ThemeHelper.hIndent2x,
     185            0 :             InputWrapper.text(
     186            0 :               title: AppLocale.labels.upToken,
     187            0 :               tooltip: AppLocale.labels.upTokenTooltip,
     188            0 :               controller: token,
     189              :               isRequired: true,
     190              :             ),
     191              :           ],
     192            0 :           ThemeHelper.hIndent2x,
     193            0 :           if (error != null) ...[
     194            0 :             Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
     195              :             ThemeHelper.hIndent,
     196              :           ],
     197            0 :           if (notice != null) ...[
     198            0 :             Text(notice!, style: textTheme.bodyLarge),
     199              :             ThemeHelper.hIndent,
     200              :           ],
     201            0 :           if (isLoading)
     202            0 :             const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
     203            0 :           else ...[
     204            0 :             accounts.isEmpty
     205            0 :                 ? FullSizedButtonWidget(
     206              :                     key: const ValueKey('up_connect'),
     207              :                     icon: Icons.login,
     208            0 :                     onPressed: connect,
     209            0 :                     title: AppLocale.labels.integrationConnect,
     210              :                   )
     211            0 :                 : FullSizedButtonWidget(
     212              :                     key: const ValueKey('up_disconnect'),
     213              :                     icon: Icons.logout,
     214            0 :                     onPressed: disconnect,
     215            0 :                     title: AppLocale.labels.integrationDisconnect,
     216              :                   ),
     217            0 :             if (access != null)
     218            0 :               Align(
     219              :                 alignment: Alignment.centerRight,
     220            0 :                 child: TextButton.icon(
     221              :                   key: const ValueKey('up_forget'),
     222              :                   icon: const Icon(Icons.link_off),
     223            0 :                   onPressed: forget,
     224            0 :                   label: Text(AppLocale.labels.integrationForget),
     225              :                 ),
     226              :               ),
     227              :           ],
     228            0 :           for (final item in accounts) buildAccount(context, item, state),
     229              :         ],
     230              :       );
     231              :     });
     232              :   }
     233              : }
        

Generated by: LCOV version 2.0-1