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 'dart:convert';
5 :
6 : import 'package:app_finance/_classes/controller/deep_link/deep_link_handler.dart';
7 : import 'package:app_finance/_classes/controller/encryption_handler.dart';
8 : import 'package:app_finance/_classes/integration/teller/teller_client.dart';
9 : import 'package:app_finance/_classes/storage/app_preferences.dart';
10 :
11 : // Access granted by Teller Connect for the accounts of one bank login
12 : class TellerEnrollment {
13 : final String id;
14 : final String accessToken;
15 : final String institution;
16 :
17 1 : const TellerEnrollment({required this.id, required this.accessToken, this.institution = ''});
18 :
19 5 : Map<String, dynamic> toJson() => {'id': id, 'accessToken': accessToken, 'institution': institution};
20 :
21 2 : factory TellerEnrollment.fromJson(Map<String, dynamic> json) => TellerEnrollment(
22 2 : id: (json['id'] ?? '').toString(),
23 2 : accessToken: (json['accessToken'] ?? '').toString(),
24 2 : institution: (json['institution'] ?? '').toString(),
25 : );
26 :
27 : // Teller Connect hands the result over by the deep link of [TellerSettings.connectPage], or it is pasted manually
28 1 : static TellerEnrollment? fromLink(Uri uri) {
29 4 : final params = {...uri.queryParameters, ...Uri.splitQueryString(uri.fragment)};
30 2 : final token = params['token']?.trim() ?? '';
31 1 : if (token.isEmpty) {
32 : return null;
33 : }
34 1 : return TellerEnrollment(
35 2 : id: params['enrollment'] ?? '', accessToken: token, institution: params['institution'] ?? '');
36 : }
37 :
38 1 : static TellerEnrollment? parse(String input) {
39 1 : final value = input.trim();
40 1 : if (value.isEmpty) {
41 : return null;
42 : }
43 1 : final uri = Uri.tryParse(value);
44 1 : if (uri != null && uri.hasScheme) {
45 1 : return fromLink(uri);
46 : }
47 1 : return TellerEnrollment(id: '', accessToken: value);
48 : }
49 : }
50 :
51 : class TellerSettings {
52 : // Hosts Teller Connect (a JavaScript widget) and returns the enrollment to [callbackUrl]
53 : static const defaultConnectPage = 'https://lyskouski.github.io/app-finance/teller.html';
54 :
55 : static const callbackUrl = '${DeepLinkHandler.scheme}://integration${DeepLinkHandler.tellerPath}';
56 :
57 : String applicationId;
58 : TellerEnvironment environment;
59 : String connectPage;
60 :
61 : // Teller account id to the uuid of the application's account
62 : final Map<String, String> links;
63 :
64 : // Teller account id to the last day transactions were imported for
65 : final Map<String, DateTime> imported;
66 :
67 1 : TellerSettings({
68 : this.applicationId = '',
69 : this.environment = TellerEnvironment.sandbox,
70 : this.connectPage = '',
71 : Map<String, String>? links,
72 : Map<String, DateTime>? imported,
73 1 : }) : links = links ?? {},
74 1 : imported = imported ?? {};
75 :
76 1 : Uri connectUrl({String? enrollmentId}) {
77 4 : final page = Uri.parse(connectPage.isEmpty ? defaultConnectPage : connectPage);
78 2 : return page.replace(queryParameters: {
79 1 : ...page.queryParameters,
80 2 : 'app': applicationId,
81 3 : 'env': environment.name,
82 2 : if (enrollmentId != null && enrollmentId.isNotEmpty) 'enrollment': enrollmentId,
83 : });
84 : }
85 :
86 2 : Map<String, dynamic> toJson() => {
87 1 : 'applicationId': applicationId,
88 2 : 'environment': environment.name,
89 1 : 'connectPage': connectPage,
90 1 : 'links': links,
91 5 : 'imported': imported.map((key, value) => MapEntry(key, value.toIso8601String())),
92 : };
93 :
94 2 : factory TellerSettings.fromJson(Map<String, dynamic> json) => TellerSettings(
95 1 : applicationId: json['applicationId'] ?? '',
96 2 : environment: TellerEnvironment.parse(json['environment']),
97 1 : connectPage: json['connectPage'] ?? '',
98 5 : links: (json['links'] as Map<String, dynamic>? ?? {}).map((key, value) => MapEntry(key, value.toString())),
99 2 : imported: (json['imported'] as Map<String, dynamic>? ?? {}).map(
100 4 : (key, value) => MapEntry(key, DateTime.parse(value.toString())),
101 : ),
102 : );
103 :
104 1 : static TellerSettings load() {
105 1 : final value = AppPreferences.get(AppPreferences.prefTeller);
106 1 : if (value == null || value.isEmpty) {
107 0 : return TellerSettings();
108 : }
109 : try {
110 2 : return TellerSettings.fromJson(jsonDecode(value));
111 0 : } on FormatException {
112 0 : return TellerSettings();
113 : }
114 : }
115 :
116 4 : Future<void> save() => AppPreferences.set(AppPreferences.prefTeller, jsonEncode(toJson()));
117 :
118 1 : static String? _decrypt(String key) {
119 1 : final value = AppPreferences.get(key);
120 1 : if (value == null || value.isEmpty) {
121 : return null;
122 : }
123 : try {
124 1 : return EncryptionHandler.decrypt(value);
125 : } catch (_) {
126 : return null;
127 : }
128 : }
129 :
130 3 : static Future<void> _encrypt(String key, String value) => AppPreferences.set(key, EncryptionHandler.encrypt(value));
131 :
132 2 : static String? loadCertificate() => _decrypt(AppPreferences.prefTellerCertificate);
133 :
134 2 : static Future<void> saveCertificate(String pem) => _encrypt(AppPreferences.prefTellerCertificate, pem);
135 :
136 2 : static String? loadKey() => _decrypt(AppPreferences.prefTellerKey);
137 :
138 2 : static Future<void> saveKey(String pem) => _encrypt(AppPreferences.prefTellerKey, pem);
139 :
140 1 : static Future<void> clearCertificate() async {
141 1 : await AppPreferences.clear(AppPreferences.prefTellerCertificate);
142 1 : await AppPreferences.clear(AppPreferences.prefTellerKey);
143 : }
144 :
145 1 : static List<TellerEnrollment> loadEnrollments() {
146 1 : final value = _decrypt(AppPreferences.prefTellerEnrollments);
147 : if (value == null) {
148 1 : return [];
149 : }
150 : try {
151 1 : return (jsonDecode(value) as List)
152 1 : .whereType<Map<String, dynamic>>()
153 1 : .map(TellerEnrollment.fromJson)
154 4 : .where((e) => e.accessToken.isNotEmpty)
155 1 : .toList();
156 : } catch (_) {
157 0 : return [];
158 : }
159 : }
160 :
161 2 : static Future<void> saveEnrollments(List<TellerEnrollment> enrollments) => enrollments.isEmpty
162 1 : ? AppPreferences.clear(AppPreferences.prefTellerEnrollments)
163 6 : : _encrypt(AppPreferences.prefTellerEnrollments, jsonEncode(enrollments.map((e) => e.toJson()).toList()));
164 :
165 : // A repaired enrollment keeps its id (and the token): the entry is replaced
166 2 : static List<TellerEnrollment> merge(List<TellerEnrollment> enrollments, TellerEnrollment item) => [
167 1 : for (final e in enrollments)
168 9 : if (e.accessToken != item.accessToken && (item.id.isEmpty || e.id != item.id)) e,
169 1 : item,
170 : ];
171 : }
|