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/controller/encryption_handler.dart';
7 : import 'package:app_finance/_classes/integration/akahu/akahu_client.dart';
8 : import 'package:app_finance/_classes/storage/app_preferences.dart';
9 :
10 : class AkahuSettings {
11 : // Akahu account id to the uuid of the application's account
12 : final Map<String, String> links;
13 :
14 : // Akahu account id to the last day transactions were imported for
15 : final Map<String, DateTime> imported;
16 :
17 1 : AkahuSettings({Map<String, String>? links, Map<String, DateTime>? imported})
18 1 : : links = links ?? {},
19 1 : imported = imported ?? {};
20 :
21 2 : Map<String, dynamic> toJson() => {
22 1 : 'links': links,
23 2 : 'imported': imported.map((key, value) => MapEntry(key, value.toIso8601String())),
24 : };
25 :
26 2 : factory AkahuSettings.fromJson(Map<String, dynamic> json) => AkahuSettings(
27 5 : links: (json['links'] as Map<String, dynamic>? ?? {}).map((key, value) => MapEntry(key, value.toString())),
28 2 : imported: (json['imported'] as Map<String, dynamic>? ?? {}).map(
29 0 : (key, value) => MapEntry(key, DateTime.parse(value.toString())),
30 : ),
31 : );
32 :
33 1 : static AkahuSettings load() {
34 1 : final value = AppPreferences.get(AppPreferences.prefAkahu);
35 1 : if (value == null || value.isEmpty) {
36 0 : return AkahuSettings();
37 : }
38 : try {
39 2 : return AkahuSettings.fromJson(jsonDecode(value));
40 0 : } on FormatException {
41 0 : return AkahuSettings();
42 : }
43 : }
44 :
45 4 : Future<void> save() => AppPreferences.set(AppPreferences.prefAkahu, jsonEncode(toJson()));
46 :
47 1 : static AkahuTokens? loadTokens() {
48 1 : final value = AppPreferences.get(AppPreferences.prefAkahuTokens);
49 1 : if (value == null || value.isEmpty) {
50 : return null;
51 : }
52 : try {
53 2 : final json = jsonDecode(EncryptionHandler.decrypt(value)) as Map<String, dynamic>;
54 4 : final result = (appToken: (json['appToken'] ?? '').toString(), userToken: (json['userToken'] ?? '').toString());
55 2 : return result.appToken.isEmpty || result.userToken.isEmpty ? null : result;
56 : } catch (_) {
57 : return null;
58 : }
59 : }
60 :
61 2 : static Future<void> saveTokens(AkahuTokens tokens) => AppPreferences.set(
62 : AppPreferences.prefAkahuTokens,
63 3 : EncryptionHandler.encrypt(jsonEncode({'appToken': tokens.appToken, 'userToken': tokens.userToken})),
64 : );
65 :
66 2 : static Future<void> clearTokens() => AppPreferences.clear(AppPreferences.prefAkahuTokens);
67 : }
|