LCOV - code coverage report
Current view: top level - lib/_classes/integration/investec - investec_client.dart Coverage Total Hit
Test: lcov.info Lines: 0.0 % 106 0
Test Date: 2026-12-05 10:54:13 Functions: - 0 0

            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            0 :   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            0 :   const InvestecAccount({
      31              :     required this.id,
      32              :     required this.number,
      33              :     required this.name,
      34              :     this.product = '',
      35              :     this.profile = '',
      36              :   });
      37              : 
      38            0 :   String get title {
      39            0 :     final masked = number.length > 4 ? '…${number.substring(number.length - 4)}' : number;
      40            0 :     return [name.isNotEmpty ? name : product, masked].where((e) => e.isNotEmpty).join(' ');
      41              :   }
      42              : 
      43            0 :   factory InvestecAccount.fromJson(Map<String, dynamic> json) => InvestecAccount(
      44            0 :         id: json['accountId'].toString(),
      45            0 :         number: (json['accountNumber'] ?? '').toString(),
      46            0 :         name: (json['referenceName'] ?? json['accountName'] ?? '').toString().trim(),
      47            0 :         product: (json['productName'] ?? '').toString().trim(),
      48            0 :         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            0 :   const InvestecBalance({required this.current, required this.currency, this.available});
      58              : 
      59            0 :   factory InvestecBalance.fromJson(Map<String, dynamic> json) => InvestecBalance(
      60            0 :         current: InvestecClient.parseAmount(json['currentBalance']),
      61            0 :         available: json['availableBalance'] != null ? InvestecClient.parseAmount(json['availableBalance']) : null,
      62            0 :         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            0 :   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            0 :   double get signedAmount => isDebit ? -amount.abs() : amount.abs();
      87              : 
      88              :   // The day of the purchase; the posting may follow days later
      89            0 :   DateTime? get date => transactionDate ?? postingDate;
      90              : 
      91            0 :   factory InvestecTransaction.fromJson(Map<String, dynamic> json) {
      92            0 :     final uuid = json['uuid']?.toString().trim();
      93            0 :     return InvestecTransaction(
      94            0 :       uuid: uuid == null || uuid.isEmpty ? null : uuid,
      95            0 :       isDebit: json['type'].toString().toUpperCase() == 'DEBIT',
      96            0 :       pending: (json['status'] ?? 'POSTED').toString().toUpperCase() != 'POSTED',
      97            0 :       description: (json['description'] ?? '').toString().trim(),
      98            0 :       postingDate: InvestecClient.parseDate(json['postingDate']),
      99            0 :       transactionDate: InvestecClient.parseDate(json['transactionDate']),
     100            0 :       amount: InvestecClient.parseAmount(json['amount']),
     101              :     );
     102              :   }
     103              : }
     104              : 
     105              : class InvestecClient {
     106            0 :   static final liveUrl = Uri.parse('https://openapi.investec.com');
     107            0 :   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            0 :   InvestecClient({http.Client? client, bool sandbox = false, DateTime Function()? now})
     119            0 :       : _client = client ?? http.Client(),
     120            0 :         baseUrl = sandbox ? sandboxUrl : liveUrl,
     121              :         now = now ?? DateTime.now;
     122              : 
     123            0 :   void close() => _client.close();
     124              : 
     125            0 :   static double parseAmount(dynamic value) {
     126            0 :     final result = value is num ? value.toDouble() : double.tryParse(value?.toString().trim() ?? '');
     127              :     if (result == null) {
     128            0 :       throw InvestecException(AppLocale.labels.integrationInvalidAmount('$value'));
     129              :     }
     130              :     return result;
     131              :   }
     132              : 
     133            0 :   static DateTime? parseDate(dynamic value) {
     134            0 :     final text = value?.toString() ?? '';
     135            0 :     return text.length < 10 ? null : DateTime.tryParse(text.substring(0, 10));
     136              :   }
     137              : 
     138            0 :   static String _date(DateTime value) =>
     139            0 :       '${value.year.toString().padLeft(4, '0')}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
     140              : 
     141            0 :   static dynamic _decode(http.Response response) {
     142            0 :     final text = utf8.decode(response.bodyBytes);
     143              :     try {
     144            0 :       return text.isEmpty ? null : jsonDecode(text);
     145            0 :     } on FormatException {
     146              :       return null;
     147              :     }
     148              :   }
     149              : 
     150            0 :   static Never _fail(http.Response response, dynamic json) {
     151            0 :     final status = response.statusCode;
     152            0 :     final error = json is Map ? (json['error_description'] ?? json['message'] ?? json['error']) : null;
     153            0 :     if (status == 401 || status == 403) {
     154            0 :       throw InvestecException(AppLocale.labels.integrationAccessDenied, status);
     155              :     }
     156            0 :     throw InvestecException(
     157            0 :       error is String && error.isNotEmpty
     158            0 :           ? AppLocale.labels.integrationServiceError(error)
     159            0 :           : AppLocale.labels.integrationHttpError('$status'),
     160              :       status,
     161              :     );
     162              :   }
     163              : 
     164            0 :   Future<String> _authorize(InvestecCredentials credentials) async {
     165            0 :     final token = _token;
     166            0 :     final expiresAt = _expiresAt;
     167            0 :     if (token != null && expiresAt != null && now().isBefore(expiresAt)) {
     168              :       return token;
     169              :     }
     170            0 :     final basic = base64.encode(utf8.encode('${credentials.clientId}:${credentials.secret}'));
     171            0 :     final response = await _client.post(
     172            0 :       baseUrl.replace(path: '/identity/v2/oauth2/token'),
     173            0 :       headers: {
     174            0 :         'Authorization': 'Basic $basic',
     175              :         'x-api-key': credentials.apiKey,
     176              :         'Accept': 'application/json',
     177              :         'Content-Type': 'application/x-www-form-urlencoded',
     178              :       },
     179            0 :       body: {'grant_type': 'client_credentials'},
     180            0 :     ).timeout(timeout);
     181            0 :     final json = _decode(response);
     182            0 :     if (response.statusCode != 200) {
     183            0 :       _fail(response, json);
     184              :     }
     185            0 :     final value = json is Map ? json['access_token']?.toString() : null;
     186            0 :     if (value == null || value.isEmpty) {
     187            0 :       throw InvestecException(AppLocale.labels.integrationUnexpectedResponse);
     188              :     }
     189              :     // Documented as 1799 seconds, sometimes sent as a string
     190            0 :     final seconds = int.tryParse('${json['expires_in'] ?? ''}') ?? 1799;
     191            0 :     _token = value;
     192            0 :     _expiresAt = now().add(Duration(seconds: seconds)).subtract(tokenMargin);
     193              :     return value;
     194              :   }
     195              : 
     196            0 :   Future<Map<String, dynamic>> _get(InvestecCredentials credentials, String path, [Map<String, String>? query]) async {
     197            0 :     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            0 :     for (var attempt = 0; attempt < 2; attempt++) {
     201            0 :       final token = await _authorize(credentials);
     202            0 :       response = await _client.get(uri, headers: {
     203            0 :         'Authorization': 'Bearer $token',
     204              :         'Accept': 'application/json',
     205            0 :       }).timeout(timeout);
     206            0 :       if (response.statusCode != 401) {
     207              :         break;
     208              :       }
     209            0 :       _token = null;
     210              :     }
     211            0 :     final json = _decode(response!);
     212            0 :     if (response.statusCode != 200) {
     213            0 :       _fail(response, json);
     214              :     }
     215            0 :     if (json is! Map<String, dynamic> || json['data'] is! Map<String, dynamic>) {
     216            0 :       throw InvestecException(AppLocale.labels.integrationUnexpectedResponse);
     217              :     }
     218            0 :     return json['data'] as Map<String, dynamic>;
     219              :   }
     220              : 
     221            0 :   Future<List<InvestecAccount>> getAccounts(InvestecCredentials credentials) async {
     222            0 :     final data = await _get(credentials, '/za/pb/v1/accounts');
     223            0 :     return (data['accounts'] as List? ?? []).whereType<Map<String, dynamic>>().map(InvestecAccount.fromJson).toList();
     224              :   }
     225              : 
     226            0 :   Future<InvestecBalance> getBalance(InvestecCredentials credentials, String accountId) async =>
     227            0 :       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            0 :   Future<List<InvestecTransaction>> getTransactions(
     231              :     InvestecCredentials credentials,
     232              :     String accountId, {
     233              :     required DateTime from,
     234              :     DateTime? to,
     235              :   }) async {
     236            0 :     final data = await _get(credentials, '/za/pb/v1/accounts/$accountId/transactions', {
     237            0 :       'fromDate': _date(from),
     238            0 :       'toDate': _date(to ?? now()),
     239              :       'includePending': 'true',
     240              :     });
     241            0 :     return (data['transactions'] as List? ?? [])
     242            0 :         .whereType<Map<String, dynamic>>()
     243            0 :         .map(InvestecTransaction.fromJson)
     244            0 :         .toList();
     245              :   }
     246              : }
        

Generated by: LCOV version 2.0-1