19 Commits
Author SHA1 Message Date
davmar 40366f0708 some issues fixed 2026-09-11 12:31:07 +02:00
davmar 2e40786bcd attempt to fix test txs 2.1 2026-09-11 00:11:00 +02:00
davmar 38bcf01ae3 attempt to fix test txs 2 2026-09-11 00:10:15 +02:00
davmar 00ab05eefc attempt to fix test txs 2026-09-10 23:59:00 +02:00
davmar f8e293f823 admin user able to create test txs 2026-09-10 23:18:24 +02:00
davmar c4f0ca785e user admin capability 2026-09-10 22:58:52 +02:00
davmar 6cc0de8945 fixed some issues and added label and, or capability 2026-09-10 22:45:25 +02:00
davmar b4d367f056 splash screen update 2026-09-10 21:11:12 +02:00
davmar c3d2680ca7 logo and readme update 2026-09-10 21:07:07 +02:00
davmar e7617a2d98 ok lets ship for now 2026-09-10 20:44:59 +02:00
davmar 3187499385 ok lets ship for now 2026-09-10 20:44:54 +02:00
davmar 4dde907f52 widgets looking very ok 2026-09-10 18:56:50 +02:00
davmar 55a13ee650 widgets looking ok 2026-09-10 18:51:35 +02:00
davmar ecc5185d3b new widget types 3 2026-09-10 17:37:10 +02:00
davmar 68a2a484c6 new widget types 2 2026-09-10 17:34:28 +02:00
davmar 86b5f1e09b new widget types 2026-09-10 17:31:18 +02:00
davmar 2727f1baf2 custom filters 2026-09-10 17:23:07 +02:00
davmar 83295439d5 new favourites feature 2026-09-10 16:25:24 +02:00
davmar aec89ac41d fix sync 2026-09-10 11:40:28 +02:00
62 changed files with 7538 additions and 567 deletions
+145 -61
View File
@@ -1,83 +1,167 @@
# MyApp # IngTrak
Generic Flutter Android starter built with Flutter **3.47** (Dart **3.13**), Material 3, null safety, and [Provider](https://pub.dev/packages/provider) for state management. Personal finance app for **Enable Banking** (ING and other supported banks): transactions, labels, charts, budgets, look-ahead projections, and **PocketBase** cloud sync.
Package name: `com.ingtrak.app` - **Package:** `com.ingtrak.app`
- **Platform:** Android (Flutter)
- **Flutter:** 3.47+ · **Dart:** 3.13+
## Features ## Features
- Splash screen that fades into the main shell - **Bank connect** — Enable Banking via backend API + in-app WebView; optional deep link `ingtrak://connected`
- Bottom navigation: Home, Search, Profile, Settings - **Home** — Balance, customizable layout: built-in sections (Transactions / Categorized / Recent) and filter widgets (stats or budget, half/full width, bar/pie/ring)
- `ListView.builder` catalog with rounded, shadowed cards - **Transactions** — Search, filters, month heatmap, labels, notes, merchant / “apply to similar” rules
- Detail screen with a matching `Hero` animation - **Overview** — Income/expense and label charts; save **favourite** chart filters
- Light / dark / system theme, persisted with `shared_preferences` - **Look ahead** — Projected balance from recurring templates
- Add-item form with validation - **Sync** — Bidirectional PocketBase sync (transactions, labels, annotations, favourites, home widgets, app prefs)
- Mock catalog plus an `http` client aimed at JSONPlaceholder (toggle in Settings) - **Theme** — Light / dark / system (local)
- **CSV** — Import ING CSV exports (Settings)
## Folder structure ## Prerequisites
- [Flutter SDK](https://docs.flutter.dev/get-started/install) **3.47** or newer (Dart **3.13**)
- Android Studio / SDK (Java **17**), emulator or device
- Reachable **bank API** (`API_BASE_URL`) and **PocketBase** (`POCKETBASE_URL`)
- PocketBase auth collection **`usersapp`** (create this before running migrations)
```bash
flutter doctor
flutter doctor --android-licenses # if prompted
```
## Quick start
```bash
cd ingtrakapp
cp .env.example .env # edit URLs if needed
flutter pub get
flutter devices
flutter run # or: flutter run -d android
```
First Android build downloads Gradle and may take a few minutes.
### Useful commands
```bash
flutter analyze
flutter test
flutter run --release
flutter build apk
```
### Override config without editing `.env`
```bash
flutter run \
--dart-define=API_BASE_URL=https://your-api.example \
--dart-define=POCKETBASE_URL=https://your-pb.example \
--dart-define=POCKETBASE_USERS_COLLECTION=usersapp
```
`--dart-define` values win over `.env`.
## Configuration
Copy [`.env.example`](.env.example) to `.env` (both are listed as Flutter assets). No secrets belong in these files.
| Variable | Purpose | Example |
|----------|---------|---------|
| `API_BASE_URL` | FastAPI bank / Enable Banking proxy | `https://ingtrak.satoshinakamoto.win` |
| `POCKETBASE_URL` | PocketBase instance | `https://pb.satoshinakamoto.win` |
| `POCKETBASE_USERS_COLLECTION` | Auth collection name | `usersapp` |
Loaded in `lib/utils/app_config.dart` at startup (`flutter_dotenv`). Fallbacks: hosted API URL, PocketBase `http://127.0.0.1:8090`.
### Bank redirect URIs
1. **HTTP callback (Enable Banking Control Panel / backend `REDIRECT_URI`):**
`{API_BASE_URL}/api/connect/callback`
2. **Optional app deep link** (after HTML bounce; not registered with Enable Banking):
`ingtrak://connected?code=…`
Declared in `AndroidManifest.xml` and handled via `app_links`.
## PocketBase setup
Migrations live in [`pocketbase/pb_migrations/`](pocketbase/pb_migrations/). They assume collection **`usersapp`** already exists.
### Collections
| Migration | Collection |
|-----------|------------|
| `1740000000` | `labels`, `tx_meta`, `merchant_rules`, `exact_templates` |
| `1740000001` | `transactions` |
| `1740000002` | `recurring_templates` |
| `1740000003` | `overview_favourites` |
| `1740000004`–`0006` | `home_filter_widgets` (+ half width, budget fields) |
| `1740000007` | `app_prefs` (Home section toggles + Look ahead years) |
| `1740000008` | `home_filter_widgets.label_match` (AND/OR) |
| `1740000009` | `usersapp.is_admin` (admin accounts) |
Built-in labels stay in the app; only **custom** labels sync. Rows are scoped per user (`user = @request.auth.id`).
### Admin accounts
Migration `1740000009` adds `is_admin` (bool) on **`usersapp`**. In PocketBase Admin → **Users** → edit a user → enable **is_admin**.
Admins see an **Admin** badge on Account and can **Create test transaction** (saved locally and synced with bank transactions). Normal users do not get that action. Re-sign-in after flipping the flag so the app picks it up.
### Apply migrations (typical Linux host)
```bash
sudo cp pocketbase/pb_migrations/*.js /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
```
Adjust paths if your PocketBase install differs. After migrate, sign in on the app and run **Sync** (Account) so local data uploads.
### What syncs
- Bank transactions, labels, tx annotations, merchant/exact templates
- Recurring templates, overview favourites, home filter widgets
- App prefs: Home built-in section visibility, Look ahead max years
Theme mode stays **device-local**.
## Project layout
``` ```
android-flutter-app-generic/ ingtrakapp/
├── android/ # Android embedding, Gradle, manifest ├── android/ # Android embedding (com.ingtrak.app)
├── assets/branding/ # App icon source + generated launcher assets
├── lib/ ├── lib/
│ ├── main.dart # Entry point, Provider scope, MaterialApp │ ├── main.dart # Providers, dotenv, deep links
│ ├── models/ │ ├── models/ # Bank, meta, favourites, home widgets, prefs
│ │ └── item.dart # Item + ItemCategory │ ├── providers/ # Auth, bank, sync, tx_meta, preferences, theme
│ ├── providers/ │ ├── screens/ # Splash, auth, Home / Overview / Look ahead, …
│ │ ├── item_provider.dart # Catalog ChangeNotifier │ ├── services/ # Bank API, PocketBase sync, CSV, storage
│ │ └── theme_provider.dart # ThemeMode ChangeNotifier │ ├── utils/ # Config, theme, constants, connect helpers
│ ├── screens/ │ └── widgets/ # Home widgets, filters, charts, sync UI
│ │ ├── splash_screen.dart ├── pocketbase/pb_migrations/ # Schema migrations
│ │ ├── main_shell.dart # NavigationBar host
│ │ ├── home_screen.dart
│ │ ├── search_screen.dart
│ │ ├── profile_screen.dart
│ │ ├── settings_screen.dart
│ │ ├── item_detail_screen.dart
│ │ └── add_item_screen.dart
│ ├── services/
│ │ ├── storage_service.dart # shared_preferences wrapper
│ │ ├── item_api.dart # http placeholder
│ │ ├── fake_item_data.dart # Offline sample catalog
│ │ └── item_repository.dart # Mock vs remote switch
│ ├── utils/
│ │ ├── app_theme.dart # Material 3 light/dark themes
│ │ ├── constants.dart
│ │ └── helpers.dart
│ └── widgets/
│ ├── app_text_field.dart
│ ├── empty_state.dart
│ ├── item_card.dart
│ ├── item_hero_badge.dart
│ ├── loading_view.dart
│ └── responsive_body.dart
├── test/ ├── test/
│ └── widget_test.dart ├── .env.example
└── pubspec.yaml └── pubspec.yaml
``` ```
## Run the app ## Launcher icon
You need the [Flutter SDK](https://docs.flutter.dev/get-started/install) (3.47 or newer) and an Android emulator or device. Source: `assets/branding/app_icon.png`. Regenerate Android mipmaps:
```bash ```bash
cd android-flutter-app-generic dart run flutter_launcher_icons
flutter pub get
flutter run
``` ```
Useful extras: (Configured in `pubspec.yaml`; iOS not enabled — no `ios/` folder yet.)
```bash ## First-run checklist
flutter devices # list emulators / devices
flutter run -d android # target Android explicitly
flutter analyze # static analysis
flutter test # widget + unit tests
```
On first Android run, Flutter will download a Gradle distribution and compile the app. Accept any Android licenses with `flutter doctor --android-licenses` if prompted. 1. `.env` points at your API + PocketBase
2. PocketBase migrations applied; `usersapp` exists; create an account (or use Admin → Users)
3. Backend Enable Banking `REDIRECT_URI` matches `{API_BASE_URL}/api/connect/callback`
4. `flutter run` → sign in → **Settings** → connect bank (or import CSV) → **Account** → Sync
## Theme and data ## License / privacy
- Open **Settings** to switch System / Light / Dark. The choice is stored locally. Private project. Bank credentials and tokens are handled by your backend and Enable Banking — keep API and PocketBase access controlled.
- Turn on **Use remote sample API** to fetch posts from `https://jsonplaceholder.typicode.com/posts` through the `http` package. If the request fails, the app falls back to the bundled mock list.
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground>
<inset
android:drawable="@drawable/ic_launcher_foreground"
android:inset="16%" />
</foreground>
</adaptive-icon>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 544 B

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 442 B

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 721 B

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#1A1C1B</color>
</resources>
Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

+9 -4
View File
@@ -49,6 +49,7 @@ class MyApp extends StatefulWidget {
class _MyAppState extends State<MyApp> { class _MyAppState extends State<MyApp> {
late final BankController _bank; late final BankController _bank;
late final TxMetaController _meta; late final TxMetaController _meta;
late final PreferencesController _prefs;
late final SyncController _sync; late final SyncController _sync;
late final AppLinks _appLinks; late final AppLinks _appLinks;
StreamSubscription<Uri>? _linkSub; StreamSubscription<Uri>? _linkSub;
@@ -57,8 +58,14 @@ class _MyAppState extends State<MyApp> {
void initState() { void initState() {
super.initState(); super.initState();
_meta = TxMetaController(widget.storage); _meta = TxMetaController(widget.storage);
_prefs = PreferencesController(widget.storage);
_bank = BankController(storage: widget.storage)..refresh(); _bank = BankController(storage: widget.storage)..refresh();
_sync = SyncController(auth: widget.auth, meta: _meta, bank: _bank); _sync = SyncController(
auth: widget.auth,
meta: _meta,
bank: _bank,
prefs: _prefs,
);
_appLinks = AppLinks(); _appLinks = AppLinks();
_listenForBankRedirects(); _listenForBankRedirects();
} }
@@ -97,9 +104,7 @@ class _MyAppState extends State<MyApp> {
providers: [ providers: [
ChangeNotifierProvider<AuthController>.value(value: widget.auth), ChangeNotifierProvider<AuthController>.value(value: widget.auth),
ChangeNotifierProvider(create: (_) => ThemeController(widget.storage)), ChangeNotifierProvider(create: (_) => ThemeController(widget.storage)),
ChangeNotifierProvider( ChangeNotifierProvider<PreferencesController>.value(value: _prefs),
create: (_) => PreferencesController(widget.storage),
),
ChangeNotifierProvider<TxMetaController>.value(value: _meta), ChangeNotifierProvider<TxMetaController>.value(value: _meta),
ChangeNotifierProvider<SyncController>.value(value: _sync), ChangeNotifierProvider<SyncController>.value(value: _sync),
ChangeNotifierProvider<BankController>.value(value: _bank), ChangeNotifierProvider<BankController>.value(value: _bank),
+41
View File
@@ -0,0 +1,41 @@
/// Cloud-synced app preferences (Home sections + Look ahead).
library;
import 'home_built_in_sections.dart';
/// One-per-user prefs row mirrored in PocketBase `app_prefs`.
class AppCloudPrefs {
const AppCloudPrefs({
required this.homeBuiltInSections,
required this.lookAheadMaxYears,
});
final HomeBuiltInSections homeBuiltInSections;
final int lookAheadMaxYears;
static const defaults = AppCloudPrefs(
homeBuiltInSections: HomeBuiltInSections.defaults,
lookAheadMaxYears: 5,
);
AppCloudPrefs copyWith({
HomeBuiltInSections? homeBuiltInSections,
int? lookAheadMaxYears,
}) {
return AppCloudPrefs(
homeBuiltInSections:
homeBuiltInSections ?? this.homeBuiltInSections,
lookAheadMaxYears: lookAheadMaxYears ?? this.lookAheadMaxYears,
);
}
}
/// Prefer local when the user has pending edits; otherwise take remote.
AppCloudPrefs mergeAppCloudPrefs({
required AppCloudPrefs local,
required AppCloudPrefs? remote,
required bool preferLocal,
}) {
if (preferLocal || remote == null) return local;
return remote;
}
+51
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,50 @@ 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';
static String stripManualStamp(String description) =>
description.replaceFirst(RegExp(r' ·#\d+$'), '');
/// True when [other] is the same row for delete/tombstone matching.
///
/// Uses id first, then date + cents + currency + description (stamp-insensitive),
/// so PocketBase float/amount rehydration cannot bypass a local delete.
bool matchesForDelete(BankTransaction other) {
if (id == other.id) return true;
if (date != other.date) return false;
if (currency.toUpperCase() != other.currency.toUpperCase()) return false;
if ((amount * 100).round() != (other.amount * 100).round()) return false;
if (descriptionKey == other.descriptionKey) return true;
return stripManualStamp(description).trim().toLowerCase() ==
stripManualStamp(other.description).trim().toLowerCase();
}
BankTransaction copyWith({
String? date,
String? description,
double? amount,
String? currency,
bool? pending,
bool? isManual,
}) {
return BankTransaction(
date: date ?? this.date,
description: description ?? this.description,
amount: amount ?? this.amount,
currency: currency ?? this.currency,
pending: pending ?? this.pending,
isManual: isManual ?? this.isManual,
);
}
Map<String, dynamic> toJson() => {
'date': date,
'description': description,
'amount': amount,
'currency': currency,
'pending': pending,
if (isManual) 'isManual': true,
};
factory BankTransaction.fromJson(Map<String, dynamic> json) { 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 +170,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,
); );
} }
} }
+43
View File
@@ -0,0 +1,43 @@
/// Visibility flags for built-in Home screen sections.
library;
class HomeBuiltInSections {
const HomeBuiltInSections({
this.showTransactions = true,
this.showCategorized = true,
this.showRecent = true,
});
static const defaults = HomeBuiltInSections();
final bool showTransactions;
final bool showCategorized;
final bool showRecent;
HomeBuiltInSections copyWith({
bool? showTransactions,
bool? showCategorized,
bool? showRecent,
}) {
return HomeBuiltInSections(
showTransactions: showTransactions ?? this.showTransactions,
showCategorized: showCategorized ?? this.showCategorized,
showRecent: showRecent ?? this.showRecent,
);
}
Map<String, dynamic> toJson() => {
'showTransactions': showTransactions,
'showCategorized': showCategorized,
'showRecent': showRecent,
};
factory HomeBuiltInSections.fromJson(Map<String, dynamic>? json) {
if (json == null) return defaults;
return HomeBuiltInSections(
showTransactions: json['showTransactions'] as bool? ?? true,
showCategorized: json['showCategorized'] as bool? ?? true,
showRecent: json['showRecent'] as bool? ?? true,
);
}
}
+351
View File
@@ -0,0 +1,351 @@
/// Named transaction-filter widgets pinned on the Home screen.
library;
import 'package:flutter/material.dart';
import '../widgets/label_filter_dialog.dart';
import 'transaction_meta.dart';
/// What a Home filter widget shows.
enum HomeWidgetType {
/// In / Out / count metrics.
stats,
/// Progress of this month’s net toward a budget cap.
budget,
}
/// How the budget ceiling is chosen.
enum HomeBudgetCapMode {
/// User-entered amount (positive).
fixed,
/// Absolute average of monthly nets over the last N months.
averageMonths,
}
/// Budget progress visualization.
enum HomeWidgetChartStyle {
bar,
pie,
ring,
}
/// Preset icons users can assign to a Home widget.
abstract final class HomeWidgetIcons {
static const List<(String id, IconData icon, String label)> all = [
('dashboard', Icons.dashboard_outlined, 'Dashboard'),
('savings', Icons.savings_outlined, 'Savings'),
('wallet', Icons.account_balance_wallet_outlined, 'Wallet'),
('cart', Icons.shopping_cart_outlined, 'Shopping'),
('bag', Icons.shopping_bag_outlined, 'Bag'),
('food', Icons.restaurant_outlined, 'Food'),
('bolt', Icons.bolt_outlined, 'Utilities'),
('home', Icons.home_work_outlined, 'Home'),
('car', Icons.directions_car_outlined, 'Transport'),
('bus', Icons.directions_bus_outlined, 'Transit'),
('health', Icons.local_hospital_outlined, 'Health'),
('sport', Icons.fitness_center_outlined, 'Sport'),
('travel', Icons.flight_outlined, 'Travel'),
('gift', Icons.card_giftcard_outlined, 'Gifts'),
('pets', Icons.pets_outlined, 'Pets'),
('work', Icons.work_outline, 'Work'),
('pay', Icons.payments_outlined, 'Pay'),
('swap', Icons.swap_horiz, 'Transfers'),
('chart', Icons.pie_chart_outline, 'Chart'),
('flag', Icons.flag_outlined, 'Goal'),
];
static IconData iconFor(String? id) {
for (final entry in all) {
if (entry.$1 == id) return entry.$2;
}
return Icons.dashboard_outlined;
}
static String labelFor(String? id) {
for (final entry in all) {
if (entry.$1 == id) return entry.$3;
}
return 'Dashboard';
}
}
/// A saved [TransactionFilterSelection] plus Home display options.
class HomeFilterWidget {
const HomeFilterWidget({
required this.id,
required this.name,
this.display = true,
this.sortOrder = 0,
this.halfWidth = false,
this.type = HomeWidgetType.stats,
this.iconId = 'dashboard',
this.chartStyle = HomeWidgetChartStyle.bar,
this.budgetCapMode = HomeBudgetCapMode.fixed,
this.budgetFixedAmount = 0,
this.budgetAverageMonths = 3,
this.labelIds = const [],
this.labelMatch = LabelMatchMode.and,
this.flow = TxFlowFilter.all,
this.amountRange = const TxAmountRange(),
this.query = '',
this.monthOnly = false,
this.showAmountIn = true,
this.showAmountOut = true,
this.showCount = true,
this.updatedAt = 0,
this.deleted = false,
});
final String id;
final String name;
final bool display;
final int sortOrder;
/// When true, the Home card uses half the row width.
final bool halfWidth;
final HomeWidgetType type;
final String iconId;
final HomeWidgetChartStyle chartStyle;
final HomeBudgetCapMode budgetCapMode;
/// Positive ceiling when [budgetCapMode] is [HomeBudgetCapMode.fixed].
final double budgetFixedAmount;
/// Months of history when [budgetCapMode] is [HomeBudgetCapMode.averageMonths].
final int budgetAverageMonths;
final List<String> labelIds;
/// AND vs OR when multiple [labelIds] are selected.
final LabelMatchMode labelMatch;
final TxFlowFilter flow;
final TxAmountRange amountRange;
final String query;
final bool monthOnly;
final bool showAmountIn;
final bool showAmountOut;
final bool showCount;
/// Epoch ms; used for last-write-wins sync across devices.
final int updatedAt;
/// Soft-delete so removals propagate via sync instead of being recreated.
final bool deleted;
IconData get icon => HomeWidgetIcons.iconFor(iconId);
TransactionFilterSelection get filter => TransactionFilterSelection(
labelIds: labelIds.toSet(),
labelMatch: labelMatch,
flow: flow,
amountRange: amountRange,
query: query,
monthOnly: monthOnly,
);
HomeFilterWidget copyWith({
String? id,
String? name,
bool? display,
int? sortOrder,
bool? halfWidth,
HomeWidgetType? type,
String? iconId,
HomeWidgetChartStyle? chartStyle,
HomeBudgetCapMode? budgetCapMode,
double? budgetFixedAmount,
int? budgetAverageMonths,
List<String>? labelIds,
LabelMatchMode? labelMatch,
TxFlowFilter? flow,
TxAmountRange? amountRange,
String? query,
bool? monthOnly,
bool? showAmountIn,
bool? showAmountOut,
bool? showCount,
int? updatedAt,
bool? deleted,
bool touchUpdatedAt = false,
}) {
return HomeFilterWidget(
id: id ?? this.id,
name: name ?? this.name,
display: display ?? this.display,
sortOrder: sortOrder ?? this.sortOrder,
halfWidth: halfWidth ?? this.halfWidth,
type: type ?? this.type,
iconId: iconId ?? this.iconId,
chartStyle: chartStyle ?? this.chartStyle,
budgetCapMode: budgetCapMode ?? this.budgetCapMode,
budgetFixedAmount: budgetFixedAmount ?? this.budgetFixedAmount,
budgetAverageMonths: budgetAverageMonths ?? this.budgetAverageMonths,
labelIds: labelIds ?? this.labelIds,
labelMatch: labelMatch ?? this.labelMatch,
flow: flow ?? this.flow,
amountRange: amountRange ?? this.amountRange,
query: query ?? this.query,
monthOnly: monthOnly ?? this.monthOnly,
showAmountIn: showAmountIn ?? this.showAmountIn,
showAmountOut: showAmountOut ?? this.showAmountOut,
showCount: showCount ?? this.showCount,
updatedAt: touchUpdatedAt
? DateTime.now().millisecondsSinceEpoch
: (updatedAt ?? this.updatedAt),
deleted: deleted ?? this.deleted,
);
}
static HomeFilterWidget fromFilter({
required String name,
required TransactionFilterSelection filter,
bool display = true,
int sortOrder = 0,
}) {
final showIn = filter.flow != TxFlowFilter.expense;
final showOut = filter.flow != TxFlowFilter.income;
return HomeFilterWidget(
id: 'hw_${DateTime.now().millisecondsSinceEpoch}',
name: name,
display: display,
sortOrder: sortOrder,
labelIds: filter.labelIds.toList(growable: false),
labelMatch: filter.labelMatch,
flow: filter.flow,
amountRange: filter.amountRange,
query: filter.query,
monthOnly: filter.monthOnly,
showAmountIn: showIn,
showAmountOut: showOut,
showCount: true,
updatedAt: DateTime.now().millisecondsSinceEpoch,
);
}
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'display': display,
'sortOrder': sortOrder,
'halfWidth': halfWidth,
'type': type.name,
'iconId': iconId,
'chartStyle': chartStyle.name,
'budgetCapMode': budgetCapMode.name,
'budgetFixedAmount': budgetFixedAmount,
'budgetAverageMonths': budgetAverageMonths,
'labelIds': labelIds,
'labelMatch': labelMatch.name,
'flow': flow.name,
'amountRange': {
if (amountRange.exact != null) 'exact': amountRange.exact,
if (amountRange.min != null) 'min': amountRange.min,
if (amountRange.max != null) 'max': amountRange.max,
},
'query': query,
'monthOnly': monthOnly,
'showAmountIn': showAmountIn,
'showAmountOut': showAmountOut,
'showCount': showCount,
'updatedAt': updatedAt,
'deleted': deleted,
};
factory HomeFilterWidget.fromJson(Map<String, dynamic> json) {
final rangeRaw = json['amountRange'];
final rangeMap = rangeRaw is Map
? Map<String, dynamic>.from(rangeRaw)
: const <String, dynamic>{};
double? asDouble(dynamic value) {
if (value is num) return value.toDouble();
return null;
}
int asInt(dynamic value, int fallback) {
if (value is int) return value;
if (value is num) return value.round();
return fallback;
}
return HomeFilterWidget(
id: json['id'] as String? ??
'hw_${DateTime.now().millisecondsSinceEpoch}',
name: (json['name'] as String?)?.trim().isNotEmpty == true
? (json['name'] as String).trim()
: 'Filter',
display: json['display'] as bool? ?? true,
sortOrder: asInt(json['sortOrder'], 0),
halfWidth: json['halfWidth'] as bool? ?? false,
type: HomeWidgetType.values.firstWhere(
(e) => e.name == json['type'],
orElse: () => HomeWidgetType.stats,
),
iconId: (json['iconId'] as String?)?.trim().isNotEmpty == true
? (json['iconId'] as String).trim()
: 'dashboard',
chartStyle: HomeWidgetChartStyle.values.firstWhere(
(e) => e.name == json['chartStyle'],
orElse: () => HomeWidgetChartStyle.bar,
),
budgetCapMode: HomeBudgetCapMode.values.firstWhere(
(e) => e.name == json['budgetCapMode'],
orElse: () => HomeBudgetCapMode.fixed,
),
budgetFixedAmount: asDouble(json['budgetFixedAmount']) ?? 0,
budgetAverageMonths: asInt(json['budgetAverageMonths'], 3).clamp(1, 36),
labelIds: [
for (final id in (json['labelIds'] as List? ?? const []))
if (id is String && id.isNotEmpty) id,
],
labelMatch: LabelMatchMode.values.firstWhere(
(e) => e.name == json['labelMatch'],
orElse: () => LabelMatchMode.and,
),
flow: TxFlowFilter.values.firstWhere(
(e) => e.name == json['flow'],
orElse: () => TxFlowFilter.all,
),
amountRange: TxAmountRange(
exact: asDouble(rangeMap['exact']),
min: asDouble(rangeMap['min']),
max: asDouble(rangeMap['max']),
),
query: json['query'] as String? ?? '',
monthOnly: json['monthOnly'] as bool? ?? false,
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 with last-write-wins on [HomeFilterWidget.updatedAt].
List<HomeFilterWidget> mergeHomeFilterWidgets(
List<HomeFilterWidget> local,
List<HomeFilterWidget> remote,
) {
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;
}
+157
View File
@@ -0,0 +1,157 @@
/// Named Overview chart filter snapshots (local favourites).
library;
import '../models/transaction_meta.dart';
import '../widgets/label_filter_dialog.dart';
/// Persisted Overview lens: period, metric, and Labels-chart options.
class OverviewFavourite {
const OverviewFavourite({
required this.id,
required this.name,
this.display = true,
this.metric = OverviewMetricMode.flow,
this.period = OverviewPeriodMode.monthly,
this.labelIds = const [],
this.flow = TxFlowFilter.expense,
this.barStyle = LabelChartBarStyle.parallel,
this.invertExpensePerspective = false,
this.updatedAt = 0,
this.deleted = false,
});
final String id;
final String name;
/// When true, this favourite appears on the Favourites overview view.
final bool display;
final OverviewMetricMode metric;
final OverviewPeriodMode period;
/// Empty = all labels (Labels metric only).
final List<String> labelIds;
final TxFlowFilter flow;
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,
bool? display,
OverviewMetricMode? metric,
OverviewPeriodMode? period,
List<String>? labelIds,
TxFlowFilter? flow,
LabelChartBarStyle? barStyle,
bool? invertExpensePerspective,
int? updatedAt,
bool? deleted,
bool touchUpdatedAt = false,
}) {
return OverviewFavourite(
id: id ?? this.id,
name: name ?? this.name,
display: display ?? this.display,
metric: metric ?? this.metric,
period: period ?? this.period,
labelIds: labelIds ?? this.labelIds,
flow: flow ?? this.flow,
barStyle: barStyle ?? this.barStyle,
invertExpensePerspective:
invertExpensePerspective ?? this.invertExpensePerspective,
updatedAt: touchUpdatedAt
? DateTime.now().millisecondsSinceEpoch
: (updatedAt ?? this.updatedAt),
deleted: deleted ?? this.deleted,
);
}
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'display': display,
'metric': metric.name,
'period': period.name,
'labelIds': labelIds,
'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
? (json['name'] as String).trim()
: 'Favourite',
display: json['display'] as bool? ?? true,
metric: OverviewMetricMode.values.firstWhere(
(e) => e.name == json['metric'],
orElse: () => OverviewMetricMode.flow,
),
period: OverviewPeriodMode.values.firstWhere(
(e) => e.name == json['period'],
orElse: () => OverviewPeriodMode.monthly,
),
labelIds: [
for (final id in (json['labelIds'] as List? ?? const []))
if (id is String && id.isNotEmpty) id,
],
flow: TxFlowFilter.values.firstWhere(
(e) => e.name == json['flow'],
orElse: () => TxFlowFilter.expense,
),
barStyle: LabelChartBarStyle.values.firstWhere(
(e) => e.name == json['barStyle'],
orElse: () => LabelChartBarStyle.parallel,
),
invertExpensePerspective:
json['invertExpensePerspective'] as bool? ?? false,
updatedAt: updatedAt,
deleted: json['deleted'] as bool? ?? false,
);
}
}
enum OverviewMetricMode { flow, labels }
enum OverviewPeriodMode { monthly, yearly }
/// Union favourites by id with last-write-wins on [OverviewFavourite.updatedAt].
List<OverviewFavourite> mergeOverviewFavourites(
List<OverviewFavourite> local,
List<OverviewFavourite> remote,
) {
final byId = <String, OverviewFavourite>{};
void put(OverviewFavourite fav) {
final existing = byId[fav.id];
if (existing == null || fav.updatedAt >= existing.updatedAt) {
byId[fav.id] = fav;
}
}
for (final fav in remote) {
put(fav);
}
for (final fav in local) {
put(fav);
}
return byId.values.toList(growable: false);
}
+9
View File
@@ -134,6 +134,15 @@ int labelVisibleDepth(
/// Filter-only id for txs with no labels (not an assignable category). /// 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();
+317 -9
View File
@@ -1,6 +1,8 @@
/// [ChangeNotifier] for bank link status, balance, and transactions. /// [ChangeNotifier] for bank link status, balance, and transactions.
library; library;
import 'dart:async';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import '../models/bank.dart'; import '../models/bank.dart';
@@ -30,16 +32,153 @@ 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),
];
_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(); _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;
/// Fired after a successful live balance + transactions fetch.
///
/// Used by [SyncController] to reconcile with PocketBase so a bank refresh
/// 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; ConnectStatus _status = ConnectStatus.disconnected;
BankBalance? _balance; BankBalance? _balance;
List<BankTransaction> _remoteTransactions = const []; List<BankTransaction> _remoteTransactions = const [];
List<BankTransaction> _importedTransactions = const []; List<BankTransaction> _importedTransactions = const [];
List<BankTransaction> _pendingRemoteDeletes = const [];
/// Tombstoned txs waiting to be removed from PocketBase (also persisted).
List<BankTransaction> get pendingRemoteDeletes =>
List<BankTransaction>.unmodifiable(_pendingRemoteDeletes);
bool get hasPendingRemoteDeletes => _pendingRemoteDeletes.isNotEmpty;
bool _isTombstoned(BankTransaction tx) {
for (final tomb in _pendingRemoteDeletes) {
if (tx.matchesForDelete(tomb)) return true;
}
return false;
}
void requeueRemoteDeletes(Iterable<BankTransaction> txs) {
for (final tx in txs) {
_queueRemoteDelete(tx, notify: false);
}
unawaited(_persistPendingDeletes());
}
void _queueRemoteDelete(BankTransaction tx, {bool notify = true}) {
if (tx.id.isEmpty) return;
if (_isTombstoned(tx)) return;
_pendingRemoteDeletes = [
..._pendingRemoteDeletes,
tx.copyWith(isManual: true),
];
unawaited(_persistPendingDeletes());
if (notify) onPendingRemoteDeletesChanged?.call();
}
/// Merge delete tombstones from another device and strip matching local rows.
Future<void> applyRemoteDeletes(
List<BankTransaction> remote, {
bool notify = true,
}) async {
var tombsChanged = false;
for (final tomb in remote) {
if (_isTombstoned(tomb)) continue;
_pendingRemoteDeletes = [
..._pendingRemoteDeletes,
tomb.copyWith(isManual: true),
];
tombsChanged = true;
}
if (_pendingRemoteDeletes.isEmpty) return;
final beforeRemote = _remoteTransactions.length;
final beforeImported = _importedTransactions.length;
_remoteTransactions = [
for (final tx in _remoteTransactions)
if (!_isTombstoned(tx)) tx,
];
_importedTransactions = [
for (final tx in _importedTransactions)
if (!_isTombstoned(tx)) tx,
];
final stripped = beforeRemote != _remoteTransactions.length ||
beforeImported != _importedTransactions.length;
if (tombsChanged || stripped) {
_invalidateMerged();
if (tombsChanged) await _persistPendingDeletes();
if (stripped) {
await _persistCache();
await _persistImported();
}
if (notify) notifyListeners();
}
}
Future<void> _persistPendingDeletes() async {
final storage = _storage;
if (storage == null) return;
await storage.savePendingTxDeletes(_pendingRemoteDeletes);
}
/// Keep [isManual] when a synced/API row replaces a matching imported test tx.
void _reapplyManualFlags(Set<String> manualIds) {
if (manualIds.isEmpty) return;
BankTransaction stamp(BankTransaction tx) =>
manualIds.contains(tx.id) && !tx.isManual
? tx.copyWith(isManual: true)
: tx;
_remoteTransactions = [for (final tx in _remoteTransactions) stamp(tx)];
_importedTransactions = [
for (final tx in _importedTransactions) stamp(tx),
];
}
Set<String> _collectManualIds([
Iterable<BankTransaction> extra = const [],
]) =>
{
for (final tx in [
..._remoteTransactions,
..._importedTransactions,
...extra,
])
if (tx.isManual) tx.id,
};
List<BankTransaction>? _mergedTransactions; List<BankTransaction>? _mergedTransactions;
bool _isLoading = false; bool _isLoading = false;
@@ -155,6 +294,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);
}
_importedTransactions = mergeTransactions(_importedTransactions, [updated]);
_invalidateMerged();
await _persistImported();
await _persistCache();
notifyListeners();
return updated;
}
/// Remove an admin test transaction from local caches.
Future<void> deleteManualTransaction(BankTransaction tx) async {
if (!tx.isManual) {
throw StateError('Only admin test transactions can be deleted');
}
_importedTransactions = [
for (final row in _importedTransactions)
if (!row.matchesForDelete(tx)) row,
];
_remoteTransactions = [
for (final row in _remoteTransactions)
if (!row.matchesForDelete(tx)) row,
];
_queueRemoteDelete(tx);
_invalidateMerged();
await _persistImported();
await _persistCache();
notifyListeners();
}
/// Union cloud txs into the local bank cache without dropping either side. /// 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.
@@ -162,13 +412,37 @@ class BankController extends ChangeNotifier {
List<BankTransaction> fromCloud, { List<BankTransaction> fromCloud, {
bool notify = true, bool notify = true,
}) async { }) async {
if (fromCloud.isEmpty) return; if (fromCloud.isEmpty && _pendingRemoteDeletes.isEmpty) return;
_remoteTransactions = mergeTransactions(_remoteTransactions, fromCloud); // Never resurrect rows the user already deleted locally.
final incoming = [
for (final tx in fromCloud)
if (!_isTombstoned(tx)) _upgradeLegacyManual(tx),
];
if (incoming.isEmpty && _pendingRemoteDeletes.isEmpty) return;
final manuals = _collectManualIds(incoming);
if (incoming.isNotEmpty) {
_remoteTransactions = mergeTransactions(_remoteTransactions, incoming);
}
// Strip any local copies that match a pending delete (defensive).
if (_pendingRemoteDeletes.isNotEmpty) {
_remoteTransactions = [
for (final tx in _remoteTransactions)
if (!_isTombstoned(tx)) tx,
];
}
_importedTransactions = filterNewTransactions( _importedTransactions = filterNewTransactions(
_remoteTransactions, _remoteTransactions,
_importedTransactions, _importedTransactions,
); );
if (_pendingRemoteDeletes.isNotEmpty) {
_importedTransactions = [
for (final tx in _importedTransactions)
if (!_isTombstoned(tx)) tx,
];
}
_reapplyManualFlags(manuals);
_invalidateMerged(); _invalidateMerged();
if (!_status.linked && _remoteTransactions.isNotEmpty) { if (!_status.linked && _remoteTransactions.isNotEmpty) {
@@ -193,6 +467,7 @@ class BankController extends ChangeNotifier {
_error = null; _error = null;
notifyListeners(); notifyListeners();
var loadedLive = false;
try { try {
try { try {
_status = await _api.fetchStatus(); _status = await _api.fetchStatus();
@@ -209,7 +484,7 @@ class BankController extends ChangeNotifier {
// have a local snapshot. Never wipe local txs because status said // have a local snapshot. Never wipe local txs because status said
// "unlinked" — only a 409 from balance/transactions clears them. // "unlinked" — only a 409 from balance/transactions clears them.
if (_status.linked || hasData) { if (_status.linked || hasData) {
await _loadLinkedData(); loadedLive = await _loadLinkedData();
await _persistCache(); await _persistCache();
} }
} on IngtrakApiException catch (error, stackTrace) { } on IngtrakApiException catch (error, stackTrace) {
@@ -230,16 +505,25 @@ class BankController extends ChangeNotifier {
_isLoading = false; _isLoading = false;
notifyListeners(); notifyListeners();
} }
if (loadedLive) {
onAfterSuccessfulLoad?.call();
}
} }
Future<void> _loadLinkedData() async { /// Returns true when balance + transactions were fetched successfully.
Future<bool> _loadLinkedData() async {
try { try {
final results = await Future.wait([ final results = await Future.wait([
_api.fetchBalance(), _api.fetchBalance(),
_api.fetchTransactions(), _api.fetchTransactions(),
]); ]);
_balance = results[0] as BankBalance; _balance = results[0] as BankBalance;
_remoteTransactions = 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
// cloud/CSV history that the API window does not include.
final manuals = _collectManualIds();
_remoteTransactions = mergeTransactions(apiTxs, _remoteTransactions);
if (!_status.linked) { if (!_status.linked) {
_status = ConnectStatus( _status = ConnectStatus(
status: 'linked', status: 'linked',
@@ -254,9 +538,21 @@ class BankController extends ChangeNotifier {
_remoteTransactions, _remoteTransactions,
_importedTransactions, _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(); _invalidateMerged();
await _persistImported(); await _persistImported();
_error = null; _error = null;
return true;
} on IngtrakApiException catch (error) { } on IngtrakApiException catch (error) {
if (error.isNotLinked) { if (error.isNotLinked) {
// Confirmed unlinked by data endpoints — clear remote only. // Confirmed unlinked by data endpoints — clear remote only.
@@ -272,6 +568,7 @@ class BankController extends ChangeNotifier {
// Keep previous balance/txs if refresh of data fails. // Keep previous balance/txs if refresh of data fails.
_error = 'Using saved data · ${error.message}'; _error = 'Using saved data · ${error.message}';
} }
return false;
} }
} }
@@ -349,11 +646,19 @@ class BankController extends ChangeNotifier {
state: state ?? _pendingState, state: state ?? _pendingState,
); );
_pendingState = null; _pendingState = null;
var loadedLive = false;
if (_status.linked) { if (_status.linked) {
await _loadLinkedData(); loadedLive = await _loadLinkedData();
await _persistCache(); await _persistCache();
} }
return _status.linked; final linked = _status.linked;
// Notify before cloud reconcile so UI can leave the connecting state.
_isLoading = false;
notifyListeners();
if (loadedLive) {
onAfterSuccessfulLoad?.call();
}
return linked;
} on IngtrakApiException catch (error, stackTrace) { } on IngtrakApiException catch (error, stackTrace) {
_error = error.message; _error = error.message;
debugPrint('BankController.completeWithCode failed: $error\n$stackTrace'); debugPrint('BankController.completeWithCode failed: $error\n$stackTrace');
@@ -363,13 +668,16 @@ class BankController extends ChangeNotifier {
debugPrint('BankController.completeWithCode failed: $error\n$stackTrace'); debugPrint('BankController.completeWithCode failed: $error\n$stackTrace');
return false; return false;
} finally { } finally {
_isLoading = false; if (_isLoading) {
notifyListeners(); _isLoading = false;
notifyListeners();
}
} }
} }
@override @override
void dispose() { void dispose() {
onAfterSuccessfulLoad = null;
_api.close(); _api.close();
super.dispose(); super.dispose();
} }
+258 -2
View File
@@ -1,26 +1,282 @@
/// App preferences beyond theme (Look ahead horizon, etc.). /// App preferences beyond theme (Look ahead, Overview favourites, Home widgets).
library; library;
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import '../models/app_cloud_prefs.dart';
import '../models/home_built_in_sections.dart';
import '../models/home_filter_widget.dart';
import '../models/overview_favourite.dart';
import '../services/storage_service.dart'; import '../services/storage_service.dart';
class PreferencesController extends ChangeNotifier { class PreferencesController extends ChangeNotifier {
PreferencesController(this._storage) { PreferencesController(this._storage) {
_lookAheadMaxYears = _storage.lookAheadMaxYears; _lookAheadMaxYears = _storage.lookAheadMaxYears;
_overviewFavourites = _storage.loadOverviewFavourites();
_homeFilterWidgets = _storage.loadHomeFilterWidgets();
_homeBuiltInSections = _storage.loadHomeBuiltInSections();
} }
final StorageService _storage; final StorageService _storage;
late int _lookAheadMaxYears; late int _lookAheadMaxYears;
late List<OverviewFavourite> _overviewFavourites;
late List<HomeFilterWidget> _homeFilterWidgets;
late HomeBuiltInSections _homeBuiltInSections;
/// Fired after favourites are persisted (for cloud push debounce).
VoidCallback? onFavouritesPersisted;
/// Fired after Home widgets are persisted (for cloud push debounce).
VoidCallback? onHomeWidgetsPersisted;
/// Fired after Home sections / Look ahead are persisted.
VoidCallback? onAppPrefsPersisted;
/// Years ahead Look ahead can navigate (1–30, default 5). /// Years ahead Look ahead can navigate (1–30, default 5).
int get lookAheadMaxYears => _lookAheadMaxYears; int get lookAheadMaxYears => _lookAheadMaxYears;
Future<void> setLookAheadMaxYears(int years) async { /// Snapshot used for PocketBase `app_prefs` sync.
AppCloudPrefs get cloudPrefs => AppCloudPrefs(
homeBuiltInSections: _homeBuiltInSections,
lookAheadMaxYears: _lookAheadMaxYears,
);
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.deleted && fav.display) fav,
];
bool get hasDisplayedOverviewFavourites =>
_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.deleted && w.display) w,
];
bool get hasDisplayedHomeFilterWidgets =>
_homeFilterWidgets.any((w) => !w.deleted && w.display);
HomeBuiltInSections get homeBuiltInSections => _homeBuiltInSections;
Future<void> setHomeBuiltInSections(
HomeBuiltInSections sections, {
bool schedulePush = true,
}) async {
if (sections.showTransactions == _homeBuiltInSections.showTransactions &&
sections.showCategorized == _homeBuiltInSections.showCategorized &&
sections.showRecent == _homeBuiltInSections.showRecent) {
return;
}
_homeBuiltInSections = sections;
notifyListeners();
await _storage.saveHomeBuiltInSections(sections);
if (schedulePush) onAppPrefsPersisted?.call();
}
Future<void> setHomeShowTransactions(bool value) => setHomeBuiltInSections(
_homeBuiltInSections.copyWith(showTransactions: value),
);
Future<void> setHomeShowCategorized(bool value) => setHomeBuiltInSections(
_homeBuiltInSections.copyWith(showCategorized: value),
);
Future<void> setHomeShowRecent(bool value) => setHomeBuiltInSections(
_homeBuiltInSections.copyWith(showRecent: value),
);
Future<void> setLookAheadMaxYears(
int years, {
bool schedulePush = true,
}) async {
final next = years.clamp(1, 30); final next = years.clamp(1, 30);
if (next == _lookAheadMaxYears) return; if (next == _lookAheadMaxYears) return;
_lookAheadMaxYears = next; _lookAheadMaxYears = next;
notifyListeners(); notifyListeners();
await _storage.setLookAheadMaxYears(next); await _storage.setLookAheadMaxYears(next);
if (schedulePush) onAppPrefsPersisted?.call();
}
Future<void> replaceCloudPrefs(
AppCloudPrefs prefs, {
bool notify = true,
bool schedulePush = false,
}) async {
_homeBuiltInSections = prefs.homeBuiltInSections;
_lookAheadMaxYears = prefs.lookAheadMaxYears.clamp(1, 30);
if (notify) notifyListeners();
await _storage.saveHomeBuiltInSections(_homeBuiltInSections);
await _storage.setLookAheadMaxYears(_lookAheadMaxYears);
if (schedulePush) onAppPrefsPersisted?.call();
}
Future<void> addOverviewFavourite(OverviewFavourite favourite) async {
final stamped = favourite.updatedAt == 0
? favourite.copyWith(touchUpdatedAt: true)
: favourite;
_overviewFavourites = [..._overviewFavourites, stamped];
notifyListeners();
await _persistFavourites();
}
Future<void> updateOverviewFavourite(OverviewFavourite favourite) async {
final index = _overviewFavourites.indexWhere((f) => f.id == favourite.id);
if (index < 0) return;
final next = [..._overviewFavourites];
next[index] = favourite.copyWith(touchUpdatedAt: true);
_overviewFavourites = next;
notifyListeners();
await _persistFavourites();
}
Future<void> removeOverviewFavourite(String id) async {
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();
}
Future<void> setOverviewFavouriteDisplay(String id, bool display) async {
final index = _overviewFavourites.indexWhere((f) => f.id == id);
if (index < 0) return;
final current = _overviewFavourites[index];
if (current.deleted || current.display == display) return;
await updateOverviewFavourite(current.copyWith(display: display));
}
Future<void> replaceOverviewFavourites(
List<OverviewFavourite> favourites, {
bool notify = true,
bool schedulePush = false,
}) async {
_overviewFavourites = List.of(favourites);
if (notify) notifyListeners();
await _storage.saveOverviewFavourites(_overviewFavourites);
if (schedulePush) onFavouritesPersisted?.call();
}
Future<void> addHomeFilterWidget(HomeFilterWidget widget) async {
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;
final stamped = (widget.updatedAt == 0
? widget.copyWith(touchUpdatedAt: true)
: widget)
.copyWith(
sortOrder: widget.sortOrder == 0 ? order : widget.sortOrder,
);
_homeFilterWidgets = [..._homeFilterWidgets, stamped];
notifyListeners();
await _persistHomeWidgets();
}
Future<void> updateHomeFilterWidget(HomeFilterWidget widget) async {
final index = _homeFilterWidgets.indexWhere((w) => w.id == widget.id);
if (index < 0) return;
final next = [..._homeFilterWidgets];
next[index] = widget.copyWith(touchUpdatedAt: true);
next.sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
_homeFilterWidgets = next;
notifyListeners();
await _persistHomeWidgets();
}
Future<void> removeHomeFilterWidget(String id) async {
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();
}
Future<void> setHomeFilterWidgetDisplay(String id, bool display) async {
final index = _homeFilterWidgets.indexWhere((w) => w.id == id);
if (index < 0) return;
final current = _homeFilterWidgets[index];
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 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();
}
Future<void> replaceHomeFilterWidgets(
List<HomeFilterWidget> widgets, {
bool notify = true,
bool schedulePush = false,
}) async {
final next = List.of(widgets)
..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
_homeFilterWidgets = next;
if (notify) notifyListeners();
await _storage.saveHomeFilterWidgets(_homeFilterWidgets);
if (schedulePush) onHomeWidgetsPersisted?.call();
}
Future<void> _persistFavourites() async {
await _storage.saveOverviewFavourites(_overviewFavourites);
onFavouritesPersisted?.call();
}
Future<void> _persistHomeWidgets() async {
await _storage.saveHomeFilterWidgets(_homeFilterWidgets);
onHomeWidgetsPersisted?.call();
} }
} }
+369 -18
View File
@@ -5,9 +5,14 @@ import 'dart:async';
import 'package:flutter/foundation.dart'; 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'; import '../services/pb_sync_service.dart';
import 'auth_provider.dart'; import 'auth_provider.dart';
import 'bank_provider.dart'; import 'bank_provider.dart';
import 'preferences_provider.dart';
import 'tx_meta_provider.dart'; import 'tx_meta_provider.dart';
/// User-visible sync toast state (watched by [SyncFeedbackListener]). /// User-visible sync toast state (watched by [SyncFeedbackListener]).
@@ -30,12 +35,19 @@ class SyncController extends ChangeNotifier {
required AuthController auth, required AuthController auth,
required TxMetaController meta, required TxMetaController meta,
required BankController bank, required BankController bank,
required PreferencesController prefs,
}) : _auth = auth, }) : _auth = auth,
_meta = meta, _meta = meta,
_bank = bank { _bank = bank,
_prefs = prefs {
_wasLoggedIn = auth.isLoggedIn; _wasLoggedIn = auth.isLoggedIn;
_meta.onPersisted = _schedulePush; _meta.onPersisted = _scheduleMetaPush;
_prefs.onFavouritesPersisted = _scheduleFavouritesPush;
_prefs.onHomeWidgetsPersisted = _scheduleHomeWidgetsPush;
_prefs.onAppPrefsPersisted = _scheduleAppPrefsPush;
_auth.addListener(_onAuthChanged); _auth.addListener(_onAuthChanged);
_bank.onAfterSuccessfulLoad = _onBankDataLoaded;
_bank.onPendingRemoteDeletesChanged = _scheduleBankTxPush;
if (_auth.isLoggedIn) { if (_auth.isLoggedIn) {
unawaited(syncNow()); unawaited(syncNow());
} }
@@ -44,11 +56,17 @@ class SyncController extends ChangeNotifier {
final AuthController _auth; final AuthController _auth;
final TxMetaController _meta; final TxMetaController _meta;
final BankController _bank; final BankController _bank;
final PreferencesController _prefs;
bool _wasLoggedIn = false; bool _wasLoggedIn = false;
bool _syncing = false; bool _syncing = false;
bool _pushQueued = false; bool _pushQueued = false;
bool _queuedFullSync = false; bool _queuedFullSync = false;
bool _pushMetaPending = false;
bool _pushFavouritesPending = false;
bool _pushHomeWidgetsPending = false;
bool _pushAppPrefsPending = false;
bool _pushBankPending = false;
Timer? _pushDebounce; Timer? _pushDebounce;
Timer? _progressHold; Timer? _progressHold;
Timer? _uiNotifyThrottle; Timer? _uiNotifyThrottle;
@@ -178,6 +196,12 @@ class SyncController extends ChangeNotifier {
_progressHold?.cancel(); _progressHold?.cancel();
_uiNotifyThrottle?.cancel(); _uiNotifyThrottle?.cancel();
_uiNotifyQueued = false; _uiNotifyQueued = false;
_pushQueued = false;
_pushMetaPending = false;
_pushFavouritesPending = false;
_pushHomeWidgetsPending = false;
_pushAppPrefsPending = false;
_pushBankPending = false;
_lastError = null; _lastError = null;
_statusDetail = ''; _statusDetail = '';
_showProgressRing = false; _showProgressRing = false;
@@ -188,8 +212,110 @@ class SyncController extends ChangeNotifier {
} }
} }
void _schedulePush() { /// Bank pull-to-refresh / reconnect finished — reconcile with PocketBase.
///
/// Runs a full sync when idle so (1) new API txs are pushed and
/// (2) any cloud-only history the bank window lacks is pulled back.
///
/// If a sync is already in flight (common at cold start: constructor sync
/// overlaps bank refresh), do **not** queue another full sync — that was
/// causing a back-to-back double pull of 4k+ txs.
void _onBankDataLoaded() {
if (!_auth.isLoggedIn) return; if (!_auth.isLoggedIn) return;
if (_syncing) {
debugPrint(
'SyncController: bank load finished during sync — skip queued full sync',
);
return;
}
unawaited(syncNow());
}
/// If the server has more bank txs than this device, sync now.
Future<void> syncIfBehindServer() async {
if (!_auth.isLoggedIn || _syncing) return;
try {
final remoteCount =
await PbSyncService(_auth.client).countTransactions();
if (remoteCount > _bank.transactions.length) {
debugPrint(
'SyncController: behind server '
'(local=${_bank.transactions.length} remote=$remoteCount) — syncing',
);
await syncNow();
}
} catch (error, stackTrace) {
debugPrint('SyncController.syncIfBehindServer failed: $error\n$stackTrace');
}
}
void _scheduleMetaPush() {
_pushMetaPending = true;
_armPushDebounce();
}
void _scheduleFavouritesPush() {
_pushFavouritesPending = true;
_armPushDebounce();
}
void _scheduleHomeWidgetsPush() {
_pushHomeWidgetsPending = true;
_armPushDebounce();
}
void _scheduleAppPrefsPush() {
_pushAppPrefsPending = true;
_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) {
_pushQueued = true;
return;
}
_pushDebounce?.cancel(); _pushDebounce?.cancel();
_pushDebounce = Timer(const Duration(seconds: 2), () { _pushDebounce = Timer(const Duration(seconds: 2), () {
unawaited(_pushOnly()); unawaited(_pushOnly());
@@ -216,6 +342,9 @@ class SyncController extends ChangeNotifier {
try { try {
final service = PbSyncService(_auth.client); 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( final remoteMeta = await service.pull(
onProgress: (p) { onProgress: (p) {
_setProgress(p * 0.35); _setProgress(p * 0.35);
@@ -232,22 +361,109 @@ class SyncController extends ChangeNotifier {
_setProgress(0.5); _setProgress(0.5);
_setStatus('Merging…'); _setStatus('Merging…');
final mergedMeta = mergeTxMetaStores(_meta.exportStore(), remoteMeta); final mergedMeta = mergeTxMetaStores(_meta.exportStore(), remoteMeta);
List<OverviewFavourite> remoteFavourites = const [];
try {
remoteFavourites = await service.pullOverviewFavourites(
onStatus: _setStatus,
);
} catch (error) {
debugPrint(
'SyncController: overview_favourites pull skipped ($error)',
);
}
final mergedFavourites = mergeOverviewFavourites(
_prefs.overviewFavouritesForSync,
remoteFavourites,
);
List<HomeFilterWidget> remoteHomeWidgets = const [];
try {
remoteHomeWidgets = await service.pullHomeFilterWidgets(
onStatus: _setStatus,
);
} catch (error) {
debugPrint(
'SyncController: home_filter_widgets pull skipped ($error)',
);
}
final mergedHomeWidgets = mergeHomeFilterWidgets(
_prefs.homeFilterWidgetsForSync,
remoteHomeWidgets,
);
AppCloudPrefs? remoteAppPrefs;
try {
remoteAppPrefs = await service.pullAppPrefs(onStatus: _setStatus);
} catch (error) {
debugPrint('SyncController: app_prefs pull skipped ($error)');
}
// Prefer local when this device has pending prefs edits; otherwise
// take remote so a new install picks up cloud Home section toggles.
final preferLocalAppPrefs = _pushAppPrefsPending;
final mergedAppPrefs = mergeAppCloudPrefs(
local: _prefs.cloudPrefs,
remote: remoteAppPrefs,
preferLocal: preferLocalAppPrefs,
);
// Apply without notifying — one rebuild after both stores are ready. // Apply without notifying — one rebuild after both stores are ready.
await _meta.replaceStore(mergedMeta, notify: false); await _meta.replaceStore(mergedMeta, notify: false);
await _bank.applySyncedTransactions(remoteTxs, notify: false); await _bank.applySyncedTransactions(remoteTxs, notify: false);
await _prefs.replaceOverviewFavourites(
mergedFavourites,
notify: false,
);
await _prefs.replaceHomeFilterWidgets(
mergedHomeWidgets,
notify: false,
);
await _prefs.replaceCloudPrefs(mergedAppPrefs, notify: false);
_meta.notifyListeners(); _meta.notifyListeners();
_bank.notifyListeners(); _bank.notifyListeners();
_prefs.notifyListeners();
_setProgress(0.55); _setProgress(0.55);
_setStatus('Pushing…'); _setStatus('Pushing…');
final metaSummary = await service.push( final metaSummary = await service.push(
mergedMeta, mergedMeta,
progressStart: 0.55, progressStart: 0.55,
progressEnd: 0.82, progressEnd: 0.75,
onProgress: _setProgress, onProgress: _setProgress,
onStatus: _setStatus, onStatus: _setStatus,
); );
try {
await service.pushOverviewFavourites(
mergedFavourites,
onStatus: _setStatus,
);
} catch (error) {
debugPrint(
'SyncController: overview_favourites push skipped ($error)',
);
}
try {
await service.pushHomeFilterWidgets(
mergedHomeWidgets,
onStatus: _setStatus,
);
} catch (error) {
debugPrint(
'SyncController: home_filter_widgets push skipped ($error)',
);
}
try {
await service.pushAppPrefs(
mergedAppPrefs,
onStatus: _setStatus,
);
_pushAppPrefsPending = false;
} catch (error) {
debugPrint('SyncController: app_prefs push skipped ($error)');
}
// Retry deletes in case any were queued during the pull/merge window.
await _flushPendingTxDeletes(service);
await _pushTxDeletes(service);
_pushBankPending = false;
final tombs = List<BankTransaction>.of(_bank.pendingRemoteDeletes);
final bankSummary = await service.pushTransactions( final bankSummary = await service.pushTransactions(
_bank.transactions, _bank.transactions,
deleteTombs: tombs,
progressStart: 0.82, progressStart: 0.82,
progressEnd: 1.0, progressEnd: 1.0,
onProgress: _setProgress, onProgress: _setProgress,
@@ -277,32 +493,162 @@ class SyncController extends ChangeNotifier {
} }
} }
/// Annotation-only push after local meta edits (avoids re-uploading 4k+ txs). /// Pushes only the stores that changed locally (debounced).
///
/// Annotation edits push tx_meta; favourite / Home-widget edits do not
/// re-upload the full annotation store or bank transactions.
Future<void> _pushOnly() async { Future<void> _pushOnly() async {
if (!_auth.isLoggedIn || _syncing) { if (!_auth.isLoggedIn) return;
if (_syncing) _pushQueued = true; if (_syncing) {
_pushQueued = true;
return;
}
final pushMeta = _pushMetaPending;
final pushFavourites = _pushFavouritesPending;
final pushHomeWidgets = _pushHomeWidgetsPending;
final pushAppPrefs = _pushAppPrefsPending;
final pushBank = _pushBankPending || _bank.pendingRemoteDeletes.isNotEmpty;
_pushMetaPending = false;
_pushFavouritesPending = false;
_pushHomeWidgetsPending = false;
_pushAppPrefsPending = false;
_pushBankPending = false;
if (!pushMeta &&
!pushFavourites &&
!pushHomeWidgets &&
!pushAppPrefs &&
!pushBank) {
return; return;
} }
_progressHold?.cancel(); _progressHold?.cancel();
_syncing = true; _syncing = true;
_progressSuccess = false; _progressSuccess = false;
_statusDetail = 'Pushing…';
final label = switch ((
pushMeta,
pushFavourites,
pushHomeWidgets,
pushAppPrefs,
pushBank,
)) {
(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…';
_setProgress(0.05); _setProgress(0.05);
_announce('Syncing…', isProgress: true); _announce('Saving $label…', isProgress: true);
try { try {
final service = PbSyncService(_auth.client); final service = PbSyncService(_auth.client);
final summary = await service.push( final parts = <String>[];
_meta.exportStore(), var done = 0;
progressStart: 0.05, final total = (pushMeta ? 1 : 0) +
progressEnd: 1.0, (pushFavourites ? 1 : 0) +
onProgress: _setProgress, (pushHomeWidgets ? 1 : 0) +
onStatus: _setStatus, (pushAppPrefs ? 1 : 0) +
); (pushBank ? 1 : 0);
void bump() {
done++;
_setProgress(done / total);
}
if (pushMeta) {
_setStatus('Pushing annotations…');
final summary = await service.push(
_meta.exportStore(),
progressStart: done / total,
progressEnd: (done + 1) / total,
onProgress: _setProgress,
onStatus: _setStatus,
);
parts.add(summary);
bump();
}
if (pushFavourites) {
_setStatus('Pushing favourites…');
try {
await service.pushOverviewFavourites(
_prefs.overviewFavouritesForSync,
onStatus: _setStatus,
);
parts.add('Favourites updated');
} catch (error) {
debugPrint(
'SyncController: overview_favourites push skipped ($error)',
);
_pushFavouritesPending = true;
}
bump();
}
if (pushHomeWidgets) {
_setStatus('Pushing home widgets…');
try {
await service.pushHomeFilterWidgets(
_prefs.homeFilterWidgetsForSync,
onStatus: _setStatus,
);
parts.add('Home widgets updated');
} catch (error) {
debugPrint(
'SyncController: home_filter_widgets push skipped ($error)',
);
_pushHomeWidgetsPending = true;
}
bump();
}
if (pushAppPrefs) {
_setStatus('Pushing app prefs…');
try {
await service.pushAppPrefs(
_prefs.cloudPrefs,
onStatus: _setStatus,
);
parts.add('App prefs updated');
} catch (error) {
debugPrint('SyncController: app_prefs push skipped ($error)');
// Re-queue so a missing collection doesn't drop the edit forever
// until the next manual full sync after migrate.
_pushAppPrefsPending = true;
}
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(); _lastSyncedAt = DateTime.now();
_lastError = null; _lastError = null;
_lastSyncSummary = summary; _lastSyncSummary = parts.isEmpty ? label : parts.join('\n');
_announce('Sync complete'); _announce('Saved $label');
_syncing = false; _syncing = false;
_finishProgress(success: true); _finishProgress(success: true);
} catch (error, stackTrace) { } catch (error, stackTrace) {
@@ -329,7 +675,12 @@ class SyncController extends ChangeNotifier {
_progressHold?.cancel(); _progressHold?.cancel();
_uiNotifyThrottle?.cancel(); _uiNotifyThrottle?.cancel();
_auth.removeListener(_onAuthChanged); _auth.removeListener(_onAuthChanged);
_bank.onAfterSuccessfulLoad = null;
_bank.onPendingRemoteDeletesChanged = null;
_meta.onPersisted = null; _meta.onPersisted = null;
_prefs.onFavouritesPersisted = null;
_prefs.onHomeWidgetsPersisted = null;
_prefs.onAppPrefsPersisted = null;
super.dispose(); super.dispose();
} }
} }
+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(
+446 -155
View File
@@ -4,13 +4,17 @@ library;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../models/home_filter_widget.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';
import '../utils/helpers.dart'; import '../utils/helpers.dart';
import '../utils/navigation.dart'; import '../utils/navigation.dart';
import '../widgets/empty_state.dart'; import '../widgets/empty_state.dart';
import '../widgets/home_filter_widget_card.dart';
import '../widgets/home_widgets_sheet.dart';
import '../widgets/loading_view.dart'; import '../widgets/loading_view.dart';
import '../widgets/responsive_body.dart'; import '../widgets/responsive_body.dart';
import '../widgets/shell_tab_scope.dart'; import '../widgets/shell_tab_scope.dart';
@@ -18,16 +22,23 @@ import '../widgets/skip_build_when_covered.dart';
import 'transaction_detail_screen.dart'; import 'transaction_detail_screen.dart';
import 'transactions_screen.dart'; import 'transactions_screen.dart';
class HomeScreen extends StatelessWidget { class HomeScreen extends StatefulWidget {
const HomeScreen({super.key}); const HomeScreen({super.key});
static const tabIndex = 0; static const tabIndex = 0;
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var _editingWidgets = false;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Inactive IndexedStack tabs must not watch providers — otherwise every // Inactive IndexedStack tabs must not watch providers — otherwise every
// annotation save rebuilds Home while the user is on another tab. // annotation save rebuilds Home while the user is on another tab.
if (ShellTabScope.of(context) != tabIndex) { if (ShellTabScope.of(context) != HomeScreen.tabIndex) {
return const SizedBox.expand(); return const SizedBox.expand();
} }
@@ -35,17 +46,31 @@ class HomeScreen extends StatelessWidget {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Home'), title: Text(_editingWidgets ? 'Edit Home' : 'Home'),
actions: bankAppBarActions( actions: [
context: context, if (bank.isLinked || bank.hasData)
onRefresh: bank.refresh, IconButton(
refreshing: bank.isLoading, tooltip: _editingWidgets ? 'Done' : 'Edit Home layout',
), onPressed: () =>
setState(() => _editingWidgets = !_editingWidgets),
icon: Icon(
_editingWidgets ? Icons.check : Icons.dashboard_customize_outlined,
),
),
...bankAppBarActions(
context: context,
onRefresh: bank.refresh,
refreshing: bank.isLoading,
),
],
), ),
body: RefreshIndicator( body: RefreshIndicator(
onRefresh: bank.refresh, onRefresh: bank.refresh,
child: ResponsiveBody( child: ResponsiveBody(
child: _HomeBody(bank: bank), child: _HomeBody(
bank: bank,
editingWidgets: _editingWidgets,
),
), ),
), ),
); );
@@ -53,9 +78,13 @@ class HomeScreen extends StatelessWidget {
} }
class _HomeBody extends StatelessWidget { class _HomeBody extends StatelessWidget {
const _HomeBody({required this.bank}); const _HomeBody({
required this.bank,
required this.editingWidgets,
});
final BankController bank; final BankController bank;
final bool editingWidgets;
void _openTransactions(BuildContext context) { void _openTransactions(BuildContext context) {
Navigator.of(context).push( Navigator.of(context).push(
@@ -68,6 +97,7 @@ class _HomeBody extends StatelessWidget {
// Stay subscribed, but skip heavy scans while covered by another route // Stay subscribed, but skip heavy scans while covered by another route
// (e.g. transaction detail applying labels to many similar txs). // (e.g. transaction detail applying labels to many similar txs).
context.watch<TxMetaController>(); context.watch<TxMetaController>();
final prefs = context.watch<PreferencesController>();
if (bank.isLoading && bank.balance == null && !bank.hasData) { if (bank.isLoading && bank.balance == null && !bank.hasData) {
return const LoadingView(message: 'Checking bank link…'); return const LoadingView(message: 'Checking bank link…');
@@ -106,163 +136,306 @@ class _HomeBody extends StatelessWidget {
return SkipBuildWhenCovered( return SkipBuildWhenCovered(
builder: (context) { builder: (context) {
final balance = bank.balance; final balance = bank.balance;
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
final meta = context.watch<TxMetaController>(); final meta = context.watch<TxMetaController>();
final recent = bank.transactions.take(5).toList(growable: false); final recent = bank.transactions.take(5).toList(growable: false);
final categorized = final categorized =
meta.labeledTransactionCount(bank.transactions); meta.labeledTransactionCount(bank.transactions);
final widgets = editingWidgets
? prefs.homeFilterWidgets
: prefs.displayedHomeFilterWidgets;
return ListView( return ListView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.only(top: 8, bottom: 32), padding: const EdgeInsets.only(top: 8, bottom: 32),
children: [ children: [
Material( Material(
color: Colors.transparent, color: Colors.transparent,
child: InkWell( child: InkWell(
borderRadius: BorderRadius.circular(20),
onTap: () => _openTransactions(context),
child: Ink(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20),
gradient: LinearGradient( onTap: () => _openTransactions(context),
colors: [colors.primary, colors.tertiary], child: Ink(
), width: double.infinity,
boxShadow: [ padding: const EdgeInsets.all(24),
BoxShadow( decoration: BoxDecoration(
color: colors.primary.withValues(alpha: 0.28), borderRadius: BorderRadius.circular(20),
blurRadius: 20, gradient: LinearGradient(
offset: const Offset(0, 10), colors: [colors.primary, colors.tertiary],
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Current balance',
style: theme.textTheme.labelMedium?.copyWith(
color: colors.onPrimary.withValues(alpha: 0.8),
), ),
), boxShadow: [
const SizedBox(height: 8), BoxShadow(
Text( color: colors.primary.withValues(alpha: 0.28),
balance == null blurRadius: 20,
? '—' offset: const Offset(0, 10),
: formatMoney(balance.amount, balance.currency),
style: theme.textTheme.headlineMedium?.copyWith(
color: colors.onPrimary,
),
),
const SizedBox(height: 12),
Row(
children: [
Icon(
Icons.receipt_long,
size: 16,
color: colors.onPrimary.withValues(alpha: 0.9),
),
const SizedBox(width: 6),
Expanded(
child: Text(
'Tap to view transactions',
style: theme.textTheme.labelMedium?.copyWith(
color: colors.onPrimary.withValues(alpha: 0.9),
),
),
),
Icon(
Icons.chevron_right,
color: colors.onPrimary.withValues(alpha: 0.9),
), ),
], ],
), ),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Current balance',
style: theme.textTheme.labelMedium?.copyWith(
color: colors.onPrimary.withValues(alpha: 0.8),
),
),
const SizedBox(height: 8),
Text(
balance == null
? '—'
: formatMoney(balance.amount, balance.currency),
style: theme.textTheme.headlineMedium?.copyWith(
color: colors.onPrimary,
),
),
const SizedBox(height: 12),
Row(
children: [
Icon(
Icons.receipt_long,
size: 16,
color: colors.onPrimary.withValues(alpha: 0.9),
),
const SizedBox(width: 6),
Expanded(
child: Text(
'Tap to view transactions',
style: theme.textTheme.labelMedium?.copyWith(
color:
colors.onPrimary.withValues(alpha: 0.9),
),
),
),
Icon(
Icons.chevron_right,
color: colors.onPrimary.withValues(alpha: 0.9),
),
],
),
],
),
),
),
),
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showTransactions,
) ||
_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showCategorized,
)) ...[
const SizedBox(height: 20),
Row(
children: [
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showTransactions,
))
Expanded(
child: _EditableHomeBlock(
editing: editingWidgets,
visible: prefs.homeBuiltInSections.showTransactions,
onToggleVisible: (value) =>
prefs.setHomeShowTransactions(value),
child: _StatChip(
label: 'Transactions',
value: '${bank.transactions.length}',
icon: Icons.list_alt,
),
),
),
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showTransactions,
) &&
_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showCategorized,
))
const SizedBox(width: 10),
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showCategorized,
))
Expanded(
child: _EditableHomeBlock(
editing: editingWidgets,
visible: prefs.homeBuiltInSections.showCategorized,
onToggleVisible: (value) =>
prefs.setHomeShowCategorized(value),
child: _StatChip(
label: 'Categorized',
value: '$categorized',
icon: Icons.label_outline,
),
),
),
], ],
), ),
),
),
),
const SizedBox(height: 20),
Row(
children: [
Expanded(
child: _StatChip(
label: 'Transactions',
value: '${bank.transactions.length}',
icon: Icons.list_alt,
),
),
const SizedBox(width: 10),
Expanded(
child: _StatChip(
label: 'Categorized',
value: '$categorized',
icon: Icons.label_outline,
),
),
],
),
if (recent.isNotEmpty) ...[
const SizedBox(height: 24),
Row(
children: [
Text('Recent', style: theme.textTheme.titleMedium),
const Spacer(),
TextButton(
onPressed: () => _openTransactions(context),
child: const Text('See all'),
),
], ],
), if (editingWidgets || widgets.isNotEmpty) ...[
const SizedBox(height: 4), const SizedBox(height: 24),
for (final tx in recent) if (editingWidgets)
ListTile( Align(
contentPadding: EdgeInsets.zero, alignment: Alignment.centerRight,
dense: true, child: TextButton.icon(
leading: Builder( onPressed: () => showHomeWidgetsSheet(context),
builder: (context) { icon: const Icon(Icons.add, size: 18),
final labels = label: const Text('Add'),
meta.leafLabelsFor(meta.metaFor(tx)); ),
final label = labels.isEmpty ? null : labels.first; ),
return Icon( if (widgets.isEmpty)
label?.icon ?? Icons.receipt_long_outlined, Text(
color: label?.color, 'No widgets yet. Tap Add to pin a transaction filter.',
style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant,
),
)
else if (editingWidgets)
ReorderableListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
buildDefaultDragHandles: false,
itemCount: widgets.length,
onReorderItem: prefs.reorderHomeFilterWidgets,
proxyDecorator: (child, index, animation) {
return Material(
elevation: 2,
color: Colors.transparent,
borderRadius: BorderRadius.circular(16),
child: child,
); );
}, },
), itemBuilder: (context, index) {
title: Text( final widgetConfig = widgets[index];
tx.description, return Padding(
maxLines: 1, key: ValueKey(widgetConfig.id),
overflow: TextOverflow.ellipsis, padding: const EdgeInsets.only(bottom: 10),
), child: _HomeWidgetSlot(
subtitle: Text(formatIsoDate(tx.date)), halfWidth: widgetConfig.halfWidth,
trailing: Text( child: HomeFilterWidgetCard(
formatMoney(tx.amount, tx.currency), widgetConfig: widgetConfig,
style: theme.textTheme.titleSmall?.copyWith( editing: true,
color: tx.amount >= 0 ? AppTheme.accent : AppTheme.expense, onToggleDisplay: (display) =>
prefs.setHomeFilterWidgetDisplay(
widgetConfig.id,
display,
),
onEdit: () async {
final preferences =
context.read<PreferencesController>();
final updated = await composeHomeFilterWidget(
context,
existing: widgetConfig,
);
if (updated == null) return;
await preferences.updateHomeFilterWidget(updated);
},
dragHandle: ReorderableDragStartListener(
index: index,
child: Icon(
Icons.drag_handle,
color: colors.onSurfaceVariant,
),
),
),
),
);
},
)
else
..._packedHomeWidgetRows(widgets),
],
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showRecent,
) &&
(recent.isNotEmpty || editingWidgets)) ...[
const SizedBox(height: 24),
_EditableHomeBlock(
editing: editingWidgets,
visible: prefs.homeBuiltInSections.showRecent,
onToggleVisible: (value) => prefs.setHomeShowRecent(value),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Text('Recent', style: theme.textTheme.titleMedium),
const Spacer(),
TextButton(
onPressed: () => _openTransactions(context),
child: const Text('See all'),
),
],
),
const SizedBox(height: 4),
if (recent.isEmpty)
Text(
'No recent transactions yet.',
style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant,
),
)
else
for (final tx in recent)
ListTile(
contentPadding: EdgeInsets.zero,
dense: true,
leading: Builder(
builder: (context) {
final labels =
meta.leafLabelsFor(meta.metaFor(tx));
final label =
labels.isEmpty ? null : labels.first;
return Icon(
label?.icon ?? Icons.receipt_long_outlined,
color: label?.color,
);
},
),
title: Text(
tx.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: Text(formatIsoDate(tx.date)),
trailing: Text(
formatMoney(tx.amount, tx.currency),
style: theme.textTheme.titleSmall?.copyWith(
color: tx.amount >= 0
? AppTheme.accent
: AppTheme.expense,
),
),
onTap: editingWidgets
? null
: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) =>
TransactionDetailScreen(tx: tx),
),
);
},
),
],
), ),
), ),
onTap: () { ],
Navigator.of(context).push( if (bank.error != null) ...[
MaterialPageRoute<void>( const SizedBox(height: 12),
builder: (_) => TransactionDetailScreen(tx: tx), Text(
), bank.error!,
); style: theme.textTheme.bodyMedium
}, ?.copyWith(color: colors.error),
), ),
], ],
if (bank.error != null) ...[ ],
const SizedBox(height: 12), );
Text(
bank.error!,
style: theme.textTheme.bodyMedium?.copyWith(color: colors.error),
),
],
],
);
}, },
); );
} }
@@ -297,8 +470,13 @@ class _StatChip extends StatelessWidget {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(
label,
style: theme.textTheme.labelMedium?.copyWith(
color: colors.onSurfaceVariant,
),
),
Text(value, style: theme.textTheme.titleMedium), Text(value, style: theme.textTheme.titleMedium),
Text(label, style: theme.textTheme.labelMedium),
], ],
), ),
), ),
@@ -307,3 +485,116 @@ class _StatChip extends StatelessWidget {
); );
} }
} }
bool _showBuiltIn({required bool editing, required bool enabled}) =>
editing || enabled;
/// Wraps a built-in Home block with show/hide controls while editing.
class _EditableHomeBlock extends StatelessWidget {
const _EditableHomeBlock({
required this.editing,
required this.visible,
required this.onToggleVisible,
required this.child,
});
final bool editing;
final bool visible;
final ValueChanged<bool> onToggleVisible;
final Widget child;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final content = Opacity(
opacity: editing && !visible ? 0.45 : 1,
child: child,
);
if (!editing) return content;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: content),
IconButton(
tooltip: visible ? 'Hide from Home' : 'Show on Home',
onPressed: () => onToggleVisible(!visible),
icon: Icon(
visible ? Icons.visibility_outlined : Icons.visibility_off_outlined,
color: visible ? colors.onSurfaceVariant : colors.primary,
),
),
],
);
}
}
/// Full- or half-width slot for a Home filter widget card.
class _HomeWidgetSlot extends StatelessWidget {
const _HomeWidgetSlot({
required this.halfWidth,
required this.child,
});
final bool halfWidth;
final Widget child;
@override
Widget build(BuildContext context) {
if (!halfWidth) return child;
return LayoutBuilder(
builder: (context, constraints) {
final width = (constraints.maxWidth - 10) / 2;
return Align(
alignment: Alignment.centerLeft,
child: SizedBox(width: width, child: child),
);
},
);
}
}
List<Widget> _packedHomeWidgetRows(List<HomeFilterWidget> widgets) {
final rows = <Widget>[];
var i = 0;
while (i < widgets.length) {
final a = widgets[i];
final canPair = a.halfWidth &&
i + 1 < widgets.length &&
widgets[i + 1].halfWidth;
if (canPair) {
final b = widgets[i + 1];
rows.add(
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: HomeFilterWidgetCard(widgetConfig: a),
),
const SizedBox(width: 10),
Expanded(
child: HomeFilterWidgetCard(widgetConfig: b),
),
],
),
),
),
);
i += 2;
continue;
}
rows.add(
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _HomeWidgetSlot(
halfWidth: a.halfWidth,
child: HomeFilterWidgetCard(widgetConfig: a),
),
),
);
i += 1;
}
return rows;
}
+4 -1
View File
@@ -31,7 +31,10 @@ class LabelTransactionsScreen extends StatelessWidget {
builder: (context) { builder: (context) {
final txs = [ final txs = [
for (final tx in bank.transactions) for (final tx in bank.transactions)
if (meta.labelIdsFor(tx).contains(label.id)) tx, if (label.id == kUncategorizedFilterId
? meta.labelIdsFor(tx).isEmpty
: meta.labelIdsFor(tx).contains(label.id))
tx,
]; ];
final theme = Theme.of(context); final theme = Theme.of(context);
final currency = bank.balance?.currency ?? final currency = bank.balance?.currency ??
+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),
),
);
},
); );
} }
} }
+11
View File
@@ -2,7 +2,9 @@
library; library;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/sync_provider.dart';
import '../widgets/shell_tab_scope.dart'; import '../widgets/shell_tab_scope.dart';
import 'home_screen.dart'; import 'home_screen.dart';
import 'look_ahead_screen.dart'; import 'look_ahead_screen.dart';
@@ -24,6 +26,15 @@ class _MainShellState extends State<MainShell> {
LookAheadScreen(), LookAheadScreen(),
]; ];
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context.read<SyncController>().syncIfBehindServer();
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ShellTabScope( return ShellTabScope(
File diff suppressed because it is too large Load Diff
+12 -16
View File
@@ -82,17 +82,13 @@ class _SplashScreenState extends State<SplashScreen>
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Container( ClipRRect(
width: 88, borderRadius: BorderRadius.circular(24),
height: 88, child: Image.asset(
decoration: BoxDecoration( 'assets/branding/app_icon.png',
color: colors.onPrimary.withValues(alpha: 0.16), width: 112,
borderRadius: BorderRadius.circular(24), height: 112,
), filterQuality: FilterQuality.high,
child: Icon(
Icons.account_balance_rounded,
size: 44,
color: colors.onPrimary,
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
@@ -103,12 +99,12 @@ class _SplashScreenState extends State<SplashScreen>
), ),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'Your bank data, simply', 'Your bank data, simply',
style: textTheme.bodyLarge?.copyWith( style: textTheme.bodyLarge?.copyWith(
color: colors.onPrimary.withValues(alpha: 0.85), color: colors.onPrimary.withValues(alpha: 0.85),
),
), ),
),
const SizedBox(height: 40), const SizedBox(height: 40),
SizedBox( SizedBox(
width: 28, width: 28,
+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,
+65 -9
View File
@@ -28,8 +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.initialFlow,
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.
@@ -38,12 +43,24 @@ 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;
/// When set, label/search results are limited to this calendar year. /// When set, label/search results are limited to this calendar year.
final int? initialYear; final int? initialYear;
/// Pre-fill search query (e.g. from a Home filter widget).
final String? initialQuery;
final TxFlowFilter? initialFlow;
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();
} }
@@ -57,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;
@@ -78,9 +97,23 @@ 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;
_flowFilter = widget.initialFlow ?? TxFlowFilter.all;
_amountRange = widget.initialAmountRange ?? const TxAmountRange();
final initialQuery = widget.initialQuery?.trim() ?? '';
if (initialQuery.isNotEmpty) {
_searchController.text = initialQuery;
_activeQuery = initialQuery;
} else if (_similarMatch != null &&
_similarMatch!.pattern.trim().isNotEmpty) {
// Show the similar pattern in the search field for context; filtering
// uses [txMatchesSimilarCriteria], not plain text contains.
_searchController.text = _similarMatch!.pattern;
}
} }
@override @override
@@ -91,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;
} }
@@ -129,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, () {
@@ -147,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 {
@@ -165,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,
@@ -177,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;
@@ -229,11 +282,13 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Transactions'), title: const Text('Transactions'),
actions: bankAppBarActions( actions: [
context: context, ...bankAppBarActions(
onRefresh: bank.refresh, context: context,
refreshing: bank.isLoading, onRefresh: bank.refresh,
), refreshing: bank.isLoading,
),
],
), ),
body: Column( body: Column(
children: [ children: [
@@ -340,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,
]; ];
+584 -6
View File
@@ -7,8 +7,13 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pocketbase/pocketbase.dart'; import 'package:pocketbase/pocketbase.dart';
import '../models/app_cloud_prefs.dart';
import '../models/bank.dart'; import '../models/bank.dart';
import '../models/home_built_in_sections.dart';
import '../models/home_filter_widget.dart';
import '../models/overview_favourite.dart';
import '../models/transaction_meta.dart'; import '../models/transaction_meta.dart';
import '../widgets/label_filter_dialog.dart';
import 'ing_csv_import.dart'; import 'ing_csv_import.dart';
import 'storage_service.dart'; import 'storage_service.dart';
@@ -335,6 +340,22 @@ class PbSyncService {
); );
} }
/// Cheap remote count for stale detection (1 row, with totals).
Future<int> countTransactions() async {
final userId = _userId;
final filter = 'user="$userId"';
final result = await _withTimeout(
_pb.collection('transactions').getList(
page: 1,
perPage: 1,
filter: filter,
skipTotal: false,
),
label: 'transactions count',
);
return result.totalItems;
}
/// Pulls the full bank transaction list for the signed-in user. /// Pulls the full bank transaction list for the signed-in user.
Future<List<BankTransaction>> pullTransactions({ Future<List<BankTransaction>> pullTransactions({
void Function(double progress)? onProgress, void Function(double progress)? onProgress,
@@ -410,10 +431,171 @@ class PbSyncService {
return txSummary; return txSummary;
} }
/// Upserts local bank txs to PocketBase. Does **not** delete remote rows /// Pull Overview favourites for the signed-in user.
/// (partial local caches must not wipe another device). ///
/// Soft-fails at the call site if the collection is missing.
Future<List<OverviewFavourite>> pullOverviewFavourites({
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Pulling overview favourites…');
final records = await _fullList('overview_favourites', filter);
final out = <OverviewFavourite>[];
for (final r in records) {
final clientId = r.getStringValue('client_id');
if (clientId.isEmpty) continue;
out.add(
OverviewFavourite(
id: clientId,
name: r.getStringValue('name').isEmpty
? 'Favourite'
: r.getStringValue('name'),
display: r.getBoolValue('display', true),
metric: OverviewMetricMode.values.firstWhere(
(e) => e.name == r.getStringValue('metric'),
orElse: () => OverviewMetricMode.flow,
),
period: OverviewPeriodMode.values.firstWhere(
(e) => e.name == r.getStringValue('period'),
orElse: () => OverviewPeriodMode.monthly,
),
labelIds: _jsonStringList(r.get<dynamic>('label_ids')),
flow: TxFlowFilter.values.firstWhere(
(e) => e.name == r.getStringValue('flow'),
orElse: () => TxFlowFilter.expense,
),
barStyle: LabelChartBarStyle.values.firstWhere(
(e) => e.name == r.getStringValue('bar_style'),
orElse: () => LabelChartBarStyle.parallel,
),
invertExpensePerspective:
r.getBoolValue('invert_expense_perspective'),
updatedAt: _recordUpdatedAtMs(r),
deleted: r.getBoolValue('deleted'),
),
);
}
debugPrint('PbSyncService pull: overview_favourites=${out.length}');
return out;
}
/// Upsert Overview favourites; deletes remote rows no longer local.
Future<void> pushOverviewFavourites(
List<OverviewFavourite> favourites, {
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Syncing overview favourites…');
await _syncOverviewFavourites(userId, filter, favourites);
}
/// Pull Home filter widgets for the signed-in user.
Future<List<HomeFilterWidget>> pullHomeFilterWidgets({
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Pulling home widgets…');
final records = await _fullList('home_filter_widgets', filter);
final out = <HomeFilterWidget>[];
for (final r in records) {
final clientId = r.getStringValue('client_id');
if (clientId.isEmpty) continue;
final rangeRaw = r.get<dynamic>('amount_range');
out.add(
HomeFilterWidget.fromJson({
'id': clientId,
'name': r.getStringValue('name'),
'display': r.getBoolValue('display', true),
'sortOrder': r.getIntValue('sort_order', 0),
'halfWidth': r.getBoolValue('half_width'),
'type': r.getStringValue('widget_type'),
'iconId': r.getStringValue('icon_id'),
'chartStyle': r.getStringValue('chart_style'),
'budgetCapMode': r.getStringValue('budget_cap_mode'),
'budgetFixedAmount': switch (r.get<dynamic>('budget_fixed_amount')) {
num n => n.toDouble(),
String s => double.tryParse(s) ?? 0,
_ => 0.0,
},
'budgetAverageMonths': r.getIntValue('budget_average_months', 3),
'labelIds': _jsonStringList(r.get<dynamic>('label_ids')),
'labelMatch': r.getStringValue('label_match'),
'flow': r.getStringValue('flow'),
'amountRange': rangeRaw is Map
? Map<String, dynamic>.from(rangeRaw)
: const <String, dynamic>{},
'query': r.getStringValue('query'),
'monthOnly': r.getBoolValue('month_only'),
'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'),
}),
);
}
debugPrint('PbSyncService pull: home_filter_widgets=${out.length}');
return out;
}
Future<void> pushHomeFilterWidgets(
List<HomeFilterWidget> widgets, {
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Syncing home widgets…');
await _syncHomeFilterWidgets(userId, filter, widgets);
}
/// Pull per-user app prefs (Home sections + Look ahead). Soft-fail if missing.
Future<AppCloudPrefs?> pullAppPrefs({
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Pulling app prefs…');
final records = await _fullList('app_prefs', filter);
if (records.isEmpty) {
debugPrint('PbSyncService pull: app_prefs=0');
return null;
}
final r = records.first;
final prefs = AppCloudPrefs(
homeBuiltInSections: HomeBuiltInSections(
showTransactions: r.getBoolValue('home_show_transactions', true),
showCategorized: r.getBoolValue('home_show_categorized', true),
showRecent: r.getBoolValue('home_show_recent', true),
),
lookAheadMaxYears:
r.getIntValue('look_ahead_max_years', 5).clamp(1, 30),
);
debugPrint('PbSyncService pull: app_prefs=1');
return prefs;
}
/// Upsert the single app_prefs row for this user.
Future<void> pushAppPrefs(
AppCloudPrefs prefs, {
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Syncing app prefs…');
await _syncAppPrefs(userId, filter, prefs);
}
/// 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( Future<String> pushTransactions(
List<BankTransaction> local, { List<BankTransaction> local, {
List<BankTransaction> deleteTombs = const [],
void Function(double progress)? onProgress, void Function(double progress)? onProgress,
void Function(String message)? onStatus, void Function(String message)? onStatus,
double progressStart = 0.0, double progressStart = 0.0,
@@ -442,10 +624,19 @@ class PbSyncService {
final ops = <_BatchOp>[]; final ops = <_BatchOp>[];
var skipped = 0; var skipped = 0;
final seen = <String>{}; 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) { for (final tx in local) {
final syncId = _clip(tx.id, 2000); final syncId = _clip(tx.id, 2000);
if (syncId.isEmpty || !seen.add(syncId)) continue; 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>{ final body = <String, dynamic>{
'user': userId, 'user': userId,
'tx_id': syncId, 'tx_id': syncId,
@@ -460,6 +651,9 @@ class PbSyncService {
8, 8,
), ),
'pending': tx.pending, 'pending': tx.pending,
// Only send when true so servers without the migration still accept
// normal bank/CSV upserts. Test rows are also detected via ·# stamp.
if (tx.isManual) 'is_manual': true,
}; };
final remote = existing[syncId]; final remote = existing[syncId];
if (remote == null) { if (remote == null) {
@@ -471,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 creates = ops.where((o) => o.kind == _BatchOpKind.create).length;
final updates = ops.where((o) => o.kind == _BatchOpKind.update).length; final updates = ops.where((o) => o.kind == _BatchOpKind.update).length;
debugPrint( debugPrint(
'PbSyncService transactions: local=${local.length} ' '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( onStatus?.call(
ops.isEmpty ops.isEmpty
@@ -489,8 +697,13 @@ class PbSyncService {
onStatus: onStatus, onStatus: onStatus,
); );
return 'Bank txs: local ${local.length} → remote ' return 'Bank txs: local ${local.length} → remote '
'${existing.length + creates} ' '${existing.length + creates - deletes} '
'(+$creates ~$updates · $skipped unchanged)'; '(+$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) { BankTransaction? _bankTxFromRecord(RecordModel r) {
@@ -511,6 +724,8 @@ class PbSyncService {
? 'EUR' ? 'EUR'
: r.getStringValue('currency'), : r.getStringValue('currency'),
pending: r.getBoolValue('pending'), pending: r.getBoolValue('pending'),
isManual: r.getBoolValue('is_manual') ||
RegExp(r' ·#\d+$').hasMatch(description),
); );
} }
@@ -521,13 +736,126 @@ class PbSyncService {
String s => double.tryParse(s) ?? 0, String s => double.tryParse(s) ?? 0,
_ => 0.0, _ => 0.0,
}; };
final remoteManual = remote.getBoolValue('is_manual') ||
RegExp(r' ·#\d+$').hasMatch(remote.getStringValue('description'));
return remote.getStringValue('date') == tx.date && return remote.getStringValue('date') == tx.date &&
remote.getStringValue('description') == remote.getStringValue('description') ==
_clip(tx.description.isEmpty ? 'Unknown' : tx.description, 4000) && _clip(tx.description.isEmpty ? 'Unknown' : tx.description, 4000) &&
(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 &&
remoteManual == tx.isManual;
}
/// Deletes remote bank rows matching [tombstones] by tx_id or field fingerprint.
///
/// Returns the tombstones that matched at least one remote row (safe to clear).
Future<List<BankTransaction>> deleteTransactionsMatching(
List<BankTransaction> tombstones,
) async {
if (tombstones.isEmpty) return const [];
final userId = _userId;
final filter = 'user="$userId"';
final existing = await _fullList('transactions', filter);
final matchedTombs = <BankTransaction>[];
final ops = <_BatchOp>[];
final seenRecordIds = <String>{};
for (final r in existing) {
final remoteTx = _bankTxFromRecord(r);
if (remoteTx == null) continue;
for (final tomb in tombstones) {
final txId = r.getStringValue('tx_id');
final idHit = txId == _clip(tomb.id, 2000);
if (!idHit && !remoteTx.matchesForDelete(tomb)) continue;
if (!seenRecordIds.add(r.id)) break;
ops.add(_BatchOp.delete(r.id));
if (!matchedTombs.any(tomb.matchesForDelete)) {
matchedTombs.add(tomb);
}
break;
}
}
if (ops.isEmpty) {
debugPrint(
'PbSyncService deleteTransactionsMatching: 0 hits '
'for ${tombstones.length} tombstone(s)',
);
return const [];
}
await _runWriteOps('transactions', ops);
debugPrint(
'PbSyncService deleteTransactionsMatching: deleted ${ops.length} '
'for ${matchedTombs.length} tombstone(s)',
);
return matchedTombs;
}
/// Pull synced delete tombstones for admin test transactions.
Future<List<BankTransaction>> pullTxDeletes({
void Function(String message)? onStatus,
}) async {
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Pulling deleted test txs…');
final records = await _fullList('tx_deletes', filter);
final out = <BankTransaction>[];
for (final r in records) {
final tx = _bankTxFromRecord(r);
if (tx == null) continue;
out.add(tx.copyWith(isManual: true));
}
debugPrint('PbSyncService pull: tx_deletes=${out.length}');
return out;
}
/// Upsert local delete tombstones. Never removes remote-only rows (union).
Future<String> pushTxDeletes(
List<BankTransaction> tombs, {
void Function(String message)? onStatus,
}) async {
if (tombs.isEmpty) return 'Tx deletes: nothing to push';
final userId = _userId;
final filter = 'user="$userId"';
onStatus?.call('Syncing deleted test txs…');
final existing = {
for (final r in await _fullList('tx_deletes', filter))
r.getStringValue('tx_id'): r,
};
final ops = <_BatchOp>[];
var skipped = 0;
final seen = <String>{};
for (final tomb in tombs) {
final syncId = _clip(tomb.id, 2000);
if (syncId.isEmpty || !seen.add(syncId)) continue;
final body = <String, dynamic>{
'user': userId,
'tx_id': syncId,
'date': _clip(tomb.date, 32),
'description': _clip(
tomb.description.isEmpty ? 'Unknown' : tomb.description,
4000,
),
'amount': tomb.amount,
'currency': _clip(
tomb.currency.isEmpty ? 'EUR' : tomb.currency.toUpperCase(),
8,
),
};
final remote = existing[syncId];
if (remote == null) {
ops.add(_BatchOp.create(body));
} else {
skipped++;
}
}
await _runWriteOps('tx_deletes', ops, onStatus: onStatus);
return 'Tx deletes: local ${tombs.length} (+${ops.length} · $skipped exist)';
} }
Future<void> _runOne(String collection, _BatchOp op) { Future<void> _runOne(String collection, _BatchOp op) {
@@ -672,12 +1000,34 @@ class PbSyncService {
filter = filter =
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"'; 'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
} }
case 'overview_favourites':
final key = body['client_id'];
if (userId != null && key is String) {
filter =
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
}
case 'home_filter_widgets':
final key = body['client_id'];
if (userId != null && key is String) {
filter =
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
}
case 'app_prefs':
if (userId != null) {
filter = 'user="$userId"';
}
case 'transactions': case 'transactions':
final key = body['tx_id']; final key = body['tx_id'];
if (userId != null && key is String) { if (userId != null && key is String) {
filter = filter =
'user="$userId" && tx_id="${key.replaceAll('"', '\\"')}"'; '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) { if (filter == null) {
throw StateError('Cannot upsert $collection without filter'); throw StateError('Cannot upsert $collection without filter');
@@ -977,6 +1327,153 @@ class PbSyncService {
await _runWriteOps('recurring_templates', ops); await _runWriteOps('recurring_templates', ops);
} }
Future<void> _syncOverviewFavourites(
String userId,
String filter,
List<OverviewFavourite> favourites,
) async {
final existing = {
for (final r in await _fullList('overview_favourites', filter))
r.getStringValue('client_id'): r,
};
final keep = <String>{};
final ops = <_BatchOp>[];
for (final fav in favourites) {
final clientId = _clip(fav.id, 120);
if (clientId.isEmpty) continue;
keep.add(clientId);
final body = <String, dynamic>{
'user': userId,
'client_id': clientId,
'name': _clip(fav.name.isEmpty ? 'Favourite' : fav.name, 200),
'display': fav.display,
'metric': fav.metric.name,
'period': fav.period.name,
'label_ids': fav.labelIds,
'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) {
ops.add(_BatchOp.create(body));
} else if (!_overviewFavouriteUnchanged(remote, fav)) {
ops.add(_BatchOp.update(remote.id, body));
}
}
for (final e in existing.entries) {
if (!keep.contains(e.key)) {
ops.add(_BatchOp.delete(e.value.id));
}
}
debugPrint(
'PbSyncService overview_favourites: remote=${existing.length} '
'ops=${ops.length}',
);
await _runWriteOps('overview_favourites', ops);
}
Future<void> _syncHomeFilterWidgets(
String userId,
String filter,
List<HomeFilterWidget> widgets,
) async {
final existing = {
for (final r in await _fullList('home_filter_widgets', filter))
r.getStringValue('client_id'): r,
};
final keep = <String>{};
final ops = <_BatchOp>[];
for (final w in widgets) {
final clientId = _clip(w.id, 120);
if (clientId.isEmpty) continue;
keep.add(clientId);
final body = <String, dynamic>{
'user': userId,
'client_id': clientId,
'name': _clip(w.name.isEmpty ? 'Filter' : w.name, 200),
'display': w.display,
'sort_order': w.sortOrder,
'half_width': w.halfWidth,
'widget_type': w.type.name,
'icon_id': w.iconId,
'chart_style': w.chartStyle.name,
'budget_cap_mode': w.budgetCapMode.name,
'budget_fixed_amount': w.budgetFixedAmount,
'budget_average_months': w.budgetAverageMonths,
'label_ids': w.labelIds,
'label_match': w.labelMatch.name,
'flow': w.flow.name,
'amount_range': {
if (w.amountRange.exact != null) 'exact': w.amountRange.exact,
if (w.amountRange.min != null) 'min': w.amountRange.min,
if (w.amountRange.max != null) 'max': w.amountRange.max,
},
'query': _clip(w.query, 400),
'month_only': w.monthOnly,
'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) {
ops.add(_BatchOp.create(body));
} else if (!_homeFilterWidgetUnchanged(remote, w)) {
ops.add(_BatchOp.update(remote.id, body));
}
}
for (final e in existing.entries) {
if (!keep.contains(e.key)) {
ops.add(_BatchOp.delete(e.value.id));
}
}
debugPrint(
'PbSyncService home_filter_widgets: remote=${existing.length} '
'ops=${ops.length}',
);
await _runWriteOps('home_filter_widgets', ops);
}
Future<void> _syncAppPrefs(
String userId,
String filter,
AppCloudPrefs prefs,
) async {
final existing = await _fullList('app_prefs', filter);
final body = <String, dynamic>{
'user': userId,
'home_show_transactions': prefs.homeBuiltInSections.showTransactions,
'home_show_categorized': prefs.homeBuiltInSections.showCategorized,
'home_show_recent': prefs.homeBuiltInSections.showRecent,
'look_ahead_max_years': prefs.lookAheadMaxYears.clamp(1, 30),
};
final ops = <_BatchOp>[];
if (existing.isEmpty) {
ops.add(_BatchOp.create(body));
} else {
final remote = existing.first;
if (!_appPrefsUnchanged(remote, prefs)) {
ops.add(_BatchOp.update(remote.id, body));
}
// Enforce singleton: drop extras if any.
for (var i = 1; i < existing.length; i++) {
ops.add(_BatchOp.delete(existing[i].id));
}
}
debugPrint('PbSyncService app_prefs: remote=${existing.length} ops=${ops.length}');
await _runWriteOps('app_prefs', ops);
}
bool _labelUnchanged(RecordModel remote, Map<String, dynamic> body) { bool _labelUnchanged(RecordModel remote, Map<String, dynamic> body) {
return remote.getStringValue('name') == body['name'] && return remote.getStringValue('name') == body['name'] &&
remote.getIntValue('color') == body['color'] && remote.getIntValue('color') == body['color'] &&
@@ -1019,6 +1516,87 @@ class PbSyncService {
remote.getIntValue('avg_count', 5) == t.avgCount && remote.getIntValue('avg_count', 5) == t.avgCount &&
remote.getBoolValue('auto_from_recurring') == t.autoFromRecurring; remote.getBoolValue('auto_from_recurring') == t.autoFromRecurring;
} }
bool _overviewFavouriteUnchanged(RecordModel remote, OverviewFavourite fav) {
final remoteIds = _jsonStringList(remote.get<dynamic>('label_ids'));
return remote.getStringValue('name') == fav.name &&
remote.getBoolValue('display', true) == fav.display &&
remote.getStringValue('metric') == fav.metric.name &&
remote.getStringValue('period') == fav.period.name &&
_sameIdList(remoteIds, fav.labelIds) &&
remote.getStringValue('flow') == fav.flow.name &&
remote.getStringValue('bar_style') == fav.barStyle.name &&
remote.getBoolValue('invert_expense_perspective') ==
fav.invertExpensePerspective &&
remote.getBoolValue('deleted') == fav.deleted &&
_recordUpdatedAtMs(remote) == fav.updatedAt;
}
bool _homeFilterWidgetUnchanged(RecordModel remote, HomeFilterWidget w) {
final remoteIds = _jsonStringList(remote.get<dynamic>('label_ids'));
final rangeRaw = remote.get<dynamic>('amount_range');
final rangeMap = rangeRaw is Map
? Map<String, dynamic>.from(rangeRaw)
: const <String, dynamic>{};
double? asDouble(dynamic value) => value is num ? value.toDouble() : null;
final remoteFixed = switch (remote.get<dynamic>('budget_fixed_amount')) {
num n => n.toDouble(),
String s => double.tryParse(s) ?? 0,
_ => 0.0,
};
return remote.getStringValue('name') == w.name &&
remote.getBoolValue('display', true) == w.display &&
remote.getIntValue('sort_order', 0) == w.sortOrder &&
remote.getBoolValue('half_width') == w.halfWidth &&
remote.getStringValue('widget_type') == w.type.name &&
remote.getStringValue('icon_id') == w.iconId &&
remote.getStringValue('chart_style') == w.chartStyle.name &&
remote.getStringValue('budget_cap_mode') == w.budgetCapMode.name &&
(remoteFixed * 100).round() == (w.budgetFixedAmount * 100).round() &&
remote.getIntValue('budget_average_months', 3) ==
w.budgetAverageMonths &&
_sameIdList(remoteIds, w.labelIds) &&
(remote.getStringValue('label_match').isEmpty
? 'and'
: remote.getStringValue('label_match')) ==
w.labelMatch.name &&
remote.getStringValue('flow') == w.flow.name &&
asDouble(rangeMap['exact']) == w.amountRange.exact &&
asDouble(rangeMap['min']) == w.amountRange.min &&
asDouble(rangeMap['max']) == w.amountRange.max &&
remote.getStringValue('query') == w.query &&
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('deleted') == w.deleted &&
_recordUpdatedAtMs(remote) == w.updatedAt;
}
bool _appPrefsUnchanged(RecordModel remote, AppCloudPrefs prefs) {
final s = prefs.homeBuiltInSections;
return remote.getBoolValue('home_show_transactions', true) ==
s.showTransactions &&
remote.getBoolValue('home_show_categorized', true) ==
s.showCategorized &&
remote.getBoolValue('home_show_recent', true) == s.showRecent &&
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) { RecurringTemplateSource _parseTemplateSource(String raw) {
+121 -18
View File
@@ -7,6 +7,9 @@ import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../models/bank.dart'; import '../models/bank.dart';
import '../models/home_built_in_sections.dart';
import '../models/home_filter_widget.dart';
import '../models/overview_favourite.dart';
import '../models/transaction_meta.dart'; import '../models/transaction_meta.dart';
import '../utils/constants.dart'; import '../utils/constants.dart';
@@ -62,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,
},
], ],
}; };
@@ -133,6 +129,75 @@ class StorageService {
return _prefs.setInt(StorageKeys.lookAheadMaxYears, years.clamp(1, 30)); return _prefs.setInt(StorageKeys.lookAheadMaxYears, years.clamp(1, 30));
} }
List<OverviewFavourite> loadOverviewFavourites() {
final raw = _prefs.getString(StorageKeys.overviewFavourites);
if (raw == null || raw.isEmpty) return const [];
try {
final decoded = jsonDecode(raw);
if (decoded is! List) return const [];
return [
for (final item in decoded)
if (item is Map)
OverviewFavourite.fromJson(Map<String, dynamic>.from(item)),
];
} catch (_) {
return const [];
}
}
Future<void> saveOverviewFavourites(List<OverviewFavourite> favourites) {
final encoded = jsonEncode([
for (final fav in favourites) fav.toJson(),
]);
return _prefs.setString(StorageKeys.overviewFavourites, encoded);
}
List<HomeFilterWidget> loadHomeFilterWidgets() {
final raw = _prefs.getString(StorageKeys.homeFilterWidgets);
if (raw == null || raw.isEmpty) return const [];
try {
final decoded = jsonDecode(raw);
if (decoded is! List) return const [];
final list = [
for (final item in decoded)
if (item is Map)
HomeFilterWidget.fromJson(Map<String, dynamic>.from(item)),
];
list.sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
return list;
} catch (_) {
return const [];
}
}
Future<void> saveHomeFilterWidgets(List<HomeFilterWidget> widgets) {
final encoded = jsonEncode([
for (final w in widgets) w.toJson(),
]);
return _prefs.setString(StorageKeys.homeFilterWidgets, encoded);
}
HomeBuiltInSections loadHomeBuiltInSections() {
final raw = _prefs.getString(StorageKeys.homeBuiltInSections);
if (raw == null || raw.isEmpty) return HomeBuiltInSections.defaults;
try {
final decoded = jsonDecode(raw);
if (decoded is! Map) return HomeBuiltInSections.defaults;
return HomeBuiltInSections.fromJson(
Map<String, dynamic>.from(decoded),
);
} catch (_) {
return HomeBuiltInSections.defaults;
}
}
Future<void> saveHomeBuiltInSections(HomeBuiltInSections sections) {
return _prefs.setString(
StorageKeys.homeBuiltInSections,
jsonEncode(sections.toJson()),
);
}
bool get useRemoteData => _prefs.getBool(StorageKeys.useRemoteData) ?? false; bool get useRemoteData => _prefs.getBool(StorageKeys.useRemoteData) ?? false;
Future<void> setUseRemoteData(bool value) { Future<void> setUseRemoteData(bool value) {
@@ -186,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);
} }
@@ -204,6 +260,53 @@ class StorageService {
return _prefs.remove(StorageKeys.importedTransactions); 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() { TxMetaStoreData loadTxMetaStore() {
final raw = _prefs.getString(StorageKeys.txMeta); final raw = _prefs.getString(StorageKeys.txMeta);
if (raw != null && raw.isNotEmpty) { if (raw != null && raw.isNotEmpty) {
+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);
+12
View File
@@ -46,11 +46,23 @@ abstract final class StorageKeys {
static const bankCache = 'bank_cache_v1'; static const bankCache = 'bank_cache_v1';
static const importedTransactions = 'imported_txs_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). /// Serialized PocketBase auth token + user record (separate from tx data).
static const pocketBaseAuth = 'pb_auth_v1'; static const pocketBaseAuth = 'pb_auth_v1';
/// How many years ahead Look ahead can navigate (default 5). /// How many years ahead Look ahead can navigate (default 5).
static const lookAheadMaxYears = 'look_ahead_max_years_v1'; static const lookAheadMaxYears = 'look_ahead_max_years_v1';
/// Named Overview chart favourites (JSON list).
static const overviewFavourites = 'overview_favourites_v1';
/// Home screen filter widgets (JSON list).
static const homeFilterWidgets = 'home_filter_widgets_v1';
/// Built-in Home sections visibility (Transactions / Categorized / Recent).
static const homeBuiltInSections = 'home_built_in_sections_v1';
} }
/// Named routes registered on [MaterialApp]. /// Named routes registered on [MaterialApp].
+160
View File
@@ -0,0 +1,160 @@
/// Apply a [TransactionFilterSelection] and compute Home widget metrics.
library;
import '../models/bank.dart';
import '../models/home_filter_widget.dart';
import '../models/transaction_meta.dart';
import '../providers/tx_meta_provider.dart';
import '../utils/tx_calendar.dart';
import '../widgets/label_filter_dialog.dart';
class TxFilterMetrics {
const TxFilterMetrics({
required this.count,
required this.amountIn,
required this.amountOut,
required this.transactions,
});
final int count;
final double amountIn;
final double amountOut;
final List<BankTransaction> transactions;
double get net => amountIn - amountOut;
}
class HomeBudgetMetrics {
const HomeBudgetMetrics({
required this.monthNet,
required this.target,
required this.averageMonths,
});
/// Net (in − out) for the current calendar month.
final double monthNet;
/// Positive budget ceiling (fixed amount or avg |net| of last N months).
final double target;
final int averageMonths;
/// How much of the ceiling is used, based on |monthNet|.
double get used => monthNet.abs();
double get progress => target <= 0 ? 0 : used / target;
bool get overBudget => target > 0 && used > target;
}
/// Filter [all] the same way Transactions does (pool → search → flow/amount).
List<BankTransaction> applyTransactionFilter({
required List<BankTransaction> all,
required TxMetaController meta,
required TransactionFilterSelection filter,
DateTime? month,
bool forceMonthOnly = false,
}) {
final nowMonth = monthStart(month ?? DateTime.now());
final limitToMonth = forceMonthOnly || filter.monthOnly;
final pool = limitToMonth
? [
for (final tx in all)
if (_txInMonth(tx, nowMonth)) tx,
]
: all;
return [
for (final tx in meta.search(
pool,
filter.query,
labelIds: filter.labelIds,
labelMatch: filter.labelMatch,
))
if (txMatchesFlow(tx, filter.flow) &&
txMatchesAmountRange(tx, filter.amountRange))
tx,
];
}
TxFilterMetrics computeTxFilterMetrics({
required List<BankTransaction> all,
required TxMetaController meta,
required TransactionFilterSelection filter,
DateTime? month,
bool forceMonthOnly = false,
}) {
final filtered = applyTransactionFilter(
all: all,
meta: meta,
filter: filter,
month: month,
forceMonthOnly: forceMonthOnly,
);
var amountIn = 0.0;
var amountOut = 0.0;
for (final tx in filtered) {
if (meta.metaFor(tx).internalTransfer) continue;
if (tx.amount < 0) {
amountOut += tx.amount.abs();
} else if (tx.amount > 0) {
amountIn += tx.amount;
}
}
return TxFilterMetrics(
count: filtered.length,
amountIn: amountIn,
amountOut: amountOut,
transactions: filtered,
);
}
/// Budget progress: this month’s |net| vs fixed or average-of-last-N-months cap.
HomeBudgetMetrics computeHomeBudgetMetrics({
required List<BankTransaction> all,
required TxMetaController meta,
required HomeFilterWidget widget,
DateTime? now,
}) {
final today = now ?? DateTime.now();
final currentMonth = monthStart(today);
final monthFilter = widget.filter;
final monthNet = computeTxFilterMetrics(
all: all,
meta: meta,
filter: monthFilter,
month: currentMonth,
forceMonthOnly: true,
).net;
final months = widget.budgetAverageMonths.clamp(1, 36);
final double target;
if (widget.budgetCapMode == HomeBudgetCapMode.fixed) {
target = widget.budgetFixedAmount.abs();
} else {
var sum = 0.0;
for (var i = 1; i <= months; i++) {
final month = addMonths(currentMonth, -i);
sum += computeTxFilterMetrics(
all: all,
meta: meta,
filter: monthFilter,
month: month,
forceMonthOnly: true,
).net.abs();
}
target = sum / months;
}
return HomeBudgetMetrics(
monthNet: monthNet,
target: target,
averageMonths: months,
);
}
bool _txInMonth(BankTransaction tx, DateTime month) {
final date = DateTime.tryParse(tx.date);
if (date == null) return false;
return isSameMonth(date, month);
}
@@ -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'),
),
],
);
}
}
+812
View File
@@ -0,0 +1,812 @@
/// Home card for a saved transaction-filter widget.
library;
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/bank.dart';
import '../models/home_filter_widget.dart';
import '../providers/bank_provider.dart';
import '../providers/tx_meta_provider.dart';
import '../screens/transactions_screen.dart';
import '../utils/app_theme.dart';
import '../utils/helpers.dart';
import '../utils/tx_filter_metrics.dart';
class HomeFilterWidgetCard extends StatelessWidget {
const HomeFilterWidgetCard({
super.key,
required this.widgetConfig,
this.editing = false,
this.onToggleDisplay,
this.onEdit,
this.dragHandle,
});
final HomeFilterWidget widgetConfig;
final bool editing;
final ValueChanged<bool>? onToggleDisplay;
final VoidCallback? onEdit;
final Widget? dragHandle;
void _openTransactions(BuildContext context) {
final filter = widgetConfig.filter;
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => TransactionsScreen(
initialLabelIds: filter.labelIds,
initialLabelMatch: filter.labelMatch,
initialSearchInMonthOnly:
widgetConfig.type == HomeWidgetType.budget || filter.monthOnly,
initialQuery: filter.query,
initialFlow: filter.flow,
initialAmountRange: filter.amountRange,
),
),
);
}
@override
Widget build(BuildContext context) {
final bank = context.watch<BankController>();
final meta = context.watch<TxMetaController>();
final theme = Theme.of(context);
final colors = theme.colorScheme;
final currency = bank.balance?.currency ??
(bank.transactions.isNotEmpty
? bank.transactions.first.currency
: 'EUR');
final hidden = editing && !widgetConfig.display;
return Opacity(
opacity: hidden ? 0.45 : 1,
child: Card(
color: colors.surfaceContainer,
elevation: 0,
margin: EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: InkWell(
onTap: editing ? onEdit : () => _openTransactions(context),
child: Padding(
padding: EdgeInsets.fromLTRB(
14,
14,
editing ? 4 : 14,
14,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (dragHandle != null) ...[
Padding(
padding: const EdgeInsets.only(top: 8),
child: dragHandle!,
),
const SizedBox(width: 4),
],
Expanded(
child: widgetConfig.type == HomeWidgetType.budget
? _BudgetBody(
widgetConfig: widgetConfig,
currency: currency,
transactions: bank.transactions,
meta: meta,
)
: _StatsBody(
widgetConfig: widgetConfig,
currency: currency,
transactions: bank.transactions,
meta: meta,
),
),
if (editing && onToggleDisplay != null)
IconButton(
tooltip: widgetConfig.display
? 'Hide from Home'
: 'Show on Home',
onPressed: () =>
onToggleDisplay!(!widgetConfig.display),
icon: Icon(
widgetConfig.display
? Icons.remove_circle_outline
: Icons.add_circle_outline,
color: widgetConfig.display
? colors.error
: colors.primary,
),
),
],
),
),
),
),
);
}
}
String _monthName(DateTime date) {
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
return months[date.month - 1];
}
String? _subtitleFor(HomeFilterWidget widget) {
if (widget.type == HomeWidgetType.budget) return 'MONTHLY LIMIT';
if (widget.monthOnly) return _monthName(DateTime.now());
return null;
}
class _IconBadge extends StatelessWidget {
const _IconBadge({required this.icon});
final IconData icon;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return Container(
width: 40,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: colors.outlineVariant.withValues(alpha: 0.55),
),
color: colors.surfaceContainerHigh.withValues(alpha: 0.35),
),
child: Icon(icon, color: colors.primary, size: 20),
);
}
}
class _CardHeader extends StatelessWidget {
const _CardHeader({
required this.icon,
required this.title,
this.subtitle,
this.trailing,
});
final IconData icon;
final String title;
final String? subtitle;
final Widget? trailing;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_IconBadge(icon: icon),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (subtitle != null) ...[
const SizedBox(height: 2),
Text(
subtitle!,
style: theme.textTheme.labelSmall?.copyWith(
color: colors.onSurfaceVariant,
letterSpacing:
subtitle == 'MONTHLY LIMIT' ? 0.6 : 0,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
),
),
if (trailing != null) ...[
const SizedBox(width: 8),
trailing!,
],
],
);
}
}
class _UsedPill extends StatelessWidget {
const _UsedPill({required this.label});
final String label;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: colors.surfaceContainerHighest.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(999),
),
child: Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
color: colors.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
);
}
}
class _StatsBody extends StatelessWidget {
const _StatsBody({
required this.widgetConfig,
required this.currency,
required this.transactions,
required this.meta,
});
final HomeFilterWidget widgetConfig;
final String currency;
final List<BankTransaction> transactions;
final TxMetaController meta;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final metrics = computeTxFilterMetrics(
all: transactions,
meta: meta,
filter: widgetConfig.filter,
);
// Prefer a single hero "Spent" figure when that's the main metric.
final spentOnly = widgetConfig.showAmountOut &&
!widgetConfig.showAmountIn &&
!widgetConfig.showCount;
final half = widgetConfig.halfWidth;
Widget metricsBlock({required bool alignEnd}) {
if (spentOnly) {
return Column(
crossAxisAlignment:
alignEnd ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
Text(
'Spent',
style: theme.textTheme.labelMedium?.copyWith(
color: colors.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(
formatMoney(metrics.amountOut, currency),
style: theme.textTheme.titleMedium?.copyWith(
color: AppTheme.expense,
fontWeight: FontWeight.w700,
height: 1.15,
),
),
],
);
}
return Wrap(
spacing: 16,
runSpacing: 8,
alignment: alignEnd ? WrapAlignment.end : WrapAlignment.start,
children: [
if (widgetConfig.showAmountIn)
_Metric(
label: 'In',
value: formatMoney(metrics.amountIn, currency),
color: AppTheme.accent,
),
if (widgetConfig.showAmountOut)
_Metric(
label: 'Spent',
value: formatMoney(metrics.amountOut, currency),
color: AppTheme.expense,
),
if (widgetConfig.showCount)
_Metric(
label: 'Transactions',
value: '${metrics.count}',
color: colors.primary,
),
],
);
}
// Avoid LayoutBuilder/Spacer/Expanded here: half-width rows use
// IntrinsicHeight, which cannot measure those widgets.
if (!half) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _CardHeader(
icon: widgetConfig.icon,
title: widgetConfig.name,
subtitle: _subtitleFor(widgetConfig),
),
),
const SizedBox(width: 12),
Flexible(
child: metricsBlock(alignEnd: true),
),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_CardHeader(
icon: widgetConfig.icon,
title: widgetConfig.name,
subtitle: _subtitleFor(widgetConfig),
),
SizedBox(height: spentOnly ? 32 : 14),
metricsBlock(alignEnd: false),
],
);
}
}
class _BudgetBody extends StatelessWidget {
const _BudgetBody({
required this.widgetConfig,
required this.currency,
required this.transactions,
required this.meta,
});
final HomeFilterWidget widgetConfig;
final String currency;
final List<BankTransaction> transactions;
final TxMetaController meta;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final budget = computeHomeBudgetMetrics(
all: transactions,
meta: meta,
widget: widgetConfig,
);
final progress = budget.progress.clamp(0.0, 1.0);
final fillColor = budget.overBudget
? AppTheme.expense
: AppTheme.budgetProgressFill(
budget.target <= 0 ? 0 : progress,
);
// Grayish unfilled track (not green-tinted).
final trackColor = Color.alphaBlend(
colors.onSurface.withValues(alpha: 0.14),
colors.surfaceContainerHigh,
);
final trackLabelColor = colors.onSurfaceVariant;
final spentLabelColor = colors.onSurface;
final pct = budget.target <= 0 ? 0 : (progress * 100).round();
final half = widgetConfig.halfWidth;
final isBar = widgetConfig.chartStyle == HomeWidgetChartStyle.bar;
final subtitle = widgetConfig.monthOnly
? _monthName(DateTime.now())
: 'MONTHLY LIMIT';
final capLine = _BudgetLegendLine(
bulletColor: trackLabelColor.withValues(alpha: 0.75),
textColor: trackLabelColor,
fontWeight: FontWeight.w500,
text: budget.target <= 0
? '— cap'
: formatMoney(budget.target, currency),
);
final spentLine = _BudgetLegendLine(
bulletColor: fillColor,
textColor: spentLabelColor,
fontWeight: FontWeight.w700,
text: formatMoney(budget.used, currency),
);
final isRingOrPie = widgetConfig.chartStyle == HomeWidgetChartStyle.pie ||
widgetConfig.chartStyle == HomeWidgetChartStyle.ring;
Widget ringChart({required double size}) => SizedBox(
width: size,
height: size,
child: CustomPaint(
painter: _BudgetChartPainter(
progress: budget.target <= 0 ? 0 : progress,
style: widgetConfig.chartStyle,
fillColor: fillColor,
trackColor: trackColor,
percentLabel: budget.target > 0 ? '$pct%' : null,
labelColor: colors.onSurface,
labelScale: 0.32,
),
),
);
// Full-width ring/pie: ring beside header+amounts so the card stays short.
if (isRingOrPie && !half) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_CardHeader(
icon: widgetConfig.icon,
title: widgetConfig.name,
subtitle: subtitle,
),
const SizedBox(height: 10),
capLine,
const SizedBox(height: 6),
spentLine,
],
),
),
const SizedBox(width: 8),
ringChart(size: 68),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_CardHeader(
icon: widgetConfig.icon,
title: widgetConfig.name,
subtitle: subtitle,
// Percent lives in the ring/pie center; pill only for full-width bars.
trailing: budget.target > 0 && !half && isBar
? _UsedPill(label: '$pct% used')
: null,
),
const SizedBox(height: 14),
switch (widgetConfig.chartStyle) {
HomeWidgetChartStyle.bar => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_BudgetBar(
progress: budget.target <= 0 ? 0 : progress,
fillColor: fillColor,
trackColor: trackColor,
// Solid rounded bar (not a slider thumb).
height: 14,
percentLabel: half && budget.target > 0 ? '$pct%' : null,
),
const SizedBox(height: 10),
if (half)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
capLine,
const SizedBox(height: 4),
spentLine,
],
)
else
Row(
children: [
Expanded(child: capLine),
const SizedBox(width: 8),
Expanded(
child: Align(
alignment: Alignment.centerRight,
child: spentLine,
),
),
],
),
],
),
HomeWidgetChartStyle.pie || HomeWidgetChartStyle.ring => half
// Stack on half cards so amounts never get crushed beside the ring
// (and avoid LayoutBuilder — half rows use IntrinsicHeight).
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
capLine,
const SizedBox(height: 6),
spentLine,
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: ringChart(size: 56),
),
],
)
: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
capLine,
const SizedBox(height: 6),
spentLine,
],
),
),
const SizedBox(width: 8),
ringChart(size: 68),
],
),
},
],
);
}
}
/// Rounded progress bar (no slider thumb).
class _BudgetBar extends StatelessWidget {
const _BudgetBar({
required this.progress,
required this.fillColor,
required this.trackColor,
required this.height,
this.percentLabel,
});
final double progress;
final Color fillColor;
final Color trackColor;
final double height;
final String? percentLabel;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
return SizedBox(
height: height,
child: ClipRRect(
borderRadius: BorderRadius.circular(999),
child: Stack(
fit: StackFit.expand,
children: [
ColoredBox(color: trackColor),
FractionallySizedBox(
widthFactor: progress.clamp(0.0, 1.0),
alignment: Alignment.centerLeft,
child: ColoredBox(color: fillColor),
),
if (percentLabel != null)
Center(
child: Text(
percentLabel!,
style: theme.textTheme.labelSmall?.copyWith(
color: progress >= 0.45
? colors.onPrimary
: colors.onSurface,
fontWeight: FontWeight.w800,
),
),
),
],
),
),
);
}
}
class _BudgetLegendLine extends StatelessWidget {
const _BudgetLegendLine({
required this.bulletColor,
required this.textColor,
required this.text,
this.fontWeight = FontWeight.w600,
});
final Color bulletColor;
final Color textColor;
final String text;
final FontWeight fontWeight;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
// Stretch to the parent width so Expanded+ellipsis can shrink safely
// (half-width ring rows can be very tight).
return Row(
children: [
Container(
width: 7,
height: 7,
decoration: BoxDecoration(
color: bulletColor,
shape: BoxShape.circle,
),
),
const SizedBox(width: 6),
Expanded(
child: Text(
text,
maxLines: 1,
softWrap: false,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.labelMedium?.copyWith(
color: textColor,
fontWeight: fontWeight,
),
),
),
],
);
}
}
class _BudgetChartPainter extends CustomPainter {
_BudgetChartPainter({
required this.progress,
required this.style,
required this.fillColor,
required this.trackColor,
this.percentLabel,
this.labelColor,
this.labelScale = 0.42,
});
final double progress;
final HomeWidgetChartStyle style;
final Color fillColor;
final Color trackColor;
final String? percentLabel;
final Color? labelColor;
final double labelScale;
@override
void paint(Canvas canvas, Size size) {
final center = Offset(size.width / 2, size.height / 2);
final radius = math.min(size.width, size.height) / 2;
final sweep = 2 * math.pi * progress.clamp(0.0, 1.0);
if (style == HomeWidgetChartStyle.pie) {
// Donut-style pizza: thick ring cutout so % stays readable.
final stroke = radius * 0.42;
final r = radius - stroke / 2;
final trackPaint = Paint()
..color = trackColor
..style = PaintingStyle.stroke
..strokeWidth = stroke;
canvas.drawCircle(center, r, trackPaint);
if (progress > 0) {
canvas.drawArc(
Rect.fromCircle(center: center, radius: r),
-math.pi / 2,
sweep,
false,
Paint()
..color = fillColor
..style = PaintingStyle.stroke
..strokeWidth = stroke
..strokeCap = StrokeCap.butt,
);
}
} else {
// Thick ring with rounded caps (reference mock).
final stroke = radius * 0.22;
final r = radius - stroke / 2;
canvas.drawCircle(
center,
r,
Paint()
..color = trackColor
..style = PaintingStyle.stroke
..strokeWidth = stroke
..strokeCap = StrokeCap.round,
);
if (progress > 0) {
canvas.drawArc(
Rect.fromCircle(center: center, radius: r),
-math.pi / 2,
sweep,
false,
Paint()
..color = fillColor
..style = PaintingStyle.stroke
..strokeWidth = stroke
..strokeCap = StrokeCap.round,
);
}
}
final label = percentLabel;
if (label != null && labelColor != null) {
final tp = TextPainter(
text: TextSpan(
text: label,
style: TextStyle(
color: labelColor,
fontSize: radius * labelScale,
fontWeight: FontWeight.w800,
height: 1,
),
),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(
canvas,
center - Offset(tp.width / 2, tp.height / 2),
);
}
}
@override
bool shouldRepaint(covariant _BudgetChartPainter oldDelegate) {
return oldDelegate.progress != progress ||
oldDelegate.style != style ||
oldDelegate.fillColor != fillColor ||
oldDelegate.trackColor != trackColor ||
oldDelegate.percentLabel != percentLabel ||
oldDelegate.labelColor != labelColor ||
oldDelegate.labelScale != labelScale;
}
}
class _Metric extends StatelessWidget {
const _Metric({
required this.label,
required this.value,
required this.color,
});
final String label;
final String value;
final Color color;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
Text(
value,
style: theme.textTheme.titleSmall?.copyWith(
color: color,
fontWeight: FontWeight.w700,
),
),
],
);
}
}
+549
View File
@@ -0,0 +1,549 @@
/// Manage Home filter widgets: display, metrics, add/remove.
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/home_filter_widget.dart';
import '../models/transaction_meta.dart';
import '../providers/bank_provider.dart';
import '../providers/preferences_provider.dart';
import '../providers/tx_meta_provider.dart';
import '../widgets/label_filter_dialog.dart';
Future<void> showHomeWidgetsSheet(BuildContext context) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (context) {
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom,
),
child: const _HomeWidgetsSheet(),
);
},
);
}
Future<HomeFilterWidget?> composeHomeFilterWidget(
BuildContext context, {
TransactionFilterSelection? initialFilter,
HomeFilterWidget? existing,
bool skipFilterDialog = false,
}) async {
// Capture before any modal opens — the caller's element may be rebuilt.
final bank = context.read<BankController>();
final meta = context.read<TxMetaController>();
final navigator = Navigator.of(context);
TransactionFilterSelection? filter = initialFilter ?? existing?.filter;
if (!skipFilterDialog || filter == null) {
filter = await showTransactionFilterDialog(
navigator.context,
available: meta.allLabels,
transactions: bank.transactions,
initial: filter ?? const TransactionFilterSelection(labelIds: {}),
);
if (filter == null || !navigator.mounted) return null;
}
if (!navigator.mounted) return null;
final draft = existing == null
? HomeFilterWidget.fromFilter(name: 'Filter', filter: filter)
: existing.copyWith(
labelIds: filter.labelIds.toList(growable: false),
labelMatch: filter.labelMatch,
flow: filter.flow,
amountRange: filter.amountRange,
query: filter.query,
monthOnly: filter.monthOnly,
);
// Name is edited inside Widget options (no separate rename dialog).
await WidgetsBinding.instance.endOfFrame;
if (!navigator.mounted) return null;
return _promptWidgetMetrics(navigator.context, draft);
}
Future<HomeFilterWidget?> _promptWidgetMetrics(
BuildContext context,
HomeFilterWidget draft,
) {
return showDialog<HomeFilterWidget>(
context: context,
useRootNavigator: true,
builder: (context) => _WidgetOptionsDialog(draft: draft),
);
}
class _WidgetOptionsDialog extends StatefulWidget {
const _WidgetOptionsDialog({required this.draft});
final HomeFilterWidget draft;
@override
State<_WidgetOptionsDialog> createState() => _WidgetOptionsDialogState();
}
class _WidgetOptionsDialogState extends State<_WidgetOptionsDialog> {
late HomeWidgetType _type;
late String _iconId;
late HomeWidgetChartStyle _chartStyle;
late HomeBudgetCapMode _budgetCapMode;
late int _budgetAverageMonths;
late bool _showIn;
late bool _showOut;
late bool _showCount;
late bool _halfWidth;
late final TextEditingController _nameController;
late final TextEditingController _amountController;
@override
void initState() {
super.initState();
final draft = widget.draft;
_type = draft.type;
_iconId = draft.iconId;
_chartStyle = draft.chartStyle;
_budgetCapMode = draft.budgetCapMode;
_budgetAverageMonths = draft.budgetAverageMonths;
_showIn = draft.showAmountIn;
_showOut = draft.showAmountOut;
_showCount = draft.showCount;
_halfWidth = draft.halfWidth;
_nameController = TextEditingController(text: draft.name);
final fixed = draft.budgetFixedAmount;
_amountController = TextEditingController(
text: fixed > 0
? (fixed == fixed.roundToDouble()
? fixed.toStringAsFixed(0)
: fixed.toStringAsFixed(2))
: '',
);
}
@override
void dispose() {
_nameController.dispose();
_amountController.dispose();
super.dispose();
}
void _save() {
final name = _nameController.text.trim();
if (name.isEmpty) return;
if (_type == HomeWidgetType.stats && !_showIn && !_showOut && !_showCount) {
return;
}
var fixed = widget.draft.budgetFixedAmount;
if (_type == HomeWidgetType.budget &&
_budgetCapMode == HomeBudgetCapMode.fixed) {
final parsed = double.tryParse(
_amountController.text.trim().replaceAll(',', '.'),
);
if (parsed == null || parsed <= 0) return;
fixed = parsed;
}
Navigator.of(context).pop(
widget.draft.copyWith(
name: name,
type: _type,
iconId: _iconId,
chartStyle: _chartStyle,
budgetCapMode: _budgetCapMode,
budgetFixedAmount: fixed,
budgetAverageMonths: _budgetAverageMonths,
showAmountIn: _showIn,
showAmountOut: _showOut,
showCount: _showCount,
halfWidth: _halfWidth,
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
title: const Text('Widget options'),
content: SizedBox(
width: double.maxFinite,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _nameController,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(
labelText: 'Name',
border: OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 16),
Text('Type', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
SegmentedButton<HomeWidgetType>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: HomeWidgetType.stats,
label: Text('Stats'),
icon: Icon(Icons.analytics_outlined),
),
ButtonSegment(
value: HomeWidgetType.budget,
label: Text('Budget'),
icon: Icon(Icons.savings_outlined),
),
],
selected: {_type},
onSelectionChanged: (value) {
setState(() => _type = value.first);
},
),
const SizedBox(height: 16),
Text('Icon', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
Wrap(
spacing: 6,
runSpacing: 6,
children: [
for (final entry in HomeWidgetIcons.all)
ChoiceChip(
label: Icon(entry.$2, size: 18),
selected: _iconId == entry.$1,
onSelected: (_) => setState(() => _iconId = entry.$1),
tooltip: entry.$3,
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.all(4),
),
],
),
const SizedBox(height: 12),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Half width'),
subtitle: const Text('Share the row with another widget'),
value: _halfWidth,
onChanged: (value) => setState(() => _halfWidth = value),
),
if (_type == HomeWidgetType.stats) ...[
const Divider(),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Amount in'),
value: _showIn,
onChanged: (value) =>
setState(() => _showIn = value ?? false),
),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Spent'),
value: _showOut,
onChanged: (value) =>
setState(() => _showOut = value ?? false),
),
CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Number of transactions'),
value: _showCount,
onChanged: (value) =>
setState(() => _showCount = value ?? false),
),
] else ...[
const Divider(),
Text('Budget cap', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
SegmentedButton<HomeBudgetCapMode>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: HomeBudgetCapMode.fixed,
label: Text('Fixed'),
),
ButtonSegment(
value: HomeBudgetCapMode.averageMonths,
label: Text('Average'),
),
],
selected: {_budgetCapMode},
onSelectionChanged: (value) {
setState(() => _budgetCapMode = value.first);
},
),
const SizedBox(height: 12),
if (_budgetCapMode == HomeBudgetCapMode.fixed)
TextField(
controller: _amountController,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
decoration: const InputDecoration(
labelText: 'Budget amount',
hintText: 'e.g. 500',
border: OutlineInputBorder(),
isDense: true,
),
)
else
DropdownButtonFormField<int>(
key: ValueKey(_budgetAverageMonths),
initialValue: _budgetAverageMonths,
isExpanded: true,
decoration: const InputDecoration(
labelText: 'Average of last N months',
border: OutlineInputBorder(),
isDense: true,
),
items: [
for (final n in const [1, 2, 3, 6, 12, 24])
DropdownMenuItem(
value: n,
child: Text('$n months'),
),
],
onChanged: (value) {
if (value == null) return;
setState(() => _budgetAverageMonths = value);
},
),
const SizedBox(height: 16),
Text('Chart', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: [
for (final entry in const [
(HomeWidgetChartStyle.bar, Icons.linear_scale, 'Bar'),
(
HomeWidgetChartStyle.pie,
Icons.pie_chart_outline,
'Pie'
),
(HomeWidgetChartStyle.ring, Icons.donut_large, 'Ring'),
])
ChoiceChip(
avatar: Icon(entry.$2, size: 18),
label: Text(entry.$3),
selected: _chartStyle == entry.$1,
onSelected: (_) =>
setState(() => _chartStyle = entry.$1),
),
],
),
const SizedBox(height: 8),
Text(
'Progress uses this month’s net (|in − out|) for the '
'filter toward the cap.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _save,
child: const Text('Save'),
),
],
);
}
}
class _HomeWidgetsSheet extends StatelessWidget {
const _HomeWidgetsSheet();
@override
Widget build(BuildContext context) {
final prefs = context.watch<PreferencesController>();
final theme = Theme.of(context);
final widgets = prefs.homeFilterWidgets;
return SafeArea(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.72,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Home layout', style: theme.textTheme.titleLarge),
const SizedBox(height: 4),
Text(
'Choose which built-in sections and filter widgets appear '
'on Home. Check Display to show an item.',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
child: Column(
children: [
CheckboxListTile(
value: prefs.homeBuiltInSections.showTransactions,
onChanged: (value) {
if (value == null) return;
prefs.setHomeShowTransactions(value);
},
title: const Text('Transactions'),
subtitle: const Text('Total transaction count'),
controlAffinity: ListTileControlAffinity.leading,
),
CheckboxListTile(
value: prefs.homeBuiltInSections.showCategorized,
onChanged: (value) {
if (value == null) return;
prefs.setHomeShowCategorized(value);
},
title: const Text('Categorized'),
subtitle: const Text('Labeled transaction count'),
controlAffinity: ListTileControlAffinity.leading,
),
CheckboxListTile(
value: prefs.homeBuiltInSections.showRecent,
onChanged: (value) {
if (value == null) return;
prefs.setHomeShowRecent(value);
},
title: const Text('Recent transactions'),
subtitle: const Text('Latest activity list'),
controlAffinity: ListTileControlAffinity.leading,
),
],
),
),
const Divider(height: 1),
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: OutlinedButton.icon(
onPressed: () async {
final preferences = context.read<PreferencesController>();
final created = await composeHomeFilterWidget(context);
if (created == null) return;
await preferences.addHomeFilterWidget(created);
},
icon: const Icon(Icons.add),
label: const Text('Add filter widget'),
),
),
const Divider(height: 1),
Expanded(
child: widgets.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
'No filter widgets yet. Add one here, or save a '
'filter from Transactions.',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
)
: ListView.separated(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 24),
itemCount: widgets.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final widgetItem = widgets[index];
return CheckboxListTile(
value: widgetItem.display,
onChanged: (value) {
if (value == null) return;
prefs.setHomeFilterWidgetDisplay(
widgetItem.id,
value,
);
},
secondary: PopupMenuButton<String>(
tooltip: 'Widget actions',
onSelected: (value) async {
if (value == 'edit') {
final preferences =
context.read<PreferencesController>();
final updated =
await composeHomeFilterWidget(
context,
existing: widgetItem,
);
if (updated == null) return;
await preferences
.updateHomeFilterWidget(updated);
} else if (value == 'delete') {
await prefs
.removeHomeFilterWidget(widgetItem.id);
}
},
itemBuilder: (context) => const [
PopupMenuItem(
value: 'edit',
child: Text('Edit'),
),
PopupMenuItem(
value: 'delete',
child: Text('Delete'),
),
],
),
title: Text(widgetItem.name),
subtitle: Text(
'${_subtitle(widgetItem)}\n'
'Display on Home',
),
isThreeLine: true,
controlAffinity: ListTileControlAffinity.leading,
);
},
),
),
],
),
),
);
}
static String _subtitle(HomeFilterWidget w) {
final parts = <String>[
w.type == HomeWidgetType.budget ? 'Budget' : 'Stats',
if (w.type == HomeWidgetType.budget)
w.budgetCapMode == HomeBudgetCapMode.fixed
? 'Fixed'
: 'Avg ${w.budgetAverageMonths}mo',
if (w.type == HomeWidgetType.budget) w.chartStyle.name,
if (w.monthOnly) 'This month',
if (w.flow != TxFlowFilter.all) w.flow.name,
if (w.labelIds.isNotEmpty) '${w.labelIds.length} labels',
if (w.query.trim().isNotEmpty) '“${w.query.trim()}”',
if (w.type == HomeWidgetType.stats && w.showAmountIn) 'In',
if (w.type == HomeWidgetType.stats && w.showAmountOut) 'Spent',
if (w.type == HomeWidgetType.stats && w.showCount) 'Count',
if (w.halfWidth) 'Half',
];
return parts.join(' · ');
}
}
+152 -23
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;
@@ -446,6 +451,8 @@ class _SimpleLabelFilterDialogState extends State<_SimpleLabelFilterDialog> {
onToggle: _toggle, onToggle: _toggle,
allowMove: widget.allowMove, allowMove: widget.allowMove,
shrinkWrap: true, shrinkWrap: true,
parentOf: meta.parentIdOf,
expandAll: needle.isNotEmpty,
), ),
], ],
), ),
@@ -495,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;
@@ -508,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);
@@ -591,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(),
@@ -838,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: () {
@@ -857,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),
@@ -868,6 +902,8 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
onToggle: _toggle, onToggle: _toggle,
allowMove: false, allowMove: false,
shrinkWrap: true, shrinkWrap: true,
parentOf: meta.parentIdOf,
expandAll: needle.isNotEmpty,
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
], ],
@@ -914,14 +950,16 @@ List<LabelTreeEntry> _filterLabelEntries({
]; ];
} }
class _LabelChecklist extends StatelessWidget { class _LabelChecklist extends StatefulWidget {
const _LabelChecklist({ const _LabelChecklist({
required this.entries, required this.entries,
required this.showUncategorized, required this.showUncategorized,
required this.selected, required this.selected,
required this.onToggle, required this.onToggle,
required this.allowMove, required this.allowMove,
required this.parentOf,
this.shrinkWrap = false, this.shrinkWrap = false,
this.expandAll = false,
}); });
final List<LabelTreeEntry> entries; final List<LabelTreeEntry> entries;
@@ -929,13 +967,62 @@ class _LabelChecklist extends StatelessWidget {
final Set<String> selected; final Set<String> selected;
final void Function(String id, bool selected) onToggle; final void Function(String id, bool selected) onToggle;
final bool allowMove; final bool allowMove;
final String? Function(String id) parentOf;
final bool shrinkWrap; final bool shrinkWrap;
final bool expandAll;
@override
State<_LabelChecklist> createState() => _LabelChecklistState();
}
class _LabelChecklistState extends State<_LabelChecklist> {
final Set<String> _expanded = {};
@override
void didUpdateWidget(covariant _LabelChecklist oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.expandAll && !oldWidget.expandAll) {
_expanded
..clear()
..addAll({
for (final entry in widget.entries)
if (_hasChildren(entry.label.id)) entry.label.id,
});
}
}
bool _hasChildren(String id) {
for (final entry in widget.entries) {
if (widget.parentOf(entry.label.id) == id) return true;
}
return false;
}
bool _isVisible(String id) {
if (widget.expandAll) return true;
var parent = widget.parentOf(id);
while (parent != null) {
if (!_expanded.contains(parent)) return false;
parent = widget.parentOf(parent);
}
return true;
}
void _toggleExpanded(String id) {
setState(() {
if (_expanded.contains(id)) {
_expanded.remove(id);
} else {
_expanded.add(id);
}
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
if (entries.isEmpty && !showUncategorized) { if (widget.entries.isEmpty && !widget.showUncategorized) {
return DecoratedBox( return DecoratedBox(
decoration: BoxDecoration( decoration: BoxDecoration(
color: colors.surfaceContainerHighest, color: colors.surfaceContainerHighest,
@@ -958,6 +1045,11 @@ class _LabelChecklist extends StatelessWidget {
); );
} }
final visibleEntries = [
for (final entry in widget.entries)
if (_isVisible(entry.label.id)) entry,
];
return DecoratedBox( return DecoratedBox(
decoration: BoxDecoration( decoration: BoxDecoration(
color: colors.surfaceContainerHighest, color: colors.surfaceContainerHighest,
@@ -969,12 +1061,13 @@ class _LabelChecklist extends StatelessWidget {
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: ListView.separated( child: ListView.separated(
shrinkWrap: shrinkWrap, shrinkWrap: widget.shrinkWrap,
physics: shrinkWrap physics: widget.shrinkWrap
? const NeverScrollableScrollPhysics() ? const NeverScrollableScrollPhysics()
: null, : null,
padding: const EdgeInsets.symmetric(vertical: 4), padding: const EdgeInsets.symmetric(vertical: 4),
itemCount: entries.length + (showUncategorized ? 1 : 0), itemCount:
visibleEntries.length + (widget.showUncategorized ? 1 : 0),
separatorBuilder: (_, _) => Divider( separatorBuilder: (_, _) => Divider(
height: 1, height: 1,
thickness: 1, thickness: 1,
@@ -982,28 +1075,35 @@ class _LabelChecklist extends StatelessWidget {
color: colors.outlineVariant.withValues(alpha: 0.45), color: colors.outlineVariant.withValues(alpha: 0.45),
), ),
itemBuilder: (context, index) { itemBuilder: (context, index) {
if (showUncategorized && index == 0) { if (widget.showUncategorized && index == 0) {
return _FilterRow( return _FilterRow(
depth: 0, depth: 0,
icon: kUncategorizedFilterLabel.icon, icon: kUncategorizedFilterLabel.icon,
color: kUncategorizedFilterLabel.color, color: kUncategorizedFilterLabel.color,
name: kUncategorizedFilterLabel.name, name: kUncategorizedFilterLabel.name,
checked: selected.contains(kUncategorizedFilterId), checked: widget.selected.contains(kUncategorizedFilterId),
onToggle: (value) => onToggle: (value) =>
onToggle(kUncategorizedFilterId, value), widget.onToggle(kUncategorizedFilterId, value),
); );
} }
final entry = final entry = visibleEntries[
entries[showUncategorized ? index - 1 : index]; widget.showUncategorized ? index - 1 : index];
final label = entry.label; final label = entry.label;
final hasChildren = _hasChildren(label.id);
final expanded =
widget.expandAll || _expanded.contains(label.id);
return _FilterRow( return _FilterRow(
depth: entry.depth, depth: entry.depth,
icon: label.icon, icon: label.icon,
color: label.color, color: label.color,
name: label.name, name: label.name,
checked: selected.contains(label.id), checked: widget.selected.contains(label.id),
onToggle: (value) => onToggle(label.id, value), onToggle: (value) => widget.onToggle(label.id, value),
onLongPress: allowMove hasChildren: hasChildren,
expanded: expanded,
onExpandToggle:
hasChildren ? () => _toggleExpanded(label.id) : null,
onLongPress: widget.allowMove
? () async { ? () async {
await showMoveLabelDialog(context, label: label); await showMoveLabelDialog(context, label: label);
} }
@@ -1134,6 +1234,9 @@ class _FilterRow extends StatelessWidget {
required this.checked, required this.checked,
required this.onToggle, required this.onToggle,
this.onLongPress, this.onLongPress,
this.hasChildren = false,
this.expanded = false,
this.onExpandToggle,
}); });
final int depth; final int depth;
@@ -1143,26 +1246,52 @@ class _FilterRow extends StatelessWidget {
final bool checked; final bool checked;
final ValueChanged<bool> onToggle; final ValueChanged<bool> onToggle;
final VoidCallback? onLongPress; final VoidCallback? onLongPress;
final bool hasChildren;
final bool expanded;
final VoidCallback? onExpandToggle;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
return InkWell( return InkWell(
onTap: () => onToggle(!checked), onTap: () {
if (hasChildren && onExpandToggle != null) {
onExpandToggle!();
} else {
onToggle(!checked);
}
},
onLongPress: onLongPress, onLongPress: onLongPress,
child: Padding( child: Padding(
padding: EdgeInsets.fromLTRB(8 + depth * 16.0, 2, 4, 2), padding: EdgeInsets.fromLTRB(8 + depth * 16.0, 2, 4, 2),
child: Row( child: Row(
children: [ children: [
if (depth > 0) ...[ SizedBox(
Icon( width: 28,
Icons.subdirectory_arrow_right, height: 32,
size: 14, child: hasChildren
color: colors.onSurfaceVariant, ? IconButton(
), tooltip: expanded ? 'Collapse' : 'Expand',
const SizedBox(width: 4), onPressed: onExpandToggle,
], padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
icon: Icon(
expanded
? Icons.expand_more
: Icons.chevron_right,
size: 20,
color: colors.onSurfaceVariant,
),
)
: depth > 0
? Icon(
Icons.subdirectory_arrow_right,
size: 14,
color: colors.onSurfaceVariant,
)
: null,
),
Icon(icon, size: 18, color: color), Icon(icon, size: 18, color: color),
const SizedBox(width: 10), const SizedBox(width: 10),
Expanded( Expanded(
+491
View File
@@ -0,0 +1,491 @@
/// Manage Overview favourites: display toggles, rename, delete, save current.
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/overview_favourite.dart';
import '../models/transaction_meta.dart';
import '../providers/preferences_provider.dart';
import '../providers/tx_meta_provider.dart';
import 'label_filter_dialog.dart';
Future<void> showOverviewFavouritesSheet(
BuildContext context, {
required OverviewFavourite? Function() currentFilterSnapshot,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (context) {
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom,
),
child: _OverviewFavouritesSheet(
currentFilterSnapshot: currentFilterSnapshot,
),
);
},
);
}
Future<String?> promptFavouriteName(
BuildContext context, {
String initial = '',
String title = 'Name this favourite',
}) {
return showDialog<String>(
context: context,
useRootNavigator: true,
builder: (dialogContext) {
return _FavouriteNameDialog(
initial: initial,
title: title,
);
},
);
}
/// Edit an existing favourite (name, metric, period, labels, display).
Future<void> showEditOverviewFavouriteSheet(
BuildContext context, {
required OverviewFavourite favourite,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (context) {
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom,
),
child: _EditOverviewFavouriteSheet(favourite: favourite),
);
},
);
}
class _FavouriteNameDialog extends StatefulWidget {
const _FavouriteNameDialog({
required this.initial,
required this.title,
});
final String initial;
final String title;
@override
State<_FavouriteNameDialog> createState() => _FavouriteNameDialogState();
}
class _FavouriteNameDialogState extends State<_FavouriteNameDialog> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.initial);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _submit() {
final name = _controller.text.trim();
if (name.isEmpty) return;
Navigator.of(context).pop(name);
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(widget.title),
content: TextField(
controller: _controller,
autofocus: true,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(
labelText: 'Name',
hintText: 'e.g. Groceries this year',
),
onSubmitted: (_) => _submit(),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _submit,
child: const Text('Save'),
),
],
);
}
}
class _OverviewFavouritesSheet extends StatelessWidget {
const _OverviewFavouritesSheet({required this.currentFilterSnapshot});
final OverviewFavourite? Function() currentFilterSnapshot;
Future<void> _saveCurrent(BuildContext context) async {
final prefs = context.read<PreferencesController>();
final snap = currentFilterSnapshot();
if (snap == null) return;
final name = await promptFavouriteName(context);
if (name == null || !context.mounted) return;
// Let the dialog route + IME finish tearing down before notifying
// dependents (avoids wrong-build-scope / _dependents asserts).
await Future<void>.delayed(Duration.zero);
if (!context.mounted) return;
await prefs.addOverviewFavourite(snap.copyWith(name: name));
if (!context.mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
messenger?.showSnackBar(SnackBar(content: Text('Saved “$name”')));
}
@override
Widget build(BuildContext context) {
final prefs = context.watch<PreferencesController>();
final theme = Theme.of(context);
final favourites = prefs.overviewFavourites;
return SafeArea(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.72,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Favourites', style: theme.textTheme.titleLarge),
const SizedBox(height: 4),
Text(
'Check Display for each favourite you want on the Favourites '
'view — all checked ones show as charts. Save as many filters '
'as you like.',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: OutlinedButton.icon(
onPressed: () => _saveCurrent(context),
icon: const Icon(Icons.star_outline),
label: const Text('Save current filter'),
),
),
const Divider(height: 1),
Expanded(
child: favourites.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
'No favourites yet. Set up Flow or Labels on Overview, '
'then save the current filter.',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
)
: ListView.separated(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 24),
itemCount: favourites.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final fav = favourites[index];
return CheckboxListTile(
value: fav.display,
onChanged: (value) {
if (value == null) return;
prefs.setOverviewFavouriteDisplay(fav.id, value);
},
secondary: IconButton(
tooltip: 'Delete',
onPressed: () =>
prefs.removeOverviewFavourite(fav.id),
icon: const Icon(Icons.delete_outline),
),
title: Text(fav.name),
subtitle: Text(
'${_subtitle(fav)}\n'
'Display on Favourites view',
),
isThreeLine: true,
controlAffinity: ListTileControlAffinity.leading,
);
},
),
),
],
),
),
);
}
static String _subtitle(OverviewFavourite fav) {
final metric =
fav.metric == OverviewMetricMode.flow ? 'Flow' : 'Labels';
final period =
fav.period == OverviewPeriodMode.monthly ? 'Month' : 'Year';
if (fav.metric == OverviewMetricMode.flow) {
return '$metric · $period';
}
final flow = switch (fav.flow) {
TxFlowFilter.all => 'All',
TxFlowFilter.income => 'Income',
TxFlowFilter.expense => 'Expenses',
};
final labels = fav.labelIds.isEmpty
? 'All labels'
: '${fav.labelIds.length} labels';
return '$metric · $period · $flow · $labels';
}
}
class _EditOverviewFavouriteSheet extends StatefulWidget {
const _EditOverviewFavouriteSheet({required this.favourite});
final OverviewFavourite favourite;
@override
State<_EditOverviewFavouriteSheet> createState() =>
_EditOverviewFavouriteSheetState();
}
class _EditOverviewFavouriteSheetState
extends State<_EditOverviewFavouriteSheet> {
late OverviewFavourite _draft;
late final TextEditingController _nameController;
static const _segmentStyle = ButtonStyle(
visualDensity: VisualDensity(horizontal: -2, vertical: -2),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 12)),
minimumSize: WidgetStatePropertyAll(Size(0, 36)),
);
@override
void initState() {
super.initState();
_draft = widget.favourite;
_nameController = TextEditingController(text: _draft.name);
}
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
Future<void> _persist(OverviewFavourite next) async {
setState(() => _draft = next);
await context.read<PreferencesController>().updateOverviewFavourite(next);
}
Future<void> _editLabels() async {
final meta = context.read<TxMetaController>();
final available = meta.allLabels;
final initial = <String>{
if (_draft.labelIds.isEmpty)
...available.map((l) => l.id)
else ...[
for (final id in _draft.labelIds)
if (id == kUncategorizedFilterId ||
available.any((l) => l.id == id))
id,
],
};
final result = await showLabelFilterDialog(
context,
available: available,
initiallySelected: initial,
title: 'Labels on chart',
subtitle: 'Choose which labels appear on this favourite.',
allowMove: true,
includeUncategorized: true,
includeFlow: true,
initialFlow: _draft.flow,
includeBarStyle: true,
initialBarStyle: _draft.barStyle,
includeInvertChart: true,
initialInvertChart: _draft.invertExpensePerspective,
);
if (result == null || !mounted) return;
final allIds = available.map((l) => l.id).toSet();
final hasUncategorized =
result.labelIds.contains(kUncategorizedFilterId);
final realIds = result.labelIds
.where((id) => id != kUncategorizedFilterId)
.toSet();
final allRealSelected =
realIds.length == allIds.length && realIds.containsAll(allIds);
final labelIds = !hasUncategorized &&
(realIds.isEmpty || allRealSelected)
? const <String>[]
: result.labelIds.toList(growable: false);
await _persist(
_draft.copyWith(
metric: OverviewMetricMode.labels,
labelIds: labelIds,
flow: result.flow,
barStyle: result.barStyle,
invertExpensePerspective:
result.flow == TxFlowFilter.all && result.invertExpensePerspective,
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final prefs = context.read<PreferencesController>();
return SafeArea(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
),
child: ListView(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 24),
children: [
Text('Edit favourite', style: theme.textTheme.titleLarge),
const SizedBox(height: 16),
TextField(
controller: _nameController,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(
labelText: 'Name',
),
textInputAction: TextInputAction.done,
onEditingComplete: () {
FocusScope.of(context).unfocus();
},
),
const SizedBox(height: 20),
Text('Chart type', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
SegmentedButton<OverviewMetricMode>(
showSelectedIcon: false,
style: _segmentStyle,
segments: const [
ButtonSegment(
value: OverviewMetricMode.flow,
label: Text('Flow'),
),
ButtonSegment(
value: OverviewMetricMode.labels,
label: Text('Labels'),
),
],
selected: {_draft.metric},
onSelectionChanged: (selection) {
_persist(_draft.copyWith(metric: selection.first));
},
),
const SizedBox(height: 16),
Text('Period', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
SegmentedButton<OverviewPeriodMode>(
showSelectedIcon: false,
style: _segmentStyle,
segments: const [
ButtonSegment(
value: OverviewPeriodMode.monthly,
label: Text('Month'),
),
ButtonSegment(
value: OverviewPeriodMode.yearly,
label: Text('Year'),
),
],
selected: {_draft.period},
onSelectionChanged: (selection) {
_persist(_draft.copyWith(period: selection.first));
},
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Display on Favourites view'),
value: _draft.display,
onChanged: (value) {
_persist(_draft.copyWith(display: value));
},
),
if (_draft.metric == OverviewMetricMode.labels) ...[
const SizedBox(height: 8),
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.filter_list),
title: const Text('Label filter'),
subtitle: Text(
_draft.labelIds.isEmpty
? 'All labels · ${_draft.flow.name}'
: '${_draft.labelIds.length} labels · ${_draft.flow.name}',
),
trailing: const Icon(Icons.chevron_right),
onTap: _editLabels,
),
],
const SizedBox(height: 16),
FilledButton(
onPressed: () async {
final name = _nameController.text.trim();
final next =
name.isEmpty ? _draft : _draft.copyWith(name: name);
await prefs.updateOverviewFavourite(next);
if (!context.mounted) return;
Navigator.of(context).pop();
},
child: const Text('Done'),
),
const SizedBox(height: 8),
TextButton.icon(
onPressed: () async {
await prefs.removeOverviewFavourite(_draft.id);
if (!context.mounted) return;
Navigator.of(context).pop();
},
icon: Icon(
Icons.delete_outline,
color: theme.colorScheme.error,
),
label: Text(
'Delete favourite',
style: TextStyle(color: theme.colorScheme.error),
),
),
],
),
),
);
}
}
+4
View File
@@ -8,6 +8,10 @@ final RouteObserver<ModalRoute<void>> appRouteObserver =
RouteObserver<ModalRoute<void>>(); RouteObserver<ModalRoute<void>>();
/// Builds via [builder] only when this route is not covered by a pushed page. /// Builds via [builder] only when this route is not covered by a pushed page.
///
/// Only [PageRoute]s count as covering (via [RouteAware]). Modal bottom sheets
/// and dialogs must not tear down the subtree — async flows started from Home
/// (e.g. compose widget → name → options) need a mounted context between steps.
class SkipBuildWhenCovered extends StatefulWidget { class SkipBuildWhenCovered extends StatefulWidget {
const SkipBuildWhenCovered({ const SkipBuildWhenCovered({
super.key, super.key,
@@ -0,0 +1,110 @@
/// PocketBase migration: Overview chart favourites.
///
/// Apply on the server (from /opt/pocketbase or wherever the binary lives):
///
/// 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
///
/// Depends on usersapp (same owner rules as labels / recurring_templates).
migrate((app) => {
const users = app.findCollectionByNameOrId("usersapp");
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 overviewFavourites = new Collection({
type: "base",
name: "overview_favourites",
...ownerRules,
fields: [
{
type: "relation",
name: "user",
required: true,
collectionId: users.id,
cascadeDelete: true,
maxSelect: 1,
},
{
// App-side OverviewFavourite.id
type: "text",
name: "client_id",
required: true,
min: 1,
max: 120,
},
{
type: "text",
name: "name",
required: true,
min: 1,
max: 200,
},
{
// Show on Favourites overview view
type: "bool",
name: "display",
required: false,
},
{
// "flow" | "labels"
type: "text",
name: "metric",
required: true,
min: 1,
max: 32,
},
{
// "monthly" | "yearly"
type: "text",
name: "period",
required: true,
min: 1,
max: 32,
},
{
// Label client_ids included on Labels chart ([] = all)
type: "json",
name: "label_ids",
required: false,
},
{
// "all" | "income" | "expense"
type: "text",
name: "flow",
required: true,
min: 1,
max: 32,
},
{
// "parallel" | "stacked"
type: "text",
name: "bar_style",
required: true,
min: 1,
max: 32,
},
{
type: "bool",
name: "invert_expense_perspective",
required: false,
},
],
indexes: [
"CREATE UNIQUE INDEX idx_overview_favourites_user_client ON overview_favourites (user, client_id)",
],
});
app.save(overviewFavourites);
}, (app) => {
try {
const col = app.findCollectionByNameOrId("overview_favourites");
app.delete(col);
} catch (_) {}
});
@@ -0,0 +1,154 @@
/// PocketBase migration: Home filter widgets.
///
/// 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
///
/// Depends on usersapp (same owner rules as overview_favourites).
migrate((app) => {
const users = app.findCollectionByNameOrId("usersapp");
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 homeFilterWidgets = new Collection({
type: "base",
name: "home_filter_widgets",
...ownerRules,
fields: [
{
type: "relation",
name: "user",
required: true,
collectionId: users.id,
cascadeDelete: true,
maxSelect: 1,
},
{
type: "text",
name: "client_id",
required: true,
min: 1,
max: 120,
},
{
type: "text",
name: "name",
required: true,
min: 1,
max: 200,
},
{
type: "bool",
name: "display",
required: false,
},
{
type: "number",
name: "sort_order",
required: false,
onlyInt: true,
},
{
type: "bool",
name: "half_width",
required: false,
},
{
type: "text",
name: "widget_type",
required: false,
max: 40,
},
{
type: "text",
name: "icon_id",
required: false,
max: 40,
},
{
type: "text",
name: "chart_style",
required: false,
max: 40,
},
{
type: "text",
name: "budget_cap_mode",
required: false,
max: 40,
},
{
type: "number",
name: "budget_fixed_amount",
required: false,
},
{
type: "number",
name: "budget_average_months",
required: false,
onlyInt: true,
},
{
type: "json",
name: "label_ids",
required: false,
},
{
type: "text",
name: "flow",
required: true,
min: 1,
max: 32,
},
{
type: "json",
name: "amount_range",
required: false,
},
{
type: "text",
name: "query",
required: false,
max: 400,
},
{
type: "bool",
name: "month_only",
required: false,
},
{
type: "bool",
name: "show_amount_in",
required: false,
},
{
type: "bool",
name: "show_amount_out",
required: false,
},
{
type: "bool",
name: "show_count",
required: false,
},
],
indexes: [
"CREATE UNIQUE INDEX idx_home_filter_widgets_user_client ON home_filter_widgets (user, client_id)",
],
});
app.save(homeFilterWidgets);
}, (app) => {
try {
const col = app.findCollectionByNameOrId("home_filter_widgets");
app.delete(col);
} catch (_) {}
});
@@ -0,0 +1,25 @@
/// PocketBase migration: half_width on home_filter_widgets.
///
/// Apply after 1740000004 if that collection already exists without half_width.
/// For new installs, 1740000004 already creates half_width — this is a no-op then.
migrate((app) => {
const col = app.findCollectionByNameOrId("home_filter_widgets");
if (col.fields.getByName("half_width")) return;
// Automigrate-style constructor (plain objects are rejected by fields.add).
col.fields.add(new Field({
type: "bool",
name: "half_width",
required: false,
}));
app.save(col);
}, (app) => {
try {
const col = app.findCollectionByNameOrId("home_filter_widgets");
const field = col.fields.getByName("half_width");
if (field) {
col.fields.removeById(field.id);
app.save(col);
}
} catch (_) {}
});
@@ -0,0 +1,63 @@
/// PocketBase migration: budget / chart / icon fields on home_filter_widgets.
migrate((app) => {
const col = app.findCollectionByNameOrId("home_filter_widgets");
const addIfMissing = (config) => {
if (col.fields.getByName(config.name)) return;
col.fields.add(new Field(config));
};
addIfMissing({
type: "text",
name: "widget_type",
required: false,
max: 40,
});
addIfMissing({
type: "text",
name: "icon_id",
required: false,
max: 40,
});
addIfMissing({
type: "text",
name: "chart_style",
required: false,
max: 40,
});
addIfMissing({
type: "text",
name: "budget_cap_mode",
required: false,
max: 40,
});
addIfMissing({
type: "number",
name: "budget_fixed_amount",
required: false,
});
addIfMissing({
type: "number",
name: "budget_average_months",
required: false,
onlyInt: true,
});
app.save(col);
}, (app) => {
try {
const col = app.findCollectionByNameOrId("home_filter_widgets");
for (const name of [
"widget_type",
"icon_id",
"chart_style",
"budget_cap_mode",
"budget_fixed_amount",
"budget_average_months",
]) {
const field = col.fields.getByName(name);
if (field) col.fields.removeById(field.id);
}
app.save(col);
} catch (_) {}
});
@@ -0,0 +1,67 @@
/// PocketBase migration: per-user app preferences (Home sections + Look ahead).
///
/// 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
///
/// Depends on usersapp.
migrate((app) => {
const users = app.findCollectionByNameOrId("usersapp");
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 appPrefs = new Collection({
type: "base",
name: "app_prefs",
...ownerRules,
fields: [
{
type: "relation",
name: "user",
required: true,
collectionId: users.id,
cascadeDelete: true,
maxSelect: 1,
},
{
type: "bool",
name: "home_show_transactions",
required: false,
},
{
type: "bool",
name: "home_show_categorized",
required: false,
},
{
type: "bool",
name: "home_show_recent",
required: false,
},
{
type: "number",
name: "look_ahead_max_years",
required: false,
onlyInt: true,
},
],
indexes: [
"CREATE UNIQUE INDEX idx_app_prefs_user ON app_prefs (user)",
],
});
app.save(appPrefs);
}, (app) => {
try {
const col = app.findCollectionByNameOrId("app_prefs");
app.delete(col);
} catch (_) {}
});
@@ -0,0 +1,22 @@
/// PocketBase migration: label_match (AND/OR) on home_filter_widgets.
migrate((app) => {
const col = app.findCollectionByNameOrId("home_filter_widgets");
if (col.fields.getByName("label_match")) return;
col.fields.add(new Field({
type: "text",
name: "label_match",
required: false,
max: 16,
}));
app.save(col);
}, (app) => {
try {
const col = app.findCollectionByNameOrId("home_filter_widgets");
const field = col.fields.getByName("label_match");
if (field) {
col.fields.removeById(field.id);
app.save(col);
}
} catch (_) {}
});
@@ -0,0 +1,31 @@
/// PocketBase migration: `is_admin` on usersapp (admin vs normal accounts).
///
/// Admins can create test transactions in the app. Set the flag in Admin UI:
/// Users → pick user → is_admin = true.
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
const users = app.findCollectionByNameOrId("usersapp");
if (users.fields.getByName("is_admin")) return;
users.fields.add(new Field({
type: "bool",
name: "is_admin",
required: false,
}));
app.save(users);
}, (app) => {
try {
const users = app.findCollectionByNameOrId("usersapp");
const field = users.fields.getByName("is_admin");
if (field) {
users.fields.removeById(field.id);
app.save(users);
}
} catch (_) {}
});
@@ -0,0 +1,28 @@
/// PocketBase migration: `is_manual` on transactions (admin test rows).
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
const transactions = app.findCollectionByNameOrId("transactions");
if (transactions.fields.getByName("is_manual")) return;
transactions.fields.add(new Field({
type: "bool",
name: "is_manual",
required: false,
}));
app.save(transactions);
}, (app) => {
try {
const transactions = app.findCollectionByNameOrId("transactions");
const field = transactions.fields.getByName("is_manual");
if (field) {
transactions.fields.removeById(field.id);
app.save(transactions);
}
} catch (_) {}
});
@@ -0,0 +1,83 @@
/// PocketBase migration: `tx_deletes` — synced tombstones for deleted admin
/// test transactions so another device cannot push them back into `transactions`.
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
const users = app.findCollectionByNameOrId("usersapp");
try {
app.findCollectionByNameOrId("tx_deletes");
return;
} catch (_) {}
const ownerRules = {
listRule: "user = @request.auth.id",
viewRule: "user = @request.auth.id",
createRule: "@request.auth.id != '' && user = @request.auth.id",
updateRule: "user = @request.auth.id",
deleteRule: "user = @request.auth.id",
};
const txDeletes = new Collection({
type: "base",
name: "tx_deletes",
...ownerRules,
fields: [
{
type: "relation",
name: "user",
required: true,
collectionId: users.id,
cascadeDelete: true,
maxSelect: 1,
},
{
// Clipped BankTransaction.id
type: "text",
name: "tx_id",
required: true,
min: 1,
max: 2000,
},
{
type: "text",
name: "date",
required: true,
min: 1,
max: 32,
},
{
type: "text",
name: "description",
required: true,
min: 1,
max: 4000,
},
{
type: "number",
name: "amount",
required: true,
},
{
type: "text",
name: "currency",
required: true,
min: 1,
max: 8,
},
],
indexes: [
"CREATE UNIQUE INDEX idx_tx_deletes_user_tx ON tx_deletes (user, tx_id)",
],
});
app.save(txDeletes);
}, (app) => {
try {
app.delete(app.findCollectionByNameOrId("tx_deletes"));
} catch (_) {}
});
@@ -0,0 +1,48 @@
/// PocketBase migration: `updated_at` + `deleted` on overview favourites and
/// home filter widgets for cross-device last-write-wins sync.
///
/// Apply on the server:
///
/// sudo cp this_file /opt/pocketbase/pb_migrations/
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
/// sudo systemctl restart pocketbase
migrate((app) => {
function addSyncFields(collectionName) {
const col = app.findCollectionByNameOrId(collectionName);
let changed = false;
if (!col.fields.getByName("updated_at")) {
col.fields.add(new Field({
type: "number",
name: "updated_at",
required: false,
}));
changed = true;
}
if (!col.fields.getByName("deleted")) {
col.fields.add(new Field({
type: "bool",
name: "deleted",
required: false,
}));
changed = true;
}
if (changed) app.save(col);
}
addSyncFields("overview_favourites");
addSyncFields("home_filter_widgets");
}, (app) => {
function removeSyncFields(collectionName) {
try {
const col = app.findCollectionByNameOrId(collectionName);
const updated = col.fields.getByName("updated_at");
if (updated) col.fields.removeById(updated.id);
const deleted = col.fields.getByName("deleted");
if (deleted) col.fields.removeById(deleted.id);
app.save(col);
} catch (_) {}
}
removeSyncFields("overview_favourites");
removeSyncFields("home_filter_widgets");
});
+64
View File
@@ -33,6 +33,22 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.4" version: "1.0.4"
archive:
dependency: transitive
description:
name: archive
sha256: ace891da0862b0e4cabbb064ee3fd87b2728b898949fdb366d83fe98342c9f19
url: "https://pub.dev"
source: hosted
version: "4.2.0"
args:
dependency: transitive
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
url: "https://pub.dev"
source: hosted
version: "2.7.0"
async: async:
dependency: transitive dependency: transitive
description: description:
@@ -57,6 +73,22 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.1" version: "1.4.1"
checked_yaml:
dependency: transitive
description:
name: checked_yaml
sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
url: "https://pub.dev"
source: hosted
version: "2.0.4"
cli_util:
dependency: transitive
description:
name: cli_util
sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c
url: "https://pub.dev"
source: hosted
version: "0.4.2"
clock: clock:
dependency: transitive dependency: transitive
description: description:
@@ -150,6 +182,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.0.1" version: "6.0.1"
flutter_launcher_icons:
dependency: "direct dev"
description:
name: flutter_launcher_icons
sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7"
url: "https://pub.dev"
source: hosted
version: "0.14.4"
flutter_lints: flutter_lints:
dependency: "direct dev" dependency: "direct dev"
description: description:
@@ -200,6 +240,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.1.2" version: "4.1.2"
image:
dependency: transitive
description:
name: image
sha256: "1976370a4df3091bb0f72409c187ad1f9132a818bc6b95ca59c0bae1c75c688e"
url: "https://pub.dev"
source: hosted
version: "4.9.2"
json_annotation: json_annotation:
dependency: transitive dependency: transitive
description: description:
@@ -328,6 +376,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.25.1" version: "0.25.1"
posix:
dependency: transitive
description:
name: posix
sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e
url: "https://pub.dev"
source: hosted
version: "6.5.2"
provider: provider:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -525,6 +581,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.0" version: "1.1.0"
yaml:
dependency: transitive
description:
name: yaml
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
url: "https://pub.dev"
source: hosted
version: "3.1.4"
sdks: sdks:
dart: ">=3.13.2 <4.0.0" dart: ">=3.13.2 <4.0.0"
flutter: ">=3.44.0" flutter: ">=3.44.0"
+10
View File
@@ -53,6 +53,15 @@ dev_dependencies:
# package. See that file for information about deactivating specific lint # package. See that file for information about deactivating specific lint
# rules and activating additional ones. # rules and activating additional ones.
flutter_lints: ^6.0.0 flutter_lints: ^6.0.0
flutter_launcher_icons: ^0.14.4
flutter_launcher_icons:
android: true
ios: false
image_path: assets/branding/app_icon.png
adaptive_icon_background: "#1A1C1B"
adaptive_icon_foreground: assets/branding/app_icon_foreground.png
min_sdk_android: 21
# For information on the generic Dart part of this file, see the # For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec # following page: https://dart.dev/tools/pub/pubspec
@@ -68,6 +77,7 @@ flutter:
assets: assets:
- .env - .env
- .env.example - .env.example
- assets/branding/app_icon.png
# An image asset can refer to one or more resolution-specific "variants", see # An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/to/resolution-aware-images # https://flutter.dev/to/resolution-aware-images
+77
View File
@@ -0,0 +1,77 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:myapp/models/home_filter_widget.dart';
import 'package:myapp/models/transaction_meta.dart';
import 'package:myapp/widgets/label_filter_dialog.dart';
void main() {
test('HomeFilterWidget JSON round-trips', () {
final widget = HomeFilterWidget.fromFilter(
name: 'Groceries out',
filter: const TransactionFilterSelection(
labelIds: {'groceries'},
flow: TxFlowFilter.expense,
monthOnly: true,
),
);
final restored = HomeFilterWidget.fromJson(widget.toJson());
expect(restored.name, 'Groceries out');
expect(restored.flow, TxFlowFilter.expense);
expect(restored.monthOnly, isTrue);
expect(restored.labelIds, ['groceries']);
expect(restored.labelMatch, LabelMatchMode.and);
expect(restored.showAmountOut, isTrue);
expect(restored.showAmountIn, isFalse);
expect(restored.showCount, isTrue);
expect(restored.halfWidth, isFalse);
expect(restored.type, HomeWidgetType.stats);
final withOr = widget.copyWith(labelMatch: LabelMatchMode.or);
expect(
HomeFilterWidget.fromJson(withOr.toJson()).labelMatch,
LabelMatchMode.or,
);
final budget = widget.copyWith(
halfWidth: true,
type: HomeWidgetType.budget,
iconId: 'cart',
chartStyle: HomeWidgetChartStyle.ring,
budgetCapMode: HomeBudgetCapMode.averageMonths,
budgetAverageMonths: 6,
budgetFixedAmount: 250,
);
final budgetRestored = HomeFilterWidget.fromJson(budget.toJson());
expect(budgetRestored.halfWidth, isTrue);
expect(budgetRestored.type, HomeWidgetType.budget);
expect(budgetRestored.iconId, 'cart');
expect(budgetRestored.chartStyle, HomeWidgetChartStyle.ring);
expect(budgetRestored.budgetCapMode, HomeBudgetCapMode.averageMonths);
expect(budgetRestored.budgetAverageMonths, 6);
expect(budgetRestored.budgetFixedAmount, 250);
});
test('mergeHomeFilterWidgets unions by id with local wins', () {
const local = HomeFilterWidget(
id: 'hw_1',
name: 'Local',
display: true,
showAmountIn: false,
);
const remote = HomeFilterWidget(
id: 'hw_1',
name: 'Remote',
display: false,
);
const remoteOnly = HomeFilterWidget(
id: 'hw_2',
name: 'Other',
sortOrder: 1,
);
final merged = mergeHomeFilterWidgets([local], [remote, remoteOnly]);
expect(merged.length, 2);
expect(merged.firstWhere((w) => w.id == 'hw_1').name, 'Local');
expect(merged.firstWhere((w) => w.id == 'hw_1').display, isTrue);
});
}
+80
View File
@@ -0,0 +1,80 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:myapp/models/overview_favourite.dart';
import 'package:myapp/models/transaction_meta.dart';
import 'package:myapp/widgets/label_filter_dialog.dart';
void main() {
test('OverviewFavourite JSON round-trips', () {
const fav = OverviewFavourite(
id: 'fav_1',
name: 'Groceries',
display: true,
metric: OverviewMetricMode.labels,
period: OverviewPeriodMode.monthly,
labelIds: ['groceries', 'custom_ah'],
flow: TxFlowFilter.expense,
barStyle: LabelChartBarStyle.stacked,
invertExpensePerspective: false,
updatedAt: 100,
deleted: false,
);
final restored = OverviewFavourite.fromJson(fav.toJson());
expect(restored.id, fav.id);
expect(restored.name, fav.name);
expect(restored.display, isTrue);
expect(restored.metric, OverviewMetricMode.labels);
expect(restored.period, OverviewPeriodMode.monthly);
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 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 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, localOlder],
[remoteConflictOlder, remoteOnly, remoteConflictNewer],
);
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');
});
}
+36
View File
@@ -97,4 +97,40 @@ void main() {
])); ]));
expect(merged.first.date, '2024-01-03'); expect(merged.first.date, '2024-01-03');
}); });
test('bank API merge keeps cloud-only txs outside the API window', () {
const cloudOnly = BankTransaction(
date: '2020-06-01',
description: 'Old cloud tx',
amount: -20,
currency: 'EUR',
pending: false,
);
const recentShared = BankTransaction(
date: '2026-09-01',
description: 'Recent Shop',
amount: -5,
currency: 'EUR',
pending: false,
);
const apiOnly = BankTransaction(
date: '2026-09-02',
description: 'New API tx',
amount: -3,
currency: 'EUR',
pending: false,
);
// Same order as BankController._loadLinkedData: API first, then existing.
final afterRefresh = mergeBankTransactionLists(
[recentShared, apiOnly],
[cloudOnly, recentShared],
);
expect(afterRefresh.length, 3);
expect(
afterRefresh.map((t) => t.description),
containsAll(['Old cloud tx', 'Recent Shop', 'New API tx']),
);
});
} }