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:app_finance/_classes/integration/enablebanking/enablebanking_client.dart';
8 : import 'package:flutter_currency_picker/flutter_currency_picker.dart';
9 : import 'package:http/http.dart' as http;
10 :
11 : // Monzo Developer API (https://docs.monzo.com): OAuth 2.0 with the user's own (confidential) client,
12 : // each sign-in is approved in the Monzo app before any data is available
13 : class MonzoException implements Exception {
14 : final String message;
15 : final int? statusCode;
16 : final String? code;
17 :
18 1 : const MonzoException(this.message, [this.statusCode, this.code]);
19 :
20 0 : @override
21 0 : String toString() => message;
22 : }
23 :
24 : class MonzoTokens {
25 : final String accessToken;
26 : final String refreshToken;
27 : final DateTime expiresAt;
28 :
29 1 : const MonzoTokens({required this.accessToken, required this.refreshToken, required this.expiresAt});
30 :
31 2 : Map<String, dynamic> toJson() => {
32 1 : 'accessToken': accessToken,
33 1 : 'refreshToken': refreshToken,
34 2 : 'expiresAt': expiresAt.toIso8601String(),
35 : };
36 :
37 2 : factory MonzoTokens.fromJson(Map<String, dynamic> json) => MonzoTokens(
38 2 : accessToken: (json['accessToken'] ?? '').toString(),
39 2 : refreshToken: (json['refreshToken'] ?? '').toString(),
40 3 : expiresAt: DateTime.tryParse((json['expiresAt'] ?? '').toString()) ?? DateTime.fromMillisecondsSinceEpoch(0),
41 : );
42 : }
43 :
44 : class MonzoAccount {
45 : final String id;
46 : final String description;
47 : final String type;
48 : final String currency;
49 : final String? accountNumber;
50 : final bool isClosed;
51 :
52 1 : const MonzoAccount({
53 : required this.id,
54 : required this.description,
55 : this.type = '',
56 : this.currency = 'GBP',
57 : this.accountNumber,
58 : this.isClosed = false,
59 : });
60 :
61 1 : String get title {
62 1 : final number = accountNumber ?? '';
63 6 : final masked = number.length > 4 ? '…${number.substring(number.length - 4)}' : number;
64 6 : return [description, masked].where((e) => e.isNotEmpty).join(' ');
65 : }
66 :
67 1 : factory MonzoAccount.fromJson(Map<String, dynamic> json) {
68 5 : final owners = (json['owners'] as List? ?? []).whereType<Map>().map((e) => e['preferred_name']).whereType<String>();
69 3 : final description = (json['description'] ?? '').toString().trim();
70 1 : return MonzoAccount(
71 2 : id: json['id'].toString(),
72 : // Descriptions of newer accounts are technical ids (e.g. "user_000…"): the owner's name is shown instead
73 2 : description: description.isEmpty || description.startsWith('user_') ? owners.join(', ') : description,
74 2 : type: (json['type'] ?? '').toString(),
75 2 : currency: (json['currency'] ?? 'GBP').toString(),
76 2 : accountNumber: json['account_number']?.toString(),
77 2 : isClosed: json['closed'] == true,
78 : );
79 : }
80 : }
81 :
82 : class MonzoBalance {
83 : final double balance;
84 : final String currency;
85 :
86 1 : const MonzoBalance({required this.balance, required this.currency});
87 : }
88 :
89 : class MonzoTransaction {
90 : final String id;
91 : final DateTime created;
92 : final double amount;
93 : final String currency;
94 : final String description;
95 : final bool pending;
96 : final bool declined;
97 :
98 1 : const MonzoTransaction({
99 : required this.id,
100 : required this.created,
101 : required this.amount,
102 : required this.currency,
103 : required this.description,
104 : this.pending = false,
105 : this.declined = false,
106 : });
107 :
108 1 : factory MonzoTransaction.fromJson(Map<String, dynamic> json) {
109 2 : final currency = (json['currency'] ?? 'GBP').toString();
110 1 : final merchant = json['merchant'];
111 4 : final merchantName = merchant is Map ? merchant['name']?.toString().trim() : null;
112 2 : final settled = (json['settled'] ?? '').toString();
113 1 : return MonzoTransaction(
114 2 : id: json['id'].toString(),
115 4 : created: DateTime.parse(json['created'].toString()).toLocal(),
116 2 : amount: MonzoClient.fromMinor(json['amount'], currency),
117 : currency: currency,
118 1 : description: merchantName != null && merchantName.isNotEmpty
119 : ? merchantName
120 3 : : (json['description'] ?? '').toString().trim(),
121 : // Authorised, but not "complete" yet: the amount may change
122 1 : pending: settled.isEmpty,
123 3 : declined: (json['decline_reason'] ?? '').toString().isNotEmpty,
124 : );
125 : }
126 : }
127 :
128 : class MonzoClient {
129 3 : static final authUrl = Uri.parse('https://auth.monzo.com/');
130 3 : static final baseUrl = Uri.parse('https://api.monzo.com');
131 : static const timeout = Duration(seconds: 90);
132 : static const pageSize = 100;
133 : // The full history is readable only shortly after the approval in the app, later only these days
134 : static const fullHistoryWindow = Duration(minutes: 5);
135 : static const historyLimit = Duration(days: 89);
136 :
137 : final http.Client _client;
138 : final String clientId;
139 : final String clientSecret;
140 : final DateTime Function() now;
141 : MonzoTokens? tokens;
142 : // Refreshed tokens are to be stored: a refresh token can be used only once
143 : final Future<void> Function(MonzoTokens tokens)? onTokens;
144 :
145 1 : MonzoClient({
146 : required this.clientId,
147 : required this.clientSecret,
148 : this.tokens,
149 : this.onTokens,
150 : http.Client? client,
151 : DateTime Function()? now,
152 0 : }) : _client = client ?? http.Client(),
153 : now = now ?? DateTime.now;
154 :
155 0 : void close() => _client.close();
156 :
157 1 : static double fromMinor(dynamic value, String currency) {
158 1 : final minor = value is num ? value : num.tryParse('${value ?? ''}');
159 : if (minor == null) {
160 0 : throw MonzoException(AppLocale.labels.integrationInvalidAmount('$value'));
161 : }
162 1 : final digits = CurrencyProvider.find(currency)?.decimalDigits ?? 2;
163 : var divider = 1;
164 2 : for (var i = 0; i < digits; i++) {
165 1 : divider *= 10;
166 : }
167 1 : return minor / divider;
168 : }
169 :
170 6 : static String _time(DateTime value) => '${value.toUtc().toIso8601String().split('.').first}Z';
171 :
172 4 : Uri authorizationUrl({required String redirectUrl, required String state}) => authUrl.replace(queryParameters: {
173 1 : 'client_id': clientId,
174 : 'redirect_uri': redirectUrl,
175 : 'response_type': 'code',
176 : 'state': state,
177 : });
178 :
179 : // [input] is the redirect address (deep link or a copy of the browser's address) or the bare code
180 1 : static String extractCode(String input, {String? state, bool requireState = false}) {
181 : try {
182 1 : return EnableBankingClient.extractCode(input, state: state, requireState: requireState);
183 0 : } on EnableBankingException catch (e) {
184 0 : throw MonzoException(e.message);
185 : }
186 : }
187 :
188 1 : static dynamic _decode(http.Response response) {
189 2 : final text = utf8.decode(response.bodyBytes);
190 : try {
191 2 : return text.isEmpty ? null : jsonDecode(text);
192 0 : } on FormatException {
193 : return null;
194 : }
195 : }
196 :
197 1 : Never _fail(http.Response response, dynamic json) {
198 1 : final status = response.statusCode;
199 3 : final code = json is Map ? json['code']?.toString() : null;
200 3 : final message = json is Map ? (json['message'] ?? json['error_description'] ?? json['error'])?.toString() : null;
201 2 : if (status == 403 && (code ?? '').contains('insufficient_permissions')) {
202 3 : throw MonzoException(AppLocale.labels.monzoApprove, status, code);
203 : }
204 0 : if (status == 403 && (code ?? '').contains('verification_required')) {
205 0 : throw MonzoException(
206 0 : AppLocale.labels.monzoHistoryLimited(_time(now().subtract(historyLimit)).substring(0, 10)), status, code);
207 : }
208 0 : if (status == 401) {
209 0 : throw MonzoException(AppLocale.labels.monzoExpired, status, code);
210 : }
211 0 : if (status == 403) {
212 0 : throw MonzoException(AppLocale.labels.integrationAccessDenied, status, code);
213 : }
214 0 : throw MonzoException(
215 0 : message != null && message.isNotEmpty
216 0 : ? AppLocale.labels.integrationServiceError(message)
217 0 : : AppLocale.labels.integrationHttpError('$status'),
218 : status,
219 : code,
220 : );
221 : }
222 :
223 1 : Future<MonzoTokens> _token(Map<String, String> fields) async {
224 2 : final response = await _client.post(
225 2 : baseUrl.replace(path: '/oauth2/token'),
226 1 : headers: {'Accept': 'application/json'},
227 6 : body: {'client_id': clientId, 'client_secret': clientSecret, ...fields},
228 1 : ).timeout(timeout);
229 1 : final json = _decode(response);
230 2 : if (response.statusCode != 200) {
231 0 : if (fields['grant_type'] == 'refresh_token' && response.statusCode < 500) {
232 0 : throw MonzoException(AppLocale.labels.monzoExpired, 401);
233 : }
234 : // A wrong client secret, redirect URL, or an already used code
235 0 : if (response.statusCode == 400 || response.statusCode == 401) {
236 0 : throw MonzoException(AppLocale.labels.integrationAccessDenied, response.statusCode);
237 : }
238 0 : _fail(response, json);
239 : }
240 3 : final access = json is Map ? json['access_token']?.toString() : null;
241 1 : if (access == null || access.isEmpty) {
242 0 : throw MonzoException(AppLocale.labels.integrationUnexpectedResponse);
243 : }
244 3 : final seconds = int.tryParse('${json['expires_in'] ?? ''}') ?? 21600;
245 1 : final result = MonzoTokens(
246 : accessToken: access,
247 : // Non-confidential clients get no refresh token: the sign-in is repeated when the access expires
248 2 : refreshToken: (json['refresh_token'] ?? '').toString(),
249 4 : expiresAt: now().add(Duration(seconds: seconds)),
250 : );
251 1 : tokens = result;
252 2 : await onTokens?.call(result);
253 : return result;
254 : }
255 :
256 3 : Future<MonzoTokens> exchange(String code, {required String redirectUrl}) => _token({
257 : 'grant_type': 'authorization_code',
258 : 'redirect_uri': redirectUrl,
259 : 'code': code,
260 : });
261 :
262 0 : Future<MonzoTokens> refresh() async {
263 0 : final current = tokens;
264 0 : if (current == null || current.refreshToken.isEmpty) {
265 0 : throw MonzoException(AppLocale.labels.monzoExpired, 401);
266 : }
267 0 : return _token({'grant_type': 'refresh_token', 'refresh_token': current.refreshToken});
268 : }
269 :
270 1 : Future<Map<String, dynamic>> _get(String path, Map<String, dynamic> query) async {
271 1 : var current = tokens;
272 : if (current == null) {
273 0 : throw MonzoException(AppLocale.labels.monzoExpired, 401);
274 : }
275 4 : if (!now().isBefore(current.expiresAt) && current.refreshToken.isNotEmpty) {
276 0 : current = await refresh();
277 : }
278 2 : final uri = baseUrl.replace(path: path, queryParameters: query);
279 4 : var response = await _client.get(uri, headers: _headers(current)).timeout(timeout);
280 : // Expired (or revoked) earlier than announced
281 2 : if (response.statusCode == 401 && current.refreshToken.isNotEmpty) {
282 0 : current = await refresh();
283 0 : response = await _client.get(uri, headers: _headers(current)).timeout(timeout);
284 : }
285 1 : final json = _decode(response);
286 2 : if (response.statusCode != 200) {
287 1 : _fail(response, json);
288 : }
289 1 : if (json is! Map<String, dynamic>) {
290 0 : throw MonzoException(AppLocale.labels.integrationUnexpectedResponse);
291 : }
292 : return json;
293 : }
294 :
295 2 : static Map<String, String> _headers(MonzoTokens tokens) => {
296 2 : 'Authorization': 'Bearer ${tokens.accessToken}',
297 : 'Accept': 'application/json',
298 : };
299 :
300 1 : Future<List<MonzoAccount>> getAccounts() async {
301 2 : final json = await _get('/accounts', {});
302 4 : return (json['accounts'] as List? ?? []).whereType<Map<String, dynamic>>().map(MonzoAccount.fromJson).toList();
303 : }
304 :
305 1 : Future<MonzoBalance> getBalance(String accountId) async {
306 2 : final json = await _get('/balance', {'account_id': accountId});
307 2 : final currency = (json['currency'] ?? 'GBP').toString();
308 3 : return MonzoBalance(balance: fromMinor(json['balance'], currency), currency: currency);
309 : }
310 :
311 : // Oldest first; the following pages continue after the id of the last transaction
312 1 : Future<List<MonzoTransaction>> getTransactions(String accountId, {required DateTime since}) async {
313 1 : final result = <MonzoTransaction>[];
314 3 : final before = _time(now());
315 1 : String cursor = _time(since);
316 : while (true) {
317 2 : final json = await _get('/transactions', {
318 : 'account_id': accountId,
319 : 'since': cursor,
320 : 'before': before,
321 : 'limit': '$pageSize',
322 : 'expand[]': 'merchant',
323 : });
324 1 : final page = (json['transactions'] as List? ?? [])
325 1 : .whereType<Map<String, dynamic>>()
326 1 : .map(MonzoTransaction.fromJson)
327 1 : .toList();
328 1 : result.addAll(page);
329 2 : if (page.length < pageSize || page.last.id == cursor) {
330 : break;
331 : }
332 0 : cursor = page.last.id;
333 : }
334 : return result;
335 : }
336 :
337 1 : Future<void> logout() async {
338 1 : final current = tokens;
339 : if (current == null) {
340 : return;
341 : }
342 6 : await _client.post(baseUrl.replace(path: '/oauth2/logout'), headers: _headers(current)).timeout(timeout);
343 : }
344 : }
|