7 Commits
Author SHA1 Message Date
davmar 40366f0708 some issues fixed 2026-09-11 12:31:07 +02:00
davmar 2e40786bcd attempt to fix test txs 2.1 2026-09-11 00:11:00 +02:00
davmar 38bcf01ae3 attempt to fix test txs 2 2026-09-11 00:10:15 +02:00
davmar 00ab05eefc attempt to fix test txs 2026-09-10 23:59:00 +02:00
davmar f8e293f823 admin user able to create test txs 2026-09-10 23:18:24 +02:00
davmar c4f0ca785e user admin capability 2026-09-10 22:58:52 +02:00
davmar 6cc0de8945 fixed some issues and added label and, or capability 2026-09-10 22:45:25 +02:00
31 changed files with 1985 additions and 260 deletions
+8
View File
@@ -95,9 +95,17 @@ Migrations live in [`pocketbase/pb_migrations/`](pocketbase/pb_migrations/). The
| `1740000003` | `overview_favourites` |
| `1740000004`–`0006` | `home_filter_widgets` (+ half width, budget fields) |
| `1740000007` | `app_prefs` (Home section toggles + Look ahead years) |
| `1740000008` | `home_filter_widgets.label_match` (AND/OR) |
| `1740000009` | `usersapp.is_admin` (admin accounts) |
Built-in labels stay in the app; only **custom** labels sync. Rows are scoped per user (`user = @request.auth.id`).
### Admin accounts
Migration `1740000009` adds `is_admin` (bool) on **`usersapp`**. In PocketBase Admin → **Users** → edit a user → enable **is_admin**.
Admins see an **Admin** badge on Account and can **Create test transaction** (saved locally and synced with bank transactions). Normal users do not get that action. Re-sign-in after flipping the flag so the app picks it up.
### Apply migrations (typical Linux host)
```bash
+51
View File
@@ -88,6 +88,7 @@ class BankTransaction {
required this.amount,
required this.currency,
required this.pending,
this.isManual = false,
});
final String date;
@@ -96,6 +97,9 @@ class BankTransaction {
final String currency;
final bool pending;
/// Admin-created test row (editable / deletable); not from bank feed or CSV.
final bool isManual;
/// Stable local key used for per-occurrence annotations.
String get id => '$date|$currency|$amount|$description';
@@ -109,6 +113,50 @@ class BankTransaction {
/// Exact match for copying notes (same description + amount + currency).
String get exactKey => '$descriptionKey|$amount|$currency';
static String stripManualStamp(String description) =>
description.replaceFirst(RegExp(r' ·#\d+$'), '');
/// True when [other] is the same row for delete/tombstone matching.
///
/// Uses id first, then date + cents + currency + description (stamp-insensitive),
/// so PocketBase float/amount rehydration cannot bypass a local delete.
bool matchesForDelete(BankTransaction other) {
if (id == other.id) return true;
if (date != other.date) return false;
if (currency.toUpperCase() != other.currency.toUpperCase()) return false;
if ((amount * 100).round() != (other.amount * 100).round()) return false;
if (descriptionKey == other.descriptionKey) return true;
return stripManualStamp(description).trim().toLowerCase() ==
stripManualStamp(other.description).trim().toLowerCase();
}
BankTransaction copyWith({
String? date,
String? description,
double? amount,
String? currency,
bool? pending,
bool? isManual,
}) {
return BankTransaction(
date: date ?? this.date,
description: description ?? this.description,
amount: amount ?? this.amount,
currency: currency ?? this.currency,
pending: pending ?? this.pending,
isManual: isManual ?? this.isManual,
);
}
Map<String, dynamic> toJson() => {
'date': date,
'description': description,
'amount': amount,
'currency': currency,
'pending': pending,
if (isManual) 'isManual': true,
};
factory BankTransaction.fromJson(Map<String, dynamic> json) {
final rawAmount = json['amount'];
final amount = switch (rawAmount) {
@@ -122,6 +170,9 @@ class BankTransaction {
amount: amount,
currency: json['currency'] as String? ?? 'EUR',
pending: json['pending'] as bool? ?? false,
isManual: json['isManual'] as bool? ??
json['is_manual'] as bool? ??
false,
);
}
}
+47 -5
View File
@@ -86,6 +86,7 @@ class HomeFilterWidget {
this.budgetFixedAmount = 0,
this.budgetAverageMonths = 3,
this.labelIds = const [],
this.labelMatch = LabelMatchMode.and,
this.flow = TxFlowFilter.all,
this.amountRange = const TxAmountRange(),
this.query = '',
@@ -93,6 +94,8 @@ class HomeFilterWidget {
this.showAmountIn = true,
this.showAmountOut = true,
this.showCount = true,
this.updatedAt = 0,
this.deleted = false,
});
final String id;
@@ -115,6 +118,10 @@ class HomeFilterWidget {
final int budgetAverageMonths;
final List<String> labelIds;
/// AND vs OR when multiple [labelIds] are selected.
final LabelMatchMode labelMatch;
final TxFlowFilter flow;
final TxAmountRange amountRange;
final String query;
@@ -124,10 +131,17 @@ class HomeFilterWidget {
final bool showAmountOut;
final bool showCount;
/// Epoch ms; used for last-write-wins sync across devices.
final int updatedAt;
/// Soft-delete so removals propagate via sync instead of being recreated.
final bool deleted;
IconData get icon => HomeWidgetIcons.iconFor(iconId);
TransactionFilterSelection get filter => TransactionFilterSelection(
labelIds: labelIds.toSet(),
labelMatch: labelMatch,
flow: flow,
amountRange: amountRange,
query: query,
@@ -147,6 +161,7 @@ class HomeFilterWidget {
double? budgetFixedAmount,
int? budgetAverageMonths,
List<String>? labelIds,
LabelMatchMode? labelMatch,
TxFlowFilter? flow,
TxAmountRange? amountRange,
String? query,
@@ -154,6 +169,9 @@ class HomeFilterWidget {
bool? showAmountIn,
bool? showAmountOut,
bool? showCount,
int? updatedAt,
bool? deleted,
bool touchUpdatedAt = false,
}) {
return HomeFilterWidget(
id: id ?? this.id,
@@ -168,6 +186,7 @@ class HomeFilterWidget {
budgetFixedAmount: budgetFixedAmount ?? this.budgetFixedAmount,
budgetAverageMonths: budgetAverageMonths ?? this.budgetAverageMonths,
labelIds: labelIds ?? this.labelIds,
labelMatch: labelMatch ?? this.labelMatch,
flow: flow ?? this.flow,
amountRange: amountRange ?? this.amountRange,
query: query ?? this.query,
@@ -175,6 +194,10 @@ class HomeFilterWidget {
showAmountIn: showAmountIn ?? this.showAmountIn,
showAmountOut: showAmountOut ?? this.showAmountOut,
showCount: showCount ?? this.showCount,
updatedAt: touchUpdatedAt
? DateTime.now().millisecondsSinceEpoch
: (updatedAt ?? this.updatedAt),
deleted: deleted ?? this.deleted,
);
}
@@ -192,6 +215,7 @@ class HomeFilterWidget {
display: display,
sortOrder: sortOrder,
labelIds: filter.labelIds.toList(growable: false),
labelMatch: filter.labelMatch,
flow: filter.flow,
amountRange: filter.amountRange,
query: filter.query,
@@ -199,6 +223,7 @@ class HomeFilterWidget {
showAmountIn: showIn,
showAmountOut: showOut,
showCount: true,
updatedAt: DateTime.now().millisecondsSinceEpoch,
);
}
@@ -215,6 +240,7 @@ class HomeFilterWidget {
'budgetFixedAmount': budgetFixedAmount,
'budgetAverageMonths': budgetAverageMonths,
'labelIds': labelIds,
'labelMatch': labelMatch.name,
'flow': flow.name,
'amountRange': {
if (amountRange.exact != null) 'exact': amountRange.exact,
@@ -226,6 +252,8 @@ class HomeFilterWidget {
'showAmountIn': showAmountIn,
'showAmountOut': showAmountOut,
'showCount': showCount,
'updatedAt': updatedAt,
'deleted': deleted,
};
factory HomeFilterWidget.fromJson(Map<String, dynamic> json) {
@@ -274,6 +302,10 @@ class HomeFilterWidget {
for (final id in (json['labelIds'] as List? ?? const []))
if (id is String && id.isNotEmpty) id,
],
labelMatch: LabelMatchMode.values.firstWhere(
(e) => e.name == json['labelMatch'],
orElse: () => LabelMatchMode.and,
),
flow: TxFlowFilter.values.firstWhere(
(e) => e.name == json['flow'],
orElse: () => TxFlowFilter.all,
@@ -288,20 +320,30 @@ class HomeFilterWidget {
showAmountIn: json['showAmountIn'] as bool? ?? true,
showAmountOut: json['showAmountOut'] as bool? ?? true,
showCount: json['showCount'] as bool? ?? true,
updatedAt: asInt(json['updatedAt'] ?? json['updated_at'], 0),
deleted: json['deleted'] as bool? ?? false,
);
}
}
/// Union home widgets by id (local wins on conflict).
/// Union home widgets by id with last-write-wins on [HomeFilterWidget.updatedAt].
List<HomeFilterWidget> mergeHomeFilterWidgets(
List<HomeFilterWidget> local,
List<HomeFilterWidget> remote,
) {
final byId = <String, HomeFilterWidget>{
for (final w in remote) w.id: w,
};
final byId = <String, HomeFilterWidget>{};
void put(HomeFilterWidget w) {
final existing = byId[w.id];
if (existing == null || w.updatedAt >= existing.updatedAt) {
byId[w.id] = w;
}
}
for (final w in remote) {
put(w);
}
for (final w in local) {
byId[w.id] = w;
put(w);
}
final merged = byId.values.toList()
..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
+48
View File
@@ -16,6 +16,8 @@ class OverviewFavourite {
this.flow = TxFlowFilter.expense,
this.barStyle = LabelChartBarStyle.parallel,
this.invertExpensePerspective = false,
this.updatedAt = 0,
this.deleted = false,
});
final String id;
@@ -34,6 +36,12 @@ class OverviewFavourite {
final LabelChartBarStyle barStyle;
final bool invertExpensePerspective;
/// Epoch ms; used for last-write-wins sync across devices.
final int updatedAt;
/// Soft-delete so removals propagate via sync instead of being recreated.
final bool deleted;
OverviewFavourite copyWith({
String? id,
String? name,
@@ -44,6 +52,9 @@ class OverviewFavourite {
TxFlowFilter? flow,
LabelChartBarStyle? barStyle,
bool? invertExpensePerspective,
int? updatedAt,
bool? deleted,
bool touchUpdatedAt = false,
}) {
return OverviewFavourite(
id: id ?? this.id,
@@ -56,6 +67,10 @@ class OverviewFavourite {
barStyle: barStyle ?? this.barStyle,
invertExpensePerspective:
invertExpensePerspective ?? this.invertExpensePerspective,
updatedAt: touchUpdatedAt
? DateTime.now().millisecondsSinceEpoch
: (updatedAt ?? this.updatedAt),
deleted: deleted ?? this.deleted,
);
}
@@ -69,9 +84,18 @@ class OverviewFavourite {
'flow': flow.name,
'barStyle': barStyle.name,
'invertExpensePerspective': invertExpensePerspective,
'updatedAt': updatedAt,
'deleted': deleted,
};
factory OverviewFavourite.fromJson(Map<String, dynamic> json) {
final rawUpdated = json['updatedAt'] ?? json['updated_at'];
final updatedAt = switch (rawUpdated) {
int n => n,
num n => n.round(),
String s => int.tryParse(s) ?? 0,
_ => 0,
};
return OverviewFavourite(
id: json['id'] as String? ?? 'fav_${DateTime.now().millisecondsSinceEpoch}',
name: (json['name'] as String?)?.trim().isNotEmpty == true
@@ -100,6 +124,8 @@ class OverviewFavourite {
),
invertExpensePerspective:
json['invertExpensePerspective'] as bool? ?? false,
updatedAt: updatedAt,
deleted: json['deleted'] as bool? ?? false,
);
}
}
@@ -107,3 +133,25 @@ class OverviewFavourite {
enum OverviewMetricMode { flow, labels }
enum OverviewPeriodMode { monthly, yearly }
/// Union favourites by id with last-write-wins on [OverviewFavourite.updatedAt].
List<OverviewFavourite> mergeOverviewFavourites(
List<OverviewFavourite> local,
List<OverviewFavourite> remote,
) {
final byId = <String, OverviewFavourite>{};
void put(OverviewFavourite fav) {
final existing = byId[fav.id];
if (existing == null || fav.updatedAt >= existing.updatedAt) {
byId[fav.id] = fav;
}
}
for (final fav in remote) {
put(fav);
}
for (final fav in local) {
put(fav);
}
return byId.values.toList(growable: false);
}
+9
View File
@@ -134,6 +134,15 @@ int labelVisibleDepth(
/// Filter-only id for txs with no labels (not an assignable category).
const String kUncategorizedFilterId = '__uncategorized__';
/// How multiple selected labels combine in a transaction filter.
enum LabelMatchMode {
/// Tx must include every selected label.
and,
/// Tx must include at least one selected label.
or,
}
/// Chip presentation for [kUncategorizedFilterId] refine filters.
const TxLabel kUncategorizedFilterLabel = TxLabel(
id: kUncategorizedFilterId,
+18
View File
@@ -26,6 +26,13 @@ class AuthController extends ChangeNotifier {
RecordModel? get user => _client?.authStore.record;
/// True when PocketBase `usersapp.is_admin` is set for this account.
bool get isAdmin {
final record = user;
if (record == null) return false;
return record.getBoolValue('is_admin');
}
String? get email {
final value = user?.getStringValue('email');
return value == null || value.isEmpty ? null : value;
@@ -80,6 +87,17 @@ class AuthController extends ChangeNotifier {
notifyListeners();
}
/// Refresh the auth record (e.g. after `is_admin` was toggled in Admin UI).
Future<void> refreshSession() async {
if (!isLoggedIn) return;
try {
await client.collection(kPocketBaseUsersCollection).authRefresh();
} catch (error, stackTrace) {
debugPrint('AuthController.refreshSession failed: $error\n$stackTrace');
}
notifyListeners();
}
Future<void> logout() async {
client.authStore.clear();
notifyListeners();
+282 -2
View File
@@ -1,6 +1,8 @@
/// [ChangeNotifier] for bank link status, balance, and transactions.
library;
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/bank.dart';
@@ -30,9 +32,34 @@ class BankController extends ChangeNotifier {
_remoteTransactions = cached.transactions;
}
_importedTransactions = _storage?.loadImportedTransactions() ?? const [];
_importedTransactions = [
for (final tx in _importedTransactions) _upgradeLegacyManual(tx),
];
_remoteTransactions = [
for (final tx in _remoteTransactions) _upgradeLegacyManual(tx),
];
_pendingRemoteDeletes = _storage?.loadPendingTxDeletes() ?? const [];
// Drop anything still queued for remote delete from the local caches.
if (_pendingRemoteDeletes.isNotEmpty) {
_remoteTransactions = [
for (final tx in _remoteTransactions)
if (!_isTombstoned(tx)) tx,
];
_importedTransactions = [
for (final tx in _importedTransactions)
if (!_isTombstoned(tx)) tx,
];
}
_invalidateMerged();
}
/// Older admin test rows used a ·#stamp suffix before [isManual] existed.
static BankTransaction _upgradeLegacyManual(BankTransaction tx) {
if (tx.isManual) return tx;
if (!RegExp(r' ·#\d+$').hasMatch(tx.description)) return tx;
return tx.copyWith(isManual: true);
}
final IngtrakApi _api;
final StorageService? _storage;
@@ -42,10 +69,116 @@ class BankController extends ChangeNotifier {
/// cannot leave the device behind the cloud (or wipe cloud-only history).
VoidCallback? onAfterSuccessfulLoad;
/// Fired when local admin txs are removed/replaced and need a remote delete.
VoidCallback? onPendingRemoteDeletesChanged;
ConnectStatus _status = ConnectStatus.disconnected;
BankBalance? _balance;
List<BankTransaction> _remoteTransactions = const [];
List<BankTransaction> _importedTransactions = const [];
List<BankTransaction> _pendingRemoteDeletes = const [];
/// Tombstoned txs waiting to be removed from PocketBase (also persisted).
List<BankTransaction> get pendingRemoteDeletes =>
List<BankTransaction>.unmodifiable(_pendingRemoteDeletes);
bool get hasPendingRemoteDeletes => _pendingRemoteDeletes.isNotEmpty;
bool _isTombstoned(BankTransaction tx) {
for (final tomb in _pendingRemoteDeletes) {
if (tx.matchesForDelete(tomb)) return true;
}
return false;
}
void requeueRemoteDeletes(Iterable<BankTransaction> txs) {
for (final tx in txs) {
_queueRemoteDelete(tx, notify: false);
}
unawaited(_persistPendingDeletes());
}
void _queueRemoteDelete(BankTransaction tx, {bool notify = true}) {
if (tx.id.isEmpty) return;
if (_isTombstoned(tx)) return;
_pendingRemoteDeletes = [
..._pendingRemoteDeletes,
tx.copyWith(isManual: true),
];
unawaited(_persistPendingDeletes());
if (notify) onPendingRemoteDeletesChanged?.call();
}
/// Merge delete tombstones from another device and strip matching local rows.
Future<void> applyRemoteDeletes(
List<BankTransaction> remote, {
bool notify = true,
}) async {
var tombsChanged = false;
for (final tomb in remote) {
if (_isTombstoned(tomb)) continue;
_pendingRemoteDeletes = [
..._pendingRemoteDeletes,
tomb.copyWith(isManual: true),
];
tombsChanged = true;
}
if (_pendingRemoteDeletes.isEmpty) return;
final beforeRemote = _remoteTransactions.length;
final beforeImported = _importedTransactions.length;
_remoteTransactions = [
for (final tx in _remoteTransactions)
if (!_isTombstoned(tx)) tx,
];
_importedTransactions = [
for (final tx in _importedTransactions)
if (!_isTombstoned(tx)) tx,
];
final stripped = beforeRemote != _remoteTransactions.length ||
beforeImported != _importedTransactions.length;
if (tombsChanged || stripped) {
_invalidateMerged();
if (tombsChanged) await _persistPendingDeletes();
if (stripped) {
await _persistCache();
await _persistImported();
}
if (notify) notifyListeners();
}
}
Future<void> _persistPendingDeletes() async {
final storage = _storage;
if (storage == null) return;
await storage.savePendingTxDeletes(_pendingRemoteDeletes);
}
/// Keep [isManual] when a synced/API row replaces a matching imported test tx.
void _reapplyManualFlags(Set<String> manualIds) {
if (manualIds.isEmpty) return;
BankTransaction stamp(BankTransaction tx) =>
manualIds.contains(tx.id) && !tx.isManual
? tx.copyWith(isManual: true)
: tx;
_remoteTransactions = [for (final tx in _remoteTransactions) stamp(tx)];
_importedTransactions = [
for (final tx in _importedTransactions) stamp(tx),
];
}
Set<String> _collectManualIds([
Iterable<BankTransaction> extra = const [],
]) =>
{
for (final tx in [
..._remoteTransactions,
..._importedTransactions,
...extra,
])
if (tx.isManual) tx.id,
};
List<BankTransaction>? _mergedTransactions;
bool _isLoading = false;
@@ -161,6 +294,117 @@ class BankController extends ChangeNotifier {
notifyListeners();
}
/// Insert a locally created transaction (admin testing). Persisted like CSV
/// imports and included in PocketBase `transactions` sync.
Future<BankTransaction> addManualTransaction({
required DateTime date,
required String description,
required double amount,
String currency = 'EUR',
bool pending = false,
}) async {
final desc =
description.trim().isEmpty ? 'Test transaction' : description.trim();
// Include a short unique suffix so identical drafts do not collide on id.
final stamp = DateTime.now().millisecondsSinceEpoch % 100000;
final tx = BankTransaction(
date:
'${date.year.toString().padLeft(4, '0')}-'
'${date.month.toString().padLeft(2, '0')}-'
'${date.day.toString().padLeft(2, '0')}',
description: '$desc ·#$stamp',
amount: amount,
currency: currency.trim().isEmpty ? 'EUR' : currency.trim().toUpperCase(),
pending: pending,
isManual: true,
);
_importedTransactions = mergeTransactions(_importedTransactions, [tx]);
_importedTransactions = filterNewTransactions(
_remoteTransactions,
_importedTransactions,
);
_invalidateMerged();
await _persistImported();
notifyListeners();
return tx;
}
/// Replace an admin test transaction. Returns the updated row (id may change).
Future<BankTransaction> updateManualTransaction({
required BankTransaction previous,
required DateTime date,
required String description,
required double amount,
String currency = 'EUR',
bool pending = false,
}) async {
if (!previous.isManual) {
throw StateError('Only admin test transactions can be edited');
}
final desc =
description.trim().isEmpty ? 'Test transaction' : description.trim();
final stamped = () {
if (RegExp(r' ·#\d+$').hasMatch(desc)) return desc;
final prevStamp = RegExp(r' ·#(\d+)$').firstMatch(previous.description);
final prevBase =
previous.description.replaceFirst(RegExp(r' ·#\d+$'), '');
if (prevStamp != null && prevBase == desc) {
return '$desc ·#${prevStamp.group(1)}';
}
return '$desc ·#${DateTime.now().millisecondsSinceEpoch % 100000}';
}();
final updated = BankTransaction(
date:
'${date.year.toString().padLeft(4, '0')}-'
'${date.month.toString().padLeft(2, '0')}-'
'${date.day.toString().padLeft(2, '0')}',
description: stamped,
amount: amount,
currency: currency.trim().isEmpty ? 'EUR' : currency.trim().toUpperCase(),
pending: pending,
isManual: true,
);
_importedTransactions = [
for (final tx in _importedTransactions)
if (tx.id != previous.id) tx,
];
_remoteTransactions = [
for (final tx in _remoteTransactions)
if (tx.id != previous.id) tx,
];
if (previous.id != updated.id) {
_queueRemoteDelete(previous);
}
_importedTransactions = mergeTransactions(_importedTransactions, [updated]);
_invalidateMerged();
await _persistImported();
await _persistCache();
notifyListeners();
return updated;
}
/// Remove an admin test transaction from local caches.
Future<void> deleteManualTransaction(BankTransaction tx) async {
if (!tx.isManual) {
throw StateError('Only admin test transactions can be deleted');
}
_importedTransactions = [
for (final row in _importedTransactions)
if (!row.matchesForDelete(tx)) row,
];
_remoteTransactions = [
for (final row in _remoteTransactions)
if (!row.matchesForDelete(tx)) row,
];
_queueRemoteDelete(tx);
_invalidateMerged();
await _persistImported();
await _persistCache();
notifyListeners();
}
/// Union cloud txs into the local bank cache without dropping either side.
///
/// Rows land in the API cache; CSV imports that match are deduped away.
@@ -168,13 +412,37 @@ class BankController extends ChangeNotifier {
List<BankTransaction> fromCloud, {
bool notify = true,
}) async {
if (fromCloud.isEmpty) return;
if (fromCloud.isEmpty && _pendingRemoteDeletes.isEmpty) return;
_remoteTransactions = mergeTransactions(_remoteTransactions, fromCloud);
// Never resurrect rows the user already deleted locally.
final incoming = [
for (final tx in fromCloud)
if (!_isTombstoned(tx)) _upgradeLegacyManual(tx),
];
if (incoming.isEmpty && _pendingRemoteDeletes.isEmpty) return;
final manuals = _collectManualIds(incoming);
if (incoming.isNotEmpty) {
_remoteTransactions = mergeTransactions(_remoteTransactions, incoming);
}
// Strip any local copies that match a pending delete (defensive).
if (_pendingRemoteDeletes.isNotEmpty) {
_remoteTransactions = [
for (final tx in _remoteTransactions)
if (!_isTombstoned(tx)) tx,
];
}
_importedTransactions = filterNewTransactions(
_remoteTransactions,
_importedTransactions,
);
if (_pendingRemoteDeletes.isNotEmpty) {
_importedTransactions = [
for (final tx in _importedTransactions)
if (!_isTombstoned(tx)) tx,
];
}
_reapplyManualFlags(manuals);
_invalidateMerged();
if (!_status.linked && _remoteTransactions.isNotEmpty) {
@@ -254,6 +522,7 @@ class BankController extends ChangeNotifier {
final apiTxs = results[1] as List<BankTransaction>;
// Bank API is ~89 days. Prefer API rows for overlaps, but keep any
// cloud/CSV history that the API window does not include.
final manuals = _collectManualIds();
_remoteTransactions = mergeTransactions(apiTxs, _remoteTransactions);
if (!_status.linked) {
_status = ConnectStatus(
@@ -269,6 +538,17 @@ class BankController extends ChangeNotifier {
_remoteTransactions,
_importedTransactions,
);
if (_pendingRemoteDeletes.isNotEmpty) {
_remoteTransactions = [
for (final tx in _remoteTransactions)
if (!_isTombstoned(tx)) tx,
];
_importedTransactions = [
for (final tx in _importedTransactions)
if (!_isTombstoned(tx)) tx,
];
}
_reapplyManualFlags(manuals);
_invalidateMerged();
await _persistImported();
_error = null;
+66 -30
View File
@@ -42,26 +42,40 @@ class PreferencesController extends ChangeNotifier {
);
List<OverviewFavourite> get overviewFavourites =>
List.unmodifiable([
for (final fav in _overviewFavourites)
if (!fav.deleted) fav,
]);
/// Full list including soft-deleted rows (for PocketBase push).
List<OverviewFavourite> get overviewFavouritesForSync =>
List.unmodifiable(_overviewFavourites);
List<OverviewFavourite> get displayedOverviewFavourites => [
for (final fav in _overviewFavourites)
if (fav.display) fav,
if (!fav.deleted && fav.display) fav,
];
bool get hasDisplayedOverviewFavourites =>
_overviewFavourites.any((f) => f.display);
_overviewFavourites.any((f) => !f.deleted && f.display);
List<HomeFilterWidget> get homeFilterWidgets =>
List.unmodifiable([
for (final w in _homeFilterWidgets)
if (!w.deleted) w,
]);
/// Full list including soft-deleted rows (for PocketBase push).
List<HomeFilterWidget> get homeFilterWidgetsForSync =>
List.unmodifiable(_homeFilterWidgets);
List<HomeFilterWidget> get displayedHomeFilterWidgets => [
for (final w in _homeFilterWidgets)
if (w.display) w,
if (!w.deleted && w.display) w,
];
bool get hasDisplayedHomeFilterWidgets =>
_homeFilterWidgets.any((w) => w.display);
_homeFilterWidgets.any((w) => !w.deleted && w.display);
HomeBuiltInSections get homeBuiltInSections => _homeBuiltInSections;
@@ -118,7 +132,10 @@ class PreferencesController extends ChangeNotifier {
}
Future<void> addOverviewFavourite(OverviewFavourite favourite) async {
_overviewFavourites = [..._overviewFavourites, favourite];
final stamped = favourite.updatedAt == 0
? favourite.copyWith(touchUpdatedAt: true)
: favourite;
_overviewFavourites = [..._overviewFavourites, stamped];
notifyListeners();
await _persistFavourites();
}
@@ -127,18 +144,19 @@ class PreferencesController extends ChangeNotifier {
final index = _overviewFavourites.indexWhere((f) => f.id == favourite.id);
if (index < 0) return;
final next = [..._overviewFavourites];
next[index] = favourite;
next[index] = favourite.copyWith(touchUpdatedAt: true);
_overviewFavourites = next;
notifyListeners();
await _persistFavourites();
}
Future<void> removeOverviewFavourite(String id) async {
final next = [
for (final fav in _overviewFavourites)
if (fav.id != id) fav,
];
if (next.length == _overviewFavourites.length) return;
final index = _overviewFavourites.indexWhere((f) => f.id == id);
if (index < 0) return;
final current = _overviewFavourites[index];
if (current.deleted) return;
final next = [..._overviewFavourites];
next[index] = current.copyWith(deleted: true, touchUpdatedAt: true);
_overviewFavourites = next;
notifyListeners();
await _persistFavourites();
@@ -148,7 +166,7 @@ class PreferencesController extends ChangeNotifier {
final index = _overviewFavourites.indexWhere((f) => f.id == id);
if (index < 0) return;
final current = _overviewFavourites[index];
if (current.display == display) return;
if (current.deleted || current.display == display) return;
await updateOverviewFavourite(current.copyWith(display: display));
}
@@ -164,16 +182,20 @@ class PreferencesController extends ChangeNotifier {
}
Future<void> addHomeFilterWidget(HomeFilterWidget widget) async {
final order = _homeFilterWidgets.isEmpty
final order = _homeFilterWidgets.where((w) => !w.deleted).isEmpty
? 0
: _homeFilterWidgets
.where((w) => !w.deleted)
.map((w) => w.sortOrder)
.reduce((a, b) => a > b ? a : b) +
1;
_homeFilterWidgets = [
..._homeFilterWidgets,
widget.copyWith(sortOrder: widget.sortOrder == 0 ? order : widget.sortOrder),
];
final stamped = (widget.updatedAt == 0
? widget.copyWith(touchUpdatedAt: true)
: widget)
.copyWith(
sortOrder: widget.sortOrder == 0 ? order : widget.sortOrder,
);
_homeFilterWidgets = [..._homeFilterWidgets, stamped];
notifyListeners();
await _persistHomeWidgets();
}
@@ -182,7 +204,7 @@ class PreferencesController extends ChangeNotifier {
final index = _homeFilterWidgets.indexWhere((w) => w.id == widget.id);
if (index < 0) return;
final next = [..._homeFilterWidgets];
next[index] = widget;
next[index] = widget.copyWith(touchUpdatedAt: true);
next.sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
_homeFilterWidgets = next;
notifyListeners();
@@ -190,11 +212,12 @@ class PreferencesController extends ChangeNotifier {
}
Future<void> removeHomeFilterWidget(String id) async {
final next = [
for (final w in _homeFilterWidgets)
if (w.id != id) w,
];
if (next.length == _homeFilterWidgets.length) return;
final index = _homeFilterWidgets.indexWhere((w) => w.id == id);
if (index < 0) return;
final current = _homeFilterWidgets[index];
if (current.deleted) return;
final next = [..._homeFilterWidgets];
next[index] = current.copyWith(deleted: true, touchUpdatedAt: true);
_homeFilterWidgets = next;
notifyListeners();
await _persistHomeWidgets();
@@ -204,19 +227,32 @@ class PreferencesController extends ChangeNotifier {
final index = _homeFilterWidgets.indexWhere((w) => w.id == id);
if (index < 0) return;
final current = _homeFilterWidgets[index];
if (current.display == display) return;
if (current.deleted || current.display == display) return;
await updateHomeFilterWidget(current.copyWith(display: display));
}
Future<void> reorderHomeFilterWidgets(int oldIndex, int newIndex) async {
if (oldIndex == newIndex) return;
final next = [..._homeFilterWidgets];
final item = next.removeAt(oldIndex);
final target = newIndex.clamp(0, next.length);
next.insert(target, item);
_homeFilterWidgets = [
for (var i = 0; i < next.length; i++) next[i].copyWith(sortOrder: i),
final visible = [
for (final w in _homeFilterWidgets)
if (!w.deleted) w,
];
if (oldIndex < 0 || oldIndex >= visible.length) return;
final nextVisible = [...visible];
final item = nextVisible.removeAt(oldIndex);
final target = newIndex.clamp(0, nextVisible.length);
nextVisible.insert(target, item);
final orderById = <String, int>{
for (var i = 0; i < nextVisible.length; i++) nextVisible[i].id: i,
};
final now = DateTime.now().millisecondsSinceEpoch;
_homeFilterWidgets = [
for (final w in _homeFilterWidgets)
if (w.deleted)
w
else
w.copyWith(sortOrder: orderById[w.id] ?? w.sortOrder, updatedAt: now),
]..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
notifyListeners();
await _persistHomeWidgets();
}
+101 -12
View File
@@ -6,6 +6,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/app_cloud_prefs.dart';
import '../models/bank.dart';
import '../models/home_filter_widget.dart';
import '../models/overview_favourite.dart';
import '../services/pb_sync_service.dart';
@@ -46,6 +47,7 @@ class SyncController extends ChangeNotifier {
_prefs.onAppPrefsPersisted = _scheduleAppPrefsPush;
_auth.addListener(_onAuthChanged);
_bank.onAfterSuccessfulLoad = _onBankDataLoaded;
_bank.onPendingRemoteDeletesChanged = _scheduleBankTxPush;
if (_auth.isLoggedIn) {
unawaited(syncNow());
}
@@ -64,6 +66,7 @@ class SyncController extends ChangeNotifier {
bool _pushFavouritesPending = false;
bool _pushHomeWidgetsPending = false;
bool _pushAppPrefsPending = false;
bool _pushBankPending = false;
Timer? _pushDebounce;
Timer? _progressHold;
Timer? _uiNotifyThrottle;
@@ -198,6 +201,7 @@ class SyncController extends ChangeNotifier {
_pushFavouritesPending = false;
_pushHomeWidgetsPending = false;
_pushAppPrefsPending = false;
_pushBankPending = false;
_lastError = null;
_statusDetail = '';
_showProgressRing = false;
@@ -265,6 +269,47 @@ class SyncController extends ChangeNotifier {
_armPushDebounce();
}
void _scheduleBankTxPush() {
_pushBankPending = true;
_armPushDebounce();
}
/// Pull shared delete tombstones, then remove matching local bank rows.
Future<void> _pullAndApplyTxDeletes(PbSyncService service) async {
try {
final remote = await service.pullTxDeletes(onStatus: _setStatus);
await _bank.applyRemoteDeletes(remote, notify: false);
} catch (error) {
debugPrint('SyncController: tx_deletes pull skipped ($error)');
}
}
/// Removes tombstoned bank txs from the transactions collection.
///
/// Tombstones themselves stay local + synced via `tx_deletes` so other
/// devices learn about the delete and do not push the row back.
Future<void> _flushPendingTxDeletes(PbSyncService service) async {
final pending = List<BankTransaction>.of(_bank.pendingRemoteDeletes);
if (pending.isEmpty) return;
_setStatus('Removing deleted bank txs…');
try {
await service.deleteTransactionsMatching(pending);
// Keep tombstones — they must remain until every device has seen them.
} catch (error) {
debugPrint('SyncController: tx deletes failed ($error)');
}
}
Future<void> _pushTxDeletes(PbSyncService service) async {
final tombs = List<BankTransaction>.of(_bank.pendingRemoteDeletes);
if (tombs.isEmpty) return;
try {
await service.pushTxDeletes(tombs, onStatus: _setStatus);
} catch (error) {
debugPrint('SyncController: tx_deletes push skipped ($error)');
}
}
void _armPushDebounce() {
if (!_auth.isLoggedIn) return;
if (_syncing) {
@@ -297,6 +342,9 @@ class SyncController extends ChangeNotifier {
try {
final service = PbSyncService(_auth.client);
// Learn deletes from other devices before merging bank txs / pushing.
await _pullAndApplyTxDeletes(service);
await _flushPendingTxDeletes(service);
final remoteMeta = await service.pull(
onProgress: (p) {
_setProgress(p * 0.35);
@@ -324,7 +372,7 @@ class SyncController extends ChangeNotifier {
);
}
final mergedFavourites = mergeOverviewFavourites(
_prefs.overviewFavourites,
_prefs.overviewFavouritesForSync,
remoteFavourites,
);
List<HomeFilterWidget> remoteHomeWidgets = const [];
@@ -338,7 +386,7 @@ class SyncController extends ChangeNotifier {
);
}
final mergedHomeWidgets = mergeHomeFilterWidgets(
_prefs.homeFilterWidgets,
_prefs.homeFilterWidgetsForSync,
remoteHomeWidgets,
);
AppCloudPrefs? remoteAppPrefs;
@@ -408,8 +456,14 @@ class SyncController extends ChangeNotifier {
} catch (error) {
debugPrint('SyncController: app_prefs push skipped ($error)');
}
// Retry deletes in case any were queued during the pull/merge window.
await _flushPendingTxDeletes(service);
await _pushTxDeletes(service);
_pushBankPending = false;
final tombs = List<BankTransaction>.of(_bank.pendingRemoteDeletes);
final bankSummary = await service.pushTransactions(
_bank.transactions,
deleteTombs: tombs,
progressStart: 0.82,
progressEnd: 1.0,
onProgress: _setProgress,
@@ -454,11 +508,17 @@ class SyncController extends ChangeNotifier {
final pushFavourites = _pushFavouritesPending;
final pushHomeWidgets = _pushHomeWidgetsPending;
final pushAppPrefs = _pushAppPrefsPending;
final pushBank = _pushBankPending || _bank.pendingRemoteDeletes.isNotEmpty;
_pushMetaPending = false;
_pushFavouritesPending = false;
_pushHomeWidgetsPending = false;
_pushAppPrefsPending = false;
if (!pushMeta && !pushFavourites && !pushHomeWidgets && !pushAppPrefs) {
_pushBankPending = false;
if (!pushMeta &&
!pushFavourites &&
!pushHomeWidgets &&
!pushAppPrefs &&
!pushBank) {
return;
}
@@ -471,13 +531,15 @@ class SyncController extends ChangeNotifier {
pushFavourites,
pushHomeWidgets,
pushAppPrefs,
pushBank,
)) {
(false, false, false, true) => 'App prefs',
(false, false, true, false) => 'Home widgets',
(false, false, true, true) => 'Home layout',
(false, true, false, false) => 'Favourites',
(false, true, true, _) => 'Home layout',
(true, false, false, false) => 'Annotations',
(false, false, false, false, true) => 'Bank txs',
(false, false, false, true, false) => 'App prefs',
(false, false, true, false, false) => 'Home widgets',
(false, false, true, true, _) => 'Home layout',
(false, true, false, false, false) => 'Favourites',
(false, true, true, _, _) => 'Home layout',
(true, false, false, false, false) => 'Annotations',
_ => 'Changes',
};
_statusDetail = 'Pushing $label…';
@@ -491,7 +553,8 @@ class SyncController extends ChangeNotifier {
final total = (pushMeta ? 1 : 0) +
(pushFavourites ? 1 : 0) +
(pushHomeWidgets ? 1 : 0) +
(pushAppPrefs ? 1 : 0);
(pushAppPrefs ? 1 : 0) +
(pushBank ? 1 : 0);
void bump() {
done++;
_setProgress(done / total);
@@ -513,7 +576,7 @@ class SyncController extends ChangeNotifier {
_setStatus('Pushing favourites…');
try {
await service.pushOverviewFavourites(
_prefs.overviewFavourites,
_prefs.overviewFavouritesForSync,
onStatus: _setStatus,
);
parts.add('Favourites updated');
@@ -521,6 +584,7 @@ class SyncController extends ChangeNotifier {
debugPrint(
'SyncController: overview_favourites push skipped ($error)',
);
_pushFavouritesPending = true;
}
bump();
}
@@ -528,7 +592,7 @@ class SyncController extends ChangeNotifier {
_setStatus('Pushing home widgets…');
try {
await service.pushHomeFilterWidgets(
_prefs.homeFilterWidgets,
_prefs.homeFilterWidgetsForSync,
onStatus: _setStatus,
);
parts.add('Home widgets updated');
@@ -536,6 +600,7 @@ class SyncController extends ChangeNotifier {
debugPrint(
'SyncController: home_filter_widgets push skipped ($error)',
);
_pushHomeWidgetsPending = true;
}
bump();
}
@@ -555,6 +620,29 @@ class SyncController extends ChangeNotifier {
}
bump();
}
if (pushBank) {
_setStatus('Updating bank txs…');
// Other devices may have deleted test txs — learn that before push.
await _pullAndApplyTxDeletes(service);
await _flushPendingTxDeletes(service);
await _pushTxDeletes(service);
try {
final tombs = List<BankTransaction>.of(_bank.pendingRemoteDeletes);
final summary = await service.pushTransactions(
_bank.transactions,
deleteTombs: tombs,
progressStart: done / total,
progressEnd: (done + 1) / total,
onProgress: _setProgress,
onStatus: _setStatus,
);
parts.add(summary);
} catch (error) {
debugPrint('SyncController: bank tx push skipped ($error)');
_pushBankPending = true;
}
bump();
}
_setProgress(1.0);
_lastSyncedAt = DateTime.now();
@@ -588,6 +676,7 @@ class SyncController extends ChangeNotifier {
_uiNotifyThrottle?.cancel();
_auth.removeListener(_onAuthChanged);
_bank.onAfterSuccessfulLoad = null;
_bank.onPendingRemoteDeletesChanged = null;
_meta.onPersisted = null;
_prefs.onFavouritesPersisted = null;
_prefs.onHomeWidgetsPersisted = null;
+51 -9
View File
@@ -722,6 +722,25 @@ class TxMetaController extends ChangeNotifier {
_schedulePersist(invalidateLabels: false);
}
/// Move per-tx annotations when an admin test transaction's id changes.
Future<void> rekeyTransaction(String fromId, String toId) async {
if (fromId == toId || fromId.isEmpty || toId.isEmpty) return;
final stored = _byId.remove(fromId);
if (stored != null) {
_byId[toId] = stored;
}
_labelIdsByTxCache = null;
_schedulePersist(invalidateLabels: true);
}
/// Drop per-tx annotations for a deleted admin test transaction.
Future<void> clearTransactionMeta(String txId) async {
if (txId.isEmpty) return;
if (_byId.remove(txId) == null) return;
_labelIdsByTxCache = null;
_schedulePersist(invalidateLabels: true);
}
Future<void> setNotes(
BankTransaction tx,
String notes, {
@@ -800,6 +819,7 @@ class TxMetaController extends ChangeNotifier {
List<BankTransaction> txs,
String query, {
Set<String> labelIds = const {},
LabelMatchMode labelMatch = LabelMatchMode.and,
}) {
final needle = query.trim().toLowerCase();
final hasText = needle.isNotEmpty;
@@ -809,7 +829,15 @@ class TxMetaController extends ChangeNotifier {
final labelIndex = _labelById;
return [
for (final tx in txs)
if (_matchesSearch(tx, needle, hasText, labelIds, hasLabels, labelIndex))
if (_matchesSearch(
tx,
needle,
hasText,
labelIds,
hasLabels,
labelMatch,
labelIndex,
))
tx,
];
}
@@ -820,10 +848,11 @@ class TxMetaController extends ChangeNotifier {
bool hasText,
Set<String> labelIds,
bool hasLabels,
LabelMatchMode labelMatch,
Map<String, TxLabel> labelIndex,
) {
final meta = metaFor(tx);
if (hasLabels && !_matchesLabelFilter(meta, labelIds)) {
if (hasLabels && !_matchesLabelFilter(meta, labelIds, labelMatch)) {
return false;
}
if (!hasText) return true;
@@ -838,20 +867,33 @@ class TxMetaController extends ChangeNotifier {
return false;
}
/// AND filter: every selected label must be on the tx.
/// AND: every selected label must be on the tx.
/// OR: at least one selected label (or unlabeled, if that filter is set).
///
/// Uncategorized alone matches unlabeled txs. Uncategorized combined with
/// other labels matches nothing (a tx cannot be both).
bool _matchesLabelFilter(TxMeta meta, Set<String> labelIds) {
/// Uncategorized alone matches unlabeled txs. Uncategorized + others with
/// AND matches nothing; with OR matches unlabeled or any of the labels.
bool _matchesLabelFilter(
TxMeta meta,
Set<String> labelIds,
LabelMatchMode mode,
) {
final wantUncategorized = labelIds.contains(kUncategorizedFilterId);
final required = <String>[
for (final id in labelIds)
if (id != kUncategorizedFilterId) id,
];
if (wantUncategorized) {
if (required.isNotEmpty) return false;
return !meta.hasLabel;
if (required.isEmpty) {
if (wantUncategorized) return !meta.hasLabel;
return true;
}
if (mode == LabelMatchMode.or) {
if (wantUncategorized && !meta.hasLabel) return true;
for (final id in required) {
if (meta.labelIds.contains(id)) return true;
}
return false;
}
if (wantUncategorized) return false;
for (final id in required) {
if (!meta.labelIds.contains(id)) return false;
}
+89 -1
View File
@@ -1,6 +1,8 @@
/// Signed-in account details, sync status, bank link, and sign-out.
library;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
@@ -10,11 +12,26 @@ import '../providers/sync_provider.dart';
import '../providers/tx_meta_provider.dart';
import '../utils/connect_bank.dart';
import '../utils/constants.dart';
import '../widgets/admin_create_transaction_dialog.dart';
import '../widgets/responsive_body.dart';
class AccountScreen extends StatelessWidget {
class AccountScreen extends StatefulWidget {
const AccountScreen({super.key});
@override
State<AccountScreen> createState() => _AccountScreenState();
}
class _AccountScreenState extends State<AccountScreen> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
unawaited(context.read<AuthController>().refreshSession());
});
}
@override
Widget build(BuildContext context) {
final auth = context.watch<AuthController>();
@@ -62,6 +79,24 @@ class AccountScreen extends StatelessWidget {
),
),
),
if (auth.isAdmin)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Chip(
avatar: Icon(
Icons.shield_outlined,
size: 16,
color: colors.onSecondaryContainer,
),
label: const Text('Admin'),
visualDensity: VisualDensity.compact,
backgroundColor: colors.secondaryContainer,
labelStyle: theme.textTheme.labelMedium?.copyWith(
color: colors.onSecondaryContainer,
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(height: 24),
Card(
child: Column(
@@ -91,6 +126,59 @@ class AccountScreen extends StatelessWidget {
),
),
const SizedBox(height: 16),
Card(
child: ListTile(
leading: Icon(
Icons.add_card_outlined,
color: auth.isAdmin ? null : colors.onSurfaceVariant,
),
title: const Text('Create test transaction'),
subtitle: Text(
auth.isAdmin
? 'Admin · saved locally and synced to PocketBase'
: 'Admin only · enable is_admin on your usersapp user in PocketBase, then sign out and back in',
),
trailing: auth.isAdmin
? const Icon(Icons.chevron_right)
: Icon(
Icons.lock_outline,
color: colors.onSurfaceVariant,
),
onTap: () async {
if (!auth.isAdmin) {
await auth.refreshSession();
if (!context.mounted) return;
if (!context.read<AuthController>().isAdmin) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Not an admin yet. In PocketBase Admin → '
'usersapp → your user → set is_admin = true, '
'then sign out and sign in again.',
),
),
);
return;
}
}
final tx = await showAdminCreateTransactionDialog(context);
if (tx == null || !context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Created “${tx.description}” · '
'${tx.amount.toStringAsFixed(2)} ${tx.currency}',
),
),
);
final sync = context.read<SyncController>();
if (sync.canSync && !sync.isSyncing) {
unawaited(sync.syncNow());
}
},
),
),
const SizedBox(height: 16),
Card(
child: ListTile(
leading: Icon(
+42 -21
View File
@@ -9,7 +9,7 @@ import '../models/transaction_meta.dart';
import '../providers/bank_provider.dart';
import '../providers/preferences_provider.dart';
import '../providers/tx_meta_provider.dart';
import '../screens/transaction_detail_screen.dart';
import '../screens/transactions_screen.dart';
import '../utils/app_theme.dart';
import '../utils/helpers.dart';
import '../utils/look_ahead.dart';
@@ -337,17 +337,6 @@ class _LookAheadScreenState extends State<LookAheadScreen> {
),
],
),
const SizedBox(height: 4),
Text(
items.isEmpty
? 'Create a spending from a transaction, or tap New.'
: '${items.length} spending${items.length == 1 ? '' : 's'} · '
'projected income ${formatMoney(income, currency)} · '
'expenses ${formatMoney(expenses, currency)}.',
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
const SizedBox(height: 10),
Row(
children: [
@@ -622,6 +611,46 @@ class _TemplateTile extends StatelessWidget {
return null;
}
void _openTransactions(BuildContext context) {
final labelIds = item.labelIds.toSet();
SimilarMatchCriteria? similar;
TxFlowFilter? flow;
String? query;
if (labelIds.isEmpty) {
final tx = _sourceTx;
if (tx != null) {
// Same matching as Look ahead / apply-to-similar for this source tx.
similar = SimilarMatchCriteria(
pattern: defaultSimilarPattern(tx.description),
flow: tx.amount < 0
? TxFlowFilter.expense
: tx.amount > 0
? TxFlowFilter.income
: TxFlowFilter.all,
);
flow = similar.flow;
} else if (template != null && template!.merchantKey.isNotEmpty) {
query = template!.merchantKey;
} else {
query = item.description;
}
}
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => TransactionsScreen(
initialLabelIds: labelIds,
initialLabelMatch: LabelMatchMode.or,
initialQuery: query,
initialFlow: flow,
initialSimilarMatch: similar,
initialSearchInMonthOnly: false,
),
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -658,15 +687,7 @@ class _TemplateTile extends StatelessWidget {
color: income ? AppTheme.accent : AppTheme.expense,
),
),
onTap: () {
final tx = _sourceTx;
if (tx == null) return;
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => TransactionDetailScreen(tx: tx),
),
);
},
onTap: () => _openTransactions(context),
);
}
}
+94 -26
View File
@@ -474,7 +474,19 @@ class _OverviewScreenState extends State<OverviewScreen> {
),
);
},
onMonthTap: (month) => _openPeriod(context, month),
onMonthTap: (month, {labelId, flow}) => _openPeriod(
context,
month,
labelId: labelId,
labelIds: {
for (final id in favourite.labelIds) id,
},
flow: flow ??
(favourite.metric == OverviewMetricMode.labels
? favourite.flow
: null),
periodMode: favourite.period,
),
);
}
@@ -590,7 +602,13 @@ class _OverviewScreenState extends State<OverviewScreen> {
),
);
},
onMonthTap: (month) => _openPeriod(context, month),
onMonthTap: (month, {labelId, flow}) => _openPeriod(
context,
month,
labelId: labelId,
flow: flow ??
(_metric == OverviewMetricMode.labels ? _labelFlow : null),
),
),
const SizedBox(height: 14),
if (_metric == OverviewMetricMode.flow) ...[
@@ -628,11 +646,11 @@ class _OverviewScreenState extends State<OverviewScreen> {
currency,
),
label: switch (_labelFlow) {
TxFlowFilter.income => 'Labeled income · $_periodTitle',
TxFlowFilter.expense => 'Labeled spend · $_periodTitle',
TxFlowFilter.income => 'Income · $_periodTitle',
TxFlowFilter.expense => 'Spend · $_periodTitle',
TxFlowFilter.all => _labelInvertChart
? 'Labeled net (expense view) · $_periodTitle'
: 'Labeled net · $_periodTitle',
? 'Net (expense view) · $_periodTitle'
: 'Net · $_periodTitle',
},
),
],
@@ -739,21 +757,28 @@ class _OverviewScreenState extends State<OverviewScreen> {
BuildContext context,
DateTime period, {
String? labelId,
Set<String>? labelIds,
TxFlowFilter? flow,
OverviewPeriodMode? periodMode,
}) {
final yearly = _period == OverviewPeriodMode.yearly;
final mode = periodMode ?? _period;
final yearly = mode == OverviewPeriodMode.yearly;
final initial = yearly ? DateTime(period.year, 12) : period;
final labelIds = labelId != null
final resolvedLabelIds = labelId != null
? {labelId}
: {
// Open with the same labels currently shown on the chart.
for (final id in _includedLabelIds) id,
};
: (labelIds ??
{
// Open with the same labels currently shown on the chart.
for (final id in _includedLabelIds) id,
});
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => TransactionsScreen(
initialMonth: initial,
initialLabelIds: labelIds,
initialSearchInMonthOnly: !yearly && labelIds.isNotEmpty,
initialLabelIds: resolvedLabelIds,
initialLabelMatch: LabelMatchMode.or,
initialFlow: flow,
initialSearchInMonthOnly: !yearly && resolvedLabelIds.isNotEmpty,
initialYear: yearly ? period.year : null,
),
),
@@ -1181,7 +1206,11 @@ class _ChartCard extends StatelessWidget {
final int? includedLabelCount;
final int availableLabelCount;
final void Function(TxLabel label) onLabelTap;
final void Function(DateTime month) onMonthTap;
final void Function(
DateTime month, {
String? labelId,
TxFlowFilter? flow,
}) onMonthTap;
final ValueChanged<OverviewPeriodMode>? onPeriodModeChanged;
final VoidCallback? onEdit;
@@ -1276,7 +1305,7 @@ class _ChartCard extends StatelessWidget {
runSpacing: 2,
alignment: WrapAlignment.end,
children: [
for (final row in labelSpend.take(compact ? 3 : 5))
for (final row in labelSpend.take(6))
GestureDetector(
onTap: () => onLabelTap(row.label),
child: _LegendDot(
@@ -1285,7 +1314,7 @@ class _ChartCard extends StatelessWidget {
compact: compact,
),
),
if (labelSpend.length > (compact ? 3 : 5))
if (labelSpend.length > 6)
_LegendDot(
color: colors.outline,
label: 'Other',
@@ -1528,6 +1557,7 @@ class _ChartCard extends StatelessWidget {
monthly: monthly,
currency: currency,
period: period,
onMonthTap: onMonthTap,
)
: _LabelMonthBars(
months: months,
@@ -1553,12 +1583,18 @@ class _FlowBars extends StatelessWidget {
required this.monthly,
required this.currency,
required this.period,
required this.onMonthTap,
});
final List<DateTime> months;
final Map<DateTime, _MonthBucket> monthly;
final String currency;
final OverviewPeriodMode period;
final void Function(
DateTime month, {
String? labelId,
TxFlowFilter? flow,
}) onMonthTap;
@override
Widget build(BuildContext context) {
@@ -1593,6 +1629,19 @@ class _FlowBars extends StatelessWidget {
maxY: safeMax,
groupsSpace: period == OverviewPeriodMode.yearly ? 16 : 10,
barTouchData: BarTouchData(
touchCallback: (event, response) {
if (event is! FlTapUpEvent) return;
final spot = response?.spot;
if (spot == null) return;
final index = spot.touchedBarGroupIndex;
if (index < 0 || index >= months.length) return;
final rodIndex = spot.touchedRodDataIndex;
// Rods: 0 = expense, 1 = income.
final flow = rodIndex == 1
? TxFlowFilter.income
: TxFlowFilter.expense;
onMonthTap(months[index], flow: flow);
},
touchTooltipData: BarTouchTooltipData(
getTooltipItem: (group, groupIndex, rod, rodIndex) {
final month = months[group.x.toInt()];
@@ -1708,7 +1757,7 @@ class _LabelMonthBars extends StatelessWidget {
required this.onMonthTap,
});
static const _maxSeriesLabels = 5;
static const _maxSeriesLabels = 6;
final List<DateTime> months;
final List<_LabelSpend> labelSpend;
@@ -1717,7 +1766,11 @@ class _LabelMonthBars extends StatelessWidget {
final OverviewPeriodMode period;
final LabelChartBarStyle barStyle;
final bool invertChart;
final void Function(DateTime month) onMonthTap;
final void Function(
DateTime month, {
String? labelId,
TxFlowFilter? flow,
}) onMonthTap;
double _plot(double value) => invertChart ? -value : value;
@@ -1804,12 +1857,12 @@ class _LabelMonthBars extends StatelessWidget {
final rodWidth = stacked
? (period == OverviewPeriodMode.yearly ? 18.0 : 14.0)
: period == OverviewPeriodMode.yearly
? (seriesCount <= 3 ? 12.0 : 8.0)
? (seriesCount <= 3 ? 12.0 : seriesCount <= 6 ? 8.0 : 6.0)
: (seriesCount <= 3
? 7.0
: seriesCount <= 5
? 5.0
: 4.0);
: seriesCount <= 6
? 4.5
: 3.5);
List<BarChartRodData> rodsFor(DateTime month) {
final bucket =
@@ -1895,9 +1948,24 @@ class _LabelMonthBars extends StatelessWidget {
barTouchData: BarTouchData(
touchCallback: (event, response) {
if (event is! FlTapUpEvent) return;
final index = response?.spot?.touchedBarGroupIndex;
if (index == null || index < 0 || index >= months.length) return;
onMonthTap(months[index]);
final spot = response?.spot;
if (spot == null) return;
final index = spot.touchedBarGroupIndex;
if (index < 0 || index >= months.length) return;
String? labelId;
if (stacked) {
final stackIdx = spot.touchedStackItemIndex;
if (stackIdx >= 0 && stackIdx < topLabels.length) {
labelId = topLabels[stackIdx].label.id;
}
} else {
final rodIdx = spot.touchedRodDataIndex;
if (rodIdx >= 0 && rodIdx < topLabels.length) {
labelId = topLabels[rodIdx].label.id;
}
// Last rod may be "Other" — open month with chart labels only.
}
onMonthTap(months[index], labelId: labelId);
},
touchTooltipData: BarTouchTooltipData(
getTooltipItem: (group, groupIndex, rod, rodIndex) {
+109 -9
View File
@@ -6,10 +6,12 @@ import 'package:provider/provider.dart';
import '../models/bank.dart';
import '../models/transaction_meta.dart';
import '../providers/auth_provider.dart';
import '../providers/bank_provider.dart';
import '../providers/tx_meta_provider.dart';
import '../utils/app_theme.dart';
import '../utils/helpers.dart';
import '../widgets/admin_create_transaction_dialog.dart';
import '../widgets/label_parent_picker.dart';
import '../widgets/recurring_template_sheet.dart';
import '../widgets/responsive_body.dart';
@@ -26,6 +28,7 @@ class TransactionDetailScreen extends StatefulWidget {
}
class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
late BankTransaction _tx;
late final TextEditingController _notesController;
late final TextEditingController _labelSearchController;
late SimilarMatchCriteria _matchCriteria;
@@ -41,11 +44,12 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
@override
void initState() {
super.initState();
_tx = widget.tx;
final meta = context.read<TxMetaController>();
final notes = meta.metaFor(widget.tx).notes;
final notes = meta.metaFor(_tx).notes;
_notesController = TextEditingController(text: notes);
_labelSearchController = TextEditingController();
final tx = widget.tx;
final tx = _tx;
_matchCriteria = SimilarMatchCriteria(
pattern: defaultSimilarPattern(tx.description),
flow: tx.amount < 0
@@ -63,7 +67,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
if (!mounted) return;
final all = context.read<BankController>().transactions;
final count = context.read<TxMetaController>().countSimilar(
widget.tx,
_tx,
all,
criteria: _matchCriteria,
);
@@ -88,14 +92,14 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
List<BankTransaction> _similarScope(TxMetaController meta) {
final all = context.read<BankController>().transactions;
if (!_applyToSimilar) return const [];
return meta.similarTo(widget.tx, all, criteria: _matchCriteria);
return meta.similarTo(_tx, all, criteria: _matchCriteria);
}
Future<void> _editMatchCriteria() async {
final all = context.read<BankController>().transactions;
final result = await showSimilarMatchDialog(
context,
prototype: widget.tx,
prototype: _tx,
all: all,
initial: _matchCriteria,
);
@@ -138,7 +142,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
final similar = _similarScope(meta);
final count = similar.isEmpty ? 1 : similar.length;
await meta.setNotes(
widget.tx,
_tx,
_notesController.text,
applyToSimilar: similar,
matchPattern: _pattern,
@@ -180,7 +184,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
() async {
final meta = context.read<TxMetaController>();
final similar = toMatched ? _similarScope(meta) : const <BankTransaction>[];
final targets = similar.isEmpty ? [widget.tx] : similar;
final targets = similar.isEmpty ? [_tx] : similar;
await meta.setLabelsForMany(
targets,
_draftLabelIds.toList(growable: false),
@@ -188,7 +192,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
if (!mounted) return;
setState(() {
_labelsDirty = false;
_draftLabelIds = meta.metaFor(widget.tx).labelIds.toSet();
_draftLabelIds = meta.metaFor(_tx).labelIds.toSet();
});
final count = targets.length;
ScaffoldMessenger.of(context).showSnackBar(
@@ -291,9 +295,79 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
await context.read<TxMetaController>().removeLabel(label.id);
}
Future<void> _editManualTransaction() async {
final updated = await showAdminCreateTransactionDialog(
context,
existing: _tx,
);
if (updated == null || !mounted) return;
final meta = context.read<TxMetaController>();
if (updated.id != _tx.id) {
await meta.rekeyTransaction(_tx.id, updated.id);
}
setState(() {
_tx = updated;
_matchCriteria = SimilarMatchCriteria(
pattern: defaultSimilarPattern(updated.description),
flow: updated.amount < 0
? TxFlowFilter.expense
: updated.amount > 0
? TxFlowFilter.income
: TxFlowFilter.all,
);
_draftLabelIds = meta.metaFor(updated).labelIds.toSet();
_labelsDirty = false;
_similarReady = false;
_similarCount = 0;
});
_refreshSimilarCount();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Test transaction updated')),
);
}
Future<void> _deleteManualTransaction() async {
final ok = await showDialog<bool>(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Delete test transaction?'),
content: const Text(
'This removes the transaction from this device. The remote copy is '
'deleted on the next PocketBase sync.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Delete'),
),
],
);
},
);
if (ok != true || !mounted) return;
final id = _tx.id;
final bank = context.read<BankController>();
final meta = context.read<TxMetaController>();
final messenger = ScaffoldMessenger.of(context);
final navigator = Navigator.of(context);
await bank.deleteManualTransaction(_tx);
await meta.clearTransactionMeta(id);
if (!mounted) return;
navigator.pop();
messenger.showSnackBar(
const SnackBar(content: Text('Test transaction deleted')),
);
}
@override
Widget build(BuildContext context) {
final tx = widget.tx;
final tx = _tx;
final metaController = context.watch<TxMetaController>();
final meta = metaController.metaFor(tx);
final similarCount = _similarCount;
@@ -317,11 +391,37 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
if (keep.contains(entry.label.id)) entry,
];
}();
final canEditManual =
context.watch<AuthController>().isAdmin && tx.isManual;
return Scaffold(
appBar: AppBar(
title: const Text('Transaction'),
actions: [
if (canEditManual)
PopupMenuButton<String>(
enabled: !_busy,
onSelected: (value) {
if (value == 'edit') {
_editManualTransaction();
} else if (value == 'delete') {
_deleteManualTransaction();
}
},
itemBuilder: (context) => [
const PopupMenuItem(
value: 'edit',
child: Text('Edit test transaction'),
),
PopupMenuItem(
value: 'delete',
child: Text(
'Delete',
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
],
),
if (_dirty)
TextButton(
onPressed: _busy ? null : _saveNotes,
+42 -32
View File
@@ -9,7 +9,6 @@ import 'package:provider/provider.dart';
import '../models/bank.dart';
import '../models/transaction_meta.dart';
import '../providers/bank_provider.dart';
import '../providers/preferences_provider.dart';
import '../providers/tx_meta_provider.dart';
import '../utils/app_theme.dart';
import '../utils/connect_bank.dart';
@@ -17,7 +16,6 @@ import '../utils/helpers.dart';
import '../utils/navigation.dart';
import '../utils/tx_calendar.dart';
import '../widgets/empty_state.dart';
import '../widgets/home_widgets_sheet.dart';
import '../widgets/label_filter_dialog.dart';
import '../widgets/loading_view.dart';
import '../widgets/responsive_body.dart';
@@ -30,11 +28,13 @@ class TransactionsScreen extends StatefulWidget {
super.key,
this.initialMonth,
this.initialLabelIds = const {},
this.initialLabelMatch = LabelMatchMode.and,
this.initialSearchInMonthOnly,
this.initialYear,
this.initialQuery,
this.initialFlow,
this.initialAmountRange,
this.initialSimilarMatch,
});
/// When set, opens on this calendar month instead of the current month.
@@ -43,6 +43,9 @@ class TransactionsScreen extends StatefulWidget {
/// Pre-select these label filters (e.g. from overview history).
final Set<String> initialLabelIds;
/// AND vs OR for [initialLabelIds] (and later filter edits).
final LabelMatchMode initialLabelMatch;
/// When set, overrides the default "search in month" checkbox.
final bool? initialSearchInMonthOnly;
@@ -55,6 +58,9 @@ class TransactionsScreen extends StatefulWidget {
final TxFlowFilter? initialFlow;
final TxAmountRange? initialAmountRange;
/// Match txs the same way as “apply to similar” / Look ahead transaction source.
final SimilarMatchCriteria? initialSimilarMatch;
@override
State<TransactionsScreen> createState() => _TransactionsScreenState();
}
@@ -68,6 +74,8 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
DateTime? _selectedDay;
late bool _searchInMonthOnly;
late final Set<String> _labelFilters;
late LabelMatchMode _labelMatch;
SimilarMatchCriteria? _similarMatch;
int? _yearFilter;
var _showCalendar = false;
var _flowFilter = TxFlowFilter.all;
@@ -89,6 +97,8 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
_month = start.isAfter(now) ? now : start;
}
_labelFilters = Set<String>.of(widget.initialLabelIds);
_labelMatch = widget.initialLabelMatch;
_similarMatch = widget.initialSimilarMatch;
// Default to current month so the list, navigator, and filter popup agree.
_searchInMonthOnly = widget.initialSearchInMonthOnly ?? true;
_yearFilter = widget.initialYear;
@@ -98,6 +108,11 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
if (initialQuery.isNotEmpty) {
_searchController.text = initialQuery;
_activeQuery = initialQuery;
} else if (_similarMatch != null &&
_similarMatch!.pattern.trim().isNotEmpty) {
// Show the similar pattern in the search field for context; filtering
// uses [txMatchesSimilarCriteria], not plain text contains.
_searchController.text = _similarMatch!.pattern;
}
}
@@ -109,16 +124,23 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
}
bool get _isSearching =>
_activeQuery.trim().isNotEmpty || _labelFilters.isNotEmpty;
_activeQuery.trim().isNotEmpty ||
_labelFilters.isNotEmpty ||
_similarMatch != null;
bool get _hasListFilters =>
_labelFilters.isNotEmpty ||
_flowFilter != TxFlowFilter.all ||
_amountRange.isActive;
_amountRange.isActive ||
_similarMatch != null;
bool _matchesExtraFilters(BankTransaction tx, TxMetaController meta) {
if (!txMatchesFlow(tx, _flowFilter)) return false;
if (!txMatchesAmountRange(tx, _amountRange)) return false;
final similar = _similarMatch;
if (similar != null && !txMatchesSimilarCriteria(tx, similar)) {
return false;
}
return true;
}
@@ -147,6 +169,11 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
final trimmed = value.trim();
_searchDebounceTimer?.cancel();
// Editing the box leaves “similar match” mode and uses plain text search.
if (_similarMatch != null) {
setState(() => _similarMatch = null);
}
if (trimmed.length >= _minLiveSearchChars) {
// TextField updates via the controller; only rebuild the list after debounce.
_searchDebounceTimer = Timer(_searchDebounce, () {
@@ -165,13 +192,19 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
void _onSearchSubmitted(String value) {
_searchDebounceTimer?.cancel();
setState(() => _activeQuery = value.trim());
setState(() {
_similarMatch = null;
_activeQuery = value.trim();
});
}
void _clearSearch() {
_searchDebounceTimer?.cancel();
_searchController.clear();
setState(() => _activeQuery = '');
setState(() {
_activeQuery = '';
_similarMatch = null;
});
}
Future<void> _pickFilters(List<TxLabel> available) async {
@@ -183,6 +216,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
currentMonth: _month,
initial: TransactionFilterSelection(
labelIds: Set<String>.of(_labelFilters),
labelMatch: _labelMatch,
flow: _flowFilter,
amountRange: _amountRange,
query: _activeQuery,
@@ -195,6 +229,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
_labelFilters
..clear()
..addAll(result.labelIds);
_labelMatch = result.labelMatch;
_flowFilter = result.flow;
_amountRange = result.amountRange;
_searchInMonthOnly = result.monthOnly;
@@ -240,27 +275,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
);
}
Future<void> _saveAsHomeWidget() async {
final preferences = context.read<PreferencesController>();
final created = await composeHomeFilterWidget(
context,
initialFilter: TransactionFilterSelection(
labelIds: Set<String>.of(_labelFilters),
flow: _flowFilter,
amountRange: _amountRange,
query: _activeQuery,
monthOnly: _searchInMonthOnly,
),
skipFilterDialog: true,
);
if (created == null) return;
await preferences.addHomeFilterWidget(created);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Added “${created.name}” to Home')),
);
}
@override
Widget build(BuildContext context) {
final bank = context.watch<BankController>();
@@ -269,11 +283,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
appBar: AppBar(
title: const Text('Transactions'),
actions: [
IconButton(
tooltip: 'Save as Home widget',
onPressed: _saveAsHomeWidget,
icon: const Icon(Icons.dashboard_customize_outlined),
),
...bankAppBarActions(
context: context,
onRefresh: bank.refresh,
@@ -386,6 +395,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
searchPool,
_activeQuery,
labelIds: _labelFilters,
labelMatch: _labelMatch,
))
if (_matchesExtraFilters(tx, metaController)) tx,
];
+196 -22
View File
@@ -25,20 +25,6 @@ List<BankTransaction> mergeBankTransactionLists(
return mergeTransactions(local, remote);
}
/// Union Overview favourites by client id (local wins on conflict).
List<OverviewFavourite> mergeOverviewFavourites(
List<OverviewFavourite> local,
List<OverviewFavourite> remote,
) {
final byId = <String, OverviewFavourite>{
for (final fav in remote) fav.id: fav,
};
for (final fav in local) {
byId[fav.id] = fav;
}
return byId.values.toList(growable: false);
}
/// Union-merge so neither device loses annotations on first sync.
TxMetaStoreData mergeTxMetaStores(TxMetaStoreData a, TxMetaStoreData b) {
final byId = <String, TxMeta>{...a.byId};
@@ -485,6 +471,8 @@ class PbSyncService {
),
invertExpensePerspective:
r.getBoolValue('invert_expense_perspective'),
updatedAt: _recordUpdatedAtMs(r),
deleted: r.getBoolValue('deleted'),
),
);
}
@@ -534,6 +522,7 @@ class PbSyncService {
},
'budgetAverageMonths': r.getIntValue('budget_average_months', 3),
'labelIds': _jsonStringList(r.get<dynamic>('label_ids')),
'labelMatch': r.getStringValue('label_match'),
'flow': r.getStringValue('flow'),
'amountRange': rangeRaw is Map
? Map<String, dynamic>.from(rangeRaw)
@@ -543,6 +532,8 @@ class PbSyncService {
'showAmountIn': r.getBoolValue('show_amount_in', true),
'showAmountOut': r.getBoolValue('show_amount_out', true),
'showCount': r.getBoolValue('show_count', true),
'updatedAt': _recordUpdatedAtMs(r),
'deleted': r.getBoolValue('deleted'),
}),
);
}
@@ -597,10 +588,14 @@ class PbSyncService {
await _syncAppPrefs(userId, filter, prefs);
}
/// Upserts local bank txs to PocketBase. Does **not** delete remote rows
/// (partial local caches must not wipe another device).
/// Upserts local bank txs to PocketBase.
///
/// Also garbage-collects remote rows that are:
/// - admin test rows (`is_manual` / `·#…` stamp) no longer local, or
/// - listed in [deleteTombs] (local delete queue).
Future<String> pushTransactions(
List<BankTransaction> local, {
List<BankTransaction> deleteTombs = const [],
void Function(double progress)? onProgress,
void Function(String message)? onStatus,
double progressStart = 0.0,
@@ -629,10 +624,19 @@ class PbSyncService {
final ops = <_BatchOp>[];
var skipped = 0;
final seen = <String>{};
final tombIds = {
for (final t in deleteTombs)
if (_clip(t.id, 2000).isNotEmpty) _clip(t.id, 2000),
};
for (final tx in local) {
final syncId = _clip(tx.id, 2000);
if (syncId.isEmpty || !seen.add(syncId)) continue;
// Never re-upsert a tombstoned row in the same pass.
if (tombIds.contains(syncId) ||
deleteTombs.any(tx.matchesForDelete)) {
continue;
}
final body = <String, dynamic>{
'user': userId,
'tx_id': syncId,
@@ -647,6 +651,9 @@ class PbSyncService {
8,
),
'pending': tx.pending,
// Only send when true so servers without the migration still accept
// normal bank/CSV upserts. Test rows are also detected via ·# stamp.
if (tx.isManual) 'is_manual': true,
};
final remote = existing[syncId];
if (remote == null) {
@@ -658,11 +665,25 @@ class PbSyncService {
}
}
// Remove admin test / tombstoned rows that this device no longer has.
var deletes = 0;
for (final entry in existing.entries) {
if (seen.contains(entry.key)) continue;
final remoteTx = _bankTxFromRecord(entry.value);
final tombHit = tombIds.contains(entry.key) ||
(remoteTx != null && deleteTombs.any(remoteTx.matchesForDelete));
final orphanManual = _remoteLooksLikeManualTest(entry.value);
if (!tombHit && !orphanManual) continue;
ops.add(_BatchOp.delete(entry.value.id));
deletes++;
}
final creates = ops.where((o) => o.kind == _BatchOpKind.create).length;
final updates = ops.where((o) => o.kind == _BatchOpKind.update).length;
debugPrint(
'PbSyncService transactions: local=${local.length} '
'remote=${existing.length} create=$creates update=$updates skip=$skipped',
'remote=${existing.length} create=$creates update=$updates '
'delete=$deletes skip=$skipped',
);
onStatus?.call(
ops.isEmpty
@@ -676,8 +697,13 @@ class PbSyncService {
onStatus: onStatus,
);
return 'Bank txs: local ${local.length} → remote '
'${existing.length + creates} '
'(+$creates ~$updates · $skipped unchanged)';
'${existing.length + creates - deletes} '
'(+$creates ~$updates -$deletes · $skipped unchanged)';
}
bool _remoteLooksLikeManualTest(RecordModel r) {
if (r.getBoolValue('is_manual')) return true;
return RegExp(r' ·#\d+$').hasMatch(r.getStringValue('description'));
}
BankTransaction? _bankTxFromRecord(RecordModel r) {
@@ -698,6 +724,8 @@ class PbSyncService {
? 'EUR'
: r.getStringValue('currency'),
pending: r.getBoolValue('pending'),
isManual: r.getBoolValue('is_manual') ||
RegExp(r' ·#\d+$').hasMatch(description),
);
}
@@ -708,13 +736,126 @@ class PbSyncService {
String s => double.tryParse(s) ?? 0,
_ => 0.0,
};
final remoteManual = remote.getBoolValue('is_manual') ||
RegExp(r' ·#\d+$').hasMatch(remote.getStringValue('description'));
return remote.getStringValue('date') == tx.date &&
remote.getStringValue('description') ==
_clip(tx.description.isEmpty ? 'Unknown' : tx.description, 4000) &&
(remoteAmount * 100).round() == (tx.amount * 100).round() &&
remote.getStringValue('currency').toUpperCase() ==
tx.currency.toUpperCase() &&
remote.getBoolValue('pending') == tx.pending;
remote.getBoolValue('pending') == tx.pending &&
remoteManual == tx.isManual;
}
/// Deletes remote bank rows matching [tombstones] by tx_id or field fingerprint.
///
/// Returns the tombstones that matched at least one remote row (safe to clear).
Future<List<BankTransaction>> deleteTransactionsMatching(
List<BankTransaction> tombstones,
) async {
if (tombstones.isEmpty) return const [];
final userId = _userId;
final filter = 'user="$userId"';
final existing = await _fullList('transactions', filter);
final matchedTombs = <BankTransaction>[];
final ops = <_BatchOp>[];
final seenRecordIds = <String>{};
for (final r in existing) {
final remoteTx = _bankTxFromRecord(r);
if (remoteTx == null) continue;
for (final tomb in tombstones) {
final txId = r.getStringValue('tx_id');
final idHit = txId == _clip(tomb.id, 2000);
if (!idHit && !remoteTx.matchesForDelete(tomb)) continue;
if (!seenRecordIds.add(r.id)) break;
ops.add(_BatchOp.delete(r.id));
if (!matchedTombs.any(tomb.matchesForDelete)) {
matchedTombs.add(tomb);
}
break;
}
}
if (ops.isEmpty) {
debugPrint(
'PbSyncService deleteTransactionsMatching: 0 hits '
'for ${tombstones.length} tombstone(s)',
);
return const [];
}
await _runWriteOps('transactions', ops);
debugPrint(
'PbSyncService deleteTransactionsMatching: deleted ${ops.length} '
'for ${matchedTombs.length} tombstone(s)',
);
return matchedTombs;
}
/// Pull synced delete tombstones for admin test transactions.
Future<List<BankTransaction>> pullTxDeletes({
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Pulling deleted test txs…');
final records = await _fullList('tx_deletes', filter);
final out = <BankTransaction>[];
for (final r in records) {
final tx = _bankTxFromRecord(r);
if (tx == null) continue;
out.add(tx.copyWith(isManual: true));
}
debugPrint('PbSyncService pull: tx_deletes=${out.length}');
return out;
}
/// Upsert local delete tombstones. Never removes remote-only rows (union).
Future<String> pushTxDeletes(
List<BankTransaction> tombs, {
void Function(String message)? onStatus,
}) async {
if (tombs.isEmpty) return 'Tx deletes: nothing to push';
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Syncing deleted test txs…');
final existing = {
for (final r in await _fullList('tx_deletes', filter))
r.getStringValue('tx_id'): r,
};
final ops = <_BatchOp>[];
var skipped = 0;
final seen = <String>{};
for (final tomb in tombs) {
final syncId = _clip(tomb.id, 2000);
if (syncId.isEmpty || !seen.add(syncId)) continue;
final body = <String, dynamic>{
'user': userId,
'tx_id': syncId,
'date': _clip(tomb.date, 32),
'description': _clip(
tomb.description.isEmpty ? 'Unknown' : tomb.description,
4000,
),
'amount': tomb.amount,
'currency': _clip(
tomb.currency.isEmpty ? 'EUR' : tomb.currency.toUpperCase(),
8,
),
};
final remote = existing[syncId];
if (remote == null) {
ops.add(_BatchOp.create(body));
} else {
skipped++;
}
}
await _runWriteOps('tx_deletes', ops, onStatus: onStatus);
return 'Tx deletes: local ${tombs.length} (+${ops.length} · $skipped exist)';
}
Future<void> _runOne(String collection, _BatchOp op) {
@@ -881,6 +1022,12 @@ class PbSyncService {
filter =
'user="$userId" && tx_id="${key.replaceAll('"', '\\"')}"';
}
case 'tx_deletes':
final key = body['tx_id'];
if (userId != null && key is String) {
filter =
'user="$userId" && tx_id="${key.replaceAll('"', '\\"')}"';
}
}
if (filter == null) {
throw StateError('Cannot upsert $collection without filter');
@@ -1207,6 +1354,8 @@ class PbSyncService {
'flow': fav.flow.name,
'bar_style': fav.barStyle.name,
'invert_expense_perspective': fav.invertExpensePerspective,
'updated_at': fav.updatedAt,
'deleted': fav.deleted,
};
final remote = existing[clientId];
if (remote == null) {
@@ -1259,6 +1408,7 @@ class PbSyncService {
'budget_fixed_amount': w.budgetFixedAmount,
'budget_average_months': w.budgetAverageMonths,
'label_ids': w.labelIds,
'label_match': w.labelMatch.name,
'flow': w.flow.name,
'amount_range': {
if (w.amountRange.exact != null) 'exact': w.amountRange.exact,
@@ -1270,6 +1420,8 @@ class PbSyncService {
'show_amount_in': w.showAmountIn,
'show_amount_out': w.showAmountOut,
'show_count': w.showCount,
'updated_at': w.updatedAt,
'deleted': w.deleted,
};
final remote = existing[clientId];
if (remote == null) {
@@ -1375,7 +1527,9 @@ class PbSyncService {
remote.getStringValue('flow') == fav.flow.name &&
remote.getStringValue('bar_style') == fav.barStyle.name &&
remote.getBoolValue('invert_expense_perspective') ==
fav.invertExpensePerspective;
fav.invertExpensePerspective &&
remote.getBoolValue('deleted') == fav.deleted &&
_recordUpdatedAtMs(remote) == fav.updatedAt;
}
bool _homeFilterWidgetUnchanged(RecordModel remote, HomeFilterWidget w) {
@@ -1402,6 +1556,10 @@ class PbSyncService {
remote.getIntValue('budget_average_months', 3) ==
w.budgetAverageMonths &&
_sameIdList(remoteIds, w.labelIds) &&
(remote.getStringValue('label_match').isEmpty
? 'and'
: remote.getStringValue('label_match')) ==
w.labelMatch.name &&
remote.getStringValue('flow') == w.flow.name &&
asDouble(rangeMap['exact']) == w.amountRange.exact &&
asDouble(rangeMap['min']) == w.amountRange.min &&
@@ -1410,7 +1568,9 @@ class PbSyncService {
remote.getBoolValue('month_only') == w.monthOnly &&
remote.getBoolValue('show_amount_in', true) == w.showAmountIn &&
remote.getBoolValue('show_amount_out', true) == w.showAmountOut &&
remote.getBoolValue('show_count', true) == w.showCount;
remote.getBoolValue('show_count', true) == w.showCount &&
remote.getBoolValue('deleted') == w.deleted &&
_recordUpdatedAtMs(remote) == w.updatedAt;
}
bool _appPrefsUnchanged(RecordModel remote, AppCloudPrefs prefs) {
@@ -1423,6 +1583,20 @@ class PbSyncService {
remote.getIntValue('look_ahead_max_years', 5) ==
prefs.lookAheadMaxYears.clamp(1, 30);
}
/// Prefer custom `updated_at`, else PocketBase system `updated`.
int _recordUpdatedAtMs(RecordModel r) {
final raw = r.get<dynamic>('updated_at');
final custom = switch (raw) {
int n => n,
num n => n.round(),
String s => int.tryParse(s) ?? 0,
_ => 0,
};
if (custom > 0) return custom;
final system = DateTime.tryParse(r.getStringValue('updated'));
return system?.millisecondsSinceEpoch ?? 0;
}
}
RecurringTemplateSource _parseTemplateSource(String raw) {
+49 -18
View File
@@ -65,14 +65,7 @@ class BankCache {
'balanceType': balance!.balanceType,
},
'transactions': [
for (final tx in transactions)
{
'date': tx.date,
'description': tx.description,
'amount': tx.amount,
'currency': tx.currency,
'pending': tx.pending,
},
for (final tx in transactions) tx.toJson(),
],
};
@@ -258,16 +251,7 @@ class StorageService {
}
Future<void> saveImportedTransactions(List<BankTransaction> txs) async {
final encoded = [
for (final tx in txs)
{
'date': tx.date,
'description': tx.description,
'amount': tx.amount,
'currency': tx.currency,
'pending': tx.pending,
},
];
final encoded = [for (final tx in txs) tx.toJson()];
final json = await compute(jsonEncode, encoded);
await _prefs.setString(StorageKeys.importedTransactions, json);
}
@@ -276,6 +260,53 @@ class StorageService {
return _prefs.remove(StorageKeys.importedTransactions);
}
/// Tombstones for locally deleted bank txs awaiting remote removal.
///
/// Supports legacy string-id lists and full transaction JSON objects.
List<BankTransaction> loadPendingTxDeletes() {
final raw = _prefs.getString(StorageKeys.pendingTxDeletes);
if (raw == null || raw.isEmpty) return const [];
try {
final decoded = jsonDecode(raw);
if (decoded is! List) return const [];
final out = <BankTransaction>[];
for (final e in decoded) {
if (e is Map) {
out.add(BankTransaction.fromJson(Map<String, dynamic>.from(e)));
} else if (e is String && e.isNotEmpty) {
// Legacy id-only entry — match by id string only.
final parts = e.split('|');
if (parts.length >= 4) {
final amount = double.tryParse(parts[2]) ?? 0;
out.add(
BankTransaction(
date: parts[0],
currency: parts[1],
amount: amount,
description: parts.sublist(3).join('|'),
pending: false,
isManual: true,
),
);
}
}
}
return out;
} catch (_) {
return const [];
}
}
Future<void> savePendingTxDeletes(List<BankTransaction> txs) {
if (txs.isEmpty) {
return _prefs.remove(StorageKeys.pendingTxDeletes);
}
return _prefs.setString(
StorageKeys.pendingTxDeletes,
jsonEncode([for (final tx in txs) tx.toJson()]),
);
}
TxMetaStoreData loadTxMetaStore() {
final raw = _prefs.getString(StorageKeys.txMeta);
if (raw != null && raw.isNotEmpty) {
+16
View File
@@ -12,6 +12,22 @@ abstract final class AppTheme {
/// Soft rose for expenses / money out.
static const Color expense = Color(0xFFE07A7A);
/// Amber mid-stop for budget progress (between mint and rose).
static const Color budgetWarn = Color(0xFFE5A24A);
/// Budget chart fill: green when low → amber → red as usage rises.
static Color budgetProgressFill(double progress) {
final t = progress.clamp(0.0, 1.0);
if (t <= 0.55) {
// Stay mostly mint through ~half the budget.
return Color.lerp(accent, budgetWarn, (t / 0.55) * 0.45)!;
}
if (t <= 0.85) {
return Color.lerp(budgetWarn, expense, (t - 0.55) / 0.30)!;
}
return Color.lerp(expense, const Color(0xFFD94C4C), (t - 0.85) / 0.15)!;
}
/// Near-black charcoal scaffold (dark).
static const Color darkCanvas = Color(0xFF0B0D0C);
+3
View File
@@ -46,6 +46,9 @@ abstract final class StorageKeys {
static const bankCache = 'bank_cache_v1';
static const importedTransactions = 'imported_txs_v1';
/// Local bank tx_ids queued for PocketBase deletion (JSON string list).
static const pendingTxDeletes = 'pending_tx_deletes_v1';
/// Serialized PocketBase auth token + user record (separate from tx data).
static const pocketBaseAuth = 'pb_auth_v1';
+1
View File
@@ -69,6 +69,7 @@ List<BankTransaction> applyTransactionFilter({
pool,
filter.query,
labelIds: filter.labelIds,
labelMatch: filter.labelMatch,
))
if (txMatchesFlow(tx, filter.flow) &&
txMatchesAmountRange(tx, filter.amountRange))
@@ -0,0 +1,268 @@
/// Admin-only dialog to create or edit a local test bank transaction.
library;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../models/bank.dart';
import '../models/transaction_meta.dart';
import '../providers/bank_provider.dart';
import '../utils/helpers.dart';
Future<BankTransaction?> showAdminCreateTransactionDialog(
BuildContext context, {
BankTransaction? existing,
}) {
return showDialog<BankTransaction>(
context: context,
builder: (context) => _AdminCreateTransactionDialog(existing: existing),
);
}
String _stripManualStamp(String description) =>
description.replaceFirst(RegExp(r' ·#\d+$'), '');
class _AdminCreateTransactionDialog extends StatefulWidget {
const _AdminCreateTransactionDialog({this.existing});
final BankTransaction? existing;
@override
State<_AdminCreateTransactionDialog> createState() =>
_AdminCreateTransactionDialogState();
}
class _AdminCreateTransactionDialogState
extends State<_AdminCreateTransactionDialog> {
late DateTime _date;
late final TextEditingController _description;
late final TextEditingController _amount;
late final TextEditingController _currency;
late TxFlowFilter _flow;
late bool _pending;
var _saving = false;
String? _error;
bool get _editing => widget.existing != null;
@override
void initState() {
super.initState();
final existing = widget.existing;
if (existing != null) {
final parsed = DateTime.tryParse(existing.date) ?? DateTime.now();
_date = DateTime(parsed.year, parsed.month, parsed.day);
_description = TextEditingController(
text: _stripManualStamp(existing.description),
);
_amount = TextEditingController(
text: existing.amount.abs().toStringAsFixed(2),
);
_currency = TextEditingController(text: existing.currency);
_flow = existing.amount >= 0
? TxFlowFilter.income
: TxFlowFilter.expense;
_pending = existing.pending;
} else {
final now = DateTime.now();
_date = DateTime(now.year, now.month, now.day);
_description = TextEditingController(text: 'Test merchant');
_amount = TextEditingController(text: '12.50');
_currency = TextEditingController(text: 'EUR');
_flow = TxFlowFilter.expense;
_pending = false;
}
}
@override
void dispose() {
_description.dispose();
_amount.dispose();
_currency.dispose();
super.dispose();
}
Future<void> _pickDate() async {
final picked = await showDatePicker(
context: context,
initialDate: _date,
firstDate: DateTime(2015),
lastDate: DateTime.now().add(const Duration(days: 365)),
);
if (picked == null || !mounted) return;
setState(() => _date = DateTime(picked.year, picked.month, picked.day));
}
Future<void> _save() async {
final raw = _amount.text.trim().replaceAll(',', '.');
final parsed = double.tryParse(raw);
if (parsed == null || parsed <= 0) {
setState(() => _error = 'Enter a positive amount');
return;
}
final signed = _flow == TxFlowFilter.income ? parsed : -parsed;
setState(() {
_saving = true;
_error = null;
});
try {
final bank = context.read<BankController>();
final existing = widget.existing;
final BankTransaction tx;
if (existing != null) {
tx = await bank.updateManualTransaction(
previous: existing,
date: _date,
description: _description.text,
amount: signed,
currency: _currency.text,
pending: _pending,
);
} else {
tx = await bank.addManualTransaction(
date: _date,
description: _description.text,
amount: signed,
currency: _currency.text,
pending: _pending,
);
}
if (!mounted) return;
Navigator.pop(context, tx);
} catch (error) {
if (!mounted) return;
setState(() {
_saving = false;
_error = '$error';
});
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
title: Text(_editing ? 'Edit test transaction' : 'Create test transaction'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
_editing
? 'Updates this device and removes the old row on the next PocketBase sync.'
: 'Saved on this device and included in the next PocketBase sync.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 16),
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Date'),
subtitle: Text(formatDate(_date)),
trailing: const Icon(Icons.calendar_today_outlined, size: 20),
onTap: _saving ? null : _pickDate,
),
TextField(
controller: _description,
enabled: !_saving,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(
labelText: 'Description',
),
),
const SizedBox(height: 12),
SegmentedButton<TxFlowFilter>(
segments: const [
ButtonSegment(
value: TxFlowFilter.expense,
label: Text('Expense'),
icon: Icon(Icons.north_east, size: 16),
),
ButtonSegment(
value: TxFlowFilter.income,
label: Text('Income'),
icon: Icon(Icons.south_west, size: 16),
),
],
selected: {_flow},
onSelectionChanged: _saving
? null
: (selection) {
setState(() => _flow = selection.first);
},
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
flex: 2,
child: TextField(
controller: _amount,
enabled: !_saving,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
],
decoration: const InputDecoration(
labelText: 'Amount',
),
),
),
const SizedBox(width: 12),
Expanded(
child: TextField(
controller: _currency,
enabled: !_saving,
textCapitalization: TextCapitalization.characters,
decoration: const InputDecoration(
labelText: 'Currency',
),
),
),
],
),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Pending'),
value: _pending,
onChanged: _saving
? null
: (value) => setState(() => _pending = value),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
_error!,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.error,
),
),
),
],
),
),
actions: [
TextButton(
onPressed: _saving ? null : () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _saving ? null : _save,
child: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(_editing ? 'Save' : 'Create'),
),
],
);
}
}
+117 -66
View File
@@ -37,6 +37,7 @@ class HomeFilterWidgetCard extends StatelessWidget {
MaterialPageRoute<void>(
builder: (_) => TransactionsScreen(
initialLabelIds: filter.labelIds,
initialLabelMatch: filter.labelMatch,
initialSearchInMonthOnly:
widgetConfig.type == HomeWidgetType.budget || filter.monthOnly,
initialQuery: filter.query,
@@ -287,9 +288,80 @@ class _StatsBody extends StatelessWidget {
final spentOnly = widgetConfig.showAmountOut &&
!widgetConfig.showAmountIn &&
!widgetConfig.showCount;
final half = widgetConfig.halfWidth;
Widget metricsBlock({required bool alignEnd}) {
if (spentOnly) {
return Column(
crossAxisAlignment:
alignEnd ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
Text(
'Spent',
style: theme.textTheme.labelMedium?.copyWith(
color: colors.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(
formatMoney(metrics.amountOut, currency),
style: theme.textTheme.titleMedium?.copyWith(
color: AppTheme.expense,
fontWeight: FontWeight.w700,
height: 1.15,
),
),
],
);
}
return Wrap(
spacing: 16,
runSpacing: 8,
alignment: alignEnd ? WrapAlignment.end : WrapAlignment.start,
children: [
if (widgetConfig.showAmountIn)
_Metric(
label: 'In',
value: formatMoney(metrics.amountIn, currency),
color: AppTheme.accent,
),
if (widgetConfig.showAmountOut)
_Metric(
label: 'Spent',
value: formatMoney(metrics.amountOut, currency),
color: AppTheme.expense,
),
if (widgetConfig.showCount)
_Metric(
label: 'Transactions',
value: '${metrics.count}',
color: colors.primary,
),
],
);
}
// Avoid LayoutBuilder/Spacer/Expanded here: half-width rows use
// IntrinsicHeight, which cannot measure those widgets.
if (!half) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _CardHeader(
icon: widgetConfig.icon,
title: widgetConfig.name,
subtitle: _subtitleFor(widgetConfig),
),
),
const SizedBox(width: 12),
Flexible(
child: metricsBlock(alignEnd: true),
),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -298,50 +370,8 @@ class _StatsBody extends StatelessWidget {
title: widgetConfig.name,
subtitle: _subtitleFor(widgetConfig),
),
if (spentOnly) ...[
const SizedBox(height: 32),
Text(
'Spent',
style: theme.textTheme.labelMedium?.copyWith(
color: colors.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(
formatMoney(metrics.amountOut, currency),
style: theme.textTheme.titleMedium?.copyWith(
color: AppTheme.expense,
fontWeight: FontWeight.w700,
height: 1.15,
),
),
] else ...[
const SizedBox(height: 14),
Wrap(
spacing: 16,
runSpacing: 8,
children: [
if (widgetConfig.showAmountIn)
_Metric(
label: 'In',
value: formatMoney(metrics.amountIn, currency),
color: AppTheme.accent,
),
if (widgetConfig.showAmountOut)
_Metric(
label: 'Spent',
value: formatMoney(metrics.amountOut, currency),
color: AppTheme.expense,
),
if (widgetConfig.showCount)
_Metric(
label: 'Txs',
value: '${metrics.count}',
color: colors.primary,
),
],
),
],
SizedBox(height: spentOnly ? 32 : 14),
metricsBlock(alignEnd: false),
],
);
}
@@ -370,8 +400,11 @@ class _BudgetBody extends StatelessWidget {
widget: widgetConfig,
);
final progress = budget.progress.clamp(0.0, 1.0);
final over = budget.overBudget;
final fillColor = over ? colors.error : colors.primary;
final fillColor = budget.overBudget
? AppTheme.expense
: AppTheme.budgetProgressFill(
budget.target <= 0 ? 0 : progress,
);
// Grayish unfilled track (not green-tinted).
final trackColor = Color.alphaBlend(
colors.onSurface.withValues(alpha: 0.14),
@@ -497,24 +530,40 @@ class _BudgetBody extends StatelessWidget {
),
],
),
HomeWidgetChartStyle.pie || HomeWidgetChartStyle.ring => Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
capLine,
const SizedBox(height: 8),
spentLine,
],
),
HomeWidgetChartStyle.pie || HomeWidgetChartStyle.ring => half
// Stack on half cards so amounts never get crushed beside the ring
// (and avoid LayoutBuilder — half rows use IntrinsicHeight).
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
capLine,
const SizedBox(height: 6),
spentLine,
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: ringChart(size: 56),
),
],
)
: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
capLine,
const SizedBox(height: 6),
spentLine,
],
),
),
const SizedBox(width: 8),
ringChart(size: 68),
],
),
const SizedBox(width: 10),
ringChart(size: 68),
],
),
},
],
);
@@ -589,8 +638,9 @@ class _BudgetLegendLine extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
// Stretch to the parent width so Expanded+ellipsis can shrink safely
// (half-width ring rows can be very tight).
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 7,
@@ -600,11 +650,12 @@ class _BudgetLegendLine extends StatelessWidget {
shape: BoxShape.circle,
),
),
const SizedBox(width: 8),
Flexible(
const SizedBox(width: 6),
Expanded(
child: Text(
text,
maxLines: 1,
softWrap: false,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.labelMedium?.copyWith(
color: textColor,
+1
View File
@@ -55,6 +55,7 @@ Future<HomeFilterWidget?> composeHomeFilterWidget(
? HomeFilterWidget.fromFilter(name: 'Filter', filter: filter)
: existing.copyWith(
labelIds: filter.labelIds.toList(growable: false),
labelMatch: filter.labelMatch,
flow: filter.flow,
amountRange: filter.amountRange,
query: filter.query,
+33 -1
View File
@@ -15,6 +15,7 @@ import 'label_parent_picker.dart';
class TransactionFilterSelection {
const TransactionFilterSelection({
required this.labelIds,
this.labelMatch = LabelMatchMode.and,
this.flow = TxFlowFilter.all,
this.amountRange = const TxAmountRange(),
this.query = '',
@@ -22,6 +23,10 @@ class TransactionFilterSelection {
});
final Set<String> labelIds;
/// AND vs OR when more than one label is selected.
final LabelMatchMode labelMatch;
final TxFlowFilter flow;
final TxAmountRange amountRange;
final String query;
@@ -497,6 +502,7 @@ class _TransactionFilterDialog extends StatefulWidget {
class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
late final Set<String> _selected;
late LabelMatchMode _labelMatch;
late TxFlowFilter _flow;
late bool _monthOnly;
late final TextEditingController _queryController;
@@ -510,6 +516,7 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
super.initState();
final initial = widget.initial;
_selected = Set<String>.of(initial.labelIds);
_labelMatch = initial.labelMatch;
_flow = initial.flow;
_monthOnly = initial.monthOnly;
_queryController = TextEditingController(text: initial.query);
@@ -593,6 +600,7 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
context,
TransactionFilterSelection(
labelIds: Set<String>.of(_selected),
labelMatch: _labelMatch,
flow: _flow,
amountRange: _amountResult,
query: _queryController.text.trim(),
@@ -840,7 +848,10 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
),
onChanged: (_) => setState(() {}),
),
Row(
Wrap(
spacing: 0,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
TextButton(
onPressed: () {
@@ -859,6 +870,27 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
onPressed: () => setState(() => _selected.clear()),
child: const Text('No labels'),
),
SegmentedButton<LabelMatchMode>(
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: LabelMatchMode.and,
label: Text('AND'),
),
ButtonSegment(
value: LabelMatchMode.or,
label: Text('OR'),
),
],
selected: {_labelMatch},
onSelectionChanged: (selection) {
setState(() => _labelMatch = selection.first);
},
),
],
),
const SizedBox(height: 4),
@@ -0,0 +1,22 @@
/// PocketBase migration: label_match (AND/OR) on home_filter_widgets.
migrate((app) => {
const col = app.findCollectionByNameOrId("home_filter_widgets");
if (col.fields.getByName("label_match")) return;
col.fields.add(new Field({
type: "text",
name: "label_match",
required: false,
max: 16,
}));
app.save(col);
}, (app) => {
try {
const col = app.findCollectionByNameOrId("home_filter_widgets");
const field = col.fields.getByName("label_match");
if (field) {
col.fields.removeById(field.id);
app.save(col);
}
} catch (_) {}
});
@@ -0,0 +1,31 @@
/// PocketBase migration: `is_admin` on usersapp (admin vs normal accounts).
///
/// Admins can create test transactions in the app. Set the flag in Admin UI:
/// Users → pick user → is_admin = true.
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
const users = app.findCollectionByNameOrId("usersapp");
if (users.fields.getByName("is_admin")) return;
users.fields.add(new Field({
type: "bool",
name: "is_admin",
required: false,
}));
app.save(users);
}, (app) => {
try {
const users = app.findCollectionByNameOrId("usersapp");
const field = users.fields.getByName("is_admin");
if (field) {
users.fields.removeById(field.id);
app.save(users);
}
} catch (_) {}
});
@@ -0,0 +1,28 @@
/// PocketBase migration: `is_manual` on transactions (admin test rows).
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
const transactions = app.findCollectionByNameOrId("transactions");
if (transactions.fields.getByName("is_manual")) return;
transactions.fields.add(new Field({
type: "bool",
name: "is_manual",
required: false,
}));
app.save(transactions);
}, (app) => {
try {
const transactions = app.findCollectionByNameOrId("transactions");
const field = transactions.fields.getByName("is_manual");
if (field) {
transactions.fields.removeById(field.id);
app.save(transactions);
}
} catch (_) {}
});
@@ -0,0 +1,83 @@
/// PocketBase migration: `tx_deletes` — synced tombstones for deleted admin
/// test transactions so another device cannot push them back into `transactions`.
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
const users = app.findCollectionByNameOrId("usersapp");
try {
app.findCollectionByNameOrId("tx_deletes");
return;
} catch (_) {}
const ownerRules = {
listRule: "user = @request.auth.id",
viewRule: "user = @request.auth.id",
createRule: "@request.auth.id != '' && user = @request.auth.id",
updateRule: "user = @request.auth.id",
deleteRule: "user = @request.auth.id",
};
const txDeletes = new Collection({
type: "base",
name: "tx_deletes",
...ownerRules,
fields: [
{
type: "relation",
name: "user",
required: true,
collectionId: users.id,
cascadeDelete: true,
maxSelect: 1,
},
{
// Clipped BankTransaction.id
type: "text",
name: "tx_id",
required: true,
min: 1,
max: 2000,
},
{
type: "text",
name: "date",
required: true,
min: 1,
max: 32,
},
{
type: "text",
name: "description",
required: true,
min: 1,
max: 4000,
},
{
type: "number",
name: "amount",
required: true,
},
{
type: "text",
name: "currency",
required: true,
min: 1,
max: 8,
},
],
indexes: [
"CREATE UNIQUE INDEX idx_tx_deletes_user_tx ON tx_deletes (user, tx_id)",
],
});
app.save(txDeletes);
}, (app) => {
try {
app.delete(app.findCollectionByNameOrId("tx_deletes"));
} catch (_) {}
});
@@ -0,0 +1,48 @@
/// PocketBase migration: `updated_at` + `deleted` on overview favourites and
/// home filter widgets for cross-device last-write-wins sync.
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
function addSyncFields(collectionName) {
const col = app.findCollectionByNameOrId(collectionName);
let changed = false;
if (!col.fields.getByName("updated_at")) {
col.fields.add(new Field({
type: "number",
name: "updated_at",
required: false,
}));
changed = true;
}
if (!col.fields.getByName("deleted")) {
col.fields.add(new Field({
type: "bool",
name: "deleted",
required: false,
}));
changed = true;
}
if (changed) app.save(col);
}
addSyncFields("overview_favourites");
addSyncFields("home_filter_widgets");
}, (app) => {
function removeSyncFields(collectionName) {
try {
const col = app.findCollectionByNameOrId(collectionName);
const updated = col.fields.getByName("updated_at");
if (updated) col.fields.removeById(updated.id);
const deleted = col.fields.getByName("deleted");
if (deleted) col.fields.removeById(deleted.id);
app.save(col);
} catch (_) {}
}
removeSyncFields("overview_favourites");
removeSyncFields("home_filter_widgets");
});
+7
View File
@@ -19,12 +19,19 @@ void main() {
expect(restored.flow, TxFlowFilter.expense);
expect(restored.monthOnly, isTrue);
expect(restored.labelIds, ['groceries']);
expect(restored.labelMatch, LabelMatchMode.and);
expect(restored.showAmountOut, isTrue);
expect(restored.showAmountIn, isFalse);
expect(restored.showCount, isTrue);
expect(restored.halfWidth, isFalse);
expect(restored.type, HomeWidgetType.stats);
final withOr = widget.copyWith(labelMatch: LabelMatchMode.or);
expect(
HomeFilterWidget.fromJson(withOr.toJson()).labelMatch,
LabelMatchMode.or,
);
final budget = widget.copyWith(
halfWidth: true,
type: HomeWidgetType.budget,
+25 -6
View File
@@ -1,7 +1,6 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:myapp/models/overview_favourite.dart';
import 'package:myapp/models/transaction_meta.dart';
import 'package:myapp/services/pb_sync_service.dart';
import 'package:myapp/widgets/label_filter_dialog.dart';
void main() {
@@ -16,6 +15,8 @@ void main() {
flow: TxFlowFilter.expense,
barStyle: LabelChartBarStyle.stacked,
invertExpensePerspective: false,
updatedAt: 100,
deleted: false,
);
final restored = OverviewFavourite.fromJson(fav.toJson());
@@ -27,35 +28,53 @@ void main() {
expect(restored.labelIds, ['groceries', 'custom_ah']);
expect(restored.flow, TxFlowFilter.expense);
expect(restored.barStyle, LabelChartBarStyle.stacked);
expect(restored.updatedAt, 100);
expect(restored.deleted, isFalse);
});
test('mergeOverviewFavourites unions by id with local wins', () {
test('mergeOverviewFavourites unions by id with last-write-wins', () {
const local = OverviewFavourite(
id: 'fav_1',
name: 'Local name',
display: true,
updatedAt: 200,
);
const remoteOnly = OverviewFavourite(
id: 'fav_2',
name: 'Remote only',
display: false,
metric: OverviewMetricMode.labels,
updatedAt: 50,
);
const remoteConflict = OverviewFavourite(
const remoteConflictOlder = OverviewFavourite(
id: 'fav_1',
name: 'Remote name',
display: false,
updatedAt: 100,
);
const remoteConflictNewer = OverviewFavourite(
id: 'fav_3',
name: 'Remote newer',
display: true,
updatedAt: 300,
);
const localOlder = OverviewFavourite(
id: 'fav_3',
name: 'Local older',
display: false,
updatedAt: 10,
);
final merged = mergeOverviewFavourites(
[local],
[remoteConflict, remoteOnly],
[local, localOlder],
[remoteConflictOlder, remoteOnly, remoteConflictNewer],
);
expect(merged.length, 2);
expect(merged.length, 3);
final byId = {for (final f in merged) f.id: f};
expect(byId['fav_1']!.name, 'Local name');
expect(byId['fav_1']!.display, isTrue);
expect(byId['fav_2']!.name, 'Remote only');
expect(byId['fav_3']!.name, 'Remote newer');
});
}