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:flutter_currency_picker/flutter_currency_picker.dart';
5 :
6 : typedef NotificationParsed = ({double amount, String? currency, String title});
7 :
8 : class NotificationParser {
9 : static const _number = r"\d{1,3}(?:[ '.,]\d{3})+(?:[.,]\d{1,2})?(?![\d]|[.,]\d)|\d+(?:[.,]\d{1,2})?(?![\d]|[.,]\d)";
10 :
11 : static const aliases = {
12 : 'US\$': 'USD',
13 : 'C\$': 'CAD',
14 : 'A\$': 'AUD',
15 : 'lei': 'RON',
16 : 'руб': 'RUB',
17 : 'грн': 'UAH',
18 : 'тг': 'KZT',
19 : 'сўм': 'UZS',
20 : "so'm": 'UZS',
21 : };
22 :
23 0 : static bool _isIgnored(Currency currency) {
24 0 : final symbol = currency.symbol.trim();
25 0 : return symbol.isEmpty ||
26 0 : symbol == currency.code ||
27 0 : RegExp(r'^[A-Za-z]$').hasMatch(symbol) ||
28 0 : RegExp(r'^[a-z]{3,}$').hasMatch(symbol);
29 : }
30 :
31 0 : static final Map<String, List<String>> symbols = () {
32 0 : final result = <String, List<String>>{};
33 0 : for (final currency in CurrencyProvider.getAll()) {
34 0 : if (!_isIgnored(currency)) {
35 0 : result.putIfAbsent(currency.symbol.trim(), () => []).add(currency.code);
36 : }
37 : }
38 0 : aliases.forEach((symbol, code) => result.putIfAbsent(symbol, () => [code]));
39 : return result;
40 0 : }();
41 :
42 : // Symbols of letters only (`kr`, `Ft`, `Le`) might be a part of a sentence
43 0 : static bool _isWeak(String symbol) =>
44 0 : RegExp(r"^[A-Za-z.' ]+$").hasMatch(symbol) && !RegExp(r'^[A-Z]{3}$').hasMatch(symbol);
45 :
46 : // Defaults of user-defined keywords: words preceding an amount to be skipped
47 : static const balanceKeywords = [
48 : 'balance',
49 : 'bal.',
50 : 'bal:',
51 : 'avail',
52 : 'limit',
53 : 'остаток',
54 : 'ост.',
55 : 'ост:',
56 : 'доступно',
57 : 'баланс',
58 : 'рэшта',
59 : 'астатак',
60 : 'даступна',
61 : 'залишок',
62 : 'saldo',
63 : 'kontostand',
64 : 'guthaben',
65 : 'verfügbar',
66 : 'solde',
67 : 'disponible',
68 : 'dostępn',
69 : 'disponibil',
70 : 'zůstatek',
71 : 'bakiye',
72 : 'kullanılabilir',
73 : 'beschikbaar',
74 : 'qoldiq',
75 : 'qalıq',
76 : 'ნაშთი',
77 : 'موجودی',
78 : 'الرصيد',
79 : 'शेष',
80 : 'बैलेंस',
81 : '残高',
82 : '余额',
83 : '餘額',
84 : '잔액',
85 : 'sisa',
86 : ];
87 :
88 : // Defaults of user-defined keywords: words marking a notification as income
89 : static const incomeKeywords = [
90 : 'received',
91 : 'credited',
92 : 'deposit',
93 : 'incoming',
94 : 'refund',
95 : 'salary',
96 : 'top-up',
97 : 'top up',
98 : 'topped up',
99 : 'cashback',
100 : 'transfer from',
101 : 'зачисл',
102 : 'поступлен',
103 : 'пополнен',
104 : 'возврат',
105 : 'перевод от',
106 : 'залічэн',
107 : 'паступлен',
108 : 'папаўнен',
109 : 'вяртан',
110 : 'зарахован',
111 : 'надходжен',
112 : 'поповнен',
113 : 'повернен',
114 : 'gutschrift',
115 : 'eingang',
116 : 'erhalten',
117 : 'erstattung',
118 : 'wpływ',
119 : 'uznanie',
120 : 'otrzyma',
121 : 'zwrot',
122 : 'recibid',
123 : 'abono',
124 : 'ingreso',
125 : 'reembolso',
126 : 'reçu',
127 : 'crédité',
128 : 'remboursement',
129 : 'ricevut',
130 : 'accredit',
131 : 'rimborso',
132 : 'recebid',
133 : 'creditad',
134 : 'ontvangen',
135 : 'bijgeschreven',
136 : 'terugbetaling',
137 : 'přijat',
138 : 'připsán',
139 : 'vrácen',
140 : 'primit',
141 : 'încasat',
142 : 'rambursare',
143 : 'gelen',
144 : 'yatırıldı',
145 : 'iade',
146 : 'tushum',
147 : 'daxil olub',
148 : 'diterima',
149 : 'masuk',
150 : 'ჩაირიცხა',
151 : 'واریز',
152 : 'إيداع',
153 : 'استرداد',
154 : 'जमा',
155 : '入金',
156 : '入账',
157 : '收到',
158 : '退款',
159 : '入帳',
160 : '입금',
161 : '환불',
162 : ];
163 :
164 : // Defaults of user-defined keywords: labels of a field with a merchant, "Lokalizacja: ROSSMANN 42", "Merchant: Starbucks"
165 : static const merchantLabels = [
166 : 'merchant',
167 : 'payee',
168 : 'location',
169 : 'place',
170 : 'store',
171 : 'shop',
172 : 'lokalizacja',
173 : 'miejsce',
174 : 'odbiorca',
175 : 'sprzedawca',
176 : 'händler',
177 : 'empfänger',
178 : 'geschäft',
179 : 'commerçant',
180 : 'marchand',
181 : 'bénéficiaire',
182 : 'lieu',
183 : 'comercio',
184 : 'establecimiento',
185 : 'beneficiario',
186 : 'esercente',
187 : 'estabelecimento',
188 : 'místo',
189 : 'obchodník',
190 : 'příjemce',
191 : 'comerciant',
192 : 'locație',
193 : 'işyeri',
194 : 'winkel',
195 : 'begunstigde',
196 : 'место',
197 : 'магазин',
198 : 'получатель',
199 : 'торговая точка',
200 : 'месца',
201 : 'атрымальнік',
202 : 'місце',
203 : 'отримувач',
204 : ];
205 :
206 : static const _letter = r'A-Za-zÀ-ÿĀ-žЀ-ӿ';
207 :
208 0 : static final _merchant = RegExp(r'(?:^|\s)(?:at|bei|chez|в|у|@)\s+([^\n,;]+?)(?=\s*(?:[,;\n]|\.\s|\.$|$))');
209 :
210 0 : static RegExp toLabelled(List<String> merchant) => RegExp(
211 0 : '(?<![$_letter])(?:${merchant.map(RegExp.escape).join('|')})\\s*:\\s*([^\\n,;]+?)(?=\\s*(?:[,;\\n]|\\.\\s|\\.\$|\$))',
212 : caseSensitive: false,
213 : );
214 :
215 0 : static final _labelled = toLabelled(merchantLabels);
216 :
217 : // The latest user-defined labels are kept compiled, they are the same for all notifications of a run
218 : static (String, RegExp)? _custom;
219 :
220 0 : static RegExp? _toLabelled(List<String> merchant) {
221 0 : if (merchant.isEmpty) {
222 : return null;
223 : }
224 : if (identical(merchant, merchantLabels)) {
225 0 : return _labelled;
226 : }
227 0 : final key = merchant.join('\n');
228 : final custom = _custom;
229 0 : if (custom != null && custom.$1 == key) {
230 : return custom.$2;
231 : }
232 0 : return (_custom = (key, toLabelled(merchant))).$2;
233 : }
234 :
235 0 : static final RegExp _money = () {
236 : // A currency should not be a part of a word
237 : const letter = r'A-Za-zÀ-ÿЀ-ӿ';
238 : // Longer symbols first: `R$` before `$`
239 0 : final scope = symbols.keys.toList()..sort((a, b) => b.length.compareTo(a.length));
240 0 : final currency = '(?<![$letter])(?:${[r'[A-Z]{3}', ...scope.map(RegExp.escape)].join('|')})(?![$letter])';
241 0 : return RegExp(
242 0 : '(?<s0>[+\\-−–])?\\s?(?:(?<c1>$currency)\\s?(?<s1>[+\\-−–])?\\s?(?<n1>$_number)|(?<n2>$_number)\\s?(?<c2>$currency))',
243 : );
244 0 : }();
245 :
246 0 : static double? toAmount(String value) {
247 0 : var number = value.replaceAll(RegExp(r"[ ']"), '');
248 0 : final decimal = RegExp(r'[.,](\d{1,2})$').firstMatch(number);
249 : var fraction = '';
250 : if (decimal != null) {
251 0 : fraction = '.${decimal.group(1)}';
252 0 : number = number.substring(0, decimal.start);
253 : }
254 0 : return double.tryParse(number.replaceAll(RegExp(r'[.,]'), '') + fraction);
255 : }
256 :
257 0 : static String? toCurrency(String? value, {Currency? fallback}) {
258 0 : if (value == null || value.isEmpty) {
259 : return null;
260 : }
261 0 : final codes = symbols[value];
262 : if (codes == null) {
263 0 : return CurrencyProvider.find(value)?.code;
264 : }
265 0 : final preferred = [
266 : fallback?.code,
267 : CurrencyDefaults.defaultCurrency?.code,
268 0 : ...?CurrencyProvider.getTop(),
269 : ];
270 0 : return preferred.firstWhere((code) => code != null && codes.contains(code), orElse: () => codes.first);
271 : }
272 :
273 0 : static List<String> toKeywords(Iterable<String> value) =>
274 0 : value.map((e) => e.trim().toLowerCase()).where((e) => e.isNotEmpty).toSet().toList();
275 :
276 0 : static bool isIncome(String text, {List<String> income = incomeKeywords}) {
277 0 : final value = text.toLowerCase();
278 0 : return income.any(value.contains);
279 : }
280 :
281 0 : static bool isBalance(String text, {List<String> balance = balanceKeywords}) {
282 0 : final value = text.toLowerCase();
283 0 : return balance.any(value.contains);
284 : }
285 :
286 : // Account (key) mentioned the earliest in the text by one of its keywords, the longer keyword wins a tie
287 0 : static String? toAccount(String text, Map<String, List<String>> accounts) {
288 0 : final value = text.toLowerCase();
289 : String? result;
290 0 : var position = value.length;
291 : var length = 0;
292 0 : accounts.forEach((account, keywords) {
293 0 : for (final keyword in keywords) {
294 0 : final index = keyword.isEmpty ? -1 : value.indexOf(keyword.toLowerCase());
295 0 : if (index >= 0 && (index < position || (index == position && keyword.length > length))) {
296 : result = account;
297 : position = index;
298 0 : length = keyword.length;
299 : }
300 : }
301 : });
302 : return result;
303 : }
304 :
305 0 : static String toLine(String value) {
306 0 : final line = value.replaceAll(RegExp(r'\s+'), ' ').trim();
307 0 : return line.length > 100 ? '${line.substring(0, 99)}…' : line;
308 : }
309 :
310 0 : static String getTitle(String text, String fallback, {List<String> merchant = merchantLabels}) {
311 0 : for (final pattern in [_toLabelled(merchant), _merchant].nonNulls) {
312 0 : final value = pattern.firstMatch(text)?.group(1)?.trim();
313 0 : if (value != null && value.isNotEmpty && !_money.hasMatch(value)) {
314 0 : return toLine(value);
315 : }
316 : }
317 0 : return toLine(fallback);
318 : }
319 :
320 0 : static int? _sign(String? value) => switch (value) {
321 0 : null || '' => null,
322 0 : '+' => 1,
323 0 : _ => -1,
324 : };
325 :
326 : // Amount without a currency: only with a fraction, to skip codes, counters and card numbers
327 0 : static final _bare = RegExp(
328 : r"(?<![\w.,])(?<s>[+\-−–])?\s?(?<n>\d{1,3}(?:[ '.,]\d{3})+[.,]\d{2}|\d+[.,]\d{2})(?![\w]|[.,]\d)",
329 : );
330 :
331 : // The currency of a notification is preferred to be the fallback one,
332 : // amounts without a currency are taken in the fallback one when `isBare` is set
333 0 : static NotificationParsed? parse(
334 : String title,
335 : String text, {
336 : Currency? fallback,
337 : bool isBare = false,
338 : List<String> income = incomeKeywords,
339 : List<String> balance = balanceKeywords,
340 : List<String> merchant = merchantLabels,
341 : }) {
342 0 : final content = [title, text].where((e) => e.isNotEmpty).join('\n');
343 : var from = 0;
344 : NotificationParsed? weak;
345 0 : for (final match in _money.allMatches(content)) {
346 0 : final before = content.substring(from, match.start).toLowerCase();
347 0 : from = match.end;
348 0 : final symbol = match.namedGroup('c1') ?? match.namedGroup('c2');
349 0 : final currency = toCurrency(symbol, fallback: fallback);
350 0 : final amount = toAmount(match.namedGroup('n1') ?? match.namedGroup('n2') ?? '');
351 0 : if (currency == null || amount == null || amount == 0 || isBalance(before, balance: balance)) {
352 : continue;
353 : }
354 0 : final sign = _sign(match.namedGroup('s0')) ??
355 0 : _sign(match.namedGroup('s1')) ??
356 0 : (isIncome(content, income: income) ? 1 : -1);
357 0 : final result = (amount: sign * amount, currency: currency, title: getTitle(content, text, merchant: merchant));
358 0 : if (!_isWeak(symbol!)) {
359 : return result;
360 : }
361 : weak ??= result;
362 : }
363 : if (weak != null || !isBare || fallback == null) {
364 : return weak;
365 : }
366 0 : return _parseBare(content, text, fallback, income: income, balance: balance, merchant: merchant);
367 : }
368 :
369 0 : static NotificationParsed? _parseBare(
370 : String content,
371 : String text,
372 : Currency currency, {
373 : required List<String> income,
374 : required List<String> balance,
375 : required List<String> merchant,
376 : }) {
377 : var from = 0;
378 0 : for (final match in _bare.allMatches(content)) {
379 0 : final before = content.substring(from, match.start).toLowerCase();
380 0 : from = match.end;
381 0 : final amount = toAmount(match.namedGroup('n')!);
382 0 : if (amount == null || amount == 0 || isBalance(before, balance: balance)) {
383 : continue;
384 : }
385 0 : final sign = _sign(match.namedGroup('s')) ?? (isIncome(content, income: income) ? 1 : -1);
386 0 : return (amount: sign * amount, currency: currency.code, title: getTitle(content, text, merchant: merchant));
387 : }
388 : return null;
389 : }
390 : }
|