fix recurrent spendings

This commit is contained in:
davmar
2026-09-10 09:23:40 +02:00
parent 5b22fc8694
commit 200ff72e2e
6 changed files with 116 additions and 150 deletions
+16 -64
View File
@@ -642,7 +642,7 @@ class TxMetaController extends ChangeNotifier {
_schedulePersist(); _schedulePersist();
} }
/// Recurring look-ahead templates (manual + auto from marked txs). /// Explicit look-ahead recurring spendings (never auto-linked from tx flags).
List<RecurringTemplate> get recurringTemplates { List<RecurringTemplate> get recurringTemplates {
final list = _recurringTemplates.values.toList(growable: false); final list = _recurringTemplates.values.toList(growable: false);
list.sort((a, b) { list.sort((a, b) {
@@ -656,6 +656,14 @@ class TxMetaController extends ChangeNotifier {
RecurringTemplate? recurringTemplateById(String id) => RecurringTemplate? recurringTemplateById(String id) =>
_recurringTemplates[id]; _recurringTemplates[id];
/// True when a spending already references this bank transaction.
bool hasRecurringSpendingForTx(String txId) {
for (final tpl in _recurringTemplates.values) {
if (tpl.sourceTxId == txId) return true;
}
return false;
}
void upsertRecurringTemplate(RecurringTemplate template) { void upsertRecurringTemplate(RecurringTemplate template) {
if (template.id.isEmpty) return; if (template.id.isEmpty) return;
_recurringTemplates[template.id] = template; _recurringTemplates[template.id] = template;
@@ -668,16 +676,10 @@ class TxMetaController extends ChangeNotifier {
_schedulePersist(invalidateLabels: false); _schedulePersist(invalidateLabels: false);
} }
/// Backfill auto templates for txs already marked recurring (upgrade path). /// Create a spending seeded from [tx] (last-value amount rule).
void ensureAutoRecurringTemplates(List<BankTransaction> transactions) { RecurringTemplate addRecurringSpendingFromTx(BankTransaction tx) {
var changed = false; final id = 'rt_${DateTime.now().microsecondsSinceEpoch.toRadixString(16)}';
final recurringIds = <String>{}; final tpl = RecurringTemplate(
for (final tx in transactions) {
if (!metaFor(tx).recurring) continue;
recurringIds.add(tx.id);
final id = RecurringTemplate.autoIdForTx(tx.id);
if (_recurringTemplates.containsKey(id)) continue;
_recurringTemplates[id] = RecurringTemplate(
id: id, id: id,
name: tx.description, name: tx.description,
dayOfMonth: (DateTime.tryParse(tx.date)?.day ?? 1).clamp(1, 28), dayOfMonth: (DateTime.tryParse(tx.date)?.day ?? 1).clamp(1, 28),
@@ -687,23 +689,10 @@ class TxMetaController extends ChangeNotifier {
merchantKey: tx.merchantKey, merchantKey: tx.merchantKey,
sourceTxId: tx.id, sourceTxId: tx.id,
avgCount: 5, avgCount: 5,
autoFromRecurring: true, autoFromRecurring: false,
); );
changed = true; upsertRecurringTemplate(tpl);
} return tpl;
// Drop orphaned auto templates whose source is no longer recurring.
final orphanIds = [
for (final e in _recurringTemplates.entries)
if (e.value.autoFromRecurring &&
(e.value.sourceTxId == null ||
!recurringIds.contains(e.value.sourceTxId)))
e.key,
];
for (final id in orphanIds) {
_recurringTemplates.remove(id);
changed = true;
}
if (changed) _schedulePersist(invalidateLabels: false);
} }
Future<void> setRecurring(BankTransaction tx, bool recurring) async { Future<void> setRecurring(BankTransaction tx, bool recurring) async {
@@ -715,39 +704,6 @@ class TxMetaController extends ChangeNotifier {
recurring: recurring, recurring: recurring,
internalTransfer: existing.internalTransfer || current.internalTransfer, internalTransfer: existing.internalTransfer || current.internalTransfer,
); );
if (recurring) {
final id = RecurringTemplate.autoIdForTx(tx.id);
final prev = _recurringTemplates[id];
_recurringTemplates[id] = RecurringTemplate(
id: id,
name: prev?.name ?? tx.description,
dayOfMonth: prev?.dayOfMonth ??
(DateTime.tryParse(tx.date)?.day ?? 1).clamp(1, 28),
currency: prev?.currency ?? tx.currency,
source: RecurringTemplateSource.transaction,
amountRule: prev?.amountRule ?? RecurringAmountRule.lastValue,
merchantKey: prev?.merchantKey.isNotEmpty == true
? prev!.merchantKey
: tx.merchantKey,
sourceTxId: tx.id,
labelId: prev?.labelId,
avgCount: prev?.avgCount ?? 5,
autoFromRecurring: true,
);
} else {
final id = RecurringTemplate.autoIdForTx(tx.id);
final existingTpl = _recurringTemplates[id];
if (existingTpl != null && existingTpl.autoFromRecurring) {
_recurringTemplates.remove(id);
}
// Also drop auto templates that still point at this tx under another id.
_recurringTemplates.removeWhere(
(_, tpl) =>
tpl.autoFromRecurring &&
tpl.sourceTxId == tx.id &&
tpl.id != id,
);
}
_schedulePersist(invalidateLabels: false); _schedulePersist(invalidateLabels: false);
} }
@@ -835,10 +791,6 @@ class TxMetaController extends ChangeNotifier {
_schedulePersist(); _schedulePersist();
} }
Future<void> toggleRecurring(BankTransaction tx) {
return setRecurring(tx, !metaFor(tx).recurring);
}
Future<void> toggleInternalTransfer(BankTransaction tx) { Future<void> toggleInternalTransfer(BankTransaction tx) {
return setInternalTransfer(tx, !metaFor(tx).internalTransfer); return setInternalTransfer(tx, !metaFor(tx).internalTransfer);
} }
+42 -18
View File
@@ -34,7 +34,6 @@ class LookAheadScreen extends StatefulWidget {
class _LookAheadScreenState extends State<LookAheadScreen> { class _LookAheadScreenState extends State<LookAheadScreen> {
var _period = _PeriodMode.monthly; var _period = _PeriodMode.monthly;
late DateTime _cursor; late DateTime _cursor;
var _didBackfill = false;
List<RecurringItem>? _cachedItems; List<RecurringItem>? _cachedItems;
int? _itemsCacheKey; int? _itemsCacheKey;
@@ -135,16 +134,6 @@ class _LookAheadScreenState extends State<LookAheadScreen> {
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
if (!_didBackfill && bank.transactions.isNotEmpty) {
_didBackfill = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context
.read<TxMetaController>()
.ensureAutoRecurringTemplates(bank.transactions);
});
}
final balance = bank.balance; final balance = bank.balance;
final currency = balance?.currency ?? final currency = balance?.currency ??
(bank.transactions.isNotEmpty (bank.transactions.isNotEmpty
@@ -190,6 +179,17 @@ class _LookAheadScreenState extends State<LookAheadScreen> {
} }
} }
// One occurrence of each template per month (template run-rate).
var monthlyIncome = 0.0;
var monthlyExpense = 0.0;
for (final item in items) {
if (item.amount >= 0) {
monthlyIncome += item.amount;
} else {
monthlyExpense += -item.amount;
}
}
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Look ahead'), title: const Text('Look ahead'),
@@ -303,7 +303,7 @@ class _LookAheadScreenState extends State<LookAheadScreen> {
children: [ children: [
Expanded( Expanded(
child: Text( child: Text(
'Recurring templates', 'Recurring spendings',
style: theme.textTheme.titleMedium, style: theme.textTheme.titleMedium,
), ),
), ),
@@ -317,8 +317,8 @@ class _LookAheadScreenState extends State<LookAheadScreen> {
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
items.isEmpty items.isEmpty
? 'Mark transactions as recurring, or create a template.' ? 'Create a spending from a transaction, or tap New.'
: '${items.length} template${items.length == 1 ? '' : 's'} · ' : '${items.length} spending${items.length == 1 ? '' : 's'} · '
'projected income ${formatMoney(income, currency)} · ' 'projected income ${formatMoney(income, currency)} · '
'expenses ${formatMoney(expenses, currency)}.', 'expenses ${formatMoney(expenses, currency)}.',
style: theme.textTheme.bodySmall?.copyWith( style: theme.textTheme.bodySmall?.copyWith(
@@ -326,13 +326,37 @@ class _LookAheadScreenState extends State<LookAheadScreen> {
), ),
), ),
const SizedBox(height: 10), const SizedBox(height: 10),
Row(
children: [
Expanded(
child: _SummaryCard(
icon: Icons.south_west,
iconBackground: AppTheme.accent.withValues(alpha: 0.18),
iconColor: AppTheme.accent,
amount: formatMoney(monthlyIncome, currency),
label: 'Monthly income',
),
),
const SizedBox(width: 12),
Expanded(
child: _SummaryCard(
icon: Icons.north_east,
iconBackground: AppTheme.expense.withValues(alpha: 0.18),
iconColor: AppTheme.expense,
amount: formatMoney(monthlyExpense, currency),
label: 'Monthly expense',
),
),
],
),
const SizedBox(height: 10),
if (items.isEmpty) if (items.isEmpty)
const EmptyState( const EmptyState(
icon: Icons.event_repeat_outlined, icon: Icons.event_repeat_outlined,
title: 'No recurring templates', title: 'No recurring spendings',
message: message:
'Mark a transaction as recurring, or tap New to base a ' 'Open a transaction and tap Create recurring spending, '
'template on a transaction or label average.', 'or use New to pick a transaction or label average.',
) )
else else
Card( Card(
@@ -584,7 +608,7 @@ class _TemplateTile extends StatelessWidget {
return ListTile( return ListTile(
leading: IconButton( leading: IconButton(
tooltip: 'Edit template', tooltip: 'Edit spending',
icon: Icon(Icons.tune, color: colors.primary), icon: Icon(Icons.tune, color: colors.primary),
onPressed: tpl == null onPressed: tpl == null
? null ? null
+21 -9
View File
@@ -11,6 +11,7 @@ import '../providers/tx_meta_provider.dart';
import '../utils/app_theme.dart'; import '../utils/app_theme.dart';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../widgets/label_parent_picker.dart'; import '../widgets/label_parent_picker.dart';
import '../widgets/recurring_template_sheet.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
import '../widgets/similar_match_dialog.dart'; import '../widgets/similar_match_dialog.dart';
@@ -409,17 +410,28 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
), ),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
SwitchListTile( ListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
secondary: const Icon(Icons.autorenew), leading: Icon(
title: const Text('Recurring'), Icons.event_repeat,
subtitle: const Text('Salary, mortgage, subscriptions…'), color: colors.primary,
value: meta.recurring, ),
onChanged: _busy title: const Text('Create recurring spending'),
subtitle: Text(
metaController.hasRecurringSpendingForTx(tx.id)
? 'Already on Look ahead — tap to add another'
: 'Add this transaction to Look ahead',
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
trailing: const Icon(Icons.chevron_right),
onTap: _busy
? null ? null
: (value) { : () => showCreateRecurringTemplateSheet(
context.read<TxMetaController>().setRecurring(tx, value); context,
}, initialTx: tx,
),
), ),
SwitchListTile( SwitchListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
+1 -16
View File
@@ -61,7 +61,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
var _showCalendar = false; var _showCalendar = false;
var _flowFilter = TxFlowFilter.all; var _flowFilter = TxFlowFilter.all;
var _amountRange = const TxAmountRange(); var _amountRange = const TxAmountRange();
var _recurringOnly = false;
/// Query actually used for filtering (Enter, or live once ≥3 chars). /// Query actually used for filtering (Enter, or live once ≥3 chars).
String _activeQuery = ''; String _activeQuery = '';
@@ -97,13 +96,11 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
bool get _hasListFilters => bool get _hasListFilters =>
_labelFilters.isNotEmpty || _labelFilters.isNotEmpty ||
_flowFilter != TxFlowFilter.all || _flowFilter != TxFlowFilter.all ||
_amountRange.isActive || _amountRange.isActive;
_recurringOnly;
bool _matchesExtraFilters(BankTransaction tx, TxMetaController meta) { bool _matchesExtraFilters(BankTransaction tx, TxMetaController meta) {
if (!txMatchesFlow(tx, _flowFilter)) return false; if (!txMatchesFlow(tx, _flowFilter)) return false;
if (!txMatchesAmountRange(tx, _amountRange)) return false; if (!txMatchesAmountRange(tx, _amountRange)) return false;
if (_recurringOnly && !meta.metaFor(tx).recurring) return false;
return true; return true;
} }
@@ -172,7 +169,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
amountRange: _amountRange, amountRange: _amountRange,
query: _activeQuery, query: _activeQuery,
monthOnly: _searchInMonthOnly, monthOnly: _searchInMonthOnly,
recurringOnly: _recurringOnly,
), ),
); );
if (result == null || !mounted) return; if (result == null || !mounted) return;
@@ -184,7 +180,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
_flowFilter = result.flow; _flowFilter = result.flow;
_amountRange = result.amountRange; _amountRange = result.amountRange;
_searchInMonthOnly = result.monthOnly; _searchInMonthOnly = result.monthOnly;
_recurringOnly = result.recurringOnly;
if (!_searchInMonthOnly) { if (!_searchInMonthOnly) {
_showCalendar = false; _showCalendar = false;
_selectedDay = null; _selectedDay = null;
@@ -682,15 +677,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
); );
}, },
), ),
if (_recurringOnly)
InputChip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.event_repeat, size: 14),
label: const Text('Recurring'),
onDeleted: () {
setState(() => _recurringOnly = false);
},
),
for (final id in _labelFilters) for (final id in _labelFilters)
if (id == kUncategorizedFilterId) if (id == kUncategorizedFilterId)
InputChip( InputChip(
@@ -968,7 +954,6 @@ class _CompactTransactionTile extends StatelessWidget {
formatIsoDate(tx.date), formatIsoDate(tx.date),
if (labels.isNotEmpty) if (labels.isNotEmpty)
labels.map((l) => l.name).join(', '), labels.map((l) => l.name).join(', '),
if (meta.recurring) 'Recurring',
if (meta.internalTransfer) 'Transfer', if (meta.internalTransfer) 'Transfer',
if (meta.hasNotes) 'Note', if (meta.hasNotes) 'Note',
if (tx.pending) 'Pending', if (tx.pending) 'Pending',
+1 -27
View File
@@ -19,7 +19,6 @@ class TransactionFilterSelection {
this.amountRange = const TxAmountRange(), this.amountRange = const TxAmountRange(),
this.query = '', this.query = '',
this.monthOnly = false, this.monthOnly = false,
this.recurringOnly = false,
}); });
final Set<String> labelIds; final Set<String> labelIds;
@@ -30,14 +29,10 @@ class TransactionFilterSelection {
/// When true, list is limited to the selected calendar month. /// When true, list is limited to the selected calendar month.
final bool monthOnly; final bool monthOnly;
/// When true, only transactions marked recurring are shown.
final bool recurringOnly;
bool get hasActiveExtras => bool get hasActiveExtras =>
flow != TxFlowFilter.all || flow != TxFlowFilter.all ||
amountRange.isActive || amountRange.isActive ||
query.trim().isNotEmpty || query.trim().isNotEmpty;
recurringOnly;
} }
/// How label series are drawn on the overview chart. /// How label series are drawn on the overview chart.
@@ -502,7 +497,6 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
late final Set<String> _selected; late final Set<String> _selected;
late TxFlowFilter _flow; late TxFlowFilter _flow;
late bool _monthOnly; late bool _monthOnly;
late bool _recurringOnly;
late final TextEditingController _queryController; late final TextEditingController _queryController;
late final TextEditingController _labelSearchController; late final TextEditingController _labelSearchController;
late final TextEditingController _exactAmountController; late final TextEditingController _exactAmountController;
@@ -516,7 +510,6 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
_selected = Set<String>.of(initial.labelIds); _selected = Set<String>.of(initial.labelIds);
_flow = initial.flow; _flow = initial.flow;
_monthOnly = initial.monthOnly; _monthOnly = initial.monthOnly;
_recurringOnly = initial.recurringOnly;
_queryController = TextEditingController(text: initial.query); _queryController = TextEditingController(text: initial.query);
_labelSearchController = TextEditingController(); _labelSearchController = TextEditingController();
@@ -602,7 +595,6 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
amountRange: _amountResult, amountRange: _amountResult,
query: _queryController.text.trim(), query: _queryController.text.trim(),
monthOnly: _monthOnly, monthOnly: _monthOnly,
recurringOnly: _recurringOnly,
), ),
); );
} }
@@ -718,24 +710,6 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
), ),
], ],
), ),
const SizedBox(height: 8),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
dense: true,
value: _recurringOnly,
onChanged: (value) {
setState(() => _recurringOnly = value ?? false);
},
controlAffinity: ListTileControlAffinity.leading,
secondary: const Icon(Icons.event_repeat, size: 20),
title: const Text('Recurring only'),
subtitle: Text(
'Only transactions marked as recurring',
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
),
const SizedBox(height: 14), const SizedBox(height: 14),
Text('Amount', style: sectionStyle), Text('Amount', style: sectionStyle),
const SizedBox(height: 8), const SizedBox(height: 8),
+25 -6
View File
@@ -12,13 +12,16 @@ import '../providers/tx_meta_provider.dart';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../utils/look_ahead.dart'; import '../utils/look_ahead.dart';
Future<void> showCreateRecurringTemplateSheet(BuildContext context) { Future<void> showCreateRecurringTemplateSheet(
BuildContext context, {
BankTransaction? initialTx,
}) {
return showModalBottomSheet<void>( return showModalBottomSheet<void>(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
useSafeArea: true, useSafeArea: true,
showDragHandle: true, showDragHandle: true,
builder: (context) => const _RecurringTemplateSheet(), builder: (context) => _RecurringTemplateSheet(initialTx: initialTx),
); );
} }
@@ -36,9 +39,10 @@ Future<void> showEditRecurringTemplateSheet(
} }
class _RecurringTemplateSheet extends StatefulWidget { class _RecurringTemplateSheet extends StatefulWidget {
const _RecurringTemplateSheet({this.existing}); const _RecurringTemplateSheet({this.existing, this.initialTx});
final RecurringTemplate? existing; final RecurringTemplate? existing;
final BankTransaction? initialTx;
@override @override
State<_RecurringTemplateSheet> createState() => State<_RecurringTemplateSheet> createState() =>
@@ -71,15 +75,28 @@ class _RecurringTemplateSheetState extends State<_RecurringTemplateSheet> {
_labelId = existing?.labelId; _labelId = existing?.labelId;
_currency = existing?.currency ?? 'EUR'; _currency = existing?.currency ?? 'EUR';
if (existing?.sourceTxId != null) { BankTransaction? seed = widget.initialTx;
if (seed == null && existing?.sourceTxId != null) {
final txs = context.read<BankController>().transactions; final txs = context.read<BankController>().transactions;
for (final tx in txs) { for (final tx in txs) {
if (tx.id == existing!.sourceTxId) { if (tx.id == existing!.sourceTxId) {
_pickedTx = tx; seed = tx;
break; break;
} }
} }
} }
if (seed != null) {
_pickedTx = seed;
_currency = seed.currency;
_source = RecurringTemplateSource.transaction;
if (_nameController.text.trim().isEmpty) {
_nameController.text = seed.description;
}
if (existing == null) {
_dayController.text =
'${(DateTime.tryParse(seed.date)?.day ?? 1).clamp(1, 28)}';
}
}
} }
@override @override
@@ -252,7 +269,9 @@ class _RecurringTemplateSheetState extends State<_RecurringTemplateSheet> {
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Text( Text(
widget.existing == null ? 'New recurring template' : 'Edit template', widget.existing == null
? 'New recurring spending'
: 'Edit recurring spending',
style: theme.textTheme.titleLarge, style: theme.textTheme.titleLarge,
), ),
const SizedBox(height: 16), const SizedBox(height: 16),