LCOV - code coverage report
Current view: top level - lib/_classes/integration/privatbank - privatbank_client.dart Coverage Total Hit
Test: lcov.info Lines: 0.0 % 96 0
Test Date: 2026-12-05 10:54:13 Functions: - 0 0

            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            0 :   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            0 :   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            0 :   const PrivatBankBalance({required this.iban, required this.currency, required this.amount, this.name});
      34              : 
      35            0 :   factory PrivatBankBalance.fromJson(Map<String, dynamic> json) => PrivatBankBalance(
      36            0 :         iban: (json['acc'] ?? '').toString(),
      37            0 :         currency: (json['currency'] ?? '').toString(),
      38            0 :         amount: PrivatBankClient.parseAmount(json['balanceOut']),
      39            0 :         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            0 :   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            0 :   bool get isBooked => isReal && status == 'r';
      64              : 
      65            0 :   bool get isPending => status == 'p' || (!isReal && status == 'r');
      66              : 
      67            0 :   factory PrivatBankTransaction.fromJson(Map<String, dynamic> json) {
      68            0 :     final value = PrivatBankClient.parseAmount(json['SUM']).abs();
      69            0 :     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            0 :     final counterparty = (json['AUT_CNTR_NAM'] ?? '').toString().trim();
      76            0 :     final reference = [json['REF'], json['REFN']].where((e) => e != null && '$e'.isNotEmpty).join('.');
      77            0 :     return PrivatBankTransaction(
      78            0 :       id: (json['ID'] ?? reference).toString(),
      79              :       date: date,
      80            0 :       amount: json['TRANTYPE'] == 'D' ? -value : value,
      81            0 :       currency: (json['CCY'] ?? '').toString(),
      82            0 :       title: counterparty.isNotEmpty ? counterparty : (json['OSND'] ?? '').toString().trim(),
      83            0 :       status: (json['PR_PR'] ?? 'r').toString().toLowerCase(),
      84            0 :       isReal: (json['FL_REAL'] ?? 'r').toString().toLowerCase() == 'r',
      85              :     );
      86              :   }
      87              : }
      88              : 
      89              : class PrivatBankClient {
      90              :   static const timeout = Duration(seconds: 90);
      91            0 :   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            0 :   PrivatBankClient({http.Client? client, Uri? baseUrl})
     100            0 :       : _client = client ?? http.Client(),
     101            0 :         baseUrl = baseUrl ?? api;
     102              : 
     103            0 :   void close() => _client.close();
     104              : 
     105              :   // Ukrainian IBAN: "UA" followed by 27 digits
     106            0 :   static String? normalizeIban(String value) {
     107            0 :     final result = value.replaceAll(RegExp(r'\s'), '').toUpperCase();
     108            0 :     return RegExp(r'^UA\d{27}$').hasMatch(result) ? result : null;
     109              :   }
     110              : 
     111            0 :   static double parseAmount(dynamic value) {
     112            0 :     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            0 :   static DateTime? parseDate(dynamic value) {
     121            0 :     final match = RegExp(r'^(\d{2})\.(\d{2})\.(\d{4})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$')
     122            0 :         .firstMatch('${value ?? ''}'.trim());
     123              :     if (match == null) {
     124              :       return null;
     125              :     }
     126            0 :     int part(int idx) => int.parse(match.group(idx) ?? '0');
     127            0 :     return DateTime(part(3), part(2), part(1), part(4), part(5), part(6));
     128              :   }
     129              : 
     130            0 :   static String formatDate(DateTime value) =>
     131            0 :       '${value.day.toString().padLeft(2, '0')}-${value.month.toString().padLeft(2, '0')}-${value.year}';
     132              : 
     133            0 :   Future<Map<String, dynamic>> _get(String token, String path, [Map<String, String>? query]) async {
     134            0 :     final uri = baseUrl.replace(path: path, queryParameters: query);
     135            0 :     final response = await _client.get(uri, headers: {
     136              :       'User-Agent': userAgent,
     137            0 :       'token': token.trim(),
     138              :       'Content-Type': 'application/json;charset=utf-8',
     139              :       'Accept': 'application/json',
     140            0 :     }).timeout(timeout);
     141            0 :     if (response.statusCode == 401 || response.statusCode == 403) {
     142            0 :       throw PrivatBankException(AppLocale.labels.integrationAccessDenied, response.statusCode);
     143              :     }
     144              :     dynamic json;
     145              :     try {
     146            0 :       json = jsonDecode(utf8.decode(response.bodyBytes, allowMalformed: true));
     147            0 :     } on FormatException {
     148              :       json = null;
     149              :     }
     150            0 :     final message = json is Map ? (json['message'] ?? json['error'])?.toString() : null;
     151            0 :     if (json is Map && json['status'] == 'ERROR') {
     152            0 :       throw PrivatBankException(
     153            0 :           AppLocale.labels.integrationServiceError(message ?? '${response.statusCode}'), response.statusCode);
     154              :     }
     155            0 :     if (response.statusCode != 200) {
     156            0 :       throw PrivatBankException(AppLocale.labels.integrationHttpError('${response.statusCode}'), response.statusCode);
     157              :     }
     158            0 :     if (json is! Map<String, dynamic>) {
     159            0 :       throw PrivatBankException(AppLocale.labels.integrationUnexpectedResponse);
     160              :     }
     161              :     return json;
     162              :   }
     163              : 
     164            0 :   static List<Map<String, dynamic>> _list(dynamic json) {
     165            0 :     if (json is! List) {
     166            0 :       throw PrivatBankException(AppLocale.labels.integrationUnexpectedResponse);
     167              :     }
     168            0 :     return json.whereType<Map<String, dynamic>>().toList();
     169              :   }
     170              : 
     171              :   // The phase of the statements service: "WRK" when the data is available
     172            0 :   Future<String> getPhase(String token) async {
     173            0 :     final json = await _get(token, '/api/statements/settings');
     174            0 :     final settings = json['settings'];
     175            0 :     if (settings is! Map) {
     176            0 :       throw PrivatBankException(AppLocale.labels.integrationUnexpectedResponse);
     177              :     }
     178            0 :     return (settings['phase'] ?? '').toString();
     179              :   }
     180              : 
     181            0 :   Future<void> ensureReady(String token) async {
     182            0 :     final phase = await getPhase(token);
     183            0 :     if (phase != phaseReady) {
     184            0 :       throw PrivatBankNotReadyException(phase);
     185              :     }
     186              :   }
     187              : 
     188            0 :   Future<List<Map<String, dynamic>>> _pages(String token, String path, String key, Map<String, String> query) async {
     189            0 :     final result = <Map<String, dynamic>>[];
     190              :     String? followId;
     191              :     do {
     192            0 :       final json = await _get(token, path, {
     193              :         ...query,
     194            0 :         'limit': '$limit',
     195            0 :         if (followId != null) 'followId': followId,
     196              :       });
     197            0 :       result.addAll(_list(json[key] ?? []));
     198            0 :       final next = json['next_page_id']?.toString();
     199            0 :       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            0 :   Future<PrivatBankBalance?> getBalance(String token, String iban, {DateTime? date}) async {
     206            0 :     final day = date ?? DateTime.now();
     207            0 :     final balances = await _pages(token, '/api/statements/balance', 'balances', {
     208              :       'acc': iban,
     209            0 :       'startDate': formatDate(day.subtract(const Duration(days: 1))),
     210            0 :       'endDate': formatDate(day),
     211              :     });
     212            0 :     return balances.isEmpty ? null : PrivatBankBalance.fromJson(balances.last);
     213              :   }
     214              : 
     215            0 :   Future<List<PrivatBankTransaction>> getTransactions(
     216              :     String token, {
     217              :     required String iban,
     218              :     required DateTime start,
     219              :     DateTime? end,
     220              :   }) async {
     221            0 :     final transactions = await _pages(token, '/api/statements/transactions', 'transactions', {
     222              :       'acc': iban,
     223            0 :       'startDate': formatDate(start),
     224            0 :       'endDate': formatDate(end ?? DateTime.now()),
     225              :     });
     226            0 :     return transactions.map(PrivatBankTransaction.fromJson).toList();
     227              :   }
     228              : }
        

Generated by: LCOV version 2.0-1