Compare commits
5
Commits
v2.0
...
cfb551328b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cfb551328b | ||
|
|
40366f0708 | ||
|
|
2e40786bcd | ||
|
|
38bcf01ae3 | ||
|
|
00ab05eefc |
@@ -113,6 +113,23 @@ 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,
|
||||
|
||||
@@ -94,6 +94,8 @@ class HomeFilterWidget {
|
||||
this.showAmountIn = true,
|
||||
this.showAmountOut = true,
|
||||
this.showCount = true,
|
||||
this.updatedAt = 0,
|
||||
this.deleted = false,
|
||||
});
|
||||
|
||||
final String id;
|
||||
@@ -129,6 +131,12 @@ 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(
|
||||
@@ -161,6 +169,9 @@ class HomeFilterWidget {
|
||||
bool? showAmountIn,
|
||||
bool? showAmountOut,
|
||||
bool? showCount,
|
||||
int? updatedAt,
|
||||
bool? deleted,
|
||||
bool touchUpdatedAt = false,
|
||||
}) {
|
||||
return HomeFilterWidget(
|
||||
id: id ?? this.id,
|
||||
@@ -183,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,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -208,6 +223,7 @@ class HomeFilterWidget {
|
||||
showAmountIn: showIn,
|
||||
showAmountOut: showOut,
|
||||
showCount: true,
|
||||
updatedAt: DateTime.now().millisecondsSinceEpoch,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -236,6 +252,8 @@ class HomeFilterWidget {
|
||||
'showAmountIn': showAmountIn,
|
||||
'showAmountOut': showAmountOut,
|
||||
'showCount': showCount,
|
||||
'updatedAt': updatedAt,
|
||||
'deleted': deleted,
|
||||
};
|
||||
|
||||
factory HomeFilterWidget.fromJson(Map<String, dynamic> json) {
|
||||
@@ -302,21 +320,31 @@ 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,
|
||||
};
|
||||
for (final w in local) {
|
||||
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) {
|
||||
put(w);
|
||||
}
|
||||
final merged = byId.values.toList()
|
||||
..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
|
||||
return merged;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
@@ -36,6 +38,18 @@ class BankController extends ChangeNotifier {
|
||||
_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();
|
||||
}
|
||||
|
||||
@@ -55,29 +69,90 @@ 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<String> _pendingRemoteDeletes = const [];
|
||||
List<BankTransaction> _pendingRemoteDeletes = const [];
|
||||
|
||||
/// Local tx_ids removed/replaced that should be deleted on the next PB push.
|
||||
List<String> takePendingRemoteDeletes() {
|
||||
final out = List<String>.of(_pendingRemoteDeletes);
|
||||
_pendingRemoteDeletes = const [];
|
||||
return out;
|
||||
/// 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<String> txIds) {
|
||||
for (final id in txIds) {
|
||||
_queueRemoteDelete(id);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
void _queueRemoteDelete(String txId) {
|
||||
if (txId.isEmpty) return;
|
||||
if (_pendingRemoteDeletes.contains(txId)) return;
|
||||
_pendingRemoteDeletes = [..._pendingRemoteDeletes, txId];
|
||||
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.
|
||||
@@ -300,7 +375,7 @@ class BankController extends ChangeNotifier {
|
||||
if (tx.id != previous.id) tx,
|
||||
];
|
||||
if (previous.id != updated.id) {
|
||||
_queueRemoteDelete(previous.id);
|
||||
_queueRemoteDelete(previous);
|
||||
}
|
||||
_importedTransactions = mergeTransactions(_importedTransactions, [updated]);
|
||||
_invalidateMerged();
|
||||
@@ -317,13 +392,13 @@ class BankController extends ChangeNotifier {
|
||||
}
|
||||
_importedTransactions = [
|
||||
for (final row in _importedTransactions)
|
||||
if (row.id != tx.id) row,
|
||||
if (!row.matchesForDelete(tx)) row,
|
||||
];
|
||||
_remoteTransactions = [
|
||||
for (final row in _remoteTransactions)
|
||||
if (row.id != tx.id) row,
|
||||
if (!row.matchesForDelete(tx)) row,
|
||||
];
|
||||
_queueRemoteDelete(tx.id);
|
||||
_queueRemoteDelete(tx);
|
||||
_invalidateMerged();
|
||||
await _persistImported();
|
||||
await _persistCache();
|
||||
@@ -337,17 +412,36 @@ class BankController extends ChangeNotifier {
|
||||
List<BankTransaction> fromCloud, {
|
||||
bool notify = true,
|
||||
}) async {
|
||||
if (fromCloud.isEmpty) return;
|
||||
if (fromCloud.isEmpty && _pendingRemoteDeletes.isEmpty) return;
|
||||
|
||||
final manuals = _collectManualIds(fromCloud.map(_upgradeLegacyManual));
|
||||
_remoteTransactions = mergeTransactions(
|
||||
_remoteTransactions,
|
||||
[for (final tx in fromCloud) _upgradeLegacyManual(tx)],
|
||||
);
|
||||
// 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();
|
||||
|
||||
@@ -444,6 +538,16 @@ 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();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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,17 +456,14 @@ class SyncController extends ChangeNotifier {
|
||||
} catch (error) {
|
||||
debugPrint('SyncController: app_prefs push skipped ($error)');
|
||||
}
|
||||
final pendingDeletes = _bank.takePendingRemoteDeletes();
|
||||
if (pendingDeletes.isNotEmpty) {
|
||||
try {
|
||||
await service.deleteTransactionsByTxIds(pendingDeletes);
|
||||
} catch (error) {
|
||||
debugPrint('SyncController: tx deletes skipped ($error)');
|
||||
_bank.requeueRemoteDeletes(pendingDeletes);
|
||||
}
|
||||
}
|
||||
// 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,
|
||||
@@ -463,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;
|
||||
}
|
||||
|
||||
@@ -480,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…';
|
||||
@@ -500,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);
|
||||
@@ -522,7 +576,7 @@ class SyncController extends ChangeNotifier {
|
||||
_setStatus('Pushing favourites…');
|
||||
try {
|
||||
await service.pushOverviewFavourites(
|
||||
_prefs.overviewFavourites,
|
||||
_prefs.overviewFavouritesForSync,
|
||||
onStatus: _setStatus,
|
||||
);
|
||||
parts.add('Favourites updated');
|
||||
@@ -530,6 +584,7 @@ class SyncController extends ChangeNotifier {
|
||||
debugPrint(
|
||||
'SyncController: overview_favourites push skipped ($error)',
|
||||
);
|
||||
_pushFavouritesPending = true;
|
||||
}
|
||||
bump();
|
||||
}
|
||||
@@ -537,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');
|
||||
@@ -545,6 +600,7 @@ class SyncController extends ChangeNotifier {
|
||||
debugPrint(
|
||||
'SyncController: home_filter_widgets push skipped ($error)',
|
||||
);
|
||||
_pushHomeWidgetsPending = true;
|
||||
}
|
||||
bump();
|
||||
}
|
||||
@@ -564,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();
|
||||
@@ -597,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;
|
||||
|
||||
@@ -474,7 +474,29 @@ 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,
|
||||
),
|
||||
onChartTap: () => _openChartFilter(
|
||||
context,
|
||||
labelIds: {
|
||||
for (final id in favourite.labelIds) id,
|
||||
},
|
||||
flow: favourite.metric == OverviewMetricMode.labels
|
||||
? favourite.flow
|
||||
: null,
|
||||
periodMode: favourite.period,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -590,7 +612,17 @@ 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),
|
||||
),
|
||||
onChartTap: () => _openChartFilter(
|
||||
context,
|
||||
flow: _metric == OverviewMetricMode.labels ? _labelFlow : null,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
if (_metric == OverviewMetricMode.flow) ...[
|
||||
@@ -739,23 +771,57 @@ 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}
|
||||
: {
|
||||
: (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: resolvedLabelIds,
|
||||
initialLabelMatch: LabelMatchMode.or,
|
||||
initialFlow: flow,
|
||||
initialSearchInMonthOnly: !yearly && resolvedLabelIds.isNotEmpty,
|
||||
initialYear: yearly ? period.year : null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Open Transactions with this chart's filters (no specific bar/column).
|
||||
void _openChartFilter(
|
||||
BuildContext context, {
|
||||
Set<String>? labelIds,
|
||||
TxFlowFilter? flow,
|
||||
OverviewPeriodMode? periodMode,
|
||||
}) {
|
||||
final mode = periodMode ?? _period;
|
||||
final yearly = mode == OverviewPeriodMode.yearly;
|
||||
final resolvedLabelIds = labelIds ??
|
||||
{
|
||||
for (final id in _includedLabelIds) id,
|
||||
};
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => TransactionsScreen(
|
||||
initialMonth: initial,
|
||||
initialLabelIds: labelIds,
|
||||
// Monthly charts show a year — open that whole year with the chart filter.
|
||||
initialMonth: yearly ? null : DateTime(_cursor.year, 12),
|
||||
initialYear: yearly ? null : _cursor.year,
|
||||
initialLabelIds: resolvedLabelIds,
|
||||
initialLabelMatch: LabelMatchMode.or,
|
||||
initialSearchInMonthOnly: !yearly && labelIds.isNotEmpty,
|
||||
initialYear: yearly ? period.year : null,
|
||||
initialFlow: flow,
|
||||
initialSearchInMonthOnly: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1159,6 +1225,7 @@ class _ChartCard extends StatelessWidget {
|
||||
required this.availableLabelCount,
|
||||
required this.onLabelTap,
|
||||
required this.onMonthTap,
|
||||
required this.onChartTap,
|
||||
this.onPeriodModeChanged,
|
||||
this.onEdit,
|
||||
});
|
||||
@@ -1182,7 +1249,12 @@ 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 VoidCallback onChartTap;
|
||||
final ValueChanged<OverviewPeriodMode>? onPeriodModeChanged;
|
||||
final VoidCallback? onEdit;
|
||||
|
||||
@@ -1277,7 +1349,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(
|
||||
@@ -1286,7 +1358,7 @@ class _ChartCard extends StatelessWidget {
|
||||
compact: compact,
|
||||
),
|
||||
),
|
||||
if (labelSpend.length > (compact ? 3 : 5))
|
||||
if (labelSpend.length > 6)
|
||||
_LegendDot(
|
||||
color: colors.outline,
|
||||
label: 'Other',
|
||||
@@ -1523,12 +1595,16 @@ class _ChartCard extends StatelessWidget {
|
||||
],
|
||||
SizedBox(
|
||||
height: chartHeight,
|
||||
child: _TappableChartArea(
|
||||
onChartTap: onChartTap,
|
||||
child: metric == OverviewMetricMode.flow
|
||||
? _FlowBars(
|
||||
months: months,
|
||||
monthly: monthly,
|
||||
currency: currency,
|
||||
period: period,
|
||||
onMonthTap: onMonthTap,
|
||||
onChartTap: onChartTap,
|
||||
)
|
||||
: _LabelMonthBars(
|
||||
months: months,
|
||||
@@ -1539,6 +1615,8 @@ class _ChartCard extends StatelessWidget {
|
||||
barStyle: labelBarStyle,
|
||||
invertChart: invertChart,
|
||||
onMonthTap: onMonthTap,
|
||||
onChartTap: onChartTap,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -1548,18 +1626,89 @@ class _ChartCard extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets empty-chart taps open the chart filter without double-firing when a bar
|
||||
/// was just selected (fl_chart + parent [GestureDetector] both see the tap).
|
||||
class _TappableChartArea extends StatefulWidget {
|
||||
const _TappableChartArea({
|
||||
required this.onChartTap,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final VoidCallback onChartTap;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<_TappableChartArea> createState() => _TappableChartAreaState();
|
||||
}
|
||||
|
||||
class _TappableChartAreaState extends State<_TappableChartArea> {
|
||||
var _handling = false;
|
||||
|
||||
void _runExclusive(VoidCallback action) {
|
||||
if (_handling) return;
|
||||
_handling = true;
|
||||
action();
|
||||
Future<void>.delayed(const Duration(milliseconds: 400), () {
|
||||
if (mounted) _handling = false;
|
||||
});
|
||||
}
|
||||
|
||||
void openChartFilter() => _runExclusive(widget.onChartTap);
|
||||
|
||||
void openBar(VoidCallback action) => _runExclusive(action);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: openChartFilter,
|
||||
child: _ChartTapScope(
|
||||
openChartFilter: openChartFilter,
|
||||
openBar: openBar,
|
||||
child: widget.child,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ChartTapScope extends InheritedWidget {
|
||||
const _ChartTapScope({
|
||||
required this.openChartFilter,
|
||||
required this.openBar,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
final VoidCallback openChartFilter;
|
||||
final void Function(VoidCallback action) openBar;
|
||||
|
||||
static _ChartTapScope? maybeOf(BuildContext context) {
|
||||
return context.getInheritedWidgetOfExactType<_ChartTapScope>();
|
||||
}
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(_ChartTapScope oldWidget) => false;
|
||||
}
|
||||
|
||||
class _FlowBars extends StatelessWidget {
|
||||
const _FlowBars({
|
||||
required this.months,
|
||||
required this.monthly,
|
||||
required this.currency,
|
||||
required this.period,
|
||||
required this.onMonthTap,
|
||||
required this.onChartTap,
|
||||
});
|
||||
|
||||
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;
|
||||
final VoidCallback onChartTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -1578,7 +1727,10 @@ class _FlowBars extends StatelessWidget {
|
||||
});
|
||||
|
||||
if (empty) {
|
||||
return Center(
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: onChartTap,
|
||||
child: Center(
|
||||
child: Text(
|
||||
period == OverviewPeriodMode.yearly
|
||||
? 'No income or expenses in these years'
|
||||
@@ -1586,6 +1738,7 @@ class _FlowBars extends StatelessWidget {
|
||||
style: theme.textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1594,6 +1747,29 @@ 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;
|
||||
final index = spot?.touchedBarGroupIndex;
|
||||
if (spot == null ||
|
||||
index == null ||
|
||||
index < 0 ||
|
||||
index >= months.length) {
|
||||
// Parent GestureDetector also handles empty-area taps.
|
||||
return;
|
||||
}
|
||||
final rodIndex = spot.touchedRodDataIndex;
|
||||
// Rods: 0 = expense, 1 = income.
|
||||
final flow = rodIndex == 1
|
||||
? TxFlowFilter.income
|
||||
: TxFlowFilter.expense;
|
||||
final scope = _ChartTapScope.maybeOf(context);
|
||||
if (scope != null) {
|
||||
scope.openBar(() => onMonthTap(months[index], flow: flow));
|
||||
} else {
|
||||
onMonthTap(months[index], flow: flow);
|
||||
}
|
||||
},
|
||||
touchTooltipData: BarTouchTooltipData(
|
||||
getTooltipItem: (group, groupIndex, rod, rodIndex) {
|
||||
final month = months[group.x.toInt()];
|
||||
@@ -1707,9 +1883,10 @@ class _LabelMonthBars extends StatelessWidget {
|
||||
required this.barStyle,
|
||||
required this.invertChart,
|
||||
required this.onMonthTap,
|
||||
required this.onChartTap,
|
||||
});
|
||||
|
||||
static const _maxSeriesLabels = 5;
|
||||
static const _maxSeriesLabels = 6;
|
||||
|
||||
final List<DateTime> months;
|
||||
final List<_LabelSpend> labelSpend;
|
||||
@@ -1718,7 +1895,12 @@ 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;
|
||||
final VoidCallback onChartTap;
|
||||
|
||||
double _plot(double value) => invertChart ? -value : value;
|
||||
|
||||
@@ -1727,12 +1909,16 @@ class _LabelMonthBars extends StatelessWidget {
|
||||
final theme = Theme.of(context);
|
||||
final colors = theme.colorScheme;
|
||||
if (labelSpend.isEmpty) {
|
||||
return Center(
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: onChartTap,
|
||||
child: Center(
|
||||
child: Text(
|
||||
'No labeled activity in this period.\nTag transactions to see them here.',
|
||||
style: theme.textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1789,12 +1975,16 @@ class _LabelMonthBars extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
if (maxY == 0 && minY == 0) {
|
||||
return Center(
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: onChartTap,
|
||||
child: Center(
|
||||
child: Text(
|
||||
'No labeled activity in this period.\nTag transactions to see them here.',
|
||||
style: theme.textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final span = (maxY - minY).abs();
|
||||
@@ -1805,12 +1995,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 =
|
||||
@@ -1896,9 +2086,36 @@ 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;
|
||||
final index = spot?.touchedBarGroupIndex;
|
||||
if (spot == null ||
|
||||
index == null ||
|
||||
index < 0 ||
|
||||
index >= months.length) {
|
||||
// Parent GestureDetector also handles empty-area taps.
|
||||
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.
|
||||
}
|
||||
final scope = _ChartTapScope.maybeOf(context);
|
||||
if (scope != null) {
|
||||
scope.openBar(
|
||||
() => onMonthTap(months[index], labelId: labelId),
|
||||
);
|
||||
} else {
|
||||
onMonthTap(months[index], labelId: labelId);
|
||||
}
|
||||
},
|
||||
touchTooltipData: BarTouchTooltipData(
|
||||
getTooltipItem: (group, groupIndex, rod, rodIndex) {
|
||||
|
||||
@@ -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'),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -544,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'),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -598,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,
|
||||
@@ -630,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,
|
||||
@@ -648,7 +651,9 @@ class PbSyncService {
|
||||
8,
|
||||
),
|
||||
'pending': tx.pending,
|
||||
'is_manual': tx.isManual,
|
||||
// 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) {
|
||||
@@ -660,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
|
||||
@@ -678,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) {
|
||||
@@ -700,7 +724,8 @@ class PbSyncService {
|
||||
? 'EUR'
|
||||
: r.getStringValue('currency'),
|
||||
pending: r.getBoolValue('pending'),
|
||||
isManual: r.getBoolValue('is_manual'),
|
||||
isManual: r.getBoolValue('is_manual') ||
|
||||
RegExp(r' ·#\d+$').hasMatch(description),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -711,6 +736,8 @@ 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) &&
|
||||
@@ -718,29 +745,117 @@ class PbSyncService {
|
||||
remote.getStringValue('currency').toUpperCase() ==
|
||||
tx.currency.toUpperCase() &&
|
||||
remote.getBoolValue('pending') == tx.pending &&
|
||||
remote.getBoolValue('is_manual') == tx.isManual;
|
||||
remoteManual == tx.isManual;
|
||||
}
|
||||
|
||||
/// Deletes remote bank rows by local [BankTransaction.id] (tx_id field).
|
||||
Future<String> deleteTransactionsByTxIds(Iterable<String> txIds) async {
|
||||
final ids = {
|
||||
for (final id in txIds)
|
||||
if (_clip(id, 2000).isNotEmpty) _clip(id, 2000),
|
||||
};
|
||||
if (ids.isEmpty) return 'Bank txs: nothing to delete';
|
||||
/// 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 ops = <_BatchOp>[
|
||||
for (final r in existing)
|
||||
if (ids.contains(r.getStringValue('tx_id'))) _BatchOp.delete(r.id),
|
||||
];
|
||||
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) {
|
||||
return 'Bank txs: 0 remote deletes (ids ${ids.length})';
|
||||
debugPrint(
|
||||
'PbSyncService deleteTransactionsMatching: 0 hits '
|
||||
'for ${tombstones.length} tombstone(s)',
|
||||
);
|
||||
return const [];
|
||||
}
|
||||
await _runWriteOps('transactions', ops);
|
||||
return 'Bank txs: deleted ${ops.length} remote row(s)';
|
||||
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) {
|
||||
@@ -907,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');
|
||||
@@ -1233,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) {
|
||||
@@ -1297,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) {
|
||||
@@ -1402,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) {
|
||||
@@ -1441,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) {
|
||||
@@ -1454,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) {
|
||||
|
||||
@@ -260,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) {
|
||||
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -288,19 +288,14 @@ class _StatsBody extends StatelessWidget {
|
||||
final spentOnly = widgetConfig.showAmountOut &&
|
||||
!widgetConfig.showAmountIn &&
|
||||
!widgetConfig.showCount;
|
||||
final half = widgetConfig.halfWidth;
|
||||
|
||||
// Avoid LayoutBuilder/Spacer/Expanded here: half-width rows use
|
||||
// IntrinsicHeight, which cannot measure those widgets.
|
||||
Widget metricsBlock({required bool alignEnd}) {
|
||||
if (spentOnly) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
crossAxisAlignment:
|
||||
alignEnd ? CrossAxisAlignment.end : CrossAxisAlignment.start,
|
||||
children: [
|
||||
_CardHeader(
|
||||
icon: widgetConfig.icon,
|
||||
title: widgetConfig.name,
|
||||
subtitle: _subtitleFor(widgetConfig),
|
||||
),
|
||||
if (spentOnly) ...[
|
||||
const SizedBox(height: 32),
|
||||
Text(
|
||||
'Spent',
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
@@ -316,11 +311,13 @@ class _StatsBody extends StatelessWidget {
|
||||
height: 1.15,
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 8,
|
||||
alignment: alignEnd ? WrapAlignment.end : WrapAlignment.start,
|
||||
children: [
|
||||
if (widgetConfig.showAmountIn)
|
||||
_Metric(
|
||||
@@ -336,13 +333,45 @@ class _StatsBody extends StatelessWidget {
|
||||
),
|
||||
if (widgetConfig.showCount)
|
||||
_Metric(
|
||||
label: 'Txs',
|
||||
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: [
|
||||
_CardHeader(
|
||||
icon: widgetConfig.icon,
|
||||
title: widgetConfig.name,
|
||||
subtitle: _subtitleFor(widgetConfig),
|
||||
),
|
||||
SizedBox(height: spentOnly ? 32 : 14),
|
||||
metricsBlock(alignEnd: false),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user