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 'package:app_finance/_classes/herald/app_design.dart';
5 : import 'package:app_finance/_classes/herald/app_locale.dart';
6 : import 'package:app_finance/_classes/integration/privatbank/privatbank_client.dart';
7 : import 'package:app_finance/_classes/integration/privatbank/privatbank_importer.dart';
8 : import 'package:app_finance/_classes/integration/privatbank/privatbank_settings.dart';
9 : import 'package:app_finance/_classes/storage/app_data.dart';
10 : import 'package:app_finance/_classes/storage/app_preferences.dart';
11 : import 'package:app_finance/_classes/storage/transaction_log.dart';
12 : import 'package:app_finance/_configs/theme_helper.dart';
13 : import 'package:app_finance/_ext/build_context_ext.dart';
14 : import 'package:app_finance/design/button/full_sized_button_widget.dart';
15 : import 'package:app_finance/design/generic/loading_widget.dart';
16 : import 'package:app_finance/design/wrapper/input_wrapper.dart';
17 : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
18 : import 'package:material_ui/material_ui.dart';
19 : import 'package:provider/provider.dart';
20 :
21 : class PrivatBankAccount extends IntegrationTarget {
22 : final String iban;
23 : PrivatBankBalance? balance;
24 :
25 1 : PrivatBankAccount(this.iban, {this.balance, super.appAccount, super.category, required super.from});
26 :
27 9 : String get title => [iban, balance?.name ?? ''].where((e) => e.isNotEmpty).join(' — ');
28 : }
29 :
30 : class PrivatBankWidget extends StatefulWidget {
31 : final PrivatBankClient? client;
32 :
33 3 : const PrivatBankWidget({super.key, this.client});
34 :
35 1 : @override
36 1 : PrivatBankWidgetState createState() => PrivatBankWidgetState();
37 : }
38 :
39 : class PrivatBankWidgetState extends State<PrivatBankWidget> {
40 : late final PrivatBankClient client;
41 : late final PrivatBankSettings settings;
42 : final token = TextEditingController();
43 : final iban = TextEditingController();
44 : String? access;
45 : bool isConnected = false;
46 : List<PrivatBankAccount> accounts = [];
47 : bool isLoading = false;
48 : String? error;
49 : String? notice;
50 :
51 1 : @override
52 : void initState() {
53 1 : super.initState();
54 4 : client = widget.client ?? PrivatBankClient();
55 2 : settings = PrivatBankSettings.load();
56 2 : access = PrivatBankSettings.loadToken();
57 : }
58 :
59 1 : @override
60 : void dispose() {
61 2 : token.dispose();
62 2 : iban.dispose();
63 2 : if (widget.client == null) {
64 2 : client.close();
65 : }
66 1 : super.dispose();
67 : }
68 :
69 1 : Future<void> _run(Future<void> Function() callback) async {
70 2 : setState(() {
71 1 : isLoading = true;
72 1 : error = null;
73 1 : notice = null;
74 : });
75 : try {
76 1 : await callback();
77 0 : } on PrivatBankException catch (e) {
78 0 : error = e.message;
79 : } catch (e) {
80 0 : error = e.toString();
81 : } finally {
82 1 : if (mounted) {
83 3 : setState(() => isLoading = false);
84 : }
85 : }
86 : }
87 :
88 2 : PrivatBankAccount _account(String value) => PrivatBankAccount(
89 : value,
90 3 : appAccount: settings.links[value],
91 1 : category: AppPreferences.get(AppPreferences.prefBudget),
92 5 : from: settings.imported[value] ?? DateTime.now().subtract(const Duration(days: 30)),
93 : );
94 :
95 1 : Future<void> _loadBalance(PrivatBankAccount item) async {
96 5 : item.balance = await client.getBalance(access!, item.iban);
97 : }
98 :
99 3 : Future<void> connect() => _run(() async {
100 4 : final value = access ?? token.text.trim();
101 1 : if (value.isEmpty) {
102 0 : throw PrivatBankException(AppLocale.labels.privatBankToken);
103 : }
104 2 : await client.ensureReady(value);
105 1 : if (access == null) {
106 1 : await PrivatBankSettings.saveToken(value);
107 2 : token.clear();
108 1 : access = value;
109 : }
110 1 : isConnected = true;
111 6 : accounts = settings.accounts.map(_account).toList();
112 1 : for (final item in accounts) {
113 0 : await _loadBalance(item);
114 : }
115 2 : if (accounts.isEmpty) {
116 3 : notice = AppLocale.labels.privatBankIbanTooltip;
117 : }
118 : });
119 :
120 3 : Future<void> addAccount() => _run(() async {
121 3 : final value = PrivatBankClient.normalizeIban(iban.text);
122 : if (value == null) {
123 0 : throw PrivatBankException(AppLocale.labels.privatBankIbanInvalid);
124 : }
125 3 : if (!settings.accounts.contains(value)) {
126 3 : settings.accounts.add(value);
127 2 : await settings.save();
128 : }
129 2 : iban.clear();
130 2 : if (!accounts.any((e) => e.iban == value)) {
131 1 : final item = _account(value);
132 2 : accounts.add(item);
133 1 : await _loadBalance(item);
134 : }
135 : });
136 :
137 0 : Future<void> removeAccount(PrivatBankAccount item) => _run(() async {
138 0 : settings.accounts.remove(item.iban);
139 0 : settings.links.remove(item.iban);
140 0 : settings.imported.remove(item.iban);
141 0 : await settings.save();
142 0 : accounts.remove(item);
143 : });
144 :
145 0 : Future<void> disconnect() => _run(() async {
146 0 : isConnected = false;
147 0 : accounts = [];
148 : });
149 :
150 3 : Future<void> forget() => _run(() async {
151 1 : await PrivatBankSettings.clearToken();
152 1 : access = null;
153 1 : isConnected = false;
154 2 : accounts = [];
155 : });
156 :
157 3 : Future<void> importTransactions(PrivatBankAccount item) => _run(() async {
158 1 : final current = access;
159 : if (current == null) {
160 : return;
161 : }
162 2 : if (item.appAccount == null || item.category == null) {
163 0 : throw PrivatBankException(AppLocale.labels.integrationSelectTarget);
164 : }
165 2 : final state = Provider.of<AppData>(context, listen: false);
166 2 : await client.ensureReady(current);
167 4 : final transactions = await client.getTransactions(current, iban: item.iban, start: item.from);
168 1 : final importer = PrivatBankImporter(
169 2 : exists: (uuid) => state.getByUuid(uuid) != null,
170 3 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
171 : );
172 1 : final summary = importer.run(
173 1 : iban: item.iban,
174 : transactions: transactions,
175 1 : account: item.appAccount!,
176 1 : category: item.category!,
177 2 : currency: item.balance?.currency,
178 1 : prediction: state.prediction,
179 : );
180 1 : await state.restate();
181 1 : final today = DateTime.now();
182 5 : settings.links[item.iban] = item.appAccount!;
183 8 : settings.imported[item.iban] = DateTime(today.year, today.month, today.day);
184 2 : await settings.save();
185 3 : notice = AppLocale.labels.integrationImported(summary.added, summary.pending, summary.skipped);
186 : });
187 :
188 1 : Widget buildAccount(BuildContext context, PrivatBankAccount item, AppData state) {
189 1 : final balance = item.balance;
190 1 : return IntegrationAccountCard(
191 3 : key: ValueKey('privatbank_${item.iban}'),
192 1 : title: item.title,
193 5 : subtitle: balance != null ? '${AppLocale.labels.balance}: ${balance.amount} ${balance.currency}' : null,
194 : target: item,
195 : state: state,
196 1 : isDisabled: isLoading,
197 0 : onChanged: () => setState(() {}),
198 2 : onImport: () => importTransactions(item),
199 1 : children: [
200 1 : Align(
201 : alignment: Alignment.centerRight,
202 1 : child: TextButton.icon(
203 : icon: const Icon(Icons.delete_outline),
204 1 : onPressed: isLoading ? null : () => removeAccount(item),
205 3 : label: Text(AppLocale.labels.privatBankRemove),
206 : ),
207 : ),
208 : ],
209 : );
210 : }
211 :
212 1 : @override
213 : Widget build(BuildContext context) {
214 1 : final textTheme = context.textTheme;
215 1 : final colorScheme = context.colorScheme;
216 2 : return Consumer<AppData>(builder: (context, state, _) {
217 1 : return Column(
218 1 : crossAxisAlignment: AppDesign.getAlignment(),
219 1 : children: [
220 4 : Text(AppLocale.labels.privatBankDescription, style: textTheme.bodyMedium),
221 : ThemeHelper.hIndent2x,
222 2 : if (access == null) ...[
223 3 : Text(AppLocale.labels.privatBankTokenSteps,
224 1 : key: const ValueKey('privatbank_steps'), style: textTheme.bodyMedium),
225 : ThemeHelper.hIndent2x,
226 1 : InputWrapper.text(
227 2 : title: AppLocale.labels.privatBankToken,
228 2 : tooltip: AppLocale.labels.privatBankTokenTooltip,
229 1 : controller: token,
230 : isRequired: true,
231 : ),
232 : ],
233 1 : ThemeHelper.hIndent2x,
234 1 : if (error != null) ...[
235 0 : Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
236 : ThemeHelper.hIndent,
237 : ],
238 2 : if (notice != null) ...[
239 3 : Text(notice!, style: textTheme.bodyLarge),
240 : ThemeHelper.hIndent,
241 : ],
242 1 : if (isLoading)
243 0 : const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48)))
244 1 : else ...[
245 1 : !isConnected
246 1 : ? FullSizedButtonWidget(
247 : key: const ValueKey('privatbank_connect'),
248 : icon: Icons.login,
249 1 : onPressed: connect,
250 2 : title: AppLocale.labels.integrationConnect,
251 : )
252 1 : : FullSizedButtonWidget(
253 : key: const ValueKey('privatbank_disconnect'),
254 : icon: Icons.logout,
255 1 : onPressed: disconnect,
256 2 : title: AppLocale.labels.integrationDisconnect,
257 : ),
258 1 : if (access != null)
259 1 : Align(
260 : alignment: Alignment.centerRight,
261 1 : child: TextButton.icon(
262 : key: const ValueKey('privatbank_forget'),
263 : icon: const Icon(Icons.link_off),
264 1 : onPressed: forget,
265 3 : label: Text(AppLocale.labels.integrationForget),
266 : ),
267 : ),
268 : ],
269 2 : for (final item in accounts) buildAccount(context, item, state),
270 2 : if (isConnected) ...[
271 : ThemeHelper.hIndent2x,
272 1 : InputWrapper.text(
273 2 : title: AppLocale.labels.privatBankIban,
274 2 : tooltip: AppLocale.labels.privatBankIbanTooltip,
275 1 : controller: iban,
276 : ),
277 1 : FullSizedButtonWidget(
278 : key: const ValueKey('privatbank_add'),
279 : icon: Icons.add,
280 1 : onPressed: addAccount,
281 2 : title: AppLocale.labels.privatBankAdd,
282 1 : isDisabled: isLoading,
283 : ),
284 : ],
285 : ],
286 : );
287 : });
288 : }
289 : }
|