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 : // Akahu API with a personal app (https://developers.akahu.nz/docs/personal-apps)
10 : class AkahuException implements Exception {
11 : final String message;
12 : final int? statusCode;
13 :
14 1 : const AkahuException(this.message, [this.statusCode]);
15 :
16 0 : @override
17 0 : String toString() => message;
18 : }
19 :
20 : typedef AkahuTokens = ({String appToken, String userToken});
21 :
22 : class AkahuAccount {
23 : final String id;
24 : final String name;
25 : final String institution;
26 : final String? number;
27 : final String currency;
28 : final double? balance;
29 : final bool isActive;
30 : final bool hasTransactions;
31 :
32 1 : const AkahuAccount({
33 : required this.id,
34 : required this.name,
35 : this.institution = '',
36 : this.number,
37 : this.currency = 'NZD',
38 : this.balance,
39 : this.isActive = true,
40 : this.hasTransactions = true,
41 : });
42 :
43 2 : String get title => [
44 1 : institution,
45 7 : [name, number ?? ''].where((e) => e.isNotEmpty).join(' ')
46 4 : ].where((e) => e.isNotEmpty).join(' — ');
47 :
48 1 : factory AkahuAccount.fromJson(Map<String, dynamic> json) {
49 3 : final connection = json['connection'] is Map ? json['connection'] as Map : const {};
50 3 : final balance = json['balance'] is Map ? json['balance'] as Map : const {};
51 4 : final attributes = (json['attributes'] as List? ?? const []).map((e) => '$e');
52 1 : final current = balance['current'];
53 1 : return AkahuAccount(
54 2 : id: json['_id'].toString(),
55 3 : name: (json['name'] ?? '').toString().trim(),
56 3 : institution: (connection['name'] ?? '').toString().trim(),
57 2 : number: json['formatted_account']?.toString(),
58 2 : currency: (balance['currency'] ?? 'NZD').toString(),
59 2 : balance: current is num ? current.toDouble() : double.tryParse('${current ?? ''}'),
60 : // Akahu keeps serving its cached copy of an inactive account
61 2 : isActive: json['status'] != 'INACTIVE',
62 2 : hasTransactions: attributes.isEmpty || attributes.contains('TRANSACTIONS'),
63 : );
64 : }
65 : }
66 :
67 : class AkahuTransaction {
68 : final String id;
69 : final DateTime date;
70 : final double amount;
71 : final String description;
72 : // Enriched data: the NZ Financial Category Codes (NZFCC) name and its personal finance group
73 : final List<String> categories;
74 :
75 1 : const AkahuTransaction({
76 : required this.id,
77 : required this.date,
78 : required this.amount,
79 : required this.description,
80 : this.categories = const [],
81 : });
82 :
83 1 : factory AkahuTransaction.fromJson(Map<String, dynamic> json) {
84 3 : final merchant = json['merchant'] is Map ? json['merchant'] as Map : const {};
85 3 : final category = json['category'] is Map ? json['category'] as Map : const {};
86 3 : final groups = category['groups'] is Map ? category['groups'] as Map : const {};
87 3 : final group = groups['personal_finance'] is Map ? groups['personal_finance'] as Map : const {};
88 3 : final name = (merchant['name'] ?? '').toString().trim();
89 1 : return AkahuTransaction(
90 2 : id: json['_id'].toString(),
91 4 : date: DateTime.parse(json['date'].toString()).toLocal(),
92 2 : amount: AkahuClient.parseAmount(json['amount']),
93 4 : description: name.isNotEmpty ? name : (json['description'] ?? '').toString().trim(),
94 8 : categories: [category['name'], group['name']].whereType<String>().where((e) => e.isNotEmpty).toList(),
95 : );
96 : }
97 : }
98 :
99 : class AkahuClient {
100 3 : static final baseUrl = Uri.parse('https://api.akahu.io');
101 : static const timeout = Duration(seconds: 90);
102 :
103 : final http.Client _client;
104 :
105 1 : AkahuClient({http.Client? client}) : _client = client ?? http.Client();
106 :
107 0 : void close() => _client.close();
108 :
109 1 : static double parseAmount(dynamic value) {
110 2 : final result = value is num ? value.toDouble() : double.tryParse('${value ?? ''}');
111 : if (result == null) {
112 0 : throw AkahuException(AppLocale.labels.integrationInvalidAmount('$value'));
113 : }
114 : return result;
115 : }
116 :
117 1 : Future<Map<String, dynamic>> _request(String method, AkahuTokens tokens, String path,
118 : [Map<String, String>? query]) async {
119 3 : final uri = baseUrl.replace(path: path, queryParameters: query == null || query.isEmpty ? null : query);
120 1 : final request = http.Request(method, uri)
121 3 : ..headers.addAll({
122 1 : 'Authorization': 'Bearer ${tokens.userToken}',
123 : 'X-Akahu-Id': tokens.appToken,
124 : 'Accept': 'application/json',
125 : });
126 4 : final response = await http.Response.fromStream(await _client.send(request).timeout(timeout));
127 : dynamic json;
128 : try {
129 3 : json = jsonDecode(utf8.decode(response.bodyBytes));
130 0 : } on FormatException {
131 : json = null;
132 : }
133 5 : if (response.statusCode == 200 && json is Map<String, dynamic> && json['success'] != false) {
134 : return json;
135 : }
136 3 : final message = json is Map ? json['message']?.toString() : null;
137 4 : if (response.statusCode == 401 || response.statusCode == 403) {
138 4 : throw AkahuException(AppLocale.labels.integrationAccessDenied, response.statusCode);
139 : }
140 1 : throw AkahuException(
141 1 : message != null && message.isNotEmpty
142 2 : ? AppLocale.labels.integrationServiceError(message)
143 2 : : (response.statusCode == 200
144 2 : ? AppLocale.labels.integrationUnexpectedResponse
145 0 : : AppLocale.labels.integrationHttpError('${response.statusCode}')),
146 1 : response.statusCode,
147 : );
148 : }
149 :
150 1 : static List<Map<String, dynamic>> _items(Map<String, dynamic> json) =>
151 3 : (json['items'] as List? ?? const []).whereType<Map<String, dynamic>>().toList();
152 :
153 1 : Future<List<AkahuAccount>> getAccounts(AkahuTokens tokens) async =>
154 4 : _items(await _request('GET', tokens, '/v1/accounts')).map(AkahuAccount.fromJson).toList();
155 :
156 : // Settled transactions dated from [from] on, page by page (the start of the range is exclusive)
157 1 : Future<List<AkahuTransaction>> getTransactions(AkahuTokens tokens, String accountId, {required DateTime from}) async {
158 3 : final start = from.toUtc().subtract(const Duration(milliseconds: 1)).toIso8601String();
159 1 : final result = <AkahuTransaction>[];
160 : String? cursor;
161 : do {
162 3 : final json = await _request('GET', tokens, '/v1/accounts/$accountId/transactions', {
163 1 : 'start': start,
164 1 : if (cursor != null) 'cursor': cursor,
165 : });
166 3 : result.addAll(_items(json).map(AkahuTransaction.fromJson));
167 4 : final next = json['cursor'] is Map ? (json['cursor'] as Map)['next'] : null;
168 3 : cursor = next is String && next.isNotEmpty && next != cursor ? next : null;
169 : } while (cursor != null);
170 : return result;
171 : }
172 :
173 : // Pending transactions have no identifier and may change completely: they are only counted
174 1 : Future<int> countPending(AkahuTokens tokens, String accountId) async =>
175 4 : _items(await _request('GET', tokens, '/v1/accounts/$accountId/transactions/pending')).length;
176 :
177 : // Akahu may ignore it within the rest period (an hour for personal apps)
178 2 : Future<void> refresh(AkahuTokens tokens) => _request('POST', tokens, '/v1/refresh');
179 : }
|