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

Generated by: LCOV version 2.0-1