LCOV - code coverage report
Current view: top level - lib/_classes/integration/up - up_client.dart Coverage Total Hit
Test: lcov.info Lines: 82.1 % 67 55
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              : // Up Banking API (https://developer.up.com.au): JSON:API with a Personal Access Token
      10              : class UpException implements Exception {
      11              :   final String message;
      12              :   final int? statusCode;
      13              : 
      14            1 :   const UpException(this.message, [this.statusCode]);
      15              : 
      16            0 :   @override
      17            0 :   String toString() => message;
      18              : }
      19              : 
      20              : typedef UpAmount = ({double value, String currency});
      21              : 
      22              : class UpAccount {
      23              :   final String id;
      24              :   final String name;
      25              :   final String type;
      26              :   final UpAmount balance;
      27              : 
      28            1 :   const UpAccount({required this.id, required this.name, required this.balance, this.type = ''});
      29              : 
      30            1 :   factory UpAccount.fromJson(Map<String, dynamic> json) {
      31            3 :     final attributes = json['attributes'] is Map ? json['attributes'] as Map : const {};
      32            1 :     return UpAccount(
      33            2 :       id: json['id'].toString(),
      34            3 :       name: (attributes['displayName'] ?? '').toString().trim(),
      35            2 :       type: (attributes['accountType'] ?? '').toString(),
      36            2 :       balance: UpClient.parseAmount(attributes['balance']),
      37              :     );
      38              :   }
      39              : }
      40              : 
      41              : class UpTransaction {
      42              :   final String id;
      43              :   final DateTime date;
      44              :   final UpAmount amount;
      45              :   final String description;
      46              :   final bool held;
      47              :   // The other Up account of a transfer (incl. Round Ups and Savers)
      48              :   final String? transferAccount;
      49              : 
      50            1 :   const UpTransaction({
      51              :     required this.id,
      52              :     required this.date,
      53              :     required this.amount,
      54              :     required this.description,
      55              :     this.held = false,
      56              :     this.transferAccount,
      57              :   });
      58              : 
      59            1 :   factory UpTransaction.fromJson(Map<String, dynamic> json) {
      60            3 :     final attributes = json['attributes'] is Map ? json['attributes'] as Map : const {};
      61            3 :     final relationships = json['relationships'] is Map ? json['relationships'] as Map : const {};
      62            3 :     final transfer = relationships['transferAccount'] is Map ? relationships['transferAccount'] as Map : const {};
      63            3 :     final data = transfer['data'] is Map ? transfer['data'] as Map : null;
      64            1 :     return UpTransaction(
      65            2 :       id: json['id'].toString(),
      66            4 :       date: DateTime.parse(attributes['createdAt'].toString()).toLocal(),
      67              :       // Always in Australian dollars, foreign purchases are converted
      68            2 :       amount: UpClient.parseAmount(attributes['amount']),
      69            3 :       description: (attributes['description'] ?? attributes['rawText'] ?? '').toString().trim(),
      70            2 :       held: attributes['status'] != 'SETTLED',
      71            2 :       transferAccount: data?['id']?.toString(),
      72              :     );
      73              :   }
      74              : }
      75              : 
      76              : class UpClient {
      77            3 :   static final baseUrl = Uri.parse('https://api.up.com.au');
      78              :   static const timeout = Duration(seconds: 90);
      79              :   static const pageSize = 100;
      80              : 
      81              :   final http.Client _client;
      82              : 
      83            2 :   UpClient({http.Client? client}) : _client = client ?? http.Client();
      84              : 
      85            3 :   void close() => _client.close();
      86              : 
      87            1 :   static UpAmount parseAmount(dynamic json) {
      88            4 :     final value = json is Map ? double.tryParse('${json['value'] ?? ''}') : null;
      89              :     if (value == null) {
      90            0 :       throw UpException(AppLocale.labels.integrationInvalidAmount('$json'));
      91              :     }
      92            2 :     return (value: value, currency: (json['currencyCode'] ?? 'AUD').toString());
      93              :   }
      94              : 
      95            1 :   Future<Map<String, dynamic>> _get(String token, Uri uri) async {
      96              :     // Pages are followed by the absolute links of Up: only its own host receives the token
      97            6 :     if (uri.scheme != 'https' || uri.host != baseUrl.host) {
      98            0 :       throw UpException(AppLocale.labels.integrationUnexpectedResponse);
      99              :     }
     100            3 :     final response = await _client.get(uri, headers: {
     101            1 :       'Authorization': 'Bearer $token',
     102              :       'Accept': 'application/json',
     103            1 :     }).timeout(timeout);
     104              :     dynamic json;
     105              :     try {
     106            3 :       json = jsonDecode(utf8.decode(response.bodyBytes));
     107            0 :     } on FormatException {
     108              :       json = null;
     109              :     }
     110            3 :     if (response.statusCode == 200 && json is Map<String, dynamic>) {
     111              :       return json;
     112              :     }
     113            2 :     if (response.statusCode == 401 || response.statusCode == 403) {
     114            4 :       throw UpException(AppLocale.labels.integrationAccessDenied, response.statusCode);
     115              :     }
     116            0 :     final errors = json is Map && json['errors'] is List ? json['errors'] as List : const [];
     117            0 :     final error = errors.whereType<Map>().firstOrNull;
     118            0 :     final message = error?['detail'] ?? error?['title'];
     119            0 :     throw UpException(
     120              :       message != null
     121            0 :           ? AppLocale.labels.integrationServiceError('$message')
     122            0 :           : AppLocale.labels.integrationHttpError('${response.statusCode}'),
     123            0 :       response.statusCode,
     124              :     );
     125              :   }
     126              : 
     127              :   // JSON:API pagination: "links.next" until it is null
     128            1 :   Future<List<Map<String, dynamic>>> _list(String token, Uri first) async {
     129            1 :     final result = <Map<String, dynamic>>[];
     130              :     Uri? next = first;
     131              :     final visited = <Uri>{};
     132            1 :     while (next != null && visited.add(next)) {
     133            1 :       final json = await _get(token, next);
     134            3 :       result.addAll((json['data'] as List? ?? const []).whereType<Map<String, dynamic>>());
     135            3 :       final links = json['links'] is Map ? json['links'] as Map : const {};
     136            2 :       next = links['next'] is String ? Uri.tryParse(links['next']) : null;
     137              :     }
     138              :     return result;
     139              :   }
     140              : 
     141            4 :   Future<void> ping(String token) => _get(token, baseUrl.replace(path: '/api/v1/util/ping'));
     142              : 
     143            2 :   Future<List<UpAccount>> getAccounts(String token) async => (await _list(
     144              :         token,
     145            3 :         baseUrl.replace(path: '/api/v1/accounts', queryParameters: {'page[size]': '$pageSize'}),
     146              :       ))
     147            1 :           .map(UpAccount.fromJson)
     148            1 :           .toList();
     149              : 
     150            1 :   Future<List<UpTransaction>> getTransactions(String token, String accountId, {required DateTime since}) async =>
     151            1 :       (await _list(
     152              :         token,
     153            4 :         baseUrl.replace(path: '/api/v1/accounts/$accountId/transactions', queryParameters: {
     154              :           'page[size]': '$pageSize',
     155            2 :           'filter[since]': since.toUtc().toIso8601String(),
     156              :         }),
     157              :       ))
     158            1 :           .map(UpTransaction.fromJson)
     159            1 :           .toList();
     160              : }
        

Generated by: LCOV version 2.0-1