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/investec/investec_client.dart';
7 : import 'package:app_finance/_classes/integration/investec/investec_importer.dart';
8 : import 'package:app_finance/_classes/integration/investec/investec_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:http/http.dart' as http;
19 : import 'package:material_ui/material_ui.dart';
20 : import 'package:provider/provider.dart';
21 :
22 : class InvestecBankAccount extends IntegrationTarget {
23 : final InvestecAccount account;
24 : InvestecBalance? balance;
25 :
26 0 : InvestecBankAccount(this.account, {super.appAccount, super.category, required super.from});
27 :
28 : // South African Rand, unless the bank tells otherwise
29 0 : String get currency => balance?.currency ?? 'ZAR';
30 : }
31 :
32 : class InvestecWidget extends StatefulWidget {
33 : final http.Client? httpClient;
34 :
35 1 : const InvestecWidget({super.key, this.httpClient});
36 :
37 0 : @override
38 0 : InvestecWidgetState createState() => InvestecWidgetState();
39 : }
40 :
41 : class InvestecWidgetState extends State<InvestecWidget> {
42 : late final InvestecSettings settings;
43 : final clientId = TextEditingController();
44 : final secret = TextEditingController();
45 : final apiKey = TextEditingController();
46 : InvestecCredentials? credentials;
47 : // Keeps the bearer token between requests (valid for 30 minutes)
48 : InvestecClient? _client;
49 : List<InvestecBankAccount> accounts = [];
50 : bool isLoading = false;
51 : String? error;
52 : String? notice;
53 :
54 0 : @override
55 : void initState() {
56 0 : super.initState();
57 0 : settings = InvestecSettings.load();
58 0 : credentials = InvestecSettings.loadCredentials();
59 : }
60 :
61 0 : @override
62 : void dispose() {
63 0 : for (final controller in [clientId, secret, apiKey]) {
64 0 : controller.dispose();
65 : }
66 0 : _closeClient();
67 0 : super.dispose();
68 : }
69 :
70 0 : void _closeClient() {
71 0 : if (widget.httpClient == null) {
72 0 : _client?.close();
73 : }
74 0 : _client = null;
75 : }
76 :
77 0 : InvestecClient get client =>
78 0 : _client ??= InvestecClient(client: widget.httpClient ?? http.Client(), sandbox: settings.sandbox);
79 :
80 0 : Future<void> _run(Future<void> Function() callback) async {
81 0 : setState(() {
82 0 : isLoading = true;
83 0 : error = null;
84 0 : notice = null;
85 : });
86 : try {
87 0 : await callback();
88 0 : } on InvestecException catch (e) {
89 0 : error = e.message;
90 : } catch (e) {
91 0 : error = e.toString();
92 : } finally {
93 0 : if (mounted) {
94 0 : setState(() => isLoading = false);
95 : }
96 : }
97 : }
98 :
99 0 : Future<void> setSandbox(bool value) async {
100 0 : setState(() => settings.sandbox = value);
101 0 : _closeClient();
102 0 : await settings.save();
103 : }
104 :
105 0 : Future<void> connect() => _run(() async {
106 0 : var current = credentials;
107 : if (current == null) {
108 0 : final entered = (clientId: clientId.text.trim(), secret: secret.text.trim(), apiKey: apiKey.text.trim());
109 0 : if (entered.clientId.isEmpty || entered.secret.isEmpty || entered.apiKey.isEmpty) {
110 0 : throw InvestecException(AppLocale.labels.investecIncomplete);
111 : }
112 : current = entered;
113 : }
114 0 : final items = await client.getAccounts(current);
115 : // Stored only after the bank has accepted them
116 0 : if (credentials == null) {
117 0 : await InvestecSettings.saveCredentials(current);
118 0 : await settings.save();
119 0 : credentials = current;
120 0 : for (final controller in [clientId, secret, apiKey]) {
121 0 : controller.clear();
122 : }
123 : }
124 0 : final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
125 0 : final monthAgo = DateTime.now().subtract(const Duration(days: 30));
126 0 : accounts = items
127 0 : .map((account) => InvestecBankAccount(
128 : account,
129 0 : appAccount: settings.links[account.id],
130 : category: defaultBudget,
131 0 : from: settings.imported[account.id] ?? monthAgo,
132 : ))
133 0 : .toList();
134 0 : for (final item in accounts) {
135 : try {
136 0 : item.balance = await client.getBalance(current, item.account.id);
137 0 : } on InvestecException {
138 : // The balance is optional for the import
139 : }
140 : }
141 0 : if (accounts.isEmpty) {
142 0 : notice = AppLocale.labels.integrationNoAccounts;
143 : }
144 : });
145 :
146 0 : Future<void> disconnect() => _run(() async => accounts = []);
147 :
148 0 : Future<void> forget() => _run(() async {
149 0 : await InvestecSettings.clearCredentials();
150 0 : credentials = null;
151 0 : accounts = [];
152 0 : _closeClient();
153 : });
154 :
155 0 : Future<void> importTransactions(InvestecBankAccount item) => _run(() async {
156 0 : final current = credentials;
157 : if (current == null) {
158 : return;
159 : }
160 0 : if (item.appAccount == null || item.category == null) {
161 0 : throw InvestecException(AppLocale.labels.integrationSelectTarget);
162 : }
163 0 : final state = Provider.of<AppData>(context, listen: false);
164 0 : final id = item.account.id;
165 0 : final transactions = await client.getTransactions(current, id, from: item.from);
166 0 : final importer = InvestecImporter(
167 0 : exists: (uuid) => state.getByUuid(uuid) != null,
168 0 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
169 : );
170 0 : final summary = importer.run(
171 : accountId: id,
172 0 : currency: item.currency,
173 : transactions: transactions,
174 0 : account: item.appAccount!,
175 0 : category: item.category!,
176 0 : prediction: state.prediction,
177 : );
178 0 : await state.restate();
179 0 : final today = DateTime.now();
180 0 : settings.links[id] = item.appAccount!;
181 0 : settings.imported[id] = DateTime(today.year, today.month, today.day);
182 0 : await settings.save();
183 0 : notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
184 : });
185 :
186 0 : Widget buildAccount(BuildContext context, InvestecBankAccount item, AppData state) {
187 0 : final balance = item.balance;
188 0 : return IntegrationAccountCard(
189 0 : title: item.account.title,
190 0 : subtitle: balance != null ? '${AppLocale.labels.balance}: ${balance.current} ${balance.currency}' : null,
191 : target: item,
192 : state: state,
193 0 : isDisabled: isLoading,
194 0 : onChanged: () => setState(() {}),
195 0 : onImport: () => importTransactions(item),
196 : );
197 : }
198 :
199 0 : Widget buildCredentials(BuildContext context) => Column(
200 0 : crossAxisAlignment: AppDesign.getAlignment(),
201 0 : children: [
202 0 : Text(
203 0 : AppLocale.labels.investecSteps,
204 : key: const ValueKey('investec_steps'),
205 0 : style: context.textTheme.bodyMedium,
206 : ),
207 : ThemeHelper.hIndent2x,
208 0 : InputWrapper.text(
209 0 : title: AppLocale.labels.investecClientId,
210 0 : tooltip: AppLocale.labels.investecCredentialsTooltip,
211 0 : controller: clientId,
212 : isRequired: true,
213 : ),
214 0 : InputWrapper.text(
215 0 : title: AppLocale.labels.investecSecret,
216 0 : tooltip: AppLocale.labels.investecCredentialsTooltip,
217 0 : controller: secret,
218 : isRequired: true,
219 : ),
220 0 : InputWrapper.text(
221 0 : title: AppLocale.labels.investecApiKey,
222 0 : tooltip: AppLocale.labels.investecCredentialsTooltip,
223 0 : controller: apiKey,
224 : isRequired: true,
225 : ),
226 0 : SwitchListTile(
227 : key: const ValueKey('investec_sandbox'),
228 : contentPadding: EdgeInsets.zero,
229 0 : title: Text(AppLocale.labels.investecSandbox),
230 0 : value: settings.sandbox,
231 0 : onChanged: isLoading ? null : setSandbox,
232 : ),
233 : ],
234 : );
235 :
236 0 : @override
237 : Widget build(BuildContext context) {
238 0 : final textTheme = context.textTheme;
239 0 : final colorScheme = context.colorScheme;
240 0 : return Consumer<AppData>(builder: (context, state, _) {
241 0 : return Column(
242 0 : crossAxisAlignment: AppDesign.getAlignment(),
243 0 : children: [
244 0 : Text(AppLocale.labels.investecDescription, style: textTheme.bodyMedium),
245 : ThemeHelper.hIndent2x,
246 0 : if (credentials == null) buildCredentials(context),
247 0 : ThemeHelper.hIndent2x,
248 0 : if (error != null) ...[
249 0 : Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
250 : ThemeHelper.hIndent,
251 : ],
252 0 : if (notice != null) ...[
253 0 : Text(notice!, style: textTheme.bodyLarge),
254 : ThemeHelper.hIndent,
255 : ],
256 0 : if (isLoading)
257 0 : const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
258 0 : else ...[
259 0 : accounts.isEmpty
260 0 : ? FullSizedButtonWidget(
261 : key: const ValueKey('investec_connect'),
262 : icon: Icons.login,
263 0 : onPressed: connect,
264 0 : title: AppLocale.labels.integrationConnect,
265 : )
266 0 : : FullSizedButtonWidget(
267 : key: const ValueKey('investec_disconnect'),
268 : icon: Icons.logout,
269 0 : onPressed: disconnect,
270 0 : title: AppLocale.labels.integrationDisconnect,
271 : ),
272 0 : if (credentials != null)
273 0 : Align(
274 : alignment: Alignment.centerRight,
275 0 : child: TextButton.icon(
276 : key: const ValueKey('investec_forget'),
277 : icon: const Icon(Icons.link_off),
278 0 : onPressed: forget,
279 0 : label: Text(AppLocale.labels.integrationForget),
280 : ),
281 : ),
282 : ],
283 0 : for (final item in accounts) buildAccount(context, item, state),
284 : ],
285 : );
286 : });
287 : }
288 : }
|