LCOV - code coverage report
Current view: top level - lib/_classes/integration/monzo - monzo_client.dart Coverage Total Hit
Test: lcov.info Lines: 0.0 % 149 0
Test Date: 2026-12-05 10:54:13 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: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            0 :   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            0 :   const MonzoTokens({required this.accessToken, required this.refreshToken, required this.expiresAt});
      30              : 
      31            0 :   Map<String, dynamic> toJson() => {
      32            0 :         'accessToken': accessToken,
      33            0 :         'refreshToken': refreshToken,
      34            0 :         'expiresAt': expiresAt.toIso8601String(),
      35              :       };
      36              : 
      37            0 :   factory MonzoTokens.fromJson(Map<String, dynamic> json) => MonzoTokens(
      38            0 :         accessToken: (json['accessToken'] ?? '').toString(),
      39            0 :         refreshToken: (json['refreshToken'] ?? '').toString(),
      40            0 :         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            0 :   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            0 :   String get title {
      62            0 :     final number = accountNumber ?? '';
      63            0 :     final masked = number.length > 4 ? '…${number.substring(number.length - 4)}' : number;
      64            0 :     return [description, masked].where((e) => e.isNotEmpty).join(' ');
      65              :   }
      66              : 
      67            0 :   factory MonzoAccount.fromJson(Map<String, dynamic> json) {
      68            0 :     final owners = (json['owners'] as List? ?? []).whereType<Map>().map((e) => e['preferred_name']).whereType<String>();
      69            0 :     final description = (json['description'] ?? '').toString().trim();
      70            0 :     return MonzoAccount(
      71            0 :       id: json['id'].toString(),
      72              :       // Descriptions of newer accounts are technical ids (e.g. "user_000…"): the owner's name is shown instead
      73            0 :       description: description.isEmpty || description.startsWith('user_') ? owners.join(', ') : description,
      74            0 :       type: (json['type'] ?? '').toString(),
      75            0 :       currency: (json['currency'] ?? 'GBP').toString(),
      76            0 :       accountNumber: json['account_number']?.toString(),
      77            0 :       isClosed: json['closed'] == true,
      78              :     );
      79              :   }
      80              : }
      81              : 
      82              : class MonzoBalance {
      83              :   final double balance;
      84              :   final String currency;
      85              : 
      86            0 :   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            0 :   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            0 :   factory MonzoTransaction.fromJson(Map<String, dynamic> json) {
     109            0 :     final currency = (json['currency'] ?? 'GBP').toString();
     110            0 :     final merchant = json['merchant'];
     111            0 :     final merchantName = merchant is Map ? merchant['name']?.toString().trim() : null;
     112            0 :     final settled = (json['settled'] ?? '').toString();
     113            0 :     return MonzoTransaction(
     114            0 :       id: json['id'].toString(),
     115            0 :       created: DateTime.parse(json['created'].toString()).toLocal(),
     116            0 :       amount: MonzoClient.fromMinor(json['amount'], currency),
     117              :       currency: currency,
     118            0 :       description: merchantName != null && merchantName.isNotEmpty
     119              :           ? merchantName
     120            0 :           : (json['description'] ?? '').toString().trim(),
     121              :       // Authorised, but not "complete" yet: the amount may change
     122            0 :       pending: settled.isEmpty,
     123            0 :       declined: (json['decline_reason'] ?? '').toString().isNotEmpty,
     124              :     );
     125              :   }
     126              : }
     127              : 
     128              : class MonzoClient {
     129            0 :   static final authUrl = Uri.parse('https://auth.monzo.com/');
     130            0 :   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            0 :   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            0 :   static double fromMinor(dynamic value, String currency) {
     158            0 :     final minor = value is num ? value : num.tryParse('${value ?? ''}');
     159              :     if (minor == null) {
     160            0 :       throw MonzoException(AppLocale.labels.integrationInvalidAmount('$value'));
     161              :     }
     162            0 :     final digits = CurrencyProvider.find(currency)?.decimalDigits ?? 2;
     163              :     var divider = 1;
     164            0 :     for (var i = 0; i < digits; i++) {
     165            0 :       divider *= 10;
     166              :     }
     167            0 :     return minor / divider;
     168              :   }
     169              : 
     170            0 :   static String _time(DateTime value) => '${value.toUtc().toIso8601String().split('.').first}Z';
     171              : 
     172            0 :   Uri authorizationUrl({required String redirectUrl, required String state}) => authUrl.replace(queryParameters: {
     173            0 :         '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            0 :   static String extractCode(String input, {String? state, bool requireState = false}) {
     181              :     try {
     182            0 :       return EnableBankingClient.extractCode(input, state: state, requireState: requireState);
     183            0 :     } on EnableBankingException catch (e) {
     184            0 :       throw MonzoException(e.message);
     185              :     }
     186              :   }
     187              : 
     188            0 :   static dynamic _decode(http.Response response) {
     189            0 :     final text = utf8.decode(response.bodyBytes);
     190              :     try {
     191            0 :       return text.isEmpty ? null : jsonDecode(text);
     192            0 :     } on FormatException {
     193              :       return null;
     194              :     }
     195              :   }
     196              : 
     197            0 :   Never _fail(http.Response response, dynamic json) {
     198            0 :     final status = response.statusCode;
     199            0 :     final code = json is Map ? json['code']?.toString() : null;
     200            0 :     final message = json is Map ? (json['message'] ?? json['error_description'] ?? json['error'])?.toString() : null;
     201            0 :     if (status == 403 && (code ?? '').contains('insufficient_permissions')) {
     202            0 :       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            0 :   Future<MonzoTokens> _token(Map<String, String> fields) async {
     224            0 :     final response = await _client.post(
     225            0 :       baseUrl.replace(path: '/oauth2/token'),
     226            0 :       headers: {'Accept': 'application/json'},
     227            0 :       body: {'client_id': clientId, 'client_secret': clientSecret, ...fields},
     228            0 :     ).timeout(timeout);
     229            0 :     final json = _decode(response);
     230            0 :     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            0 :     final access = json is Map ? json['access_token']?.toString() : null;
     241            0 :     if (access == null || access.isEmpty) {
     242            0 :       throw MonzoException(AppLocale.labels.integrationUnexpectedResponse);
     243              :     }
     244            0 :     final seconds = int.tryParse('${json['expires_in'] ?? ''}') ?? 21600;
     245            0 :     final result = MonzoTokens(
     246              :       accessToken: access,
     247              :       // Non-confidential clients get no refresh token: the sign-in is repeated when the access expires
     248            0 :       refreshToken: (json['refresh_token'] ?? '').toString(),
     249            0 :       expiresAt: now().add(Duration(seconds: seconds)),
     250              :     );
     251            0 :     tokens = result;
     252            0 :     await onTokens?.call(result);
     253              :     return result;
     254              :   }
     255              : 
     256            0 :   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            0 :   Future<Map<String, dynamic>> _get(String path, Map<String, dynamic> query) async {
     271            0 :     var current = tokens;
     272              :     if (current == null) {
     273            0 :       throw MonzoException(AppLocale.labels.monzoExpired, 401);
     274              :     }
     275            0 :     if (!now().isBefore(current.expiresAt) && current.refreshToken.isNotEmpty) {
     276            0 :       current = await refresh();
     277              :     }
     278            0 :     final uri = baseUrl.replace(path: path, queryParameters: query);
     279            0 :     var response = await _client.get(uri, headers: _headers(current)).timeout(timeout);
     280              :     // Expired (or revoked) earlier than announced
     281            0 :     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            0 :     final json = _decode(response);
     286            0 :     if (response.statusCode != 200) {
     287            0 :       _fail(response, json);
     288              :     }
     289            0 :     if (json is! Map<String, dynamic>) {
     290            0 :       throw MonzoException(AppLocale.labels.integrationUnexpectedResponse);
     291              :     }
     292              :     return json;
     293              :   }
     294              : 
     295            0 :   static Map<String, String> _headers(MonzoTokens tokens) => {
     296            0 :         'Authorization': 'Bearer ${tokens.accessToken}',
     297              :         'Accept': 'application/json',
     298              :       };
     299              : 
     300            0 :   Future<List<MonzoAccount>> getAccounts() async {
     301            0 :     final json = await _get('/accounts', {});
     302            0 :     return (json['accounts'] as List? ?? []).whereType<Map<String, dynamic>>().map(MonzoAccount.fromJson).toList();
     303              :   }
     304              : 
     305            0 :   Future<MonzoBalance> getBalance(String accountId) async {
     306            0 :     final json = await _get('/balance', {'account_id': accountId});
     307            0 :     final currency = (json['currency'] ?? 'GBP').toString();
     308            0 :     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            0 :   Future<List<MonzoTransaction>> getTransactions(String accountId, {required DateTime since}) async {
     313            0 :     final result = <MonzoTransaction>[];
     314            0 :     final before = _time(now());
     315            0 :     String cursor = _time(since);
     316              :     while (true) {
     317            0 :       final json = await _get('/transactions', {
     318              :         'account_id': accountId,
     319              :         'since': cursor,
     320              :         'before': before,
     321              :         'limit': '$pageSize',
     322              :         'expand[]': 'merchant',
     323              :       });
     324            0 :       final page = (json['transactions'] as List? ?? [])
     325            0 :           .whereType<Map<String, dynamic>>()
     326            0 :           .map(MonzoTransaction.fromJson)
     327            0 :           .toList();
     328            0 :       result.addAll(page);
     329            0 :       if (page.length < pageSize || page.last.id == cursor) {
     330              :         break;
     331              :       }
     332            0 :       cursor = page.last.id;
     333              :     }
     334              :     return result;
     335              :   }
     336              : 
     337            0 :   Future<void> logout() async {
     338            0 :     final current = tokens;
     339              :     if (current == null) {
     340              :       return;
     341              :     }
     342            0 :     await _client.post(baseUrl.replace(path: '/oauth2/logout'), headers: _headers(current)).timeout(timeout);
     343              :   }
     344              : }
        

Generated by: LCOV version 2.0-1