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