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/controller/deep_link/deep_link_handler.dart';
5 : import 'package:app_finance/_classes/herald/app_design.dart';
6 : import 'package:app_finance/_classes/herald/app_locale.dart';
7 : import 'package:app_finance/_classes/integration/teller/teller_client.dart';
8 : import 'package:app_finance/_classes/integration/teller/teller_http.dart';
9 : import 'package:app_finance/_classes/integration/teller/teller_importer.dart';
10 : import 'package:app_finance/_classes/integration/teller/teller_settings.dart';
11 : import 'package:app_finance/_classes/storage/app_data.dart';
12 : import 'package:app_finance/_classes/storage/app_preferences.dart';
13 : import 'package:app_finance/_classes/storage/transaction_log.dart';
14 : import 'package:app_finance/_configs/theme_helper.dart';
15 : import 'package:app_finance/_ext/build_context_ext.dart';
16 : import 'package:app_finance/_mixins/file/file_import_mixin.dart';
17 : import 'package:app_finance/design/button/full_sized_button_widget.dart';
18 : import 'package:app_finance/design/form/list_selector_item.dart';
19 : import 'package:app_finance/design/generic/loading_widget.dart';
20 : import 'package:app_finance/design/wrapper/input_wrapper.dart';
21 : import 'package:app_finance/pages/integration/widgets/enablebanking_widget.dart' show UrlLauncher;
22 : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
23 : import 'package:http/http.dart' as http;
24 : import 'package:material_ui/material_ui.dart';
25 : import 'package:provider/provider.dart';
26 : import 'package:url_launcher/url_launcher.dart';
27 :
28 : class TellerBankAccount extends IntegrationTarget {
29 : final TellerAccount account;
30 : final TellerEnrollment enrollment;
31 : TellerBalance? balance;
32 :
33 0 : TellerBankAccount(this.account, this.enrollment, {super.appAccount, super.category, required super.from});
34 :
35 0 : String get title {
36 0 : final institution = account.institution ?? enrollment.institution;
37 0 : final number = account.lastFour != null && account.lastFour!.isNotEmpty ? '…${account.lastFour}' : '';
38 0 : return [
39 : institution,
40 0 : [account.name, number].where((e) => e.isNotEmpty).join(' '),
41 0 : ].where((e) => e.isNotEmpty).join(' — ');
42 : }
43 : }
44 :
45 : class TellerWidget extends StatefulWidget {
46 : final http.Client? httpClient;
47 : final UrlLauncher? launcher;
48 :
49 1 : const TellerWidget({super.key, this.httpClient, this.launcher});
50 :
51 0 : @override
52 0 : TellerWidgetState createState() => TellerWidgetState();
53 : }
54 :
55 : class TellerWidgetState extends State<TellerWidget> with FileImportMixin {
56 : // Pending transactions may get an earlier date when posted: a repeated import looks back for them
57 : static const postingDelay = Duration(days: 10);
58 :
59 : late final TellerSettings settings;
60 : late final TextEditingController applicationId;
61 : late final TextEditingController connectPage;
62 : final certificate = TextEditingController();
63 : final privateKey = TextEditingController();
64 : final accessToken = TextEditingController();
65 : List<TellerEnrollment> enrollments = [];
66 : List<TellerBankAccount> accounts = [];
67 : // Enrollment to be repaired by Teller Connect (new login, MFA, ...)
68 : String? disconnected;
69 : bool isLoading = false;
70 : String? error;
71 : String? notice;
72 :
73 0 : @override
74 : void initState() {
75 0 : super.initState();
76 0 : settings = TellerSettings.load();
77 0 : enrollments = TellerSettings.loadEnrollments();
78 0 : applicationId = TextEditingController(text: settings.applicationId);
79 0 : connectPage = TextEditingController(
80 0 : text: settings.connectPage.isEmpty ? TellerSettings.defaultConnectPage : settings.connectPage,
81 : );
82 0 : DeepLinkHandler.tellerCallback.addListener(onLink);
83 : // A callback that came before this section was open (e.g. the application was started by it)
84 0 : WidgetsBinding.instance.addPostFrameCallback((_) => onLink());
85 : }
86 :
87 0 : @override
88 : void dispose() {
89 0 : DeepLinkHandler.tellerCallback.removeListener(onLink);
90 0 : for (final controller in [applicationId, connectPage, certificate, privateKey, accessToken]) {
91 0 : controller.dispose();
92 : }
93 0 : super.dispose();
94 : }
95 :
96 0 : bool get hasCertificate => TellerSettings.loadCertificate() != null && TellerSettings.loadKey() != null;
97 :
98 0 : Future<void> _run(Future<void> Function(TellerClient client) callback) async {
99 0 : setState(() {
100 0 : isLoading = true;
101 0 : error = null;
102 0 : notice = null;
103 : });
104 : TellerClient? client;
105 : try {
106 0 : await saveSettings();
107 0 : final cert = TellerSettings.loadCertificate();
108 0 : final key = TellerSettings.loadKey();
109 0 : if (settings.environment.requiresCertificate && (cert == null || key == null)) {
110 0 : throw TellerException(AppLocale.labels.tellerIncomplete);
111 : }
112 0 : client = TellerClient(
113 0 : client: widget.httpClient ?? createTellerHttpClient(certificate: cert, privateKey: key),
114 : );
115 0 : await callback(client);
116 0 : } on TellerException catch (e) {
117 0 : error = e.message;
118 : } catch (e) {
119 0 : error = e.toString();
120 : } finally {
121 0 : if (widget.httpClient == null) {
122 0 : client?.close();
123 : }
124 0 : if (mounted) {
125 0 : setState(() => isLoading = false);
126 : }
127 : }
128 : }
129 :
130 0 : Future<void> saveSettings() async {
131 0 : final cert = certificate.text.trim();
132 0 : final key = privateKey.text.trim();
133 : // Both are validated before either is stored
134 0 : final normalizedCert = cert.isNotEmpty ? TellerClient.normalizeCertificate(cert) : null;
135 0 : final normalizedKey = key.isNotEmpty ? TellerClient.normalizePrivateKey(key) : null;
136 : if (normalizedCert != null) {
137 0 : await TellerSettings.saveCertificate(normalizedCert);
138 0 : certificate.clear();
139 : }
140 : if (normalizedKey != null) {
141 0 : await TellerSettings.saveKey(normalizedKey);
142 0 : privateKey.clear();
143 : }
144 0 : final page = connectPage.text.trim();
145 0 : settings
146 0 : ..applicationId = applicationId.text.trim()
147 0 : ..connectPage = page == TellerSettings.defaultConnectPage ? '' : page;
148 0 : await settings.save();
149 : }
150 :
151 0 : Future<void> upload(TextEditingController controller) async {
152 0 : final content = await importFile(['pem', 'crt', 'cer', 'key']);
153 0 : if (content != null && mounted) {
154 0 : setState(() => controller.text = content);
155 : }
156 : }
157 :
158 0 : void onLink() {
159 0 : if (!mounted || DeepLinkHandler.tellerCallback.value == null) {
160 : return;
161 : }
162 0 : if (isLoading) {
163 0 : Future.delayed(const Duration(milliseconds: 300), onLink);
164 : return;
165 : }
166 0 : final link = DeepLinkHandler.takeTellerCallback()!;
167 0 : connect(enrollment: TellerEnrollment.fromLink(link));
168 : }
169 :
170 : // Teller Connect is a JavaScript widget: it is opened by the connection page in a browser
171 0 : Future<void> connectBank() => _run((_) async {
172 0 : if (settings.applicationId.isEmpty) {
173 0 : throw TellerException(AppLocale.labels.tellerIncomplete);
174 : }
175 0 : final page = settings.connectUrl(enrollmentId: disconnected);
176 0 : if (page.scheme != 'https') {
177 0 : throw TellerException(AppLocale.labels.integrationHttpsRequired);
178 : }
179 0 : await (widget.launcher ?? (uri) => launchUrl(uri, mode: LaunchMode.externalApplication))(page);
180 : });
181 :
182 : // [enrollment] comes from the connection page (deep link); the access token field is filled in manually
183 0 : Future<void> connect({TellerEnrollment? enrollment}) => _run((client) async {
184 0 : final added = enrollment ?? TellerEnrollment.parse(accessToken.text);
185 : if (added != null) {
186 : // The token is checked before it is stored
187 0 : await client.getAccounts(added.accessToken);
188 0 : enrollments = TellerSettings.merge(enrollments, added);
189 0 : await TellerSettings.saveEnrollments(enrollments);
190 0 : accessToken.clear();
191 0 : if (added.id == disconnected) {
192 0 : disconnected = null;
193 : }
194 : }
195 0 : if (enrollments.isEmpty) {
196 0 : throw TellerException(AppLocale.labels.tellerAccessToken);
197 : }
198 0 : await _loadAccounts(client);
199 : });
200 :
201 0 : Future<void> _loadAccounts(TellerClient client) async {
202 0 : final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
203 0 : final monthAgo = DateTime.now().subtract(const Duration(days: 30));
204 0 : final errors = <String>[];
205 0 : final result = <TellerBankAccount>[];
206 0 : for (final enrollment in enrollments) {
207 : try {
208 0 : final items = await client.getAccounts(enrollment.accessToken);
209 0 : for (final account in items.where((e) => e.isOpen)) {
210 0 : final item = TellerBankAccount(
211 : account,
212 : enrollment,
213 0 : appAccount: settings.links[account.id],
214 : category: defaultBudget,
215 0 : from: settings.imported[account.id] ?? monthAgo,
216 : );
217 : try {
218 0 : item.balance = await client.getBalances(enrollment.accessToken, account.id);
219 0 : } on TellerException catch (e) {
220 0 : if (e.isDisconnected) {
221 : rethrow;
222 : }
223 : // Balances are optional for the import
224 : }
225 0 : result.add(item);
226 : }
227 0 : } on TellerException catch (e) {
228 0 : if (e.isDisconnected) {
229 0 : disconnected = enrollment.id.isNotEmpty ? enrollment.id : disconnected;
230 : }
231 0 : final name = enrollment.institution.isNotEmpty ? '${enrollment.institution}: ' : '';
232 0 : errors.add('$name${e.message}');
233 : }
234 : }
235 0 : accounts = result;
236 0 : if (errors.isNotEmpty) {
237 0 : error = errors.join('\n');
238 0 : } else if (accounts.isEmpty) {
239 0 : notice = AppLocale.labels.integrationNoAccounts;
240 : }
241 : }
242 :
243 0 : Future<void> disconnect() async => setState(() => accounts = []);
244 :
245 0 : Future<void> forget() => _run((client) async {
246 0 : final current = enrollments;
247 0 : enrollments = [];
248 0 : accounts = [];
249 0 : disconnected = null;
250 0 : await TellerSettings.saveEnrollments(enrollments);
251 0 : for (final enrollment in current) {
252 : try {
253 0 : await client.deleteEnrollment(enrollment.accessToken);
254 0 : } on TellerException {
255 : // Already revoked or disconnected: nothing else to do
256 : }
257 : }
258 : });
259 :
260 0 : Future<void> importTransactions(TellerBankAccount item) => _run((client) async {
261 0 : if (item.appAccount == null || item.category == null) {
262 0 : throw TellerException(AppLocale.labels.integrationSelectTarget);
263 : }
264 0 : final state = Provider.of<AppData>(context, listen: false);
265 0 : final id = item.account.id;
266 0 : final last = settings.imported[id];
267 0 : final from = last != null && !item.from.isAfter(last) ? item.from.subtract(postingDelay) : item.from;
268 : final List<TellerTransaction> transactions;
269 : try {
270 0 : transactions = await client.getTransactions(item.enrollment.accessToken, id, from: from);
271 0 : } on TellerException catch (e) {
272 0 : if (e.isDisconnected && item.enrollment.id.isNotEmpty) {
273 0 : disconnected = item.enrollment.id;
274 : }
275 : rethrow;
276 : }
277 0 : final importer = TellerImporter(
278 0 : exists: (uuid) => state.getByUuid(uuid) != null,
279 0 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
280 : );
281 0 : final summary = importer.run(
282 0 : source: item.account,
283 : transactions: transactions,
284 0 : account: item.appAccount!,
285 0 : category: item.category!,
286 0 : prediction: state.prediction,
287 : );
288 0 : await state.restate();
289 0 : final today = DateTime.now();
290 0 : settings.links[id] = item.appAccount!;
291 0 : settings.imported[id] = DateTime(today.year, today.month, today.day);
292 0 : await settings.save();
293 0 : notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
294 : });
295 :
296 0 : Widget buildUpload(String key, TextEditingController controller) => Align(
297 : alignment: Alignment.centerRight,
298 0 : child: TextButton.icon(
299 0 : key: ValueKey('teller_upload_$key'),
300 : icon: const Icon(Icons.upload_file),
301 0 : onPressed: isLoading ? null : () => upload(controller),
302 0 : label: Text(AppLocale.labels.tellerUpload),
303 : ),
304 : );
305 :
306 0 : Widget buildSettings(BuildContext context) {
307 0 : final stored = hasCertificate;
308 0 : return Column(
309 0 : crossAxisAlignment: AppDesign.getAlignment(),
310 0 : children: [
311 0 : Text(AppLocale.labels.tellerSteps, style: context.textTheme.bodyMedium),
312 : ThemeHelper.hIndent2x,
313 0 : InputWrapper.text(
314 0 : title: AppLocale.labels.tellerAppId,
315 0 : tooltip: AppLocale.labels.tellerAppIdTooltip,
316 0 : controller: applicationId,
317 : isRequired: true,
318 : ),
319 0 : InputWrapper.select(
320 0 : title: AppLocale.labels.tellerEnvironment,
321 0 : value: settings.environment.name,
322 : isRequired: true,
323 0 : options: <ListSelectorItem>[
324 0 : for (final env in TellerEnvironment.values) ListSelectorItem(id: env.name, name: env.name),
325 : ],
326 0 : onChange: (value) => setState(() => settings.environment = TellerEnvironment.parse(value)),
327 : ),
328 0 : if (isTellerCertificateSupported) ...[
329 0 : InputWrapper.text(
330 0 : title: AppLocale.labels.tellerCertificate,
331 0 : tooltip: AppLocale.labels.tellerCertificateTooltip,
332 0 : controller: certificate,
333 0 : isRequired: settings.environment.requiresCertificate && !stored,
334 : ),
335 0 : buildUpload('certificate', certificate),
336 0 : InputWrapper.text(
337 0 : title: AppLocale.labels.tellerKey,
338 0 : tooltip: AppLocale.labels.tellerKeyTooltip,
339 0 : controller: privateKey,
340 0 : isRequired: settings.environment.requiresCertificate && !stored,
341 : ),
342 0 : buildUpload('key', privateKey),
343 : ],
344 0 : InputWrapper.text(
345 0 : title: AppLocale.labels.tellerConnectPage,
346 0 : tooltip: AppLocale.labels.tellerConnectPageTooltip,
347 0 : controller: connectPage,
348 : isRequired: true,
349 : inputType: TextInputType.url,
350 : ),
351 0 : Align(
352 : alignment: Alignment.centerRight,
353 0 : child: TextButton.icon(
354 : key: const ValueKey('teller_connect_bank'),
355 : icon: const Icon(Icons.account_balance),
356 0 : onPressed: isLoading ? null : connectBank,
357 0 : label: Text(AppLocale.labels.tellerConnectBank),
358 : ),
359 : ),
360 0 : InputWrapper.text(
361 0 : title: AppLocale.labels.tellerAccessToken,
362 0 : tooltip: AppLocale.labels.tellerAccessTokenTooltip,
363 0 : controller: accessToken,
364 0 : isRequired: enrollments.isEmpty,
365 : ),
366 : ],
367 : );
368 : }
369 :
370 0 : Widget buildAccount(BuildContext context, TellerBankAccount item, AppData state) {
371 0 : final amount = item.balance?.amount;
372 0 : return IntegrationAccountCard(
373 0 : title: item.title,
374 0 : subtitle: amount != null ? '${AppLocale.labels.balance}: $amount ${item.account.currency}' : null,
375 : target: item,
376 : state: state,
377 0 : isDisabled: isLoading,
378 0 : onChanged: () => setState(() {}),
379 0 : onImport: () => importTransactions(item),
380 : );
381 : }
382 :
383 0 : @override
384 : Widget build(BuildContext context) {
385 0 : final textTheme = context.textTheme;
386 0 : final colorScheme = context.colorScheme;
387 0 : return Consumer<AppData>(builder: (context, state, _) {
388 0 : return Column(
389 0 : crossAxisAlignment: AppDesign.getAlignment(),
390 0 : children: [
391 0 : Text(AppLocale.labels.tellerDescription, style: textTheme.bodyMedium),
392 : ThemeHelper.hIndent2x,
393 0 : if (accounts.isEmpty) buildSettings(context),
394 0 : ThemeHelper.hIndent2x,
395 0 : if (error != null) ...[
396 0 : Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
397 : ThemeHelper.hIndent,
398 : ],
399 0 : if (notice != null) ...[
400 0 : Text(notice!, style: textTheme.bodyLarge),
401 : ThemeHelper.hIndent,
402 : ],
403 0 : if (isLoading)
404 0 : const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
405 0 : else ...[
406 0 : if (accounts.isNotEmpty)
407 0 : FullSizedButtonWidget(
408 : key: const ValueKey('teller_disconnect'),
409 : icon: Icons.logout,
410 0 : onPressed: disconnect,
411 0 : title: AppLocale.labels.integrationDisconnect,
412 : )
413 : else
414 0 : FullSizedButtonWidget(
415 : key: const ValueKey('teller_connect'),
416 : icon: Icons.login,
417 0 : onPressed: connect,
418 0 : title: AppLocale.labels.integrationConnect,
419 : ),
420 0 : if (accounts.isNotEmpty || disconnected != null)
421 0 : Align(
422 : alignment: Alignment.centerRight,
423 0 : child: TextButton.icon(
424 : key: const ValueKey('teller_add_bank'),
425 : icon: const Icon(Icons.add_link),
426 0 : onPressed: connectBank,
427 0 : label: Text(AppLocale.labels.tellerConnectBank),
428 : ),
429 : ),
430 0 : if (enrollments.isNotEmpty)
431 0 : Align(
432 : alignment: Alignment.centerRight,
433 0 : child: TextButton.icon(
434 : key: const ValueKey('teller_forget'),
435 : icon: const Icon(Icons.link_off),
436 0 : onPressed: forget,
437 0 : label: Text(AppLocale.labels.integrationForget),
438 : ),
439 : ),
440 : ],
441 0 : for (final item in accounts) buildAccount(context, item, state),
442 : ],
443 : );
444 : });
445 : }
446 : }
|