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/monobank/monobank_client.dart';
7 : import 'package:app_finance/_classes/integration/monobank/monobank_importer.dart';
8 : import 'package:app_finance/_classes/integration/monobank/monobank_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/_classes/structure/account_app_data.dart';
13 : import 'package:app_finance/_classes/structure/bill_app_data.dart';
14 : import 'package:app_finance/_configs/account_type.dart';
15 : import 'package:app_finance/_configs/theme_helper.dart';
16 : import 'package:app_finance/_ext/build_context_ext.dart';
17 : import 'package:app_finance/design/button/full_sized_button_widget.dart';
18 : import 'package:app_finance/design/generic/loading_widget.dart';
19 : import 'package:app_finance/design/wrapper/input_wrapper.dart';
20 : import 'package:app_finance/pages/integration/widgets/integration_account_card.dart';
21 : import 'package:flutter_currency_picker/flutter_currency_picker.dart';
22 : import 'package:material_ui/material_ui.dart';
23 : import 'package:provider/provider.dart';
24 :
25 : class MonobankBankAccount extends IntegrationTarget {
26 : final MonobankAccount account;
27 :
28 1 : MonobankBankAccount(this.account, {super.appAccount, super.category, required super.from});
29 :
30 1 : String get title {
31 1 : final source = account;
32 1 : if (source.isJar) {
33 0 : return [AppLocale.labels.monobankJar, source.title ?? ''].where((e) => e.isNotEmpty).join(': ');
34 : }
35 8 : final type = source.type.isNotEmpty ? '${source.type[0].toUpperCase()}${source.type.substring(1)}' : '';
36 4 : final pan = source.maskedPan.isNotEmpty ? source.maskedPan.first : (source.iban ?? '');
37 6 : return [type, pan, source.currency].where((e) => e.isNotEmpty).join(' — ');
38 : }
39 :
40 1 : String get accountType {
41 2 : if (account.isJar) {
42 0 : return AppAccountType.deposit.toString();
43 : }
44 3 : if (account.type == 'fop') {
45 0 : return AppAccountType.account.toString();
46 : }
47 4 : return (account.creditLimit > 0 ? AppAccountType.creditCard : AppAccountType.debitCard).toString();
48 : }
49 : }
50 :
51 : class MonobankWidget extends StatefulWidget {
52 : final MonobankClient? client;
53 :
54 3 : const MonobankWidget({super.key, this.client});
55 :
56 1 : @override
57 1 : MonobankWidgetState createState() => MonobankWidgetState();
58 : }
59 :
60 : class MonobankWidgetState extends State<MonobankWidget> {
61 : late final MonobankClient client;
62 : late final MonobankSettings settings;
63 : final token = TextEditingController();
64 : String? access;
65 : List<MonobankBankAccount> accounts = [];
66 : bool isLoading = false;
67 : String? error;
68 : String? notice;
69 : MonobankCancelToken? cancelToken;
70 : String? progress;
71 : double? progressValue;
72 :
73 1 : @override
74 : void initState() {
75 1 : super.initState();
76 4 : client = widget.client ?? MonobankClient();
77 2 : settings = MonobankSettings.load();
78 2 : access = MonobankSettings.loadToken();
79 : }
80 :
81 1 : @override
82 : void dispose() {
83 1 : cancelToken?.cancel();
84 2 : token.dispose();
85 2 : if (widget.client == null) {
86 2 : client.close();
87 : }
88 1 : super.dispose();
89 : }
90 :
91 1 : Future<void> _run(Future<void> Function() callback) async {
92 2 : setState(() {
93 1 : isLoading = true;
94 1 : error = null;
95 1 : notice = null;
96 1 : progress = null;
97 1 : progressValue = null;
98 : });
99 : try {
100 1 : await callback();
101 0 : } on MonobankCanceledException {
102 : // Already imported windows are kept
103 0 : } on MonobankException catch (e) {
104 0 : error = e.message;
105 : } catch (e) {
106 0 : error = e.toString();
107 : } finally {
108 1 : cancelToken = null;
109 1 : if (mounted) {
110 3 : setState(() => isLoading = false);
111 : }
112 : }
113 : }
114 :
115 1 : void _progress(int done, int total, Duration? wait) {
116 1 : if (!mounted) {
117 : return;
118 : }
119 2 : setState(() {
120 3 : progressValue = total > 0 ? done / total : null;
121 2 : progress = [
122 2 : AppLocale.labels.monobankProgress(done, total),
123 3 : if (wait != null) AppLocale.labels.monobankRateLimit(wait.inSeconds),
124 1 : ].join('\n');
125 : });
126 : }
127 :
128 0 : void cancel() => cancelToken?.cancel();
129 :
130 3 : Future<void> connect() => _run(() async {
131 4 : final value = access ?? token.text.trim();
132 1 : if (value.isEmpty) {
133 0 : throw MonobankException(AppLocale.labels.monobankToken);
134 : }
135 2 : cancelToken = MonobankCancelToken();
136 3 : final info = await client.getClientInfo(value, cancel: cancelToken);
137 1 : if (access == null) {
138 1 : await MonobankSettings.saveToken(value);
139 2 : token.clear();
140 1 : access = value;
141 : }
142 1 : final defaultBudget = AppPreferences.get(AppPreferences.prefBudget);
143 2 : final monthAgo = DateTime.now().subtract(const Duration(days: 30));
144 2 : accounts = info.accounts
145 3 : .map((account) => MonobankBankAccount(
146 : account,
147 4 : appAccount: settings.links[account.id],
148 : category: defaultBudget,
149 4 : from: settings.imported[account.id] ?? monthAgo,
150 : ))
151 1 : .toList();
152 2 : if (accounts.isEmpty) {
153 0 : notice = AppLocale.labels.integrationNoAccounts;
154 : }
155 : });
156 :
157 0 : Future<void> disconnect() => _run(() async => accounts = []);
158 :
159 3 : Future<void> forget() => _run(() async {
160 1 : await MonobankSettings.clearToken();
161 1 : access = null;
162 2 : accounts = [];
163 : });
164 :
165 3 : Future<void> createAccount(MonobankBankAccount item) => _run(() async {
166 2 : final state = Provider.of<AppData>(context, listen: false);
167 3 : final currency = CurrencyProvider.find(item.account.currency);
168 2 : final created = state.add(AccountAppData(
169 1 : title: item.title,
170 1 : type: item.accountType,
171 2 : details: item.account.amount,
172 : progress: 1.0,
173 : currency: currency,
174 : hidden: false,
175 : )) as AccountAppData;
176 2 : item.appAccount = created.uuid;
177 6 : settings.links[item.account.id] = created.uuid!;
178 2 : await settings.save();
179 : });
180 :
181 3 : Future<void> importTransactions(MonobankBankAccount item) => _run(() async {
182 1 : final current = access;
183 : if (current == null) {
184 : return;
185 : }
186 2 : if (item.appAccount == null || item.category == null) {
187 0 : throw MonobankException(AppLocale.labels.integrationSelectTarget);
188 : }
189 2 : final state = Provider.of<AppData>(context, listen: false);
190 2 : final id = item.account.id;
191 1 : final importer = MonobankImporter(
192 2 : exists: (uuid) => state.getByUuid(uuid) != null,
193 3 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
194 3 : categories: MonobankImporter.learn(settings.records, (uuid) {
195 0 : final bill = state.getByUuid(uuid);
196 0 : return bill is BillAppData && !bill.hidden ? bill.category : null;
197 : }),
198 : );
199 : var added = 0;
200 : var skipped = 0;
201 : var pending = 0;
202 4 : settings.links[id] = item.appAccount!;
203 2 : cancelToken = MonobankCancelToken();
204 : try {
205 2 : await client.getTransactions(
206 : current,
207 : id,
208 1 : from: item.from,
209 1 : cancel: cancelToken,
210 1 : onProgress: _progress,
211 1 : onWindow: (window, transactions) {
212 1 : final summary = importer.run(
213 : id: id,
214 : transactions: transactions,
215 1 : account: item.appAccount!,
216 1 : category: item.category!,
217 2 : currency: item.account.currency,
218 1 : prediction: state.prediction,
219 : );
220 1 : added += summary.added;
221 1 : skipped += summary.skipped;
222 1 : pending += summary.pending;
223 : // Transactions on hold are requested again on the next import
224 1 : final since = importer.pendingSince;
225 0 : final last = since != null && since.isBefore(window.to) ? since : window.to;
226 7 : settings.imported[id] = DateTime(last.year, last.month, last.day);
227 : },
228 : );
229 : } finally {
230 3 : settings.addRecords(importer.records);
231 2 : await settings.save();
232 4 : item.from = settings.imported[id] ?? item.from;
233 1 : await state.restate();
234 3 : notice = AppLocale.labels.integrationImported(added, pending, skipped);
235 : }
236 : });
237 :
238 1 : Widget buildAccount(BuildContext context, MonobankBankAccount item, AppData state) {
239 1 : final source = item.account;
240 1 : return IntegrationAccountCard(
241 3 : key: ValueKey('monobank_${source.id}'),
242 1 : title: item.title,
243 1 : subtitle: [
244 5 : '${AppLocale.labels.balance}: ${source.amount} ${source.currency}',
245 2 : if (source.creditLimit > 0) '${AppLocale.labels.creditCard}: ${source.limit} ${source.currency}',
246 1 : ].join('\n'),
247 : target: item,
248 : state: state,
249 1 : isDisabled: isLoading,
250 0 : onChanged: () => setState(() {}),
251 2 : onImport: () => importTransactions(item),
252 1 : children: [
253 3 : if (item.appAccount == null || state.getByUuid(item.appAccount!) == null)
254 1 : Align(
255 : alignment: Alignment.centerRight,
256 1 : child: TextButton.icon(
257 3 : key: ValueKey('monobank_create_${source.id}'),
258 : icon: const Icon(Icons.add),
259 3 : onPressed: isLoading ? null : () => createAccount(item),
260 3 : label: Text(AppLocale.labels.monobankCreateAccount),
261 : ),
262 : ),
263 : ],
264 : );
265 : }
266 :
267 0 : Widget buildProgress(BuildContext context) {
268 0 : final textTheme = context.textTheme;
269 0 : return Column(
270 : crossAxisAlignment: CrossAxisAlignment.stretch,
271 0 : children: [
272 0 : if (progress != null) ...[
273 0 : Text(progress!, key: const ValueKey('monobank_progress'), style: textTheme.bodyMedium),
274 : ThemeHelper.hIndent,
275 0 : LinearProgressIndicator(value: progressValue),
276 : ] else
277 0 : const Center(child: LoadingWidget(isLoading: true, size: Size(48, 48))),
278 0 : if (cancelToken != null)
279 0 : Align(
280 : alignment: Alignment.centerRight,
281 0 : child: TextButton.icon(
282 : key: const ValueKey('monobank_cancel'),
283 : icon: const Icon(Icons.close),
284 0 : onPressed: cancel,
285 0 : label: Text(AppLocale.labels.btnCancel),
286 : ),
287 : ),
288 : ],
289 : );
290 : }
291 :
292 1 : @override
293 : Widget build(BuildContext context) {
294 1 : final textTheme = context.textTheme;
295 1 : final colorScheme = context.colorScheme;
296 2 : return Consumer<AppData>(builder: (context, state, _) {
297 1 : return Column(
298 1 : crossAxisAlignment: AppDesign.getAlignment(),
299 1 : children: [
300 4 : Text(AppLocale.labels.monobankDescription, style: textTheme.bodyMedium),
301 : ThemeHelper.hIndent2x,
302 2 : if (access == null) ...[
303 3 : Text(AppLocale.labels.monobankTokenSteps,
304 1 : key: const ValueKey('monobank_steps'), style: textTheme.bodyMedium),
305 : ThemeHelper.hIndent2x,
306 1 : InputWrapper.text(
307 2 : title: AppLocale.labels.monobankToken,
308 2 : tooltip: AppLocale.labels.monobankTokenTooltip,
309 1 : controller: token,
310 : isRequired: true,
311 : ),
312 : ],
313 1 : ThemeHelper.hIndent2x,
314 1 : if (error != null) ...[
315 0 : Text(error!, style: textTheme.bodyLarge?.copyWith(color: colorScheme.error)),
316 : ThemeHelper.hIndent,
317 : ],
318 2 : if (notice != null) ...[
319 3 : Text(notice!, style: textTheme.bodyLarge),
320 : ThemeHelper.hIndent,
321 : ],
322 1 : if (isLoading)
323 0 : buildProgress(context)
324 1 : else ...[
325 2 : accounts.isEmpty
326 1 : ? FullSizedButtonWidget(
327 : key: const ValueKey('monobank_connect'),
328 : icon: Icons.login,
329 1 : onPressed: connect,
330 2 : title: AppLocale.labels.integrationConnect,
331 : )
332 1 : : FullSizedButtonWidget(
333 : key: const ValueKey('monobank_disconnect'),
334 : icon: Icons.logout,
335 1 : onPressed: disconnect,
336 2 : title: AppLocale.labels.integrationDisconnect,
337 : ),
338 1 : if (access != null)
339 1 : Align(
340 : alignment: Alignment.centerRight,
341 1 : child: TextButton.icon(
342 : key: const ValueKey('monobank_forget'),
343 : icon: const Icon(Icons.link_off),
344 1 : onPressed: forget,
345 3 : label: Text(AppLocale.labels.integrationForget),
346 : ),
347 : ),
348 : ],
349 2 : for (final item in accounts) buildAccount(context, item, state),
350 : ],
351 : );
352 : });
353 : }
354 : }
|