LCOV - code coverage report
Current view: top level - lib/pages/integration/widgets - teller_widget.dart Coverage Total Hit
Test: lcov.info Lines: 86.9 % 237 206
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/controller/deep_link/deep_link_handler.dart';
       5              : import 'package:app_finance/_classes/herald/app_design.dart';
       6              : import 'package:app_finance/_classes/herald/app_locale.dart';
       7              : import 'package:app_finance/_classes/integration/teller/teller_client.dart';
       8              : import 'package:app_finance/_classes/integration/teller/teller_http.dart';
       9              : import 'package:app_finance/_classes/integration/teller/teller_importer.dart';
      10              : import 'package:app_finance/_classes/integration/teller/teller_settings.dart';
      11              : import 'package:app_finance/_classes/storage/app_data.dart';
      12              : import 'package:app_finance/_classes/storage/app_preferences.dart';
      13              : import 'package:app_finance/_classes/storage/transaction_log.dart';
      14              : import 'package:app_finance/_configs/theme_helper.dart';
      15              : import 'package:app_finance/_ext/build_context_ext.dart';
      16              : import 'package:app_finance/_mixins/file/file_import_mixin.dart';
      17              : import 'package:app_finance/design/button/full_sized_button_widget.dart';
      18              : import 'package:app_finance/design/form/list_selector_item.dart';
      19              : import 'package:app_finance/design/generic/loading_widget.dart';
      20              : import 'package:app_finance/design/wrapper/input_wrapper.dart';
      21              : import 'package:app_finance/pages/integration/widgets/enablebanking_widget.dart' show UrlLauncher;
      22              : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
      23              : import 'package:http/http.dart' as http;
      24              : import 'package:material_ui/material_ui.dart';
      25              : import 'package:provider/provider.dart';
      26              : import 'package:url_launcher/url_launcher.dart';
      27              : 
      28              : class TellerBankAccount extends IntegrationTarget {
      29              :   final TellerAccount account;
      30              :   final TellerEnrollment enrollment;
      31              :   TellerBalance? balance;
      32              : 
      33            1 :   TellerBankAccount(this.account, this.enrollment, {super.appAccount, super.category, required super.from});
      34              : 
      35            1 :   String get title {
      36            2 :     final institution = account.institution ?? enrollment.institution;
      37            8 :     final number = account.lastFour != null && account.lastFour!.isNotEmpty ? '…${account.lastFour}' : '';
      38            1 :     return [
      39              :       institution,
      40            7 :       [account.name, number].where((e) => e.isNotEmpty).join(' '),
      41            4 :     ].where((e) => e.isNotEmpty).join(' — ');
      42              :   }
      43              : }
      44              : 
      45              : class TellerWidget extends StatefulWidget {
      46              :   final http.Client? httpClient;
      47              :   final UrlLauncher? launcher;
      48              : 
      49            3 :   const TellerWidget({super.key, this.httpClient, this.launcher});
      50              : 
      51            1 :   @override
      52            1 :   TellerWidgetState createState() => TellerWidgetState();
      53              : }
      54              : 
      55              : class TellerWidgetState extends State<TellerWidget> with FileImportMixin {
      56              :   // Pending transactions may get an earlier date when posted: a repeated import looks back for them
      57              :   static const postingDelay = Duration(days: 10);
      58              : 
      59              :   late final TellerSettings settings;
      60              :   late final TextEditingController applicationId;
      61              :   late final TextEditingController connectPage;
      62              :   final certificate = TextEditingController();
      63              :   final privateKey = TextEditingController();
      64              :   final accessToken = TextEditingController();
      65              :   List<TellerEnrollment> enrollments = [];
      66              :   List<TellerBankAccount> accounts = [];
      67              :   // Enrollment to be repaired by Teller Connect (new login, MFA, ...)
      68              :   String? disconnected;
      69              :   bool isLoading = false;
      70              :   String? error;
      71              :   String? notice;
      72              : 
      73            1 :   @override
      74              :   void initState() {
      75            1 :     super.initState();
      76            2 :     settings = TellerSettings.load();
      77            2 :     enrollments = TellerSettings.loadEnrollments();
      78            4 :     applicationId = TextEditingController(text: settings.applicationId);
      79            2 :     connectPage = TextEditingController(
      80            3 :       text: settings.connectPage.isEmpty ? TellerSettings.defaultConnectPage : settings.connectPage,
      81              :     );
      82            3 :     DeepLinkHandler.tellerCallback.addListener(onLink);
      83              :     // A callback that came before this section was open (e.g. the application was started by it)
      84            4 :     WidgetsBinding.instance.addPostFrameCallback((_) => onLink());
      85              :   }
      86              : 
      87            1 :   @override
      88              :   void dispose() {
      89            3 :     DeepLinkHandler.tellerCallback.removeListener(onLink);
      90            7 :     for (final controller in [applicationId, connectPage, certificate, privateKey, accessToken]) {
      91            1 :       controller.dispose();
      92              :     }
      93            1 :     super.dispose();
      94              :   }
      95              : 
      96            2 :   bool get hasCertificate => TellerSettings.loadCertificate() != null && TellerSettings.loadKey() != null;
      97              : 
      98            1 :   Future<void> _run(Future<void> Function(TellerClient client) callback) async {
      99            2 :     setState(() {
     100            1 :       isLoading = true;
     101            1 :       error = null;
     102            1 :       notice = null;
     103              :     });
     104              :     TellerClient? client;
     105              :     try {
     106            1 :       await saveSettings();
     107            1 :       final cert = TellerSettings.loadCertificate();
     108            1 :       final key = TellerSettings.loadKey();
     109            3 :       if (settings.environment.requiresCertificate && (cert == null || key == null)) {
     110            3 :         throw TellerException(AppLocale.labels.tellerIncomplete);
     111              :       }
     112            1 :       client = TellerClient(
     113            2 :         client: widget.httpClient ?? createTellerHttpClient(certificate: cert, privateKey: key),
     114              :       );
     115            1 :       await callback(client);
     116            1 :     } on TellerException catch (e) {
     117            2 :       error = e.message;
     118              :     } catch (e) {
     119            0 :       error = e.toString();
     120              :     } finally {
     121            2 :       if (widget.httpClient == null) {
     122            0 :         client?.close();
     123              :       }
     124            1 :       if (mounted) {
     125            3 :         setState(() => isLoading = false);
     126              :       }
     127              :     }
     128              :   }
     129              : 
     130            1 :   Future<void> saveSettings() async {
     131            3 :     final cert = certificate.text.trim();
     132            3 :     final key = privateKey.text.trim();
     133              :     // Both are validated before either is stored
     134            1 :     final normalizedCert = cert.isNotEmpty ? TellerClient.normalizeCertificate(cert) : null;
     135            1 :     final normalizedKey = key.isNotEmpty ? TellerClient.normalizePrivateKey(key) : null;
     136              :     if (normalizedCert != null) {
     137            0 :       await TellerSettings.saveCertificate(normalizedCert);
     138            0 :       certificate.clear();
     139              :     }
     140              :     if (normalizedKey != null) {
     141            0 :       await TellerSettings.saveKey(normalizedKey);
     142            0 :       privateKey.clear();
     143              :     }
     144            3 :     final page = connectPage.text.trim();
     145            1 :     settings
     146            4 :       ..applicationId = applicationId.text.trim()
     147            2 :       ..connectPage = page == TellerSettings.defaultConnectPage ? '' : page;
     148            2 :     await settings.save();
     149              :   }
     150              : 
     151            0 :   Future<void> upload(TextEditingController controller) async {
     152            0 :     final content = await importFile(['pem', 'crt', 'cer', 'key']);
     153            0 :     if (content != null && mounted) {
     154            0 :       setState(() => controller.text = content);
     155              :     }
     156              :   }
     157              : 
     158            1 :   void onLink() {
     159            3 :     if (!mounted || DeepLinkHandler.tellerCallback.value == null) {
     160              :       return;
     161              :     }
     162            1 :     if (isLoading) {
     163            0 :       Future.delayed(const Duration(milliseconds: 300), onLink);
     164              :       return;
     165              :     }
     166            1 :     final link = DeepLinkHandler.takeTellerCallback()!;
     167            2 :     connect(enrollment: TellerEnrollment.fromLink(link));
     168              :   }
     169              : 
     170              :   // Teller Connect is a JavaScript widget: it is opened by the connection page in a browser
     171            3 :   Future<void> connectBank() => _run((_) async {
     172            3 :         if (settings.applicationId.isEmpty) {
     173            0 :           throw TellerException(AppLocale.labels.tellerIncomplete);
     174              :         }
     175            3 :         final page = settings.connectUrl(enrollmentId: disconnected);
     176            2 :         if (page.scheme != 'https') {
     177            0 :           throw TellerException(AppLocale.labels.integrationHttpsRequired);
     178              :         }
     179            3 :         await (widget.launcher ?? (uri) => launchUrl(uri, mode: LaunchMode.externalApplication))(page);
     180              :       });
     181              : 
     182              :   // [enrollment] comes from the connection page (deep link); the access token field is filled in manually
     183            3 :   Future<void> connect({TellerEnrollment? enrollment}) => _run((client) async {
     184            0 :         final added = enrollment ?? TellerEnrollment.parse(accessToken.text);
     185              :         if (added != null) {
     186              :           // The token is checked before it is stored
     187            2 :           await client.getAccounts(added.accessToken);
     188            3 :           enrollments = TellerSettings.merge(enrollments, added);
     189            2 :           await TellerSettings.saveEnrollments(enrollments);
     190            2 :           accessToken.clear();
     191            3 :           if (added.id == disconnected) {
     192            0 :             disconnected = null;
     193              :           }
     194              :         }
     195            2 :         if (enrollments.isEmpty) {
     196            0 :           throw TellerException(AppLocale.labels.tellerAccessToken);
     197              :         }
     198            1 :         await _loadAccounts(client);
     199              :       });
     200              : 
     201            1 :   Future<void> _loadAccounts(TellerClient client) async {
     202            1 :     final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
     203            2 :     final monthAgo = DateTime.now().subtract(const Duration(days: 30));
     204            1 :     final errors = <String>[];
     205            1 :     final result = <TellerBankAccount>[];
     206            2 :     for (final enrollment in enrollments) {
     207              :       try {
     208            2 :         final items = await client.getAccounts(enrollment.accessToken);
     209            4 :         for (final account in items.where((e) => e.isOpen)) {
     210            1 :           final item = TellerBankAccount(
     211              :             account,
     212              :             enrollment,
     213            4 :             appAccount: settings.links[account.id],
     214              :             category: defaultBudget,
     215            4 :             from: settings.imported[account.id] ?? monthAgo,
     216              :           );
     217              :           try {
     218            4 :             item.balance = await client.getBalances(enrollment.accessToken, account.id);
     219            0 :           } on TellerException catch (e) {
     220            0 :             if (e.isDisconnected) {
     221              :               rethrow;
     222              :             }
     223              :             // Balances are optional for the import
     224              :           }
     225            1 :           result.add(item);
     226              :         }
     227            0 :       } on TellerException catch (e) {
     228            0 :         if (e.isDisconnected) {
     229            0 :           disconnected = enrollment.id.isNotEmpty ? enrollment.id : disconnected;
     230              :         }
     231            0 :         final name = enrollment.institution.isNotEmpty ? '${enrollment.institution}: ' : '';
     232            0 :         errors.add('$name${e.message}');
     233              :       }
     234              :     }
     235            1 :     accounts = result;
     236            1 :     if (errors.isNotEmpty) {
     237            0 :       error = errors.join('\n');
     238            2 :     } else if (accounts.isEmpty) {
     239            0 :       notice = AppLocale.labels.integrationNoAccounts;
     240              :     }
     241              :   }
     242              : 
     243            0 :   Future<void> disconnect() async => setState(() => accounts = []);
     244              : 
     245            3 :   Future<void> forget() => _run((client) async {
     246            1 :         final current = enrollments;
     247            2 :         enrollments = [];
     248            2 :         accounts = [];
     249            1 :         disconnected = null;
     250            2 :         await TellerSettings.saveEnrollments(enrollments);
     251            2 :         for (final enrollment in current) {
     252              :           try {
     253            2 :             await client.deleteEnrollment(enrollment.accessToken);
     254            0 :           } on TellerException {
     255              :             // Already revoked or disconnected: nothing else to do
     256              :           }
     257              :         }
     258              :       });
     259              : 
     260            3 :   Future<void> importTransactions(TellerBankAccount item) => _run((client) async {
     261            2 :         if (item.appAccount == null || item.category == null) {
     262            0 :           throw TellerException(AppLocale.labels.integrationSelectTarget);
     263              :         }
     264            2 :         final state = Provider.of<AppData>(context, listen: false);
     265            2 :         final id = item.account.id;
     266            3 :         final last = settings.imported[id];
     267            5 :         final from = last != null && !item.from.isAfter(last) ? item.from.subtract(postingDelay) : item.from;
     268              :         final List<TellerTransaction> transactions;
     269              :         try {
     270            3 :           transactions = await client.getTransactions(item.enrollment.accessToken, id, from: from);
     271            1 :         } on TellerException catch (e) {
     272            4 :           if (e.isDisconnected && item.enrollment.id.isNotEmpty) {
     273            3 :             disconnected = item.enrollment.id;
     274              :           }
     275              :           rethrow;
     276              :         }
     277            1 :         final importer = TellerImporter(
     278            2 :           exists: (uuid) => state.getByUuid(uuid) != null,
     279            3 :           add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
     280              :         );
     281            1 :         final summary = importer.run(
     282            1 :           source: item.account,
     283              :           transactions: transactions,
     284            1 :           account: item.appAccount!,
     285            1 :           category: item.category!,
     286            1 :           prediction: state.prediction,
     287              :         );
     288            1 :         await state.restate();
     289            1 :         final today = DateTime.now();
     290            4 :         settings.links[id] = item.appAccount!;
     291            7 :         settings.imported[id] = DateTime(today.year, today.month, today.day);
     292            2 :         await settings.save();
     293            3 :         notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
     294              :       });
     295              : 
     296            2 :   Widget buildUpload(String key, TextEditingController controller) => Align(
     297              :         alignment: Alignment.centerRight,
     298            1 :         child: TextButton.icon(
     299            2 :           key: ValueKey('teller_upload_$key'),
     300              :           icon: const Icon(Icons.upload_file),
     301            1 :           onPressed: isLoading ? null : () => upload(controller),
     302            3 :           label: Text(AppLocale.labels.tellerUpload),
     303              :         ),
     304              :       );
     305              : 
     306            1 :   Widget buildSettings(BuildContext context) {
     307            1 :     final stored = hasCertificate;
     308            1 :     return Column(
     309            1 :       crossAxisAlignment: AppDesign.getAlignment(),
     310            1 :       children: [
     311            5 :         Text(AppLocale.labels.tellerSteps, style: context.textTheme.bodyMedium),
     312              :         ThemeHelper.hIndent2x,
     313            1 :         InputWrapper.text(
     314            2 :           title: AppLocale.labels.tellerAppId,
     315            2 :           tooltip: AppLocale.labels.tellerAppIdTooltip,
     316            1 :           controller: applicationId,
     317              :           isRequired: true,
     318              :         ),
     319            1 :         InputWrapper.select(
     320            2 :           title: AppLocale.labels.tellerEnvironment,
     321            3 :           value: settings.environment.name,
     322              :           isRequired: true,
     323            1 :           options: <ListSelectorItem>[
     324            4 :             for (final env in TellerEnvironment.values) ListSelectorItem(id: env.name, name: env.name),
     325              :           ],
     326            0 :           onChange: (value) => setState(() => settings.environment = TellerEnvironment.parse(value)),
     327              :         ),
     328            1 :         if (isTellerCertificateSupported) ...[
     329            1 :           InputWrapper.text(
     330            2 :             title: AppLocale.labels.tellerCertificate,
     331            2 :             tooltip: AppLocale.labels.tellerCertificateTooltip,
     332            1 :             controller: certificate,
     333            3 :             isRequired: settings.environment.requiresCertificate && !stored,
     334              :           ),
     335            2 :           buildUpload('certificate', certificate),
     336            1 :           InputWrapper.text(
     337            2 :             title: AppLocale.labels.tellerKey,
     338            2 :             tooltip: AppLocale.labels.tellerKeyTooltip,
     339            1 :             controller: privateKey,
     340            3 :             isRequired: settings.environment.requiresCertificate && !stored,
     341              :           ),
     342            2 :           buildUpload('key', privateKey),
     343              :         ],
     344            1 :         InputWrapper.text(
     345            2 :           title: AppLocale.labels.tellerConnectPage,
     346            2 :           tooltip: AppLocale.labels.tellerConnectPageTooltip,
     347            1 :           controller: connectPage,
     348              :           isRequired: true,
     349              :           inputType: TextInputType.url,
     350              :         ),
     351            1 :         Align(
     352              :           alignment: Alignment.centerRight,
     353            1 :           child: TextButton.icon(
     354              :             key: const ValueKey('teller_connect_bank'),
     355              :             icon: const Icon(Icons.account_balance),
     356            2 :             onPressed: isLoading ? null : connectBank,
     357            3 :             label: Text(AppLocale.labels.tellerConnectBank),
     358              :           ),
     359              :         ),
     360            1 :         InputWrapper.text(
     361            2 :           title: AppLocale.labels.tellerAccessToken,
     362            2 :           tooltip: AppLocale.labels.tellerAccessTokenTooltip,
     363            1 :           controller: accessToken,
     364            2 :           isRequired: enrollments.isEmpty,
     365              :         ),
     366              :       ],
     367              :     );
     368              :   }
     369              : 
     370            1 :   Widget buildAccount(BuildContext context, TellerBankAccount item, AppData state) {
     371            2 :     final amount = item.balance?.amount;
     372            1 :     return IntegrationAccountCard(
     373            1 :       title: item.title,
     374            5 :       subtitle: amount != null ? '${AppLocale.labels.balance}: $amount ${item.account.currency}' : null,
     375              :       target: item,
     376              :       state: state,
     377            1 :       isDisabled: isLoading,
     378            0 :       onChanged: () => setState(() {}),
     379            2 :       onImport: () => importTransactions(item),
     380              :     );
     381              :   }
     382              : 
     383            1 :   @override
     384              :   Widget build(BuildContext context) {
     385            1 :     final textTheme = context.textTheme;
     386            1 :     final colorScheme = context.colorScheme;
     387            2 :     return Consumer<AppData>(builder: (context, state, _) {
     388            1 :       return Column(
     389            1 :         crossAxisAlignment: AppDesign.getAlignment(),
     390            1 :         children: [
     391            4 :           Text(AppLocale.labels.tellerDescription, style: textTheme.bodyMedium),
     392              :           ThemeHelper.hIndent2x,
     393            3 :           if (accounts.isEmpty) buildSettings(context),
     394            1 :           ThemeHelper.hIndent2x,
     395            2 :           if (error != null) ...[
     396            5 :             Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
     397              :             ThemeHelper.hIndent,
     398              :           ],
     399            2 :           if (notice != null) ...[
     400            3 :             Text(notice!, style: textTheme.bodyLarge),
     401              :             ThemeHelper.hIndent,
     402              :           ],
     403            1 :           if (isLoading)
     404            0 :             const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
     405            1 :           else ...[
     406            2 :             if (accounts.isNotEmpty)
     407            1 :               FullSizedButtonWidget(
     408              :                 key: const ValueKey('teller_disconnect'),
     409              :                 icon: Icons.logout,
     410            1 :                 onPressed: disconnect,
     411            2 :                 title: AppLocale.labels.integrationDisconnect,
     412              :               )
     413              :             else
     414            1 :               FullSizedButtonWidget(
     415              :                 key: const ValueKey('teller_connect'),
     416              :                 icon: Icons.login,
     417            1 :                 onPressed: connect,
     418            2 :                 title: AppLocale.labels.integrationConnect,
     419              :               ),
     420            3 :             if (accounts.isNotEmpty || disconnected != null)
     421            1 :               Align(
     422              :                 alignment: Alignment.centerRight,
     423            1 :                 child: TextButton.icon(
     424              :                   key: const ValueKey('teller_add_bank'),
     425              :                   icon: const Icon(Icons.add_link),
     426            1 :                   onPressed: connectBank,
     427            3 :                   label: Text(AppLocale.labels.tellerConnectBank),
     428              :                 ),
     429              :               ),
     430            2 :             if (enrollments.isNotEmpty)
     431            1 :               Align(
     432              :                 alignment: Alignment.centerRight,
     433            1 :                 child: TextButton.icon(
     434              :                   key: const ValueKey('teller_forget'),
     435              :                   icon: const Icon(Icons.link_off),
     436            1 :                   onPressed: forget,
     437            3 :                   label: Text(AppLocale.labels.integrationForget),
     438              :                 ),
     439              :               ),
     440              :           ],
     441            2 :           for (final item in accounts) buildAccount(context, item, state),
     442              :         ],
     443              :       );
     444              :     });
     445              :   }
     446              : }
        

Generated by: LCOV version 2.0-1