3 Commits
Author SHA1 Message Date
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
25 changed files with 1092 additions and 119 deletions
+8
View File
@@ -95,9 +95,17 @@ Migrations live in [`pocketbase/pb_migrations/`](pocketbase/pb_migrations/). The
| `1740000003` | `overview_favourites` | | `1740000003` | `overview_favourites` |
| `1740000004`–`0006` | `home_filter_widgets` (+ half width, budget fields) | | `1740000004`–`0006` | `home_filter_widgets` (+ half width, budget fields) |
| `1740000007` | `app_prefs` (Home section toggles + Look ahead years) | | `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`). 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) ### Apply migrations (typical Linux host)
```bash ```bash
+34
View File
@@ -88,6 +88,7 @@ class BankTransaction {
required this.amount, required this.amount,
required this.currency, required this.currency,
required this.pending, required this.pending,
this.isManual = false,
}); });
final String date; final String date;
@@ -96,6 +97,9 @@ class BankTransaction {
final String currency; final String currency;
final bool pending; 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. /// Stable local key used for per-occurrence annotations.
String get id => '$date|$currency|$amount|$description'; String get id => '$date|$currency|$amount|$description';
@@ -109,6 +113,33 @@ class BankTransaction {
/// Exact match for copying notes (same description + amount + currency). /// Exact match for copying notes (same description + amount + currency).
String get exactKey => '$descriptionKey|$amount|$currency'; String get exactKey => '$descriptionKey|$amount|$currency';
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) { factory BankTransaction.fromJson(Map<String, dynamic> json) {
final rawAmount = json['amount']; final rawAmount = json['amount'];
final amount = switch (rawAmount) { final amount = switch (rawAmount) {
@@ -122,6 +153,9 @@ class BankTransaction {
amount: amount, amount: amount,
currency: json['currency'] as String? ?? 'EUR', currency: json['currency'] as String? ?? 'EUR',
pending: json['pending'] as bool? ?? false, pending: json['pending'] as bool? ?? false,
isManual: json['isManual'] as bool? ??
json['is_manual'] as bool? ??
false,
); );
} }
} }
+14
View File
@@ -86,6 +86,7 @@ class HomeFilterWidget {
this.budgetFixedAmount = 0, this.budgetFixedAmount = 0,
this.budgetAverageMonths = 3, this.budgetAverageMonths = 3,
this.labelIds = const [], this.labelIds = const [],
this.labelMatch = LabelMatchMode.and,
this.flow = TxFlowFilter.all, this.flow = TxFlowFilter.all,
this.amountRange = const TxAmountRange(), this.amountRange = const TxAmountRange(),
this.query = '', this.query = '',
@@ -115,6 +116,10 @@ class HomeFilterWidget {
final int budgetAverageMonths; final int budgetAverageMonths;
final List<String> labelIds; final List<String> labelIds;
/// AND vs OR when multiple [labelIds] are selected.
final LabelMatchMode labelMatch;
final TxFlowFilter flow; final TxFlowFilter flow;
final TxAmountRange amountRange; final TxAmountRange amountRange;
final String query; final String query;
@@ -128,6 +133,7 @@ class HomeFilterWidget {
TransactionFilterSelection get filter => TransactionFilterSelection( TransactionFilterSelection get filter => TransactionFilterSelection(
labelIds: labelIds.toSet(), labelIds: labelIds.toSet(),
labelMatch: labelMatch,
flow: flow, flow: flow,
amountRange: amountRange, amountRange: amountRange,
query: query, query: query,
@@ -147,6 +153,7 @@ class HomeFilterWidget {
double? budgetFixedAmount, double? budgetFixedAmount,
int? budgetAverageMonths, int? budgetAverageMonths,
List<String>? labelIds, List<String>? labelIds,
LabelMatchMode? labelMatch,
TxFlowFilter? flow, TxFlowFilter? flow,
TxAmountRange? amountRange, TxAmountRange? amountRange,
String? query, String? query,
@@ -168,6 +175,7 @@ class HomeFilterWidget {
budgetFixedAmount: budgetFixedAmount ?? this.budgetFixedAmount, budgetFixedAmount: budgetFixedAmount ?? this.budgetFixedAmount,
budgetAverageMonths: budgetAverageMonths ?? this.budgetAverageMonths, budgetAverageMonths: budgetAverageMonths ?? this.budgetAverageMonths,
labelIds: labelIds ?? this.labelIds, labelIds: labelIds ?? this.labelIds,
labelMatch: labelMatch ?? this.labelMatch,
flow: flow ?? this.flow, flow: flow ?? this.flow,
amountRange: amountRange ?? this.amountRange, amountRange: amountRange ?? this.amountRange,
query: query ?? this.query, query: query ?? this.query,
@@ -192,6 +200,7 @@ class HomeFilterWidget {
display: display, display: display,
sortOrder: sortOrder, sortOrder: sortOrder,
labelIds: filter.labelIds.toList(growable: false), labelIds: filter.labelIds.toList(growable: false),
labelMatch: filter.labelMatch,
flow: filter.flow, flow: filter.flow,
amountRange: filter.amountRange, amountRange: filter.amountRange,
query: filter.query, query: filter.query,
@@ -215,6 +224,7 @@ class HomeFilterWidget {
'budgetFixedAmount': budgetFixedAmount, 'budgetFixedAmount': budgetFixedAmount,
'budgetAverageMonths': budgetAverageMonths, 'budgetAverageMonths': budgetAverageMonths,
'labelIds': labelIds, 'labelIds': labelIds,
'labelMatch': labelMatch.name,
'flow': flow.name, 'flow': flow.name,
'amountRange': { 'amountRange': {
if (amountRange.exact != null) 'exact': amountRange.exact, if (amountRange.exact != null) 'exact': amountRange.exact,
@@ -274,6 +284,10 @@ class HomeFilterWidget {
for (final id in (json['labelIds'] as List? ?? const [])) for (final id in (json['labelIds'] as List? ?? const []))
if (id is String && id.isNotEmpty) id, if (id is String && id.isNotEmpty) id,
], ],
labelMatch: LabelMatchMode.values.firstWhere(
(e) => e.name == json['labelMatch'],
orElse: () => LabelMatchMode.and,
),
flow: TxFlowFilter.values.firstWhere( flow: TxFlowFilter.values.firstWhere(
(e) => e.name == json['flow'], (e) => e.name == json['flow'],
orElse: () => TxFlowFilter.all, orElse: () => TxFlowFilter.all,
+9
View File
@@ -134,6 +134,15 @@ int labelVisibleDepth(
/// Filter-only id for txs with no labels (not an assignable category). /// Filter-only id for txs with no labels (not an assignable category).
const String kUncategorizedFilterId = '__uncategorized__'; 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. /// Chip presentation for [kUncategorizedFilterId] refine filters.
const TxLabel kUncategorizedFilterLabel = TxLabel( const TxLabel kUncategorizedFilterLabel = TxLabel(
id: kUncategorizedFilterId, id: kUncategorizedFilterId,
+18
View File
@@ -26,6 +26,13 @@ class AuthController extends ChangeNotifier {
RecordModel? get user => _client?.authStore.record; 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 { String? get email {
final value = user?.getStringValue('email'); final value = user?.getStringValue('email');
return value == null || value.isEmpty ? null : value; return value == null || value.isEmpty ? null : value;
@@ -80,6 +87,17 @@ class AuthController extends ChangeNotifier {
notifyListeners(); 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 { Future<void> logout() async {
client.authStore.clear(); client.authStore.clear();
notifyListeners(); notifyListeners();
+177 -1
View File
@@ -30,9 +30,22 @@ class BankController extends ChangeNotifier {
_remoteTransactions = cached.transactions; _remoteTransactions = cached.transactions;
} }
_importedTransactions = _storage?.loadImportedTransactions() ?? const []; _importedTransactions = _storage?.loadImportedTransactions() ?? const [];
_importedTransactions = [
for (final tx in _importedTransactions) _upgradeLegacyManual(tx),
];
_remoteTransactions = [
for (final tx in _remoteTransactions) _upgradeLegacyManual(tx),
];
_invalidateMerged(); _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 IngtrakApi _api;
final StorageService? _storage; final StorageService? _storage;
@@ -46,6 +59,51 @@ class BankController extends ChangeNotifier {
BankBalance? _balance; BankBalance? _balance;
List<BankTransaction> _remoteTransactions = const []; List<BankTransaction> _remoteTransactions = const [];
List<BankTransaction> _importedTransactions = const []; List<BankTransaction> _importedTransactions = const [];
List<String> _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;
}
void requeueRemoteDeletes(Iterable<String> txIds) {
for (final id in txIds) {
_queueRemoteDelete(id);
}
}
void _queueRemoteDelete(String txId) {
if (txId.isEmpty) return;
if (_pendingRemoteDeletes.contains(txId)) return;
_pendingRemoteDeletes = [..._pendingRemoteDeletes, txId];
}
/// 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; List<BankTransaction>? _mergedTransactions;
bool _isLoading = false; bool _isLoading = false;
@@ -161,6 +219,117 @@ class BankController extends ChangeNotifier {
notifyListeners(); 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.id);
}
_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.id != tx.id) row,
];
_remoteTransactions = [
for (final row in _remoteTransactions)
if (row.id != tx.id) row,
];
_queueRemoteDelete(tx.id);
_invalidateMerged();
await _persistImported();
await _persistCache();
notifyListeners();
}
/// Union cloud txs into the local bank cache without dropping either side. /// 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. /// Rows land in the API cache; CSV imports that match are deduped away.
@@ -170,11 +339,16 @@ class BankController extends ChangeNotifier {
}) async { }) async {
if (fromCloud.isEmpty) return; if (fromCloud.isEmpty) return;
_remoteTransactions = mergeTransactions(_remoteTransactions, fromCloud); final manuals = _collectManualIds(fromCloud.map(_upgradeLegacyManual));
_remoteTransactions = mergeTransactions(
_remoteTransactions,
[for (final tx in fromCloud) _upgradeLegacyManual(tx)],
);
_importedTransactions = filterNewTransactions( _importedTransactions = filterNewTransactions(
_remoteTransactions, _remoteTransactions,
_importedTransactions, _importedTransactions,
); );
_reapplyManualFlags(manuals);
_invalidateMerged(); _invalidateMerged();
if (!_status.linked && _remoteTransactions.isNotEmpty) { if (!_status.linked && _remoteTransactions.isNotEmpty) {
@@ -254,6 +428,7 @@ class BankController extends ChangeNotifier {
final apiTxs = results[1] as List<BankTransaction>; final apiTxs = results[1] as List<BankTransaction>;
// Bank API is ~89 days. Prefer API rows for overlaps, but keep any // Bank API is ~89 days. Prefer API rows for overlaps, but keep any
// cloud/CSV history that the API window does not include. // cloud/CSV history that the API window does not include.
final manuals = _collectManualIds();
_remoteTransactions = mergeTransactions(apiTxs, _remoteTransactions); _remoteTransactions = mergeTransactions(apiTxs, _remoteTransactions);
if (!_status.linked) { if (!_status.linked) {
_status = ConnectStatus( _status = ConnectStatus(
@@ -269,6 +444,7 @@ class BankController extends ChangeNotifier {
_remoteTransactions, _remoteTransactions,
_importedTransactions, _importedTransactions,
); );
_reapplyManualFlags(manuals);
_invalidateMerged(); _invalidateMerged();
await _persistImported(); await _persistImported();
_error = null; _error = null;
+9
View File
@@ -408,6 +408,15 @@ class SyncController extends ChangeNotifier {
} catch (error) { } catch (error) {
debugPrint('SyncController: app_prefs push skipped ($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);
}
}
final bankSummary = await service.pushTransactions( final bankSummary = await service.pushTransactions(
_bank.transactions, _bank.transactions,
progressStart: 0.82, progressStart: 0.82,
+51 -9
View File
@@ -722,6 +722,25 @@ class TxMetaController extends ChangeNotifier {
_schedulePersist(invalidateLabels: false); _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( Future<void> setNotes(
BankTransaction tx, BankTransaction tx,
String notes, { String notes, {
@@ -800,6 +819,7 @@ class TxMetaController extends ChangeNotifier {
List<BankTransaction> txs, List<BankTransaction> txs,
String query, { String query, {
Set<String> labelIds = const {}, Set<String> labelIds = const {},
LabelMatchMode labelMatch = LabelMatchMode.and,
}) { }) {
final needle = query.trim().toLowerCase(); final needle = query.trim().toLowerCase();
final hasText = needle.isNotEmpty; final hasText = needle.isNotEmpty;
@@ -809,7 +829,15 @@ class TxMetaController extends ChangeNotifier {
final labelIndex = _labelById; final labelIndex = _labelById;
return [ return [
for (final tx in txs) for (final tx in txs)
if (_matchesSearch(tx, needle, hasText, labelIds, hasLabels, labelIndex)) if (_matchesSearch(
tx,
needle,
hasText,
labelIds,
hasLabels,
labelMatch,
labelIndex,
))
tx, tx,
]; ];
} }
@@ -820,10 +848,11 @@ class TxMetaController extends ChangeNotifier {
bool hasText, bool hasText,
Set<String> labelIds, Set<String> labelIds,
bool hasLabels, bool hasLabels,
LabelMatchMode labelMatch,
Map<String, TxLabel> labelIndex, Map<String, TxLabel> labelIndex,
) { ) {
final meta = metaFor(tx); final meta = metaFor(tx);
if (hasLabels && !_matchesLabelFilter(meta, labelIds)) { if (hasLabels && !_matchesLabelFilter(meta, labelIds, labelMatch)) {
return false; return false;
} }
if (!hasText) return true; if (!hasText) return true;
@@ -838,20 +867,33 @@ class TxMetaController extends ChangeNotifier {
return false; 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 /// Uncategorized alone matches unlabeled txs. Uncategorized + others with
/// other labels matches nothing (a tx cannot be both). /// AND matches nothing; with OR matches unlabeled or any of the labels.
bool _matchesLabelFilter(TxMeta meta, Set<String> labelIds) { bool _matchesLabelFilter(
TxMeta meta,
Set<String> labelIds,
LabelMatchMode mode,
) {
final wantUncategorized = labelIds.contains(kUncategorizedFilterId); final wantUncategorized = labelIds.contains(kUncategorizedFilterId);
final required = <String>[ final required = <String>[
for (final id in labelIds) for (final id in labelIds)
if (id != kUncategorizedFilterId) id, if (id != kUncategorizedFilterId) id,
]; ];
if (wantUncategorized) { if (required.isEmpty) {
if (required.isNotEmpty) return false; if (wantUncategorized) return !meta.hasLabel;
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) { for (final id in required) {
if (!meta.labelIds.contains(id)) return false; 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. /// Signed-in account details, sync status, bank link, and sign-out.
library; library;
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -10,11 +12,26 @@ import '../providers/sync_provider.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
import '../utils/connect_bank.dart'; import '../utils/connect_bank.dart';
import '../utils/constants.dart'; import '../utils/constants.dart';
import '../widgets/admin_create_transaction_dialog.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
class AccountScreen extends StatelessWidget { class AccountScreen extends StatefulWidget {
const AccountScreen({super.key}); 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final auth = context.watch<AuthController>(); 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), const SizedBox(height: 24),
Card( Card(
child: Column( child: Column(
@@ -91,6 +126,59 @@ class AccountScreen extends StatelessWidget {
), ),
), ),
const SizedBox(height: 16), 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( Card(
child: ListTile( child: ListTile(
leading: Icon( leading: Icon(
+42 -21
View File
@@ -9,7 +9,7 @@ import '../models/transaction_meta.dart';
import '../providers/bank_provider.dart'; import '../providers/bank_provider.dart';
import '../providers/preferences_provider.dart'; import '../providers/preferences_provider.dart';
import '../providers/tx_meta_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/app_theme.dart';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../utils/look_ahead.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), const SizedBox(height: 10),
Row( Row(
children: [ children: [
@@ -622,6 +611,46 @@ class _TemplateTile extends StatelessWidget {
return null; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
@@ -658,15 +687,7 @@ class _TemplateTile extends StatelessWidget {
color: income ? AppTheme.accent : AppTheme.expense, color: income ? AppTheme.accent : AppTheme.expense,
), ),
), ),
onTap: () { onTap: () => _openTransactions(context),
final tx = _sourceTx;
if (tx == null) return;
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => TransactionDetailScreen(tx: tx),
),
);
},
); );
} }
} }
+5 -4
View File
@@ -628,11 +628,11 @@ class _OverviewScreenState extends State<OverviewScreen> {
currency, currency,
), ),
label: switch (_labelFlow) { label: switch (_labelFlow) {
TxFlowFilter.income => 'Labeled income · $_periodTitle', TxFlowFilter.income => 'Income · $_periodTitle',
TxFlowFilter.expense => 'Labeled spend · $_periodTitle', TxFlowFilter.expense => 'Spend · $_periodTitle',
TxFlowFilter.all => _labelInvertChart TxFlowFilter.all => _labelInvertChart
? 'Labeled net (expense view) · $_periodTitle' ? 'Net (expense view) · $_periodTitle'
: 'Labeled net · $_periodTitle', : 'Net · $_periodTitle',
}, },
), ),
], ],
@@ -753,6 +753,7 @@ class _OverviewScreenState extends State<OverviewScreen> {
builder: (_) => TransactionsScreen( builder: (_) => TransactionsScreen(
initialMonth: initial, initialMonth: initial,
initialLabelIds: labelIds, initialLabelIds: labelIds,
initialLabelMatch: LabelMatchMode.or,
initialSearchInMonthOnly: !yearly && labelIds.isNotEmpty, initialSearchInMonthOnly: !yearly && labelIds.isNotEmpty,
initialYear: yearly ? period.year : null, initialYear: yearly ? period.year : null,
), ),
+109 -9
View File
@@ -6,10 +6,12 @@ import 'package:provider/provider.dart';
import '../models/bank.dart'; import '../models/bank.dart';
import '../models/transaction_meta.dart'; import '../models/transaction_meta.dart';
import '../providers/auth_provider.dart';
import '../providers/bank_provider.dart'; import '../providers/bank_provider.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
import '../utils/app_theme.dart'; import '../utils/app_theme.dart';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../widgets/admin_create_transaction_dialog.dart';
import '../widgets/label_parent_picker.dart'; import '../widgets/label_parent_picker.dart';
import '../widgets/recurring_template_sheet.dart'; import '../widgets/recurring_template_sheet.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
@@ -26,6 +28,7 @@ class TransactionDetailScreen extends StatefulWidget {
} }
class _TransactionDetailScreenState extends State<TransactionDetailScreen> { class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
late BankTransaction _tx;
late final TextEditingController _notesController; late final TextEditingController _notesController;
late final TextEditingController _labelSearchController; late final TextEditingController _labelSearchController;
late SimilarMatchCriteria _matchCriteria; late SimilarMatchCriteria _matchCriteria;
@@ -41,11 +44,12 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_tx = widget.tx;
final meta = context.read<TxMetaController>(); final meta = context.read<TxMetaController>();
final notes = meta.metaFor(widget.tx).notes; final notes = meta.metaFor(_tx).notes;
_notesController = TextEditingController(text: notes); _notesController = TextEditingController(text: notes);
_labelSearchController = TextEditingController(); _labelSearchController = TextEditingController();
final tx = widget.tx; final tx = _tx;
_matchCriteria = SimilarMatchCriteria( _matchCriteria = SimilarMatchCriteria(
pattern: defaultSimilarPattern(tx.description), pattern: defaultSimilarPattern(tx.description),
flow: tx.amount < 0 flow: tx.amount < 0
@@ -63,7 +67,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
if (!mounted) return; if (!mounted) return;
final all = context.read<BankController>().transactions; final all = context.read<BankController>().transactions;
final count = context.read<TxMetaController>().countSimilar( final count = context.read<TxMetaController>().countSimilar(
widget.tx, _tx,
all, all,
criteria: _matchCriteria, criteria: _matchCriteria,
); );
@@ -88,14 +92,14 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
List<BankTransaction> _similarScope(TxMetaController meta) { List<BankTransaction> _similarScope(TxMetaController meta) {
final all = context.read<BankController>().transactions; final all = context.read<BankController>().transactions;
if (!_applyToSimilar) return const []; if (!_applyToSimilar) return const [];
return meta.similarTo(widget.tx, all, criteria: _matchCriteria); return meta.similarTo(_tx, all, criteria: _matchCriteria);
} }
Future<void> _editMatchCriteria() async { Future<void> _editMatchCriteria() async {
final all = context.read<BankController>().transactions; final all = context.read<BankController>().transactions;
final result = await showSimilarMatchDialog( final result = await showSimilarMatchDialog(
context, context,
prototype: widget.tx, prototype: _tx,
all: all, all: all,
initial: _matchCriteria, initial: _matchCriteria,
); );
@@ -138,7 +142,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
final similar = _similarScope(meta); final similar = _similarScope(meta);
final count = similar.isEmpty ? 1 : similar.length; final count = similar.isEmpty ? 1 : similar.length;
await meta.setNotes( await meta.setNotes(
widget.tx, _tx,
_notesController.text, _notesController.text,
applyToSimilar: similar, applyToSimilar: similar,
matchPattern: _pattern, matchPattern: _pattern,
@@ -180,7 +184,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
() async { () async {
final meta = context.read<TxMetaController>(); final meta = context.read<TxMetaController>();
final similar = toMatched ? _similarScope(meta) : const <BankTransaction>[]; final similar = toMatched ? _similarScope(meta) : const <BankTransaction>[];
final targets = similar.isEmpty ? [widget.tx] : similar; final targets = similar.isEmpty ? [_tx] : similar;
await meta.setLabelsForMany( await meta.setLabelsForMany(
targets, targets,
_draftLabelIds.toList(growable: false), _draftLabelIds.toList(growable: false),
@@ -188,7 +192,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
_labelsDirty = false; _labelsDirty = false;
_draftLabelIds = meta.metaFor(widget.tx).labelIds.toSet(); _draftLabelIds = meta.metaFor(_tx).labelIds.toSet();
}); });
final count = targets.length; final count = targets.length;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -291,9 +295,79 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
await context.read<TxMetaController>().removeLabel(label.id); 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final tx = widget.tx; final tx = _tx;
final metaController = context.watch<TxMetaController>(); final metaController = context.watch<TxMetaController>();
final meta = metaController.metaFor(tx); final meta = metaController.metaFor(tx);
final similarCount = _similarCount; final similarCount = _similarCount;
@@ -317,11 +391,37 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
if (keep.contains(entry.label.id)) entry, if (keep.contains(entry.label.id)) entry,
]; ];
}(); }();
final canEditManual =
context.watch<AuthController>().isAdmin && tx.isManual;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Transaction'), title: const Text('Transaction'),
actions: [ 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) if (_dirty)
TextButton( TextButton(
onPressed: _busy ? null : _saveNotes, onPressed: _busy ? null : _saveNotes,
+42 -32
View File
@@ -9,7 +9,6 @@ import 'package:provider/provider.dart';
import '../models/bank.dart'; import '../models/bank.dart';
import '../models/transaction_meta.dart'; import '../models/transaction_meta.dart';
import '../providers/bank_provider.dart'; import '../providers/bank_provider.dart';
import '../providers/preferences_provider.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
import '../utils/app_theme.dart'; import '../utils/app_theme.dart';
import '../utils/connect_bank.dart'; import '../utils/connect_bank.dart';
@@ -17,7 +16,6 @@ import '../utils/helpers.dart';
import '../utils/navigation.dart'; import '../utils/navigation.dart';
import '../utils/tx_calendar.dart'; import '../utils/tx_calendar.dart';
import '../widgets/empty_state.dart'; import '../widgets/empty_state.dart';
import '../widgets/home_widgets_sheet.dart';
import '../widgets/label_filter_dialog.dart'; import '../widgets/label_filter_dialog.dart';
import '../widgets/loading_view.dart'; import '../widgets/loading_view.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
@@ -30,11 +28,13 @@ class TransactionsScreen extends StatefulWidget {
super.key, super.key,
this.initialMonth, this.initialMonth,
this.initialLabelIds = const {}, this.initialLabelIds = const {},
this.initialLabelMatch = LabelMatchMode.and,
this.initialSearchInMonthOnly, this.initialSearchInMonthOnly,
this.initialYear, this.initialYear,
this.initialQuery, this.initialQuery,
this.initialFlow, this.initialFlow,
this.initialAmountRange, this.initialAmountRange,
this.initialSimilarMatch,
}); });
/// When set, opens on this calendar month instead of the current month. /// 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). /// Pre-select these label filters (e.g. from overview history).
final Set<String> initialLabelIds; 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. /// When set, overrides the default "search in month" checkbox.
final bool? initialSearchInMonthOnly; final bool? initialSearchInMonthOnly;
@@ -55,6 +58,9 @@ class TransactionsScreen extends StatefulWidget {
final TxFlowFilter? initialFlow; final TxFlowFilter? initialFlow;
final TxAmountRange? initialAmountRange; final TxAmountRange? initialAmountRange;
/// Match txs the same way as “apply to similar” / Look ahead transaction source.
final SimilarMatchCriteria? initialSimilarMatch;
@override @override
State<TransactionsScreen> createState() => _TransactionsScreenState(); State<TransactionsScreen> createState() => _TransactionsScreenState();
} }
@@ -68,6 +74,8 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
DateTime? _selectedDay; DateTime? _selectedDay;
late bool _searchInMonthOnly; late bool _searchInMonthOnly;
late final Set<String> _labelFilters; late final Set<String> _labelFilters;
late LabelMatchMode _labelMatch;
SimilarMatchCriteria? _similarMatch;
int? _yearFilter; int? _yearFilter;
var _showCalendar = false; var _showCalendar = false;
var _flowFilter = TxFlowFilter.all; var _flowFilter = TxFlowFilter.all;
@@ -89,6 +97,8 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
_month = start.isAfter(now) ? now : start; _month = start.isAfter(now) ? now : start;
} }
_labelFilters = Set<String>.of(widget.initialLabelIds); _labelFilters = Set<String>.of(widget.initialLabelIds);
_labelMatch = widget.initialLabelMatch;
_similarMatch = widget.initialSimilarMatch;
// Default to current month so the list, navigator, and filter popup agree. // Default to current month so the list, navigator, and filter popup agree.
_searchInMonthOnly = widget.initialSearchInMonthOnly ?? true; _searchInMonthOnly = widget.initialSearchInMonthOnly ?? true;
_yearFilter = widget.initialYear; _yearFilter = widget.initialYear;
@@ -98,6 +108,11 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
if (initialQuery.isNotEmpty) { if (initialQuery.isNotEmpty) {
_searchController.text = initialQuery; _searchController.text = initialQuery;
_activeQuery = 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 => bool get _isSearching =>
_activeQuery.trim().isNotEmpty || _labelFilters.isNotEmpty; _activeQuery.trim().isNotEmpty ||
_labelFilters.isNotEmpty ||
_similarMatch != null;
bool get _hasListFilters => bool get _hasListFilters =>
_labelFilters.isNotEmpty || _labelFilters.isNotEmpty ||
_flowFilter != TxFlowFilter.all || _flowFilter != TxFlowFilter.all ||
_amountRange.isActive; _amountRange.isActive ||
_similarMatch != null;
bool _matchesExtraFilters(BankTransaction tx, TxMetaController meta) { bool _matchesExtraFilters(BankTransaction tx, TxMetaController meta) {
if (!txMatchesFlow(tx, _flowFilter)) return false; if (!txMatchesFlow(tx, _flowFilter)) return false;
if (!txMatchesAmountRange(tx, _amountRange)) return false; if (!txMatchesAmountRange(tx, _amountRange)) return false;
final similar = _similarMatch;
if (similar != null && !txMatchesSimilarCriteria(tx, similar)) {
return false;
}
return true; return true;
} }
@@ -147,6 +169,11 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
final trimmed = value.trim(); final trimmed = value.trim();
_searchDebounceTimer?.cancel(); _searchDebounceTimer?.cancel();
// Editing the box leaves “similar match” mode and uses plain text search.
if (_similarMatch != null) {
setState(() => _similarMatch = null);
}
if (trimmed.length >= _minLiveSearchChars) { if (trimmed.length >= _minLiveSearchChars) {
// TextField updates via the controller; only rebuild the list after debounce. // TextField updates via the controller; only rebuild the list after debounce.
_searchDebounceTimer = Timer(_searchDebounce, () { _searchDebounceTimer = Timer(_searchDebounce, () {
@@ -165,13 +192,19 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
void _onSearchSubmitted(String value) { void _onSearchSubmitted(String value) {
_searchDebounceTimer?.cancel(); _searchDebounceTimer?.cancel();
setState(() => _activeQuery = value.trim()); setState(() {
_similarMatch = null;
_activeQuery = value.trim();
});
} }
void _clearSearch() { void _clearSearch() {
_searchDebounceTimer?.cancel(); _searchDebounceTimer?.cancel();
_searchController.clear(); _searchController.clear();
setState(() => _activeQuery = ''); setState(() {
_activeQuery = '';
_similarMatch = null;
});
} }
Future<void> _pickFilters(List<TxLabel> available) async { Future<void> _pickFilters(List<TxLabel> available) async {
@@ -183,6 +216,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
currentMonth: _month, currentMonth: _month,
initial: TransactionFilterSelection( initial: TransactionFilterSelection(
labelIds: Set<String>.of(_labelFilters), labelIds: Set<String>.of(_labelFilters),
labelMatch: _labelMatch,
flow: _flowFilter, flow: _flowFilter,
amountRange: _amountRange, amountRange: _amountRange,
query: _activeQuery, query: _activeQuery,
@@ -195,6 +229,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
_labelFilters _labelFilters
..clear() ..clear()
..addAll(result.labelIds); ..addAll(result.labelIds);
_labelMatch = result.labelMatch;
_flowFilter = result.flow; _flowFilter = result.flow;
_amountRange = result.amountRange; _amountRange = result.amountRange;
_searchInMonthOnly = result.monthOnly; _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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final bank = context.watch<BankController>(); final bank = context.watch<BankController>();
@@ -269,11 +283,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
appBar: AppBar( appBar: AppBar(
title: const Text('Transactions'), title: const Text('Transactions'),
actions: [ actions: [
IconButton(
tooltip: 'Save as Home widget',
onPressed: _saveAsHomeWidget,
icon: const Icon(Icons.dashboard_customize_outlined),
),
...bankAppBarActions( ...bankAppBarActions(
context: context, context: context,
onRefresh: bank.refresh, onRefresh: bank.refresh,
@@ -386,6 +395,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
searchPool, searchPool,
_activeQuery, _activeQuery,
labelIds: _labelFilters, labelIds: _labelFilters,
labelMatch: _labelMatch,
)) ))
if (_matchesExtraFilters(tx, metaController)) tx, if (_matchesExtraFilters(tx, metaController)) tx,
]; ];
+32 -1
View File
@@ -534,6 +534,7 @@ class PbSyncService {
}, },
'budgetAverageMonths': r.getIntValue('budget_average_months', 3), 'budgetAverageMonths': r.getIntValue('budget_average_months', 3),
'labelIds': _jsonStringList(r.get<dynamic>('label_ids')), 'labelIds': _jsonStringList(r.get<dynamic>('label_ids')),
'labelMatch': r.getStringValue('label_match'),
'flow': r.getStringValue('flow'), 'flow': r.getStringValue('flow'),
'amountRange': rangeRaw is Map 'amountRange': rangeRaw is Map
? Map<String, dynamic>.from(rangeRaw) ? Map<String, dynamic>.from(rangeRaw)
@@ -647,6 +648,7 @@ class PbSyncService {
8, 8,
), ),
'pending': tx.pending, 'pending': tx.pending,
'is_manual': tx.isManual,
}; };
final remote = existing[syncId]; final remote = existing[syncId];
if (remote == null) { if (remote == null) {
@@ -698,6 +700,7 @@ class PbSyncService {
? 'EUR' ? 'EUR'
: r.getStringValue('currency'), : r.getStringValue('currency'),
pending: r.getBoolValue('pending'), pending: r.getBoolValue('pending'),
isManual: r.getBoolValue('is_manual'),
); );
} }
@@ -714,7 +717,30 @@ class PbSyncService {
(remoteAmount * 100).round() == (tx.amount * 100).round() && (remoteAmount * 100).round() == (tx.amount * 100).round() &&
remote.getStringValue('currency').toUpperCase() == remote.getStringValue('currency').toUpperCase() ==
tx.currency.toUpperCase() && tx.currency.toUpperCase() &&
remote.getBoolValue('pending') == tx.pending; remote.getBoolValue('pending') == tx.pending &&
remote.getBoolValue('is_manual') == 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';
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),
];
if (ops.isEmpty) {
return 'Bank txs: 0 remote deletes (ids ${ids.length})';
}
await _runWriteOps('transactions', ops);
return 'Bank txs: deleted ${ops.length} remote row(s)';
} }
Future<void> _runOne(String collection, _BatchOp op) { Future<void> _runOne(String collection, _BatchOp op) {
@@ -1259,6 +1285,7 @@ class PbSyncService {
'budget_fixed_amount': w.budgetFixedAmount, 'budget_fixed_amount': w.budgetFixedAmount,
'budget_average_months': w.budgetAverageMonths, 'budget_average_months': w.budgetAverageMonths,
'label_ids': w.labelIds, 'label_ids': w.labelIds,
'label_match': w.labelMatch.name,
'flow': w.flow.name, 'flow': w.flow.name,
'amount_range': { 'amount_range': {
if (w.amountRange.exact != null) 'exact': w.amountRange.exact, if (w.amountRange.exact != null) 'exact': w.amountRange.exact,
@@ -1402,6 +1429,10 @@ class PbSyncService {
remote.getIntValue('budget_average_months', 3) == remote.getIntValue('budget_average_months', 3) ==
w.budgetAverageMonths && w.budgetAverageMonths &&
_sameIdList(remoteIds, w.labelIds) && _sameIdList(remoteIds, w.labelIds) &&
(remote.getStringValue('label_match').isEmpty
? 'and'
: remote.getStringValue('label_match')) ==
w.labelMatch.name &&
remote.getStringValue('flow') == w.flow.name && remote.getStringValue('flow') == w.flow.name &&
asDouble(rangeMap['exact']) == w.amountRange.exact && asDouble(rangeMap['exact']) == w.amountRange.exact &&
asDouble(rangeMap['min']) == w.amountRange.min && asDouble(rangeMap['min']) == w.amountRange.min &&
+2 -18
View File
@@ -65,14 +65,7 @@ class BankCache {
'balanceType': balance!.balanceType, 'balanceType': balance!.balanceType,
}, },
'transactions': [ 'transactions': [
for (final tx in transactions) for (final tx in transactions) tx.toJson(),
{
'date': tx.date,
'description': tx.description,
'amount': tx.amount,
'currency': tx.currency,
'pending': tx.pending,
},
], ],
}; };
@@ -258,16 +251,7 @@ class StorageService {
} }
Future<void> saveImportedTransactions(List<BankTransaction> txs) async { Future<void> saveImportedTransactions(List<BankTransaction> txs) async {
final encoded = [ final encoded = [for (final tx in txs) tx.toJson()];
for (final tx in txs)
{
'date': tx.date,
'description': tx.description,
'amount': tx.amount,
'currency': tx.currency,
'pending': tx.pending,
},
];
final json = await compute(jsonEncode, encoded); final json = await compute(jsonEncode, encoded);
await _prefs.setString(StorageKeys.importedTransactions, json); await _prefs.setString(StorageKeys.importedTransactions, json);
} }
+16
View File
@@ -12,6 +12,22 @@ abstract final class AppTheme {
/// Soft rose for expenses / money out. /// Soft rose for expenses / money out.
static const Color expense = Color(0xFFE07A7A); 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). /// Near-black charcoal scaffold (dark).
static const Color darkCanvas = Color(0xFF0B0D0C); static const Color darkCanvas = Color(0xFF0B0D0C);
+1
View File
@@ -69,6 +69,7 @@ List<BankTransaction> applyTransactionFilter({
pool, pool,
filter.query, filter.query,
labelIds: filter.labelIds, labelIds: filter.labelIds,
labelMatch: filter.labelMatch,
)) ))
if (txMatchesFlow(tx, filter.flow) && if (txMatchesFlow(tx, filter.flow) &&
txMatchesAmountRange(tx, filter.amountRange)) 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'),
),
],
);
}
}
+44 -22
View File
@@ -37,6 +37,7 @@ class HomeFilterWidgetCard extends StatelessWidget {
MaterialPageRoute<void>( MaterialPageRoute<void>(
builder: (_) => TransactionsScreen( builder: (_) => TransactionsScreen(
initialLabelIds: filter.labelIds, initialLabelIds: filter.labelIds,
initialLabelMatch: filter.labelMatch,
initialSearchInMonthOnly: initialSearchInMonthOnly:
widgetConfig.type == HomeWidgetType.budget || filter.monthOnly, widgetConfig.type == HomeWidgetType.budget || filter.monthOnly,
initialQuery: filter.query, initialQuery: filter.query,
@@ -370,8 +371,11 @@ class _BudgetBody extends StatelessWidget {
widget: widgetConfig, widget: widgetConfig,
); );
final progress = budget.progress.clamp(0.0, 1.0); final progress = budget.progress.clamp(0.0, 1.0);
final over = budget.overBudget; final fillColor = budget.overBudget
final fillColor = over ? colors.error : colors.primary; ? AppTheme.expense
: AppTheme.budgetProgressFill(
budget.target <= 0 ? 0 : progress,
);
// Grayish unfilled track (not green-tinted). // Grayish unfilled track (not green-tinted).
final trackColor = Color.alphaBlend( final trackColor = Color.alphaBlend(
colors.onSurface.withValues(alpha: 0.14), colors.onSurface.withValues(alpha: 0.14),
@@ -497,24 +501,40 @@ class _BudgetBody extends StatelessWidget {
), ),
], ],
), ),
HomeWidgetChartStyle.pie || HomeWidgetChartStyle.ring => Row( HomeWidgetChartStyle.pie || HomeWidgetChartStyle.ring => half
crossAxisAlignment: CrossAxisAlignment.center, // Stack on half cards so amounts never get crushed beside the ring
children: [ // (and avoid LayoutBuilder — half rows use IntrinsicHeight).
Expanded( ? Column(
child: Column( crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, children: [
mainAxisAlignment: MainAxisAlignment.center, capLine,
children: [ const SizedBox(height: 6),
capLine, spentLine,
const SizedBox(height: 8), const SizedBox(height: 8),
spentLine, 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 +609,9 @@ class _BudgetLegendLine extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(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( return Row(
mainAxisSize: MainAxisSize.min,
children: [ children: [
Container( Container(
width: 7, width: 7,
@@ -600,11 +621,12 @@ class _BudgetLegendLine extends StatelessWidget {
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
), ),
const SizedBox(width: 8), const SizedBox(width: 6),
Flexible( Expanded(
child: Text( child: Text(
text, text,
maxLines: 1, maxLines: 1,
softWrap: false,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: theme.textTheme.labelMedium?.copyWith( style: theme.textTheme.labelMedium?.copyWith(
color: textColor, color: textColor,
+1
View File
@@ -55,6 +55,7 @@ Future<HomeFilterWidget?> composeHomeFilterWidget(
? HomeFilterWidget.fromFilter(name: 'Filter', filter: filter) ? HomeFilterWidget.fromFilter(name: 'Filter', filter: filter)
: existing.copyWith( : existing.copyWith(
labelIds: filter.labelIds.toList(growable: false), labelIds: filter.labelIds.toList(growable: false),
labelMatch: filter.labelMatch,
flow: filter.flow, flow: filter.flow,
amountRange: filter.amountRange, amountRange: filter.amountRange,
query: filter.query, query: filter.query,
+33 -1
View File
@@ -15,6 +15,7 @@ import 'label_parent_picker.dart';
class TransactionFilterSelection { class TransactionFilterSelection {
const TransactionFilterSelection({ const TransactionFilterSelection({
required this.labelIds, required this.labelIds,
this.labelMatch = LabelMatchMode.and,
this.flow = TxFlowFilter.all, this.flow = TxFlowFilter.all,
this.amountRange = const TxAmountRange(), this.amountRange = const TxAmountRange(),
this.query = '', this.query = '',
@@ -22,6 +23,10 @@ class TransactionFilterSelection {
}); });
final Set<String> labelIds; final Set<String> labelIds;
/// AND vs OR when more than one label is selected.
final LabelMatchMode labelMatch;
final TxFlowFilter flow; final TxFlowFilter flow;
final TxAmountRange amountRange; final TxAmountRange amountRange;
final String query; final String query;
@@ -497,6 +502,7 @@ class _TransactionFilterDialog extends StatefulWidget {
class _TransactionFilterDialogState extends State<_TransactionFilterDialog> { class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
late final Set<String> _selected; late final Set<String> _selected;
late LabelMatchMode _labelMatch;
late TxFlowFilter _flow; late TxFlowFilter _flow;
late bool _monthOnly; late bool _monthOnly;
late final TextEditingController _queryController; late final TextEditingController _queryController;
@@ -510,6 +516,7 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
super.initState(); super.initState();
final initial = widget.initial; final initial = widget.initial;
_selected = Set<String>.of(initial.labelIds); _selected = Set<String>.of(initial.labelIds);
_labelMatch = initial.labelMatch;
_flow = initial.flow; _flow = initial.flow;
_monthOnly = initial.monthOnly; _monthOnly = initial.monthOnly;
_queryController = TextEditingController(text: initial.query); _queryController = TextEditingController(text: initial.query);
@@ -593,6 +600,7 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
context, context,
TransactionFilterSelection( TransactionFilterSelection(
labelIds: Set<String>.of(_selected), labelIds: Set<String>.of(_selected),
labelMatch: _labelMatch,
flow: _flow, flow: _flow,
amountRange: _amountResult, amountRange: _amountResult,
query: _queryController.text.trim(), query: _queryController.text.trim(),
@@ -840,7 +848,10 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
), ),
onChanged: (_) => setState(() {}), onChanged: (_) => setState(() {}),
), ),
Row( Wrap(
spacing: 0,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [ children: [
TextButton( TextButton(
onPressed: () { onPressed: () {
@@ -859,6 +870,27 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
onPressed: () => setState(() => _selected.clear()), onPressed: () => setState(() => _selected.clear()),
child: const Text('No labels'), 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), 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 (_) {}
});
+7
View File
@@ -19,12 +19,19 @@ void main() {
expect(restored.flow, TxFlowFilter.expense); expect(restored.flow, TxFlowFilter.expense);
expect(restored.monthOnly, isTrue); expect(restored.monthOnly, isTrue);
expect(restored.labelIds, ['groceries']); expect(restored.labelIds, ['groceries']);
expect(restored.labelMatch, LabelMatchMode.and);
expect(restored.showAmountOut, isTrue); expect(restored.showAmountOut, isTrue);
expect(restored.showAmountIn, isFalse); expect(restored.showAmountIn, isFalse);
expect(restored.showCount, isTrue); expect(restored.showCount, isTrue);
expect(restored.halfWidth, isFalse); expect(restored.halfWidth, isFalse);
expect(restored.type, HomeWidgetType.stats); expect(restored.type, HomeWidgetType.stats);
final withOr = widget.copyWith(labelMatch: LabelMatchMode.or);
expect(
HomeFilterWidget.fromJson(withOr.toJson()).labelMatch,
LabelMatchMode.or,
);
final budget = widget.copyWith( final budget = widget.copyWith(
halfWidth: true, halfWidth: true,
type: HomeWidgetType.budget, type: HomeWidgetType.budget,