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 0 : 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 0 : const UpAccount({required this.id, required this.name, required this.balance, this.type = ''});
29 :
30 0 : factory UpAccount.fromJson(Map<String, dynamic> json) {
31 0 : final attributes = json['attributes'] is Map ? json['attributes'] as Map : const {};
32 0 : return UpAccount(
33 0 : id: json['id'].toString(),
34 0 : name: (attributes['displayName'] ?? '').toString().trim(),
35 0 : type: (attributes['accountType'] ?? '').toString(),
36 0 : 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 0 : 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 0 : factory UpTransaction.fromJson(Map<String, dynamic> json) {
60 0 : final attributes = json['attributes'] is Map ? json['attributes'] as Map : const {};
61 0 : final relationships = json['relationships'] is Map ? json['relationships'] as Map : const {};
62 0 : final transfer = relationships['transferAccount'] is Map ? relationships['transferAccount'] as Map : const {};
63 0 : final data = transfer['data'] is Map ? transfer['data'] as Map : null;
64 0 : return UpTransaction(
65 0 : id: json['id'].toString(),
66 0 : date: DateTime.parse(attributes['createdAt'].toString()).toLocal(),
67 : // Always in Australian dollars, foreign purchases are converted
68 0 : amount: UpClient.parseAmount(attributes['amount']),
69 0 : description: (attributes['description'] ?? attributes['rawText'] ?? '').toString().trim(),
70 0 : held: attributes['status'] != 'SETTLED',
71 0 : transferAccount: data?['id']?.toString(),
72 : );
73 : }
74 : }
75 :
76 : class UpClient {
77 0 : 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 0 : UpClient({http.Client? client}) : _client = client ?? http.Client();
84 :
85 0 : void close() => _client.close();
86 :
87 0 : static UpAmount parseAmount(dynamic json) {
88 0 : final value = json is Map ? double.tryParse('${json['value'] ?? ''}') : null;
89 : if (value == null) {
90 0 : throw UpException(AppLocale.labels.integrationInvalidAmount('$json'));
91 : }
92 0 : return (value: value, currency: (json['currencyCode'] ?? 'AUD').toString());
93 : }
94 :
95 0 : 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 0 : if (uri.scheme != 'https' || uri.host != baseUrl.host) {
98 0 : throw UpException(AppLocale.labels.integrationUnexpectedResponse);
99 : }
100 0 : final response = await _client.get(uri, headers: {
101 0 : 'Authorization': 'Bearer $token',
102 : 'Accept': 'application/json',
103 0 : }).timeout(timeout);
104 : dynamic json;
105 : try {
106 0 : json = jsonDecode(utf8.decode(response.bodyBytes));
107 0 : } on FormatException {
108 : json = null;
109 : }
110 0 : if (response.statusCode == 200 && json is Map<String, dynamic>) {
111 : return json;
112 : }
113 0 : if (response.statusCode == 401 || response.statusCode == 403) {
114 0 : 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 0 : Future<List<Map<String, dynamic>>> _list(String token, Uri first) async {
129 0 : final result = <Map<String, dynamic>>[];
130 : Uri? next = first;
131 : final visited = <Uri>{};
132 0 : while (next != null && visited.add(next)) {
133 0 : final json = await _get(token, next);
134 0 : result.addAll((json['data'] as List? ?? const []).whereType<Map<String, dynamic>>());
135 0 : final links = json['links'] is Map ? json['links'] as Map : const {};
136 0 : next = links['next'] is String ? Uri.tryParse(links['next']) : null;
137 : }
138 : return result;
139 : }
140 :
141 0 : Future<void> ping(String token) => _get(token, baseUrl.replace(path: '/api/v1/util/ping'));
142 :
143 0 : Future<List<UpAccount>> getAccounts(String token) async => (await _list(
144 : token,
145 0 : baseUrl.replace(path: '/api/v1/accounts', queryParameters: {'page[size]': '$pageSize'}),
146 : ))
147 0 : .map(UpAccount.fromJson)
148 0 : .toList();
149 :
150 0 : Future<List<UpTransaction>> getTransactions(String token, String accountId, {required DateTime since}) async =>
151 0 : (await _list(
152 : token,
153 0 : baseUrl.replace(path: '/api/v1/accounts/$accountId/transactions', queryParameters: {
154 : 'page[size]': '$pageSize',
155 0 : 'filter[since]': since.toUtc().toIso8601String(),
156 : }),
157 : ))
158 0 : .map(UpTransaction.fromJson)
159 0 : .toList();
160 : }
|