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 : // Wise Platform API with a Personal API Token (https://docs.wise.com/api-docs/api-reference)
10 : class WiseException implements Exception {
11 : final String message;
12 : final int? statusCode;
13 :
14 0 : const WiseException(this.message, [this.statusCode]);
15 :
16 0 : @override
17 0 : String toString() => message;
18 : }
19 :
20 : // Strong Customer Authentication is required (UK/EEA)
21 : class WiseScaException extends WiseException {
22 0 : WiseScaException() : super(AppLocale.labels.wiseScaRequired, 403);
23 : }
24 :
25 : typedef WiseAmount = ({double value, String currency});
26 :
27 : class WiseProfile {
28 : final int id;
29 : final String type;
30 : final String name;
31 :
32 0 : const WiseProfile({required this.id, required this.type, required this.name});
33 :
34 0 : factory WiseProfile.fromJson(Map<String, dynamic> json) {
35 0 : final details = json['details'] is Map ? json['details'] as Map : const {};
36 0 : final person = [json['firstName'] ?? details['firstName'], json['lastName'] ?? details['lastName']]
37 0 : .where((e) => e != null && e.toString().isNotEmpty)
38 0 : .join(' ');
39 0 : return WiseProfile(
40 0 : id: (json['id'] as num).toInt(),
41 0 : type: (json['type'] ?? '').toString().toUpperCase(),
42 0 : name: (json['fullName'] ?? json['businessName'] ?? details['name'] ?? person).toString().trim(),
43 : );
44 : }
45 :
46 0 : String get title => [name, type].where((e) => e.isNotEmpty).join(' — ');
47 : }
48 :
49 : class WiseBalance {
50 : final int id;
51 : final String currency;
52 : final double amount;
53 : final String? name;
54 :
55 0 : const WiseBalance({required this.id, required this.currency, required this.amount, this.name});
56 :
57 0 : factory WiseBalance.fromJson(Map<String, dynamic> json) {
58 0 : final amount = WiseClient.parseAmount(json['amount']);
59 0 : return WiseBalance(
60 0 : id: (json['id'] as num).toInt(),
61 0 : currency: (json['currency'] ?? amount?.currency ?? '').toString(),
62 : amount: amount?.value ?? 0.0,
63 0 : name: json['name']?.toString(),
64 : );
65 : }
66 : }
67 :
68 : class WiseTransaction {
69 : final String type;
70 : final DateTime date;
71 : final WiseAmount amount;
72 : final String description;
73 : final String referenceNumber;
74 : final String? detailsType;
75 : final WiseAmount? sourceAmount;
76 : final WiseAmount? targetAmount;
77 :
78 0 : const WiseTransaction({
79 : required this.type,
80 : required this.date,
81 : required this.amount,
82 : required this.description,
83 : required this.referenceNumber,
84 : this.detailsType,
85 : this.sourceAmount,
86 : this.targetAmount,
87 : });
88 :
89 0 : bool get isConversion => detailsType == 'CONVERSION' && sourceAmount != null && targetAmount != null;
90 :
91 0 : factory WiseTransaction.fromJson(Map<String, dynamic> json) {
92 0 : final details = json['details'] is Map<String, dynamic> ? json['details'] as Map<String, dynamic> : const {};
93 0 : final merchant = details['merchant'] is Map ? details['merchant']['name'] : null;
94 0 : final amount = WiseClient.parseAmount(json['amount']);
95 0 : final date = DateTime.tryParse(json['date']?.toString() ?? '');
96 : if (amount == null || date == null) {
97 0 : throw WiseException(AppLocale.labels.integrationInvalidAmount('${json['amount']}'));
98 : }
99 0 : return WiseTransaction(
100 0 : type: (json['type'] ?? '').toString(),
101 0 : date: date.toLocal(),
102 : amount: amount,
103 0 : description: (merchant ?? details['description'] ?? '').toString().trim(),
104 0 : referenceNumber: (json['referenceNumber'] ?? '').toString(),
105 0 : detailsType: details['type']?.toString(),
106 0 : sourceAmount: WiseClient.parseAmount(details['sourceAmount']),
107 0 : targetAmount: WiseClient.parseAmount(details['targetAmount']),
108 : );
109 : }
110 : }
111 :
112 : class WiseClient {
113 : static const timeout = Duration(seconds: 90);
114 0 : static final api = Uri.parse('https://api.wise.com');
115 : static const maxInterval = Duration(days: 469);
116 :
117 : final http.Client _client;
118 : final Uri baseUrl;
119 :
120 0 : WiseClient({http.Client? client, Uri? baseUrl})
121 0 : : _client = client ?? http.Client(),
122 0 : baseUrl = baseUrl ?? api;
123 :
124 0 : void close() => _client.close();
125 :
126 0 : static WiseAmount? parseAmount(dynamic value) {
127 0 : if (value is! Map) {
128 : return null;
129 : }
130 0 : final amount = value['value'];
131 0 : final result = amount is num ? amount.toDouble() : double.tryParse(amount?.toString() ?? '');
132 : if (result == null) {
133 0 : throw WiseException(AppLocale.labels.integrationInvalidAmount('$amount'));
134 : }
135 0 : return (value: result, currency: (value['currency'] ?? '').toString());
136 : }
137 :
138 0 : static String _time(DateTime value) => value.toUtc().toIso8601String();
139 :
140 0 : Future<dynamic> _get(String token, String path, [Map<String, String>? query]) async {
141 0 : final uri = baseUrl.replace(path: path, queryParameters: query);
142 0 : final response = await _client.get(uri, headers: {
143 0 : 'Authorization': 'Bearer ${token.trim()}',
144 : 'Accept': 'application/json',
145 0 : }).timeout(timeout);
146 0 : final headers = response.headers;
147 0 : final requiresSca = response.statusCode == 403 && headers.containsKey('x-2fa-approval');
148 : if (requiresSca) {
149 0 : throw WiseScaException();
150 : }
151 0 : if (response.statusCode == 401 || response.statusCode == 403) {
152 0 : throw WiseException(AppLocale.labels.integrationAccessDenied, response.statusCode);
153 : }
154 0 : if (response.statusCode != 200) {
155 0 : throw WiseException(AppLocale.labels.integrationHttpError('${response.statusCode}'), response.statusCode);
156 : }
157 : try {
158 0 : return jsonDecode(utf8.decode(response.bodyBytes));
159 0 : } on FormatException {
160 0 : throw WiseException(AppLocale.labels.integrationUnexpectedResponse);
161 : }
162 : }
163 :
164 0 : static List<Map<String, dynamic>> _list(dynamic json) {
165 0 : if (json is! List) {
166 0 : throw WiseException(AppLocale.labels.integrationUnexpectedResponse);
167 : }
168 0 : return json.whereType<Map<String, dynamic>>().toList();
169 : }
170 :
171 0 : Future<List<WiseProfile>> getProfiles(String token) async =>
172 0 : _list(await _get(token, '/v2/profiles')).map(WiseProfile.fromJson).toList();
173 :
174 0 : Future<List<WiseBalance>> getBalances(String token, int profileId) async =>
175 0 : _list(await _get(token, '/v4/profiles/$profileId/balances', {'types': 'STANDARD'}))
176 0 : .map(WiseBalance.fromJson)
177 0 : .toList();
178 :
179 0 : Future<List<WiseTransaction>> getStatement(
180 : String token, {
181 : required int profileId,
182 : required WiseBalance balance,
183 : required DateTime start,
184 : DateTime? end,
185 : }) async {
186 0 : final result = <WiseTransaction>[];
187 0 : final till = end ?? DateTime.now();
188 : var from = start;
189 0 : while (from.isBefore(till)) {
190 0 : final to = from.add(maxInterval).isBefore(till) ? from.add(maxInterval) : till;
191 0 : final json = await _get(token, '/v1/profiles/$profileId/balance-statements/${balance.id}/statement.json', {
192 0 : 'currency': balance.currency,
193 0 : 'intervalStart': _time(from),
194 0 : 'intervalEnd': _time(to),
195 : 'type': 'COMPACT',
196 : });
197 0 : if (json is! Map<String, dynamic>) {
198 0 : throw WiseException(AppLocale.labels.integrationUnexpectedResponse);
199 : }
200 0 : result.addAll(_list(json['transactions'] ?? []).map(WiseTransaction.fromJson));
201 : from = to;
202 : }
203 : return result;
204 : }
205 : }
|