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