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
+477 -237
View File
@@ -1,6 +1,8 @@
/// Searchable transaction list with month heatmap and money in/out totals.
library;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
@@ -13,28 +15,53 @@ import '../utils/helpers.dart';
import '../utils/navigation.dart';
import '../utils/tx_calendar.dart';
import '../widgets/empty_state.dart';
import '../widgets/label_filter_dialog.dart';
import '../widgets/loading_view.dart';
import '../widgets/responsive_body.dart';
import '../widgets/skip_build_when_covered.dart';
import '../widgets/tx_heatmap.dart';
import 'transaction_detail_screen.dart';
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.
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
State<TransactionsScreen> createState() => _TransactionsScreenState();
}
class _TransactionsScreenState extends State<TransactionsScreen> {
static const _minLiveSearchChars = 3;
static const _searchDebounce = Duration(milliseconds: 280);
final _searchController = TextEditingController();
String _query = '';
late DateTime _month;
DateTime? _selectedDay;
var _searchInMonthOnly = false;
final Set<String> _labelFilters = {};
late bool _searchInMonthOnly;
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
void initState() {
@@ -47,16 +74,20 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
final start = monthStart(initial);
_month = start.isAfter(now) ? now : start;
}
_labelFilters = Set<String>.of(widget.initialLabelIds);
_searchInMonthOnly = widget.initialSearchInMonthOnly ?? false;
_yearFilter = widget.initialYear;
}
@override
void dispose() {
_searchDebounceTimer?.cancel();
_searchController.dispose();
super.dispose();
}
bool get _isSearching =>
_query.trim().isNotEmpty || _labelFilters.isNotEmpty;
_activeQuery.trim().isNotEmpty || _labelFilters.isNotEmpty;
void _goMonth(int delta) {
final next = addMonths(_month, delta);
@@ -70,17 +101,44 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
DateTime? _txDate(BankTransaction tx) => DateTime.tryParse(tx.date);
bool _inCalendarScope(BankTransaction tx) {
final date = _txDate(tx);
if (date == null) return false;
if (_selectedDay != null) return isSameDay(date, _selectedDay!);
return isSameMonth(date, _month);
List<BankTransaction> _yearScoped(List<BankTransaction> all) {
final year = _yearFilter;
if (year == null) return all;
return [
for (final tx in all)
if (_txDate(tx)?.year == year) tx,
];
}
bool _inMonth(BankTransaction tx) {
final date = _txDate(tx);
if (date == null) return false;
return isSameMonth(date, _month);
void _onSearchChanged(String value) {
final trimmed = value.trim();
_searchDebounceTimer?.cancel();
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 {
@@ -91,70 +149,21 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
return;
}
final selected = Set<String>.of(_labelFilters);
await showModalBottomSheet<void>(
context: context,
showDragHandle: true,
builder: (sheetContext) {
return StatefulBuilder(
builder: (context, setSheetState) {
return SafeArea(
child: Padding(
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(() {
_labelFilters
..clear()
..addAll(selected);
});
Navigator.pop(sheetContext);
},
child: const Text('Apply'),
),
],
),
),
);
},
);
},
final result = await showLabelFilterDialog(
context,
available: available,
initiallySelected: Set<String>.of(_labelFilters),
title: 'Filter transactions',
subtitle: 'Show transactions with any of these labels.',
includeUncategorized: true,
);
if (result == null || !mounted) return;
setState(() {
_labelFilters
..clear()
..addAll(result);
});
}
@override
@@ -170,11 +179,21 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
refreshing: bank.isLoading,
),
),
body: RefreshIndicator(
onRefresh: bank.refresh,
child: ResponsiveBody(
child: _buildBody(context, bank),
),
body: Column(
children: [
if (bank.isLoading && bank.transactions.isNotEmpty)
const LinearProgressIndicator(minHeight: 2),
Expanded(
child: RefreshIndicator(
onRefresh: bank.refresh,
child: ResponsiveBody(
child: SkipBuildWhenCovered(
builder: (context) => _buildBody(context, bank),
),
),
),
),
],
),
);
}
@@ -183,12 +202,13 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
final metaController = context.watch<TxMetaController>();
final theme = Theme.of(context);
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…');
}
if (!bank.isLinked && bank.transactions.isEmpty) {
if (!bank.isLinked && txs.isEmpty) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
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(
physics: const AlwaysScrollableScrollPhysics(),
children: [
@@ -219,7 +239,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
);
}
if (bank.transactions.isEmpty) {
if (txs.isEmpty) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const [
@@ -233,33 +253,55 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
}
final nowMonth = monthStart(DateTime.now());
final monthDates = <DateTime>[
for (final tx in bank.transactions)
if (_txDate(tx) != null && isSameMonth(_txDate(tx)!, _month))
dateOnly(_txDate(tx)!),
];
final counts = txCountsByDay(monthDates);
final monthDates = <DateTime>[];
final calendarScoped = <BankTransaction>[];
final monthScoped = <BankTransaction>[];
final calendarScoped = [
for (final tx in bank.transactions)
if (_inCalendarScope(tx)) tx,
];
for (final tx in txs) {
final date = _txDate(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
? calendarScoped
: _searchInMonthOnly
? [
for (final tx in bank.transactions)
if (_inMonth(tx)) tx,
]
: bank.transactions;
? monthScoped
: _yearScoped(txs);
// Text hits first (no label filter) so refine chips stay available while selecting.
final textMatched = _activeQuery.trim().isEmpty
? const <BankTransaction>[]
: metaController.search(searchPool, _activeQuery);
final filtered = metaController.search(
searchPool,
_query,
_activeQuery,
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 moneyIn = 0.0;
for (final tx in calendarScoped) {
@@ -270,173 +312,371 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
}
}
final currency = bank.balance?.currency ??
(bank.transactions.isNotEmpty
? bank.transactions.first.currency
: 'EUR');
final usedLabels = metaController.usedLabels(bank.transactions);
(txs.isNotEmpty ? txs.first.currency : 'EUR');
final labelById = {
for (final label in metaController.allLabels) label.id: label,
};
return ListView(
return CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.only(bottom: 32),
children: [
Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Row(
children: [
Expanded(
child: TextField(
controller: _searchController,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: 'Search description, notes…',
prefixIcon: IconButton(
tooltip: 'Labels',
onPressed: () => _pickLabels(usedLabels),
icon: Icon(
Icons.search,
color: _labelFilters.isEmpty ? null : colors.primary,
),
),
suffixIcon: _query.isEmpty
? null
: IconButton(
tooltip: 'Clear',
onPressed: () {
_searchController.clear();
setState(() => _query = '');
},
icon: const Icon(Icons.clear),
),
slivers: [
if (bank.error != null && txs.isNotEmpty)
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,
),
onChanged: (value) => setState(() => _query = value),
),
),
const SizedBox(width: 4),
Tooltip(
message: 'Search only in calendar month',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Checkbox(
value: _searchInMonthOnly,
onChanged: (value) {
setState(() => _searchInMonthOnly = value ?? false);
},
child: Text(
bank.error!,
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onErrorContainer,
),
Text('Month', style: theme.textTheme.labelMedium),
],
),
),
),
],
),
),
),
if (_labelFilters.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Wrap(
spacing: 8,
runSpacing: 8,
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final id in _labelFilters)
if (labelById[id] != null)
InputChip(
avatar: Icon(
labelById[id]!.icon,
size: 16,
color: labelById[id]!.color,
Expanded(
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,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText:
'Search (3+ chars, or press search)',
prefixIcon: const Icon(Icons.search),
suffixIcon: value.text.isNotEmpty
? IconButton(
tooltip: 'Clear',
onPressed: _clearSearch,
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,
),
),
),
],
);
},
),
),
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,
),
),
Tooltip(
message: 'Search only in calendar month',
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Checkbox(
value: _searchInMonthOnly,
onChanged: (value) {
setState(
() => _searchInMonthOnly = value ?? false,
);
},
),
label: Text(labelById[id]!.name),
onDeleted: () {
setState(() => _labelFilters.remove(id));
},
),
Text('Month', style: theme.textTheme.labelMedium),
],
),
),
],
),
),
TxHeatmap(
month: _month,
counts: counts,
canGoForward: _month.isBefore(nowMonth),
selectedDay: _selectedDay,
onPreviousMonth: () => _goMonth(-1),
onNextMonth: () => _goMonth(1),
onSelectDay: (day) => setState(() => _selectedDay = day),
),
if (_selectedDay != null)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Align(
alignment: Alignment.centerLeft,
child: InputChip(
label: Text(formatDate(_selectedDay!)),
onDeleted: () => setState(() => _selectedDay = null),
if (_showCalendar) ...[
SliverToBoxAdapter(
child: TxHeatmap(
month: _month,
counts: counts,
canGoForward: _month.isBefore(nowMonth),
selectedDay: _selectedDay,
onPreviousMonth: () => _goMonth(-1),
onNextMonth: () => _goMonth(1),
onSelectDay: (day) => setState(() => _selectedDay = day),
),
),
if (_selectedDay != null)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Align(
alignment: Alignment.centerLeft,
child: InputChip(
label: Text(formatDate(_selectedDay!)),
onDeleted: () => setState(() => _selectedDay = null),
),
),
),
),
] 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),
),
],
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 12),
child: Row(
children: [
Expanded(
child: _TotalsCard(
label: 'Money out',
value: formatMoney(moneyOut, currency),
color: colors.error,
icon: Icons.arrow_upward,
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 12),
child: Row(
children: [
Expanded(
child: _TotalsCard(
label: 'Money out',
value: formatMoney(moneyOut, currency),
color: colors.error,
icon: Icons.arrow_upward,
),
),
),
const SizedBox(width: 10),
Expanded(
child: _TotalsCard(
label: 'Money in',
value: formatMoney(moneyIn, currency),
color: colors.primary,
icon: Icons.arrow_downward,
const SizedBox(width: 10),
Expanded(
child: _TotalsCard(
label: 'Money in',
value: formatMoney(moneyIn, currency),
color: colors.primary,
icon: Icons.arrow_downward,
),
),
),
],
],
),
),
),
if (_isSearching)
Padding(
if (_isSearching || _labelFilters.isNotEmpty)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (_isSearching)
Text(
_yearFilter != null
? 'Filtered to $_yearFilter'
: _searchInMonthOnly
? 'Searching in ${formatMonthYear(_month)}'
: 'Searching all transactions',
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(
_searchInMonthOnly
? 'Searching in ${formatMonthYear(_month)}'
: 'Searching all transactions',
style: theme.textTheme.labelMedium,
filtered.length == 1
? '1 transaction'
: '${filtered.length} transactions',
style: theme.textTheme.titleSmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
),
),
if (filtered.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Text(
_isSearching
? 'No transactions match this search.'
: _selectedDay != null
? 'No transactions on this day.'
: 'No transactions this month.',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Text(
_isSearching
? 'No transactions match this search.'
: _selectedDay != null
? 'No transactions on this day.'
: 'No transactions this month.',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
),
),
)
else
for (var i = 0; i < filtered.length; i++) ...[
if (i > 0)
Divider(
height: 1,
color: colors.outlineVariant.withValues(alpha: 0.5),
),
_CompactTransactionTile(
tx: filtered[i],
meta: metaController.metaFor(filtered[i]),
labels: metaController
.labelsFor(metaController.metaFor(filtered[i])),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final tx = filtered[index];
final meta = metaController.metaFor(tx);
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (index > 0)
Divider(
height: 1,
color: colors.outlineVariant.withValues(alpha: 0.5),
),
_CompactTransactionTile(
tx: tx,
meta: meta,
labels: metaController.leafLabelsFor(meta),
),
],
);
},
childCount: filtered.length,
addAutomaticKeepAlives: false,
),
],
),
const SliverToBoxAdapter(child: SizedBox(height: 32)),
],
);
}