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/herald/app_locale.dart';
7 : import 'package:http/http.dart' as http;
8 :
9 : // Teller API (https://teller.io/docs/api): access tokens per enrollment, mutual TLS for real bank data
10 : class TellerException implements Exception {
11 : final String message;
12 : final int? statusCode;
13 : final String? code;
14 :
15 1 : const TellerException(this.message, [this.statusCode, this.code]);
16 :
17 : // The bank requires a user action (new login, MFA, ...): Teller Connect has to be opened again for the enrollment
18 3 : bool get isDisconnected => code?.startsWith('enrollment.disconnected') ?? false;
19 :
20 0 : @override
21 0 : String toString() => message;
22 : }
23 :
24 : enum TellerEnvironment {
25 : sandbox,
26 : development,
27 : production;
28 :
29 : // Real bank data is served only through mutual TLS
30 0 : bool get requiresCertificate => this != sandbox;
31 :
32 6 : static TellerEnvironment parse(String? value) => values.where((e) => e.name == value).firstOrNull ?? sandbox;
33 : }
34 :
35 : class TellerAccount {
36 : final String id;
37 : final String enrollmentId;
38 : final String name;
39 : final String? institution;
40 : final String? lastFour;
41 : final String currency;
42 : final String type;
43 : final bool isOpen;
44 :
45 1 : const TellerAccount({
46 : required this.id,
47 : required this.enrollmentId,
48 : required this.name,
49 : required this.currency,
50 : this.institution,
51 : this.lastFour,
52 : this.type = '',
53 : this.isOpen = true,
54 : });
55 :
56 1 : factory TellerAccount.fromJson(Map<String, dynamic> json) {
57 1 : final institution = json['institution'];
58 1 : return TellerAccount(
59 2 : id: json['id'].toString(),
60 2 : enrollmentId: (json['enrollment_id'] ?? '').toString(),
61 3 : name: (json['name'] ?? '').toString().trim(),
62 3 : institution: institution is Map ? institution['name']?.toString() : null,
63 2 : lastFour: json['last_four']?.toString(),
64 2 : currency: (json['currency'] ?? '').toString(),
65 2 : type: (json['type'] ?? '').toString(),
66 2 : isOpen: json['status'] != 'closed',
67 : );
68 : }
69 : }
70 :
71 : class TellerBalance {
72 : final double? ledger;
73 : final double? available;
74 :
75 1 : const TellerBalance({this.ledger, this.available});
76 :
77 2 : double? get amount => ledger ?? available;
78 :
79 2 : factory TellerBalance.fromJson(Map<String, dynamic> json) => TellerBalance(
80 3 : ledger: json['ledger'] != null ? TellerClient.parseAmount(json['ledger']) : null,
81 1 : available: json['available'] != null ? TellerClient.parseAmount(json['available']) : null,
82 : );
83 : }
84 :
85 : class TellerTransaction {
86 : final String id;
87 : final DateTime? date;
88 : final double amount;
89 : final String description;
90 : final bool pending;
91 :
92 1 : const TellerTransaction({
93 : required this.id,
94 : required this.amount,
95 : required this.description,
96 : this.date,
97 : this.pending = false,
98 : });
99 :
100 1 : factory TellerTransaction.fromJson(Map<String, dynamic> json) {
101 3 : final details = json['details'] is Map ? json['details'] as Map : const {};
102 3 : final counterparty = details['counterparty'] is Map ? details['counterparty'] as Map : const {};
103 3 : final description = (json['description'] ?? '').toString().trim();
104 1 : return TellerTransaction(
105 2 : id: json['id'].toString(),
106 3 : date: DateTime.tryParse((json['date'] ?? '').toString()),
107 2 : amount: TellerClient.parseAmount(json['amount']),
108 4 : description: description.isNotEmpty ? description : (counterparty['name'] ?? '').toString().trim(),
109 2 : pending: json['status'] != 'posted',
110 : );
111 : }
112 : }
113 :
114 : class TellerClient {
115 3 : static final baseUrl = Uri.parse('https://api.teller.io');
116 : static const timeout = Duration(seconds: 90);
117 : static const pageSize = 250;
118 :
119 : final http.Client _client;
120 :
121 1 : TellerClient({http.Client? client}) : _client = client ?? http.Client();
122 :
123 0 : void close() => _client.close();
124 :
125 1 : static double parseAmount(dynamic value) {
126 3 : final result = double.tryParse(value?.toString().trim() ?? '');
127 : if (result == null) {
128 0 : throw TellerException(AppLocale.labels.integrationInvalidAmount('$value'));
129 : }
130 : return result;
131 : }
132 :
133 : // Canonical PEM block (pasted with or without line breaks), [label] matches e.g. "CERTIFICATE" or "PRIVATE KEY"
134 1 : static String? normalizePem(String pem, String label) {
135 3 : final match = RegExp('-----BEGIN ([A-Z ]*$label)-----(.+?)-----END \\1-----', dotAll: true).firstMatch(pem);
136 : if (match == null) {
137 : return null;
138 : }
139 3 : final body = match.group(2)!.replaceAll(RegExp(r'\s'), '');
140 8 : final lines = [for (var i = 0; i < body.length; i += 64) body.substring(i, (i + 64).clamp(0, body.length))];
141 4 : return '-----BEGIN ${match.group(1)}-----\n${lines.join('\n')}\n-----END ${match.group(1)}-----\n';
142 : }
143 :
144 1 : static String normalizeCertificate(String pem) {
145 : // A chain may hold several certificates: each is kept
146 1 : final blocks = RegExp(r'-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----', dotAll: true)
147 1 : .allMatches(pem)
148 4 : .map((e) => normalizePem(e.group(0)!, 'CERTIFICATE')!)
149 1 : .toList();
150 1 : if (blocks.isEmpty) {
151 3 : throw TellerException(AppLocale.labels.tellerCertificateInvalid);
152 : }
153 1 : return blocks.join();
154 : }
155 :
156 1 : static String normalizePrivateKey(String pem) {
157 1 : final result = normalizePem(pem, 'PRIVATE KEY');
158 : if (result == null) {
159 3 : throw TellerException(AppLocale.labels.tellerKeyInvalid);
160 : }
161 : return result;
162 : }
163 :
164 1 : static String _date(DateTime value) =>
165 10 : '${value.year.toString().padLeft(4, '0')}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
166 :
167 1 : Future<dynamic> _request(String method, String accessToken, String path, [Map<String, String>? query]) async {
168 3 : final uri = baseUrl.replace(path: path, queryParameters: query == null || query.isEmpty ? null : query);
169 1 : final request = http.Request(method, uri)
170 6 : ..headers['Authorization'] = 'Basic ${base64.encode(utf8.encode('$accessToken:'))}'
171 2 : ..headers['Accept'] = 'application/json';
172 4 : final response = await http.Response.fromStream(await _client.send(request).timeout(timeout));
173 2 : final text = utf8.decode(response.bodyBytes);
174 : dynamic json;
175 : try {
176 2 : json = text.isEmpty ? null : jsonDecode(text);
177 0 : } on FormatException {
178 : json = null;
179 : }
180 4 : if (response.statusCode >= 200 && response.statusCode < 300) {
181 : return json;
182 : }
183 4 : final error = json is Map && json['error'] is Map ? json['error'] as Map : const {};
184 2 : final code = error['code']?.toString();
185 2 : final message = error['message']?.toString();
186 1 : final status = response.statusCode;
187 1 : if (code != null && code.startsWith('enrollment.disconnected')) {
188 3 : throw TellerException(AppLocale.labels.tellerDisconnected, status, code);
189 : }
190 3 : if (status == 400 && (message ?? '').toLowerCase().contains('certificate')) {
191 3 : throw TellerException(AppLocale.labels.tellerMissingCertificate, status, code);
192 : }
193 2 : if (status == 401 || status == 403) {
194 3 : throw TellerException(AppLocale.labels.integrationAccessDenied, status, code);
195 : }
196 1 : throw TellerException(
197 : message != null
198 2 : ? AppLocale.labels.integrationServiceError(message)
199 3 : : AppLocale.labels.integrationHttpError('$status'),
200 : status,
201 : code,
202 : );
203 : }
204 :
205 1 : static List<Map<String, dynamic>> _list(dynamic json) {
206 1 : if (json is! List) {
207 0 : throw TellerException(AppLocale.labels.integrationUnexpectedResponse);
208 : }
209 2 : return json.whereType<Map<String, dynamic>>().toList();
210 : }
211 :
212 1 : Future<List<TellerAccount>> getAccounts(String accessToken) async =>
213 4 : _list(await _request('GET', accessToken, '/accounts')).map(TellerAccount.fromJson).toList();
214 :
215 1 : Future<TellerBalance> getBalances(String accessToken, String accountId) async {
216 2 : final json = await _request('GET', accessToken, '/accounts/$accountId/balances');
217 1 : if (json is! Map<String, dynamic>) {
218 0 : throw TellerException(AppLocale.labels.integrationUnexpectedResponse);
219 : }
220 1 : return TellerBalance.fromJson(json);
221 : }
222 :
223 : // Pages backward (newest first) until the start date is covered
224 1 : Future<List<TellerTransaction>> getTransactions(String accessToken, String accountId, {DateTime? from}) async {
225 1 : final result = <TellerTransaction>[];
226 : String? lastId;
227 : while (true) {
228 4 : final page = _list(await _request('GET', accessToken, '/accounts/$accountId/transactions', {
229 1 : 'count': '$pageSize',
230 2 : if (from != null) 'start_date': _date(from),
231 1 : if (lastId != null) 'from_id': lastId,
232 : }))
233 1 : .map(TellerTransaction.fromJson)
234 1 : .toList();
235 1 : result.addAll(page);
236 5 : if (page.length < pageSize || page.last.id == lastId) {
237 : break;
238 : }
239 2 : lastId = page.last.id;
240 : }
241 : return result;
242 : }
243 :
244 : // Revokes the application's access to all accounts of the enrollment
245 2 : Future<void> deleteEnrollment(String accessToken) => _request('DELETE', accessToken, '/accounts');
246 : }
|