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 : // PrivatBank "Autoclient" API of Privat24 for Business (https://acp.privatbank.ua)
10 : class PrivatBankException implements Exception {
11 : final String message;
12 : final int? statusCode;
13 :
14 1 : const PrivatBankException(this.message, [this.statusCode]);
15 :
16 0 : @override
17 0 : String toString() => message;
18 : }
19 :
20 : // Statements are being prepared by the bank (the phase differs from "WRK")
21 : class PrivatBankNotReadyException extends PrivatBankException {
22 : final String phase;
23 :
24 4 : PrivatBankNotReadyException(this.phase) : super(AppLocale.labels.privatBankNotReady(phase));
25 : }
26 :
27 : class PrivatBankBalance {
28 : final String iban;
29 : final String currency;
30 : final double amount;
31 : final String? name;
32 :
33 1 : const PrivatBankBalance({required this.iban, required this.currency, required this.amount, this.name});
34 :
35 2 : factory PrivatBankBalance.fromJson(Map<String, dynamic> json) => PrivatBankBalance(
36 2 : iban: (json['acc'] ?? '').toString(),
37 2 : currency: (json['currency'] ?? '').toString(),
38 2 : amount: PrivatBankClient.parseAmount(json['balanceOut']),
39 2 : name: json['nameACC']?.toString(),
40 : );
41 : }
42 :
43 : class PrivatBankTransaction {
44 : final String id;
45 : final DateTime date;
46 : final double amount;
47 : final String currency;
48 : final String title;
49 : // "r" - booked, "p" - in progress, "t" - reversed, "n" - rejected
50 : final String status;
51 : final bool isReal;
52 :
53 1 : const PrivatBankTransaction({
54 : required this.id,
55 : required this.date,
56 : required this.amount,
57 : required this.currency,
58 : required this.title,
59 : this.status = 'r',
60 : this.isReal = true,
61 : });
62 :
63 4 : bool get isBooked => isReal && status == 'r';
64 :
65 4 : bool get isPending => status == 'p' || (!isReal && status == 'r');
66 :
67 1 : factory PrivatBankTransaction.fromJson(Map<String, dynamic> json) {
68 3 : final value = PrivatBankClient.parseAmount(json['SUM']).abs();
69 2 : final date = PrivatBankClient.parseDate(json['DATE_TIME_DAT_OD_TIM_P']) ??
70 0 : PrivatBankClient.parseDate('${json['DAT_OD'] ?? ''} ${json['TIM_P'] ?? ''}') ??
71 0 : PrivatBankClient.parseDate(json['DAT_OD']);
72 : if (date == null) {
73 0 : throw PrivatBankException(AppLocale.labels.integrationUnexpectedResponse);
74 : }
75 3 : final counterparty = (json['AUT_CNTR_NAM'] ?? '').toString().trim();
76 8 : final reference = [json['REF'], json['REFN']].where((e) => e != null && '$e'.isNotEmpty).join('.');
77 1 : return PrivatBankTransaction(
78 2 : id: (json['ID'] ?? reference).toString(),
79 : date: date,
80 3 : amount: json['TRANTYPE'] == 'D' ? -value : value,
81 2 : currency: (json['CCY'] ?? '').toString(),
82 1 : title: counterparty.isNotEmpty ? counterparty : (json['OSND'] ?? '').toString().trim(),
83 3 : status: (json['PR_PR'] ?? 'r').toString().toLowerCase(),
84 4 : isReal: (json['FL_REAL'] ?? 'r').toString().toLowerCase() == 'r',
85 : );
86 : }
87 : }
88 :
89 : class PrivatBankClient {
90 : static const timeout = Duration(seconds: 90);
91 3 : static final api = Uri.parse('https://acp.privatbank.ua');
92 : static const userAgent = 'Fingrom';
93 : static const phaseReady = 'WRK';
94 : static const limit = 500;
95 :
96 : final http.Client _client;
97 : final Uri baseUrl;
98 :
99 1 : PrivatBankClient({http.Client? client, Uri? baseUrl})
100 0 : : _client = client ?? http.Client(),
101 1 : baseUrl = baseUrl ?? api;
102 :
103 0 : void close() => _client.close();
104 :
105 : // Ukrainian IBAN: "UA" followed by 27 digits
106 1 : static String? normalizeIban(String value) {
107 3 : final result = value.replaceAll(RegExp(r'\s'), '').toUpperCase();
108 2 : return RegExp(r'^UA\d{27}$').hasMatch(result) ? result : null;
109 : }
110 :
111 1 : static double parseAmount(dynamic value) {
112 5 : final result = value is num ? value.toDouble() : double.tryParse('${value ?? ''}'.trim().replaceAll(',', '.'));
113 : if (result == null) {
114 0 : throw PrivatBankException(AppLocale.labels.integrationInvalidAmount('$value'));
115 : }
116 : return result;
117 : }
118 :
119 : // "dd.MM.yyyy" with an optional "HH:mm[:ss]"
120 1 : static DateTime? parseDate(dynamic value) {
121 1 : final match = RegExp(r'^(\d{2})\.(\d{2})\.(\d{4})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$')
122 3 : .firstMatch('${value ?? ''}'.trim());
123 : if (match == null) {
124 : return null;
125 : }
126 3 : int part(int idx) => int.parse(match.group(idx) ?? '0');
127 7 : return DateTime(part(3), part(2), part(1), part(4), part(5), part(6));
128 : }
129 :
130 1 : static String formatDate(DateTime value) =>
131 8 : '${value.day.toString().padLeft(2, '0')}-${value.month.toString().padLeft(2, '0')}-${value.year}';
132 :
133 1 : Future<Map<String, dynamic>> _get(String token, String path, [Map<String, String>? query]) async {
134 2 : final uri = baseUrl.replace(path: path, queryParameters: query);
135 3 : final response = await _client.get(uri, headers: {
136 : 'User-Agent': userAgent,
137 1 : 'token': token.trim(),
138 : 'Content-Type': 'application/json;charset=utf-8',
139 : 'Accept': 'application/json',
140 1 : }).timeout(timeout);
141 4 : if (response.statusCode == 401 || response.statusCode == 403) {
142 4 : throw PrivatBankException(AppLocale.labels.integrationAccessDenied, response.statusCode);
143 : }
144 : dynamic json;
145 : try {
146 3 : json = jsonDecode(utf8.decode(response.bodyBytes, allowMalformed: true));
147 0 : } on FormatException {
148 : json = null;
149 : }
150 4 : final message = json is Map ? (json['message'] ?? json['error'])?.toString() : null;
151 3 : if (json is Map && json['status'] == 'ERROR') {
152 1 : throw PrivatBankException(
153 3 : AppLocale.labels.integrationServiceError(message ?? '${response.statusCode}'), response.statusCode);
154 : }
155 2 : if (response.statusCode != 200) {
156 0 : throw PrivatBankException(AppLocale.labels.integrationHttpError('${response.statusCode}'), response.statusCode);
157 : }
158 1 : if (json is! Map<String, dynamic>) {
159 0 : throw PrivatBankException(AppLocale.labels.integrationUnexpectedResponse);
160 : }
161 : return json;
162 : }
163 :
164 1 : static List<Map<String, dynamic>> _list(dynamic json) {
165 1 : if (json is! List) {
166 0 : throw PrivatBankException(AppLocale.labels.integrationUnexpectedResponse);
167 : }
168 2 : return json.whereType<Map<String, dynamic>>().toList();
169 : }
170 :
171 : // The phase of the statements service: "WRK" when the data is available
172 1 : Future<String> getPhase(String token) async {
173 1 : final json = await _get(token, '/api/statements/settings');
174 1 : final settings = json['settings'];
175 1 : if (settings is! Map) {
176 0 : throw PrivatBankException(AppLocale.labels.integrationUnexpectedResponse);
177 : }
178 2 : return (settings['phase'] ?? '').toString();
179 : }
180 :
181 1 : Future<void> ensureReady(String token) async {
182 1 : final phase = await getPhase(token);
183 1 : if (phase != phaseReady) {
184 1 : throw PrivatBankNotReadyException(phase);
185 : }
186 : }
187 :
188 1 : Future<List<Map<String, dynamic>>> _pages(String token, String path, String key, Map<String, String> query) async {
189 1 : final result = <Map<String, dynamic>>[];
190 : String? followId;
191 : do {
192 2 : final json = await _get(token, path, {
193 : ...query,
194 1 : 'limit': '$limit',
195 1 : if (followId != null) 'followId': followId,
196 : });
197 3 : result.addAll(_list(json[key] ?? []));
198 2 : final next = json['next_page_id']?.toString();
199 4 : final hasNext = json['exist_next_page'] == true && next != null && next.isNotEmpty && next != followId;
200 : followId = hasNext ? next : null;
201 : } while (followId != null);
202 : return result;
203 : }
204 :
205 1 : Future<PrivatBankBalance?> getBalance(String token, String iban, {DateTime? date}) async {
206 1 : final day = date ?? DateTime.now();
207 2 : final balances = await _pages(token, '/api/statements/balance', 'balances', {
208 : 'acc': iban,
209 2 : 'startDate': formatDate(day.subtract(const Duration(days: 1))),
210 1 : 'endDate': formatDate(day),
211 : });
212 3 : return balances.isEmpty ? null : PrivatBankBalance.fromJson(balances.last);
213 : }
214 :
215 1 : Future<List<PrivatBankTransaction>> getTransactions(
216 : String token, {
217 : required String iban,
218 : required DateTime start,
219 : DateTime? end,
220 : }) async {
221 2 : final transactions = await _pages(token, '/api/statements/transactions', 'transactions', {
222 : 'acc': iban,
223 1 : 'startDate': formatDate(start),
224 1 : 'endDate': formatDate(end ?? DateTime.now()),
225 : });
226 2 : return transactions.map(PrivatBankTransaction.fromJson).toList();
227 : }
228 : }
|