nice overview working

This commit is contained in:
davmar
2026-09-08 23:52:54 +02:00
parent e7a7b1a357
commit 2a741c7f2a
16 changed files with 3512 additions and 810 deletions
+2
View File
@@ -14,6 +14,7 @@ import 'screens/splash_screen.dart';
import 'services/storage_service.dart'; import 'services/storage_service.dart';
import 'utils/app_theme.dart'; import 'utils/app_theme.dart';
import 'utils/constants.dart'; import 'utils/constants.dart';
import 'widgets/skip_build_when_covered.dart';
Future<void> main() async { Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
@@ -101,6 +102,7 @@ class _MaterialRoot extends StatelessWidget {
theme: AppTheme.light(), theme: AppTheme.light(),
darkTheme: AppTheme.dark(), darkTheme: AppTheme.dark(),
themeMode: themeMode, themeMode: themeMode,
navigatorObservers: [appRouteObserver],
home: const SplashScreen(), home: const SplashScreen(),
); );
} }
+160 -4
View File
@@ -11,6 +11,7 @@ class TxLabel {
required this.color, required this.color,
this.icon = Icons.label_outline, this.icon = Icons.label_outline,
this.custom = false, this.custom = false,
this.parentId,
}); });
final String id; final String id;
@@ -19,25 +20,127 @@ class TxLabel {
final IconData icon; final IconData icon;
final bool custom; final bool custom;
/// Optional parent label id for nesting (sub-labels).
final String? parentId;
bool get isRoot => parentId == null || parentId!.isEmpty;
TxLabel copyWith({
String? name,
Color? color,
IconData? icon,
String? parentId,
bool clearParent = false,
}) {
return TxLabel(
id: id,
name: name ?? this.name,
color: color ?? this.color,
icon: icon ?? this.icon,
custom: custom,
parentId: clearParent ? null : (parentId ?? this.parentId),
);
}
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
'id': id, 'id': id,
'name': name, 'name': name,
// ignore: deprecated_member_use — wide compatibility across Flutter versions // ignore: deprecated_member_use — wide compatibility across Flutter versions
'color': color.value, 'color': color.value,
'custom': custom, 'custom': custom,
if (parentId != null && parentId!.isNotEmpty) 'parentId': parentId,
}; };
factory TxLabel.fromJson(Map<String, dynamic> json) { factory TxLabel.fromJson(Map<String, dynamic> json) {
final parent = json['parentId'] as String?;
return TxLabel( return TxLabel(
id: json['id'] as String? ?? 'custom', id: json['id'] as String? ?? 'custom',
name: json['name'] as String? ?? 'Label', name: json['name'] as String? ?? 'Label',
color: Color(json['color'] as int? ?? 0xFF64748B), color: Color(json['color'] as int? ?? 0xFF64748B),
custom: json['custom'] as bool? ?? true, custom: json['custom'] as bool? ?? true,
parentId: (parent != null && parent.isNotEmpty) ? parent : null,
); );
} }
} }
/// Built-in presets (no "uncategorized" / "other"). /// One row in a depth-first label tree walk.
class LabelTreeEntry {
const LabelTreeEntry({required this.label, required this.depth});
final TxLabel label;
final int depth;
}
/// Max nesting depth (root = 0).
const int kMaxLabelDepth = 3;
/// Depth-first tree order using each label's [TxLabel.parentId].
List<LabelTreeEntry> flattenLabelTree(
Iterable<TxLabel> labels, {
String? Function(String id)? parentOf,
}) {
final byId = <String, TxLabel>{
for (final label in labels) label.id: label,
};
String? resolveParent(String id) {
if (parentOf != null) return parentOf(id);
return byId[id]?.parentId;
}
final children = <String?, List<TxLabel>>{};
for (final label in byId.values) {
final parent = resolveParent(label.id);
final key = (parent != null && byId.containsKey(parent)) ? parent : null;
(children[key] ??= []).add(label);
}
for (final list in children.values) {
list.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
}
final out = <LabelTreeEntry>[];
void walk(String? parentId, int depth) {
final kids = children[parentId];
if (kids == null) return;
for (final label in kids) {
out.add(LabelTreeEntry(label: label, depth: depth));
if (depth < kMaxLabelDepth) {
walk(label.id, depth + 1);
}
}
}
walk(null, 0);
return out;
}
/// Visible indent depth among [visibleIds] only (skip missing ancestors).
int labelVisibleDepth(
String labelId,
Set<String> visibleIds,
String? Function(String id) parentOf,
) {
var depth = 0;
var parent = parentOf(labelId);
final seen = <String>{labelId};
while (parent != null && parent.isNotEmpty && seen.add(parent)) {
if (visibleIds.contains(parent)) depth++;
parent = parentOf(parent);
}
return depth;
}
/// Filter-only id for txs with no labels (not an assignable category).
const String kUncategorizedFilterId = '__uncategorized__';
/// Chip presentation for [kUncategorizedFilterId] refine filters.
const TxLabel kUncategorizedFilterLabel = TxLabel(
id: kUncategorizedFilterId,
name: 'Uncategorized',
color: Color(0xFF64748B),
icon: Icons.label_off_outlined,
);
/// Built-in presets (no "uncategorized" / "other" as assignable labels).
const List<TxLabel> kBuiltinLabels = [ const List<TxLabel> kBuiltinLabels = [
TxLabel( TxLabel(
id: 'groceries', id: 'groceries',
@@ -205,7 +308,10 @@ class TxExactTemplate {
} }
} }
/// Strip bank noise so "AH Campus … Transactie:123" matches other AH Campus txs. /// Strip bank noise so supermarket / POS lines group by merchant stem.
///
/// Example: `BCK*AH CAMPUS DIEMEN ZUID NLD Pasvolgnr:…` → `ah campus`
/// Example: `Albert Heijn 1562 Utrecht` → `albert heijn`
String merchantKeyFromDescription(String description) { String merchantKeyFromDescription(String description) {
var s = description var s = description
.trim() .trim()
@@ -240,8 +346,58 @@ String merchantKeyFromDescription(String description) {
} }
s = s s = s
.replaceAll(RegExp(r'\s+nld\s*$'), '')
.replaceAll(RegExp(r'^bck\*'), '') .replaceAll(RegExp(r'^bck\*'), '')
.replaceAll(RegExp(r'\s+'), ' ')
.trim(); .trim();
return s;
// Drop trailing country / city noise and store / terminal numbers.
s = s.replaceAll(
RegExp(
r'\s+(nld|nl|nederland|netherlands|bel|belgium|deu|germany|de)\s*$',
),
'',
);
// Remove digit runs (store ids, amounts embedded in text, etc.).
s = s.replaceAll(RegExp(r'\b\d+\b'), ' ');
s = s.replaceAll(RegExp(r'\s+'), ' ').trim();
// Keep a short stem so "ah campus diemen zuid" ≈ "ah campus".
final words = [
for (final w in s.split(' '))
if (w.length > 1) w,
];
if (words.isEmpty) return s;
if (words.length <= 2) return words.join(' ');
// Prefer first two tokens for long POS strings; three when the 2nd is tiny
// ("de", "van") so "albert heijn" / "jumbo city" stay intact.
if (words[1].length <= 2 && words.length >= 3) {
return words.take(3).join(' ');
}
return words.take(2).join(' ');
} }
/// Default “apply to similar” pattern — usually the merchant stem.
String defaultSimilarPattern(String description) =>
merchantKeyFromDescription(description);
/// Match [description] against a simple contains needle or `/regex/`.
bool descriptionMatchesPattern(String description, String pattern) {
final raw = pattern.trim();
if (raw.isEmpty) return false;
final hay = description.toLowerCase();
if (raw.length >= 3 && raw.startsWith('/') && raw.endsWith('/')) {
final body = raw.substring(1, raw.length - 1);
if (body.isEmpty) return false;
try {
return RegExp(body, caseSensitive: false).hasMatch(description);
} catch (_) {
return hay.contains(raw.toLowerCase());
}
}
final needle = raw.toLowerCase();
if (needle.length < 2) return false;
return hay.contains(needle);
}
+14
View File
@@ -30,6 +30,7 @@ class BankController extends ChangeNotifier {
_remoteTransactions = cached.transactions; _remoteTransactions = cached.transactions;
} }
_importedTransactions = _storage?.loadImportedTransactions() ?? const []; _importedTransactions = _storage?.loadImportedTransactions() ?? const [];
_invalidateMerged();
} }
final IngtrakApi _api; final IngtrakApi _api;
@@ -39,6 +40,7 @@ class BankController extends ChangeNotifier {
BankBalance? _balance; BankBalance? _balance;
List<BankTransaction> _remoteTransactions = const []; List<BankTransaction> _remoteTransactions = const [];
List<BankTransaction> _importedTransactions = const []; List<BankTransaction> _importedTransactions = const [];
List<BankTransaction>? _mergedTransactions;
bool _isLoading = false; bool _isLoading = false;
bool _isConnecting = false; bool _isConnecting = false;
@@ -50,9 +52,17 @@ class BankController extends ChangeNotifier {
BankBalance? get balance => _balance; BankBalance? get balance => _balance;
/// Remote API txs merged with locally imported CSV txs (deduped). /// Remote API txs merged with locally imported CSV txs (deduped).
///
/// Cached — [mergeTransactions] is O(n·m) and was re-running on every
/// `bank.transactions` read during rebuilds.
List<BankTransaction> get transactions => List<BankTransaction> get transactions =>
_mergedTransactions ??=
mergeTransactions(_remoteTransactions, _importedTransactions); mergeTransactions(_remoteTransactions, _importedTransactions);
void _invalidateMerged() {
_mergedTransactions = null;
}
int get importedCount => _importedTransactions.length; int get importedCount => _importedTransactions.length;
bool get isLoading => _isLoading; bool get isLoading => _isLoading;
bool get isConnecting => _isConnecting; bool get isConnecting => _isConnecting;
@@ -121,6 +131,7 @@ class BankController extends ChangeNotifier {
_remoteTransactions, _remoteTransactions,
_importedTransactions, _importedTransactions,
); );
_invalidateMerged();
await _persistImported(); await _persistImported();
} }
return result; return result;
@@ -139,6 +150,7 @@ class BankController extends ChangeNotifier {
Future<void> clearImportedTransactions() async { Future<void> clearImportedTransactions() async {
_importedTransactions = const []; _importedTransactions = const [];
_invalidateMerged();
await _storage?.clearImportedTransactions(); await _storage?.clearImportedTransactions();
notifyListeners(); notifyListeners();
} }
@@ -210,6 +222,7 @@ class BankController extends ChangeNotifier {
_remoteTransactions, _remoteTransactions,
_importedTransactions, _importedTransactions,
); );
_invalidateMerged();
await _persistImported(); await _persistImported();
_error = null; _error = null;
} on IngtrakApiException catch (error) { } on IngtrakApiException catch (error) {
@@ -218,6 +231,7 @@ class BankController extends ChangeNotifier {
_status = ConnectStatus.disconnected; _status = ConnectStatus.disconnected;
_balance = null; _balance = null;
_remoteTransactions = const []; _remoteTransactions = const [];
_invalidateMerged();
_error = error.message; _error = error.message;
await _persistCache(); await _persistCache();
} else if (!hasData) { } else if (!hasData) {
+443 -70
View File
@@ -1,6 +1,8 @@
/// Local labels / notes / recurring annotations for bank transactions. /// Local labels / notes / recurring annotations for bank transactions.
library; library;
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../models/bank.dart'; import '../models/bank.dart';
@@ -18,6 +20,7 @@ class TxMetaController extends ChangeNotifier {
_notesByMerchant = Map.of(loaded.notesByMerchant); _notesByMerchant = Map.of(loaded.notesByMerchant);
_exactTemplates = Map.of(loaded.exactTemplates); _exactTemplates = Map.of(loaded.exactTemplates);
_customLabels = List.of(loaded.customLabels); _customLabels = List.of(loaded.customLabels);
_labelParents = Map.of(loaded.labelParents);
} }
final StorageService _storage; final StorageService _storage;
@@ -27,39 +30,246 @@ class TxMetaController extends ChangeNotifier {
Map<String, String> _notesByMerchant = {}; Map<String, String> _notesByMerchant = {};
Map<String, TxExactTemplate> _exactTemplates = {}; Map<String, TxExactTemplate> _exactTemplates = {};
List<TxLabel> _customLabels = []; List<TxLabel> _customLabels = [];
Map<String, String> _labelParents = {};
/// Built-in + custom labels available for picking. /// Built-in + custom labels available for picking.
List<TxLabel> get allLabels => [...kBuiltinLabels, ..._customLabels]; List<TxLabel> get allLabels => [...kBuiltinLabels, ..._customLabels];
Map<String, TxLabel>? _labelByIdCache;
Map<String, List<String>>? _labelIdsByTxCache;
Map<String, TxLabel> get _labelById {
return _labelByIdCache ??= {
for (final label in allLabels) label.id: label,
};
}
void _invalidateLabelCache() {
_labelByIdCache = null;
_labelIdsByTxCache = null;
_labeledTxCount = null;
_labeledCountListIdentity = null;
}
int? _labeledTxCount;
int? _labeledCountListIdentity;
/// Cached count of txs that resolve to at least one label.
int labeledTransactionCount(List<BankTransaction> txs) {
final identity = identityHashCode(txs);
if (_labeledTxCount != null && _labeledCountListIdentity == identity) {
return _labeledTxCount!;
}
var n = 0;
for (final tx in txs) {
if (labelIdsFor(tx).isNotEmpty) n++;
}
_labeledTxCount = n;
_labeledCountListIdentity = identity;
return n;
}
List<TxLabel> get customLabels => List.unmodifiable(_customLabels); List<TxLabel> get customLabels => List.unmodifiable(_customLabels);
/// Effective parent id (hierarchy map wins over embedded [TxLabel.parentId]).
String? parentIdOf(String labelId) {
final mapped = _labelParents[labelId];
if (mapped != null) {
return mapped.isEmpty ? null : mapped;
}
final embedded = _labelById[labelId]?.parentId;
if (embedded == null || embedded.isEmpty) return null;
return embedded;
}
/// Labels in tree order with depth.
List<LabelTreeEntry> labelsInTreeOrder([Iterable<TxLabel>? subset]) {
final source = subset?.toList() ?? allLabels;
return flattenLabelTree(source, parentOf: parentIdOf);
}
/// Tree order limited to [available], keeping relative indent.
List<LabelTreeEntry> treeOrderFor(Iterable<TxLabel> available) {
final availableList = available.toList();
final ids = availableList.map((l) => l.id).toSet();
final full = flattenLabelTree(allLabels, parentOf: parentIdOf);
return [
for (final entry in full)
if (ids.contains(entry.label.id))
LabelTreeEntry(
label: entry.label,
depth: labelVisibleDepth(entry.label.id, ids, parentIdOf),
),
];
}
int depthOf(String labelId) {
var depth = 0;
var parent = parentIdOf(labelId);
final seen = <String>{labelId};
while (parent != null && seen.add(parent)) {
depth++;
parent = parentIdOf(parent);
if (depth > kMaxLabelDepth) break;
}
return depth;
}
/// Parent chain of [labelId], nearest parent first.
List<String> ancestorIdsOf(String labelId) {
final out = <String>[];
var parent = parentIdOf(labelId);
final seen = <String>{labelId};
while (parent != null && parent.isNotEmpty && seen.add(parent)) {
out.add(parent);
parent = parentIdOf(parent);
}
return out;
}
/// All nested labels under [labelId].
List<String> descendantIdsOf(String labelId) {
final out = <String>[];
void walk(String id) {
for (final label in allLabels) {
if (parentIdOf(label.id) == id) {
out.add(label.id);
walk(label.id);
}
}
}
walk(labelId);
return out;
}
/// Ensures every selected sub-label also includes its parents.
List<String> expandWithAncestors(Iterable<String> ids) {
final out = <String>{};
for (final id in ids) {
if (id.isEmpty) continue;
out.add(id);
out.addAll(ancestorIdsOf(id));
}
return out.toList(growable: false);
}
bool canSetParent({required String labelId, String? parentId}) {
if (parentId == null || parentId.isEmpty) return true;
if (parentId == labelId) return false;
if (_labelById[parentId] == null) return false;
if (depthOf(parentId) >= kMaxLabelDepth) return false;
// Prevent cycles: parent cannot be a descendant of label.
var walk = parentIdOf(parentId);
final seen = <String>{parentId};
while (walk != null && seen.add(walk)) {
if (walk == labelId) return false;
walk = parentIdOf(walk);
}
return true;
}
/// Candidates that [labelId] can move under (excluding self/descendants).
List<TxLabel> validParentsFor(String labelId) {
final banned = <String>{labelId};
void collectDescendants(String id) {
for (final label in allLabels) {
if (parentIdOf(label.id) == id && banned.add(label.id)) {
collectDescendants(label.id);
}
}
}
collectDescendants(labelId);
return [
for (final label in allLabels)
if (!banned.contains(label.id) && depthOf(label.id) < kMaxLabelDepth)
label,
]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
}
Future<void> setLabelParent(String labelId, String? parentId) async {
final nextParent =
(parentId == null || parentId.isEmpty) ? null : parentId;
if (!canSetParent(labelId: labelId, parentId: nextParent)) {
return;
}
final nextParents = Map<String, String>.of(_labelParents);
if (nextParent == null) {
nextParents.remove(labelId);
} else {
nextParents[labelId] = nextParent;
}
_labelParents = nextParents;
final customIndex = _customLabels.indexWhere((l) => l.id == labelId);
if (customIndex >= 0) {
final current = _customLabels[customIndex];
final updated = nextParent == null
? current.copyWith(clearParent: true)
: current.copyWith(parentId: nextParent);
_customLabels = [
for (var i = 0; i < _customLabels.length; i++)
if (i == customIndex) updated else _customLabels[i],
];
}
_schedulePersist();
}
TxLabel? labelById(String? id) { TxLabel? labelById(String? id) {
if (id == null || id.isEmpty) return null; if (id == null || id.isEmpty) return null;
for (final label in allLabels) { return _labelById[id];
if (label.id == id) return label;
}
return null;
} }
List<TxLabel> labelsFor(TxMeta meta) { List<TxLabel> labelsFor(TxMeta meta) {
final index = _labelById;
return [ return [
for (final id in meta.labelIds) for (final id in meta.labelIds)
if (labelById(id) != null) labelById(id)!, if (index[id] != null) index[id]!,
]; ];
} }
/// Labels to show on tiles: omit parents when a child is also selected.
List<TxLabel> leafLabelsFor(TxMeta meta) {
final ids = meta.labelIds.toSet();
final index = _labelById;
return [
for (final id in ids)
if (index[id] != null &&
!ids.any(
(other) =>
other != id && ancestorIdsOf(other).contains(id),
))
index[id]!,
];
}
/// Label ids only — cheaper than [metaFor] for chart aggregation.
/// Always includes ancestor labels of any selected sub-label.
List<String> labelIdsFor(BankTransaction tx) {
final cache = _labelIdsByTxCache ??= {};
final cached = cache[tx.id];
if (cached != null) return cached;
final stored = _byId[tx.id];
final raw = stored != null && stored.hasLabel
? stored.labelIds
: (_resolveMerchantLabels(tx) ?? const <String>[]);
final ids = expandWithAncestors(raw);
final frozen = ids.isEmpty
? const <String>[]
: List<String>.unmodifiable(ids);
cache[tx.id] = frozen;
return frozen;
}
/// Resolved meta: per-id overrides + inherited merchant rules. /// Resolved meta: per-id overrides + inherited merchant rules.
TxMeta metaFor(BankTransaction tx) { TxMeta metaFor(BankTransaction tx) {
final stored = _byId[tx.id]; final stored = _byId[tx.id];
final template = _exactTemplates[tx.exactKey]; final template = _exactTemplates[tx.exactKey];
final inheritedLabels = _labelsByMerchant[tx.merchantKey] ?? final labelIds = labelIdsFor(tx);
_labelsByMerchant[tx.descriptionKey]; final inheritedNotes = _resolveMerchantNotes(tx);
final inheritedNotes = _notesByMerchant[tx.merchantKey] ??
_notesByMerchant[tx.descriptionKey];
final labelIds = stored != null && stored.hasLabel
? stored.labelIds
: (inheritedLabels ?? const <String>[]);
final notes = stored != null && stored.hasNotes final notes = stored != null && stored.hasNotes
? stored.notes ? stored.notes
@@ -76,93 +286,165 @@ class TxMetaController extends ChangeNotifier {
); );
} }
/// Exact merchant key first, then longest rule key contained in description.
List<String>? _resolveMerchantLabels(BankTransaction tx) {
final direct = _labelsByMerchant[tx.merchantKey] ??
_labelsByMerchant[tx.descriptionKey];
if (direct != null) return direct;
return _bestMatchingRule(_labelsByMerchant, tx.description);
}
String? _resolveMerchantNotes(BankTransaction tx) {
final direct =
_notesByMerchant[tx.merchantKey] ?? _notesByMerchant[tx.descriptionKey];
if (direct != null) return direct;
return _bestMatchingRule(_notesByMerchant, tx.description);
}
V? _bestMatchingRule<V>(Map<String, V> rules, String description) {
if (rules.isEmpty) return null;
final hay = description.toLowerCase();
String? bestKey;
V? bestValue;
for (final entry in rules.entries) {
final key = entry.key;
if (key.length < 2) continue;
if (!hay.contains(key)) continue;
if (bestKey == null || key.length > bestKey.length) {
bestKey = key;
bestValue = entry.value;
}
}
return bestValue;
}
int countSimilar( int countSimilar(
BankTransaction prototype, BankTransaction prototype,
List<BankTransaction> all, List<BankTransaction> all, {
) { String? pattern,
final key = prototype.merchantKey; }) {
if (key.isEmpty) return 1; final needle = (pattern ?? prototype.merchantKey).trim();
return all.where((tx) => tx.merchantKey == key).length; if (needle.isEmpty) return 1;
var count = 0;
for (final tx in all) {
if (descriptionMatchesPattern(tx.description, needle)) count++;
}
return count == 0 ? 1 : count;
} }
List<BankTransaction> similarTo( List<BankTransaction> similarTo(
BankTransaction prototype, BankTransaction prototype,
List<BankTransaction> all, List<BankTransaction> all, {
) { String? pattern,
final key = prototype.merchantKey; }) {
if (key.isEmpty) return [prototype]; final needle = (pattern ?? prototype.merchantKey).trim();
return [ if (needle.isEmpty) return [prototype];
final matches = [
for (final tx in all) for (final tx in all)
if (tx.merchantKey == key) tx, if (descriptionMatchesPattern(tx.description, needle)) tx,
]; ];
return matches.isEmpty ? [prototype] : matches;
} }
Future<void> setLabels( Future<void> setLabels(
BankTransaction tx, BankTransaction tx,
List<String> labelIds, { List<String> labelIds, {
List<BankTransaction> applyToSimilar = const [], List<BankTransaction> applyToSimilar = const [],
String? matchPattern,
}) async { }) async {
final cleaned = <String>[ final expanded = expandWithAncestors([
for (final id in labelIds) for (final id in labelIds)
if (id.isNotEmpty) id, if (id.isNotEmpty) id,
]; ]);
// Deduplicate while preserving order. // Deduplicate while preserving order.
final unique = <String>[]; final unique = <String>[];
for (final id in cleaned) { for (final id in expanded) {
if (!unique.contains(id)) unique.add(id); if (!unique.contains(id)) unique.add(id);
} }
final scope = applyToSimilar.isEmpty ? [tx] : applyToSimilar; final pattern = (matchPattern ?? tx.merchantKey).trim().toLowerCase();
final applying = applyToSimilar.isNotEmpty;
final nextById = Map<String, TxMeta>.of(_byId); final nextById = Map<String, TxMeta>.of(_byId);
for (final other in scope) { void writeTx(BankTransaction other) {
if (applyToSimilar.isNotEmpty && final stored = nextById[other.id];
other.merchantKey != tx.merchantKey) { final current = stored ?? metaFor(other);
continue;
}
final current = metaFor(other);
nextById[other.id] = unique.isEmpty nextById[other.id] = unique.isEmpty
? current.copyWith(clearLabels: true) ? current.copyWith(clearLabels: true)
: current.copyWith(labelIds: unique); : current.copyWith(labelIds: unique);
} }
_byId = nextById;
writeTx(tx);
if (applying) {
// Only patch txs that already have per-id overrides; others inherit
// from the merchant rule so we avoid bloating SharedPreferences.
for (final other in applyToSimilar) {
if (other.id == tx.id) continue;
if (!nextById.containsKey(other.id)) continue;
writeTx(other);
}
final nextRules = Map<String, List<String>>.of(_labelsByMerchant); final nextRules = Map<String, List<String>>.of(_labelsByMerchant);
if (unique.isEmpty) { if (unique.isEmpty) {
if (pattern.isNotEmpty) nextRules.remove(pattern);
nextRules.remove(tx.merchantKey); nextRules.remove(tx.merchantKey);
nextRules.remove(tx.descriptionKey); nextRules.remove(tx.descriptionKey);
} else { } else if (pattern.isNotEmpty) {
nextRules[tx.merchantKey] = unique; nextRules[pattern] = unique;
} }
_labelsByMerchant = nextRules; _labelsByMerchant = nextRules;
await _persist(); }
_byId = nextById;
_schedulePersist();
} }
Future<void> toggleLabel( Future<void> toggleLabel(
BankTransaction tx, BankTransaction tx,
String labelId, { String labelId, {
List<BankTransaction> applyToSimilar = const [], List<BankTransaction> applyToSimilar = const [],
String? matchPattern,
}) async { }) async {
final current = List<String>.of(metaFor(tx).labelIds); final current = List<String>.of(metaFor(tx).labelIds);
if (current.contains(labelId)) { if (current.contains(labelId)) {
current.remove(labelId); final remove = {labelId, ...descendantIdsOf(labelId)};
current.removeWhere(remove.contains);
} else { } else {
current.add(labelId); current.add(labelId);
} }
await setLabels(tx, current, applyToSimilar: applyToSimilar); await setLabels(
tx,
current,
applyToSimilar: applyToSimilar,
matchPattern: matchPattern,
);
} }
Future<void> clearLabels( Future<void> clearLabels(
BankTransaction tx, { BankTransaction tx, {
List<BankTransaction> applyToSimilar = const [], List<BankTransaction> applyToSimilar = const [],
String? matchPattern,
}) { }) {
return setLabels(tx, const [], applyToSimilar: applyToSimilar); return setLabels(
tx,
const [],
applyToSimilar: applyToSimilar,
matchPattern: matchPattern,
);
} }
Future<TxLabel> createLabel(String name) async { Future<TxLabel> createLabel(String name, {String? parentId}) async {
final trimmed = name.trim(); final trimmed = name.trim();
if (trimmed.isEmpty) { if (trimmed.isEmpty) {
throw ArgumentError('Label name required'); throw ArgumentError('Label name required');
} }
final parent =
(parentId == null || parentId.isEmpty) ? null : parentId;
if (parent != null && _labelById[parent] == null) {
throw ArgumentError('Unknown parent label');
}
if (parent != null && depthOf(parent) >= kMaxLabelDepth) {
throw ArgumentError('Parent is already at max depth');
}
final color = final color =
kCustomLabelColors[_customLabels.length % kCustomLabelColors.length]; kCustomLabelColors[_customLabels.length % kCustomLabelColors.length];
final label = TxLabel( final label = TxLabel(
@@ -171,15 +453,44 @@ class TxMetaController extends ChangeNotifier {
color: color, color: color,
icon: Icons.label_outline, icon: Icons.label_outline,
custom: true, custom: true,
parentId: parent,
); );
_customLabels = [..._customLabels, label]; _customLabels = [..._customLabels, label];
await _persist(); if (parent != null) {
_labelParents = {..._labelParents, label.id: parent};
}
_schedulePersist();
return label; return label;
} }
Future<void> removeLabel(String labelId) async { Future<void> removeLabel(String labelId) async {
final oldParent = parentIdOf(labelId);
_customLabels = _customLabels =
_customLabels.where((label) => label.id != labelId).toList(); _customLabels.where((label) => label.id != labelId).toList();
// Re-parent children to the removed label's parent (or root).
final nextParents = <String, String>{};
for (final entry in _labelParents.entries) {
if (entry.key == labelId) continue;
if (entry.value == labelId) {
if (oldParent != null) {
nextParents[entry.key] = oldParent;
}
} else {
nextParents[entry.key] = entry.value;
}
}
_labelParents = nextParents;
_customLabels = [
for (final label in _customLabels)
if (label.parentId == labelId)
oldParent == null
? label.copyWith(clearParent: true)
: label.copyWith(parentId: oldParent)
else
label,
];
final nextById = <String, TxMeta>{}; final nextById = <String, TxMeta>{};
for (final entry in _byId.entries) { for (final entry in _byId.entries) {
if (entry.value.labelIds.contains(labelId)) { if (entry.value.labelIds.contains(labelId)) {
@@ -200,7 +511,7 @@ class TxMetaController extends ChangeNotifier {
if (id != labelId) id, if (id != labelId) id,
], ],
}; };
await _persist(); _schedulePersist();
} }
Future<void> setRecurring(BankTransaction tx, bool recurring) async { Future<void> setRecurring(BankTransaction tx, bool recurring) async {
@@ -217,28 +528,36 @@ class TxMetaController extends ChangeNotifier {
recurring: recurring, recurring: recurring,
), ),
}; };
await _persist(); _schedulePersist();
} }
Future<void> setNotes( Future<void> setNotes(
BankTransaction tx, BankTransaction tx,
String notes, { String notes, {
List<BankTransaction> applyToSimilar = const [], List<BankTransaction> applyToSimilar = const [],
String? matchPattern,
}) async { }) async {
final trimmed = notes.trim(); final trimmed = notes.trim();
final scope = applyToSimilar.isEmpty ? [tx] : applyToSimilar; final pattern = (matchPattern ?? tx.merchantKey).trim().toLowerCase();
final applying = applyToSimilar.isNotEmpty;
final nextById = Map<String, TxMeta>.of(_byId); final nextById = Map<String, TxMeta>.of(_byId);
for (final other in scope) { void writeTx(BankTransaction other) {
if (applyToSimilar.isNotEmpty &&
other.merchantKey != tx.merchantKey) {
continue;
}
final current = metaFor(other); final current = metaFor(other);
nextById[other.id] = current.copyWith(notes: trimmed); nextById[other.id] = current.copyWith(notes: trimmed);
} }
writeTx(tx);
if (applying) {
for (final other in applyToSimilar) {
if (other.id == tx.id) continue;
if (!nextById.containsKey(other.id)) continue;
writeTx(other);
}
}
_byId = nextById; _byId = nextById;
if (applyToSimilar.isEmpty) { if (!applying) {
final current = metaFor(tx); final current = metaFor(tx);
final existing = _exactTemplates[tx.exactKey] ?? const TxExactTemplate(); final existing = _exactTemplates[tx.exactKey] ?? const TxExactTemplate();
if (trimmed.isEmpty && !existing.recurring && !current.recurring) { if (trimmed.isEmpty && !existing.recurring && !current.recurring) {
@@ -255,21 +574,23 @@ class TxMetaController extends ChangeNotifier {
if (trimmed.isEmpty) { if (trimmed.isEmpty) {
_notesByMerchant = Map.of(_notesByMerchant) _notesByMerchant = Map.of(_notesByMerchant)
..remove(tx.merchantKey) ..remove(tx.merchantKey)
..remove(tx.descriptionKey); ..remove(tx.descriptionKey)
..remove(pattern);
} }
} else { } else {
if (trimmed.isEmpty) { if (trimmed.isEmpty) {
_notesByMerchant = Map.of(_notesByMerchant) _notesByMerchant = Map.of(_notesByMerchant)
..remove(tx.merchantKey) ..remove(tx.merchantKey)
..remove(tx.descriptionKey); ..remove(tx.descriptionKey)
} else { ..remove(pattern);
} else if (pattern.isNotEmpty) {
_notesByMerchant = { _notesByMerchant = {
..._notesByMerchant, ..._notesByMerchant,
tx.merchantKey: trimmed, pattern: trimmed,
}; };
} }
} }
await _persist(); _schedulePersist();
} }
Future<void> toggleRecurring(BankTransaction tx) { Future<void> toggleRecurring(BankTransaction tx) {
@@ -287,19 +608,47 @@ class TxMetaController extends ChangeNotifier {
final hasLabels = labelIds.isNotEmpty; final hasLabels = labelIds.isNotEmpty;
if (!hasText && !hasLabels) return txs; if (!hasText && !hasLabels) return txs;
return txs.where((tx) { final labelIndex = _labelById;
return [
for (final tx in txs)
if (_matchesSearch(tx, needle, hasText, labelIds, hasLabels, labelIndex))
tx,
];
}
bool _matchesSearch(
BankTransaction tx,
String needle,
bool hasText,
Set<String> labelIds,
bool hasLabels,
Map<String, TxLabel> labelIndex,
) {
final meta = metaFor(tx); final meta = metaFor(tx);
if (hasLabels && !meta.labelIds.any(labelIds.contains)) { if (hasLabels && !_matchesLabelFilter(meta, labelIds)) {
return false; return false;
} }
if (!hasText) return true; if (!hasText) return true;
final labelNames = labelsFor(meta).map((l) => l.name.toLowerCase()); if (tx.description.toLowerCase().contains(needle)) return true;
return tx.description.toLowerCase().contains(needle) || if (meta.notes.toLowerCase().contains(needle)) return true;
meta.notes.toLowerCase().contains(needle) || if (tx.date.toLowerCase().contains(needle)) return true;
labelNames.any((name) => name.contains(needle)) || if (tx.amount.toString().contains(needle)) return true;
tx.date.toLowerCase().contains(needle) || for (final id in meta.labelIds) {
tx.amount.toString().contains(needle); final name = labelIndex[id]?.name;
}).toList(growable: false); if (name != null && name.toLowerCase().contains(needle)) return true;
}
return false;
}
/// OR filter: any selected label, and/or unlabeled when uncategorized is selected.
bool _matchesLabelFilter(TxMeta meta, Set<String> labelIds) {
final wantUncategorized = labelIds.contains(kUncategorizedFilterId);
if (wantUncategorized && !meta.hasLabel) return true;
for (final id in labelIds) {
if (id == kUncategorizedFilterId) continue;
if (meta.labelIds.contains(id)) return true;
}
return false;
} }
/// Labels currently used by [transactions]. /// Labels currently used by [transactions].
@@ -316,17 +665,41 @@ class TxMetaController extends ChangeNotifier {
return list; return list;
} }
Future<void> _persist() async { /// UI-first: notify on the next frame so callers can paint a busy state first,
/// then write SharedPreferences in the background.
void _schedulePersist() {
_invalidateLabelCache();
final binding = WidgetsBinding.instance;
binding.addPostFrameCallback((_) {
notifyListeners(); notifyListeners();
await _storage.saveTxMetaStore( });
TxMetaStoreData( // Ensure a frame is scheduled even if nothing else is dirty yet.
binding.scheduleFrame();
unawaited(_writeStore());
}
Future<void> _writeStore() async {
// Let the busy indicator / label checkbox paint before JSON work.
await Future<void>.delayed(Duration.zero);
final snapshot = TxMetaStoreData(
byId: _byId, byId: _byId,
labelsByMerchant: _labelsByMerchant, labelsByMerchant: _labelsByMerchant,
notesByMerchant: _notesByMerchant, notesByMerchant: _notesByMerchant,
exactTemplates: _exactTemplates, exactTemplates: _exactTemplates,
customLabels: _customLabels, customLabels: [
for (final label in _customLabels)
label.copyWith(
parentId: parentIdOf(label.id),
clearParent: parentIdOf(label.id) == null,
), ),
],
labelParents: _labelParents,
); );
try {
await _storage.saveTxMetaStore(snapshot);
} catch (error, stackTrace) {
debugPrint('TxMetaController persist failed: $error\n$stackTrace');
}
} }
/// Absolute spend (outflows) per label. Multi-label txs count fully in each. /// Absolute spend (outflows) per label. Multi-label txs count fully in each.
+12 -4
View File
@@ -12,6 +12,7 @@ import '../utils/navigation.dart';
import '../widgets/empty_state.dart'; import '../widgets/empty_state.dart';
import '../widgets/loading_view.dart'; import '../widgets/loading_view.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
import '../widgets/skip_build_when_covered.dart';
import 'transaction_detail_screen.dart'; import 'transaction_detail_screen.dart';
import 'transactions_screen.dart'; import 'transactions_screen.dart';
@@ -54,6 +55,10 @@ class _HomeBody extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Stay subscribed, but skip heavy scans while covered by another route
// (e.g. transaction detail applying labels to many similar txs).
context.watch<TxMetaController>();
if (bank.isLoading && bank.balance == null && !bank.hasData) { if (bank.isLoading && bank.balance == null && !bank.hasData) {
return const LoadingView(message: 'Checking bank link…'); return const LoadingView(message: 'Checking bank link…');
} }
@@ -89,14 +94,15 @@ class _HomeBody extends StatelessWidget {
); );
} }
return SkipBuildWhenCovered(
builder: (context) {
final balance = bank.balance; final balance = bank.balance;
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
final meta = context.watch<TxMetaController>(); final meta = context.watch<TxMetaController>();
final recent = bank.transactions.take(5).toList(growable: false); final recent = bank.transactions.take(5).toList(growable: false);
final categorized = bank.transactions final categorized =
.where((tx) => meta.metaFor(tx).hasLabel) meta.labeledTransactionCount(bank.transactions);
.length;
return ListView( return ListView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
@@ -209,7 +215,7 @@ class _HomeBody extends StatelessWidget {
leading: Builder( leading: Builder(
builder: (context) { builder: (context) {
final labels = final labels =
meta.labelsFor(meta.metaFor(tx)); meta.leafLabelsFor(meta.metaFor(tx));
final label = labels.isEmpty ? null : labels.first; final label = labels.isEmpty ? null : labels.first;
return Icon( return Icon(
label?.icon ?? Icons.receipt_long_outlined, label?.icon ?? Icons.receipt_long_outlined,
@@ -247,6 +253,8 @@ class _HomeBody extends StatelessWidget {
], ],
], ],
); );
},
);
} }
} }
+19 -10
View File
@@ -9,6 +9,7 @@ import '../providers/bank_provider.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
import '../widgets/skip_build_when_covered.dart';
import 'transaction_detail_screen.dart'; import 'transaction_detail_screen.dart';
class LabelTransactionsScreen extends StatelessWidget { class LabelTransactionsScreen extends StatelessWidget {
@@ -20,9 +21,16 @@ class LabelTransactionsScreen extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final bank = context.watch<BankController>(); final bank = context.watch<BankController>();
final meta = context.watch<TxMetaController>(); final meta = context.watch<TxMetaController>();
return Scaffold(
appBar: AppBar(
title: Text(label.name),
),
body: ResponsiveBody(
child: SkipBuildWhenCovered(
builder: (context) {
final txs = [ final txs = [
for (final tx in bank.transactions) for (final tx in bank.transactions)
if (meta.metaFor(tx).labelIds.contains(label.id)) tx, if (meta.labelIdsFor(tx).contains(label.id)) tx,
]; ];
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
@@ -33,19 +41,15 @@ class LabelTransactionsScreen extends StatelessWidget {
if (tx.amount < 0) totalOut += tx.amount.abs(); if (tx.amount < 0) totalOut += tx.amount.abs();
} }
return Scaffold( return ListView(
appBar: AppBar(
title: Text(label.name),
),
body: ResponsiveBody(
child: ListView(
padding: const EdgeInsets.only(top: 8, bottom: 32), padding: const EdgeInsets.only(top: 8, bottom: 32),
children: [ children: [
ListTile( ListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
leading: Icon(label.icon, color: label.color), leading: Icon(label.icon, color: label.color),
title: Text('${txs.length} transactions'), title: Text('${txs.length} transactions'),
subtitle: Text('Money out ${formatMoney(totalOut, currency)}'), subtitle:
Text('Money out ${formatMoney(totalOut, currency)}'),
), ),
const Divider(), const Divider(),
if (txs.isEmpty) if (txs.isEmpty)
@@ -70,18 +74,23 @@ class LabelTransactionsScreen extends StatelessWidget {
trailing: Text( trailing: Text(
formatMoney(tx.amount, tx.currency), formatMoney(tx.amount, tx.currency),
style: theme.textTheme.titleSmall?.copyWith( style: theme.textTheme.titleSmall?.copyWith(
color: tx.amount >= 0 ? colors.primary : colors.error, color: tx.amount >= 0
? colors.primary
: colors.error,
), ),
), ),
onTap: () { onTap: () {
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute<void>( MaterialPageRoute<void>(
builder: (_) => TransactionDetailScreen(tx: tx), builder: (_) =>
TransactionDetailScreen(tx: tx),
), ),
); );
}, },
), ),
], ],
);
},
), ),
), ),
); );
+201
View File
@@ -0,0 +1,201 @@
/// Manage labels: create, nest, and delete.
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/transaction_meta.dart';
import '../providers/tx_meta_provider.dart';
import '../widgets/label_parent_picker.dart';
import '../widgets/responsive_body.dart';
class LabelsScreen extends StatelessWidget {
const LabelsScreen({super.key});
Future<void> _create(
BuildContext context, {
String? parentId,
}) async {
final meta = context.read<TxMetaController>();
final result = await showCreateLabelDialog(
context,
parents: meta.allLabels,
initialParentId: parentId,
);
if (result == null || !context.mounted) return;
await meta.createLabel(result.name, parentId: result.parentId);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Created “${result.name}”')),
);
}
Future<void> _delete(BuildContext context, TxLabel label) async {
final ok = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: Text('Remove “${label.name}”?'),
content: const Text(
'This deletes the label. Transactions keep any other labels. '
'Sub-labels move up one level.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: const Text('Remove'),
),
],
);
},
);
if (ok != true || !context.mounted) return;
await context.read<TxMetaController>().removeLabel(label.id);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Removed “${label.name}”')),
);
}
@override
Widget build(BuildContext context) {
final meta = context.watch<TxMetaController>();
final theme = Theme.of(context);
final colors = theme.colorScheme;
final entries = meta.labelsInTreeOrder();
return Scaffold(
appBar: AppBar(
title: const Text('Labels'),
actions: [
IconButton(
tooltip: 'New label',
onPressed: () => _create(context),
icon: const Icon(Icons.add),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _create(context),
icon: const Icon(Icons.add),
label: const Text('New label'),
),
body: ResponsiveBody(
child: entries.isEmpty
? ListView(
children: [
const SizedBox(height: 48),
Icon(
Icons.label_outline,
size: 48,
color: colors.outline,
),
const SizedBox(height: 12),
Text(
'No labels yet',
textAlign: TextAlign.center,
style: theme.textTheme.titleMedium,
),
const SizedBox(height: 8),
Text(
'Create labels to categorize spending.',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
),
],
)
: ListView.separated(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 88),
itemCount: entries.length + 1,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
if (index == 0) {
return Padding(
padding: const EdgeInsets.fromLTRB(4, 4, 4, 12),
child: Text(
'Create, nest under another label, or delete custom '
'ones. Built-in labels can be moved but not deleted.',
style: theme.textTheme.bodyMedium,
),
);
}
final entry = entries[index - 1];
final label = entry.label;
final parentId = meta.parentIdOf(label.id);
final parent = parentId == null ? null : meta.labelById(parentId);
return ListTile(
contentPadding: EdgeInsets.fromLTRB(
8 + entry.depth * 16.0,
0,
4,
0,
),
leading: Icon(label.icon, color: label.color),
title: Text(label.name),
subtitle: Text(
[
if (label.custom) 'Custom' else 'Built-in',
if (parent != null) 'under ${parent.name}',
].join(' · '),
),
trailing: PopupMenuButton<String>(
tooltip: 'Actions',
onSelected: (value) async {
switch (value) {
case 'sub':
await _create(context, parentId: label.id);
case 'move':
await showMoveLabelDialog(context, label: label);
case 'delete':
await _delete(context, label);
}
},
itemBuilder: (context) => [
if (meta.depthOf(label.id) < kMaxLabelDepth)
const PopupMenuItem(
value: 'sub',
child: ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
leading: Icon(Icons.subdirectory_arrow_right),
title: Text('Add sub-label'),
),
),
const PopupMenuItem(
value: 'move',
child: ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
leading: Icon(Icons.account_tree_outlined),
title: Text('Move under…'),
),
),
if (label.custom)
PopupMenuItem(
value: 'delete',
child: ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
leading: Icon(
Icons.delete_outline,
color: colors.error,
),
title: Text(
'Delete',
style: TextStyle(color: colors.error),
),
),
),
],
),
);
},
),
),
);
}
}
File diff suppressed because it is too large Load Diff
+19
View File
@@ -13,6 +13,7 @@ import '../utils/connect_bank.dart';
import '../utils/constants.dart'; import '../utils/constants.dart';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
import 'labels_screen.dart';
class SettingsScreen extends StatelessWidget { class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key}); const SettingsScreen({super.key});
@@ -201,6 +202,24 @@ class SettingsScreen extends StatelessWidget {
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
), ),
const SizedBox(height: 28), const SizedBox(height: 28),
Text('Labels', style: theme.textTheme.titleMedium),
const SizedBox(height: 8),
Card(
child: ListTile(
leading: const Icon(Icons.label_outline),
title: const Text('Manage labels'),
subtitle: const Text('Create, nest, move, or delete'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const LabelsScreen(),
),
);
},
),
),
const SizedBox(height: 28),
Text('CSV import', style: theme.textTheme.titleMedium), Text('CSV import', style: theme.textTheme.titleMedium),
const SizedBox(height: 8), const SizedBox(height: 8),
Card( Card(
+258 -100
View File
@@ -9,6 +9,7 @@ import '../models/transaction_meta.dart';
import '../providers/bank_provider.dart'; import '../providers/bank_provider.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../widgets/label_parent_picker.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
class TransactionDetailScreen extends StatefulWidget { class TransactionDetailScreen extends StatefulWidget {
@@ -23,8 +24,11 @@ class TransactionDetailScreen extends StatefulWidget {
class _TransactionDetailScreenState extends State<TransactionDetailScreen> { class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
late final TextEditingController _notesController; late final TextEditingController _notesController;
late final TextEditingController _patternController;
var _dirty = false; var _dirty = false;
late bool _applyToSimilar; late bool _applyToSimilar;
var _busy = false;
String? _busyMessage;
@override @override
void initState() { void initState() {
@@ -32,8 +36,14 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
final meta = context.read<TxMetaController>(); final meta = context.read<TxMetaController>();
final notes = meta.metaFor(widget.tx).notes; final notes = meta.metaFor(widget.tx).notes;
_notesController = TextEditingController(text: notes); _notesController = TextEditingController(text: notes);
final pattern = defaultSimilarPattern(widget.tx.description);
_patternController = TextEditingController(text: pattern);
final all = context.read<BankController>().transactions; final all = context.read<BankController>().transactions;
final similarCount = meta.countSimilar(widget.tx, all); final similarCount = meta.countSimilar(
widget.tx,
all,
pattern: pattern,
);
// Default on when there are peers — otherwise users never notice the toggle. // Default on when there are peers — otherwise users never notice the toggle.
_applyToSimilar = similarCount > 1; _applyToSimilar = similarCount > 1;
} }
@@ -41,26 +51,55 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
@override @override
void dispose() { void dispose() {
_notesController.dispose(); _notesController.dispose();
_patternController.dispose();
super.dispose(); super.dispose();
} }
String get _pattern => _patternController.text.trim();
List<BankTransaction> _similarScope(TxMetaController meta) { List<BankTransaction> _similarScope(TxMetaController meta) {
final all = context.read<BankController>().transactions; final all = context.read<BankController>().transactions;
if (!_applyToSimilar) return const []; if (!_applyToSimilar) return const [];
return meta.similarTo(widget.tx, all); return meta.similarTo(widget.tx, all, pattern: _pattern);
}
Future<void> _runBusy(
Future<void> Function() action, {
String? message,
}) async {
if (_busy) return;
setState(() {
_busy = true;
_busyMessage = message;
});
// Let the progress bar paint before heavy similar-matching / rebuilds.
await WidgetsBinding.instance.endOfFrame;
try {
await action();
} finally {
if (mounted) {
setState(() {
_busy = false;
_busyMessage = null;
});
}
}
} }
Future<void> _saveNotes() async { Future<void> _saveNotes() async {
await _runBusy(
() async {
final meta = context.read<TxMetaController>(); final meta = context.read<TxMetaController>();
final similar = _similarScope(meta); final similar = _similarScope(meta);
final count = similar.isEmpty ? 1 : similar.length;
await meta.setNotes( await meta.setNotes(
widget.tx, widget.tx,
_notesController.text, _notesController.text,
applyToSimilar: similar, applyToSimilar: similar,
matchPattern: _pattern,
); );
if (!mounted) return; if (!mounted) return;
setState(() => _dirty = false); setState(() => _dirty = false);
final count = similar.isEmpty ? 1 : similar.length;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text( content: Text(
@@ -70,18 +109,26 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
), ),
), ),
); );
},
message: _applyToSimilar
? 'Saving notes on matching transactions…'
: 'Saving notes…',
);
} }
Future<void> _toggleLabel(String labelId) async { Future<void> _toggleLabel(String labelId) async {
await _runBusy(
() async {
final meta = context.read<TxMetaController>(); final meta = context.read<TxMetaController>();
final similar = _similarScope(meta); final similar = _similarScope(meta);
final count = similar.isEmpty ? 1 : similar.length;
await meta.toggleLabel( await meta.toggleLabel(
widget.tx, widget.tx,
labelId, labelId,
applyToSimilar: similar, applyToSimilar: similar,
matchPattern: _pattern,
); );
if (!mounted) return; if (!mounted) return;
final count = similar.isEmpty ? 1 : similar.length;
if (count > 1) { if (count > 1) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
@@ -89,29 +136,80 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
), ),
); );
} }
},
message: _applyToSimilar
? 'Updating labels on matching transactions…'
: null,
);
} }
Future<void> _clearLabels() async { Future<void> _clearLabels() async {
await _runBusy(
() {
final meta = context.read<TxMetaController>(); final meta = context.read<TxMetaController>();
final similar = _similarScope(meta); return meta.clearLabels(
await meta.clearLabels(
widget.tx, widget.tx,
applyToSimilar: similar, applyToSimilar: _similarScope(meta),
matchPattern: _pattern,
);
},
message: _applyToSimilar
? 'Clearing labels on matching transactions…'
: 'Clearing labels…',
); );
} }
Future<void> _createLabel() async { Future<void> _createLabel() async {
final name = await showDialog<String>(
context: context,
builder: (context) => const _NewLabelDialog(),
);
if (name == null || name.isEmpty || !mounted) return;
final meta = context.read<TxMetaController>(); final meta = context.read<TxMetaController>();
final label = await meta.createLabel(name); final result = await showCreateLabelDialog(
context,
parents: meta.allLabels,
);
if (result == null || !mounted) return;
final label = await meta.createLabel(
result.name,
parentId: result.parentId,
);
if (!mounted) return; if (!mounted) return;
await _toggleLabel(label.id); await _toggleLabel(label.id);
} }
Future<void> _labelActions(TxLabel label) async {
final action = await showModalBottomSheet<String>(
context: context,
showDragHandle: true,
builder: (sheetContext) {
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Icons.account_tree_outlined),
title: const Text('Move under…'),
onTap: () => Navigator.pop(sheetContext, 'move'),
),
if (label.custom)
ListTile(
leading: Icon(
Icons.delete_outline,
color: Theme.of(sheetContext).colorScheme.error,
),
title: const Text('Remove label'),
onTap: () => Navigator.pop(sheetContext, 'remove'),
),
],
),
);
},
);
if (!mounted || action == null) return;
if (action == 'move') {
await showMoveLabelDialog(context, label: label);
} else if (action == 'remove') {
await _confirmRemoveLabel(label);
}
}
Future<void> _confirmRemoveLabel(TxLabel label) async { Future<void> _confirmRemoveLabel(TxLabel label) async {
final ok = await showDialog<bool>( final ok = await showDialog<bool>(
context: context, context: context,
@@ -143,17 +241,18 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
final tx = widget.tx; final tx = widget.tx;
final metaController = context.watch<TxMetaController>(); final metaController = context.watch<TxMetaController>();
final meta = metaController.metaFor(tx); final meta = metaController.metaFor(tx);
final all = context.watch<BankController>().transactions; // Prefer read: bank data rarely changes while editing labels.
final similarCount = metaController.countSimilar(tx, all); final all = context.read<BankController>().transactions;
final similarCount = metaController.countSimilar(
tx,
all,
pattern: _pattern,
);
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
final amountColor = tx.amount >= 0 ? colors.primary : colors.error; final amountColor = tx.amount >= 0 ? colors.primary : colors.error;
final selectedIds = meta.labelIds.toSet(); final selectedIds = meta.labelIds.toSet();
final merchantPreview = tx.merchantKey.isEmpty final labelEntries = metaController.labelsInTreeOrder();
? tx.description
: (tx.merchantKey.length > 48
? '${tx.merchantKey.substring(0, 47)}…'
: tx.merchantKey);
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
@@ -161,7 +260,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
actions: [ actions: [
if (_dirty) if (_dirty)
TextButton( TextButton(
onPressed: _saveNotes, onPressed: _busy ? null : _saveNotes,
child: const Text('Save'), child: const Text('Save'),
), ),
], ],
@@ -170,9 +269,29 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
child: ListView( child: ListView(
padding: const EdgeInsets.only(top: 8, bottom: 32), padding: const EdgeInsets.only(top: 8, bottom: 32),
children: [ children: [
if (_busy) ...[
const LinearProgressIndicator(minHeight: 2),
if (_busyMessage != null)
Padding(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 4),
child: Text(
_busyMessage!,
style: theme.textTheme.labelMedium?.copyWith(
color: colors.primary,
),
),
),
],
AbsorbPointer(
absorbing: _busy,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text( Text(
formatMoney(tx.amount, tx.currency), formatMoney(tx.amount, tx.currency),
style: theme.textTheme.headlineMedium?.copyWith(color: amountColor), style: theme.textTheme.headlineMedium?.copyWith(
color: amountColor,
),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text(tx.description, style: theme.textTheme.titleMedium), Text(tx.description, style: theme.textTheme.titleMedium),
@@ -184,19 +303,47 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
].join(' · '), ].join(' · '),
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
), ),
if (similarCount > 1) ...[
const SizedBox(height: 16), const SizedBox(height: 16),
Text('Match similar', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
TextField(
controller: _patternController,
textInputAction: TextInputAction.done,
enabled: !_busy,
decoration: InputDecoration(
hintText: 'e.g. albert heijn or /albert\\s*heijn/',
helperText:
'Plain text = contains. Wrap with /…/ for regex.',
helperMaxLines: 2,
suffixIcon: IconButton(
tooltip: 'Reset default',
onPressed: _busy
? null
: () {
setState(() {
_patternController.text =
defaultSimilarPattern(tx.description);
});
},
icon: const Icon(Icons.refresh),
),
),
onChanged: (_) => setState(() {}),
),
SwitchListTile( SwitchListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
secondary: const Icon(Icons.copy_all_outlined), secondary: const Icon(Icons.copy_all_outlined),
title: const Text('Apply to all similar'), title: const Text('Apply to all similar'),
subtitle: Text( subtitle: Text(
'$similarCount matches · $merchantPreview', similarCount <= 1
? 'No other matches for this pattern'
: '$similarCount matching transactions',
), ),
value: _applyToSimilar, value: _applyToSimilar && similarCount > 1,
onChanged: (value) => setState(() => _applyToSimilar = value), onChanged: _busy || similarCount <= 1
? null
: (value) => setState(() => _applyToSimilar = value),
), ),
],
const SizedBox(height: 8), const SizedBox(height: 8),
SwitchListTile( SwitchListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
@@ -204,7 +351,9 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
title: const Text('Recurring'), title: const Text('Recurring'),
subtitle: const Text('Salary, mortgage, subscriptions…'), subtitle: const Text('Salary, mortgage, subscriptions…'),
value: meta.recurring, value: meta.recurring,
onChanged: (value) { onChanged: _busy
? null
: (value) {
context.read<TxMetaController>().setRecurring(tx, value); context.read<TxMetaController>().setRecurring(tx, value);
}, },
), ),
@@ -213,37 +362,94 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
children: [ children: [
Text('Labels', style: theme.textTheme.titleSmall), Text('Labels', style: theme.textTheme.titleSmall),
const Spacer(), const Spacer(),
TextButton(
onPressed: _busy ? null : _createLabel,
child: const Text('New'),
),
if (meta.hasLabel) if (meta.hasLabel)
TextButton( TextButton(
onPressed: _clearLabels, onPressed: _busy ? null : _clearLabels,
child: const Text('Clear'), child: const Text('Clear'),
), ),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Wrap( DecoratedBox(
spacing: 8, decoration: BoxDecoration(
runSpacing: 8, color: colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: colors.outlineVariant.withValues(alpha: 0.8),
),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Column(
children: [ children: [
for (final label in metaController.allLabels) for (final entry in labelEntries) ...[
GestureDetector( if (entry != labelEntries.first)
onLongPress: label.custom Divider(
? () => _confirmRemoveLabel(label) height: 1,
: null, indent: 40,
child: FilterChip( color: colors.outlineVariant.withValues(alpha: 0.45),
avatar: Icon(label.icon, size: 16, color: label.color), ),
label: Text(label.name), InkWell(
selected: selectedIds.contains(label.id), onTap: _busy ? null : () => _toggleLabel(entry.label.id),
onSelected: (_) => _toggleLabel(label.id), onLongPress:
_busy ? null : () => _labelActions(entry.label),
child: Padding(
padding: EdgeInsets.fromLTRB(
8 + entry.depth * 16.0,
2,
4,
2,
),
child: Row(
children: [
if (entry.depth > 0) ...[
Icon(
Icons.subdirectory_arrow_right,
size: 14,
color: colors.onSurfaceVariant,
),
const SizedBox(width: 4),
],
Icon(
entry.label.icon,
size: 18,
color: entry.label.color,
),
const SizedBox(width: 10),
Expanded(
child: Text(
entry.label.name,
style: theme.textTheme.bodyMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
), ),
), ),
ActionChip( SizedBox(
avatar: const Icon(Icons.add, size: 16), height: 32,
label: const Text('New label'), width: 32,
onPressed: _createLabel, child: Checkbox(
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
value: selectedIds.contains(entry.label.id),
onChanged: _busy
? null
: (_) => _toggleLabel(entry.label.id),
),
), ),
], ],
), ),
),
),
],
],
),
),
),
const SizedBox(height: 24), const SizedBox(height: 24),
Text('Notes', style: theme.textTheme.titleSmall), Text('Notes', style: theme.textTheme.titleSmall),
const SizedBox(height: 8), const SizedBox(height: 8),
@@ -251,6 +457,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
controller: _notesController, controller: _notesController,
minLines: 3, minLines: 3,
maxLines: 6, maxLines: 6,
enabled: !_busy,
textInputAction: TextInputAction.newline, textInputAction: TextInputAction.newline,
decoration: const InputDecoration( decoration: const InputDecoration(
hintText: 'Add a private note…', hintText: 'Add a private note…',
@@ -261,7 +468,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
FilledButton( FilledButton(
onPressed: _dirty ? _saveNotes : null, onPressed: _dirty && !_busy ? _saveNotes : null,
child: Text( child: Text(
_applyToSimilar && similarCount > 1 _applyToSimilar && similarCount > 1
? 'Save notes for $similarCount' ? 'Save notes for $similarCount'
@@ -270,65 +477,16 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'Tap labels to add or remove several. Long-press a custom label ' 'Sub-labels also select their parents. Unchecking a parent '
'to delete it. Similar matches strip dates and ids so supermarket ' 'clears its sub-labels. Long-press a row to move or delete.',
'purchases group together.',
style: theme.textTheme.labelMedium, style: theme.textTheme.labelMedium,
), ),
], ],
), ),
), ),
);
}
}
class _NewLabelDialog extends StatefulWidget {
const _NewLabelDialog();
@override
State<_NewLabelDialog> createState() => _NewLabelDialogState();
}
class _NewLabelDialogState extends State<_NewLabelDialog> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _submit() {
Navigator.pop(context, _controller.text.trim());
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('New label'),
content: TextField(
controller: _controller,
autofocus: true,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(hintText: 'e.g. Supermarket'),
onSubmitted: (_) => _submit(),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _submit,
child: const Text('Create'),
),
], ],
),
),
); );
} }
} }
+400 -160
View File
@@ -1,6 +1,8 @@
/// Searchable transaction list with month heatmap and money in/out totals. /// Searchable transaction list with month heatmap and money in/out totals.
library; library;
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -13,28 +15,53 @@ import '../utils/helpers.dart';
import '../utils/navigation.dart'; import '../utils/navigation.dart';
import '../utils/tx_calendar.dart'; import '../utils/tx_calendar.dart';
import '../widgets/empty_state.dart'; import '../widgets/empty_state.dart';
import '../widgets/label_filter_dialog.dart';
import '../widgets/loading_view.dart'; import '../widgets/loading_view.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
import '../widgets/skip_build_when_covered.dart';
import '../widgets/tx_heatmap.dart'; import '../widgets/tx_heatmap.dart';
import 'transaction_detail_screen.dart'; import 'transaction_detail_screen.dart';
class TransactionsScreen extends StatefulWidget { class TransactionsScreen extends StatefulWidget {
const TransactionsScreen({super.key, this.initialMonth}); const TransactionsScreen({
super.key,
this.initialMonth,
this.initialLabelIds = const {},
this.initialSearchInMonthOnly,
this.initialYear,
});
/// When set, opens on this calendar month instead of the current month. /// When set, opens on this calendar month instead of the current month.
final DateTime? initialMonth; final DateTime? initialMonth;
/// Pre-select these label filters (e.g. from overview history).
final Set<String> initialLabelIds;
/// When set, overrides the default "search in month" checkbox.
final bool? initialSearchInMonthOnly;
/// When set, label/search results are limited to this calendar year.
final int? initialYear;
@override @override
State<TransactionsScreen> createState() => _TransactionsScreenState(); State<TransactionsScreen> createState() => _TransactionsScreenState();
} }
class _TransactionsScreenState extends State<TransactionsScreen> { class _TransactionsScreenState extends State<TransactionsScreen> {
static const _minLiveSearchChars = 3;
static const _searchDebounce = Duration(milliseconds: 280);
final _searchController = TextEditingController(); final _searchController = TextEditingController();
String _query = '';
late DateTime _month; late DateTime _month;
DateTime? _selectedDay; DateTime? _selectedDay;
var _searchInMonthOnly = false; late bool _searchInMonthOnly;
final Set<String> _labelFilters = {}; late final Set<String> _labelFilters;
int? _yearFilter;
var _showCalendar = false;
/// Query actually used for filtering (Enter, or live once ≥3 chars).
String _activeQuery = '';
Timer? _searchDebounceTimer;
@override @override
void initState() { void initState() {
@@ -47,16 +74,20 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
final start = monthStart(initial); final start = monthStart(initial);
_month = start.isAfter(now) ? now : start; _month = start.isAfter(now) ? now : start;
} }
_labelFilters = Set<String>.of(widget.initialLabelIds);
_searchInMonthOnly = widget.initialSearchInMonthOnly ?? false;
_yearFilter = widget.initialYear;
} }
@override @override
void dispose() { void dispose() {
_searchDebounceTimer?.cancel();
_searchController.dispose(); _searchController.dispose();
super.dispose(); super.dispose();
} }
bool get _isSearching => bool get _isSearching =>
_query.trim().isNotEmpty || _labelFilters.isNotEmpty; _activeQuery.trim().isNotEmpty || _labelFilters.isNotEmpty;
void _goMonth(int delta) { void _goMonth(int delta) {
final next = addMonths(_month, delta); final next = addMonths(_month, delta);
@@ -70,17 +101,44 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
DateTime? _txDate(BankTransaction tx) => DateTime.tryParse(tx.date); DateTime? _txDate(BankTransaction tx) => DateTime.tryParse(tx.date);
bool _inCalendarScope(BankTransaction tx) { List<BankTransaction> _yearScoped(List<BankTransaction> all) {
final date = _txDate(tx); final year = _yearFilter;
if (date == null) return false; if (year == null) return all;
if (_selectedDay != null) return isSameDay(date, _selectedDay!); return [
return isSameMonth(date, _month); for (final tx in all)
if (_txDate(tx)?.year == year) tx,
];
} }
bool _inMonth(BankTransaction tx) { void _onSearchChanged(String value) {
final date = _txDate(tx); final trimmed = value.trim();
if (date == null) return false; _searchDebounceTimer?.cancel();
return isSameMonth(date, _month);
if (trimmed.length >= _minLiveSearchChars) {
// TextField updates via the controller; only rebuild the list after debounce.
_searchDebounceTimer = Timer(_searchDebounce, () {
if (!mounted) return;
if (_activeQuery == trimmed) return;
setState(() => _activeQuery = trimmed);
});
return;
}
// Below threshold: no live search. Clear active text filter if needed.
if (_activeQuery.isNotEmpty) {
setState(() => _activeQuery = '');
}
}
void _onSearchSubmitted(String value) {
_searchDebounceTimer?.cancel();
setState(() => _activeQuery = value.trim());
}
void _clearSearch() {
_searchDebounceTimer?.cancel();
_searchController.clear();
setState(() => _activeQuery = '');
} }
Future<void> _pickLabels(List<TxLabel> available) async { Future<void> _pickLabels(List<TxLabel> available) async {
@@ -91,70 +149,21 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
return; return;
} }
final selected = Set<String>.of(_labelFilters); final result = await showLabelFilterDialog(
await showModalBottomSheet<void>( context,
context: context, available: available,
showDragHandle: true, initiallySelected: Set<String>.of(_labelFilters),
builder: (sheetContext) { title: 'Filter transactions',
return StatefulBuilder( subtitle: 'Show transactions with any of these labels.',
builder: (context, setSheetState) { includeUncategorized: true,
return SafeArea( );
child: Padding( if (result == null || !mounted) return;
padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'Filter by label',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final label in available)
FilterChip(
avatar: Icon(
label.icon,
size: 16,
color: label.color,
),
label: Text(label.name),
selected: selected.contains(label.id),
onSelected: (value) {
setSheetState(() {
if (value) {
selected.add(label.id);
} else {
selected.remove(label.id);
}
});
},
),
],
),
const SizedBox(height: 16),
FilledButton(
onPressed: () {
setState(() { setState(() {
_labelFilters _labelFilters
..clear() ..clear()
..addAll(selected); ..addAll(result);
}); });
Navigator.pop(sheetContext);
},
child: const Text('Apply'),
),
],
),
),
);
},
);
},
);
} }
@override @override
@@ -170,12 +179,22 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
refreshing: bank.isLoading, refreshing: bank.isLoading,
), ),
), ),
body: RefreshIndicator( body: Column(
children: [
if (bank.isLoading && bank.transactions.isNotEmpty)
const LinearProgressIndicator(minHeight: 2),
Expanded(
child: RefreshIndicator(
onRefresh: bank.refresh, onRefresh: bank.refresh,
child: ResponsiveBody( child: ResponsiveBody(
child: _buildBody(context, bank), child: SkipBuildWhenCovered(
builder: (context) => _buildBody(context, bank),
), ),
), ),
),
),
],
),
); );
} }
@@ -183,12 +202,13 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
final metaController = context.watch<TxMetaController>(); final metaController = context.watch<TxMetaController>();
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
final txs = bank.transactions;
if (bank.isLoading && bank.transactions.isEmpty) { if (bank.isLoading && txs.isEmpty) {
return const LoadingView(message: 'Loading transactions…'); return const LoadingView(message: 'Loading transactions…');
} }
if (!bank.isLinked && bank.transactions.isEmpty) { if (!bank.isLinked && txs.isEmpty) {
return ListView( return ListView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
children: [ children: [
@@ -204,7 +224,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
); );
} }
if (bank.error != null && bank.transactions.isEmpty) { if (bank.error != null && txs.isEmpty) {
return ListView( return ListView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
children: [ children: [
@@ -219,7 +239,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
); );
} }
if (bank.transactions.isEmpty) { if (txs.isEmpty) {
return ListView( return ListView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
children: const [ children: const [
@@ -233,33 +253,55 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
} }
final nowMonth = monthStart(DateTime.now()); final nowMonth = monthStart(DateTime.now());
final monthDates = <DateTime>[ final monthDates = <DateTime>[];
for (final tx in bank.transactions) final calendarScoped = <BankTransaction>[];
if (_txDate(tx) != null && isSameMonth(_txDate(tx)!, _month)) final monthScoped = <BankTransaction>[];
dateOnly(_txDate(tx)!),
];
final counts = txCountsByDay(monthDates);
final calendarScoped = [ for (final tx in txs) {
for (final tx in bank.transactions) final date = _txDate(tx);
if (_inCalendarScope(tx)) tx, if (date == null) continue;
]; if (isSameMonth(date, _month)) {
monthDates.add(dateOnly(date));
monthScoped.add(tx);
if (_selectedDay == null || isSameDay(date, _selectedDay!)) {
calendarScoped.add(tx);
}
} else if (_selectedDay != null && isSameDay(date, _selectedDay!)) {
calendarScoped.add(tx);
}
}
final counts = txCountsByDay(monthDates);
final searchPool = !_isSearching final searchPool = !_isSearching
? calendarScoped ? calendarScoped
: _searchInMonthOnly : _searchInMonthOnly
? [ ? monthScoped
for (final tx in bank.transactions) : _yearScoped(txs);
if (_inMonth(tx)) tx,
] // Text hits first (no label filter) so refine chips stay available while selecting.
: bank.transactions; final textMatched = _activeQuery.trim().isEmpty
? const <BankTransaction>[]
: metaController.search(searchPool, _activeQuery);
final filtered = metaController.search( final filtered = metaController.search(
searchPool, searchPool,
_query, _activeQuery,
labelIds: _labelFilters, labelIds: _labelFilters,
); );
final refineLabels = _activeQuery.trim().isEmpty
? const <TxLabel>[]
: metaController.usedLabels(textMatched);
final showUncategorizedRefine = _activeQuery.trim().isNotEmpty &&
textMatched.any((tx) => !metaController.metaFor(tx).hasLabel);
final refineChoices = <TxLabel>[
if (showUncategorizedRefine &&
!_labelFilters.contains(kUncategorizedFilterId))
kUncategorizedFilterLabel,
for (final label in refineLabels)
if (!_labelFilters.contains(label.id)) label,
];
var moneyOut = 0.0; var moneyOut = 0.0;
var moneyIn = 0.0; var moneyIn = 0.0;
for (final tx in calendarScoped) { for (final tx in calendarScoped) {
@@ -270,51 +312,125 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
} }
} }
final currency = bank.balance?.currency ?? final currency = bank.balance?.currency ??
(bank.transactions.isNotEmpty (txs.isNotEmpty ? txs.first.currency : 'EUR');
? bank.transactions.first.currency
: 'EUR');
final usedLabels = metaController.usedLabels(bank.transactions);
final labelById = { final labelById = {
for (final label in metaController.allLabels) label.id: label, for (final label in metaController.allLabels) label.id: label,
}; };
return ListView( return CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.only(bottom: 32), slivers: [
children: [ if (bank.error != null && txs.isNotEmpty)
Padding( SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Material(
color: colors.errorContainer,
borderRadius: BorderRadius.circular(10),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 8,
),
child: Text(
bank.error!,
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onErrorContainer,
),
),
),
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4), padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Expanded( Expanded(
child: TextField( child: ValueListenableBuilder<TextEditingValue>(
valueListenable: _searchController,
builder: (context, value, _) {
final draft = value.text.trim();
final showHint = draft.isNotEmpty &&
draft.length < _minLiveSearchChars &&
draft != _activeQuery.trim();
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _searchController, controller: _searchController,
textInputAction: TextInputAction.search, textInputAction: TextInputAction.search,
decoration: InputDecoration( decoration: InputDecoration(
hintText: 'Search description, notes…', hintText:
prefixIcon: IconButton( 'Search (3+ chars, or press search)',
tooltip: 'Labels', prefixIcon: const Icon(Icons.search),
onPressed: () => _pickLabels(usedLabels), suffixIcon: value.text.isNotEmpty
icon: Icon( ? IconButton(
Icons.search,
color: _labelFilters.isEmpty ? null : colors.primary,
),
),
suffixIcon: _query.isEmpty
? null
: IconButton(
tooltip: 'Clear', tooltip: 'Clear',
onPressed: () { onPressed: _clearSearch,
_searchController.clear();
setState(() => _query = '');
},
icon: const Icon(Icons.clear), icon: const Icon(Icons.clear),
)
: null,
),
onChanged: _onSearchChanged,
onSubmitted: _onSearchSubmitted,
),
if (showHint)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
'Press search to look up short terms',
style:
theme.textTheme.labelMedium?.copyWith(
color: colors.onSurfaceVariant,
), ),
), ),
onChanged: (value) => setState(() => _query = value), ),
],
);
},
),
),
const SizedBox(width: 2),
IconButton(
tooltip: _labelFilters.isEmpty
? 'Filter by label'
: 'Filter by label (${_labelFilters.length})',
onPressed: () => _pickLabels(
metaController.usedLabels(txs),
),
style: IconButton.styleFrom(
backgroundColor: _labelFilters.isEmpty
? null
: colors.secondaryContainer,
),
icon: Badge(
isLabelVisible: _labelFilters.isNotEmpty,
smallSize: 6,
child: const Icon(Icons.filter_list),
),
),
IconButton(
tooltip: _showCalendar ? 'Hide calendar' : 'Show calendar',
onPressed: () {
setState(() {
_showCalendar = !_showCalendar;
if (!_showCalendar) _selectedDay = null;
});
},
style: IconButton.styleFrom(
backgroundColor: _showCalendar
? colors.secondaryContainer
: null,
),
icon: Icon(
_showCalendar
? Icons.calendar_month
: Icons.calendar_month_outlined,
), ),
), ),
const SizedBox(width: 4),
Tooltip( Tooltip(
message: 'Search only in calendar month', message: 'Search only in calendar month',
child: Row( child: Row(
@@ -323,7 +439,9 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
Checkbox( Checkbox(
value: _searchInMonthOnly, value: _searchInMonthOnly,
onChanged: (value) { onChanged: (value) {
setState(() => _searchInMonthOnly = value ?? false); setState(
() => _searchInMonthOnly = value ?? false,
);
}, },
), ),
Text('Month', style: theme.textTheme.labelMedium), Text('Month', style: theme.textTheme.labelMedium),
@@ -333,30 +451,10 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
], ],
), ),
), ),
if (_labelFilters.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final id in _labelFilters)
if (labelById[id] != null)
InputChip(
avatar: Icon(
labelById[id]!.icon,
size: 16,
color: labelById[id]!.color,
), ),
label: Text(labelById[id]!.name), if (_showCalendar) ...[
onDeleted: () { SliverToBoxAdapter(
setState(() => _labelFilters.remove(id)); child: TxHeatmap(
},
),
],
),
),
TxHeatmap(
month: _month, month: _month,
counts: counts, counts: counts,
canGoForward: _month.isBefore(nowMonth), canGoForward: _month.isBefore(nowMonth),
@@ -365,8 +463,10 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
onNextMonth: () => _goMonth(1), onNextMonth: () => _goMonth(1),
onSelectDay: (day) => setState(() => _selectedDay = day), onSelectDay: (day) => setState(() => _selectedDay = day),
), ),
),
if (_selectedDay != null) if (_selectedDay != null)
Padding( SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 8), padding: const EdgeInsets.only(bottom: 8),
child: Align( child: Align(
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
@@ -376,7 +476,37 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
), ),
), ),
), ),
Padding( ),
] else
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 8),
child: Row(
children: [
IconButton(
tooltip: 'Previous month',
onPressed: () => _goMonth(-1),
icon: const Icon(Icons.chevron_left),
),
Expanded(
child: Text(
formatMonthYear(_month),
textAlign: TextAlign.center,
style: theme.textTheme.titleMedium,
),
),
IconButton(
tooltip: 'Next month',
onPressed:
_month.isBefore(nowMonth) ? () => _goMonth(1) : null,
icon: const Icon(Icons.chevron_right),
),
],
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 12), padding: const EdgeInsets.fromLTRB(0, 4, 0, 12),
child: Row( child: Row(
children: [ children: [
@@ -400,18 +530,114 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
], ],
), ),
), ),
if (_isSearching) ),
Padding( if (_isSearching || _labelFilters.isNotEmpty)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 8), padding: const EdgeInsets.only(bottom: 8),
child: Text( child: Column(
_searchInMonthOnly crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (_isSearching)
Text(
_yearFilter != null
? 'Filtered to $_yearFilter'
: _searchInMonthOnly
? 'Searching in ${formatMonthYear(_month)}' ? 'Searching in ${formatMonthYear(_month)}'
: 'Searching all transactions', : 'Searching all transactions',
style: theme.textTheme.labelMedium, style: theme.textTheme.labelMedium,
), ),
if (_labelFilters.isNotEmpty) ...[
if (_isSearching) const SizedBox(height: 8),
Wrap(
spacing: 6,
runSpacing: 6,
children: [
for (final id in _labelFilters)
if (id == kUncategorizedFilterId)
InputChip(
visualDensity: VisualDensity.compact,
avatar: Icon(
kUncategorizedFilterLabel.icon,
size: 14,
color: kUncategorizedFilterLabel.color,
),
label: const Text('Uncategorized'),
onDeleted: () {
setState(
() => _labelFilters
.remove(kUncategorizedFilterId),
);
},
)
else if (labelById[id] != null)
InputChip(
visualDensity: VisualDensity.compact,
avatar: Icon(
labelById[id]!.icon,
size: 14,
color: labelById[id]!.color,
),
label: Text(labelById[id]!.name),
onDeleted: () {
setState(() => _labelFilters.remove(id));
},
),
],
),
],
if (refineChoices.isNotEmpty) ...[
const SizedBox(height: 8),
Text(
'Refine by label',
style: theme.textTheme.labelSmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
const SizedBox(height: 6),
Wrap(
spacing: 6,
runSpacing: 6,
children: [
for (final label in refineChoices)
FilterChip(
visualDensity: VisualDensity.compact,
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
avatar: Icon(
label.icon,
size: 14,
color: label.color,
),
label: Text(label.name),
selected: false,
onSelected: (_) {
setState(() => _labelFilters.add(label.id));
},
),
],
),
],
],
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
filtered.length == 1
? '1 transaction'
: '${filtered.length} transactions',
style: theme.textTheme.titleSmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
),
), ),
if (filtered.isEmpty) if (filtered.isEmpty)
Padding( SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 24), padding: const EdgeInsets.symmetric(vertical: 24),
child: Text( child: Text(
_isSearching _isSearching
@@ -422,21 +648,35 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
), ),
),
) )
else else
for (var i = 0; i < filtered.length; i++) ...[ SliverList(
if (i > 0) delegate: SliverChildBuilderDelegate(
(context, index) {
final tx = filtered[index];
final meta = metaController.metaFor(tx);
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (index > 0)
Divider( Divider(
height: 1, height: 1,
color: colors.outlineVariant.withValues(alpha: 0.5), color: colors.outlineVariant.withValues(alpha: 0.5),
), ),
_CompactTransactionTile( _CompactTransactionTile(
tx: filtered[i], tx: tx,
meta: metaController.metaFor(filtered[i]), meta: meta,
labels: metaController labels: metaController.leafLabelsFor(meta),
.labelsFor(metaController.metaFor(filtered[i])),
), ),
], ],
);
},
childCount: filtered.length,
addAutomaticKeepAlives: false,
),
),
const SliverToBoxAdapter(child: SizedBox(height: 32)),
], ],
); );
} }
+28
View File
@@ -17,6 +17,7 @@ class TxMetaStoreData {
this.notesByMerchant = const {}, this.notesByMerchant = const {},
this.exactTemplates = const {}, this.exactTemplates = const {},
this.customLabels = const [], this.customLabels = const [],
this.labelParents = const {},
}); });
final Map<String, TxMeta> byId; final Map<String, TxMeta> byId;
@@ -24,6 +25,9 @@ class TxMetaStoreData {
final Map<String, String> notesByMerchant; final Map<String, String> notesByMerchant;
final Map<String, TxExactTemplate> exactTemplates; final Map<String, TxExactTemplate> exactTemplates;
final List<TxLabel> customLabels; final List<TxLabel> customLabels;
/// childLabelId → parentLabelId (roots omitted).
final Map<String, String> labelParents;
} }
/// Cached bank payload so the app stays usable across restarts / brief outages. /// Cached bank payload so the app stays usable across restarts / brief outages.
@@ -236,6 +240,7 @@ class StorageService {
'customLabels': [ 'customLabels': [
for (final label in store.customLabels) label.toJson(), for (final label in store.customLabels) label.toJson(),
], ],
'labelParents': store.labelParents,
}; };
return _prefs.setString(StorageKeys.txMeta, jsonEncode(encoded)); return _prefs.setString(StorageKeys.txMeta, jsonEncode(encoded));
} }
@@ -323,12 +328,35 @@ class StorageService {
} }
} }
final labelParents = <String, String>{};
final parentsRaw = root['labelParents'];
if (parentsRaw is Map) {
parentsRaw.forEach((key, value) {
if (key is String &&
value is String &&
key.isNotEmpty &&
value.isNotEmpty) {
labelParents[key] = value;
}
});
}
// Prefer explicit map; fall back to parentId embedded on custom labels.
for (final label in customLabels) {
final parent = label.parentId;
if (parent != null &&
parent.isNotEmpty &&
!labelParents.containsKey(label.id)) {
labelParents[label.id] = parent;
}
}
return TxMetaStoreData( return TxMetaStoreData(
byId: byId, byId: byId,
labelsByMerchant: labelsByMerchant, labelsByMerchant: labelsByMerchant,
notesByMerchant: notesByMerchant, notesByMerchant: notesByMerchant,
exactTemplates: exactTemplates, exactTemplates: exactTemplates,
customLabels: customLabels, customLabels: customLabels,
labelParents: labelParents,
); );
} catch (_) { } catch (_) {
return const TxMetaStoreData(); return const TxMetaStoreData();
+283
View File
@@ -0,0 +1,283 @@
/// Compact indented label multi-select for list/chart filters.
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/transaction_meta.dart';
import '../providers/tx_meta_provider.dart';
import 'label_parent_picker.dart';
/// Returns the selected label ids, or `null` if cancelled.
///
/// When [includeUncategorized] is true, [kUncategorizedFilterId] may be
/// selected. Long-press still opens move-parent when [allowMove] is true.
Future<Set<String>?> showLabelFilterDialog(
BuildContext context, {
required List<TxLabel> available,
required Set<String> initiallySelected,
String title = 'Filter by label',
String subtitle = 'Choose which labels to include.',
bool includeUncategorized = false,
bool allowMove = false,
}) {
return showDialog<Set<String>>(
context: context,
builder: (dialogContext) {
return _LabelFilterDialog(
available: available,
initiallySelected: initiallySelected,
title: title,
subtitle: subtitle,
includeUncategorized: includeUncategorized,
allowMove: allowMove,
);
},
);
}
class _LabelFilterDialog extends StatefulWidget {
const _LabelFilterDialog({
required this.available,
required this.initiallySelected,
required this.title,
required this.subtitle,
required this.includeUncategorized,
required this.allowMove,
});
final List<TxLabel> available;
final Set<String> initiallySelected;
final String title;
final String subtitle;
final bool includeUncategorized;
final bool allowMove;
@override
State<_LabelFilterDialog> createState() => _LabelFilterDialogState();
}
class _LabelFilterDialogState extends State<_LabelFilterDialog> {
late final Set<String> _selected;
@override
void initState() {
super.initState();
_selected = Set<String>.of(widget.initiallySelected);
}
void _toggle(String id, bool selected) {
setState(() {
if (selected) {
_selected.add(id);
} else {
_selected.remove(id);
}
});
}
void _selectAll() {
setState(() {
_selected
..clear()
..addAll(widget.available.map((l) => l.id));
if (widget.includeUncategorized) {
_selected.add(kUncategorizedFilterId);
}
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final meta = context.watch<TxMetaController>();
final entries = meta.treeOrderFor(widget.available);
final maxListHeight = MediaQuery.sizeOf(context).height * 0.45;
final uncategorizedChecked =
_selected.contains(kUncategorizedFilterId);
return AlertDialog(
title: Text(widget.title),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(widget.subtitle, style: theme.textTheme.bodyMedium),
const SizedBox(height: 10),
ConstrainedBox(
constraints: BoxConstraints(maxHeight: maxListHeight),
child: DecoratedBox(
decoration: BoxDecoration(
color: colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: colors.outlineVariant.withValues(alpha: 0.8),
),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: ListView.separated(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 4),
itemCount: entries.length +
(widget.includeUncategorized ? 1 : 0),
separatorBuilder: (_, _) => Divider(
height: 1,
thickness: 1,
indent: 40,
color:
colors.outlineVariant.withValues(alpha: 0.45),
),
itemBuilder: (context, index) {
if (widget.includeUncategorized && index == 0) {
return _FilterRow(
depth: 0,
icon: kUncategorizedFilterLabel.icon,
color: kUncategorizedFilterLabel.color,
name: kUncategorizedFilterLabel.name,
checked: uncategorizedChecked,
onToggle: (value) =>
_toggle(kUncategorizedFilterId, value),
);
}
final entry = entries[
widget.includeUncategorized ? index - 1 : index];
final label = entry.label;
final checked = _selected.contains(label.id);
return _FilterRow(
depth: entry.depth,
icon: label.icon,
color: label.color,
name: label.name,
checked: checked,
onToggle: (value) => _toggle(label.id, value),
onLongPress: widget.allowMove
? () async {
await showMoveLabelDialog(
context,
label: label,
);
if (mounted) setState(() {});
}
: null,
);
},
),
),
),
),
],
),
),
actionsPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
actions: [
SizedBox(
width: double.maxFinite,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: TextButton(
onPressed: _selectAll,
child: const Text('All'),
),
),
Expanded(
child: TextButton(
onPressed: () {
setState(() => _selected.clear());
},
child: const Text('None'),
),
),
Expanded(
child: TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
],
),
const SizedBox(height: 4),
FilledButton(
onPressed: () =>
Navigator.pop(context, Set<String>.of(_selected)),
child: const Text('Apply'),
),
],
),
),
],
);
}
}
class _FilterRow extends StatelessWidget {
const _FilterRow({
required this.depth,
required this.icon,
required this.color,
required this.name,
required this.checked,
required this.onToggle,
this.onLongPress,
});
final int depth;
final IconData icon;
final Color color;
final String name;
final bool checked;
final ValueChanged<bool> onToggle;
final VoidCallback? onLongPress;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
return InkWell(
onTap: () => onToggle(!checked),
onLongPress: onLongPress,
child: Padding(
padding: EdgeInsets.fromLTRB(8 + depth * 16.0, 2, 4, 2),
child: Row(
children: [
if (depth > 0) ...[
Icon(
Icons.subdirectory_arrow_right,
size: 14,
color: colors.onSurfaceVariant,
),
const SizedBox(width: 4),
],
Icon(icon, size: 18, color: color),
const SizedBox(width: 10),
Expanded(
child: Text(
name,
style: theme.textTheme.bodyMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
SizedBox(
height: 32,
width: 32,
child: Checkbox(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
value: checked,
onChanged: (value) => onToggle(value ?? false),
),
),
],
),
),
);
}
}
+207
View File
@@ -0,0 +1,207 @@
/// Dialogs to nest or create labels.
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/transaction_meta.dart';
import '../providers/tx_meta_provider.dart';
Future<void> showMoveLabelDialog(
BuildContext context, {
required TxLabel label,
}) async {
final meta = context.read<TxMetaController>();
final parents = meta.validParentsFor(label.id);
final currentParent = meta.parentIdOf(label.id);
final chosen = await showDialog<String?>(
context: context,
builder: (dialogContext) {
final theme = Theme.of(dialogContext);
final maxHeight = MediaQuery.sizeOf(dialogContext).height * 0.45;
return AlertDialog(
title: Text('Move “${label.name}”'),
titleTextStyle: theme.textTheme.titleMedium?.copyWith(
color: theme.colorScheme.onSurface,
),
contentPadding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
content: SizedBox(
width: double.maxFinite,
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: maxHeight),
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.zero,
children: [
ListTile(
dense: true,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -3,
),
contentPadding: const EdgeInsets.symmetric(horizontal: 4),
minLeadingWidth: 28,
leading: Icon(
currentParent == null
? Icons.check_circle
: Icons.circle_outlined,
size: 18,
),
title: Text(
'Top level',
style: theme.textTheme.bodyMedium,
),
onTap: () => Navigator.pop(dialogContext, ''),
),
Divider(
height: 1,
color: theme.colorScheme.outlineVariant.withValues(
alpha: 0.5,
),
),
for (final parent in parents)
ListTile(
dense: true,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -3,
),
contentPadding: const EdgeInsets.symmetric(horizontal: 4),
minLeadingWidth: 28,
leading: Icon(
parent.id == currentParent
? Icons.check_circle
: parent.icon,
size: 18,
color: parent.color,
),
title: Text(
parent.name,
style: theme.textTheme.bodyMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
onTap: () => Navigator.pop(dialogContext, parent.id),
),
],
),
),
),
actionsPadding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('Cancel'),
),
],
);
},
);
if (chosen == null || !context.mounted) return;
await meta.setLabelParent(label.id, chosen.isEmpty ? null : chosen);
}
/// Returns name + optional parent, or null if cancelled.
Future<({String name, String? parentId})?> showCreateLabelDialog(
BuildContext context, {
required List<TxLabel> parents,
String? initialParentId,
}) {
return showDialog<({String name, String? parentId})>(
context: context,
builder: (context) => _CreateLabelDialog(
parents: parents,
initialParentId: initialParentId,
),
);
}
class _CreateLabelDialog extends StatefulWidget {
const _CreateLabelDialog({
required this.parents,
this.initialParentId,
});
final List<TxLabel> parents;
final String? initialParentId;
@override
State<_CreateLabelDialog> createState() => _CreateLabelDialogState();
}
class _CreateLabelDialogState extends State<_CreateLabelDialog> {
late final TextEditingController _controller;
String? _parentId;
@override
void initState() {
super.initState();
_controller = TextEditingController();
_parentId = widget.initialParentId;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _submit() {
final name = _controller.text.trim();
if (name.isEmpty) return;
Navigator.pop(context, (name: name, parentId: _parentId));
}
@override
Widget build(BuildContext context) {
final parentChoices = List<TxLabel>.of(widget.parents)
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
return AlertDialog(
title: const Text('New label'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _controller,
autofocus: true,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(hintText: 'e.g. Supermarket'),
onSubmitted: (_) => _submit(),
),
const SizedBox(height: 12),
DropdownButtonFormField<String?>(
initialValue: _parentId,
decoration: const InputDecoration(
labelText: 'Under label (optional)',
),
items: [
const DropdownMenuItem<String?>(
value: null,
child: Text('Top level'),
),
for (final parent in parentChoices)
DropdownMenuItem<String?>(
value: parent.id,
child: Text(parent.name),
),
],
onChanged: (value) => setState(() => _parentId = value),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _submit,
child: const Text('Create'),
),
],
);
}
}
+59
View File
@@ -0,0 +1,59 @@
/// Skips building while another route covers this one, then rebuilds on pop.
library;
import 'package:flutter/material.dart';
/// Shared observer — register on [MaterialApp.navigatorObservers].
final RouteObserver<ModalRoute<void>> appRouteObserver =
RouteObserver<ModalRoute<void>>();
/// Builds via [builder] only when this route is not covered by a pushed page.
class SkipBuildWhenCovered extends StatefulWidget {
const SkipBuildWhenCovered({
super.key,
required this.builder,
this.placeholder = const SizedBox.expand(),
});
final WidgetBuilder builder;
final Widget placeholder;
@override
State<SkipBuildWhenCovered> createState() => _SkipBuildWhenCoveredState();
}
class _SkipBuildWhenCoveredState extends State<SkipBuildWhenCovered>
with RouteAware {
var _covered = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final route = ModalRoute.of(context);
if (route is PageRoute) {
appRouteObserver.subscribe(this, route);
}
}
@override
void dispose() {
appRouteObserver.unsubscribe(this);
super.dispose();
}
@override
void didPushNext() {
if (!_covered) setState(() => _covered = true);
}
@override
void didPopNext() {
if (_covered) setState(() => _covered = false);
}
@override
Widget build(BuildContext context) {
if (_covered) return widget.placeholder;
return widget.builder(context);
}
}
+51 -1
View File
@@ -1,3 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:myapp/main.dart'; import 'package:myapp/main.dart';
import 'package:myapp/models/bank.dart'; import 'package:myapp/models/bank.dart';
@@ -51,13 +52,62 @@ void main() {
'pending': false, 'pending': false,
}); });
expect(tx.descriptionKey, contains('pasvolgnr')); expect(tx.descriptionKey, contains('pasvolgnr'));
expect(tx.merchantKey, contains('ah campus diemen')); expect(tx.merchantKey, 'ah campus');
expect(tx.merchantKey.contains('pasvolgnr'), isFalse); expect(tx.merchantKey.contains('pasvolgnr'), isFalse);
expect(tx.exactKey, contains('-3.5')); expect(tx.exactKey, contains('-3.5'));
expect(formatMoney(tx.amount, tx.currency), contains('EUR')); expect(formatMoney(tx.amount, tx.currency), contains('EUR'));
expect(kBuiltinLabels.first.name, 'Groceries'); expect(kBuiltinLabels.first.name, 'Groceries');
}); });
test('merchant stems group Albert Heijn / AH across stores', () {
final a = merchantKeyFromDescription('Albert Heijn 1562 Utrecht NLD');
final b = merchantKeyFromDescription('ALBERT HEIJN 1847 AMSTERDAM');
final c = merchantKeyFromDescription(
'BCK*AH CAMPUS DIEMEN ZUID NLD Pasvolgnr: 001 Transactie: X',
);
final d = merchantKeyFromDescription('AH CAMPUS AMSTERDAM NLD');
expect(a, 'albert heijn');
expect(b, 'albert heijn');
expect(c, 'ah campus');
expect(d, 'ah campus');
expect(descriptionMatchesPattern('Albert Heijn 1562 Utrecht', a), isTrue);
expect(
descriptionMatchesPattern('Jumbo City Centrum', a),
isFalse,
);
expect(
descriptionMatchesPattern('AH CAMPUS DIEMEN', '/ah campus/'),
isTrue,
);
});
test('flattenLabelTree indents children under parents', () {
const parent = TxLabel(
id: 'groceries',
name: 'Groceries',
color: Color(0xFF16A34A),
);
const child = TxLabel(
id: 'custom_ah',
name: 'Albert Heijn',
color: Color(0xFF0F766E),
custom: true,
parentId: 'groceries',
);
const other = TxLabel(
id: 'dining',
name: 'Dining',
color: Color(0xFFEA580C),
);
final tree = flattenLabelTree([child, other, parent]);
expect(tree.map((e) => e.label.id).toList(), [
'dining',
'groceries',
'custom_ah',
]);
expect(tree.map((e) => e.depth).toList(), [0, 0, 1]);
});
test('look-ahead applies monthly recurring amounts', () { test('look-ahead applies monthly recurring amounts', () {
final items = [ final items = [
const RecurringItem( const RecurringItem(