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 1 : 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 1 : const StarlingAccount({
31 : required this.id,
32 : required this.defaultCategory,
33 : required this.currency,
34 : this.name = '',
35 : this.type = '',
36 : });
37 :
38 8 : String get title => [name, currency].where((e) => e.isNotEmpty).join(' — ');
39 :
40 2 : factory StarlingAccount.fromJson(Map<String, dynamic> json) => StarlingAccount(
41 2 : id: json['accountUid'].toString(),
42 2 : defaultCategory: (json['defaultCategory'] ?? '').toString(),
43 2 : currency: (json['currency'] ?? 'GBP').toString(),
44 3 : name: (json['name'] ?? '').toString().trim(),
45 2 : 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 2 : static StarlingStatus parse(String? value) => switch ((value ?? '').toUpperCase()) {
58 2 : 'SETTLED' || 'REFUNDED' => booked,
59 1 : '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 1 : 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 1 : factory StarlingFeedItem.fromJson(Map<String, dynamic> json) {
82 2 : final amount = StarlingClient.parseAmount(json['amount']);
83 3 : final counterparty = (json['counterPartyName'] ?? '').toString().trim();
84 3 : final reference = (json['reference'] ?? '').toString().trim();
85 1 : return StarlingFeedItem(
86 2 : id: json['feedItemUid'].toString(),
87 4 : date: DateTime.parse(json['transactionTime'].toString()).toLocal(),
88 : // Amounts are always positive: the direction tells whether money comes in or goes out
89 6 : amount: json['direction'].toString().toUpperCase() == 'OUT' ? -amount.value.abs() : amount.value.abs(),
90 : currency: amount.currency,
91 1 : title: counterparty.isNotEmpty ? counterparty : reference,
92 3 : status: StarlingStatus.parse(json['status']?.toString()),
93 : );
94 : }
95 : }
96 :
97 : class StarlingClient {
98 3 : static final baseUrl = Uri.parse('https://api.starlingbank.com');
99 : static const timeout = Duration(seconds: 90);
100 :
101 : final http.Client _client;
102 :
103 2 : StarlingClient({http.Client? client}) : _client = client ?? http.Client();
104 :
105 3 : void close() => _client.close();
106 :
107 1 : static StarlingAmount parseAmount(dynamic json) {
108 3 : final currency = json is Map ? (json['currency'] ?? 'GBP').toString() : 'GBP';
109 2 : final minor = json is Map ? json['minorUnits'] : null;
110 1 : final value = minor is num ? minor : num.tryParse('${minor ?? ''}');
111 : if (value == null) {
112 0 : throw StarlingException(AppLocale.labels.integrationInvalidAmount('$json'));
113 : }
114 1 : final digits = CurrencyProvider.find(currency)?.decimalDigits ?? 2;
115 : var divider = 1;
116 2 : for (var i = 0; i < digits; i++) {
117 1 : divider *= 10;
118 : }
119 1 : return (value: value / divider, currency: currency);
120 : }
121 :
122 6 : static String _time(DateTime value) => '${value.toUtc().toIso8601String().split('.').first}.000Z';
123 :
124 1 : Future<Map<String, dynamic>> _get(String token, String path, [Map<String, String>? query]) async {
125 3 : final uri = baseUrl.replace(path: path, queryParameters: query == null || query.isEmpty ? null : query);
126 3 : final response = await _client.get(uri, headers: {
127 1 : 'Authorization': 'Bearer $token',
128 : 'Accept': 'application/json',
129 1 : }).timeout(timeout);
130 : dynamic json;
131 : try {
132 3 : json = jsonDecode(utf8.decode(response.bodyBytes));
133 0 : } on FormatException {
134 : json = null;
135 : }
136 2 : if (response.statusCode != 200) {
137 3 : final error = json is Map ? json['error']?.toString() : null;
138 3 : final errors = json is Map && json['errors'] is List ? json['errors'] as List : const [];
139 1 : final message = json is Map
140 4 : ? (json['error_description'] ?? errors.whereType<Map>().map((e) => e['message']).firstOrNull)?.toString()
141 : : null;
142 2 : if (response.statusCode == 403 && (error == 'insufficient_scope' || (message ?? '').contains('scope'))) {
143 0 : throw StarlingException(AppLocale.labels.starlingScopes, 403);
144 : }
145 2 : if (response.statusCode == 401 || response.statusCode == 403) {
146 4 : 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 1 : if (json is! Map<String, dynamic>) {
156 0 : throw StarlingException(AppLocale.labels.integrationUnexpectedResponse);
157 : }
158 : return json;
159 : }
160 :
161 1 : Future<List<StarlingAccount>> getAccounts(String token) async {
162 1 : final json = await _get(token, '/api/v2/accounts');
163 4 : 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 1 : Future<StarlingAmount> getBalance(String token, String accountId) async {
168 2 : final json = await _get(token, '/api/v2/accounts/$accountId/balance');
169 2 : 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 1 : Future<List<StarlingFeedItem>> getFeed(String token, StarlingAccount account, {required DateTime from}) async {
174 1 : final json = await _get(
175 : token,
176 3 : '/api/v2/feed/account/${account.id}/category/${account.defaultCategory}',
177 2 : {'changesSince': _time(from)},
178 : );
179 1 : return (json['feedItems'] as List? ?? [])
180 1 : .whereType<Map<String, dynamic>>()
181 1 : .map(StarlingFeedItem.fromJson)
182 4 : .where((e) => !e.date.isBefore(from))
183 1 : .toList();
184 : }
185 : }
|