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:async';
5 : import 'dart:convert';
6 :
7 : import 'package:app_finance/_classes/herald/app_locale.dart';
8 : import 'package:flutter/foundation.dart';
9 : import 'package:flutter_currency_picker/flutter_currency_picker.dart';
10 : import 'package:http/http.dart' as http;
11 :
12 : // Monobank Personal API (https://api.monobank.ua/docs/)
13 : class MonobankException implements Exception {
14 : final String message;
15 : final int? statusCode;
16 :
17 2 : const MonobankException(this.message, [this.statusCode]);
18 :
19 0 : @override
20 0 : String toString() => message;
21 : }
22 :
23 : class MonobankCanceledException extends MonobankException {
24 4 : const MonobankCanceledException() : super('');
25 : }
26 :
27 : // Stops long-running requests (statements are limited to one call per minute)
28 : class MonobankCancelToken {
29 : final _completer = Completer<void>();
30 :
31 3 : bool get isCanceled => _completer.isCompleted;
32 :
33 3 : Future<void> get future => _completer.future;
34 :
35 0 : void cancel() {
36 0 : if (!_completer.isCompleted) {
37 0 : _completer.complete();
38 : }
39 : }
40 : }
41 :
42 : // [done] of [total] statement windows are received; [wait] is a pause before the next request
43 : typedef MonobankProgress = void Function(int done, int total, Duration? wait);
44 :
45 : typedef MonobankWindow = ({DateTime from, DateTime to});
46 :
47 : class MonobankAccount {
48 : final String id;
49 : final String? iban;
50 : final String currency;
51 : final int balance;
52 : final int creditLimit;
53 : // "black", "white", "platinum", "iron", "fop", "yellow", "eAid", "madeInUkraine"
54 : final String type;
55 : final List<String> maskedPan;
56 : final bool isJar;
57 : final String? title;
58 :
59 1 : const MonobankAccount({
60 : required this.id,
61 : required this.currency,
62 : required this.balance,
63 : this.iban,
64 : this.creditLimit = 0,
65 : this.type = '',
66 : this.maskedPan = const [],
67 : this.isJar = false,
68 : this.title,
69 : });
70 :
71 6 : double get amount => MonobankClient.fromMinor(balance - creditLimit, currency);
72 :
73 0 : double get limit => MonobankClient.fromMinor(creditLimit, currency);
74 :
75 2 : factory MonobankAccount.fromJson(Map<String, dynamic> json) => MonobankAccount(
76 2 : id: (json['id'] ?? '').toString(),
77 2 : iban: json['iban']?.toString(),
78 2 : currency: MonobankClient.currencyCode(json['currencyCode']),
79 2 : balance: MonobankClient.parseInt(json['balance']),
80 2 : creditLimit: MonobankClient.parseInt(json['creditLimit'] ?? 0),
81 2 : type: (json['type'] ?? '').toString(),
82 5 : maskedPan: (json['maskedPan'] as List<dynamic>? ?? []).map((e) => e.toString()).toList(),
83 : );
84 :
85 0 : factory MonobankAccount.fromJarJson(Map<String, dynamic> json) => MonobankAccount(
86 0 : id: (json['id'] ?? '').toString(),
87 0 : currency: MonobankClient.currencyCode(json['currencyCode']),
88 0 : balance: MonobankClient.parseInt(json['balance']),
89 : isJar: true,
90 0 : title: json['title']?.toString(),
91 : );
92 : }
93 :
94 : class MonobankClientInfo {
95 : final String name;
96 : final List<MonobankAccount> accounts;
97 :
98 1 : const MonobankClientInfo({required this.name, required this.accounts});
99 :
100 2 : factory MonobankClientInfo.fromJson(Map<String, dynamic> json) => MonobankClientInfo(
101 2 : name: (json['name'] ?? '').toString(),
102 1 : accounts: [
103 3 : ...MonobankClient._list(json['accounts'] ?? []).map(MonobankAccount.fromJson),
104 3 : ...MonobankClient._list(json['jars'] ?? []).map(MonobankAccount.fromJarJson),
105 : ],
106 : );
107 : }
108 :
109 : class MonobankTransaction {
110 : final String id;
111 : final DateTime date;
112 : final int amount;
113 : final String title;
114 : final int? mcc;
115 : final bool isHold;
116 :
117 1 : const MonobankTransaction({
118 : required this.id,
119 : required this.date,
120 : required this.amount,
121 : required this.title,
122 : this.mcc,
123 : this.isHold = false,
124 : });
125 :
126 1 : factory MonobankTransaction.fromJson(Map<String, dynamic> json) {
127 1 : final time = json['time'];
128 2 : if (json['id'] == null || time is! num) {
129 0 : throw MonobankException(AppLocale.labels.integrationUnexpectedResponse);
130 : }
131 4 : final title = [json['description'], json['counterName'], json['comment']]
132 4 : .map((e) => (e ?? '').toString().trim())
133 3 : .firstWhere((e) => e.isNotEmpty, orElse: () => '');
134 1 : final mcc = json['mcc'];
135 1 : return MonobankTransaction(
136 2 : id: json['id'].toString(),
137 3 : date: DateTime.fromMillisecondsSinceEpoch(time.toInt() * 1000),
138 2 : amount: MonobankClient.parseInt(json['amount']),
139 : title: title,
140 3 : mcc: mcc is num && mcc > 0 ? mcc.toInt() : null,
141 2 : isHold: json['hold'] == true,
142 : );
143 : }
144 : }
145 :
146 : class MonobankClient {
147 : static const timeout = Duration(seconds: 60);
148 3 : static final api = Uri.parse('https://api.monobank.ua');
149 : static const userAgent = 'Fingrom';
150 : static const interval = Duration(seconds: 61);
151 : static const window = Duration(days: 31);
152 : static const limit = 500;
153 : static const retries = 2;
154 :
155 : final http.Client _client;
156 : final Uri baseUrl;
157 : final Future<void> Function(Duration duration) _wait;
158 : final DateTime Function() _now;
159 : final _lastCall = <String, DateTime>{};
160 :
161 1 : MonobankClient({
162 : http.Client? client,
163 : Uri? baseUrl,
164 : Future<void> Function(Duration duration)? wait,
165 : DateTime Function()? now,
166 1 : }) : _client = client ?? http.Client(),
167 1 : baseUrl = baseUrl ?? api,
168 : _wait = wait ?? Future<void>.delayed,
169 : _now = now ?? DateTime.now;
170 :
171 3 : void close() => _client.close();
172 :
173 1 : static int parseInt(dynamic value) {
174 2 : final result = value is num ? value.toInt() : int.tryParse('${value ?? ''}'.trim());
175 : if (result == null) {
176 0 : throw MonobankException(AppLocale.labels.integrationInvalidAmount('$value'));
177 : }
178 : return result;
179 : }
180 :
181 2 : static int _digits(String currency) => CurrencyProvider.find(currency)?.decimalDigits ?? 2;
182 :
183 1 : static double fromMinor(int value, String currency) {
184 1 : final digits = _digits(currency);
185 : var divider = 1;
186 2 : for (var i = 0; i < digits; i++) {
187 1 : divider *= 10;
188 : }
189 1 : return value / divider;
190 : }
191 :
192 : // ISO 4217 numeric code to the alphabetic one
193 1 : static String currencyCode(dynamic value) {
194 2 : final code = int.tryParse('${value ?? ''}');
195 1 : return _iso4217[code] ?? '${value ?? ''}';
196 : }
197 :
198 1 : static List<MonobankWindow> split(DateTime from, DateTime to) {
199 1 : final result = <MonobankWindow>[];
200 : var start = from;
201 1 : while (start.isBefore(to)) {
202 1 : final end = start.add(window);
203 2 : result.add((from: start, to: end.isBefore(to) ? end : to));
204 : start = end;
205 : }
206 : return result;
207 : }
208 :
209 3 : static int _seconds(DateTime value) => value.millisecondsSinceEpoch ~/ 1000;
210 :
211 1 : static List<Map<String, dynamic>> _list(dynamic json) {
212 1 : if (json is! List) {
213 0 : throw MonobankException(AppLocale.labels.integrationUnexpectedResponse);
214 : }
215 2 : return json.whereType<Map<String, dynamic>>().toList();
216 : }
217 :
218 1 : Future<void> _pause(Duration duration, MonobankCancelToken? cancel) async {
219 1 : if (duration <= Duration.zero) {
220 : return;
221 : }
222 5 : await Future.any([_wait(duration), if (cancel != null) cancel.future]);
223 1 : if (cancel?.isCanceled ?? false) {
224 : throw const MonobankCanceledException();
225 : }
226 : }
227 :
228 1 : Future<void> _throttle(String endpoint, MonobankCancelToken? cancel, void Function(Duration wait)? onWait) async {
229 2 : final last = _lastCall[endpoint];
230 : if (last != null) {
231 4 : final left = interval - _now().difference(last);
232 1 : if (left > Duration.zero) {
233 1 : onWait?.call(left);
234 1 : await _pause(left, cancel);
235 : }
236 : }
237 : }
238 :
239 1 : Future<dynamic> _get(
240 : String token,
241 : String endpoint,
242 : String path, {
243 : MonobankCancelToken? cancel,
244 : void Function(Duration wait)? onWait,
245 : }) async {
246 0 : for (var attempt = 0;; attempt++) {
247 1 : if (cancel?.isCanceled ?? false) {
248 : throw const MonobankCanceledException();
249 : }
250 1 : await _throttle(endpoint, cancel, onWait);
251 4 : _lastCall[endpoint] = _now();
252 5 : final response = await _client.get(baseUrl.replace(path: path), headers: {
253 : // Browsers forbid to change the agent, and the preflight of CORS allows only "X-Token"
254 1 : if (!kIsWeb) 'User-Agent': userAgent,
255 2 : 'X-Token': token.trim(),
256 1 : 'Accept': 'application/json',
257 1 : }).timeout(timeout);
258 2 : if (response.statusCode == 429 && attempt < retries) {
259 : continue;
260 : }
261 4 : if (response.statusCode == 401 || response.statusCode == 403) {
262 0 : throw MonobankException(AppLocale.labels.integrationAccessDenied, response.statusCode);
263 : }
264 : dynamic json;
265 : try {
266 3 : json = jsonDecode(utf8.decode(response.bodyBytes, allowMalformed: true));
267 0 : } on FormatException {
268 : json = null;
269 : }
270 2 : if (response.statusCode != 200) {
271 0 : final message = json is Map ? json['errorDescription']?.toString() : null;
272 0 : throw MonobankException(
273 : message != null
274 0 : ? AppLocale.labels.integrationServiceError(message)
275 0 : : AppLocale.labels.integrationHttpError('${response.statusCode}'),
276 0 : response.statusCode,
277 : );
278 : }
279 : return json;
280 : }
281 : }
282 :
283 1 : Future<MonobankClientInfo> getClientInfo(String token, {MonobankCancelToken? cancel}) async {
284 1 : final json = await _get(token, 'client-info', '/personal/client-info', cancel: cancel);
285 1 : if (json is! Map<String, dynamic>) {
286 0 : throw MonobankException(AppLocale.labels.integrationUnexpectedResponse);
287 : }
288 1 : return MonobankClientInfo.fromJson(json);
289 : }
290 :
291 1 : Future<List<MonobankTransaction>> getStatement(
292 : String token,
293 : String account,
294 : DateTime from,
295 : DateTime to, {
296 : MonobankCancelToken? cancel,
297 : void Function(Duration wait)? onWait,
298 : }) async {
299 1 : final json = await _get(
300 : token,
301 : 'statement',
302 3 : '/personal/statement/$account/${_seconds(from)}/${_seconds(to)}',
303 : cancel: cancel,
304 : onWait: onWait,
305 : );
306 3 : return _list(json).map(MonobankTransaction.fromJson).toList();
307 : }
308 :
309 1 : Future<List<MonobankTransaction>> getTransactions(
310 : String token,
311 : String account, {
312 : required DateTime from,
313 : DateTime? to,
314 : MonobankCancelToken? cancel,
315 : MonobankProgress? onProgress,
316 : void Function(MonobankWindow window, List<MonobankTransaction> items)? onWindow,
317 : }) async {
318 3 : final windows = split(from, to ?? _now());
319 1 : final result = <String, MonobankTransaction>{};
320 3 : for (var i = 0; i < windows.length; i++) {
321 1 : final items = <String, MonobankTransaction>{};
322 1 : var end = windows[i].to;
323 : while (true) {
324 2 : onProgress?.call(i, windows.length, null);
325 1 : final page = await getStatement(
326 : token,
327 : account,
328 1 : windows[i].from,
329 : end,
330 : cancel: cancel,
331 3 : onWait: (wait) => onProgress?.call(i, windows.length, wait),
332 : );
333 2 : for (final item in page) {
334 2 : items[item.id] = item;
335 : }
336 2 : if (page.length < limit) {
337 : break;
338 : }
339 0 : final oldest = page.map((e) => e.date).reduce((a, b) => a.isBefore(b) ? a : b);
340 0 : if (!oldest.isAfter(windows[i].from) || !oldest.isBefore(end)) {
341 : break;
342 : }
343 : end = oldest;
344 : }
345 1 : result.addAll(items);
346 4 : onWindow?.call(windows[i], items.values.toList());
347 : }
348 3 : onProgress?.call(windows.length, windows.length, null);
349 2 : return result.values.toList();
350 : }
351 :
352 : static const _iso4217 = <int, String>{
353 : 8: 'ALL',
354 : 12: 'DZD',
355 : 32: 'ARS',
356 : 36: 'AUD',
357 : 44: 'BSD',
358 : 48: 'BHD',
359 : 50: 'BDT',
360 : 51: 'AMD',
361 : 52: 'BBD',
362 : 60: 'BMD',
363 : 64: 'BTN',
364 : 68: 'BOB',
365 : 72: 'BWP',
366 : 84: 'BZD',
367 : 90: 'SBD',
368 : 96: 'BND',
369 : 104: 'MMK',
370 : 108: 'BIF',
371 : 116: 'KHR',
372 : 124: 'CAD',
373 : 132: 'CVE',
374 : 136: 'KYD',
375 : 144: 'LKR',
376 : 152: 'CLP',
377 : 156: 'CNY',
378 : 170: 'COP',
379 : 174: 'KMF',
380 : 188: 'CRC',
381 : 191: 'HRK',
382 : 192: 'CUP',
383 : 203: 'CZK',
384 : 208: 'DKK',
385 : 214: 'DOP',
386 : 222: 'SVC',
387 : 230: 'ETB',
388 : 232: 'ERN',
389 : 238: 'FKP',
390 : 242: 'FJD',
391 : 262: 'DJF',
392 : 270: 'GMD',
393 : 292: 'GIP',
394 : 320: 'GTQ',
395 : 324: 'GNF',
396 : 328: 'GYD',
397 : 332: 'HTG',
398 : 340: 'HNL',
399 : 344: 'HKD',
400 : 348: 'HUF',
401 : 352: 'ISK',
402 : 356: 'INR',
403 : 360: 'IDR',
404 : 364: 'IRR',
405 : 368: 'IQD',
406 : 376: 'ILS',
407 : 388: 'JMD',
408 : 392: 'JPY',
409 : 398: 'KZT',
410 : 400: 'JOD',
411 : 404: 'KES',
412 : 408: 'KPW',
413 : 410: 'KRW',
414 : 414: 'KWD',
415 : 417: 'KGS',
416 : 418: 'LAK',
417 : 422: 'LBP',
418 : 426: 'LSL',
419 : 430: 'LRD',
420 : 434: 'LYD',
421 : 446: 'MOP',
422 : 454: 'MWK',
423 : 458: 'MYR',
424 : 462: 'MVR',
425 : 480: 'MUR',
426 : 484: 'MXN',
427 : 496: 'MNT',
428 : 498: 'MDL',
429 : 504: 'MAD',
430 : 512: 'OMR',
431 : 516: 'NAD',
432 : 524: 'NPR',
433 : 532: 'ANG',
434 : 533: 'AWG',
435 : 548: 'VUV',
436 : 554: 'NZD',
437 : 558: 'NIO',
438 : 566: 'NGN',
439 : 578: 'NOK',
440 : 586: 'PKR',
441 : 590: 'PAB',
442 : 598: 'PGK',
443 : 600: 'PYG',
444 : 604: 'PEN',
445 : 608: 'PHP',
446 : 634: 'QAR',
447 : 643: 'RUB',
448 : 646: 'RWF',
449 : 654: 'SHP',
450 : 682: 'SAR',
451 : 690: 'SCR',
452 : 694: 'SLL',
453 : 702: 'SGD',
454 : 704: 'VND',
455 : 706: 'SOS',
456 : 710: 'ZAR',
457 : 728: 'SSP',
458 : 748: 'SZL',
459 : 752: 'SEK',
460 : 756: 'CHF',
461 : 760: 'SYP',
462 : 764: 'THB',
463 : 776: 'TOP',
464 : 780: 'TTD',
465 : 784: 'AED',
466 : 788: 'TND',
467 : 800: 'UGX',
468 : 807: 'MKD',
469 : 818: 'EGP',
470 : 826: 'GBP',
471 : 834: 'TZS',
472 : 840: 'USD',
473 : 858: 'UYU',
474 : 860: 'UZS',
475 : 882: 'WST',
476 : 886: 'YER',
477 : 901: 'TWD',
478 : 925: 'SLE',
479 : 926: 'VED',
480 : 928: 'VES',
481 : 929: 'MRU',
482 : 930: 'STN',
483 : 933: 'BYN',
484 : 934: 'TMT',
485 : 936: 'GHS',
486 : 937: 'VEF',
487 : 938: 'SDG',
488 : 941: 'RSD',
489 : 943: 'MZN',
490 : 944: 'AZN',
491 : 946: 'RON',
492 : 949: 'TRY',
493 : 950: 'XAF',
494 : 951: 'XCD',
495 : 952: 'XOF',
496 : 953: 'XPF',
497 : 960: 'XDR',
498 : 967: 'ZMW',
499 : 968: 'SRD',
500 : 969: 'MGA',
501 : 971: 'AFN',
502 : 972: 'TJS',
503 : 973: 'AOA',
504 : 975: 'BGN',
505 : 976: 'CDF',
506 : 977: 'BAM',
507 : 978: 'EUR',
508 : 980: 'UAH',
509 : 981: 'GEL',
510 : 985: 'PLN',
511 : 986: 'BRL',
512 : };
513 : }
|