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:flutter_currency_picker/flutter_currency_picker.dart';
8 : import 'package:http/http.dart' as http;
9 :
10 : // Starling Bank Public API v2 with a Personal Access Token (https://developer.starlingbank.com)
11 : class StarlingException implements Exception {
12 : final String message;
13 : final int? statusCode;
14 :
15 0 : const StarlingException(this.message, [this.statusCode]);
16 :
17 0 : @override
18 0 : String toString() => message;
19 : }
20 :
21 : typedef StarlingAmount = ({double value, String currency});
22 :
23 : class StarlingAccount {
24 : final String id;
25 : final String defaultCategory;
26 : final String currency;
27 : final String name;
28 : final String type;
29 :
30 0 : const StarlingAccount({
31 : required this.id,
32 : required this.defaultCategory,
33 : required this.currency,
34 : this.name = '',
35 : this.type = '',
36 : });
37 :
38 0 : String get title => [name, currency].where((e) => e.isNotEmpty).join(' — ');
39 :
40 0 : factory StarlingAccount.fromJson(Map<String, dynamic> json) => StarlingAccount(
41 0 : id: json['accountUid'].toString(),
42 0 : defaultCategory: (json['defaultCategory'] ?? '').toString(),
43 0 : currency: (json['currency'] ?? 'GBP').toString(),
44 0 : name: (json['name'] ?? '').toString().trim(),
45 0 : type: (json['accountType'] ?? '').toString(),
46 : );
47 : }
48 :
49 : enum StarlingStatus {
50 : // Imported: money has moved (a refunded transaction is followed by its refund)
51 : booked,
52 : // Counted as pending: may still change
53 : pending,
54 : // Left out: no money has moved
55 : ignored;
56 :
57 0 : static StarlingStatus parse(String? value) => switch ((value ?? '').toUpperCase()) {
58 0 : 'SETTLED' || 'REFUNDED' => booked,
59 0 : 'PENDING' || 'UPCOMING' || 'RETRYING' => pending,
60 : _ => ignored,
61 : };
62 : }
63 :
64 : class StarlingFeedItem {
65 : final String id;
66 : final DateTime date;
67 : final double amount;
68 : final String currency;
69 : final String title;
70 : final StarlingStatus status;
71 :
72 0 : const StarlingFeedItem({
73 : required this.id,
74 : required this.date,
75 : required this.amount,
76 : required this.currency,
77 : required this.title,
78 : required this.status,
79 : });
80 :
81 0 : factory StarlingFeedItem.fromJson(Map<String, dynamic> json) {
82 0 : final amount = StarlingClient.parseAmount(json['amount']);
83 0 : final counterparty = (json['counterPartyName'] ?? '').toString().trim();
84 0 : final reference = (json['reference'] ?? '').toString().trim();
85 0 : return StarlingFeedItem(
86 0 : id: json['feedItemUid'].toString(),
87 0 : date: DateTime.parse(json['transactionTime'].toString()).toLocal(),
88 : // Amounts are always positive: the direction tells whether money comes in or goes out
89 0 : amount: json['direction'].toString().toUpperCase() == 'OUT' ? -amount.value.abs() : amount.value.abs(),
90 : currency: amount.currency,
91 0 : title: counterparty.isNotEmpty ? counterparty : reference,
92 0 : status: StarlingStatus.parse(json['status']?.toString()),
93 : );
94 : }
95 : }
96 :
97 : class StarlingClient {
98 0 : static final baseUrl = Uri.parse('https://api.starlingbank.com');
99 : static const timeout = Duration(seconds: 90);
100 :
101 : final http.Client _client;
102 :
103 0 : StarlingClient({http.Client? client}) : _client = client ?? http.Client();
104 :
105 0 : void close() => _client.close();
106 :
107 0 : static StarlingAmount parseAmount(dynamic json) {
108 0 : final currency = json is Map ? (json['currency'] ?? 'GBP').toString() : 'GBP';
109 0 : final minor = json is Map ? json['minorUnits'] : null;
110 0 : final value = minor is num ? minor : num.tryParse('${minor ?? ''}');
111 : if (value == null) {
112 0 : throw StarlingException(AppLocale.labels.integrationInvalidAmount('$json'));
113 : }
114 0 : final digits = CurrencyProvider.find(currency)?.decimalDigits ?? 2;
115 : var divider = 1;
116 0 : for (var i = 0; i < digits; i++) {
117 0 : divider *= 10;
118 : }
119 0 : return (value: value / divider, currency: currency);
120 : }
121 :
122 0 : static String _time(DateTime value) => '${value.toUtc().toIso8601String().split('.').first}.000Z';
123 :
124 0 : Future<Map<String, dynamic>> _get(String token, String path, [Map<String, String>? query]) async {
125 0 : final uri = baseUrl.replace(path: path, queryParameters: query == null || query.isEmpty ? null : query);
126 0 : final response = await _client.get(uri, headers: {
127 0 : 'Authorization': 'Bearer $token',
128 : 'Accept': 'application/json',
129 0 : }).timeout(timeout);
130 : dynamic json;
131 : try {
132 0 : json = jsonDecode(utf8.decode(response.bodyBytes));
133 0 : } on FormatException {
134 : json = null;
135 : }
136 0 : if (response.statusCode != 200) {
137 0 : final error = json is Map ? json['error']?.toString() : null;
138 0 : final errors = json is Map && json['errors'] is List ? json['errors'] as List : const [];
139 0 : final message = json is Map
140 0 : ? (json['error_description'] ?? errors.whereType<Map>().map((e) => e['message']).firstOrNull)?.toString()
141 : : null;
142 0 : if (response.statusCode == 403 && (error == 'insufficient_scope' || (message ?? '').contains('scope'))) {
143 0 : throw StarlingException(AppLocale.labels.starlingScopes, 403);
144 : }
145 0 : if (response.statusCode == 401 || response.statusCode == 403) {
146 0 : throw StarlingException(AppLocale.labels.integrationAccessDenied, response.statusCode);
147 : }
148 0 : throw StarlingException(
149 0 : message != null && message.isNotEmpty
150 0 : ? AppLocale.labels.integrationServiceError(message)
151 0 : : AppLocale.labels.integrationHttpError('${response.statusCode}'),
152 0 : response.statusCode,
153 : );
154 : }
155 0 : if (json is! Map<String, dynamic>) {
156 0 : throw StarlingException(AppLocale.labels.integrationUnexpectedResponse);
157 : }
158 : return json;
159 : }
160 :
161 0 : Future<List<StarlingAccount>> getAccounts(String token) async {
162 0 : final json = await _get(token, '/api/v2/accounts');
163 0 : return (json['accounts'] as List? ?? []).whereType<Map<String, dynamic>>().map(StarlingAccount.fromJson).toList();
164 : }
165 :
166 : // The effective balance includes pending transactions, as shown in the Starling app
167 0 : Future<StarlingAmount> getBalance(String token, String accountId) async {
168 0 : final json = await _get(token, '/api/v2/accounts/$accountId/balance');
169 0 : return parseAmount(json['effectiveBalance'] ?? json['clearedBalance']);
170 : }
171 :
172 : // Items of the account's main category changed since [from]; older ones (e.g. settled lately) are left out
173 0 : Future<List<StarlingFeedItem>> getFeed(String token, StarlingAccount account, {required DateTime from}) async {
174 0 : final json = await _get(
175 : token,
176 0 : '/api/v2/feed/account/${account.id}/category/${account.defaultCategory}',
177 0 : {'changesSince': _time(from)},
178 : );
179 0 : return (json['feedItems'] as List? ?? [])
180 0 : .whereType<Map<String, dynamic>>()
181 0 : .map(StarlingFeedItem.fromJson)
182 0 : .where((e) => !e.date.isBefore(from))
183 0 : .toList();
184 : }
185 : }
|