Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00ab05eefc | ||
|
|
f8e293f823 | ||
|
|
c4f0ca785e | ||
|
|
6cc0de8945 | ||
|
|
b4d367f056 | ||
|
|
c3d2680ca7 | ||
|
|
e7617a2d98 | ||
|
|
3187499385 | ||
|
|
4dde907f52 | ||
|
|
55a13ee650 |
@@ -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
|
||||
|
||||
- Splash screen that fades into the main shell
|
||||
- Bottom navigation: Home, Search, Profile, Settings
|
||||
- `ListView.builder` catalog with rounded, shadowed cards
|
||||
- Detail screen with a matching `Hero` animation
|
||||
- Light / dark / system theme, persisted with `shared_preferences`
|
||||
- Add-item form with validation
|
||||
- Mock catalog plus an `http` client aimed at JSONPlaceholder (toggle in Settings)
|
||||
- **Bank connect** — Enable Banking via backend API + in-app WebView; optional deep link `ingtrak://connected`
|
||||
- **Home** — Balance, customizable layout: built-in sections (Transactions / Categorized / Recent) and filter widgets (stats or budget, half/full width, bar/pie/ring)
|
||||
- **Transactions** — Search, filters, month heatmap, labels, notes, merchant / “apply to similar” rules
|
||||
- **Overview** — Income/expense and label charts; save **favourite** chart filters
|
||||
- **Look ahead** — Projected balance from recurring templates
|
||||
- **Sync** — Bidirectional PocketBase sync (transactions, labels, annotations, favourites, home widgets, app prefs)
|
||||
- **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/
|
||||
├── android/ # Android embedding, Gradle, manifest
|
||||
ingtrakapp/
|
||||
├── android/ # Android embedding (com.ingtrak.app)
|
||||
├── assets/branding/ # App icon source + generated launcher assets
|
||||
├── lib/
|
||||
│ ├── main.dart # Entry point, Provider scope, MaterialApp
|
||||
│ ├── models/
|
||||
│ │ └── item.dart # Item + ItemCategory
|
||||
│ ├── providers/
|
||||
│ │ ├── item_provider.dart # Catalog ChangeNotifier
|
||||
│ │ └── theme_provider.dart # ThemeMode ChangeNotifier
|
||||
│ ├── screens/
|
||||
│ │ ├── splash_screen.dart
|
||||
│ │ ├── 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
|
||||
│ ├── main.dart # Providers, dotenv, deep links
|
||||
│ ├── models/ # Bank, meta, favourites, home widgets, prefs
|
||||
│ ├── providers/ # Auth, bank, sync, tx_meta, preferences, theme
|
||||
│ ├── screens/ # Splash, auth, Home / Overview / Look ahead, …
|
||||
│ ├── services/ # Bank API, PocketBase sync, CSV, storage
|
||||
│ ├── utils/ # Config, theme, constants, connect helpers
|
||||
│ └── widgets/ # Home widgets, filters, charts, sync UI
|
||||
├── pocketbase/pb_migrations/ # Schema migrations
|
||||
├── test/
|
||||
│ └── widget_test.dart
|
||||
├── .env.example
|
||||
└── 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
|
||||
cd android-flutter-app-generic
|
||||
flutter pub get
|
||||
flutter run
|
||||
dart run flutter_launcher_icons
|
||||
```
|
||||
|
||||
Useful extras:
|
||||
(Configured in `pubspec.yaml`; iOS not enabled — no `ios/` folder yet.)
|
||||
|
||||
```bash
|
||||
flutter devices # list emulators / devices
|
||||
flutter run -d android # target Android explicitly
|
||||
flutter analyze # static analysis
|
||||
flutter test # widget + unit tests
|
||||
```
|
||||
## First-run checklist
|
||||
|
||||
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.
|
||||
- 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.
|
||||
Private project. Bank credentials and tokens are handled by your backend and Enable Banking — keep API and PocketBase access controlled.
|
||||
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
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>
|
||||
|
Before Width: | Height: | Size: 544 B After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 442 B After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 721 B After Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 9.6 KiB |
|
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>
|
||||
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 208 KiB |
@@ -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;
|
||||
}
|
||||
@@ -88,6 +88,7 @@ class BankTransaction {
|
||||
required this.amount,
|
||||
required this.currency,
|
||||
required this.pending,
|
||||
this.isManual = false,
|
||||
});
|
||||
|
||||
final String date;
|
||||
@@ -96,6 +97,9 @@ class BankTransaction {
|
||||
final String currency;
|
||||
final bool pending;
|
||||
|
||||
/// Admin-created test row (editable / deletable); not from bank feed or CSV.
|
||||
final bool isManual;
|
||||
|
||||
/// Stable local key used for per-occurrence annotations.
|
||||
String get id => '$date|$currency|$amount|$description';
|
||||
|
||||
@@ -109,6 +113,50 @@ class BankTransaction {
|
||||
/// Exact match for copying notes (same description + amount + currency).
|
||||
String get exactKey => '$descriptionKey|$amount|$currency';
|
||||
|
||||
static String stripManualStamp(String description) =>
|
||||
description.replaceFirst(RegExp(r' ·#\d+$'), '');
|
||||
|
||||
/// True when [other] is the same row for delete/tombstone matching.
|
||||
///
|
||||
/// Uses id first, then date + cents + currency + description (stamp-insensitive),
|
||||
/// so PocketBase float/amount rehydration cannot bypass a local delete.
|
||||
bool matchesForDelete(BankTransaction other) {
|
||||
if (id == other.id) return true;
|
||||
if (date != other.date) return false;
|
||||
if (currency.toUpperCase() != other.currency.toUpperCase()) return false;
|
||||
if ((amount * 100).round() != (other.amount * 100).round()) return false;
|
||||
if (descriptionKey == other.descriptionKey) return true;
|
||||
return stripManualStamp(description).trim().toLowerCase() ==
|
||||
stripManualStamp(other.description).trim().toLowerCase();
|
||||
}
|
||||
|
||||
BankTransaction copyWith({
|
||||
String? date,
|
||||
String? description,
|
||||
double? amount,
|
||||
String? currency,
|
||||
bool? pending,
|
||||
bool? isManual,
|
||||
}) {
|
||||
return BankTransaction(
|
||||
date: date ?? this.date,
|
||||
description: description ?? this.description,
|
||||
amount: amount ?? this.amount,
|
||||
currency: currency ?? this.currency,
|
||||
pending: pending ?? this.pending,
|
||||
isManual: isManual ?? this.isManual,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'date': date,
|
||||
'description': description,
|
||||
'amount': amount,
|
||||
'currency': currency,
|
||||
'pending': pending,
|
||||
if (isManual) 'isManual': true,
|
||||
};
|
||||
|
||||
factory BankTransaction.fromJson(Map<String, dynamic> json) {
|
||||
final rawAmount = json['amount'];
|
||||
final amount = switch (rawAmount) {
|
||||
@@ -122,6 +170,9 @@ class BankTransaction {
|
||||
amount: amount,
|
||||
currency: json['currency'] as String? ?? 'EUR',
|
||||
pending: json['pending'] as bool? ?? false,
|
||||
isManual: json['isManual'] as bool? ??
|
||||
json['is_manual'] as bool? ??
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ class HomeFilterWidget {
|
||||
this.budgetFixedAmount = 0,
|
||||
this.budgetAverageMonths = 3,
|
||||
this.labelIds = const [],
|
||||
this.labelMatch = LabelMatchMode.and,
|
||||
this.flow = TxFlowFilter.all,
|
||||
this.amountRange = const TxAmountRange(),
|
||||
this.query = '',
|
||||
@@ -115,6 +116,10 @@ class HomeFilterWidget {
|
||||
final int budgetAverageMonths;
|
||||
|
||||
final List<String> labelIds;
|
||||
|
||||
/// AND vs OR when multiple [labelIds] are selected.
|
||||
final LabelMatchMode labelMatch;
|
||||
|
||||
final TxFlowFilter flow;
|
||||
final TxAmountRange amountRange;
|
||||
final String query;
|
||||
@@ -128,6 +133,7 @@ class HomeFilterWidget {
|
||||
|
||||
TransactionFilterSelection get filter => TransactionFilterSelection(
|
||||
labelIds: labelIds.toSet(),
|
||||
labelMatch: labelMatch,
|
||||
flow: flow,
|
||||
amountRange: amountRange,
|
||||
query: query,
|
||||
@@ -147,6 +153,7 @@ class HomeFilterWidget {
|
||||
double? budgetFixedAmount,
|
||||
int? budgetAverageMonths,
|
||||
List<String>? labelIds,
|
||||
LabelMatchMode? labelMatch,
|
||||
TxFlowFilter? flow,
|
||||
TxAmountRange? amountRange,
|
||||
String? query,
|
||||
@@ -168,6 +175,7 @@ class HomeFilterWidget {
|
||||
budgetFixedAmount: budgetFixedAmount ?? this.budgetFixedAmount,
|
||||
budgetAverageMonths: budgetAverageMonths ?? this.budgetAverageMonths,
|
||||
labelIds: labelIds ?? this.labelIds,
|
||||
labelMatch: labelMatch ?? this.labelMatch,
|
||||
flow: flow ?? this.flow,
|
||||
amountRange: amountRange ?? this.amountRange,
|
||||
query: query ?? this.query,
|
||||
@@ -192,6 +200,7 @@ class HomeFilterWidget {
|
||||
display: display,
|
||||
sortOrder: sortOrder,
|
||||
labelIds: filter.labelIds.toList(growable: false),
|
||||
labelMatch: filter.labelMatch,
|
||||
flow: filter.flow,
|
||||
amountRange: filter.amountRange,
|
||||
query: filter.query,
|
||||
@@ -215,6 +224,7 @@ class HomeFilterWidget {
|
||||
'budgetFixedAmount': budgetFixedAmount,
|
||||
'budgetAverageMonths': budgetAverageMonths,
|
||||
'labelIds': labelIds,
|
||||
'labelMatch': labelMatch.name,
|
||||
'flow': flow.name,
|
||||
'amountRange': {
|
||||
if (amountRange.exact != null) 'exact': amountRange.exact,
|
||||
@@ -274,6 +284,10 @@ class HomeFilterWidget {
|
||||
for (final id in (json['labelIds'] as List? ?? const []))
|
||||
if (id is String && id.isNotEmpty) id,
|
||||
],
|
||||
labelMatch: LabelMatchMode.values.firstWhere(
|
||||
(e) => e.name == json['labelMatch'],
|
||||
orElse: () => LabelMatchMode.and,
|
||||
),
|
||||
flow: TxFlowFilter.values.firstWhere(
|
||||
(e) => e.name == json['flow'],
|
||||
orElse: () => TxFlowFilter.all,
|
||||
|
||||
@@ -134,6 +134,15 @@ int labelVisibleDepth(
|
||||
/// Filter-only id for txs with no labels (not an assignable category).
|
||||
const String kUncategorizedFilterId = '__uncategorized__';
|
||||
|
||||
/// How multiple selected labels combine in a transaction filter.
|
||||
enum LabelMatchMode {
|
||||
/// Tx must include every selected label.
|
||||
and,
|
||||
|
||||
/// Tx must include at least one selected label.
|
||||
or,
|
||||
}
|
||||
|
||||
/// Chip presentation for [kUncategorizedFilterId] refine filters.
|
||||
const TxLabel kUncategorizedFilterLabel = TxLabel(
|
||||
id: kUncategorizedFilterId,
|
||||
|
||||
@@ -26,6 +26,13 @@ class AuthController extends ChangeNotifier {
|
||||
|
||||
RecordModel? get user => _client?.authStore.record;
|
||||
|
||||
/// True when PocketBase `usersapp.is_admin` is set for this account.
|
||||
bool get isAdmin {
|
||||
final record = user;
|
||||
if (record == null) return false;
|
||||
return record.getBoolValue('is_admin');
|
||||
}
|
||||
|
||||
String? get email {
|
||||
final value = user?.getStringValue('email');
|
||||
return value == null || value.isEmpty ? null : value;
|
||||
@@ -80,6 +87,17 @@ class AuthController extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Refresh the auth record (e.g. after `is_admin` was toggled in Admin UI).
|
||||
Future<void> refreshSession() async {
|
||||
if (!isLoggedIn) return;
|
||||
try {
|
||||
await client.collection(kPocketBaseUsersCollection).authRefresh();
|
||||
} catch (error, stackTrace) {
|
||||
debugPrint('AuthController.refreshSession failed: $error\n$stackTrace');
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
client.authStore.clear();
|
||||
notifyListeners();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/// [ChangeNotifier] for bank link status, balance, and transactions.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../models/bank.dart';
|
||||
@@ -30,9 +32,34 @@ class BankController extends ChangeNotifier {
|
||||
_remoteTransactions = cached.transactions;
|
||||
}
|
||||
_importedTransactions = _storage?.loadImportedTransactions() ?? const [];
|
||||
_importedTransactions = [
|
||||
for (final tx in _importedTransactions) _upgradeLegacyManual(tx),
|
||||
];
|
||||
_remoteTransactions = [
|
||||
for (final tx in _remoteTransactions) _upgradeLegacyManual(tx),
|
||||
];
|
||||
_pendingRemoteDeletes = _storage?.loadPendingTxDeletes() ?? const [];
|
||||
// Drop anything still queued for remote delete from the local caches.
|
||||
if (_pendingRemoteDeletes.isNotEmpty) {
|
||||
_remoteTransactions = [
|
||||
for (final tx in _remoteTransactions)
|
||||
if (!_isTombstoned(tx)) tx,
|
||||
];
|
||||
_importedTransactions = [
|
||||
for (final tx in _importedTransactions)
|
||||
if (!_isTombstoned(tx)) tx,
|
||||
];
|
||||
}
|
||||
_invalidateMerged();
|
||||
}
|
||||
|
||||
/// Older admin test rows used a ·#stamp suffix before [isManual] existed.
|
||||
static BankTransaction _upgradeLegacyManual(BankTransaction tx) {
|
||||
if (tx.isManual) return tx;
|
||||
if (!RegExp(r' ·#\d+$').hasMatch(tx.description)) return tx;
|
||||
return tx.copyWith(isManual: true);
|
||||
}
|
||||
|
||||
final IngtrakApi _api;
|
||||
final StorageService? _storage;
|
||||
|
||||
@@ -42,10 +69,92 @@ class BankController extends ChangeNotifier {
|
||||
/// cannot leave the device behind the cloud (or wipe cloud-only history).
|
||||
VoidCallback? onAfterSuccessfulLoad;
|
||||
|
||||
/// Fired when local admin txs are removed/replaced and need a remote delete.
|
||||
VoidCallback? onPendingRemoteDeletesChanged;
|
||||
|
||||
ConnectStatus _status = ConnectStatus.disconnected;
|
||||
BankBalance? _balance;
|
||||
List<BankTransaction> _remoteTransactions = const [];
|
||||
List<BankTransaction> _importedTransactions = const [];
|
||||
List<BankTransaction> _pendingRemoteDeletes = const [];
|
||||
|
||||
/// Tombstoned txs waiting to be removed from PocketBase (also persisted).
|
||||
List<BankTransaction> get pendingRemoteDeletes =>
|
||||
List<BankTransaction>.unmodifiable(_pendingRemoteDeletes);
|
||||
|
||||
bool get hasPendingRemoteDeletes => _pendingRemoteDeletes.isNotEmpty;
|
||||
|
||||
bool _isTombstoned(BankTransaction tx) {
|
||||
for (final tomb in _pendingRemoteDeletes) {
|
||||
if (tx.matchesForDelete(tomb)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Drop tombstones that match any of [txs] (fingerprint-aware).
|
||||
void clearRemoteDeletesMatching(Iterable<BankTransaction> txs) {
|
||||
final list = txs.toList(growable: false);
|
||||
if (list.isEmpty) return;
|
||||
final next = [
|
||||
for (final tomb in _pendingRemoteDeletes)
|
||||
if (!list.any(tomb.matchesForDelete)) tomb,
|
||||
];
|
||||
if (next.length == _pendingRemoteDeletes.length) return;
|
||||
_pendingRemoteDeletes = next;
|
||||
unawaited(_persistPendingDeletes());
|
||||
}
|
||||
|
||||
void clearAllPendingRemoteDeletes() {
|
||||
if (_pendingRemoteDeletes.isEmpty) return;
|
||||
_pendingRemoteDeletes = const [];
|
||||
unawaited(_persistPendingDeletes());
|
||||
}
|
||||
|
||||
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];
|
||||
unawaited(_persistPendingDeletes());
|
||||
if (notify) onPendingRemoteDeletesChanged?.call();
|
||||
}
|
||||
|
||||
Future<void> _persistPendingDeletes() async {
|
||||
final storage = _storage;
|
||||
if (storage == null) return;
|
||||
await storage.savePendingTxDeletes(_pendingRemoteDeletes);
|
||||
}
|
||||
|
||||
/// Keep [isManual] when a synced/API row replaces a matching imported test tx.
|
||||
void _reapplyManualFlags(Set<String> manualIds) {
|
||||
if (manualIds.isEmpty) return;
|
||||
BankTransaction stamp(BankTransaction tx) =>
|
||||
manualIds.contains(tx.id) && !tx.isManual
|
||||
? tx.copyWith(isManual: true)
|
||||
: tx;
|
||||
_remoteTransactions = [for (final tx in _remoteTransactions) stamp(tx)];
|
||||
_importedTransactions = [
|
||||
for (final tx in _importedTransactions) stamp(tx),
|
||||
];
|
||||
}
|
||||
|
||||
Set<String> _collectManualIds([
|
||||
Iterable<BankTransaction> extra = const [],
|
||||
]) =>
|
||||
{
|
||||
for (final tx in [
|
||||
..._remoteTransactions,
|
||||
..._importedTransactions,
|
||||
...extra,
|
||||
])
|
||||
if (tx.isManual) tx.id,
|
||||
};
|
||||
List<BankTransaction>? _mergedTransactions;
|
||||
|
||||
bool _isLoading = false;
|
||||
@@ -161,6 +270,117 @@ class BankController extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Insert a locally created transaction (admin testing). Persisted like CSV
|
||||
/// imports and included in PocketBase `transactions` sync.
|
||||
Future<BankTransaction> addManualTransaction({
|
||||
required DateTime date,
|
||||
required String description,
|
||||
required double amount,
|
||||
String currency = 'EUR',
|
||||
bool pending = false,
|
||||
}) async {
|
||||
final desc =
|
||||
description.trim().isEmpty ? 'Test transaction' : description.trim();
|
||||
// Include a short unique suffix so identical drafts do not collide on id.
|
||||
final stamp = DateTime.now().millisecondsSinceEpoch % 100000;
|
||||
final tx = BankTransaction(
|
||||
date:
|
||||
'${date.year.toString().padLeft(4, '0')}-'
|
||||
'${date.month.toString().padLeft(2, '0')}-'
|
||||
'${date.day.toString().padLeft(2, '0')}',
|
||||
description: '$desc ·#$stamp',
|
||||
amount: amount,
|
||||
currency: currency.trim().isEmpty ? 'EUR' : currency.trim().toUpperCase(),
|
||||
pending: pending,
|
||||
isManual: true,
|
||||
);
|
||||
|
||||
_importedTransactions = mergeTransactions(_importedTransactions, [tx]);
|
||||
_importedTransactions = filterNewTransactions(
|
||||
_remoteTransactions,
|
||||
_importedTransactions,
|
||||
);
|
||||
_invalidateMerged();
|
||||
await _persistImported();
|
||||
notifyListeners();
|
||||
return tx;
|
||||
}
|
||||
|
||||
/// Replace an admin test transaction. Returns the updated row (id may change).
|
||||
Future<BankTransaction> updateManualTransaction({
|
||||
required BankTransaction previous,
|
||||
required DateTime date,
|
||||
required String description,
|
||||
required double amount,
|
||||
String currency = 'EUR',
|
||||
bool pending = false,
|
||||
}) async {
|
||||
if (!previous.isManual) {
|
||||
throw StateError('Only admin test transactions can be edited');
|
||||
}
|
||||
final desc =
|
||||
description.trim().isEmpty ? 'Test transaction' : description.trim();
|
||||
final stamped = () {
|
||||
if (RegExp(r' ·#\d+$').hasMatch(desc)) return desc;
|
||||
final prevStamp = RegExp(r' ·#(\d+)$').firstMatch(previous.description);
|
||||
final prevBase =
|
||||
previous.description.replaceFirst(RegExp(r' ·#\d+$'), '');
|
||||
if (prevStamp != null && prevBase == desc) {
|
||||
return '$desc ·#${prevStamp.group(1)}';
|
||||
}
|
||||
return '$desc ·#${DateTime.now().millisecondsSinceEpoch % 100000}';
|
||||
}();
|
||||
final updated = BankTransaction(
|
||||
date:
|
||||
'${date.year.toString().padLeft(4, '0')}-'
|
||||
'${date.month.toString().padLeft(2, '0')}-'
|
||||
'${date.day.toString().padLeft(2, '0')}',
|
||||
description: stamped,
|
||||
amount: amount,
|
||||
currency: currency.trim().isEmpty ? 'EUR' : currency.trim().toUpperCase(),
|
||||
pending: pending,
|
||||
isManual: true,
|
||||
);
|
||||
|
||||
_importedTransactions = [
|
||||
for (final tx in _importedTransactions)
|
||||
if (tx.id != previous.id) tx,
|
||||
];
|
||||
_remoteTransactions = [
|
||||
for (final tx in _remoteTransactions)
|
||||
if (tx.id != previous.id) tx,
|
||||
];
|
||||
if (previous.id != updated.id) {
|
||||
_queueRemoteDelete(previous);
|
||||
}
|
||||
_importedTransactions = mergeTransactions(_importedTransactions, [updated]);
|
||||
_invalidateMerged();
|
||||
await _persistImported();
|
||||
await _persistCache();
|
||||
notifyListeners();
|
||||
return updated;
|
||||
}
|
||||
|
||||
/// Remove an admin test transaction from local caches.
|
||||
Future<void> deleteManualTransaction(BankTransaction tx) async {
|
||||
if (!tx.isManual) {
|
||||
throw StateError('Only admin test transactions can be deleted');
|
||||
}
|
||||
_importedTransactions = [
|
||||
for (final row in _importedTransactions)
|
||||
if (!row.matchesForDelete(tx)) row,
|
||||
];
|
||||
_remoteTransactions = [
|
||||
for (final row in _remoteTransactions)
|
||||
if (!row.matchesForDelete(tx)) row,
|
||||
];
|
||||
_queueRemoteDelete(tx);
|
||||
_invalidateMerged();
|
||||
await _persistImported();
|
||||
await _persistCache();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Union cloud txs into the local bank cache without dropping either side.
|
||||
///
|
||||
/// Rows land in the API cache; CSV imports that match are deduped away.
|
||||
@@ -168,13 +388,37 @@ class BankController extends ChangeNotifier {
|
||||
List<BankTransaction> fromCloud, {
|
||||
bool notify = true,
|
||||
}) async {
|
||||
if (fromCloud.isEmpty) return;
|
||||
if (fromCloud.isEmpty && _pendingRemoteDeletes.isEmpty) return;
|
||||
|
||||
_remoteTransactions = mergeTransactions(_remoteTransactions, fromCloud);
|
||||
// Never resurrect rows the user already deleted locally.
|
||||
final incoming = [
|
||||
for (final tx in fromCloud)
|
||||
if (!_isTombstoned(tx)) _upgradeLegacyManual(tx),
|
||||
];
|
||||
if (incoming.isEmpty && _pendingRemoteDeletes.isEmpty) return;
|
||||
|
||||
final manuals = _collectManualIds(incoming);
|
||||
if (incoming.isNotEmpty) {
|
||||
_remoteTransactions = mergeTransactions(_remoteTransactions, incoming);
|
||||
}
|
||||
// Strip any local copies that match a pending delete (defensive).
|
||||
if (_pendingRemoteDeletes.isNotEmpty) {
|
||||
_remoteTransactions = [
|
||||
for (final tx in _remoteTransactions)
|
||||
if (!_isTombstoned(tx)) tx,
|
||||
];
|
||||
}
|
||||
_importedTransactions = filterNewTransactions(
|
||||
_remoteTransactions,
|
||||
_importedTransactions,
|
||||
);
|
||||
if (_pendingRemoteDeletes.isNotEmpty) {
|
||||
_importedTransactions = [
|
||||
for (final tx in _importedTransactions)
|
||||
if (!_isTombstoned(tx)) tx,
|
||||
];
|
||||
}
|
||||
_reapplyManualFlags(manuals);
|
||||
_invalidateMerged();
|
||||
|
||||
if (!_status.linked && _remoteTransactions.isNotEmpty) {
|
||||
@@ -254,6 +498,7 @@ class BankController extends ChangeNotifier {
|
||||
final apiTxs = results[1] as List<BankTransaction>;
|
||||
// Bank API is ~89 days. Prefer API rows for overlaps, but keep any
|
||||
// cloud/CSV history that the API window does not include.
|
||||
final manuals = _collectManualIds();
|
||||
_remoteTransactions = mergeTransactions(apiTxs, _remoteTransactions);
|
||||
if (!_status.linked) {
|
||||
_status = ConnectStatus(
|
||||
@@ -269,6 +514,17 @@ class BankController extends ChangeNotifier {
|
||||
_remoteTransactions,
|
||||
_importedTransactions,
|
||||
);
|
||||
if (_pendingRemoteDeletes.isNotEmpty) {
|
||||
_remoteTransactions = [
|
||||
for (final tx in _remoteTransactions)
|
||||
if (!_isTombstoned(tx)) tx,
|
||||
];
|
||||
_importedTransactions = [
|
||||
for (final tx in _importedTransactions)
|
||||
if (!_isTombstoned(tx)) tx,
|
||||
];
|
||||
}
|
||||
_reapplyManualFlags(manuals);
|
||||
_invalidateMerged();
|
||||
await _persistImported();
|
||||
_error = null;
|
||||
|
||||
@@ -3,6 +3,7 @@ library;
|
||||
|
||||
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';
|
||||
@@ -28,9 +29,18 @@ class PreferencesController extends ChangeNotifier {
|
||||
/// 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).
|
||||
int get lookAheadMaxYears => _lookAheadMaxYears;
|
||||
|
||||
/// Snapshot used for PocketBase `app_prefs` sync.
|
||||
AppCloudPrefs get cloudPrefs => AppCloudPrefs(
|
||||
homeBuiltInSections: _homeBuiltInSections,
|
||||
lookAheadMaxYears: _lookAheadMaxYears,
|
||||
);
|
||||
|
||||
List<OverviewFavourite> get overviewFavourites =>
|
||||
List.unmodifiable(_overviewFavourites);
|
||||
|
||||
@@ -55,7 +65,10 @@ class PreferencesController extends ChangeNotifier {
|
||||
|
||||
HomeBuiltInSections get homeBuiltInSections => _homeBuiltInSections;
|
||||
|
||||
Future<void> setHomeBuiltInSections(HomeBuiltInSections sections) async {
|
||||
Future<void> setHomeBuiltInSections(
|
||||
HomeBuiltInSections sections, {
|
||||
bool schedulePush = true,
|
||||
}) async {
|
||||
if (sections.showTransactions == _homeBuiltInSections.showTransactions &&
|
||||
sections.showCategorized == _homeBuiltInSections.showCategorized &&
|
||||
sections.showRecent == _homeBuiltInSections.showRecent) {
|
||||
@@ -64,6 +77,7 @@ class PreferencesController extends ChangeNotifier {
|
||||
_homeBuiltInSections = sections;
|
||||
notifyListeners();
|
||||
await _storage.saveHomeBuiltInSections(sections);
|
||||
if (schedulePush) onAppPrefsPersisted?.call();
|
||||
}
|
||||
|
||||
Future<void> setHomeShowTransactions(bool value) => setHomeBuiltInSections(
|
||||
@@ -78,12 +92,29 @@ class PreferencesController extends ChangeNotifier {
|
||||
_homeBuiltInSections.copyWith(showRecent: value),
|
||||
);
|
||||
|
||||
Future<void> setLookAheadMaxYears(int years) async {
|
||||
Future<void> setLookAheadMaxYears(
|
||||
int years, {
|
||||
bool schedulePush = true,
|
||||
}) async {
|
||||
final next = years.clamp(1, 30);
|
||||
if (next == _lookAheadMaxYears) return;
|
||||
_lookAheadMaxYears = next;
|
||||
notifyListeners();
|
||||
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 {
|
||||
|
||||
@@ -5,6 +5,8 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../models/app_cloud_prefs.dart';
|
||||
import '../models/bank.dart';
|
||||
import '../models/home_filter_widget.dart';
|
||||
import '../models/overview_favourite.dart';
|
||||
import '../services/pb_sync_service.dart';
|
||||
@@ -42,8 +44,10 @@ class SyncController extends ChangeNotifier {
|
||||
_meta.onPersisted = _scheduleMetaPush;
|
||||
_prefs.onFavouritesPersisted = _scheduleFavouritesPush;
|
||||
_prefs.onHomeWidgetsPersisted = _scheduleHomeWidgetsPush;
|
||||
_prefs.onAppPrefsPersisted = _scheduleAppPrefsPush;
|
||||
_auth.addListener(_onAuthChanged);
|
||||
_bank.onAfterSuccessfulLoad = _onBankDataLoaded;
|
||||
_bank.onPendingRemoteDeletesChanged = _scheduleBankTxPush;
|
||||
if (_auth.isLoggedIn) {
|
||||
unawaited(syncNow());
|
||||
}
|
||||
@@ -61,6 +65,8 @@ class SyncController extends ChangeNotifier {
|
||||
bool _pushMetaPending = false;
|
||||
bool _pushFavouritesPending = false;
|
||||
bool _pushHomeWidgetsPending = false;
|
||||
bool _pushAppPrefsPending = false;
|
||||
bool _pushBankPending = false;
|
||||
Timer? _pushDebounce;
|
||||
Timer? _progressHold;
|
||||
Timer? _uiNotifyThrottle;
|
||||
@@ -194,6 +200,8 @@ class SyncController extends ChangeNotifier {
|
||||
_pushMetaPending = false;
|
||||
_pushFavouritesPending = false;
|
||||
_pushHomeWidgetsPending = false;
|
||||
_pushAppPrefsPending = false;
|
||||
_pushBankPending = false;
|
||||
_lastError = null;
|
||||
_statusDetail = '';
|
||||
_showProgressRing = false;
|
||||
@@ -206,10 +214,20 @@ class SyncController extends ChangeNotifier {
|
||||
|
||||
/// Bank pull-to-refresh / reconnect finished — reconcile with PocketBase.
|
||||
///
|
||||
/// Always runs a full sync when logged in so (1) new API txs are pushed and
|
||||
/// 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 (_syncing) {
|
||||
debugPrint(
|
||||
'SyncController: bank load finished during sync — skip queued full sync',
|
||||
);
|
||||
return;
|
||||
}
|
||||
unawaited(syncNow());
|
||||
}
|
||||
|
||||
@@ -246,6 +264,33 @@ class SyncController extends ChangeNotifier {
|
||||
_armPushDebounce();
|
||||
}
|
||||
|
||||
void _scheduleAppPrefsPush() {
|
||||
_pushAppPrefsPending = true;
|
||||
_armPushDebounce();
|
||||
}
|
||||
|
||||
void _scheduleBankTxPush() {
|
||||
_pushBankPending = true;
|
||||
_armPushDebounce();
|
||||
}
|
||||
|
||||
/// Removes tombstoned bank txs from PocketBase before pull/push can resurrect them.
|
||||
Future<void> _flushPendingTxDeletes(PbSyncService service) async {
|
||||
final pending = List<BankTransaction>.of(_bank.pendingRemoteDeletes);
|
||||
if (pending.isEmpty) return;
|
||||
_setStatus('Removing deleted bank txs…');
|
||||
try {
|
||||
final matched = await service.deleteTransactionsMatching(pending);
|
||||
if (matched.isNotEmpty) {
|
||||
_bank.clearRemoteDeletesMatching(matched);
|
||||
}
|
||||
// Do NOT clear unmatched tombstones — they still block pull resurrection
|
||||
// until pushTransactions GC removes the remote rows.
|
||||
} catch (error) {
|
||||
debugPrint('SyncController: tx deletes failed ($error)');
|
||||
}
|
||||
}
|
||||
|
||||
void _armPushDebounce() {
|
||||
if (!_auth.isLoggedIn) return;
|
||||
if (_syncing) {
|
||||
@@ -278,6 +323,8 @@ class SyncController extends ChangeNotifier {
|
||||
|
||||
try {
|
||||
final service = PbSyncService(_auth.client);
|
||||
// Delete first — otherwise pull re-merges the row and push recreates it.
|
||||
await _flushPendingTxDeletes(service);
|
||||
final remoteMeta = await service.pull(
|
||||
onProgress: (p) {
|
||||
_setProgress(p * 0.35);
|
||||
@@ -322,6 +369,20 @@ class SyncController extends ChangeNotifier {
|
||||
_prefs.homeFilterWidgets,
|
||||
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.
|
||||
await _meta.replaceStore(mergedMeta, notify: false);
|
||||
await _bank.applySyncedTransactions(remoteTxs, notify: false);
|
||||
@@ -333,6 +394,7 @@ class SyncController extends ChangeNotifier {
|
||||
mergedHomeWidgets,
|
||||
notify: false,
|
||||
);
|
||||
await _prefs.replaceCloudPrefs(mergedAppPrefs, notify: false);
|
||||
_meta.notifyListeners();
|
||||
_bank.notifyListeners();
|
||||
_prefs.notifyListeners();
|
||||
@@ -365,13 +427,29 @@ class SyncController extends ChangeNotifier {
|
||||
'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);
|
||||
_pushBankPending = false;
|
||||
final tombs = List<BankTransaction>.of(_bank.pendingRemoteDeletes);
|
||||
final bankSummary = await service.pushTransactions(
|
||||
_bank.transactions,
|
||||
deleteTombs: tombs,
|
||||
progressStart: 0.82,
|
||||
progressEnd: 1.0,
|
||||
onProgress: _setProgress,
|
||||
onStatus: _setStatus,
|
||||
);
|
||||
// Push GC removes orphan admin test rows; tombstones are done.
|
||||
_bank.clearAllPendingRemoteDeletes();
|
||||
_lastSyncedAt = DateTime.now();
|
||||
_lastError = null;
|
||||
_lastSyncSummary = '$metaSummary\n$bankSummary';
|
||||
@@ -410,20 +488,39 @@ class SyncController extends ChangeNotifier {
|
||||
final pushMeta = _pushMetaPending;
|
||||
final pushFavourites = _pushFavouritesPending;
|
||||
final pushHomeWidgets = _pushHomeWidgetsPending;
|
||||
final pushAppPrefs = _pushAppPrefsPending;
|
||||
final pushBank = _pushBankPending || _bank.pendingRemoteDeletes.isNotEmpty;
|
||||
_pushMetaPending = false;
|
||||
_pushFavouritesPending = false;
|
||||
_pushHomeWidgetsPending = false;
|
||||
if (!pushMeta && !pushFavourites && !pushHomeWidgets) return;
|
||||
_pushAppPrefsPending = false;
|
||||
_pushBankPending = false;
|
||||
if (!pushMeta &&
|
||||
!pushFavourites &&
|
||||
!pushHomeWidgets &&
|
||||
!pushAppPrefs &&
|
||||
!pushBank) {
|
||||
return;
|
||||
}
|
||||
|
||||
_progressHold?.cancel();
|
||||
_syncing = true;
|
||||
_progressSuccess = false;
|
||||
|
||||
final label = switch ((pushMeta, pushFavourites, pushHomeWidgets)) {
|
||||
(false, false, true) => 'Home widgets',
|
||||
(false, true, false) => 'Favourites',
|
||||
(false, true, true) => 'Home layout',
|
||||
(true, false, false) => 'Annotations',
|
||||
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…';
|
||||
@@ -436,7 +533,9 @@ class SyncController extends ChangeNotifier {
|
||||
var done = 0;
|
||||
final total = (pushMeta ? 1 : 0) +
|
||||
(pushFavourites ? 1 : 0) +
|
||||
(pushHomeWidgets ? 1 : 0);
|
||||
(pushHomeWidgets ? 1 : 0) +
|
||||
(pushAppPrefs ? 1 : 0) +
|
||||
(pushBank ? 1 : 0);
|
||||
void bump() {
|
||||
done++;
|
||||
_setProgress(done / total);
|
||||
@@ -484,6 +583,43 @@ class SyncController extends ChangeNotifier {
|
||||
}
|
||||
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…');
|
||||
await _flushPendingTxDeletes(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,
|
||||
);
|
||||
_bank.clearAllPendingRemoteDeletes();
|
||||
parts.add(summary);
|
||||
} catch (error) {
|
||||
debugPrint('SyncController: bank tx push skipped ($error)');
|
||||
_pushBankPending = true;
|
||||
}
|
||||
bump();
|
||||
}
|
||||
|
||||
_setProgress(1.0);
|
||||
_lastSyncedAt = DateTime.now();
|
||||
@@ -517,9 +653,11 @@ class SyncController extends ChangeNotifier {
|
||||
_uiNotifyThrottle?.cancel();
|
||||
_auth.removeListener(_onAuthChanged);
|
||||
_bank.onAfterSuccessfulLoad = null;
|
||||
_bank.onPendingRemoteDeletesChanged = null;
|
||||
_meta.onPersisted = null;
|
||||
_prefs.onFavouritesPersisted = null;
|
||||
_prefs.onHomeWidgetsPersisted = null;
|
||||
_prefs.onAppPrefsPersisted = null;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -722,6 +722,25 @@ class TxMetaController extends ChangeNotifier {
|
||||
_schedulePersist(invalidateLabels: false);
|
||||
}
|
||||
|
||||
/// Move per-tx annotations when an admin test transaction's id changes.
|
||||
Future<void> rekeyTransaction(String fromId, String toId) async {
|
||||
if (fromId == toId || fromId.isEmpty || toId.isEmpty) return;
|
||||
final stored = _byId.remove(fromId);
|
||||
if (stored != null) {
|
||||
_byId[toId] = stored;
|
||||
}
|
||||
_labelIdsByTxCache = null;
|
||||
_schedulePersist(invalidateLabels: true);
|
||||
}
|
||||
|
||||
/// Drop per-tx annotations for a deleted admin test transaction.
|
||||
Future<void> clearTransactionMeta(String txId) async {
|
||||
if (txId.isEmpty) return;
|
||||
if (_byId.remove(txId) == null) return;
|
||||
_labelIdsByTxCache = null;
|
||||
_schedulePersist(invalidateLabels: true);
|
||||
}
|
||||
|
||||
Future<void> setNotes(
|
||||
BankTransaction tx,
|
||||
String notes, {
|
||||
@@ -800,6 +819,7 @@ class TxMetaController extends ChangeNotifier {
|
||||
List<BankTransaction> txs,
|
||||
String query, {
|
||||
Set<String> labelIds = const {},
|
||||
LabelMatchMode labelMatch = LabelMatchMode.and,
|
||||
}) {
|
||||
final needle = query.trim().toLowerCase();
|
||||
final hasText = needle.isNotEmpty;
|
||||
@@ -809,7 +829,15 @@ class TxMetaController extends ChangeNotifier {
|
||||
final labelIndex = _labelById;
|
||||
return [
|
||||
for (final tx in txs)
|
||||
if (_matchesSearch(tx, needle, hasText, labelIds, hasLabels, labelIndex))
|
||||
if (_matchesSearch(
|
||||
tx,
|
||||
needle,
|
||||
hasText,
|
||||
labelIds,
|
||||
hasLabels,
|
||||
labelMatch,
|
||||
labelIndex,
|
||||
))
|
||||
tx,
|
||||
];
|
||||
}
|
||||
@@ -820,10 +848,11 @@ class TxMetaController extends ChangeNotifier {
|
||||
bool hasText,
|
||||
Set<String> labelIds,
|
||||
bool hasLabels,
|
||||
LabelMatchMode labelMatch,
|
||||
Map<String, TxLabel> labelIndex,
|
||||
) {
|
||||
final meta = metaFor(tx);
|
||||
if (hasLabels && !_matchesLabelFilter(meta, labelIds)) {
|
||||
if (hasLabels && !_matchesLabelFilter(meta, labelIds, labelMatch)) {
|
||||
return false;
|
||||
}
|
||||
if (!hasText) return true;
|
||||
@@ -838,20 +867,33 @@ class TxMetaController extends ChangeNotifier {
|
||||
return false;
|
||||
}
|
||||
|
||||
/// AND filter: every selected label must be on the tx.
|
||||
/// AND: every selected label must be on the tx.
|
||||
/// OR: at least one selected label (or unlabeled, if that filter is set).
|
||||
///
|
||||
/// Uncategorized alone matches unlabeled txs. Uncategorized combined with
|
||||
/// other labels matches nothing (a tx cannot be both).
|
||||
bool _matchesLabelFilter(TxMeta meta, Set<String> labelIds) {
|
||||
/// Uncategorized alone matches unlabeled txs. Uncategorized + others with
|
||||
/// AND matches nothing; with OR matches unlabeled or any of the labels.
|
||||
bool _matchesLabelFilter(
|
||||
TxMeta meta,
|
||||
Set<String> labelIds,
|
||||
LabelMatchMode mode,
|
||||
) {
|
||||
final wantUncategorized = labelIds.contains(kUncategorizedFilterId);
|
||||
final required = <String>[
|
||||
for (final id in labelIds)
|
||||
if (id != kUncategorizedFilterId) id,
|
||||
];
|
||||
if (wantUncategorized) {
|
||||
if (required.isNotEmpty) return false;
|
||||
return !meta.hasLabel;
|
||||
if (required.isEmpty) {
|
||||
if (wantUncategorized) return !meta.hasLabel;
|
||||
return true;
|
||||
}
|
||||
if (mode == LabelMatchMode.or) {
|
||||
if (wantUncategorized && !meta.hasLabel) return true;
|
||||
for (final id in required) {
|
||||
if (meta.labelIds.contains(id)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (wantUncategorized) return false;
|
||||
for (final id in required) {
|
||||
if (!meta.labelIds.contains(id)) return false;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/// Signed-in account details, sync status, bank link, and sign-out.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
@@ -10,11 +12,26 @@ import '../providers/sync_provider.dart';
|
||||
import '../providers/tx_meta_provider.dart';
|
||||
import '../utils/connect_bank.dart';
|
||||
import '../utils/constants.dart';
|
||||
import '../widgets/admin_create_transaction_dialog.dart';
|
||||
import '../widgets/responsive_body.dart';
|
||||
|
||||
class AccountScreen extends StatelessWidget {
|
||||
class AccountScreen extends StatefulWidget {
|
||||
const AccountScreen({super.key});
|
||||
|
||||
@override
|
||||
State<AccountScreen> createState() => _AccountScreenState();
|
||||
}
|
||||
|
||||
class _AccountScreenState extends State<AccountScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
unawaited(context.read<AuthController>().refreshSession());
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final auth = context.watch<AuthController>();
|
||||
@@ -62,6 +79,24 @@ class AccountScreen extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
if (auth.isAdmin)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Chip(
|
||||
avatar: Icon(
|
||||
Icons.shield_outlined,
|
||||
size: 16,
|
||||
color: colors.onSecondaryContainer,
|
||||
),
|
||||
label: const Text('Admin'),
|
||||
visualDensity: VisualDensity.compact,
|
||||
backgroundColor: colors.secondaryContainer,
|
||||
labelStyle: theme.textTheme.labelMedium?.copyWith(
|
||||
color: colors.onSecondaryContainer,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Card(
|
||||
child: Column(
|
||||
@@ -91,6 +126,59 @@ class AccountScreen extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: Icon(
|
||||
Icons.add_card_outlined,
|
||||
color: auth.isAdmin ? null : colors.onSurfaceVariant,
|
||||
),
|
||||
title: const Text('Create test transaction'),
|
||||
subtitle: Text(
|
||||
auth.isAdmin
|
||||
? 'Admin · saved locally and synced to PocketBase'
|
||||
: 'Admin only · enable is_admin on your usersapp user in PocketBase, then sign out and back in',
|
||||
),
|
||||
trailing: auth.isAdmin
|
||||
? const Icon(Icons.chevron_right)
|
||||
: Icon(
|
||||
Icons.lock_outline,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
onTap: () async {
|
||||
if (!auth.isAdmin) {
|
||||
await auth.refreshSession();
|
||||
if (!context.mounted) return;
|
||||
if (!context.read<AuthController>().isAdmin) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Not an admin yet. In PocketBase Admin → '
|
||||
'usersapp → your user → set is_admin = true, '
|
||||
'then sign out and sign in again.',
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
final tx = await showAdminCreateTransactionDialog(context);
|
||||
if (tx == null || !context.mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Created “${tx.description}” · '
|
||||
'${tx.amount.toStringAsFixed(2)} ${tx.currency}',
|
||||
),
|
||||
),
|
||||
);
|
||||
final sync = context.read<SyncController>();
|
||||
if (sync.canSync && !sync.isSyncing) {
|
||||
unawaited(sync.syncNow());
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: Icon(
|
||||
|
||||
@@ -566,13 +566,19 @@ List<Widget> _packedHomeWidgetRows(List<HomeFilterWidget> widgets) {
|
||||
rows.add(
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: HomeFilterWidgetCard(widgetConfig: a)),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(child: HomeFilterWidgetCard(widgetConfig: b)),
|
||||
],
|
||||
child: IntrinsicHeight(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: HomeFilterWidgetCard(widgetConfig: a),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: HomeFilterWidgetCard(widgetConfig: b),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -9,7 +9,7 @@ import '../models/transaction_meta.dart';
|
||||
import '../providers/bank_provider.dart';
|
||||
import '../providers/preferences_provider.dart';
|
||||
import '../providers/tx_meta_provider.dart';
|
||||
import '../screens/transaction_detail_screen.dart';
|
||||
import '../screens/transactions_screen.dart';
|
||||
import '../utils/app_theme.dart';
|
||||
import '../utils/helpers.dart';
|
||||
import '../utils/look_ahead.dart';
|
||||
@@ -337,17 +337,6 @@ class _LookAheadScreenState extends State<LookAheadScreen> {
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
items.isEmpty
|
||||
? 'Create a spending from a transaction, or tap New.'
|
||||
: '${items.length} spending${items.length == 1 ? '' : 's'} · '
|
||||
'projected income ${formatMoney(income, currency)} · '
|
||||
'expenses ${formatMoney(expenses, currency)}.',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Row(
|
||||
children: [
|
||||
@@ -622,6 +611,46 @@ class _TemplateTile extends StatelessWidget {
|
||||
return null;
|
||||
}
|
||||
|
||||
void _openTransactions(BuildContext context) {
|
||||
final labelIds = item.labelIds.toSet();
|
||||
SimilarMatchCriteria? similar;
|
||||
TxFlowFilter? flow;
|
||||
String? query;
|
||||
|
||||
if (labelIds.isEmpty) {
|
||||
final tx = _sourceTx;
|
||||
if (tx != null) {
|
||||
// Same matching as Look ahead / apply-to-similar for this source tx.
|
||||
similar = SimilarMatchCriteria(
|
||||
pattern: defaultSimilarPattern(tx.description),
|
||||
flow: tx.amount < 0
|
||||
? TxFlowFilter.expense
|
||||
: tx.amount > 0
|
||||
? TxFlowFilter.income
|
||||
: TxFlowFilter.all,
|
||||
);
|
||||
flow = similar.flow;
|
||||
} else if (template != null && template!.merchantKey.isNotEmpty) {
|
||||
query = template!.merchantKey;
|
||||
} else {
|
||||
query = item.description;
|
||||
}
|
||||
}
|
||||
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => TransactionsScreen(
|
||||
initialLabelIds: labelIds,
|
||||
initialLabelMatch: LabelMatchMode.or,
|
||||
initialQuery: query,
|
||||
initialFlow: flow,
|
||||
initialSimilarMatch: similar,
|
||||
initialSearchInMonthOnly: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
@@ -658,15 +687,7 @@ class _TemplateTile extends StatelessWidget {
|
||||
color: income ? AppTheme.accent : AppTheme.expense,
|
||||
),
|
||||
),
|
||||
onTap: () {
|
||||
final tx = _sourceTx;
|
||||
if (tx == null) return;
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => TransactionDetailScreen(tx: tx),
|
||||
),
|
||||
);
|
||||
},
|
||||
onTap: () => _openTransactions(context),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +332,7 @@ class _OverviewScreenState extends State<OverviewScreen> {
|
||||
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(0, 8, 0, 32),
|
||||
padding: const EdgeInsets.fromLTRB(0, 4, 0, 24),
|
||||
children: [
|
||||
if (bank.error != null) ...[
|
||||
Text(
|
||||
@@ -341,7 +341,7 @@ class _OverviewScreenState extends State<OverviewScreen> {
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
Row(
|
||||
children: [
|
||||
@@ -355,23 +355,33 @@ class _OverviewScreenState extends State<OverviewScreen> {
|
||||
),
|
||||
TextButton(
|
||||
onPressed: _openFavouritesManager,
|
||||
style: TextButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
),
|
||||
child: const Text('Manage'),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: () => setState(() => _showFavouritesView = false),
|
||||
icon: const Icon(Icons.insights_outlined, size: 18),
|
||||
style: TextButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
),
|
||||
icon: const Icon(Icons.open_in_new, size: 16),
|
||||
label: const Text('Full overview'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'All favourites with Display checked appear here. '
|
||||
'Use Full overview to set a filter, then ★ → Save current filter.',
|
||||
style: theme.textTheme.labelMedium,
|
||||
),
|
||||
if (displayed.isEmpty) ...[
|
||||
const SizedBox(height: 24),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'All favourites with Display checked appear here. '
|
||||
'Use Full overview to set a filter, then ★ → Save current filter.',
|
||||
style: theme.textTheme.labelMedium,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No displayed favourites yet. Tap Manage to enable Display, '
|
||||
'or save a new filter from Full overview.',
|
||||
@@ -380,9 +390,9 @@ class _OverviewScreenState extends State<OverviewScreen> {
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
const SizedBox(height: 12),
|
||||
const SizedBox(height: 8),
|
||||
for (var i = 0; i < displayed.length; i++) ...[
|
||||
if (i > 0) const SizedBox(height: 14),
|
||||
if (i > 0) const SizedBox(height: 10),
|
||||
_favouriteChartCard(
|
||||
context: context,
|
||||
favourite: displayed[i],
|
||||
@@ -618,11 +628,11 @@ class _OverviewScreenState extends State<OverviewScreen> {
|
||||
currency,
|
||||
),
|
||||
label: switch (_labelFlow) {
|
||||
TxFlowFilter.income => 'Labeled income · $_periodTitle',
|
||||
TxFlowFilter.expense => 'Labeled spend · $_periodTitle',
|
||||
TxFlowFilter.income => 'Income · $_periodTitle',
|
||||
TxFlowFilter.expense => 'Spend · $_periodTitle',
|
||||
TxFlowFilter.all => _labelInvertChart
|
||||
? 'Labeled net (expense view) · $_periodTitle'
|
||||
: 'Labeled net · $_periodTitle',
|
||||
? 'Net (expense view) · $_periodTitle'
|
||||
: 'Net · $_periodTitle',
|
||||
},
|
||||
),
|
||||
],
|
||||
@@ -743,6 +753,7 @@ class _OverviewScreenState extends State<OverviewScreen> {
|
||||
builder: (_) => TransactionsScreen(
|
||||
initialMonth: initial,
|
||||
initialLabelIds: labelIds,
|
||||
initialLabelMatch: LabelMatchMode.or,
|
||||
initialSearchInMonthOnly: !yearly && labelIds.isNotEmpty,
|
||||
initialYear: yearly ? period.year : null,
|
||||
),
|
||||
@@ -1176,10 +1187,13 @@ class _ChartCard extends StatelessWidget {
|
||||
final VoidCallback? onEdit;
|
||||
|
||||
static const _compactSegmentStyle = ButtonStyle(
|
||||
visualDensity: VisualDensity(horizontal: -4, vertical: -3),
|
||||
visualDensity: VisualDensity(horizontal: -4, vertical: -4),
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 8)),
|
||||
minimumSize: WidgetStatePropertyAll(Size(0, 32)),
|
||||
padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 6)),
|
||||
minimumSize: WidgetStatePropertyAll(Size(0, 28)),
|
||||
textStyle: WidgetStatePropertyAll(
|
||||
TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _filterButton(ColorScheme colors) {
|
||||
@@ -1216,44 +1230,152 @@ class _ChartCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _editButton(ColorScheme colors) {
|
||||
Widget _editButton(ColorScheme colors, {required bool compact}) {
|
||||
return IconButton(
|
||||
tooltip: 'Edit favourite',
|
||||
onPressed: onEdit,
|
||||
visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
|
||||
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
|
||||
constraints: BoxConstraints(
|
||||
minWidth: compact ? 28 : 36,
|
||||
minHeight: compact ? 28 : 36,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: colors.surfaceContainerHigh,
|
||||
backgroundColor:
|
||||
compact ? null : colors.surfaceContainerHigh,
|
||||
foregroundColor: colors.onSurfaceVariant,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
icon: const Icon(Icons.edit_outlined, size: 18),
|
||||
icon: Icon(Icons.edit_outlined, size: compact ? 16 : 18),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _legendRow(ColorScheme colors, {required bool compact}) {
|
||||
if (metric == OverviewMetricMode.flow) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_LegendDot(
|
||||
color: _kIncomeColor,
|
||||
label: 'Income',
|
||||
compact: compact,
|
||||
),
|
||||
SizedBox(width: compact ? 10 : 14),
|
||||
_LegendDot(
|
||||
color: _kExpenseColor,
|
||||
label: 'Expense',
|
||||
compact: compact,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (labelSpend.isEmpty) return const SizedBox.shrink();
|
||||
return Wrap(
|
||||
spacing: compact ? 8 : 12,
|
||||
runSpacing: 2,
|
||||
alignment: WrapAlignment.end,
|
||||
children: [
|
||||
for (final row in labelSpend.take(compact ? 3 : 5))
|
||||
GestureDetector(
|
||||
onTap: () => onLabelTap(row.label),
|
||||
child: _LegendDot(
|
||||
color: row.label.color,
|
||||
label: row.label.name,
|
||||
compact: compact,
|
||||
),
|
||||
),
|
||||
if (labelSpend.length > (compact ? 3 : 5))
|
||||
_LegendDot(
|
||||
color: colors.outline,
|
||||
label: 'Other',
|
||||
compact: compact,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _periodControls(ThemeData theme, {required bool compact}) {
|
||||
final titleStyle = (compact
|
||||
? theme.textTheme.labelMedium
|
||||
: theme.textTheme.titleMedium)
|
||||
?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: compact ? theme.colorScheme.onSurfaceVariant : null,
|
||||
);
|
||||
|
||||
if (period == OverviewPeriodMode.monthly) {
|
||||
return Row(
|
||||
children: [
|
||||
IconButton(
|
||||
tooltip: 'Previous year',
|
||||
onPressed: canGoBack ? onBack : null,
|
||||
visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
|
||||
constraints: BoxConstraints(
|
||||
minWidth: compact ? 28 : 32,
|
||||
minHeight: compact ? 28 : 32,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
icon: Icon(Icons.chevron_left, size: compact ? 20 : 22),
|
||||
),
|
||||
Flexible(
|
||||
child: Text(
|
||||
periodTitle,
|
||||
textAlign: TextAlign.left,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: titleStyle,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Next year',
|
||||
onPressed: canGoForward ? onForward : null,
|
||||
visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
|
||||
constraints: BoxConstraints(
|
||||
minWidth: compact ? 28 : 32,
|
||||
minHeight: compact ? 28 : 32,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
icon: Icon(Icons.chevron_right, size: compact ? 20 : 22),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return Text(periodTitle, style: titleStyle);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final colors = theme.colorScheme;
|
||||
final showFilter =
|
||||
metric == OverviewMetricMode.labels && onPickLabels != null;
|
||||
final showFavouriteChrome =
|
||||
onPeriodModeChanged != null || onEdit != null;
|
||||
final compact = onPeriodModeChanged != null || onEdit != null;
|
||||
final chartHeight = compact ? 176.0 : 220.0;
|
||||
|
||||
final legend = _legendRow(colors, compact: compact);
|
||||
final hasLegend = metric == OverviewMetricMode.flow ||
|
||||
labelSpend.isNotEmpty;
|
||||
|
||||
return Card(
|
||||
color: colors.surfaceContainer,
|
||||
elevation: 0,
|
||||
margin: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
borderRadius: BorderRadius.circular(compact ? 16 : 20),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 12, 14, 16),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
compact ? 12 : 14,
|
||||
compact ? 10 : 12,
|
||||
compact ? 10 : 14,
|
||||
compact ? 12 : 16,
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
if (showFavouriteChrome) ...[
|
||||
if (compact) ...[
|
||||
Row(
|
||||
children: [
|
||||
if (onPeriodModeChanged != null)
|
||||
@@ -1274,145 +1396,133 @@ class _ChartCard extends StatelessWidget {
|
||||
onSelectionChanged: (selection) {
|
||||
onPeriodModeChanged!(selection.first);
|
||||
},
|
||||
)
|
||||
else
|
||||
const SizedBox.shrink(),
|
||||
),
|
||||
if (heading != null) ...[
|
||||
const SizedBox(width: 10),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
heading!,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
] else
|
||||
const Spacer(),
|
||||
if (onEdit != null) ...[
|
||||
const SizedBox(width: 6),
|
||||
_editButton(colors),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
] else if (heading != null) ...[
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(
|
||||
heading!,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
if (period == OverviewPeriodMode.monthly)
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
tooltip: 'Previous year',
|
||||
onPressed: canGoBack ? onBack : null,
|
||||
visualDensity: const VisualDensity(
|
||||
horizontal: -4,
|
||||
vertical: -4,
|
||||
),
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 32,
|
||||
minHeight: 32,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
icon: const Icon(Icons.chevron_left, size: 22),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
periodTitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Next year',
|
||||
onPressed: canGoForward ? onForward : null,
|
||||
visualDensity: const VisualDensity(
|
||||
horizontal: -4,
|
||||
vertical: -4,
|
||||
),
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 32,
|
||||
minHeight: 32,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
icon: const Icon(Icons.chevron_right, size: 22),
|
||||
),
|
||||
if (showFilter) ...[
|
||||
const SizedBox(width: 2),
|
||||
const SizedBox(width: 4),
|
||||
_filterButton(colors),
|
||||
],
|
||||
if (onEdit != null) ...[
|
||||
const SizedBox(width: 2),
|
||||
_editButton(colors, compact: true),
|
||||
],
|
||||
],
|
||||
)
|
||||
else
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
SizedBox(width: showFilter ? 36 : 0),
|
||||
Expanded(
|
||||
child: Text(
|
||||
periodTitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
child: _periodControls(theme, compact: true),
|
||||
),
|
||||
if (hasLegend) ...[
|
||||
const SizedBox(width: 8),
|
||||
Flexible(child: legend),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
] else ...[
|
||||
if (heading != null) ...[
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(
|
||||
heading!,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
if (showFilter)
|
||||
_filterButton(colors)
|
||||
else
|
||||
const SizedBox(width: 0),
|
||||
],
|
||||
),
|
||||
if (metric == OverviewMetricMode.flow) ...[
|
||||
const Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
_LegendDot(color: _kIncomeColor, label: 'Income'),
|
||||
SizedBox(width: 14),
|
||||
_LegendDot(color: _kExpenseColor, label: 'Expense'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
] else if (labelSpend.isNotEmpty) ...[
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 4,
|
||||
alignment: WrapAlignment.end,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
if (period == OverviewPeriodMode.monthly)
|
||||
Row(
|
||||
children: [
|
||||
for (final row in labelSpend.take(5))
|
||||
GestureDetector(
|
||||
onTap: () => onLabelTap(row.label),
|
||||
child: _LegendDot(
|
||||
color: row.label.color,
|
||||
label: row.label.name,
|
||||
IconButton(
|
||||
tooltip: 'Previous year',
|
||||
onPressed: canGoBack ? onBack : null,
|
||||
visualDensity: const VisualDensity(
|
||||
horizontal: -4,
|
||||
vertical: -4,
|
||||
),
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 32,
|
||||
minHeight: 32,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
icon: const Icon(Icons.chevron_left, size: 22),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
periodTitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
if (labelSpend.length > 5)
|
||||
_LegendDot(
|
||||
color: colors.outline,
|
||||
label: 'Other',
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Next year',
|
||||
onPressed: canGoForward ? onForward : null,
|
||||
visualDensity: const VisualDensity(
|
||||
horizontal: -4,
|
||||
vertical: -4,
|
||||
),
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 32,
|
||||
minHeight: 32,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
icon: const Icon(Icons.chevron_right, size: 22),
|
||||
),
|
||||
if (showFilter) ...[
|
||||
const SizedBox(width: 2),
|
||||
_filterButton(colors),
|
||||
],
|
||||
],
|
||||
)
|
||||
else
|
||||
Row(
|
||||
children: [
|
||||
SizedBox(width: showFilter ? 36 : 0),
|
||||
Expanded(
|
||||
child: Text(
|
||||
periodTitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (showFilter)
|
||||
_filterButton(colors)
|
||||
else
|
||||
const SizedBox(width: 0),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (hasLegend) ...[
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: legend,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
],
|
||||
SizedBox(
|
||||
height: 220,
|
||||
height: chartHeight,
|
||||
child: metric == OverviewMetricMode.flow
|
||||
? _FlowBars(
|
||||
months: months,
|
||||
@@ -1908,23 +2018,34 @@ class _LabelMonthBars extends StatelessWidget {
|
||||
}
|
||||
|
||||
class _LegendDot extends StatelessWidget {
|
||||
const _LegendDot({required this.color, required this.label});
|
||||
const _LegendDot({
|
||||
required this.color,
|
||||
required this.label,
|
||||
this.compact = false,
|
||||
});
|
||||
|
||||
final Color color;
|
||||
final String label;
|
||||
final bool compact;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
width: compact ? 6 : 8,
|
||||
height: compact ? 6 : 8,
|
||||
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(label, style: Theme.of(context).textTheme.labelMedium),
|
||||
SizedBox(width: compact ? 4 : 6),
|
||||
Text(
|
||||
label,
|
||||
style: compact
|
||||
? theme.textTheme.labelSmall
|
||||
: theme.textTheme.labelMedium,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -82,17 +82,13 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 88,
|
||||
height: 88,
|
||||
decoration: BoxDecoration(
|
||||
color: colors.onPrimary.withValues(alpha: 0.16),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.account_balance_rounded,
|
||||
size: 44,
|
||||
color: colors.onPrimary,
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
child: Image.asset(
|
||||
'assets/branding/app_icon.png',
|
||||
width: 112,
|
||||
height: 112,
|
||||
filterQuality: FilterQuality.high,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
@@ -103,12 +99,12 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Your bank data, simply',
|
||||
style: textTheme.bodyLarge?.copyWith(
|
||||
color: colors.onPrimary.withValues(alpha: 0.85),
|
||||
),
|
||||
Text(
|
||||
'Your bank data, simply',
|
||||
style: textTheme.bodyLarge?.copyWith(
|
||||
color: colors.onPrimary.withValues(alpha: 0.85),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
SizedBox(
|
||||
width: 28,
|
||||
|
||||
@@ -6,10 +6,12 @@ import 'package:provider/provider.dart';
|
||||
|
||||
import '../models/bank.dart';
|
||||
import '../models/transaction_meta.dart';
|
||||
import '../providers/auth_provider.dart';
|
||||
import '../providers/bank_provider.dart';
|
||||
import '../providers/tx_meta_provider.dart';
|
||||
import '../utils/app_theme.dart';
|
||||
import '../utils/helpers.dart';
|
||||
import '../widgets/admin_create_transaction_dialog.dart';
|
||||
import '../widgets/label_parent_picker.dart';
|
||||
import '../widgets/recurring_template_sheet.dart';
|
||||
import '../widgets/responsive_body.dart';
|
||||
@@ -26,6 +28,7 @@ class TransactionDetailScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
late BankTransaction _tx;
|
||||
late final TextEditingController _notesController;
|
||||
late final TextEditingController _labelSearchController;
|
||||
late SimilarMatchCriteria _matchCriteria;
|
||||
@@ -41,11 +44,12 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tx = widget.tx;
|
||||
final meta = context.read<TxMetaController>();
|
||||
final notes = meta.metaFor(widget.tx).notes;
|
||||
final notes = meta.metaFor(_tx).notes;
|
||||
_notesController = TextEditingController(text: notes);
|
||||
_labelSearchController = TextEditingController();
|
||||
final tx = widget.tx;
|
||||
final tx = _tx;
|
||||
_matchCriteria = SimilarMatchCriteria(
|
||||
pattern: defaultSimilarPattern(tx.description),
|
||||
flow: tx.amount < 0
|
||||
@@ -63,7 +67,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
if (!mounted) return;
|
||||
final all = context.read<BankController>().transactions;
|
||||
final count = context.read<TxMetaController>().countSimilar(
|
||||
widget.tx,
|
||||
_tx,
|
||||
all,
|
||||
criteria: _matchCriteria,
|
||||
);
|
||||
@@ -88,14 +92,14 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
List<BankTransaction> _similarScope(TxMetaController meta) {
|
||||
final all = context.read<BankController>().transactions;
|
||||
if (!_applyToSimilar) return const [];
|
||||
return meta.similarTo(widget.tx, all, criteria: _matchCriteria);
|
||||
return meta.similarTo(_tx, all, criteria: _matchCriteria);
|
||||
}
|
||||
|
||||
Future<void> _editMatchCriteria() async {
|
||||
final all = context.read<BankController>().transactions;
|
||||
final result = await showSimilarMatchDialog(
|
||||
context,
|
||||
prototype: widget.tx,
|
||||
prototype: _tx,
|
||||
all: all,
|
||||
initial: _matchCriteria,
|
||||
);
|
||||
@@ -138,7 +142,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
final similar = _similarScope(meta);
|
||||
final count = similar.isEmpty ? 1 : similar.length;
|
||||
await meta.setNotes(
|
||||
widget.tx,
|
||||
_tx,
|
||||
_notesController.text,
|
||||
applyToSimilar: similar,
|
||||
matchPattern: _pattern,
|
||||
@@ -180,7 +184,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
() async {
|
||||
final meta = context.read<TxMetaController>();
|
||||
final similar = toMatched ? _similarScope(meta) : const <BankTransaction>[];
|
||||
final targets = similar.isEmpty ? [widget.tx] : similar;
|
||||
final targets = similar.isEmpty ? [_tx] : similar;
|
||||
await meta.setLabelsForMany(
|
||||
targets,
|
||||
_draftLabelIds.toList(growable: false),
|
||||
@@ -188,7 +192,7 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_labelsDirty = false;
|
||||
_draftLabelIds = meta.metaFor(widget.tx).labelIds.toSet();
|
||||
_draftLabelIds = meta.metaFor(_tx).labelIds.toSet();
|
||||
});
|
||||
final count = targets.length;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@@ -291,9 +295,79 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
await context.read<TxMetaController>().removeLabel(label.id);
|
||||
}
|
||||
|
||||
Future<void> _editManualTransaction() async {
|
||||
final updated = await showAdminCreateTransactionDialog(
|
||||
context,
|
||||
existing: _tx,
|
||||
);
|
||||
if (updated == null || !mounted) return;
|
||||
final meta = context.read<TxMetaController>();
|
||||
if (updated.id != _tx.id) {
|
||||
await meta.rekeyTransaction(_tx.id, updated.id);
|
||||
}
|
||||
setState(() {
|
||||
_tx = updated;
|
||||
_matchCriteria = SimilarMatchCriteria(
|
||||
pattern: defaultSimilarPattern(updated.description),
|
||||
flow: updated.amount < 0
|
||||
? TxFlowFilter.expense
|
||||
: updated.amount > 0
|
||||
? TxFlowFilter.income
|
||||
: TxFlowFilter.all,
|
||||
);
|
||||
_draftLabelIds = meta.metaFor(updated).labelIds.toSet();
|
||||
_labelsDirty = false;
|
||||
_similarReady = false;
|
||||
_similarCount = 0;
|
||||
});
|
||||
_refreshSimilarCount();
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Test transaction updated')),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _deleteManualTransaction() async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Delete test transaction?'),
|
||||
content: const Text(
|
||||
'This removes the transaction from this device. The remote copy is '
|
||||
'deleted on the next PocketBase sync.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
if (ok != true || !mounted) return;
|
||||
final id = _tx.id;
|
||||
final bank = context.read<BankController>();
|
||||
final meta = context.read<TxMetaController>();
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final navigator = Navigator.of(context);
|
||||
await bank.deleteManualTransaction(_tx);
|
||||
await meta.clearTransactionMeta(id);
|
||||
if (!mounted) return;
|
||||
navigator.pop();
|
||||
messenger.showSnackBar(
|
||||
const SnackBar(content: Text('Test transaction deleted')),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tx = widget.tx;
|
||||
final tx = _tx;
|
||||
final metaController = context.watch<TxMetaController>();
|
||||
final meta = metaController.metaFor(tx);
|
||||
final similarCount = _similarCount;
|
||||
@@ -317,11 +391,37 @@ class _TransactionDetailScreenState extends State<TransactionDetailScreen> {
|
||||
if (keep.contains(entry.label.id)) entry,
|
||||
];
|
||||
}();
|
||||
final canEditManual =
|
||||
context.watch<AuthController>().isAdmin && tx.isManual;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Transaction'),
|
||||
actions: [
|
||||
if (canEditManual)
|
||||
PopupMenuButton<String>(
|
||||
enabled: !_busy,
|
||||
onSelected: (value) {
|
||||
if (value == 'edit') {
|
||||
_editManualTransaction();
|
||||
} else if (value == 'delete') {
|
||||
_deleteManualTransaction();
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
const PopupMenuItem(
|
||||
value: 'edit',
|
||||
child: Text('Edit test transaction'),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: 'delete',
|
||||
child: Text(
|
||||
'Delete',
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_dirty)
|
||||
TextButton(
|
||||
onPressed: _busy ? null : _saveNotes,
|
||||
|
||||
@@ -9,7 +9,6 @@ import 'package:provider/provider.dart';
|
||||
import '../models/bank.dart';
|
||||
import '../models/transaction_meta.dart';
|
||||
import '../providers/bank_provider.dart';
|
||||
import '../providers/preferences_provider.dart';
|
||||
import '../providers/tx_meta_provider.dart';
|
||||
import '../utils/app_theme.dart';
|
||||
import '../utils/connect_bank.dart';
|
||||
@@ -17,7 +16,6 @@ import '../utils/helpers.dart';
|
||||
import '../utils/navigation.dart';
|
||||
import '../utils/tx_calendar.dart';
|
||||
import '../widgets/empty_state.dart';
|
||||
import '../widgets/home_widgets_sheet.dart';
|
||||
import '../widgets/label_filter_dialog.dart';
|
||||
import '../widgets/loading_view.dart';
|
||||
import '../widgets/responsive_body.dart';
|
||||
@@ -30,11 +28,13 @@ class TransactionsScreen extends StatefulWidget {
|
||||
super.key,
|
||||
this.initialMonth,
|
||||
this.initialLabelIds = const {},
|
||||
this.initialLabelMatch = LabelMatchMode.and,
|
||||
this.initialSearchInMonthOnly,
|
||||
this.initialYear,
|
||||
this.initialQuery,
|
||||
this.initialFlow,
|
||||
this.initialAmountRange,
|
||||
this.initialSimilarMatch,
|
||||
});
|
||||
|
||||
/// When set, opens on this calendar month instead of the current month.
|
||||
@@ -43,6 +43,9 @@ class TransactionsScreen extends StatefulWidget {
|
||||
/// Pre-select these label filters (e.g. from overview history).
|
||||
final Set<String> initialLabelIds;
|
||||
|
||||
/// AND vs OR for [initialLabelIds] (and later filter edits).
|
||||
final LabelMatchMode initialLabelMatch;
|
||||
|
||||
/// When set, overrides the default "search in month" checkbox.
|
||||
final bool? initialSearchInMonthOnly;
|
||||
|
||||
@@ -55,6 +58,9 @@ class TransactionsScreen extends StatefulWidget {
|
||||
final TxFlowFilter? initialFlow;
|
||||
final TxAmountRange? initialAmountRange;
|
||||
|
||||
/// Match txs the same way as “apply to similar” / Look ahead transaction source.
|
||||
final SimilarMatchCriteria? initialSimilarMatch;
|
||||
|
||||
@override
|
||||
State<TransactionsScreen> createState() => _TransactionsScreenState();
|
||||
}
|
||||
@@ -68,6 +74,8 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
DateTime? _selectedDay;
|
||||
late bool _searchInMonthOnly;
|
||||
late final Set<String> _labelFilters;
|
||||
late LabelMatchMode _labelMatch;
|
||||
SimilarMatchCriteria? _similarMatch;
|
||||
int? _yearFilter;
|
||||
var _showCalendar = false;
|
||||
var _flowFilter = TxFlowFilter.all;
|
||||
@@ -89,6 +97,8 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
_month = start.isAfter(now) ? now : start;
|
||||
}
|
||||
_labelFilters = Set<String>.of(widget.initialLabelIds);
|
||||
_labelMatch = widget.initialLabelMatch;
|
||||
_similarMatch = widget.initialSimilarMatch;
|
||||
// Default to current month so the list, navigator, and filter popup agree.
|
||||
_searchInMonthOnly = widget.initialSearchInMonthOnly ?? true;
|
||||
_yearFilter = widget.initialYear;
|
||||
@@ -98,6 +108,11 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
if (initialQuery.isNotEmpty) {
|
||||
_searchController.text = initialQuery;
|
||||
_activeQuery = initialQuery;
|
||||
} else if (_similarMatch != null &&
|
||||
_similarMatch!.pattern.trim().isNotEmpty) {
|
||||
// Show the similar pattern in the search field for context; filtering
|
||||
// uses [txMatchesSimilarCriteria], not plain text contains.
|
||||
_searchController.text = _similarMatch!.pattern;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,16 +124,23 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
}
|
||||
|
||||
bool get _isSearching =>
|
||||
_activeQuery.trim().isNotEmpty || _labelFilters.isNotEmpty;
|
||||
_activeQuery.trim().isNotEmpty ||
|
||||
_labelFilters.isNotEmpty ||
|
||||
_similarMatch != null;
|
||||
|
||||
bool get _hasListFilters =>
|
||||
_labelFilters.isNotEmpty ||
|
||||
_flowFilter != TxFlowFilter.all ||
|
||||
_amountRange.isActive;
|
||||
_amountRange.isActive ||
|
||||
_similarMatch != null;
|
||||
|
||||
bool _matchesExtraFilters(BankTransaction tx, TxMetaController meta) {
|
||||
if (!txMatchesFlow(tx, _flowFilter)) return false;
|
||||
if (!txMatchesAmountRange(tx, _amountRange)) return false;
|
||||
final similar = _similarMatch;
|
||||
if (similar != null && !txMatchesSimilarCriteria(tx, similar)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -147,6 +169,11 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
final trimmed = value.trim();
|
||||
_searchDebounceTimer?.cancel();
|
||||
|
||||
// Editing the box leaves “similar match” mode and uses plain text search.
|
||||
if (_similarMatch != null) {
|
||||
setState(() => _similarMatch = null);
|
||||
}
|
||||
|
||||
if (trimmed.length >= _minLiveSearchChars) {
|
||||
// TextField updates via the controller; only rebuild the list after debounce.
|
||||
_searchDebounceTimer = Timer(_searchDebounce, () {
|
||||
@@ -165,13 +192,19 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
|
||||
void _onSearchSubmitted(String value) {
|
||||
_searchDebounceTimer?.cancel();
|
||||
setState(() => _activeQuery = value.trim());
|
||||
setState(() {
|
||||
_similarMatch = null;
|
||||
_activeQuery = value.trim();
|
||||
});
|
||||
}
|
||||
|
||||
void _clearSearch() {
|
||||
_searchDebounceTimer?.cancel();
|
||||
_searchController.clear();
|
||||
setState(() => _activeQuery = '');
|
||||
setState(() {
|
||||
_activeQuery = '';
|
||||
_similarMatch = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _pickFilters(List<TxLabel> available) async {
|
||||
@@ -183,6 +216,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
currentMonth: _month,
|
||||
initial: TransactionFilterSelection(
|
||||
labelIds: Set<String>.of(_labelFilters),
|
||||
labelMatch: _labelMatch,
|
||||
flow: _flowFilter,
|
||||
amountRange: _amountRange,
|
||||
query: _activeQuery,
|
||||
@@ -195,6 +229,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
_labelFilters
|
||||
..clear()
|
||||
..addAll(result.labelIds);
|
||||
_labelMatch = result.labelMatch;
|
||||
_flowFilter = result.flow;
|
||||
_amountRange = result.amountRange;
|
||||
_searchInMonthOnly = result.monthOnly;
|
||||
@@ -240,27 +275,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _saveAsHomeWidget() async {
|
||||
final preferences = context.read<PreferencesController>();
|
||||
final created = await composeHomeFilterWidget(
|
||||
context,
|
||||
initialFilter: TransactionFilterSelection(
|
||||
labelIds: Set<String>.of(_labelFilters),
|
||||
flow: _flowFilter,
|
||||
amountRange: _amountRange,
|
||||
query: _activeQuery,
|
||||
monthOnly: _searchInMonthOnly,
|
||||
),
|
||||
skipFilterDialog: true,
|
||||
);
|
||||
if (created == null) return;
|
||||
await preferences.addHomeFilterWidget(created);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Added “${created.name}” to Home')),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bank = context.watch<BankController>();
|
||||
@@ -269,11 +283,6 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
appBar: AppBar(
|
||||
title: const Text('Transactions'),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: 'Save as Home widget',
|
||||
onPressed: _saveAsHomeWidget,
|
||||
icon: const Icon(Icons.dashboard_customize_outlined),
|
||||
),
|
||||
...bankAppBarActions(
|
||||
context: context,
|
||||
onRefresh: bank.refresh,
|
||||
@@ -386,6 +395,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
||||
searchPool,
|
||||
_activeQuery,
|
||||
labelIds: _labelFilters,
|
||||
labelMatch: _labelMatch,
|
||||
))
|
||||
if (_matchesExtraFilters(tx, metaController)) tx,
|
||||
];
|
||||
|
||||
@@ -7,7 +7,9 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pocketbase/pocketbase.dart';
|
||||
|
||||
import '../models/app_cloud_prefs.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';
|
||||
@@ -532,6 +534,7 @@ class PbSyncService {
|
||||
},
|
||||
'budgetAverageMonths': r.getIntValue('budget_average_months', 3),
|
||||
'labelIds': _jsonStringList(r.get<dynamic>('label_ids')),
|
||||
'labelMatch': r.getStringValue('label_match'),
|
||||
'flow': r.getStringValue('flow'),
|
||||
'amountRange': rangeRaw is Map
|
||||
? Map<String, dynamic>.from(rangeRaw)
|
||||
@@ -558,10 +561,51 @@ class PbSyncService {
|
||||
await _syncHomeFilterWidgets(userId, filter, widgets);
|
||||
}
|
||||
|
||||
/// Upserts local bank txs to PocketBase. Does **not** delete remote rows
|
||||
/// (partial local caches must not wipe another device).
|
||||
/// 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(
|
||||
List<BankTransaction> local, {
|
||||
List<BankTransaction> deleteTombs = const [],
|
||||
void Function(double progress)? onProgress,
|
||||
void Function(String message)? onStatus,
|
||||
double progressStart = 0.0,
|
||||
@@ -590,10 +634,19 @@ class PbSyncService {
|
||||
final ops = <_BatchOp>[];
|
||||
var skipped = 0;
|
||||
final seen = <String>{};
|
||||
final tombIds = {
|
||||
for (final t in deleteTombs)
|
||||
if (_clip(t.id, 2000).isNotEmpty) _clip(t.id, 2000),
|
||||
};
|
||||
|
||||
for (final tx in local) {
|
||||
final syncId = _clip(tx.id, 2000);
|
||||
if (syncId.isEmpty || !seen.add(syncId)) continue;
|
||||
// Never re-upsert a tombstoned row in the same pass.
|
||||
if (tombIds.contains(syncId) ||
|
||||
deleteTombs.any(tx.matchesForDelete)) {
|
||||
continue;
|
||||
}
|
||||
final body = <String, dynamic>{
|
||||
'user': userId,
|
||||
'tx_id': syncId,
|
||||
@@ -608,6 +661,9 @@ class PbSyncService {
|
||||
8,
|
||||
),
|
||||
'pending': tx.pending,
|
||||
// Only send when true so servers without the migration still accept
|
||||
// normal bank/CSV upserts. Test rows are also detected via ·# stamp.
|
||||
if (tx.isManual) 'is_manual': true,
|
||||
};
|
||||
final remote = existing[syncId];
|
||||
if (remote == null) {
|
||||
@@ -619,11 +675,25 @@ class PbSyncService {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove admin test / tombstoned rows that this device no longer has.
|
||||
var deletes = 0;
|
||||
for (final entry in existing.entries) {
|
||||
if (seen.contains(entry.key)) continue;
|
||||
final remoteTx = _bankTxFromRecord(entry.value);
|
||||
final tombHit = tombIds.contains(entry.key) ||
|
||||
(remoteTx != null && deleteTombs.any(remoteTx.matchesForDelete));
|
||||
final orphanManual = _remoteLooksLikeManualTest(entry.value);
|
||||
if (!tombHit && !orphanManual) continue;
|
||||
ops.add(_BatchOp.delete(entry.value.id));
|
||||
deletes++;
|
||||
}
|
||||
|
||||
final creates = ops.where((o) => o.kind == _BatchOpKind.create).length;
|
||||
final updates = ops.where((o) => o.kind == _BatchOpKind.update).length;
|
||||
debugPrint(
|
||||
'PbSyncService transactions: local=${local.length} '
|
||||
'remote=${existing.length} create=$creates update=$updates skip=$skipped',
|
||||
'remote=${existing.length} create=$creates update=$updates '
|
||||
'delete=$deletes skip=$skipped',
|
||||
);
|
||||
onStatus?.call(
|
||||
ops.isEmpty
|
||||
@@ -637,8 +707,13 @@ class PbSyncService {
|
||||
onStatus: onStatus,
|
||||
);
|
||||
return 'Bank txs: local ${local.length} → remote '
|
||||
'${existing.length + creates} '
|
||||
'(+$creates ~$updates · $skipped unchanged)';
|
||||
'${existing.length + creates - deletes} '
|
||||
'(+$creates ~$updates -$deletes · $skipped unchanged)';
|
||||
}
|
||||
|
||||
bool _remoteLooksLikeManualTest(RecordModel r) {
|
||||
if (r.getBoolValue('is_manual')) return true;
|
||||
return RegExp(r' ·#\d+$').hasMatch(r.getStringValue('description'));
|
||||
}
|
||||
|
||||
BankTransaction? _bankTxFromRecord(RecordModel r) {
|
||||
@@ -659,6 +734,8 @@ class PbSyncService {
|
||||
? 'EUR'
|
||||
: r.getStringValue('currency'),
|
||||
pending: r.getBoolValue('pending'),
|
||||
isManual: r.getBoolValue('is_manual') ||
|
||||
RegExp(r' ·#\d+$').hasMatch(description),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -669,13 +746,62 @@ class PbSyncService {
|
||||
String s => double.tryParse(s) ?? 0,
|
||||
_ => 0.0,
|
||||
};
|
||||
final remoteManual = remote.getBoolValue('is_manual') ||
|
||||
RegExp(r' ·#\d+$').hasMatch(remote.getStringValue('description'));
|
||||
return remote.getStringValue('date') == tx.date &&
|
||||
remote.getStringValue('description') ==
|
||||
_clip(tx.description.isEmpty ? 'Unknown' : tx.description, 4000) &&
|
||||
(remoteAmount * 100).round() == (tx.amount * 100).round() &&
|
||||
remote.getStringValue('currency').toUpperCase() ==
|
||||
tx.currency.toUpperCase() &&
|
||||
remote.getBoolValue('pending') == tx.pending;
|
||||
remote.getBoolValue('pending') == tx.pending &&
|
||||
remoteManual == tx.isManual;
|
||||
}
|
||||
|
||||
/// Deletes remote bank rows matching [tombstones] by tx_id or field fingerprint.
|
||||
///
|
||||
/// Returns the tombstones that matched at least one remote row (safe to clear).
|
||||
Future<List<BankTransaction>> deleteTransactionsMatching(
|
||||
List<BankTransaction> tombstones,
|
||||
) async {
|
||||
if (tombstones.isEmpty) return const [];
|
||||
|
||||
final userId = _userId;
|
||||
final filter = 'user="$userId"';
|
||||
final existing = await _fullList('transactions', filter);
|
||||
final matchedTombs = <BankTransaction>[];
|
||||
final ops = <_BatchOp>[];
|
||||
final seenRecordIds = <String>{};
|
||||
|
||||
for (final r in existing) {
|
||||
final remoteTx = _bankTxFromRecord(r);
|
||||
if (remoteTx == null) continue;
|
||||
for (final tomb in tombstones) {
|
||||
final txId = r.getStringValue('tx_id');
|
||||
final idHit = txId == _clip(tomb.id, 2000);
|
||||
if (!idHit && !remoteTx.matchesForDelete(tomb)) continue;
|
||||
if (!seenRecordIds.add(r.id)) break;
|
||||
ops.add(_BatchOp.delete(r.id));
|
||||
if (!matchedTombs.any(tomb.matchesForDelete)) {
|
||||
matchedTombs.add(tomb);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ops.isEmpty) {
|
||||
debugPrint(
|
||||
'PbSyncService deleteTransactionsMatching: 0 hits '
|
||||
'for ${tombstones.length} tombstone(s)',
|
||||
);
|
||||
return const [];
|
||||
}
|
||||
await _runWriteOps('transactions', ops);
|
||||
debugPrint(
|
||||
'PbSyncService deleteTransactionsMatching: deleted ${ops.length} '
|
||||
'for ${matchedTombs.length} tombstone(s)',
|
||||
);
|
||||
return matchedTombs;
|
||||
}
|
||||
|
||||
Future<void> _runOne(String collection, _BatchOp op) {
|
||||
@@ -832,6 +958,10 @@ class PbSyncService {
|
||||
filter =
|
||||
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
|
||||
}
|
||||
case 'app_prefs':
|
||||
if (userId != null) {
|
||||
filter = 'user="$userId"';
|
||||
}
|
||||
case 'transactions':
|
||||
final key = body['tx_id'];
|
||||
if (userId != null && key is String) {
|
||||
@@ -1216,6 +1346,7 @@ class PbSyncService {
|
||||
'budget_fixed_amount': w.budgetFixedAmount,
|
||||
'budget_average_months': w.budgetAverageMonths,
|
||||
'label_ids': w.labelIds,
|
||||
'label_match': w.labelMatch.name,
|
||||
'flow': w.flow.name,
|
||||
'amount_range': {
|
||||
if (w.amountRange.exact != null) 'exact': w.amountRange.exact,
|
||||
@@ -1249,6 +1380,36 @@ class PbSyncService {
|
||||
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) {
|
||||
return remote.getStringValue('name') == body['name'] &&
|
||||
remote.getIntValue('color') == body['color'] &&
|
||||
@@ -1329,6 +1490,10 @@ class PbSyncService {
|
||||
remote.getIntValue('budget_average_months', 3) ==
|
||||
w.budgetAverageMonths &&
|
||||
_sameIdList(remoteIds, w.labelIds) &&
|
||||
(remote.getStringValue('label_match').isEmpty
|
||||
? 'and'
|
||||
: remote.getStringValue('label_match')) ==
|
||||
w.labelMatch.name &&
|
||||
remote.getStringValue('flow') == w.flow.name &&
|
||||
asDouble(rangeMap['exact']) == w.amountRange.exact &&
|
||||
asDouble(rangeMap['min']) == w.amountRange.min &&
|
||||
@@ -1339,6 +1504,17 @@ class PbSyncService {
|
||||
remote.getBoolValue('show_amount_out', true) == w.showAmountOut &&
|
||||
remote.getBoolValue('show_count', true) == w.showCount;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
RecurringTemplateSource _parseTemplateSource(String raw) {
|
||||
|
||||
@@ -65,14 +65,7 @@ class BankCache {
|
||||
'balanceType': balance!.balanceType,
|
||||
},
|
||||
'transactions': [
|
||||
for (final tx in transactions)
|
||||
{
|
||||
'date': tx.date,
|
||||
'description': tx.description,
|
||||
'amount': tx.amount,
|
||||
'currency': tx.currency,
|
||||
'pending': tx.pending,
|
||||
},
|
||||
for (final tx in transactions) tx.toJson(),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -258,16 +251,7 @@ class StorageService {
|
||||
}
|
||||
|
||||
Future<void> saveImportedTransactions(List<BankTransaction> txs) async {
|
||||
final encoded = [
|
||||
for (final tx in txs)
|
||||
{
|
||||
'date': tx.date,
|
||||
'description': tx.description,
|
||||
'amount': tx.amount,
|
||||
'currency': tx.currency,
|
||||
'pending': tx.pending,
|
||||
},
|
||||
];
|
||||
final encoded = [for (final tx in txs) tx.toJson()];
|
||||
final json = await compute(jsonEncode, encoded);
|
||||
await _prefs.setString(StorageKeys.importedTransactions, json);
|
||||
}
|
||||
@@ -276,6 +260,53 @@ class StorageService {
|
||||
return _prefs.remove(StorageKeys.importedTransactions);
|
||||
}
|
||||
|
||||
/// Tombstones for locally deleted bank txs awaiting remote removal.
|
||||
///
|
||||
/// Supports legacy string-id lists and full transaction JSON objects.
|
||||
List<BankTransaction> loadPendingTxDeletes() {
|
||||
final raw = _prefs.getString(StorageKeys.pendingTxDeletes);
|
||||
if (raw == null || raw.isEmpty) return const [];
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! List) return const [];
|
||||
final out = <BankTransaction>[];
|
||||
for (final e in decoded) {
|
||||
if (e is Map) {
|
||||
out.add(BankTransaction.fromJson(Map<String, dynamic>.from(e)));
|
||||
} else if (e is String && e.isNotEmpty) {
|
||||
// Legacy id-only entry — match by id string only.
|
||||
final parts = e.split('|');
|
||||
if (parts.length >= 4) {
|
||||
final amount = double.tryParse(parts[2]) ?? 0;
|
||||
out.add(
|
||||
BankTransaction(
|
||||
date: parts[0],
|
||||
currency: parts[1],
|
||||
amount: amount,
|
||||
description: parts.sublist(3).join('|'),
|
||||
pending: false,
|
||||
isManual: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} catch (_) {
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> savePendingTxDeletes(List<BankTransaction> txs) {
|
||||
if (txs.isEmpty) {
|
||||
return _prefs.remove(StorageKeys.pendingTxDeletes);
|
||||
}
|
||||
return _prefs.setString(
|
||||
StorageKeys.pendingTxDeletes,
|
||||
jsonEncode([for (final tx in txs) tx.toJson()]),
|
||||
);
|
||||
}
|
||||
|
||||
TxMetaStoreData loadTxMetaStore() {
|
||||
final raw = _prefs.getString(StorageKeys.txMeta);
|
||||
if (raw != null && raw.isNotEmpty) {
|
||||
|
||||
@@ -12,6 +12,22 @@ abstract final class AppTheme {
|
||||
/// Soft rose for expenses / money out.
|
||||
static const Color expense = Color(0xFFE07A7A);
|
||||
|
||||
/// Amber mid-stop for budget progress (between mint and rose).
|
||||
static const Color budgetWarn = Color(0xFFE5A24A);
|
||||
|
||||
/// Budget chart fill: green when low → amber → red as usage rises.
|
||||
static Color budgetProgressFill(double progress) {
|
||||
final t = progress.clamp(0.0, 1.0);
|
||||
if (t <= 0.55) {
|
||||
// Stay mostly mint through ~half the budget.
|
||||
return Color.lerp(accent, budgetWarn, (t / 0.55) * 0.45)!;
|
||||
}
|
||||
if (t <= 0.85) {
|
||||
return Color.lerp(budgetWarn, expense, (t - 0.55) / 0.30)!;
|
||||
}
|
||||
return Color.lerp(expense, const Color(0xFFD94C4C), (t - 0.85) / 0.15)!;
|
||||
}
|
||||
|
||||
/// Near-black charcoal scaffold (dark).
|
||||
static const Color darkCanvas = Color(0xFF0B0D0C);
|
||||
|
||||
|
||||
@@ -46,6 +46,9 @@ abstract final class StorageKeys {
|
||||
static const bankCache = 'bank_cache_v1';
|
||||
static const importedTransactions = 'imported_txs_v1';
|
||||
|
||||
/// Local bank tx_ids queued for PocketBase deletion (JSON string list).
|
||||
static const pendingTxDeletes = 'pending_tx_deletes_v1';
|
||||
|
||||
/// Serialized PocketBase auth token + user record (separate from tx data).
|
||||
static const pocketBaseAuth = 'pb_auth_v1';
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ List<BankTransaction> applyTransactionFilter({
|
||||
pool,
|
||||
filter.query,
|
||||
labelIds: filter.labelIds,
|
||||
labelMatch: filter.labelMatch,
|
||||
))
|
||||
if (txMatchesFlow(tx, filter.flow) &&
|
||||
txMatchesAmountRange(tx, filter.amountRange))
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
/// Admin-only dialog to create or edit a local test bank transaction.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../models/bank.dart';
|
||||
import '../models/transaction_meta.dart';
|
||||
import '../providers/bank_provider.dart';
|
||||
import '../utils/helpers.dart';
|
||||
|
||||
Future<BankTransaction?> showAdminCreateTransactionDialog(
|
||||
BuildContext context, {
|
||||
BankTransaction? existing,
|
||||
}) {
|
||||
return showDialog<BankTransaction>(
|
||||
context: context,
|
||||
builder: (context) => _AdminCreateTransactionDialog(existing: existing),
|
||||
);
|
||||
}
|
||||
|
||||
String _stripManualStamp(String description) =>
|
||||
description.replaceFirst(RegExp(r' ·#\d+$'), '');
|
||||
|
||||
class _AdminCreateTransactionDialog extends StatefulWidget {
|
||||
const _AdminCreateTransactionDialog({this.existing});
|
||||
|
||||
final BankTransaction? existing;
|
||||
|
||||
@override
|
||||
State<_AdminCreateTransactionDialog> createState() =>
|
||||
_AdminCreateTransactionDialogState();
|
||||
}
|
||||
|
||||
class _AdminCreateTransactionDialogState
|
||||
extends State<_AdminCreateTransactionDialog> {
|
||||
late DateTime _date;
|
||||
late final TextEditingController _description;
|
||||
late final TextEditingController _amount;
|
||||
late final TextEditingController _currency;
|
||||
late TxFlowFilter _flow;
|
||||
late bool _pending;
|
||||
var _saving = false;
|
||||
String? _error;
|
||||
|
||||
bool get _editing => widget.existing != null;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final existing = widget.existing;
|
||||
if (existing != null) {
|
||||
final parsed = DateTime.tryParse(existing.date) ?? DateTime.now();
|
||||
_date = DateTime(parsed.year, parsed.month, parsed.day);
|
||||
_description = TextEditingController(
|
||||
text: _stripManualStamp(existing.description),
|
||||
);
|
||||
_amount = TextEditingController(
|
||||
text: existing.amount.abs().toStringAsFixed(2),
|
||||
);
|
||||
_currency = TextEditingController(text: existing.currency);
|
||||
_flow = existing.amount >= 0
|
||||
? TxFlowFilter.income
|
||||
: TxFlowFilter.expense;
|
||||
_pending = existing.pending;
|
||||
} else {
|
||||
final now = DateTime.now();
|
||||
_date = DateTime(now.year, now.month, now.day);
|
||||
_description = TextEditingController(text: 'Test merchant');
|
||||
_amount = TextEditingController(text: '12.50');
|
||||
_currency = TextEditingController(text: 'EUR');
|
||||
_flow = TxFlowFilter.expense;
|
||||
_pending = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_description.dispose();
|
||||
_amount.dispose();
|
||||
_currency.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _pickDate() async {
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _date,
|
||||
firstDate: DateTime(2015),
|
||||
lastDate: DateTime.now().add(const Duration(days: 365)),
|
||||
);
|
||||
if (picked == null || !mounted) return;
|
||||
setState(() => _date = DateTime(picked.year, picked.month, picked.day));
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final raw = _amount.text.trim().replaceAll(',', '.');
|
||||
final parsed = double.tryParse(raw);
|
||||
if (parsed == null || parsed <= 0) {
|
||||
setState(() => _error = 'Enter a positive amount');
|
||||
return;
|
||||
}
|
||||
final signed = _flow == TxFlowFilter.income ? parsed : -parsed;
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final bank = context.read<BankController>();
|
||||
final existing = widget.existing;
|
||||
final BankTransaction tx;
|
||||
if (existing != null) {
|
||||
tx = await bank.updateManualTransaction(
|
||||
previous: existing,
|
||||
date: _date,
|
||||
description: _description.text,
|
||||
amount: signed,
|
||||
currency: _currency.text,
|
||||
pending: _pending,
|
||||
);
|
||||
} else {
|
||||
tx = await bank.addManualTransaction(
|
||||
date: _date,
|
||||
description: _description.text,
|
||||
amount: signed,
|
||||
currency: _currency.text,
|
||||
pending: _pending,
|
||||
);
|
||||
}
|
||||
if (!mounted) return;
|
||||
Navigator.pop(context, tx);
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = '$error';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
title: Text(_editing ? 'Edit test transaction' : 'Create test transaction'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
_editing
|
||||
? 'Updates this device and removes the old row on the next PocketBase sync.'
|
||||
: 'Saved on this device and included in the next PocketBase sync.',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('Date'),
|
||||
subtitle: Text(formatDate(_date)),
|
||||
trailing: const Icon(Icons.calendar_today_outlined, size: 20),
|
||||
onTap: _saving ? null : _pickDate,
|
||||
),
|
||||
TextField(
|
||||
controller: _description,
|
||||
enabled: !_saving,
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Description',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SegmentedButton<TxFlowFilter>(
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: TxFlowFilter.expense,
|
||||
label: Text('Expense'),
|
||||
icon: Icon(Icons.north_east, size: 16),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: TxFlowFilter.income,
|
||||
label: Text('Income'),
|
||||
icon: Icon(Icons.south_west, size: 16),
|
||||
),
|
||||
],
|
||||
selected: {_flow},
|
||||
onSelectionChanged: _saving
|
||||
? null
|
||||
: (selection) {
|
||||
setState(() => _flow = selection.first);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: TextField(
|
||||
controller: _amount,
|
||||
enabled: !_saving,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
|
||||
],
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Amount',
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _currency,
|
||||
enabled: !_saving,
|
||||
textCapitalization: TextCapitalization.characters,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Currency',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('Pending'),
|
||||
value: _pending,
|
||||
onChanged: _saving
|
||||
? null
|
||||
: (value) => setState(() => _pending = value),
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
_error!,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _saving ? null : () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(_editing ? 'Save' : 'Create'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ class HomeFilterWidgetCard extends StatelessWidget {
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => TransactionsScreen(
|
||||
initialLabelIds: filter.labelIds,
|
||||
initialLabelMatch: filter.labelMatch,
|
||||
initialSearchInMonthOnly:
|
||||
widgetConfig.type == HomeWidgetType.budget || filter.monthOnly,
|
||||
initialQuery: filter.query,
|
||||
@@ -65,28 +66,28 @@ class HomeFilterWidgetCard extends StatelessWidget {
|
||||
child: Card(
|
||||
color: colors.surfaceContainer,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
margin: EdgeInsets.zero,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
onTap: editing ? onEdit : () => _openTransactions(context),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
14,
|
||||
12,
|
||||
14,
|
||||
editing ? 4 : 14,
|
||||
12,
|
||||
14,
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (dragHandle != null) ...[
|
||||
dragHandle!,
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: dragHandle!,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
Icon(
|
||||
widgetConfig.icon,
|
||||
color: colors.primary,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: widgetConfig.type == HomeWidgetType.budget
|
||||
? _BudgetBody(
|
||||
@@ -127,6 +128,139 @@ class HomeFilterWidgetCard extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -150,42 +284,65 @@ class _StatsBody extends StatelessWidget {
|
||||
filter: widgetConfig.filter,
|
||||
);
|
||||
|
||||
// Prefer a single hero "Spent" figure when that's the main metric.
|
||||
final spentOnly = widgetConfig.showAmountOut &&
|
||||
!widgetConfig.showAmountIn &&
|
||||
!widgetConfig.showCount;
|
||||
|
||||
// Avoid LayoutBuilder/Spacer/Expanded here: half-width rows use
|
||||
// IntrinsicHeight, which cannot measure those widgets.
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
widgetConfig.name,
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
_CardHeader(
|
||||
icon: widgetConfig.icon,
|
||||
title: widgetConfig.name,
|
||||
subtitle: _subtitleFor(widgetConfig),
|
||||
),
|
||||
if (spentOnly) ...[
|
||||
const SizedBox(height: 32),
|
||||
Text(
|
||||
'Spent',
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
if (widgetConfig.showAmountIn)
|
||||
_Metric(
|
||||
label: 'In',
|
||||
value: formatMoney(metrics.amountIn, currency),
|
||||
color: AppTheme.accent,
|
||||
),
|
||||
if (widgetConfig.showAmountOut)
|
||||
_Metric(
|
||||
label: 'Out',
|
||||
value: formatMoney(metrics.amountOut, currency),
|
||||
color: AppTheme.expense,
|
||||
),
|
||||
if (widgetConfig.showCount)
|
||||
_Metric(
|
||||
label: 'Txs',
|
||||
value: '${metrics.count}',
|
||||
color: colors.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
formatMoney(metrics.amountOut, currency),
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
color: AppTheme.expense,
|
||||
fontWeight: FontWeight.w700,
|
||||
height: 1.15,
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
if (widgetConfig.showAmountIn)
|
||||
_Metric(
|
||||
label: 'In',
|
||||
value: formatMoney(metrics.amountIn, currency),
|
||||
color: AppTheme.accent,
|
||||
),
|
||||
if (widgetConfig.showAmountOut)
|
||||
_Metric(
|
||||
label: 'Spent',
|
||||
value: formatMoney(metrics.amountOut, currency),
|
||||
color: AppTheme.expense,
|
||||
),
|
||||
if (widgetConfig.showCount)
|
||||
_Metric(
|
||||
label: 'Txs',
|
||||
value: '${metrics.count}',
|
||||
color: colors.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -214,130 +371,366 @@ class _BudgetBody extends StatelessWidget {
|
||||
widget: widgetConfig,
|
||||
);
|
||||
final progress = budget.progress.clamp(0.0, 1.0);
|
||||
final over = budget.overBudget;
|
||||
final fillColor = over ? colors.error : colors.primary;
|
||||
final trackColor = colors.surfaceContainerHighest;
|
||||
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: [
|
||||
Text(
|
||||
widgetConfig.name,
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
_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: 4),
|
||||
Text(
|
||||
'${formatMoney(budget.monthNet, currency)} · '
|
||||
'${formatMoney(budget.used, currency)} / '
|
||||
'${budget.target <= 0 ? '—' : formatMoney(budget.target, currency)}',
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: over ? colors.error : colors.onSurfaceVariant,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const SizedBox(height: 14),
|
||||
switch (widgetConfig.chartStyle) {
|
||||
HomeWidgetChartStyle.bar => ClipRRect(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: LinearProgressIndicator(
|
||||
value: budget.target <= 0 ? 0 : progress,
|
||||
minHeight: 10,
|
||||
backgroundColor: trackColor,
|
||||
color: fillColor,
|
||||
),
|
||||
),
|
||||
HomeWidgetChartStyle.pie || HomeWidgetChartStyle.ring => Row(
|
||||
HomeWidgetChartStyle.bar => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 52,
|
||||
height: 52,
|
||||
child: CustomPaint(
|
||||
painter: _BudgetChartPainter(
|
||||
progress: budget.target <= 0 ? 0 : progress,
|
||||
style: widgetConfig.chartStyle,
|
||||
fillColor: fillColor,
|
||||
trackColor: trackColor,
|
||||
),
|
||||
),
|
||||
_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(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
over
|
||||
? 'Over budget'
|
||||
: budget.target <= 0
|
||||
? 'Set a budget cap'
|
||||
: '${(progress * 100).round()}% of cap',
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: over ? colors.error : colors.onSurfaceVariant,
|
||||
),
|
||||
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) {
|
||||
final rect = Rect.fromCircle(center: center, radius: radius);
|
||||
final track = Paint()..color = trackColor;
|
||||
canvas.drawCircle(center, radius, track);
|
||||
// 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) {
|
||||
final sweep = 2 * math.pi * progress.clamp(0.0, 1.0);
|
||||
final fill = Paint()..color = fillColor;
|
||||
canvas.drawArc(rect, -math.pi / 2, sweep, true, fill);
|
||||
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,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Ring (activity-style).
|
||||
const stroke = 7.0;
|
||||
final trackPaint = Paint()
|
||||
..color = trackColor
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = stroke
|
||||
..strokeCap = StrokeCap.round;
|
||||
final fillPaint = Paint()
|
||||
..color = fillColor
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = stroke
|
||||
..strokeCap = StrokeCap.round;
|
||||
final r = radius - stroke / 2;
|
||||
canvas.drawCircle(center, r, trackPaint);
|
||||
if (progress > 0) {
|
||||
final sweep = 2 * math.pi * progress.clamp(0.0, 1.0);
|
||||
canvas.drawArc(
|
||||
Rect.fromCircle(center: center, radius: r),
|
||||
-math.pi / 2,
|
||||
sweep,
|
||||
false,
|
||||
fillPaint,
|
||||
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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -347,7 +740,10 @@ class _BudgetChartPainter extends CustomPainter {
|
||||
return oldDelegate.progress != progress ||
|
||||
oldDelegate.style != style ||
|
||||
oldDelegate.fillColor != fillColor ||
|
||||
oldDelegate.trackColor != trackColor;
|
||||
oldDelegate.trackColor != trackColor ||
|
||||
oldDelegate.percentLabel != percentLabel ||
|
||||
oldDelegate.labelColor != labelColor ||
|
||||
oldDelegate.labelScale != labelScale;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import '../providers/bank_provider.dart';
|
||||
import '../providers/preferences_provider.dart';
|
||||
import '../providers/tx_meta_provider.dart';
|
||||
import '../widgets/label_filter_dialog.dart';
|
||||
import '../widgets/overview_favourites_sheet.dart' show promptFavouriteName;
|
||||
|
||||
Future<void> showHomeWidgetsSheet(BuildContext context) {
|
||||
return showModalBottomSheet<void>(
|
||||
@@ -50,29 +49,22 @@ Future<HomeFilterWidget?> composeHomeFilterWidget(
|
||||
if (filter == null || !navigator.mounted) return null;
|
||||
}
|
||||
|
||||
if (!navigator.mounted) return null;
|
||||
final name = await promptFavouriteName(
|
||||
navigator.context,
|
||||
initial: existing?.name ?? '',
|
||||
title: existing == null ? 'Name this widget' : 'Rename widget',
|
||||
);
|
||||
if (name == null || !navigator.mounted) return null;
|
||||
|
||||
// Let the name dialog finish popping before presenting options.
|
||||
await WidgetsBinding.instance.endOfFrame;
|
||||
if (!navigator.mounted) return null;
|
||||
|
||||
final draft = existing == null
|
||||
? HomeFilterWidget.fromFilter(name: name, filter: filter)
|
||||
? HomeFilterWidget.fromFilter(name: 'Filter', filter: filter)
|
||||
: existing.copyWith(
|
||||
name: name,
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -80,265 +72,296 @@ Future<HomeFilterWidget?> _promptWidgetMetrics(
|
||||
BuildContext context,
|
||||
HomeFilterWidget draft,
|
||||
) {
|
||||
var type = draft.type;
|
||||
var iconId = draft.iconId;
|
||||
var chartStyle = draft.chartStyle;
|
||||
var budgetCapMode = draft.budgetCapMode;
|
||||
var budgetFixedAmount = draft.budgetFixedAmount;
|
||||
var budgetAverageMonths = draft.budgetAverageMonths;
|
||||
var showIn = draft.showAmountIn;
|
||||
var showOut = draft.showAmountOut;
|
||||
var showCount = draft.showCount;
|
||||
var halfWidth = draft.halfWidth;
|
||||
final amountController = TextEditingController(
|
||||
text: budgetFixedAmount > 0
|
||||
? (budgetFixedAmount == budgetFixedAmount.roundToDouble()
|
||||
? budgetFixedAmount.toStringAsFixed(0)
|
||||
: budgetFixedAmount.toStringAsFixed(2))
|
||||
: '',
|
||||
);
|
||||
|
||||
return showDialog<HomeFilterWidget>(
|
||||
context: context,
|
||||
useRootNavigator: true,
|
||||
builder: (context) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setState) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
title: const Text('Widget options'),
|
||||
content: SizedBox(
|
||||
width: 360,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Type', style: theme.textTheme.titleSmall),
|
||||
const SizedBox(height: 8),
|
||||
SegmentedButton<HomeWidgetType>(
|
||||
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('Amount out'),
|
||||
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>(
|
||||
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
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Average |net| of last',
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 88,
|
||||
child: DropdownButtonFormField<int>(
|
||||
initialValue: budgetAverageMonths,
|
||||
decoration: const InputDecoration(
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
suffixText: 'mo',
|
||||
),
|
||||
items: [
|
||||
for (final n in const [1, 2, 3, 6, 12, 24])
|
||||
DropdownMenuItem(
|
||||
value: n,
|
||||
child: Text('$n'),
|
||||
),
|
||||
],
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setState(
|
||||
() => budgetAverageMonths = value,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text('Chart', style: theme.textTheme.titleSmall),
|
||||
const SizedBox(height: 8),
|
||||
SegmentedButton<HomeWidgetChartStyle>(
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: HomeWidgetChartStyle.bar,
|
||||
label: Text('Bar'),
|
||||
icon: Icon(Icons.linear_scale),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: HomeWidgetChartStyle.pie,
|
||||
label: Text('Pie'),
|
||||
icon: Icon(Icons.pie_chart_outline),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: HomeWidgetChartStyle.ring,
|
||||
label: Text('Ring'),
|
||||
icon: Icon(Icons.donut_large),
|
||||
),
|
||||
],
|
||||
selected: {chartStyle},
|
||||
onSelectionChanged: (value) {
|
||||
setState(() => chartStyle = value.first);
|
||||
},
|
||||
),
|
||||
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,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
if (type == HomeWidgetType.stats &&
|
||||
!showIn &&
|
||||
!showOut &&
|
||||
!showCount) {
|
||||
return;
|
||||
}
|
||||
var fixed = 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(
|
||||
draft.copyWith(
|
||||
type: type,
|
||||
iconId: iconId,
|
||||
chartStyle: chartStyle,
|
||||
budgetCapMode: budgetCapMode,
|
||||
budgetFixedAmount: fixed,
|
||||
budgetAverageMonths: budgetAverageMonths,
|
||||
showAmountIn: showIn,
|
||||
showAmountOut: showOut,
|
||||
showCount: showCount,
|
||||
halfWidth: halfWidth,
|
||||
),
|
||||
);
|
||||
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);
|
||||
},
|
||||
child: const Text('Save'),
|
||||
),
|
||||
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,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
).whenComplete(amountController.dispose);
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _save,
|
||||
child: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HomeWidgetsSheet extends StatelessWidget {
|
||||
@@ -517,7 +540,7 @@ class _HomeWidgetsSheet extends StatelessWidget {
|
||||
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) 'Out',
|
||||
if (w.type == HomeWidgetType.stats && w.showAmountOut) 'Spent',
|
||||
if (w.type == HomeWidgetType.stats && w.showCount) 'Count',
|
||||
if (w.halfWidth) 'Half',
|
||||
];
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'label_parent_picker.dart';
|
||||
class TransactionFilterSelection {
|
||||
const TransactionFilterSelection({
|
||||
required this.labelIds,
|
||||
this.labelMatch = LabelMatchMode.and,
|
||||
this.flow = TxFlowFilter.all,
|
||||
this.amountRange = const TxAmountRange(),
|
||||
this.query = '',
|
||||
@@ -22,6 +23,10 @@ class TransactionFilterSelection {
|
||||
});
|
||||
|
||||
final Set<String> labelIds;
|
||||
|
||||
/// AND vs OR when more than one label is selected.
|
||||
final LabelMatchMode labelMatch;
|
||||
|
||||
final TxFlowFilter flow;
|
||||
final TxAmountRange amountRange;
|
||||
final String query;
|
||||
@@ -497,6 +502,7 @@ class _TransactionFilterDialog extends StatefulWidget {
|
||||
|
||||
class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
|
||||
late final Set<String> _selected;
|
||||
late LabelMatchMode _labelMatch;
|
||||
late TxFlowFilter _flow;
|
||||
late bool _monthOnly;
|
||||
late final TextEditingController _queryController;
|
||||
@@ -510,6 +516,7 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
|
||||
super.initState();
|
||||
final initial = widget.initial;
|
||||
_selected = Set<String>.of(initial.labelIds);
|
||||
_labelMatch = initial.labelMatch;
|
||||
_flow = initial.flow;
|
||||
_monthOnly = initial.monthOnly;
|
||||
_queryController = TextEditingController(text: initial.query);
|
||||
@@ -593,6 +600,7 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
|
||||
context,
|
||||
TransactionFilterSelection(
|
||||
labelIds: Set<String>.of(_selected),
|
||||
labelMatch: _labelMatch,
|
||||
flow: _flow,
|
||||
amountRange: _amountResult,
|
||||
query: _queryController.text.trim(),
|
||||
@@ -840,7 +848,10 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
|
||||
),
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
Row(
|
||||
Wrap(
|
||||
spacing: 0,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
@@ -859,6 +870,27 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
|
||||
onPressed: () => setState(() => _selected.clear()),
|
||||
child: const Text('No labels'),
|
||||
),
|
||||
SegmentedButton<LabelMatchMode>(
|
||||
style: const ButtonStyle(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: LabelMatchMode.and,
|
||||
label: Text('AND'),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: LabelMatchMode.or,
|
||||
label: Text('OR'),
|
||||
),
|
||||
],
|
||||
selected: {_labelMatch},
|
||||
onSelectionChanged: (selection) {
|
||||
setState(() => _labelMatch = selection.first);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
|
||||
@@ -0,0 +1,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 (_) {}
|
||||
});
|
||||
@@ -33,6 +33,22 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
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:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -57,6 +73,22 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
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:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -150,6 +182,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
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:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -200,6 +240,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
image:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: image
|
||||
sha256: "1976370a4df3091bb0f72409c187ad1f9132a818bc6b95ca59c0bae1c75c688e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.9.2"
|
||||
json_annotation:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -328,6 +376,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.25.1"
|
||||
posix:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: posix
|
||||
sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.5.2"
|
||||
provider:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -525,6 +581,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: yaml
|
||||
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.4"
|
||||
sdks:
|
||||
dart: ">=3.13.2 <4.0.0"
|
||||
flutter: ">=3.44.0"
|
||||
|
||||
@@ -53,6 +53,15 @@ dev_dependencies:
|
||||
# package. See that file for information about deactivating specific lint
|
||||
# rules and activating additional ones.
|
||||
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
|
||||
# following page: https://dart.dev/tools/pub/pubspec
|
||||
@@ -68,6 +77,7 @@ flutter:
|
||||
assets:
|
||||
- .env
|
||||
- .env.example
|
||||
- assets/branding/app_icon.png
|
||||
|
||||
# An image asset can refer to one or more resolution-specific "variants", see
|
||||
# https://flutter.dev/to/resolution-aware-images
|
||||
|
||||
@@ -19,12 +19,19 @@ void main() {
|
||||
expect(restored.flow, TxFlowFilter.expense);
|
||||
expect(restored.monthOnly, isTrue);
|
||||
expect(restored.labelIds, ['groceries']);
|
||||
expect(restored.labelMatch, LabelMatchMode.and);
|
||||
expect(restored.showAmountOut, isTrue);
|
||||
expect(restored.showAmountIn, isFalse);
|
||||
expect(restored.showCount, isTrue);
|
||||
expect(restored.halfWidth, isFalse);
|
||||
expect(restored.type, HomeWidgetType.stats);
|
||||
|
||||
final withOr = widget.copyWith(labelMatch: LabelMatchMode.or);
|
||||
expect(
|
||||
HomeFilterWidget.fromJson(withOr.toJson()).labelMatch,
|
||||
LabelMatchMode.or,
|
||||
);
|
||||
|
||||
final budget = widget.copyWith(
|
||||
halfWidth: true,
|
||||
type: HomeWidgetType.budget,
|
||||
|
||||