LCOV - code coverage report
Current view: top level - lib/_classes/integration/wise - wise_client.dart Coverage Total Hit
Test: lcov.info Lines: 83.9 % 87 73
Test Date: 2026-12-05 10:50:38 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              : // Wise Platform API with a Personal API Token (https://docs.wise.com/api-docs/api-reference)
      10              : class WiseException implements Exception {
      11              :   final String message;
      12              :   final int? statusCode;
      13              : 
      14            0 :   const WiseException(this.message, [this.statusCode]);
      15              : 
      16            0 :   @override
      17            0 :   String toString() => message;
      18              : }
      19              : 
      20              : // Strong Customer Authentication is required (UK/EEA)
      21              : class WiseScaException extends WiseException {
      22            0 :   WiseScaException() : super(AppLocale.labels.wiseScaRequired, 403);
      23              : }
      24              : 
      25              : typedef WiseAmount = ({double value, String currency});
      26              : 
      27              : class WiseProfile {
      28              :   final int id;
      29              :   final String type;
      30              :   final String name;
      31              : 
      32            1 :   const WiseProfile({required this.id, required this.type, required this.name});
      33              : 
      34            1 :   factory WiseProfile.fromJson(Map<String, dynamic> json) {
      35            2 :     final details = json['details'] is Map ? json['details'] as Map : const {};
      36            5 :     final person = [json['firstName'] ?? details['firstName'], json['lastName'] ?? details['lastName']]
      37            2 :         .where((e) => e != null && e.toString().isNotEmpty)
      38            1 :         .join(' ');
      39            1 :     return WiseProfile(
      40            2 :       id: (json['id'] as num).toInt(),
      41            3 :       type: (json['type'] ?? '').toString().toUpperCase(),
      42            3 :       name: (json['fullName'] ?? json['businessName'] ?? details['name'] ?? person).toString().trim(),
      43              :     );
      44              :   }
      45              : 
      46            0 :   String get title => [name, type].where((e) => e.isNotEmpty).join(' — ');
      47              : }
      48              : 
      49              : class WiseBalance {
      50              :   final int id;
      51              :   final String currency;
      52              :   final double amount;
      53              :   final String? name;
      54              : 
      55            1 :   const WiseBalance({required this.id, required this.currency, required this.amount, this.name});
      56              : 
      57            1 :   factory WiseBalance.fromJson(Map<String, dynamic> json) {
      58            2 :     final amount = WiseClient.parseAmount(json['amount']);
      59            1 :     return WiseBalance(
      60            2 :       id: (json['id'] as num).toInt(),
      61            2 :       currency: (json['currency'] ?? amount?.currency ?? '').toString(),
      62              :       amount: amount?.value ?? 0.0,
      63            1 :       name: json['name']?.toString(),
      64              :     );
      65              :   }
      66              : }
      67              : 
      68              : class WiseTransaction {
      69              :   final String type;
      70              :   final DateTime date;
      71              :   final WiseAmount amount;
      72              :   final String description;
      73              :   final String referenceNumber;
      74              :   final String? detailsType;
      75              :   final WiseAmount? sourceAmount;
      76              :   final WiseAmount? targetAmount;
      77              : 
      78            1 :   const WiseTransaction({
      79              :     required this.type,
      80              :     required this.date,
      81              :     required this.amount,
      82              :     required this.description,
      83              :     required this.referenceNumber,
      84              :     this.detailsType,
      85              :     this.sourceAmount,
      86              :     this.targetAmount,
      87              :   });
      88              : 
      89            3 :   bool get isConversion => detailsType == 'CONVERSION' && sourceAmount != null && targetAmount != null;
      90              : 
      91            1 :   factory WiseTransaction.fromJson(Map<String, dynamic> json) {
      92            3 :     final details = json['details'] is Map<String, dynamic> ? json['details'] as Map<String, dynamic> : const {};
      93            4 :     final merchant = details['merchant'] is Map ? details['merchant']['name'] : null;
      94            2 :     final amount = WiseClient.parseAmount(json['amount']);
      95            3 :     final date = DateTime.tryParse(json['date']?.toString() ?? '');
      96              :     if (amount == null || date == null) {
      97            0 :       throw WiseException(AppLocale.labels.integrationInvalidAmount('${json['amount']}'));
      98              :     }
      99            1 :     return WiseTransaction(
     100            2 :       type: (json['type'] ?? '').toString(),
     101            1 :       date: date.toLocal(),
     102              :       amount: amount,
     103            2 :       description: (merchant ?? details['description'] ?? '').toString().trim(),
     104            2 :       referenceNumber: (json['referenceNumber'] ?? '').toString(),
     105            2 :       detailsType: details['type']?.toString(),
     106            2 :       sourceAmount: WiseClient.parseAmount(details['sourceAmount']),
     107            2 :       targetAmount: WiseClient.parseAmount(details['targetAmount']),
     108              :     );
     109              :   }
     110              : }
     111              : 
     112              : class WiseClient {
     113              :   static const timeout = Duration(seconds: 90);
     114            3 :   static final api = Uri.parse('https://api.wise.com');
     115              :   static const maxInterval = Duration(days: 469);
     116              : 
     117              :   final http.Client _client;
     118              :   final Uri baseUrl;
     119              : 
     120            1 :   WiseClient({http.Client? client, Uri? baseUrl})
     121            1 :       : _client = client ?? http.Client(),
     122            1 :         baseUrl = baseUrl ?? api;
     123              : 
     124            3 :   void close() => _client.close();
     125              : 
     126            1 :   static WiseAmount? parseAmount(dynamic value) {
     127            1 :     if (value is! Map) {
     128              :       return null;
     129              :     }
     130            1 :     final amount = value['value'];
     131            2 :     final result = amount is num ? amount.toDouble() : double.tryParse(amount?.toString() ?? '');
     132              :     if (result == null) {
     133            0 :       throw WiseException(AppLocale.labels.integrationInvalidAmount('$amount'));
     134              :     }
     135            2 :     return (value: result, currency: (value['currency'] ?? '').toString());
     136              :   }
     137              : 
     138            3 :   static String _time(DateTime value) => value.toUtc().toIso8601String();
     139              : 
     140            1 :   Future<dynamic> _get(String token, String path, [Map<String, String>? query]) async {
     141            2 :     final uri = baseUrl.replace(path: path, queryParameters: query);
     142            3 :     final response = await _client.get(uri, headers: {
     143            2 :       'Authorization': 'Bearer ${token.trim()}',
     144              :       'Accept': 'application/json',
     145            1 :     }).timeout(timeout);
     146            1 :     final headers = response.headers;
     147            2 :     final requiresSca = response.statusCode == 403 && headers.containsKey('x-2fa-approval');
     148              :     if (requiresSca) {
     149            0 :       throw WiseScaException();
     150              :     }
     151            4 :     if (response.statusCode == 401 || response.statusCode == 403) {
     152            0 :       throw WiseException(AppLocale.labels.integrationAccessDenied, response.statusCode);
     153              :     }
     154            2 :     if (response.statusCode != 200) {
     155            0 :       throw WiseException(AppLocale.labels.integrationHttpError('${response.statusCode}'), response.statusCode);
     156              :     }
     157              :     try {
     158            3 :       return jsonDecode(utf8.decode(response.bodyBytes));
     159            0 :     } on FormatException {
     160            0 :       throw WiseException(AppLocale.labels.integrationUnexpectedResponse);
     161              :     }
     162              :   }
     163              : 
     164            1 :   static List<Map<String, dynamic>> _list(dynamic json) {
     165            1 :     if (json is! List) {
     166            0 :       throw WiseException(AppLocale.labels.integrationUnexpectedResponse);
     167              :     }
     168            2 :     return json.whereType<Map<String, dynamic>>().toList();
     169              :   }
     170              : 
     171            1 :   Future<List<WiseProfile>> getProfiles(String token) async =>
     172            4 :       _list(await _get(token, '/v2/profiles')).map(WiseProfile.fromJson).toList();
     173              : 
     174            1 :   Future<List<WiseBalance>> getBalances(String token, int profileId) async =>
     175            4 :       _list(await _get(token, '/v4/profiles/$profileId/balances', {'types': 'STANDARD'}))
     176            1 :           .map(WiseBalance.fromJson)
     177            1 :           .toList();
     178              : 
     179            1 :   Future<List<WiseTransaction>> getStatement(
     180              :     String token, {
     181              :     required int profileId,
     182              :     required WiseBalance balance,
     183              :     required DateTime start,
     184              :     DateTime? end,
     185              :   }) async {
     186            1 :     final result = <WiseTransaction>[];
     187            1 :     final till = end ?? DateTime.now();
     188              :     var from = start;
     189            1 :     while (from.isBefore(till)) {
     190            2 :       final to = from.add(maxInterval).isBefore(till) ? from.add(maxInterval) : till;
     191            4 :       final json = await _get(token, '/v1/profiles/$profileId/balance-statements/${balance.id}/statement.json', {
     192            1 :         'currency': balance.currency,
     193            1 :         'intervalStart': _time(from),
     194            1 :         'intervalEnd': _time(to),
     195              :         'type': 'COMPACT',
     196              :       });
     197            1 :       if (json is! Map<String, dynamic>) {
     198            0 :         throw WiseException(AppLocale.labels.integrationUnexpectedResponse);
     199              :       }
     200            4 :       result.addAll(_list(json['transactions'] ?? []).map(WiseTransaction.fromJson));
     201              :       from = to;
     202              :     }
     203              :     return result;
     204              :   }
     205              : }
        

Generated by: LCOV version 2.0-1