LCOV - code coverage report
Current view: top level - lib/pages/integration/widgets - notification_widget.dart Coverage Total Hit
Test: lcov.info Lines: 94.1 % 204 192
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/notification/notification_channel.dart';
       7              : import 'package:app_finance/_classes/integration/notification/notification_controller.dart';
       8              : import 'package:app_finance/_classes/integration/notification/notification_parser.dart';
       9              : import 'package:app_finance/_classes/integration/notification/notification_settings.dart';
      10              : import 'package:app_finance/_classes/storage/app_data.dart';
      11              : import 'package:app_finance/_classes/storage/app_preferences.dart';
      12              : import 'package:app_finance/_classes/structure/account_app_data.dart';
      13              : import 'package:app_finance/_configs/theme_helper.dart';
      14              : import 'package:app_finance/_ext/build_context_ext.dart';
      15              : import 'package:app_finance/design/button/full_sized_button_widget.dart';
      16              : import 'package:app_finance/design/form/tags_input.dart';
      17              : import 'package:app_finance/design/generic/loading_widget.dart';
      18              : import 'package:app_finance/design/wrapper/input_wrapper.dart';
      19              : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
      20              : import 'package:flutter/services.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 NotificationSource extends IntegrationTarget {
      26              :   final String package;
      27              :   final String label;
      28              :   Currency? currency;
      29              : 
      30            1 :   NotificationSource(
      31              :     this.package,
      32              :     this.label, {
      33              :     super.appAccount,
      34              :     super.category,
      35              :     required super.from,
      36              :     this.currency,
      37              :   });
      38              : 
      39            2 :   NotificationApp toLink() => NotificationApp(
      40            1 :         account: appAccount,
      41            1 :         category: category,
      42            1 :         currency: currency?.code,
      43              :       );
      44              : }
      45              : 
      46              : class NotificationWidget extends StatefulWidget {
      47              :   final NotificationChannel channel;
      48              : 
      49            2 :   const NotificationWidget({super.key, this.channel = const NotificationChannel()});
      50              : 
      51            1 :   @override
      52            1 :   NotificationWidgetState createState() => NotificationWidgetState();
      53              : }
      54              : 
      55              : class NotificationWidgetState extends State<NotificationWidget> with WidgetsBindingObserver {
      56              :   late final NotificationSettings settings;
      57              :   // Parsing options shared by all apps
      58              :   late final ValueNotifier<List<String>> income;
      59              :   late final ValueNotifier<List<String>> balance;
      60              :   late final ValueNotifier<List<String>> merchant;
      61              :   // Keywords recognizing the account of a transaction instead of the default one
      62              :   final Map<String, ValueNotifier<List<String>>> accounts = {};
      63              :   bool isGranted = false;
      64              :   bool isLoading = false;
      65              :   Map<String, String> apps = {};
      66              :   Set<String> packages = {};
      67              :   List<NotificationRecord> records = [];
      68              :   final Map<String, NotificationSource> sources = {};
      69              :   String? error;
      70              : 
      71            3 :   NotificationChannel get channel => widget.channel;
      72              : 
      73            2 :   NotificationController get controller => NotificationController.instance;
      74              : 
      75            1 :   @override
      76              :   void initState() {
      77            1 :     super.initState();
      78            2 :     settings = NotificationSettings.load();
      79            7 :     income = ValueNotifier([...settings.income])..addListener(persistKeywords);
      80            7 :     balance = ValueNotifier([...settings.balance])..addListener(persistKeywords);
      81            7 :     merchant = ValueNotifier([...settings.merchant])..addListener(persistKeywords);
      82            2 :     WidgetsBinding.instance.addObserver(this);
      83            4 :     controller.revision.addListener(refresh);
      84            1 :     refresh();
      85              :   }
      86              : 
      87            1 :   @override
      88              :   void dispose() {
      89            2 :     WidgetsBinding.instance.removeObserver(this);
      90            4 :     controller.revision.removeListener(refresh);
      91            2 :     income.dispose();
      92            2 :     balance.dispose();
      93            2 :     merchant.dispose();
      94            3 :     for (final item in accounts.values) {
      95            1 :       item.dispose();
      96              :     }
      97            1 :     super.dispose();
      98              :   }
      99              : 
     100              :   // The access is granted in the system settings, outside of the application
     101            1 :   @override
     102              :   void didChangeAppLifecycleState(AppLifecycleState state) {
     103            1 :     if (state == AppLifecycleState.resumed) {
     104            1 :       refresh();
     105              :     }
     106              :   }
     107              : 
     108            1 :   Future<void> _run(Future<void> Function() callback) async {
     109            1 :     if (!mounted) {
     110              :       return;
     111              :     }
     112            2 :     setState(() {
     113            1 :       isLoading = true;
     114            1 :       error = null;
     115              :     });
     116              :     try {
     117            1 :       await callback();
     118            0 :     } on PlatformException catch (e) {
     119            0 :       error = e.message ?? e.code;
     120            0 :     } on MissingPluginException {
     121            0 :       isGranted = false;
     122              :     } catch (e) {
     123            0 :       error = e.toString();
     124              :     } finally {
     125            1 :       if (mounted) {
     126            3 :         setState(() => isLoading = false);
     127              :       }
     128              :     }
     129              :   }
     130              : 
     131            4 :   NotificationSource source(String package) => sources.putIfAbsent(package, () {
     132            2 :         final link = settings.get(package);
     133            1 :         return NotificationSource(
     134              :           package,
     135            2 :           apps[package] ?? package,
     136            1 :           appAccount: link.account,
     137            2 :           category: link.category ?? AppPreferences.get(AppPreferences.prefBudget),
     138            2 :           from: DateTime.now().subtract(const Duration(days: 30)),
     139            1 :           currency: link.currency != null ? CurrencyProvider.find(link.currency!) : null,
     140              :         );
     141              :       });
     142              : 
     143            1 :   Future<void> persist(String package) async {
     144            2 :     final item = sources[package];
     145              :     if (item == null) {
     146              :       return;
     147              :     }
     148            4 :     settings.apps[package] = item.toLink();
     149            2 :     await settings.save();
     150            2 :     await controller.syncAutoPackages();
     151            1 :     await importLinked();
     152              :   }
     153              : 
     154              :   // Recognized notifications of linked apps are imported right away, the rest wait for adjusted settings
     155            1 :   Future<void> importLinked() async {
     156            7 :     if (!mounted || !settings.apps.values.any((e) => e.isLinked)) {
     157              :       return;
     158              :     }
     159            4 :     controller.attach(Provider.of<AppData>(context, listen: false));
     160            2 :     await controller.run();
     161              :   }
     162              : 
     163            3 :   ValueNotifier<List<String>> accountKeywords(String uuid) => accounts.putIfAbsent(
     164              :         uuid,
     165            8 :         () => ValueNotifier([...?settings.accounts[uuid]])..addListener(persistKeywords),
     166              :       );
     167              : 
     168            8 :   Listenable get keywords => Listenable.merge([income, balance, merchant, ...accounts.values]);
     169              : 
     170            1 :   Future<void> persistKeywords() async {
     171            1 :     settings
     172            4 :       ..income = [...income.value]
     173            4 :       ..balance = [...balance.value]
     174            4 :       ..merchant = [...merchant.value];
     175            8 :     accounts.forEach((uuid, item) => settings.accounts[uuid] = [...item.value]);
     176            2 :     await settings.save();
     177            1 :     await importLinked();
     178              :   }
     179              : 
     180            3 :   Future<void> refresh() => _run(() async {
     181            3 :         isGranted = await channel.isGranted();
     182            1 :         if (!isGranted) {
     183              :           return;
     184              :         }
     185            3 :         apps = await channel.getApps();
     186            3 :         packages = await channel.getPackages();
     187            3 :         records = await channel.getNotifications();
     188              :       });
     189              : 
     190            5 :   Future<void> grant() => _run(() => channel.openSettings());
     191              : 
     192            3 :   Future<void> toggle(String package, bool isSelected) => _run(() async {
     193            2 :         final scope = {...packages};
     194            1 :         isSelected ? scope.add(package) : scope.remove(package);
     195            2 :         await channel.setPackages(scope);
     196            1 :         packages = scope;
     197            3 :         records = await channel.getNotifications();
     198              :       });
     199              : 
     200            3 :   Future<void> clear(NotificationSource item) => _run(() async {
     201           11 :         await channel.removeNotifications(records.where((e) => e.package == item.package).map((e) => e.id));
     202            3 :         records = await channel.getNotifications();
     203              :       });
     204              : 
     205            1 :   Widget buildPreview(BuildContext context, NotificationSource item, List<NotificationRecord> scope, AppData state) {
     206            1 :     final textTheme = context.textTheme;
     207            1 :     final colorScheme = context.colorScheme;
     208            1 :     return Column(
     209              :       crossAxisAlignment: CrossAxisAlignment.stretch,
     210            1 :       children: [
     211            2 :         for (final record in scope.reversed.take(3))
     212            2 :           Builder(builder: (context) {
     213              :             // The same order of currencies as by the import: recognized account, app, default account
     214            6 :             final recognized = NotificationParser.toAccount('${record.title}\n${record.text}', settings.accounts);
     215            1 :             final uuid = recognized ?? item.appAccount;
     216            1 :             final account = uuid != null ? state.getByUuid(uuid) : null;
     217            3 :             final defaultAccount = item.appAccount != null ? state.getByUuid(item.appAccount!) : null;
     218            1 :             final parsed = NotificationParser.parse(
     219            1 :               record.title,
     220            1 :               record.text,
     221            2 :               fallback: (recognized != null && account is AccountAppData ? account.currency : null) ??
     222            1 :                   item.currency ??
     223            2 :                   (defaultAccount is AccountAppData ? defaultAccount.currency : null),
     224            1 :               isBare: item.currency != null,
     225            2 :               income: income.value,
     226            2 :               balance: balance.value,
     227              :             );
     228            1 :             return ListTile(
     229              :               dense: true,
     230              :               contentPadding: EdgeInsets.zero,
     231            1 :               leading: Icon(
     232              :                 parsed != null ? Icons.check_circle_outline : Icons.help_outline,
     233            2 :                 color: parsed != null ? colorScheme.primary : colorScheme.error,
     234              :               ),
     235            1 :               title: Text(
     236              :                 parsed != null
     237            1 :                     ? '${parsed.amount} ${parsed.currency ?? ''} — ${parsed.title}'
     238            3 :                         '${account is AccountAppData ? ' → ${account.title}' : ''}'
     239            2 :                     : AppLocale.labels.notificationUnparsed,
     240            1 :                 style: textTheme.bodyMedium,
     241              :               ),
     242            1 :               subtitle: Text(
     243            8 :                 NotificationParser.toLine([record.title, record.text].where((e) => e.isNotEmpty).join(': ')),
     244            1 :                 style: textTheme.bodySmall,
     245              :               ),
     246              :             );
     247              :           }),
     248              :       ],
     249              :     );
     250              :   }
     251              : 
     252              :   // Keywords are matched case-insensitively
     253            3 :   static String _normalize(String value) => value.trim().toLowerCase();
     254              : 
     255            1 :   Widget buildSource(BuildContext context, NotificationSource item, AppData state) {
     256            7 :     final scope = records.where((e) => e.package == item.package).toList();
     257            1 :     return IntegrationAccountCard(
     258            3 :       key: ValueKey('notification_${item.package}'),
     259            1 :       title: item.label,
     260            3 :       subtitle: AppLocale.labels.notificationCaptured(scope.length),
     261            2 :       accountTitle: AppLocale.labels.notificationDefaultAccount,
     262              :       target: item,
     263              :       state: state,
     264            0 :       onChanged: () {
     265            0 :         setState(() {});
     266            0 :         persist(item.package);
     267              :       },
     268            1 :       children: [
     269            1 :         InputWrapper.currency(
     270            3 :           key: ValueKey('notification_currency_${item.package}'),
     271            2 :           title: AppLocale.labels.currencyDefault,
     272            2 :           tooltip: AppLocale.labels.notificationCurrencyTooltip,
     273            1 :           value: item.currency,
     274            0 :           onChange: (value) {
     275            0 :             setState(() => item.currency = value);
     276            0 :             persist(item.package);
     277              :           },
     278              :         ),
     279            5 :         Text(AppLocale.labels.notificationAutoTooltip, style: context.textTheme.bodySmall),
     280            1 :         ListenableBuilder(
     281            1 :           listenable: keywords,
     282            2 :           builder: (context, _) => buildPreview(context, item, scope, state),
     283              :         ),
     284            1 :         if (scope.isNotEmpty)
     285            1 :           Align(
     286              :             alignment: Alignment.centerRight,
     287            1 :             child: TextButton.icon(
     288              :               icon: const Icon(Icons.delete_sweep_outlined),
     289            3 :               onPressed: isLoading ? null : () => clear(item),
     290            3 :               label: Text(AppLocale.labels.notificationClear),
     291              :             ),
     292              :           ),
     293              :       ],
     294              :     );
     295              :   }
     296              : 
     297            4 :   List<MapEntry<String, String>> _sortedApps() => apps.entries.toList()
     298            2 :     ..sort((a, b) {
     299            5 :       return a.value.toLowerCase().compareTo(b.value.toLowerCase());
     300              :     });
     301              : 
     302            1 :   @override
     303              :   Widget build(BuildContext context) {
     304            1 :     final textTheme = context.textTheme;
     305            1 :     final colorScheme = context.colorScheme;
     306            2 :     return Consumer<AppData>(builder: (context, state, _) {
     307            1 :       return Column(
     308            1 :         crossAxisAlignment: AppDesign.getAlignment(),
     309            1 :         children: [
     310            4 :           Text(AppLocale.labels.notificationDescription, style: textTheme.bodyMedium),
     311              :           ThemeHelper.hIndent2x,
     312            1 :           TagsInput(
     313              :             key: const ValueKey('notification_income'),
     314            2 :             title: AppLocale.labels.notificationIncome,
     315            2 :             tooltip: AppLocale.labels.notificationIncomeTooltip,
     316            1 :             controller: income,
     317              :             defaults: NotificationParser.incomeKeywords,
     318              :             normalize: _normalize,
     319              :           ),
     320            1 :           TagsInput(
     321              :             key: const ValueKey('notification_balance'),
     322            2 :             title: AppLocale.labels.notificationBalance,
     323            2 :             tooltip: AppLocale.labels.notificationBalanceTooltip,
     324            1 :             controller: balance,
     325              :             defaults: NotificationParser.balanceKeywords,
     326              :             normalize: _normalize,
     327              :           ),
     328            1 :           TagsInput(
     329              :             key: const ValueKey('notification_merchant'),
     330            2 :             title: AppLocale.labels.notificationMerchant,
     331            2 :             tooltip: AppLocale.labels.notificationMerchantTooltip,
     332            1 :             controller: merchant,
     333              :             defaults: NotificationParser.merchantLabels,
     334              :             normalize: _normalize,
     335              :           ),
     336            4 :           Text(AppLocale.labels.notificationAccounts, style: textTheme.titleMedium),
     337            4 :           Text(AppLocale.labels.notificationAccountsTooltip, style: textTheme.bodyMedium),
     338              :           ThemeHelper.hIndent,
     339            2 :           for (final account in state.getList(AppDataType.accounts).whereType<AccountAppData>())
     340            1 :             TagsInput(
     341            3 :               key: ValueKey('notification_account_${account.uuid}'),
     342            1 :               title: account.title,
     343            2 :               controller: accountKeywords(account.uuid!),
     344              :               normalize: _normalize,
     345              :             ),
     346            1 :           if (error != null) ...[
     347            0 :             Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
     348              :             ThemeHelper.hIndent,
     349              :           ],
     350            3 :           if (isLoading && apps.isEmpty)
     351            1 :             const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
     352            2 :           else if (!isGranted) ...[
     353            3 :             Text(AppLocale.labels.notificationAccessSteps,
     354            1 :                 key: const ValueKey('notification_steps'), style: textTheme.bodyMedium),
     355              :             ThemeHelper.hIndent2x,
     356            1 :             FullSizedButtonWidget(
     357              :               key: const ValueKey('notification_grant'),
     358              :               icon: Icons.notifications_active_outlined,
     359            1 :               onPressed: grant,
     360            2 :               title: AppLocale.labels.notificationGrant,
     361              :             ),
     362            1 :           ] else ...[
     363            4 :             Text(AppLocale.labels.notificationApps, style: textTheme.titleMedium),
     364            2 :             if (apps.isEmpty) Text(AppLocale.labels.notificationNoApps, style: textTheme.bodyMedium),
     365            1 :             for (final app in _sortedApps())
     366            1 :               SwitchListTile(
     367            3 :                 key: ValueKey('notification_app_${app.key}'),
     368              :                 contentPadding: EdgeInsets.zero,
     369            2 :                 title: Text(app.value),
     370            3 :                 subtitle: Text(app.key, style: textTheme.bodySmall),
     371            3 :                 value: packages.contains(app.key),
     372            4 :                 onChanged: isLoading ? null : (value) => toggle(app.key, value),
     373              :               ),
     374            3 :             for (final package in packages) buildSource(context, source(package), state),
     375            1 :             Align(
     376              :               alignment: Alignment.centerRight,
     377            1 :               child: TextButton.icon(
     378              :                 key: const ValueKey('notification_settings'),
     379              :                 icon: const Icon(Icons.settings_outlined),
     380            1 :                 onPressed: grant,
     381            3 :                 label: Text(AppLocale.labels.notificationAccessSettings),
     382              :               ),
     383              :             ),
     384              :           ],
     385              :         ],
     386              :       );
     387              :     });
     388              :   }
     389              : }
        

Generated by: LCOV version 2.0-1