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

Generated by: LCOV version 2.0-1