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 : // Investec Programmable Banking, South Africa Private Banking (https://developer.investec.com):
10 : // OAuth 2.0 client credentials with an extra API key, bearer tokens valid for 30 minutes
11 : class InvestecException implements Exception {
12 : final String message;
13 : final int? statusCode;
14 :
15 1 : const InvestecException(this.message, [this.statusCode]);
16 :
17 0 : @override
18 0 : String toString() => message;
19 : }
20 :
21 : typedef InvestecCredentials = ({String clientId, String secret, String apiKey});
22 :
23 : class InvestecAccount {
24 : final String id;
25 : final String number;
26 : final String name;
27 : final String product;
28 : final String profile;
29 :
30 1 : const InvestecAccount({
31 : required this.id,
32 : required this.number,
33 : required this.name,
34 : this.product = '',
35 : this.profile = '',
36 : });
37 :
38 1 : String get title {
39 9 : final masked = number.length > 4 ? '…${number.substring(number.length - 4)}' : number;
40 8 : return [name.isNotEmpty ? name : product, masked].where((e) => e.isNotEmpty).join(' ');
41 : }
42 :
43 2 : factory InvestecAccount.fromJson(Map<String, dynamic> json) => InvestecAccount(
44 2 : id: json['accountId'].toString(),
45 2 : number: (json['accountNumber'] ?? '').toString(),
46 3 : name: (json['referenceName'] ?? json['accountName'] ?? '').toString().trim(),
47 3 : product: (json['productName'] ?? '').toString().trim(),
48 3 : profile: (json['profileName'] ?? '').toString().trim(),
49 : );
50 : }
51 :
52 : class InvestecBalance {
53 : final double current;
54 : final double? available;
55 : final String currency;
56 :
57 1 : const InvestecBalance({required this.current, required this.currency, this.available});
58 :
59 2 : factory InvestecBalance.fromJson(Map<String, dynamic> json) => InvestecBalance(
60 2 : current: InvestecClient.parseAmount(json['currentBalance']),
61 3 : available: json['availableBalance'] != null ? InvestecClient.parseAmount(json['availableBalance']) : null,
62 2 : currency: (json['currency'] ?? 'ZAR').toString(),
63 : );
64 : }
65 :
66 : class InvestecTransaction {
67 : final String? uuid;
68 : final bool isDebit;
69 : final bool pending;
70 : final String description;
71 : final DateTime? postingDate;
72 : final DateTime? transactionDate;
73 : // Always positive: the direction is given by the type (DEBIT or CREDIT)
74 : final double amount;
75 :
76 1 : const InvestecTransaction({
77 : required this.isDebit,
78 : required this.amount,
79 : required this.description,
80 : this.uuid,
81 : this.pending = false,
82 : this.postingDate,
83 : this.transactionDate,
84 : });
85 :
86 7 : double get signedAmount => isDebit ? -amount.abs() : amount.abs();
87 :
88 : // The day of the purchase; the posting may follow days later
89 2 : DateTime? get date => transactionDate ?? postingDate;
90 :
91 1 : factory InvestecTransaction.fromJson(Map<String, dynamic> json) {
92 3 : final uuid = json['uuid']?.toString().trim();
93 1 : return InvestecTransaction(
94 1 : uuid: uuid == null || uuid.isEmpty ? null : uuid,
95 4 : isDebit: json['type'].toString().toUpperCase() == 'DEBIT',
96 4 : pending: (json['status'] ?? 'POSTED').toString().toUpperCase() != 'POSTED',
97 3 : description: (json['description'] ?? '').toString().trim(),
98 2 : postingDate: InvestecClient.parseDate(json['postingDate']),
99 2 : transactionDate: InvestecClient.parseDate(json['transactionDate']),
100 2 : amount: InvestecClient.parseAmount(json['amount']),
101 : );
102 : }
103 : }
104 :
105 : class InvestecClient {
106 3 : static final liveUrl = Uri.parse('https://openapi.investec.com');
107 3 : static final sandboxUrl = Uri.parse('https://openapisandbox.investec.com');
108 : static const timeout = Duration(seconds: 90);
109 : // A token is renewed a bit before it expires
110 : static const tokenMargin = Duration(seconds: 60);
111 :
112 : final http.Client _client;
113 : final Uri baseUrl;
114 : final DateTime Function() now;
115 : String? _token;
116 : DateTime? _expiresAt;
117 :
118 1 : InvestecClient({http.Client? client, bool sandbox = false, DateTime Function()? now})
119 0 : : _client = client ?? http.Client(),
120 2 : baseUrl = sandbox ? sandboxUrl : liveUrl,
121 : now = now ?? DateTime.now;
122 :
123 0 : void close() => _client.close();
124 :
125 1 : static double parseAmount(dynamic value) {
126 5 : final result = value is num ? value.toDouble() : double.tryParse(value?.toString().trim() ?? '');
127 : if (result == null) {
128 4 : throw InvestecException(AppLocale.labels.integrationInvalidAmount('$value'));
129 : }
130 : return result;
131 : }
132 :
133 1 : static DateTime? parseDate(dynamic value) {
134 1 : final text = value?.toString() ?? '';
135 4 : return text.length < 10 ? null : DateTime.tryParse(text.substring(0, 10));
136 : }
137 :
138 1 : static String _date(DateTime value) =>
139 10 : '${value.year.toString().padLeft(4, '0')}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
140 :
141 1 : static dynamic _decode(http.Response response) {
142 2 : final text = utf8.decode(response.bodyBytes);
143 : try {
144 2 : return text.isEmpty ? null : jsonDecode(text);
145 0 : } on FormatException {
146 : return null;
147 : }
148 : }
149 :
150 1 : static Never _fail(http.Response response, dynamic json) {
151 1 : final status = response.statusCode;
152 4 : final error = json is Map ? (json['error_description'] ?? json['message'] ?? json['error']) : null;
153 2 : if (status == 401 || status == 403) {
154 3 : throw InvestecException(AppLocale.labels.integrationAccessDenied, status);
155 : }
156 1 : throw InvestecException(
157 2 : error is String && error.isNotEmpty
158 2 : ? AppLocale.labels.integrationServiceError(error)
159 0 : : AppLocale.labels.integrationHttpError('$status'),
160 : status,
161 : );
162 : }
163 :
164 1 : Future<String> _authorize(InvestecCredentials credentials) async {
165 1 : final token = _token;
166 1 : final expiresAt = _expiresAt;
167 3 : if (token != null && expiresAt != null && now().isBefore(expiresAt)) {
168 : return token;
169 : }
170 3 : final basic = base64.encode(utf8.encode('${credentials.clientId}:${credentials.secret}'));
171 2 : final response = await _client.post(
172 2 : baseUrl.replace(path: '/identity/v2/oauth2/token'),
173 1 : headers: {
174 1 : 'Authorization': 'Basic $basic',
175 : 'x-api-key': credentials.apiKey,
176 : 'Accept': 'application/json',
177 : 'Content-Type': 'application/x-www-form-urlencoded',
178 : },
179 1 : body: {'grant_type': 'client_credentials'},
180 1 : ).timeout(timeout);
181 1 : final json = _decode(response);
182 2 : if (response.statusCode != 200) {
183 1 : _fail(response, json);
184 : }
185 3 : final value = json is Map ? json['access_token']?.toString() : null;
186 1 : if (value == null || value.isEmpty) {
187 0 : throw InvestecException(AppLocale.labels.integrationUnexpectedResponse);
188 : }
189 : // Documented as 1799 seconds, sometimes sent as a string
190 3 : final seconds = int.tryParse('${json['expires_in'] ?? ''}') ?? 1799;
191 1 : _token = value;
192 6 : _expiresAt = now().add(Duration(seconds: seconds)).subtract(tokenMargin);
193 : return value;
194 : }
195 :
196 1 : Future<Map<String, dynamic>> _get(InvestecCredentials credentials, String path, [Map<String, String>? query]) async {
197 3 : final uri = baseUrl.replace(path: path, queryParameters: query == null || query.isEmpty ? null : query);
198 : http.Response? response;
199 : // A token revoked before its expiry is requested once again
200 2 : for (var attempt = 0; attempt < 2; attempt++) {
201 1 : final token = await _authorize(credentials);
202 3 : response = await _client.get(uri, headers: {
203 1 : 'Authorization': 'Bearer $token',
204 : 'Accept': 'application/json',
205 1 : }).timeout(timeout);
206 2 : if (response.statusCode != 401) {
207 : break;
208 : }
209 1 : _token = null;
210 : }
211 1 : final json = _decode(response!);
212 2 : if (response.statusCode != 200) {
213 0 : _fail(response, json);
214 : }
215 3 : if (json is! Map<String, dynamic> || json['data'] is! Map<String, dynamic>) {
216 0 : throw InvestecException(AppLocale.labels.integrationUnexpectedResponse);
217 : }
218 1 : return json['data'] as Map<String, dynamic>;
219 : }
220 :
221 1 : Future<List<InvestecAccount>> getAccounts(InvestecCredentials credentials) async {
222 1 : final data = await _get(credentials, '/za/pb/v1/accounts');
223 4 : return (data['accounts'] as List? ?? []).whereType<Map<String, dynamic>>().map(InvestecAccount.fromJson).toList();
224 : }
225 :
226 1 : Future<InvestecBalance> getBalance(InvestecCredentials credentials, String accountId) async =>
227 3 : InvestecBalance.fromJson(await _get(credentials, '/za/pb/v1/accounts/$accountId/balance'));
228 :
229 : // Filtered by the posting date; pending transactions are included to be reported
230 1 : Future<List<InvestecTransaction>> getTransactions(
231 : InvestecCredentials credentials,
232 : String accountId, {
233 : required DateTime from,
234 : DateTime? to,
235 : }) async {
236 3 : final data = await _get(credentials, '/za/pb/v1/accounts/$accountId/transactions', {
237 1 : 'fromDate': _date(from),
238 3 : 'toDate': _date(to ?? now()),
239 : 'includePending': 'true',
240 : });
241 1 : return (data['transactions'] as List? ?? [])
242 1 : .whereType<Map<String, dynamic>>()
243 1 : .map(InvestecTransaction.fromJson)
244 1 : .toList();
245 : }
246 : }
|