Compare commits
3
Commits
v1.2
...
86b5f1e09b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86b5f1e09b | ||
|
|
2727f1baf2 | ||
|
|
83295439d5 |
+9
-4
@@ -49,6 +49,7 @@ class MyApp extends StatefulWidget {
|
|||||||
class _MyAppState extends State<MyApp> {
|
class _MyAppState extends State<MyApp> {
|
||||||
late final BankController _bank;
|
late final BankController _bank;
|
||||||
late final TxMetaController _meta;
|
late final TxMetaController _meta;
|
||||||
|
late final PreferencesController _prefs;
|
||||||
late final SyncController _sync;
|
late final SyncController _sync;
|
||||||
late final AppLinks _appLinks;
|
late final AppLinks _appLinks;
|
||||||
StreamSubscription<Uri>? _linkSub;
|
StreamSubscription<Uri>? _linkSub;
|
||||||
@@ -57,8 +58,14 @@ class _MyAppState extends State<MyApp> {
|
|||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_meta = TxMetaController(widget.storage);
|
_meta = TxMetaController(widget.storage);
|
||||||
|
_prefs = PreferencesController(widget.storage);
|
||||||
_bank = BankController(storage: widget.storage)..refresh();
|
_bank = BankController(storage: widget.storage)..refresh();
|
||||||
_sync = SyncController(auth: widget.auth, meta: _meta, bank: _bank);
|
_sync = SyncController(
|
||||||
|
auth: widget.auth,
|
||||||
|
meta: _meta,
|
||||||
|
bank: _bank,
|
||||||
|
prefs: _prefs,
|
||||||
|
);
|
||||||
_appLinks = AppLinks();
|
_appLinks = AppLinks();
|
||||||
_listenForBankRedirects();
|
_listenForBankRedirects();
|
||||||
}
|
}
|
||||||
@@ -97,9 +104,7 @@ class _MyAppState extends State<MyApp> {
|
|||||||
providers: [
|
providers: [
|
||||||
ChangeNotifierProvider<AuthController>.value(value: widget.auth),
|
ChangeNotifierProvider<AuthController>.value(value: widget.auth),
|
||||||
ChangeNotifierProvider(create: (_) => ThemeController(widget.storage)),
|
ChangeNotifierProvider(create: (_) => ThemeController(widget.storage)),
|
||||||
ChangeNotifierProvider(
|
ChangeNotifierProvider<PreferencesController>.value(value: _prefs),
|
||||||
create: (_) => PreferencesController(widget.storage),
|
|
||||||
),
|
|
||||||
ChangeNotifierProvider<TxMetaController>.value(value: _meta),
|
ChangeNotifierProvider<TxMetaController>.value(value: _meta),
|
||||||
ChangeNotifierProvider<SyncController>.value(value: _sync),
|
ChangeNotifierProvider<SyncController>.value(value: _sync),
|
||||||
ChangeNotifierProvider<BankController>.value(value: _bank),
|
ChangeNotifierProvider<BankController>.value(value: _bank),
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/// Visibility flags for built-in Home screen sections.
|
||||||
|
library;
|
||||||
|
|
||||||
|
class HomeBuiltInSections {
|
||||||
|
const HomeBuiltInSections({
|
||||||
|
this.showTransactions = true,
|
||||||
|
this.showCategorized = true,
|
||||||
|
this.showRecent = true,
|
||||||
|
});
|
||||||
|
|
||||||
|
static const defaults = HomeBuiltInSections();
|
||||||
|
|
||||||
|
final bool showTransactions;
|
||||||
|
final bool showCategorized;
|
||||||
|
final bool showRecent;
|
||||||
|
|
||||||
|
HomeBuiltInSections copyWith({
|
||||||
|
bool? showTransactions,
|
||||||
|
bool? showCategorized,
|
||||||
|
bool? showRecent,
|
||||||
|
}) {
|
||||||
|
return HomeBuiltInSections(
|
||||||
|
showTransactions: showTransactions ?? this.showTransactions,
|
||||||
|
showCategorized: showCategorized ?? this.showCategorized,
|
||||||
|
showRecent: showRecent ?? this.showRecent,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
'showTransactions': showTransactions,
|
||||||
|
'showCategorized': showCategorized,
|
||||||
|
'showRecent': showRecent,
|
||||||
|
};
|
||||||
|
|
||||||
|
factory HomeBuiltInSections.fromJson(Map<String, dynamic>? json) {
|
||||||
|
if (json == null) return defaults;
|
||||||
|
return HomeBuiltInSections(
|
||||||
|
showTransactions: json['showTransactions'] as bool? ?? true,
|
||||||
|
showCategorized: json['showCategorized'] as bool? ?? true,
|
||||||
|
showRecent: json['showRecent'] as bool? ?? true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
/// Named transaction-filter widgets pinned on the Home screen.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../widgets/label_filter_dialog.dart';
|
||||||
|
import 'transaction_meta.dart';
|
||||||
|
|
||||||
|
/// What a Home filter widget shows.
|
||||||
|
enum HomeWidgetType {
|
||||||
|
/// In / Out / count metrics.
|
||||||
|
stats,
|
||||||
|
|
||||||
|
/// Progress of this month’s net toward a budget cap.
|
||||||
|
budget,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the budget ceiling is chosen.
|
||||||
|
enum HomeBudgetCapMode {
|
||||||
|
/// User-entered amount (positive).
|
||||||
|
fixed,
|
||||||
|
|
||||||
|
/// Absolute average of monthly nets over the last N months.
|
||||||
|
averageMonths,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Budget progress visualization.
|
||||||
|
enum HomeWidgetChartStyle {
|
||||||
|
bar,
|
||||||
|
pie,
|
||||||
|
ring,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Preset icons users can assign to a Home widget.
|
||||||
|
abstract final class HomeWidgetIcons {
|
||||||
|
static const List<(String id, IconData icon, String label)> all = [
|
||||||
|
('dashboard', Icons.dashboard_outlined, 'Dashboard'),
|
||||||
|
('savings', Icons.savings_outlined, 'Savings'),
|
||||||
|
('wallet', Icons.account_balance_wallet_outlined, 'Wallet'),
|
||||||
|
('cart', Icons.shopping_cart_outlined, 'Shopping'),
|
||||||
|
('bag', Icons.shopping_bag_outlined, 'Bag'),
|
||||||
|
('food', Icons.restaurant_outlined, 'Food'),
|
||||||
|
('bolt', Icons.bolt_outlined, 'Utilities'),
|
||||||
|
('home', Icons.home_work_outlined, 'Home'),
|
||||||
|
('car', Icons.directions_car_outlined, 'Transport'),
|
||||||
|
('bus', Icons.directions_bus_outlined, 'Transit'),
|
||||||
|
('health', Icons.local_hospital_outlined, 'Health'),
|
||||||
|
('sport', Icons.fitness_center_outlined, 'Sport'),
|
||||||
|
('travel', Icons.flight_outlined, 'Travel'),
|
||||||
|
('gift', Icons.card_giftcard_outlined, 'Gifts'),
|
||||||
|
('pets', Icons.pets_outlined, 'Pets'),
|
||||||
|
('work', Icons.work_outline, 'Work'),
|
||||||
|
('pay', Icons.payments_outlined, 'Pay'),
|
||||||
|
('swap', Icons.swap_horiz, 'Transfers'),
|
||||||
|
('chart', Icons.pie_chart_outline, 'Chart'),
|
||||||
|
('flag', Icons.flag_outlined, 'Goal'),
|
||||||
|
];
|
||||||
|
|
||||||
|
static IconData iconFor(String? id) {
|
||||||
|
for (final entry in all) {
|
||||||
|
if (entry.$1 == id) return entry.$2;
|
||||||
|
}
|
||||||
|
return Icons.dashboard_outlined;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String labelFor(String? id) {
|
||||||
|
for (final entry in all) {
|
||||||
|
if (entry.$1 == id) return entry.$3;
|
||||||
|
}
|
||||||
|
return 'Dashboard';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A saved [TransactionFilterSelection] plus Home display options.
|
||||||
|
class HomeFilterWidget {
|
||||||
|
const HomeFilterWidget({
|
||||||
|
required this.id,
|
||||||
|
required this.name,
|
||||||
|
this.display = true,
|
||||||
|
this.sortOrder = 0,
|
||||||
|
this.halfWidth = false,
|
||||||
|
this.type = HomeWidgetType.stats,
|
||||||
|
this.iconId = 'dashboard',
|
||||||
|
this.chartStyle = HomeWidgetChartStyle.bar,
|
||||||
|
this.budgetCapMode = HomeBudgetCapMode.fixed,
|
||||||
|
this.budgetFixedAmount = 0,
|
||||||
|
this.budgetAverageMonths = 3,
|
||||||
|
this.labelIds = const [],
|
||||||
|
this.flow = TxFlowFilter.all,
|
||||||
|
this.amountRange = const TxAmountRange(),
|
||||||
|
this.query = '',
|
||||||
|
this.monthOnly = false,
|
||||||
|
this.showAmountIn = true,
|
||||||
|
this.showAmountOut = true,
|
||||||
|
this.showCount = true,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final bool display;
|
||||||
|
final int sortOrder;
|
||||||
|
|
||||||
|
/// When true, the Home card uses half the row width.
|
||||||
|
final bool halfWidth;
|
||||||
|
|
||||||
|
final HomeWidgetType type;
|
||||||
|
final String iconId;
|
||||||
|
final HomeWidgetChartStyle chartStyle;
|
||||||
|
final HomeBudgetCapMode budgetCapMode;
|
||||||
|
|
||||||
|
/// Positive ceiling when [budgetCapMode] is [HomeBudgetCapMode.fixed].
|
||||||
|
final double budgetFixedAmount;
|
||||||
|
|
||||||
|
/// Months of history when [budgetCapMode] is [HomeBudgetCapMode.averageMonths].
|
||||||
|
final int budgetAverageMonths;
|
||||||
|
|
||||||
|
final List<String> labelIds;
|
||||||
|
final TxFlowFilter flow;
|
||||||
|
final TxAmountRange amountRange;
|
||||||
|
final String query;
|
||||||
|
final bool monthOnly;
|
||||||
|
|
||||||
|
final bool showAmountIn;
|
||||||
|
final bool showAmountOut;
|
||||||
|
final bool showCount;
|
||||||
|
|
||||||
|
IconData get icon => HomeWidgetIcons.iconFor(iconId);
|
||||||
|
|
||||||
|
TransactionFilterSelection get filter => TransactionFilterSelection(
|
||||||
|
labelIds: labelIds.toSet(),
|
||||||
|
flow: flow,
|
||||||
|
amountRange: amountRange,
|
||||||
|
query: query,
|
||||||
|
monthOnly: monthOnly,
|
||||||
|
);
|
||||||
|
|
||||||
|
HomeFilterWidget copyWith({
|
||||||
|
String? id,
|
||||||
|
String? name,
|
||||||
|
bool? display,
|
||||||
|
int? sortOrder,
|
||||||
|
bool? halfWidth,
|
||||||
|
HomeWidgetType? type,
|
||||||
|
String? iconId,
|
||||||
|
HomeWidgetChartStyle? chartStyle,
|
||||||
|
HomeBudgetCapMode? budgetCapMode,
|
||||||
|
double? budgetFixedAmount,
|
||||||
|
int? budgetAverageMonths,
|
||||||
|
List<String>? labelIds,
|
||||||
|
TxFlowFilter? flow,
|
||||||
|
TxAmountRange? amountRange,
|
||||||
|
String? query,
|
||||||
|
bool? monthOnly,
|
||||||
|
bool? showAmountIn,
|
||||||
|
bool? showAmountOut,
|
||||||
|
bool? showCount,
|
||||||
|
}) {
|
||||||
|
return HomeFilterWidget(
|
||||||
|
id: id ?? this.id,
|
||||||
|
name: name ?? this.name,
|
||||||
|
display: display ?? this.display,
|
||||||
|
sortOrder: sortOrder ?? this.sortOrder,
|
||||||
|
halfWidth: halfWidth ?? this.halfWidth,
|
||||||
|
type: type ?? this.type,
|
||||||
|
iconId: iconId ?? this.iconId,
|
||||||
|
chartStyle: chartStyle ?? this.chartStyle,
|
||||||
|
budgetCapMode: budgetCapMode ?? this.budgetCapMode,
|
||||||
|
budgetFixedAmount: budgetFixedAmount ?? this.budgetFixedAmount,
|
||||||
|
budgetAverageMonths: budgetAverageMonths ?? this.budgetAverageMonths,
|
||||||
|
labelIds: labelIds ?? this.labelIds,
|
||||||
|
flow: flow ?? this.flow,
|
||||||
|
amountRange: amountRange ?? this.amountRange,
|
||||||
|
query: query ?? this.query,
|
||||||
|
monthOnly: monthOnly ?? this.monthOnly,
|
||||||
|
showAmountIn: showAmountIn ?? this.showAmountIn,
|
||||||
|
showAmountOut: showAmountOut ?? this.showAmountOut,
|
||||||
|
showCount: showCount ?? this.showCount,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static HomeFilterWidget fromFilter({
|
||||||
|
required String name,
|
||||||
|
required TransactionFilterSelection filter,
|
||||||
|
bool display = true,
|
||||||
|
int sortOrder = 0,
|
||||||
|
}) {
|
||||||
|
final showIn = filter.flow != TxFlowFilter.expense;
|
||||||
|
final showOut = filter.flow != TxFlowFilter.income;
|
||||||
|
return HomeFilterWidget(
|
||||||
|
id: 'hw_${DateTime.now().millisecondsSinceEpoch}',
|
||||||
|
name: name,
|
||||||
|
display: display,
|
||||||
|
sortOrder: sortOrder,
|
||||||
|
labelIds: filter.labelIds.toList(growable: false),
|
||||||
|
flow: filter.flow,
|
||||||
|
amountRange: filter.amountRange,
|
||||||
|
query: filter.query,
|
||||||
|
monthOnly: filter.monthOnly,
|
||||||
|
showAmountIn: showIn,
|
||||||
|
showAmountOut: showOut,
|
||||||
|
showCount: true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
'id': id,
|
||||||
|
'name': name,
|
||||||
|
'display': display,
|
||||||
|
'sortOrder': sortOrder,
|
||||||
|
'halfWidth': halfWidth,
|
||||||
|
'type': type.name,
|
||||||
|
'iconId': iconId,
|
||||||
|
'chartStyle': chartStyle.name,
|
||||||
|
'budgetCapMode': budgetCapMode.name,
|
||||||
|
'budgetFixedAmount': budgetFixedAmount,
|
||||||
|
'budgetAverageMonths': budgetAverageMonths,
|
||||||
|
'labelIds': labelIds,
|
||||||
|
'flow': flow.name,
|
||||||
|
'amountRange': {
|
||||||
|
if (amountRange.exact != null) 'exact': amountRange.exact,
|
||||||
|
if (amountRange.min != null) 'min': amountRange.min,
|
||||||
|
if (amountRange.max != null) 'max': amountRange.max,
|
||||||
|
},
|
||||||
|
'query': query,
|
||||||
|
'monthOnly': monthOnly,
|
||||||
|
'showAmountIn': showAmountIn,
|
||||||
|
'showAmountOut': showAmountOut,
|
||||||
|
'showCount': showCount,
|
||||||
|
};
|
||||||
|
|
||||||
|
factory HomeFilterWidget.fromJson(Map<String, dynamic> json) {
|
||||||
|
final rangeRaw = json['amountRange'];
|
||||||
|
final rangeMap = rangeRaw is Map
|
||||||
|
? Map<String, dynamic>.from(rangeRaw)
|
||||||
|
: const <String, dynamic>{};
|
||||||
|
double? asDouble(dynamic value) {
|
||||||
|
if (value is num) return value.toDouble();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int asInt(dynamic value, int fallback) {
|
||||||
|
if (value is int) return value;
|
||||||
|
if (value is num) return value.round();
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
return HomeFilterWidget(
|
||||||
|
id: json['id'] as String? ??
|
||||||
|
'hw_${DateTime.now().millisecondsSinceEpoch}',
|
||||||
|
name: (json['name'] as String?)?.trim().isNotEmpty == true
|
||||||
|
? (json['name'] as String).trim()
|
||||||
|
: 'Filter',
|
||||||
|
display: json['display'] as bool? ?? true,
|
||||||
|
sortOrder: asInt(json['sortOrder'], 0),
|
||||||
|
halfWidth: json['halfWidth'] as bool? ?? false,
|
||||||
|
type: HomeWidgetType.values.firstWhere(
|
||||||
|
(e) => e.name == json['type'],
|
||||||
|
orElse: () => HomeWidgetType.stats,
|
||||||
|
),
|
||||||
|
iconId: (json['iconId'] as String?)?.trim().isNotEmpty == true
|
||||||
|
? (json['iconId'] as String).trim()
|
||||||
|
: 'dashboard',
|
||||||
|
chartStyle: HomeWidgetChartStyle.values.firstWhere(
|
||||||
|
(e) => e.name == json['chartStyle'],
|
||||||
|
orElse: () => HomeWidgetChartStyle.bar,
|
||||||
|
),
|
||||||
|
budgetCapMode: HomeBudgetCapMode.values.firstWhere(
|
||||||
|
(e) => e.name == json['budgetCapMode'],
|
||||||
|
orElse: () => HomeBudgetCapMode.fixed,
|
||||||
|
),
|
||||||
|
budgetFixedAmount: asDouble(json['budgetFixedAmount']) ?? 0,
|
||||||
|
budgetAverageMonths: asInt(json['budgetAverageMonths'], 3).clamp(1, 36),
|
||||||
|
labelIds: [
|
||||||
|
for (final id in (json['labelIds'] as List? ?? const []))
|
||||||
|
if (id is String && id.isNotEmpty) id,
|
||||||
|
],
|
||||||
|
flow: TxFlowFilter.values.firstWhere(
|
||||||
|
(e) => e.name == json['flow'],
|
||||||
|
orElse: () => TxFlowFilter.all,
|
||||||
|
),
|
||||||
|
amountRange: TxAmountRange(
|
||||||
|
exact: asDouble(rangeMap['exact']),
|
||||||
|
min: asDouble(rangeMap['min']),
|
||||||
|
max: asDouble(rangeMap['max']),
|
||||||
|
),
|
||||||
|
query: json['query'] as String? ?? '',
|
||||||
|
monthOnly: json['monthOnly'] as bool? ?? false,
|
||||||
|
showAmountIn: json['showAmountIn'] as bool? ?? true,
|
||||||
|
showAmountOut: json['showAmountOut'] as bool? ?? true,
|
||||||
|
showCount: json['showCount'] as bool? ?? true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Union home widgets by id (local wins on conflict).
|
||||||
|
List<HomeFilterWidget> mergeHomeFilterWidgets(
|
||||||
|
List<HomeFilterWidget> local,
|
||||||
|
List<HomeFilterWidget> remote,
|
||||||
|
) {
|
||||||
|
final byId = <String, HomeFilterWidget>{
|
||||||
|
for (final w in remote) w.id: w,
|
||||||
|
};
|
||||||
|
for (final w in local) {
|
||||||
|
byId[w.id] = w;
|
||||||
|
}
|
||||||
|
final merged = byId.values.toList()
|
||||||
|
..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
/// Named Overview chart filter snapshots (local favourites).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import '../models/transaction_meta.dart';
|
||||||
|
import '../widgets/label_filter_dialog.dart';
|
||||||
|
|
||||||
|
/// Persisted Overview lens: period, metric, and Labels-chart options.
|
||||||
|
class OverviewFavourite {
|
||||||
|
const OverviewFavourite({
|
||||||
|
required this.id,
|
||||||
|
required this.name,
|
||||||
|
this.display = true,
|
||||||
|
this.metric = OverviewMetricMode.flow,
|
||||||
|
this.period = OverviewPeriodMode.monthly,
|
||||||
|
this.labelIds = const [],
|
||||||
|
this.flow = TxFlowFilter.expense,
|
||||||
|
this.barStyle = LabelChartBarStyle.parallel,
|
||||||
|
this.invertExpensePerspective = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
/// When true, this favourite appears on the Favourites overview view.
|
||||||
|
final bool display;
|
||||||
|
|
||||||
|
final OverviewMetricMode metric;
|
||||||
|
final OverviewPeriodMode period;
|
||||||
|
|
||||||
|
/// Empty = all labels (Labels metric only).
|
||||||
|
final List<String> labelIds;
|
||||||
|
|
||||||
|
final TxFlowFilter flow;
|
||||||
|
final LabelChartBarStyle barStyle;
|
||||||
|
final bool invertExpensePerspective;
|
||||||
|
|
||||||
|
OverviewFavourite copyWith({
|
||||||
|
String? id,
|
||||||
|
String? name,
|
||||||
|
bool? display,
|
||||||
|
OverviewMetricMode? metric,
|
||||||
|
OverviewPeriodMode? period,
|
||||||
|
List<String>? labelIds,
|
||||||
|
TxFlowFilter? flow,
|
||||||
|
LabelChartBarStyle? barStyle,
|
||||||
|
bool? invertExpensePerspective,
|
||||||
|
}) {
|
||||||
|
return OverviewFavourite(
|
||||||
|
id: id ?? this.id,
|
||||||
|
name: name ?? this.name,
|
||||||
|
display: display ?? this.display,
|
||||||
|
metric: metric ?? this.metric,
|
||||||
|
period: period ?? this.period,
|
||||||
|
labelIds: labelIds ?? this.labelIds,
|
||||||
|
flow: flow ?? this.flow,
|
||||||
|
barStyle: barStyle ?? this.barStyle,
|
||||||
|
invertExpensePerspective:
|
||||||
|
invertExpensePerspective ?? this.invertExpensePerspective,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
'id': id,
|
||||||
|
'name': name,
|
||||||
|
'display': display,
|
||||||
|
'metric': metric.name,
|
||||||
|
'period': period.name,
|
||||||
|
'labelIds': labelIds,
|
||||||
|
'flow': flow.name,
|
||||||
|
'barStyle': barStyle.name,
|
||||||
|
'invertExpensePerspective': invertExpensePerspective,
|
||||||
|
};
|
||||||
|
|
||||||
|
factory OverviewFavourite.fromJson(Map<String, dynamic> json) {
|
||||||
|
return OverviewFavourite(
|
||||||
|
id: json['id'] as String? ?? 'fav_${DateTime.now().millisecondsSinceEpoch}',
|
||||||
|
name: (json['name'] as String?)?.trim().isNotEmpty == true
|
||||||
|
? (json['name'] as String).trim()
|
||||||
|
: 'Favourite',
|
||||||
|
display: json['display'] as bool? ?? true,
|
||||||
|
metric: OverviewMetricMode.values.firstWhere(
|
||||||
|
(e) => e.name == json['metric'],
|
||||||
|
orElse: () => OverviewMetricMode.flow,
|
||||||
|
),
|
||||||
|
period: OverviewPeriodMode.values.firstWhere(
|
||||||
|
(e) => e.name == json['period'],
|
||||||
|
orElse: () => OverviewPeriodMode.monthly,
|
||||||
|
),
|
||||||
|
labelIds: [
|
||||||
|
for (final id in (json['labelIds'] as List? ?? const []))
|
||||||
|
if (id is String && id.isNotEmpty) id,
|
||||||
|
],
|
||||||
|
flow: TxFlowFilter.values.firstWhere(
|
||||||
|
(e) => e.name == json['flow'],
|
||||||
|
orElse: () => TxFlowFilter.expense,
|
||||||
|
),
|
||||||
|
barStyle: LabelChartBarStyle.values.firstWhere(
|
||||||
|
(e) => e.name == json['barStyle'],
|
||||||
|
orElse: () => LabelChartBarStyle.parallel,
|
||||||
|
),
|
||||||
|
invertExpensePerspective:
|
||||||
|
json['invertExpensePerspective'] as bool? ?? false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum OverviewMetricMode { flow, labels }
|
||||||
|
|
||||||
|
enum OverviewPeriodMode { monthly, yearly }
|
||||||
@@ -1,21 +1,83 @@
|
|||||||
/// App preferences beyond theme (Look ahead horizon, etc.).
|
/// App preferences beyond theme (Look ahead, Overview favourites, Home widgets).
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
import '../models/home_built_in_sections.dart';
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
|
import '../models/overview_favourite.dart';
|
||||||
import '../services/storage_service.dart';
|
import '../services/storage_service.dart';
|
||||||
|
|
||||||
class PreferencesController extends ChangeNotifier {
|
class PreferencesController extends ChangeNotifier {
|
||||||
PreferencesController(this._storage) {
|
PreferencesController(this._storage) {
|
||||||
_lookAheadMaxYears = _storage.lookAheadMaxYears;
|
_lookAheadMaxYears = _storage.lookAheadMaxYears;
|
||||||
|
_overviewFavourites = _storage.loadOverviewFavourites();
|
||||||
|
_homeFilterWidgets = _storage.loadHomeFilterWidgets();
|
||||||
|
_homeBuiltInSections = _storage.loadHomeBuiltInSections();
|
||||||
}
|
}
|
||||||
|
|
||||||
final StorageService _storage;
|
final StorageService _storage;
|
||||||
late int _lookAheadMaxYears;
|
late int _lookAheadMaxYears;
|
||||||
|
late List<OverviewFavourite> _overviewFavourites;
|
||||||
|
late List<HomeFilterWidget> _homeFilterWidgets;
|
||||||
|
late HomeBuiltInSections _homeBuiltInSections;
|
||||||
|
|
||||||
|
/// Fired after favourites are persisted (for cloud push debounce).
|
||||||
|
VoidCallback? onFavouritesPersisted;
|
||||||
|
|
||||||
|
/// Fired after Home widgets are persisted (for cloud push debounce).
|
||||||
|
VoidCallback? onHomeWidgetsPersisted;
|
||||||
|
|
||||||
/// Years ahead Look ahead can navigate (1–30, default 5).
|
/// Years ahead Look ahead can navigate (1–30, default 5).
|
||||||
int get lookAheadMaxYears => _lookAheadMaxYears;
|
int get lookAheadMaxYears => _lookAheadMaxYears;
|
||||||
|
|
||||||
|
List<OverviewFavourite> get overviewFavourites =>
|
||||||
|
List.unmodifiable(_overviewFavourites);
|
||||||
|
|
||||||
|
List<OverviewFavourite> get displayedOverviewFavourites => [
|
||||||
|
for (final fav in _overviewFavourites)
|
||||||
|
if (fav.display) fav,
|
||||||
|
];
|
||||||
|
|
||||||
|
bool get hasDisplayedOverviewFavourites =>
|
||||||
|
_overviewFavourites.any((f) => f.display);
|
||||||
|
|
||||||
|
List<HomeFilterWidget> get homeFilterWidgets =>
|
||||||
|
List.unmodifiable(_homeFilterWidgets);
|
||||||
|
|
||||||
|
List<HomeFilterWidget> get displayedHomeFilterWidgets => [
|
||||||
|
for (final w in _homeFilterWidgets)
|
||||||
|
if (w.display) w,
|
||||||
|
];
|
||||||
|
|
||||||
|
bool get hasDisplayedHomeFilterWidgets =>
|
||||||
|
_homeFilterWidgets.any((w) => w.display);
|
||||||
|
|
||||||
|
HomeBuiltInSections get homeBuiltInSections => _homeBuiltInSections;
|
||||||
|
|
||||||
|
Future<void> setHomeBuiltInSections(HomeBuiltInSections sections) async {
|
||||||
|
if (sections.showTransactions == _homeBuiltInSections.showTransactions &&
|
||||||
|
sections.showCategorized == _homeBuiltInSections.showCategorized &&
|
||||||
|
sections.showRecent == _homeBuiltInSections.showRecent) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_homeBuiltInSections = sections;
|
||||||
|
notifyListeners();
|
||||||
|
await _storage.saveHomeBuiltInSections(sections);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setHomeShowTransactions(bool value) => setHomeBuiltInSections(
|
||||||
|
_homeBuiltInSections.copyWith(showTransactions: value),
|
||||||
|
);
|
||||||
|
|
||||||
|
Future<void> setHomeShowCategorized(bool value) => setHomeBuiltInSections(
|
||||||
|
_homeBuiltInSections.copyWith(showCategorized: value),
|
||||||
|
);
|
||||||
|
|
||||||
|
Future<void> setHomeShowRecent(bool value) => setHomeBuiltInSections(
|
||||||
|
_homeBuiltInSections.copyWith(showRecent: value),
|
||||||
|
);
|
||||||
|
|
||||||
Future<void> setLookAheadMaxYears(int years) async {
|
Future<void> setLookAheadMaxYears(int years) async {
|
||||||
final next = years.clamp(1, 30);
|
final next = years.clamp(1, 30);
|
||||||
if (next == _lookAheadMaxYears) return;
|
if (next == _lookAheadMaxYears) return;
|
||||||
@@ -23,4 +85,131 @@ class PreferencesController extends ChangeNotifier {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
await _storage.setLookAheadMaxYears(next);
|
await _storage.setLookAheadMaxYears(next);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> addOverviewFavourite(OverviewFavourite favourite) async {
|
||||||
|
_overviewFavourites = [..._overviewFavourites, favourite];
|
||||||
|
notifyListeners();
|
||||||
|
await _persistFavourites();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> updateOverviewFavourite(OverviewFavourite favourite) async {
|
||||||
|
final index = _overviewFavourites.indexWhere((f) => f.id == favourite.id);
|
||||||
|
if (index < 0) return;
|
||||||
|
final next = [..._overviewFavourites];
|
||||||
|
next[index] = favourite;
|
||||||
|
_overviewFavourites = next;
|
||||||
|
notifyListeners();
|
||||||
|
await _persistFavourites();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> removeOverviewFavourite(String id) async {
|
||||||
|
final next = [
|
||||||
|
for (final fav in _overviewFavourites)
|
||||||
|
if (fav.id != id) fav,
|
||||||
|
];
|
||||||
|
if (next.length == _overviewFavourites.length) return;
|
||||||
|
_overviewFavourites = next;
|
||||||
|
notifyListeners();
|
||||||
|
await _persistFavourites();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setOverviewFavouriteDisplay(String id, bool display) async {
|
||||||
|
final index = _overviewFavourites.indexWhere((f) => f.id == id);
|
||||||
|
if (index < 0) return;
|
||||||
|
final current = _overviewFavourites[index];
|
||||||
|
if (current.display == display) return;
|
||||||
|
await updateOverviewFavourite(current.copyWith(display: display));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> replaceOverviewFavourites(
|
||||||
|
List<OverviewFavourite> favourites, {
|
||||||
|
bool notify = true,
|
||||||
|
bool schedulePush = false,
|
||||||
|
}) async {
|
||||||
|
_overviewFavourites = List.of(favourites);
|
||||||
|
if (notify) notifyListeners();
|
||||||
|
await _storage.saveOverviewFavourites(_overviewFavourites);
|
||||||
|
if (schedulePush) onFavouritesPersisted?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> addHomeFilterWidget(HomeFilterWidget widget) async {
|
||||||
|
final order = _homeFilterWidgets.isEmpty
|
||||||
|
? 0
|
||||||
|
: _homeFilterWidgets
|
||||||
|
.map((w) => w.sortOrder)
|
||||||
|
.reduce((a, b) => a > b ? a : b) +
|
||||||
|
1;
|
||||||
|
_homeFilterWidgets = [
|
||||||
|
..._homeFilterWidgets,
|
||||||
|
widget.copyWith(sortOrder: widget.sortOrder == 0 ? order : widget.sortOrder),
|
||||||
|
];
|
||||||
|
notifyListeners();
|
||||||
|
await _persistHomeWidgets();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> updateHomeFilterWidget(HomeFilterWidget widget) async {
|
||||||
|
final index = _homeFilterWidgets.indexWhere((w) => w.id == widget.id);
|
||||||
|
if (index < 0) return;
|
||||||
|
final next = [..._homeFilterWidgets];
|
||||||
|
next[index] = widget;
|
||||||
|
next.sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
|
||||||
|
_homeFilterWidgets = next;
|
||||||
|
notifyListeners();
|
||||||
|
await _persistHomeWidgets();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> removeHomeFilterWidget(String id) async {
|
||||||
|
final next = [
|
||||||
|
for (final w in _homeFilterWidgets)
|
||||||
|
if (w.id != id) w,
|
||||||
|
];
|
||||||
|
if (next.length == _homeFilterWidgets.length) return;
|
||||||
|
_homeFilterWidgets = next;
|
||||||
|
notifyListeners();
|
||||||
|
await _persistHomeWidgets();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setHomeFilterWidgetDisplay(String id, bool display) async {
|
||||||
|
final index = _homeFilterWidgets.indexWhere((w) => w.id == id);
|
||||||
|
if (index < 0) return;
|
||||||
|
final current = _homeFilterWidgets[index];
|
||||||
|
if (current.display == display) return;
|
||||||
|
await updateHomeFilterWidget(current.copyWith(display: display));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> reorderHomeFilterWidgets(int oldIndex, int newIndex) async {
|
||||||
|
if (oldIndex == newIndex) return;
|
||||||
|
final next = [..._homeFilterWidgets];
|
||||||
|
final item = next.removeAt(oldIndex);
|
||||||
|
final target = newIndex.clamp(0, next.length);
|
||||||
|
next.insert(target, item);
|
||||||
|
_homeFilterWidgets = [
|
||||||
|
for (var i = 0; i < next.length; i++) next[i].copyWith(sortOrder: i),
|
||||||
|
];
|
||||||
|
notifyListeners();
|
||||||
|
await _persistHomeWidgets();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> replaceHomeFilterWidgets(
|
||||||
|
List<HomeFilterWidget> widgets, {
|
||||||
|
bool notify = true,
|
||||||
|
bool schedulePush = false,
|
||||||
|
}) async {
|
||||||
|
final next = List.of(widgets)
|
||||||
|
..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
|
||||||
|
_homeFilterWidgets = next;
|
||||||
|
if (notify) notifyListeners();
|
||||||
|
await _storage.saveHomeFilterWidgets(_homeFilterWidgets);
|
||||||
|
if (schedulePush) onHomeWidgetsPersisted?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _persistFavourites() async {
|
||||||
|
await _storage.saveOverviewFavourites(_overviewFavourites);
|
||||||
|
onFavouritesPersisted?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _persistHomeWidgets() async {
|
||||||
|
await _storage.saveHomeFilterWidgets(_homeFilterWidgets);
|
||||||
|
onHomeWidgetsPersisted?.call();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ import 'dart:async';
|
|||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
|
import '../models/overview_favourite.dart';
|
||||||
import '../services/pb_sync_service.dart';
|
import '../services/pb_sync_service.dart';
|
||||||
import 'auth_provider.dart';
|
import 'auth_provider.dart';
|
||||||
import 'bank_provider.dart';
|
import 'bank_provider.dart';
|
||||||
|
import 'preferences_provider.dart';
|
||||||
import 'tx_meta_provider.dart';
|
import 'tx_meta_provider.dart';
|
||||||
|
|
||||||
/// User-visible sync toast state (watched by [SyncFeedbackListener]).
|
/// User-visible sync toast state (watched by [SyncFeedbackListener]).
|
||||||
@@ -30,11 +33,15 @@ class SyncController extends ChangeNotifier {
|
|||||||
required AuthController auth,
|
required AuthController auth,
|
||||||
required TxMetaController meta,
|
required TxMetaController meta,
|
||||||
required BankController bank,
|
required BankController bank,
|
||||||
|
required PreferencesController prefs,
|
||||||
}) : _auth = auth,
|
}) : _auth = auth,
|
||||||
_meta = meta,
|
_meta = meta,
|
||||||
_bank = bank {
|
_bank = bank,
|
||||||
|
_prefs = prefs {
|
||||||
_wasLoggedIn = auth.isLoggedIn;
|
_wasLoggedIn = auth.isLoggedIn;
|
||||||
_meta.onPersisted = _schedulePush;
|
_meta.onPersisted = _scheduleMetaPush;
|
||||||
|
_prefs.onFavouritesPersisted = _scheduleFavouritesPush;
|
||||||
|
_prefs.onHomeWidgetsPersisted = _scheduleHomeWidgetsPush;
|
||||||
_auth.addListener(_onAuthChanged);
|
_auth.addListener(_onAuthChanged);
|
||||||
_bank.onAfterSuccessfulLoad = _onBankDataLoaded;
|
_bank.onAfterSuccessfulLoad = _onBankDataLoaded;
|
||||||
if (_auth.isLoggedIn) {
|
if (_auth.isLoggedIn) {
|
||||||
@@ -45,11 +52,15 @@ class SyncController extends ChangeNotifier {
|
|||||||
final AuthController _auth;
|
final AuthController _auth;
|
||||||
final TxMetaController _meta;
|
final TxMetaController _meta;
|
||||||
final BankController _bank;
|
final BankController _bank;
|
||||||
|
final PreferencesController _prefs;
|
||||||
|
|
||||||
bool _wasLoggedIn = false;
|
bool _wasLoggedIn = false;
|
||||||
bool _syncing = false;
|
bool _syncing = false;
|
||||||
bool _pushQueued = false;
|
bool _pushQueued = false;
|
||||||
bool _queuedFullSync = false;
|
bool _queuedFullSync = false;
|
||||||
|
bool _pushMetaPending = false;
|
||||||
|
bool _pushFavouritesPending = false;
|
||||||
|
bool _pushHomeWidgetsPending = false;
|
||||||
Timer? _pushDebounce;
|
Timer? _pushDebounce;
|
||||||
Timer? _progressHold;
|
Timer? _progressHold;
|
||||||
Timer? _uiNotifyThrottle;
|
Timer? _uiNotifyThrottle;
|
||||||
@@ -179,6 +190,10 @@ class SyncController extends ChangeNotifier {
|
|||||||
_progressHold?.cancel();
|
_progressHold?.cancel();
|
||||||
_uiNotifyThrottle?.cancel();
|
_uiNotifyThrottle?.cancel();
|
||||||
_uiNotifyQueued = false;
|
_uiNotifyQueued = false;
|
||||||
|
_pushQueued = false;
|
||||||
|
_pushMetaPending = false;
|
||||||
|
_pushFavouritesPending = false;
|
||||||
|
_pushHomeWidgetsPending = false;
|
||||||
_lastError = null;
|
_lastError = null;
|
||||||
_statusDetail = '';
|
_statusDetail = '';
|
||||||
_showProgressRing = false;
|
_showProgressRing = false;
|
||||||
@@ -216,8 +231,27 @@ class SyncController extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _schedulePush() {
|
void _scheduleMetaPush() {
|
||||||
|
_pushMetaPending = true;
|
||||||
|
_armPushDebounce();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleFavouritesPush() {
|
||||||
|
_pushFavouritesPending = true;
|
||||||
|
_armPushDebounce();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleHomeWidgetsPush() {
|
||||||
|
_pushHomeWidgetsPending = true;
|
||||||
|
_armPushDebounce();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _armPushDebounce() {
|
||||||
if (!_auth.isLoggedIn) return;
|
if (!_auth.isLoggedIn) return;
|
||||||
|
if (_syncing) {
|
||||||
|
_pushQueued = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
_pushDebounce?.cancel();
|
_pushDebounce?.cancel();
|
||||||
_pushDebounce = Timer(const Duration(seconds: 2), () {
|
_pushDebounce = Timer(const Duration(seconds: 2), () {
|
||||||
unawaited(_pushOnly());
|
unawaited(_pushOnly());
|
||||||
@@ -260,20 +294,77 @@ class SyncController extends ChangeNotifier {
|
|||||||
_setProgress(0.5);
|
_setProgress(0.5);
|
||||||
_setStatus('Merging…');
|
_setStatus('Merging…');
|
||||||
final mergedMeta = mergeTxMetaStores(_meta.exportStore(), remoteMeta);
|
final mergedMeta = mergeTxMetaStores(_meta.exportStore(), remoteMeta);
|
||||||
|
List<OverviewFavourite> remoteFavourites = const [];
|
||||||
|
try {
|
||||||
|
remoteFavourites = await service.pullOverviewFavourites(
|
||||||
|
onStatus: _setStatus,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
debugPrint(
|
||||||
|
'SyncController: overview_favourites pull skipped ($error)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final mergedFavourites = mergeOverviewFavourites(
|
||||||
|
_prefs.overviewFavourites,
|
||||||
|
remoteFavourites,
|
||||||
|
);
|
||||||
|
List<HomeFilterWidget> remoteHomeWidgets = const [];
|
||||||
|
try {
|
||||||
|
remoteHomeWidgets = await service.pullHomeFilterWidgets(
|
||||||
|
onStatus: _setStatus,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
debugPrint(
|
||||||
|
'SyncController: home_filter_widgets pull skipped ($error)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final mergedHomeWidgets = mergeHomeFilterWidgets(
|
||||||
|
_prefs.homeFilterWidgets,
|
||||||
|
remoteHomeWidgets,
|
||||||
|
);
|
||||||
// Apply without notifying — one rebuild after both stores are ready.
|
// Apply without notifying — one rebuild after both stores are ready.
|
||||||
await _meta.replaceStore(mergedMeta, notify: false);
|
await _meta.replaceStore(mergedMeta, notify: false);
|
||||||
await _bank.applySyncedTransactions(remoteTxs, notify: false);
|
await _bank.applySyncedTransactions(remoteTxs, notify: false);
|
||||||
|
await _prefs.replaceOverviewFavourites(
|
||||||
|
mergedFavourites,
|
||||||
|
notify: false,
|
||||||
|
);
|
||||||
|
await _prefs.replaceHomeFilterWidgets(
|
||||||
|
mergedHomeWidgets,
|
||||||
|
notify: false,
|
||||||
|
);
|
||||||
_meta.notifyListeners();
|
_meta.notifyListeners();
|
||||||
_bank.notifyListeners();
|
_bank.notifyListeners();
|
||||||
|
_prefs.notifyListeners();
|
||||||
_setProgress(0.55);
|
_setProgress(0.55);
|
||||||
_setStatus('Pushing…');
|
_setStatus('Pushing…');
|
||||||
final metaSummary = await service.push(
|
final metaSummary = await service.push(
|
||||||
mergedMeta,
|
mergedMeta,
|
||||||
progressStart: 0.55,
|
progressStart: 0.55,
|
||||||
progressEnd: 0.82,
|
progressEnd: 0.75,
|
||||||
onProgress: _setProgress,
|
onProgress: _setProgress,
|
||||||
onStatus: _setStatus,
|
onStatus: _setStatus,
|
||||||
);
|
);
|
||||||
|
try {
|
||||||
|
await service.pushOverviewFavourites(
|
||||||
|
mergedFavourites,
|
||||||
|
onStatus: _setStatus,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
debugPrint(
|
||||||
|
'SyncController: overview_favourites push skipped ($error)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await service.pushHomeFilterWidgets(
|
||||||
|
mergedHomeWidgets,
|
||||||
|
onStatus: _setStatus,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
debugPrint(
|
||||||
|
'SyncController: home_filter_widgets push skipped ($error)',
|
||||||
|
);
|
||||||
|
}
|
||||||
final bankSummary = await service.pushTransactions(
|
final bankSummary = await service.pushTransactions(
|
||||||
_bank.transactions,
|
_bank.transactions,
|
||||||
progressStart: 0.82,
|
progressStart: 0.82,
|
||||||
@@ -305,32 +396,100 @@ class SyncController extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Annotation-only push after local meta edits (avoids re-uploading 4k+ txs).
|
/// Pushes only the stores that changed locally (debounced).
|
||||||
|
///
|
||||||
|
/// Annotation edits push tx_meta; favourite / Home-widget edits do not
|
||||||
|
/// re-upload the full annotation store or bank transactions.
|
||||||
Future<void> _pushOnly() async {
|
Future<void> _pushOnly() async {
|
||||||
if (!_auth.isLoggedIn || _syncing) {
|
if (!_auth.isLoggedIn) return;
|
||||||
if (_syncing) _pushQueued = true;
|
if (_syncing) {
|
||||||
|
_pushQueued = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final pushMeta = _pushMetaPending;
|
||||||
|
final pushFavourites = _pushFavouritesPending;
|
||||||
|
final pushHomeWidgets = _pushHomeWidgetsPending;
|
||||||
|
_pushMetaPending = false;
|
||||||
|
_pushFavouritesPending = false;
|
||||||
|
_pushHomeWidgetsPending = false;
|
||||||
|
if (!pushMeta && !pushFavourites && !pushHomeWidgets) return;
|
||||||
|
|
||||||
_progressHold?.cancel();
|
_progressHold?.cancel();
|
||||||
_syncing = true;
|
_syncing = true;
|
||||||
_progressSuccess = false;
|
_progressSuccess = false;
|
||||||
_statusDetail = 'Pushing…';
|
|
||||||
|
final label = switch ((pushMeta, pushFavourites, pushHomeWidgets)) {
|
||||||
|
(false, false, true) => 'Home widgets',
|
||||||
|
(false, true, false) => 'Favourites',
|
||||||
|
(false, true, true) => 'Home layout',
|
||||||
|
(true, false, false) => 'Annotations',
|
||||||
|
_ => 'Changes',
|
||||||
|
};
|
||||||
|
_statusDetail = 'Pushing $label…';
|
||||||
_setProgress(0.05);
|
_setProgress(0.05);
|
||||||
_announce('Syncing…', isProgress: true);
|
_announce('Saving $label…', isProgress: true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final service = PbSyncService(_auth.client);
|
final service = PbSyncService(_auth.client);
|
||||||
|
final parts = <String>[];
|
||||||
|
var done = 0;
|
||||||
|
final total = (pushMeta ? 1 : 0) +
|
||||||
|
(pushFavourites ? 1 : 0) +
|
||||||
|
(pushHomeWidgets ? 1 : 0);
|
||||||
|
void bump() {
|
||||||
|
done++;
|
||||||
|
_setProgress(done / total);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pushMeta) {
|
||||||
|
_setStatus('Pushing annotations…');
|
||||||
final summary = await service.push(
|
final summary = await service.push(
|
||||||
_meta.exportStore(),
|
_meta.exportStore(),
|
||||||
progressStart: 0.05,
|
progressStart: done / total,
|
||||||
progressEnd: 1.0,
|
progressEnd: (done + 1) / total,
|
||||||
onProgress: _setProgress,
|
onProgress: _setProgress,
|
||||||
onStatus: _setStatus,
|
onStatus: _setStatus,
|
||||||
);
|
);
|
||||||
|
parts.add(summary);
|
||||||
|
bump();
|
||||||
|
}
|
||||||
|
if (pushFavourites) {
|
||||||
|
_setStatus('Pushing favourites…');
|
||||||
|
try {
|
||||||
|
await service.pushOverviewFavourites(
|
||||||
|
_prefs.overviewFavourites,
|
||||||
|
onStatus: _setStatus,
|
||||||
|
);
|
||||||
|
parts.add('Favourites updated');
|
||||||
|
} catch (error) {
|
||||||
|
debugPrint(
|
||||||
|
'SyncController: overview_favourites push skipped ($error)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
bump();
|
||||||
|
}
|
||||||
|
if (pushHomeWidgets) {
|
||||||
|
_setStatus('Pushing home widgets…');
|
||||||
|
try {
|
||||||
|
await service.pushHomeFilterWidgets(
|
||||||
|
_prefs.homeFilterWidgets,
|
||||||
|
onStatus: _setStatus,
|
||||||
|
);
|
||||||
|
parts.add('Home widgets updated');
|
||||||
|
} catch (error) {
|
||||||
|
debugPrint(
|
||||||
|
'SyncController: home_filter_widgets push skipped ($error)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
_setProgress(1.0);
|
||||||
_lastSyncedAt = DateTime.now();
|
_lastSyncedAt = DateTime.now();
|
||||||
_lastError = null;
|
_lastError = null;
|
||||||
_lastSyncSummary = summary;
|
_lastSyncSummary = parts.isEmpty ? label : parts.join('\n');
|
||||||
_announce('Sync complete');
|
_announce('Saved $label');
|
||||||
_syncing = false;
|
_syncing = false;
|
||||||
_finishProgress(success: true);
|
_finishProgress(success: true);
|
||||||
} catch (error, stackTrace) {
|
} catch (error, stackTrace) {
|
||||||
@@ -359,6 +518,8 @@ class SyncController extends ChangeNotifier {
|
|||||||
_auth.removeListener(_onAuthChanged);
|
_auth.removeListener(_onAuthChanged);
|
||||||
_bank.onAfterSuccessfulLoad = null;
|
_bank.onAfterSuccessfulLoad = null;
|
||||||
_meta.onPersisted = null;
|
_meta.onPersisted = null;
|
||||||
|
_prefs.onFavouritesPersisted = null;
|
||||||
|
_prefs.onHomeWidgetsPersisted = null;
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+299
-14
@@ -4,13 +4,17 @@ library;
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
import '../providers/bank_provider.dart';
|
import '../providers/bank_provider.dart';
|
||||||
|
import '../providers/preferences_provider.dart';
|
||||||
import '../providers/tx_meta_provider.dart';
|
import '../providers/tx_meta_provider.dart';
|
||||||
import '../utils/app_theme.dart';
|
import '../utils/app_theme.dart';
|
||||||
import '../utils/connect_bank.dart';
|
import '../utils/connect_bank.dart';
|
||||||
import '../utils/helpers.dart';
|
import '../utils/helpers.dart';
|
||||||
import '../utils/navigation.dart';
|
import '../utils/navigation.dart';
|
||||||
import '../widgets/empty_state.dart';
|
import '../widgets/empty_state.dart';
|
||||||
|
import '../widgets/home_filter_widget_card.dart';
|
||||||
|
import '../widgets/home_widgets_sheet.dart';
|
||||||
import '../widgets/loading_view.dart';
|
import '../widgets/loading_view.dart';
|
||||||
import '../widgets/responsive_body.dart';
|
import '../widgets/responsive_body.dart';
|
||||||
import '../widgets/shell_tab_scope.dart';
|
import '../widgets/shell_tab_scope.dart';
|
||||||
@@ -18,16 +22,23 @@ import '../widgets/skip_build_when_covered.dart';
|
|||||||
import 'transaction_detail_screen.dart';
|
import 'transaction_detail_screen.dart';
|
||||||
import 'transactions_screen.dart';
|
import 'transactions_screen.dart';
|
||||||
|
|
||||||
class HomeScreen extends StatelessWidget {
|
class HomeScreen extends StatefulWidget {
|
||||||
const HomeScreen({super.key});
|
const HomeScreen({super.key});
|
||||||
|
|
||||||
static const tabIndex = 0;
|
static const tabIndex = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<HomeScreen> createState() => _HomeScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HomeScreenState extends State<HomeScreen> {
|
||||||
|
var _editingWidgets = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
// Inactive IndexedStack tabs must not watch providers — otherwise every
|
// Inactive IndexedStack tabs must not watch providers — otherwise every
|
||||||
// annotation save rebuilds Home while the user is on another tab.
|
// annotation save rebuilds Home while the user is on another tab.
|
||||||
if (ShellTabScope.of(context) != tabIndex) {
|
if (ShellTabScope.of(context) != HomeScreen.tabIndex) {
|
||||||
return const SizedBox.expand();
|
return const SizedBox.expand();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,17 +46,31 @@ class HomeScreen extends StatelessWidget {
|
|||||||
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Home'),
|
title: Text(_editingWidgets ? 'Edit Home' : 'Home'),
|
||||||
actions: bankAppBarActions(
|
actions: [
|
||||||
|
if (bank.isLinked || bank.hasData)
|
||||||
|
IconButton(
|
||||||
|
tooltip: _editingWidgets ? 'Done' : 'Edit Home layout',
|
||||||
|
onPressed: () =>
|
||||||
|
setState(() => _editingWidgets = !_editingWidgets),
|
||||||
|
icon: Icon(
|
||||||
|
_editingWidgets ? Icons.check : Icons.dashboard_customize_outlined,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
...bankAppBarActions(
|
||||||
context: context,
|
context: context,
|
||||||
onRefresh: bank.refresh,
|
onRefresh: bank.refresh,
|
||||||
refreshing: bank.isLoading,
|
refreshing: bank.isLoading,
|
||||||
),
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
body: RefreshIndicator(
|
body: RefreshIndicator(
|
||||||
onRefresh: bank.refresh,
|
onRefresh: bank.refresh,
|
||||||
child: ResponsiveBody(
|
child: ResponsiveBody(
|
||||||
child: _HomeBody(bank: bank),
|
child: _HomeBody(
|
||||||
|
bank: bank,
|
||||||
|
editingWidgets: _editingWidgets,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -53,9 +78,13 @@ class HomeScreen extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _HomeBody extends StatelessWidget {
|
class _HomeBody extends StatelessWidget {
|
||||||
const _HomeBody({required this.bank});
|
const _HomeBody({
|
||||||
|
required this.bank,
|
||||||
|
required this.editingWidgets,
|
||||||
|
});
|
||||||
|
|
||||||
final BankController bank;
|
final BankController bank;
|
||||||
|
final bool editingWidgets;
|
||||||
|
|
||||||
void _openTransactions(BuildContext context) {
|
void _openTransactions(BuildContext context) {
|
||||||
Navigator.of(context).push(
|
Navigator.of(context).push(
|
||||||
@@ -68,6 +97,7 @@ class _HomeBody extends StatelessWidget {
|
|||||||
// Stay subscribed, but skip heavy scans while covered by another route
|
// Stay subscribed, but skip heavy scans while covered by another route
|
||||||
// (e.g. transaction detail applying labels to many similar txs).
|
// (e.g. transaction detail applying labels to many similar txs).
|
||||||
context.watch<TxMetaController>();
|
context.watch<TxMetaController>();
|
||||||
|
final prefs = context.watch<PreferencesController>();
|
||||||
|
|
||||||
if (bank.isLoading && bank.balance == null && !bank.hasData) {
|
if (bank.isLoading && bank.balance == null && !bank.hasData) {
|
||||||
return const LoadingView(message: 'Checking bank link…');
|
return const LoadingView(message: 'Checking bank link…');
|
||||||
@@ -113,6 +143,9 @@ class _HomeBody extends StatelessWidget {
|
|||||||
final recent = bank.transactions.take(5).toList(growable: false);
|
final recent = bank.transactions.take(5).toList(growable: false);
|
||||||
final categorized =
|
final categorized =
|
||||||
meta.labeledTransactionCount(bank.transactions);
|
meta.labeledTransactionCount(bank.transactions);
|
||||||
|
final widgets = editingWidgets
|
||||||
|
? prefs.homeFilterWidgets
|
||||||
|
: prefs.displayedHomeFilterWidgets;
|
||||||
|
|
||||||
return ListView(
|
return ListView(
|
||||||
physics: const AlwaysScrollableScrollPhysics(),
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
@@ -170,7 +203,8 @@ class _HomeBody extends StatelessWidget {
|
|||||||
child: Text(
|
child: Text(
|
||||||
'Tap to view transactions',
|
'Tap to view transactions',
|
||||||
style: theme.textTheme.labelMedium?.copyWith(
|
style: theme.textTheme.labelMedium?.copyWith(
|
||||||
color: colors.onPrimary.withValues(alpha: 0.9),
|
color:
|
||||||
|
colors.onPrimary.withValues(alpha: 0.9),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -185,28 +219,149 @@ class _HomeBody extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
if (_showBuiltIn(
|
||||||
|
editing: editingWidgets,
|
||||||
|
enabled: prefs.homeBuiltInSections.showTransactions,
|
||||||
|
) ||
|
||||||
|
_showBuiltIn(
|
||||||
|
editing: editingWidgets,
|
||||||
|
enabled: prefs.homeBuiltInSections.showCategorized,
|
||||||
|
)) ...[
|
||||||
const SizedBox(height: 20),
|
const SizedBox(height: 20),
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
|
if (_showBuiltIn(
|
||||||
|
editing: editingWidgets,
|
||||||
|
enabled: prefs.homeBuiltInSections.showTransactions,
|
||||||
|
))
|
||||||
Expanded(
|
Expanded(
|
||||||
|
child: _EditableHomeBlock(
|
||||||
|
editing: editingWidgets,
|
||||||
|
visible: prefs.homeBuiltInSections.showTransactions,
|
||||||
|
onToggleVisible: (value) =>
|
||||||
|
prefs.setHomeShowTransactions(value),
|
||||||
child: _StatChip(
|
child: _StatChip(
|
||||||
label: 'Transactions',
|
label: 'Transactions',
|
||||||
value: '${bank.transactions.length}',
|
value: '${bank.transactions.length}',
|
||||||
icon: Icons.list_alt,
|
icon: Icons.list_alt,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
if (_showBuiltIn(
|
||||||
|
editing: editingWidgets,
|
||||||
|
enabled: prefs.homeBuiltInSections.showTransactions,
|
||||||
|
) &&
|
||||||
|
_showBuiltIn(
|
||||||
|
editing: editingWidgets,
|
||||||
|
enabled: prefs.homeBuiltInSections.showCategorized,
|
||||||
|
))
|
||||||
const SizedBox(width: 10),
|
const SizedBox(width: 10),
|
||||||
|
if (_showBuiltIn(
|
||||||
|
editing: editingWidgets,
|
||||||
|
enabled: prefs.homeBuiltInSections.showCategorized,
|
||||||
|
))
|
||||||
Expanded(
|
Expanded(
|
||||||
|
child: _EditableHomeBlock(
|
||||||
|
editing: editingWidgets,
|
||||||
|
visible: prefs.homeBuiltInSections.showCategorized,
|
||||||
|
onToggleVisible: (value) =>
|
||||||
|
prefs.setHomeShowCategorized(value),
|
||||||
child: _StatChip(
|
child: _StatChip(
|
||||||
label: 'Categorized',
|
label: 'Categorized',
|
||||||
value: '$categorized',
|
value: '$categorized',
|
||||||
icon: Icons.label_outline,
|
icon: Icons.label_outline,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (recent.isNotEmpty) ...[
|
],
|
||||||
|
if (editingWidgets || widgets.isNotEmpty) ...[
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
|
if (editingWidgets)
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
child: TextButton.icon(
|
||||||
|
onPressed: () => showHomeWidgetsSheet(context),
|
||||||
|
icon: const Icon(Icons.add, size: 18),
|
||||||
|
label: const Text('Add'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (widgets.isEmpty)
|
||||||
|
Text(
|
||||||
|
'No widgets yet. Tap Add to pin a transaction filter.',
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: colors.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (editingWidgets)
|
||||||
|
ReorderableListView.builder(
|
||||||
|
shrinkWrap: true,
|
||||||
|
physics: const NeverScrollableScrollPhysics(),
|
||||||
|
buildDefaultDragHandles: false,
|
||||||
|
itemCount: widgets.length,
|
||||||
|
onReorderItem: prefs.reorderHomeFilterWidgets,
|
||||||
|
proxyDecorator: (child, index, animation) {
|
||||||
|
return Material(
|
||||||
|
elevation: 2,
|
||||||
|
color: Colors.transparent,
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final widgetConfig = widgets[index];
|
||||||
|
return Padding(
|
||||||
|
key: ValueKey(widgetConfig.id),
|
||||||
|
padding: const EdgeInsets.only(bottom: 10),
|
||||||
|
child: _HomeWidgetSlot(
|
||||||
|
halfWidth: widgetConfig.halfWidth,
|
||||||
|
child: HomeFilterWidgetCard(
|
||||||
|
widgetConfig: widgetConfig,
|
||||||
|
editing: true,
|
||||||
|
onToggleDisplay: (display) =>
|
||||||
|
prefs.setHomeFilterWidgetDisplay(
|
||||||
|
widgetConfig.id,
|
||||||
|
display,
|
||||||
|
),
|
||||||
|
onEdit: () async {
|
||||||
|
final preferences =
|
||||||
|
context.read<PreferencesController>();
|
||||||
|
final updated = await composeHomeFilterWidget(
|
||||||
|
context,
|
||||||
|
existing: widgetConfig,
|
||||||
|
);
|
||||||
|
if (updated == null) return;
|
||||||
|
await preferences.updateHomeFilterWidget(updated);
|
||||||
|
},
|
||||||
|
dragHandle: ReorderableDragStartListener(
|
||||||
|
index: index,
|
||||||
|
child: Icon(
|
||||||
|
Icons.drag_handle,
|
||||||
|
color: colors.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
)
|
||||||
|
else
|
||||||
|
..._packedHomeWidgetRows(widgets),
|
||||||
|
],
|
||||||
|
if (_showBuiltIn(
|
||||||
|
editing: editingWidgets,
|
||||||
|
enabled: prefs.homeBuiltInSections.showRecent,
|
||||||
|
) &&
|
||||||
|
(recent.isNotEmpty || editingWidgets)) ...[
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
_EditableHomeBlock(
|
||||||
|
editing: editingWidgets,
|
||||||
|
visible: prefs.homeBuiltInSections.showRecent,
|
||||||
|
onToggleVisible: (value) => prefs.setHomeShowRecent(value),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Text('Recent', style: theme.textTheme.titleMedium),
|
Text('Recent', style: theme.textTheme.titleMedium),
|
||||||
@@ -218,6 +373,14 @@ class _HomeBody extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
|
if (recent.isEmpty)
|
||||||
|
Text(
|
||||||
|
'No recent transactions yet.',
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: colors.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
for (final tx in recent)
|
for (final tx in recent)
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
@@ -226,7 +389,8 @@ class _HomeBody extends StatelessWidget {
|
|||||||
builder: (context) {
|
builder: (context) {
|
||||||
final labels =
|
final labels =
|
||||||
meta.leafLabelsFor(meta.metaFor(tx));
|
meta.leafLabelsFor(meta.metaFor(tx));
|
||||||
final label = labels.isEmpty ? null : labels.first;
|
final label =
|
||||||
|
labels.isEmpty ? null : labels.first;
|
||||||
return Icon(
|
return Icon(
|
||||||
label?.icon ?? Icons.receipt_long_outlined,
|
label?.icon ?? Icons.receipt_long_outlined,
|
||||||
color: label?.color,
|
color: label?.color,
|
||||||
@@ -242,23 +406,32 @@ class _HomeBody extends StatelessWidget {
|
|||||||
trailing: Text(
|
trailing: Text(
|
||||||
formatMoney(tx.amount, tx.currency),
|
formatMoney(tx.amount, tx.currency),
|
||||||
style: theme.textTheme.titleSmall?.copyWith(
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
color: tx.amount >= 0 ? AppTheme.accent : AppTheme.expense,
|
color: tx.amount >= 0
|
||||||
|
? AppTheme.accent
|
||||||
|
: AppTheme.expense,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
onTap: () {
|
onTap: editingWidgets
|
||||||
|
? null
|
||||||
|
: () {
|
||||||
Navigator.of(context).push(
|
Navigator.of(context).push(
|
||||||
MaterialPageRoute<void>(
|
MaterialPageRoute<void>(
|
||||||
builder: (_) => TransactionDetailScreen(tx: tx),
|
builder: (_) =>
|
||||||
|
TransactionDetailScreen(tx: tx),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
if (bank.error != null) ...[
|
if (bank.error != null) ...[
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Text(
|
Text(
|
||||||
bank.error!,
|
bank.error!,
|
||||||
style: theme.textTheme.bodyMedium?.copyWith(color: colors.error),
|
style: theme.textTheme.bodyMedium
|
||||||
|
?.copyWith(color: colors.error),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
@@ -297,8 +470,13 @@ class _StatChip extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
|
Text(
|
||||||
|
label,
|
||||||
|
style: theme.textTheme.labelMedium?.copyWith(
|
||||||
|
color: colors.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
Text(value, style: theme.textTheme.titleMedium),
|
Text(value, style: theme.textTheme.titleMedium),
|
||||||
Text(label, style: theme.textTheme.labelMedium),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -307,3 +485,110 @@ class _StatChip extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool _showBuiltIn({required bool editing, required bool enabled}) =>
|
||||||
|
editing || enabled;
|
||||||
|
|
||||||
|
/// Wraps a built-in Home block with show/hide controls while editing.
|
||||||
|
class _EditableHomeBlock extends StatelessWidget {
|
||||||
|
const _EditableHomeBlock({
|
||||||
|
required this.editing,
|
||||||
|
required this.visible,
|
||||||
|
required this.onToggleVisible,
|
||||||
|
required this.child,
|
||||||
|
});
|
||||||
|
|
||||||
|
final bool editing;
|
||||||
|
final bool visible;
|
||||||
|
final ValueChanged<bool> onToggleVisible;
|
||||||
|
final Widget child;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final colors = Theme.of(context).colorScheme;
|
||||||
|
final content = Opacity(
|
||||||
|
opacity: editing && !visible ? 0.45 : 1,
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
if (!editing) return content;
|
||||||
|
return Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Expanded(child: content),
|
||||||
|
IconButton(
|
||||||
|
tooltip: visible ? 'Hide from Home' : 'Show on Home',
|
||||||
|
onPressed: () => onToggleVisible(!visible),
|
||||||
|
icon: Icon(
|
||||||
|
visible ? Icons.visibility_outlined : Icons.visibility_off_outlined,
|
||||||
|
color: visible ? colors.onSurfaceVariant : colors.primary,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full- or half-width slot for a Home filter widget card.
|
||||||
|
class _HomeWidgetSlot extends StatelessWidget {
|
||||||
|
const _HomeWidgetSlot({
|
||||||
|
required this.halfWidth,
|
||||||
|
required this.child,
|
||||||
|
});
|
||||||
|
|
||||||
|
final bool halfWidth;
|
||||||
|
final Widget child;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (!halfWidth) return child;
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final width = (constraints.maxWidth - 10) / 2;
|
||||||
|
return Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: SizedBox(width: width, child: child),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Widget> _packedHomeWidgetRows(List<HomeFilterWidget> widgets) {
|
||||||
|
final rows = <Widget>[];
|
||||||
|
var i = 0;
|
||||||
|
while (i < widgets.length) {
|
||||||
|
final a = widgets[i];
|
||||||
|
final canPair = a.halfWidth &&
|
||||||
|
i + 1 < widgets.length &&
|
||||||
|
widgets[i + 1].halfWidth;
|
||||||
|
if (canPair) {
|
||||||
|
final b = widgets[i + 1];
|
||||||
|
rows.add(
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 10),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Expanded(child: HomeFilterWidgetCard(widgetConfig: a)),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(child: HomeFilterWidgetCard(widgetConfig: b)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rows.add(
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 10),
|
||||||
|
child: _HomeWidgetSlot(
|
||||||
|
halfWidth: a.halfWidth,
|
||||||
|
child: HomeFilterWidgetCard(widgetConfig: a),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|||||||
@@ -31,7 +31,10 @@ class LabelTransactionsScreen extends StatelessWidget {
|
|||||||
builder: (context) {
|
builder: (context) {
|
||||||
final txs = [
|
final txs = [
|
||||||
for (final tx in bank.transactions)
|
for (final tx in bank.transactions)
|
||||||
if (meta.labelIdsFor(tx).contains(label.id)) tx,
|
if (label.id == kUncategorizedFilterId
|
||||||
|
? meta.labelIdsFor(tx).isEmpty
|
||||||
|
: meta.labelIdsFor(tx).contains(label.id))
|
||||||
|
tx,
|
||||||
];
|
];
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final currency = bank.balance?.currency ??
|
final currency = bank.balance?.currency ??
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@ import 'package:provider/provider.dart';
|
|||||||
import '../models/bank.dart';
|
import '../models/bank.dart';
|
||||||
import '../models/transaction_meta.dart';
|
import '../models/transaction_meta.dart';
|
||||||
import '../providers/bank_provider.dart';
|
import '../providers/bank_provider.dart';
|
||||||
|
import '../providers/preferences_provider.dart';
|
||||||
import '../providers/tx_meta_provider.dart';
|
import '../providers/tx_meta_provider.dart';
|
||||||
import '../utils/app_theme.dart';
|
import '../utils/app_theme.dart';
|
||||||
import '../utils/connect_bank.dart';
|
import '../utils/connect_bank.dart';
|
||||||
@@ -16,6 +17,7 @@ import '../utils/helpers.dart';
|
|||||||
import '../utils/navigation.dart';
|
import '../utils/navigation.dart';
|
||||||
import '../utils/tx_calendar.dart';
|
import '../utils/tx_calendar.dart';
|
||||||
import '../widgets/empty_state.dart';
|
import '../widgets/empty_state.dart';
|
||||||
|
import '../widgets/home_widgets_sheet.dart';
|
||||||
import '../widgets/label_filter_dialog.dart';
|
import '../widgets/label_filter_dialog.dart';
|
||||||
import '../widgets/loading_view.dart';
|
import '../widgets/loading_view.dart';
|
||||||
import '../widgets/responsive_body.dart';
|
import '../widgets/responsive_body.dart';
|
||||||
@@ -30,6 +32,9 @@ class TransactionsScreen extends StatefulWidget {
|
|||||||
this.initialLabelIds = const {},
|
this.initialLabelIds = const {},
|
||||||
this.initialSearchInMonthOnly,
|
this.initialSearchInMonthOnly,
|
||||||
this.initialYear,
|
this.initialYear,
|
||||||
|
this.initialQuery,
|
||||||
|
this.initialFlow,
|
||||||
|
this.initialAmountRange,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// When set, opens on this calendar month instead of the current month.
|
/// When set, opens on this calendar month instead of the current month.
|
||||||
@@ -44,6 +49,12 @@ class TransactionsScreen extends StatefulWidget {
|
|||||||
/// When set, label/search results are limited to this calendar year.
|
/// When set, label/search results are limited to this calendar year.
|
||||||
final int? initialYear;
|
final int? initialYear;
|
||||||
|
|
||||||
|
/// Pre-fill search query (e.g. from a Home filter widget).
|
||||||
|
final String? initialQuery;
|
||||||
|
|
||||||
|
final TxFlowFilter? initialFlow;
|
||||||
|
final TxAmountRange? initialAmountRange;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<TransactionsScreen> createState() => _TransactionsScreenState();
|
State<TransactionsScreen> createState() => _TransactionsScreenState();
|
||||||
}
|
}
|
||||||
@@ -81,6 +92,13 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
|||||||
// Default to current month so the list, navigator, and filter popup agree.
|
// Default to current month so the list, navigator, and filter popup agree.
|
||||||
_searchInMonthOnly = widget.initialSearchInMonthOnly ?? true;
|
_searchInMonthOnly = widget.initialSearchInMonthOnly ?? true;
|
||||||
_yearFilter = widget.initialYear;
|
_yearFilter = widget.initialYear;
|
||||||
|
_flowFilter = widget.initialFlow ?? TxFlowFilter.all;
|
||||||
|
_amountRange = widget.initialAmountRange ?? const TxAmountRange();
|
||||||
|
final initialQuery = widget.initialQuery?.trim() ?? '';
|
||||||
|
if (initialQuery.isNotEmpty) {
|
||||||
|
_searchController.text = initialQuery;
|
||||||
|
_activeQuery = initialQuery;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -222,6 +240,27 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _saveAsHomeWidget() async {
|
||||||
|
final preferences = context.read<PreferencesController>();
|
||||||
|
final created = await composeHomeFilterWidget(
|
||||||
|
context,
|
||||||
|
initialFilter: TransactionFilterSelection(
|
||||||
|
labelIds: Set<String>.of(_labelFilters),
|
||||||
|
flow: _flowFilter,
|
||||||
|
amountRange: _amountRange,
|
||||||
|
query: _activeQuery,
|
||||||
|
monthOnly: _searchInMonthOnly,
|
||||||
|
),
|
||||||
|
skipFilterDialog: true,
|
||||||
|
);
|
||||||
|
if (created == null) return;
|
||||||
|
await preferences.addHomeFilterWidget(created);
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Added “${created.name}” to Home')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final bank = context.watch<BankController>();
|
final bank = context.watch<BankController>();
|
||||||
@@ -229,11 +268,18 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
|
|||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Transactions'),
|
title: const Text('Transactions'),
|
||||||
actions: bankAppBarActions(
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Save as Home widget',
|
||||||
|
onPressed: _saveAsHomeWidget,
|
||||||
|
icon: const Icon(Icons.dashboard_customize_outlined),
|
||||||
|
),
|
||||||
|
...bankAppBarActions(
|
||||||
context: context,
|
context: context,
|
||||||
onRefresh: bank.refresh,
|
onRefresh: bank.refresh,
|
||||||
refreshing: bank.isLoading,
|
refreshing: bank.isLoading,
|
||||||
),
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
body: Column(
|
body: Column(
|
||||||
children: [
|
children: [
|
||||||
|
|||||||
@@ -8,7 +8,10 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:pocketbase/pocketbase.dart';
|
import 'package:pocketbase/pocketbase.dart';
|
||||||
|
|
||||||
import '../models/bank.dart';
|
import '../models/bank.dart';
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
|
import '../models/overview_favourite.dart';
|
||||||
import '../models/transaction_meta.dart';
|
import '../models/transaction_meta.dart';
|
||||||
|
import '../widgets/label_filter_dialog.dart';
|
||||||
import 'ing_csv_import.dart';
|
import 'ing_csv_import.dart';
|
||||||
import 'storage_service.dart';
|
import 'storage_service.dart';
|
||||||
|
|
||||||
@@ -20,6 +23,20 @@ List<BankTransaction> mergeBankTransactionLists(
|
|||||||
return mergeTransactions(local, remote);
|
return mergeTransactions(local, remote);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Union Overview favourites by client id (local wins on conflict).
|
||||||
|
List<OverviewFavourite> mergeOverviewFavourites(
|
||||||
|
List<OverviewFavourite> local,
|
||||||
|
List<OverviewFavourite> remote,
|
||||||
|
) {
|
||||||
|
final byId = <String, OverviewFavourite>{
|
||||||
|
for (final fav in remote) fav.id: fav,
|
||||||
|
};
|
||||||
|
for (final fav in local) {
|
||||||
|
byId[fav.id] = fav;
|
||||||
|
}
|
||||||
|
return byId.values.toList(growable: false);
|
||||||
|
}
|
||||||
|
|
||||||
/// Union-merge so neither device loses annotations on first sync.
|
/// Union-merge so neither device loses annotations on first sync.
|
||||||
TxMetaStoreData mergeTxMetaStores(TxMetaStoreData a, TxMetaStoreData b) {
|
TxMetaStoreData mergeTxMetaStores(TxMetaStoreData a, TxMetaStoreData b) {
|
||||||
final byId = <String, TxMeta>{...a.byId};
|
final byId = <String, TxMeta>{...a.byId};
|
||||||
@@ -426,6 +443,121 @@ class PbSyncService {
|
|||||||
return txSummary;
|
return txSummary;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Pull Overview favourites for the signed-in user.
|
||||||
|
///
|
||||||
|
/// Soft-fails at the call site if the collection is missing.
|
||||||
|
Future<List<OverviewFavourite>> pullOverviewFavourites({
|
||||||
|
void Function(String message)? onStatus,
|
||||||
|
}) async {
|
||||||
|
final userId = _userId;
|
||||||
|
final filter = 'user="$userId"';
|
||||||
|
onStatus?.call('Pulling overview favourites…');
|
||||||
|
final records = await _fullList('overview_favourites', filter);
|
||||||
|
final out = <OverviewFavourite>[];
|
||||||
|
for (final r in records) {
|
||||||
|
final clientId = r.getStringValue('client_id');
|
||||||
|
if (clientId.isEmpty) continue;
|
||||||
|
out.add(
|
||||||
|
OverviewFavourite(
|
||||||
|
id: clientId,
|
||||||
|
name: r.getStringValue('name').isEmpty
|
||||||
|
? 'Favourite'
|
||||||
|
: r.getStringValue('name'),
|
||||||
|
display: r.getBoolValue('display', true),
|
||||||
|
metric: OverviewMetricMode.values.firstWhere(
|
||||||
|
(e) => e.name == r.getStringValue('metric'),
|
||||||
|
orElse: () => OverviewMetricMode.flow,
|
||||||
|
),
|
||||||
|
period: OverviewPeriodMode.values.firstWhere(
|
||||||
|
(e) => e.name == r.getStringValue('period'),
|
||||||
|
orElse: () => OverviewPeriodMode.monthly,
|
||||||
|
),
|
||||||
|
labelIds: _jsonStringList(r.get<dynamic>('label_ids')),
|
||||||
|
flow: TxFlowFilter.values.firstWhere(
|
||||||
|
(e) => e.name == r.getStringValue('flow'),
|
||||||
|
orElse: () => TxFlowFilter.expense,
|
||||||
|
),
|
||||||
|
barStyle: LabelChartBarStyle.values.firstWhere(
|
||||||
|
(e) => e.name == r.getStringValue('bar_style'),
|
||||||
|
orElse: () => LabelChartBarStyle.parallel,
|
||||||
|
),
|
||||||
|
invertExpensePerspective:
|
||||||
|
r.getBoolValue('invert_expense_perspective'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
debugPrint('PbSyncService pull: overview_favourites=${out.length}');
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upsert Overview favourites; deletes remote rows no longer local.
|
||||||
|
Future<void> pushOverviewFavourites(
|
||||||
|
List<OverviewFavourite> favourites, {
|
||||||
|
void Function(String message)? onStatus,
|
||||||
|
}) async {
|
||||||
|
final userId = _userId;
|
||||||
|
final filter = 'user="$userId"';
|
||||||
|
onStatus?.call('Syncing overview favourites…');
|
||||||
|
await _syncOverviewFavourites(userId, filter, favourites);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pull Home filter widgets for the signed-in user.
|
||||||
|
Future<List<HomeFilterWidget>> pullHomeFilterWidgets({
|
||||||
|
void Function(String message)? onStatus,
|
||||||
|
}) async {
|
||||||
|
final userId = _userId;
|
||||||
|
final filter = 'user="$userId"';
|
||||||
|
onStatus?.call('Pulling home widgets…');
|
||||||
|
final records = await _fullList('home_filter_widgets', filter);
|
||||||
|
final out = <HomeFilterWidget>[];
|
||||||
|
for (final r in records) {
|
||||||
|
final clientId = r.getStringValue('client_id');
|
||||||
|
if (clientId.isEmpty) continue;
|
||||||
|
final rangeRaw = r.get<dynamic>('amount_range');
|
||||||
|
out.add(
|
||||||
|
HomeFilterWidget.fromJson({
|
||||||
|
'id': clientId,
|
||||||
|
'name': r.getStringValue('name'),
|
||||||
|
'display': r.getBoolValue('display', true),
|
||||||
|
'sortOrder': r.getIntValue('sort_order', 0),
|
||||||
|
'halfWidth': r.getBoolValue('half_width'),
|
||||||
|
'type': r.getStringValue('widget_type'),
|
||||||
|
'iconId': r.getStringValue('icon_id'),
|
||||||
|
'chartStyle': r.getStringValue('chart_style'),
|
||||||
|
'budgetCapMode': r.getStringValue('budget_cap_mode'),
|
||||||
|
'budgetFixedAmount': switch (r.get<dynamic>('budget_fixed_amount')) {
|
||||||
|
num n => n.toDouble(),
|
||||||
|
String s => double.tryParse(s) ?? 0,
|
||||||
|
_ => 0.0,
|
||||||
|
},
|
||||||
|
'budgetAverageMonths': r.getIntValue('budget_average_months', 3),
|
||||||
|
'labelIds': _jsonStringList(r.get<dynamic>('label_ids')),
|
||||||
|
'flow': r.getStringValue('flow'),
|
||||||
|
'amountRange': rangeRaw is Map
|
||||||
|
? Map<String, dynamic>.from(rangeRaw)
|
||||||
|
: const <String, dynamic>{},
|
||||||
|
'query': r.getStringValue('query'),
|
||||||
|
'monthOnly': r.getBoolValue('month_only'),
|
||||||
|
'showAmountIn': r.getBoolValue('show_amount_in', true),
|
||||||
|
'showAmountOut': r.getBoolValue('show_amount_out', true),
|
||||||
|
'showCount': r.getBoolValue('show_count', true),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
debugPrint('PbSyncService pull: home_filter_widgets=${out.length}');
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> pushHomeFilterWidgets(
|
||||||
|
List<HomeFilterWidget> widgets, {
|
||||||
|
void Function(String message)? onStatus,
|
||||||
|
}) async {
|
||||||
|
final userId = _userId;
|
||||||
|
final filter = 'user="$userId"';
|
||||||
|
onStatus?.call('Syncing home widgets…');
|
||||||
|
await _syncHomeFilterWidgets(userId, filter, widgets);
|
||||||
|
}
|
||||||
|
|
||||||
/// Upserts local bank txs to PocketBase. Does **not** delete remote rows
|
/// Upserts local bank txs to PocketBase. Does **not** delete remote rows
|
||||||
/// (partial local caches must not wipe another device).
|
/// (partial local caches must not wipe another device).
|
||||||
Future<String> pushTransactions(
|
Future<String> pushTransactions(
|
||||||
@@ -688,6 +820,18 @@ class PbSyncService {
|
|||||||
filter =
|
filter =
|
||||||
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
|
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
|
||||||
}
|
}
|
||||||
|
case 'overview_favourites':
|
||||||
|
final key = body['client_id'];
|
||||||
|
if (userId != null && key is String) {
|
||||||
|
filter =
|
||||||
|
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
|
||||||
|
}
|
||||||
|
case 'home_filter_widgets':
|
||||||
|
final key = body['client_id'];
|
||||||
|
if (userId != null && key is String) {
|
||||||
|
filter =
|
||||||
|
'user="$userId" && client_id="${key.replaceAll('"', '\\"')}"';
|
||||||
|
}
|
||||||
case 'transactions':
|
case 'transactions':
|
||||||
final key = body['tx_id'];
|
final key = body['tx_id'];
|
||||||
if (userId != null && key is String) {
|
if (userId != null && key is String) {
|
||||||
@@ -993,6 +1137,118 @@ class PbSyncService {
|
|||||||
await _runWriteOps('recurring_templates', ops);
|
await _runWriteOps('recurring_templates', ops);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _syncOverviewFavourites(
|
||||||
|
String userId,
|
||||||
|
String filter,
|
||||||
|
List<OverviewFavourite> favourites,
|
||||||
|
) async {
|
||||||
|
final existing = {
|
||||||
|
for (final r in await _fullList('overview_favourites', filter))
|
||||||
|
r.getStringValue('client_id'): r,
|
||||||
|
};
|
||||||
|
final keep = <String>{};
|
||||||
|
final ops = <_BatchOp>[];
|
||||||
|
|
||||||
|
for (final fav in favourites) {
|
||||||
|
final clientId = _clip(fav.id, 120);
|
||||||
|
if (clientId.isEmpty) continue;
|
||||||
|
keep.add(clientId);
|
||||||
|
final body = <String, dynamic>{
|
||||||
|
'user': userId,
|
||||||
|
'client_id': clientId,
|
||||||
|
'name': _clip(fav.name.isEmpty ? 'Favourite' : fav.name, 200),
|
||||||
|
'display': fav.display,
|
||||||
|
'metric': fav.metric.name,
|
||||||
|
'period': fav.period.name,
|
||||||
|
'label_ids': fav.labelIds,
|
||||||
|
'flow': fav.flow.name,
|
||||||
|
'bar_style': fav.barStyle.name,
|
||||||
|
'invert_expense_perspective': fav.invertExpensePerspective,
|
||||||
|
};
|
||||||
|
final remote = existing[clientId];
|
||||||
|
if (remote == null) {
|
||||||
|
ops.add(_BatchOp.create(body));
|
||||||
|
} else if (!_overviewFavouriteUnchanged(remote, fav)) {
|
||||||
|
ops.add(_BatchOp.update(remote.id, body));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final e in existing.entries) {
|
||||||
|
if (!keep.contains(e.key)) {
|
||||||
|
ops.add(_BatchOp.delete(e.value.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
debugPrint(
|
||||||
|
'PbSyncService overview_favourites: remote=${existing.length} '
|
||||||
|
'ops=${ops.length}',
|
||||||
|
);
|
||||||
|
await _runWriteOps('overview_favourites', ops);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _syncHomeFilterWidgets(
|
||||||
|
String userId,
|
||||||
|
String filter,
|
||||||
|
List<HomeFilterWidget> widgets,
|
||||||
|
) async {
|
||||||
|
final existing = {
|
||||||
|
for (final r in await _fullList('home_filter_widgets', filter))
|
||||||
|
r.getStringValue('client_id'): r,
|
||||||
|
};
|
||||||
|
final keep = <String>{};
|
||||||
|
final ops = <_BatchOp>[];
|
||||||
|
|
||||||
|
for (final w in widgets) {
|
||||||
|
final clientId = _clip(w.id, 120);
|
||||||
|
if (clientId.isEmpty) continue;
|
||||||
|
keep.add(clientId);
|
||||||
|
final body = <String, dynamic>{
|
||||||
|
'user': userId,
|
||||||
|
'client_id': clientId,
|
||||||
|
'name': _clip(w.name.isEmpty ? 'Filter' : w.name, 200),
|
||||||
|
'display': w.display,
|
||||||
|
'sort_order': w.sortOrder,
|
||||||
|
'half_width': w.halfWidth,
|
||||||
|
'widget_type': w.type.name,
|
||||||
|
'icon_id': w.iconId,
|
||||||
|
'chart_style': w.chartStyle.name,
|
||||||
|
'budget_cap_mode': w.budgetCapMode.name,
|
||||||
|
'budget_fixed_amount': w.budgetFixedAmount,
|
||||||
|
'budget_average_months': w.budgetAverageMonths,
|
||||||
|
'label_ids': w.labelIds,
|
||||||
|
'flow': w.flow.name,
|
||||||
|
'amount_range': {
|
||||||
|
if (w.amountRange.exact != null) 'exact': w.amountRange.exact,
|
||||||
|
if (w.amountRange.min != null) 'min': w.amountRange.min,
|
||||||
|
if (w.amountRange.max != null) 'max': w.amountRange.max,
|
||||||
|
},
|
||||||
|
'query': _clip(w.query, 400),
|
||||||
|
'month_only': w.monthOnly,
|
||||||
|
'show_amount_in': w.showAmountIn,
|
||||||
|
'show_amount_out': w.showAmountOut,
|
||||||
|
'show_count': w.showCount,
|
||||||
|
};
|
||||||
|
final remote = existing[clientId];
|
||||||
|
if (remote == null) {
|
||||||
|
ops.add(_BatchOp.create(body));
|
||||||
|
} else if (!_homeFilterWidgetUnchanged(remote, w)) {
|
||||||
|
ops.add(_BatchOp.update(remote.id, body));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final e in existing.entries) {
|
||||||
|
if (!keep.contains(e.key)) {
|
||||||
|
ops.add(_BatchOp.delete(e.value.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
debugPrint(
|
||||||
|
'PbSyncService home_filter_widgets: remote=${existing.length} '
|
||||||
|
'ops=${ops.length}',
|
||||||
|
);
|
||||||
|
await _runWriteOps('home_filter_widgets', ops);
|
||||||
|
}
|
||||||
|
|
||||||
bool _labelUnchanged(RecordModel remote, Map<String, dynamic> body) {
|
bool _labelUnchanged(RecordModel remote, Map<String, dynamic> body) {
|
||||||
return remote.getStringValue('name') == body['name'] &&
|
return remote.getStringValue('name') == body['name'] &&
|
||||||
remote.getIntValue('color') == body['color'] &&
|
remote.getIntValue('color') == body['color'] &&
|
||||||
@@ -1035,6 +1291,54 @@ class PbSyncService {
|
|||||||
remote.getIntValue('avg_count', 5) == t.avgCount &&
|
remote.getIntValue('avg_count', 5) == t.avgCount &&
|
||||||
remote.getBoolValue('auto_from_recurring') == t.autoFromRecurring;
|
remote.getBoolValue('auto_from_recurring') == t.autoFromRecurring;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool _overviewFavouriteUnchanged(RecordModel remote, OverviewFavourite fav) {
|
||||||
|
final remoteIds = _jsonStringList(remote.get<dynamic>('label_ids'));
|
||||||
|
return remote.getStringValue('name') == fav.name &&
|
||||||
|
remote.getBoolValue('display', true) == fav.display &&
|
||||||
|
remote.getStringValue('metric') == fav.metric.name &&
|
||||||
|
remote.getStringValue('period') == fav.period.name &&
|
||||||
|
_sameIdList(remoteIds, fav.labelIds) &&
|
||||||
|
remote.getStringValue('flow') == fav.flow.name &&
|
||||||
|
remote.getStringValue('bar_style') == fav.barStyle.name &&
|
||||||
|
remote.getBoolValue('invert_expense_perspective') ==
|
||||||
|
fav.invertExpensePerspective;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _homeFilterWidgetUnchanged(RecordModel remote, HomeFilterWidget w) {
|
||||||
|
final remoteIds = _jsonStringList(remote.get<dynamic>('label_ids'));
|
||||||
|
final rangeRaw = remote.get<dynamic>('amount_range');
|
||||||
|
final rangeMap = rangeRaw is Map
|
||||||
|
? Map<String, dynamic>.from(rangeRaw)
|
||||||
|
: const <String, dynamic>{};
|
||||||
|
double? asDouble(dynamic value) => value is num ? value.toDouble() : null;
|
||||||
|
final remoteFixed = switch (remote.get<dynamic>('budget_fixed_amount')) {
|
||||||
|
num n => n.toDouble(),
|
||||||
|
String s => double.tryParse(s) ?? 0,
|
||||||
|
_ => 0.0,
|
||||||
|
};
|
||||||
|
return remote.getStringValue('name') == w.name &&
|
||||||
|
remote.getBoolValue('display', true) == w.display &&
|
||||||
|
remote.getIntValue('sort_order', 0) == w.sortOrder &&
|
||||||
|
remote.getBoolValue('half_width') == w.halfWidth &&
|
||||||
|
remote.getStringValue('widget_type') == w.type.name &&
|
||||||
|
remote.getStringValue('icon_id') == w.iconId &&
|
||||||
|
remote.getStringValue('chart_style') == w.chartStyle.name &&
|
||||||
|
remote.getStringValue('budget_cap_mode') == w.budgetCapMode.name &&
|
||||||
|
(remoteFixed * 100).round() == (w.budgetFixedAmount * 100).round() &&
|
||||||
|
remote.getIntValue('budget_average_months', 3) ==
|
||||||
|
w.budgetAverageMonths &&
|
||||||
|
_sameIdList(remoteIds, w.labelIds) &&
|
||||||
|
remote.getStringValue('flow') == w.flow.name &&
|
||||||
|
asDouble(rangeMap['exact']) == w.amountRange.exact &&
|
||||||
|
asDouble(rangeMap['min']) == w.amountRange.min &&
|
||||||
|
asDouble(rangeMap['max']) == w.amountRange.max &&
|
||||||
|
remote.getStringValue('query') == w.query &&
|
||||||
|
remote.getBoolValue('month_only') == w.monthOnly &&
|
||||||
|
remote.getBoolValue('show_amount_in', true) == w.showAmountIn &&
|
||||||
|
remote.getBoolValue('show_amount_out', true) == w.showAmountOut &&
|
||||||
|
remote.getBoolValue('show_count', true) == w.showCount;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
RecurringTemplateSource _parseTemplateSource(String raw) {
|
RecurringTemplateSource _parseTemplateSource(String raw) {
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ import 'package:flutter/foundation.dart';
|
|||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
import '../models/bank.dart';
|
import '../models/bank.dart';
|
||||||
|
import '../models/home_built_in_sections.dart';
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
|
import '../models/overview_favourite.dart';
|
||||||
import '../models/transaction_meta.dart';
|
import '../models/transaction_meta.dart';
|
||||||
import '../utils/constants.dart';
|
import '../utils/constants.dart';
|
||||||
|
|
||||||
@@ -133,6 +136,75 @@ class StorageService {
|
|||||||
return _prefs.setInt(StorageKeys.lookAheadMaxYears, years.clamp(1, 30));
|
return _prefs.setInt(StorageKeys.lookAheadMaxYears, years.clamp(1, 30));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<OverviewFavourite> loadOverviewFavourites() {
|
||||||
|
final raw = _prefs.getString(StorageKeys.overviewFavourites);
|
||||||
|
if (raw == null || raw.isEmpty) return const [];
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is! List) return const [];
|
||||||
|
return [
|
||||||
|
for (final item in decoded)
|
||||||
|
if (item is Map)
|
||||||
|
OverviewFavourite.fromJson(Map<String, dynamic>.from(item)),
|
||||||
|
];
|
||||||
|
} catch (_) {
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> saveOverviewFavourites(List<OverviewFavourite> favourites) {
|
||||||
|
final encoded = jsonEncode([
|
||||||
|
for (final fav in favourites) fav.toJson(),
|
||||||
|
]);
|
||||||
|
return _prefs.setString(StorageKeys.overviewFavourites, encoded);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<HomeFilterWidget> loadHomeFilterWidgets() {
|
||||||
|
final raw = _prefs.getString(StorageKeys.homeFilterWidgets);
|
||||||
|
if (raw == null || raw.isEmpty) return const [];
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is! List) return const [];
|
||||||
|
final list = [
|
||||||
|
for (final item in decoded)
|
||||||
|
if (item is Map)
|
||||||
|
HomeFilterWidget.fromJson(Map<String, dynamic>.from(item)),
|
||||||
|
];
|
||||||
|
list.sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
|
||||||
|
return list;
|
||||||
|
} catch (_) {
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> saveHomeFilterWidgets(List<HomeFilterWidget> widgets) {
|
||||||
|
final encoded = jsonEncode([
|
||||||
|
for (final w in widgets) w.toJson(),
|
||||||
|
]);
|
||||||
|
return _prefs.setString(StorageKeys.homeFilterWidgets, encoded);
|
||||||
|
}
|
||||||
|
|
||||||
|
HomeBuiltInSections loadHomeBuiltInSections() {
|
||||||
|
final raw = _prefs.getString(StorageKeys.homeBuiltInSections);
|
||||||
|
if (raw == null || raw.isEmpty) return HomeBuiltInSections.defaults;
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is! Map) return HomeBuiltInSections.defaults;
|
||||||
|
return HomeBuiltInSections.fromJson(
|
||||||
|
Map<String, dynamic>.from(decoded),
|
||||||
|
);
|
||||||
|
} catch (_) {
|
||||||
|
return HomeBuiltInSections.defaults;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> saveHomeBuiltInSections(HomeBuiltInSections sections) {
|
||||||
|
return _prefs.setString(
|
||||||
|
StorageKeys.homeBuiltInSections,
|
||||||
|
jsonEncode(sections.toJson()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
bool get useRemoteData => _prefs.getBool(StorageKeys.useRemoteData) ?? false;
|
bool get useRemoteData => _prefs.getBool(StorageKeys.useRemoteData) ?? false;
|
||||||
|
|
||||||
Future<void> setUseRemoteData(bool value) {
|
Future<void> setUseRemoteData(bool value) {
|
||||||
|
|||||||
@@ -51,6 +51,15 @@ abstract final class StorageKeys {
|
|||||||
|
|
||||||
/// How many years ahead Look ahead can navigate (default 5).
|
/// How many years ahead Look ahead can navigate (default 5).
|
||||||
static const lookAheadMaxYears = 'look_ahead_max_years_v1';
|
static const lookAheadMaxYears = 'look_ahead_max_years_v1';
|
||||||
|
|
||||||
|
/// Named Overview chart favourites (JSON list).
|
||||||
|
static const overviewFavourites = 'overview_favourites_v1';
|
||||||
|
|
||||||
|
/// Home screen filter widgets (JSON list).
|
||||||
|
static const homeFilterWidgets = 'home_filter_widgets_v1';
|
||||||
|
|
||||||
|
/// Built-in Home sections visibility (Transactions / Categorized / Recent).
|
||||||
|
static const homeBuiltInSections = 'home_built_in_sections_v1';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Named routes registered on [MaterialApp].
|
/// Named routes registered on [MaterialApp].
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
/// Apply a [TransactionFilterSelection] and compute Home widget metrics.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import '../models/bank.dart';
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
|
import '../models/transaction_meta.dart';
|
||||||
|
import '../providers/tx_meta_provider.dart';
|
||||||
|
import '../utils/tx_calendar.dart';
|
||||||
|
import '../widgets/label_filter_dialog.dart';
|
||||||
|
|
||||||
|
class TxFilterMetrics {
|
||||||
|
const TxFilterMetrics({
|
||||||
|
required this.count,
|
||||||
|
required this.amountIn,
|
||||||
|
required this.amountOut,
|
||||||
|
required this.transactions,
|
||||||
|
});
|
||||||
|
|
||||||
|
final int count;
|
||||||
|
final double amountIn;
|
||||||
|
final double amountOut;
|
||||||
|
final List<BankTransaction> transactions;
|
||||||
|
|
||||||
|
double get net => amountIn - amountOut;
|
||||||
|
}
|
||||||
|
|
||||||
|
class HomeBudgetMetrics {
|
||||||
|
const HomeBudgetMetrics({
|
||||||
|
required this.monthNet,
|
||||||
|
required this.target,
|
||||||
|
required this.averageMonths,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Net (in − out) for the current calendar month.
|
||||||
|
final double monthNet;
|
||||||
|
|
||||||
|
/// Positive budget ceiling (fixed amount or avg |net| of last N months).
|
||||||
|
final double target;
|
||||||
|
|
||||||
|
final int averageMonths;
|
||||||
|
|
||||||
|
/// How much of the ceiling is used, based on |monthNet|.
|
||||||
|
double get used => monthNet.abs();
|
||||||
|
|
||||||
|
double get progress => target <= 0 ? 0 : used / target;
|
||||||
|
|
||||||
|
bool get overBudget => target > 0 && used > target;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter [all] the same way Transactions does (pool → search → flow/amount).
|
||||||
|
List<BankTransaction> applyTransactionFilter({
|
||||||
|
required List<BankTransaction> all,
|
||||||
|
required TxMetaController meta,
|
||||||
|
required TransactionFilterSelection filter,
|
||||||
|
DateTime? month,
|
||||||
|
bool forceMonthOnly = false,
|
||||||
|
}) {
|
||||||
|
final nowMonth = monthStart(month ?? DateTime.now());
|
||||||
|
final limitToMonth = forceMonthOnly || filter.monthOnly;
|
||||||
|
final pool = limitToMonth
|
||||||
|
? [
|
||||||
|
for (final tx in all)
|
||||||
|
if (_txInMonth(tx, nowMonth)) tx,
|
||||||
|
]
|
||||||
|
: all;
|
||||||
|
|
||||||
|
return [
|
||||||
|
for (final tx in meta.search(
|
||||||
|
pool,
|
||||||
|
filter.query,
|
||||||
|
labelIds: filter.labelIds,
|
||||||
|
))
|
||||||
|
if (txMatchesFlow(tx, filter.flow) &&
|
||||||
|
txMatchesAmountRange(tx, filter.amountRange))
|
||||||
|
tx,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
TxFilterMetrics computeTxFilterMetrics({
|
||||||
|
required List<BankTransaction> all,
|
||||||
|
required TxMetaController meta,
|
||||||
|
required TransactionFilterSelection filter,
|
||||||
|
DateTime? month,
|
||||||
|
bool forceMonthOnly = false,
|
||||||
|
}) {
|
||||||
|
final filtered = applyTransactionFilter(
|
||||||
|
all: all,
|
||||||
|
meta: meta,
|
||||||
|
filter: filter,
|
||||||
|
month: month,
|
||||||
|
forceMonthOnly: forceMonthOnly,
|
||||||
|
);
|
||||||
|
var amountIn = 0.0;
|
||||||
|
var amountOut = 0.0;
|
||||||
|
for (final tx in filtered) {
|
||||||
|
if (meta.metaFor(tx).internalTransfer) continue;
|
||||||
|
if (tx.amount < 0) {
|
||||||
|
amountOut += tx.amount.abs();
|
||||||
|
} else if (tx.amount > 0) {
|
||||||
|
amountIn += tx.amount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return TxFilterMetrics(
|
||||||
|
count: filtered.length,
|
||||||
|
amountIn: amountIn,
|
||||||
|
amountOut: amountOut,
|
||||||
|
transactions: filtered,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Budget progress: this month’s |net| vs fixed or average-of-last-N-months cap.
|
||||||
|
HomeBudgetMetrics computeHomeBudgetMetrics({
|
||||||
|
required List<BankTransaction> all,
|
||||||
|
required TxMetaController meta,
|
||||||
|
required HomeFilterWidget widget,
|
||||||
|
DateTime? now,
|
||||||
|
}) {
|
||||||
|
final today = now ?? DateTime.now();
|
||||||
|
final currentMonth = monthStart(today);
|
||||||
|
final monthFilter = widget.filter;
|
||||||
|
final monthNet = computeTxFilterMetrics(
|
||||||
|
all: all,
|
||||||
|
meta: meta,
|
||||||
|
filter: monthFilter,
|
||||||
|
month: currentMonth,
|
||||||
|
forceMonthOnly: true,
|
||||||
|
).net;
|
||||||
|
|
||||||
|
final months = widget.budgetAverageMonths.clamp(1, 36);
|
||||||
|
final double target;
|
||||||
|
if (widget.budgetCapMode == HomeBudgetCapMode.fixed) {
|
||||||
|
target = widget.budgetFixedAmount.abs();
|
||||||
|
} else {
|
||||||
|
var sum = 0.0;
|
||||||
|
for (var i = 1; i <= months; i++) {
|
||||||
|
final month = addMonths(currentMonth, -i);
|
||||||
|
sum += computeTxFilterMetrics(
|
||||||
|
all: all,
|
||||||
|
meta: meta,
|
||||||
|
filter: monthFilter,
|
||||||
|
month: month,
|
||||||
|
forceMonthOnly: true,
|
||||||
|
).net.abs();
|
||||||
|
}
|
||||||
|
target = sum / months;
|
||||||
|
}
|
||||||
|
|
||||||
|
return HomeBudgetMetrics(
|
||||||
|
monthNet: monthNet,
|
||||||
|
target: target,
|
||||||
|
averageMonths: months,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _txInMonth(BankTransaction tx, DateTime month) {
|
||||||
|
final date = DateTime.tryParse(tx.date);
|
||||||
|
if (date == null) return false;
|
||||||
|
return isSameMonth(date, month);
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
/// Home card for a saved transaction-filter widget.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../models/bank.dart';
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
|
import '../providers/bank_provider.dart';
|
||||||
|
import '../providers/tx_meta_provider.dart';
|
||||||
|
import '../screens/transactions_screen.dart';
|
||||||
|
import '../utils/app_theme.dart';
|
||||||
|
import '../utils/helpers.dart';
|
||||||
|
import '../utils/tx_filter_metrics.dart';
|
||||||
|
|
||||||
|
class HomeFilterWidgetCard extends StatelessWidget {
|
||||||
|
const HomeFilterWidgetCard({
|
||||||
|
super.key,
|
||||||
|
required this.widgetConfig,
|
||||||
|
this.editing = false,
|
||||||
|
this.onToggleDisplay,
|
||||||
|
this.onEdit,
|
||||||
|
this.dragHandle,
|
||||||
|
});
|
||||||
|
|
||||||
|
final HomeFilterWidget widgetConfig;
|
||||||
|
final bool editing;
|
||||||
|
final ValueChanged<bool>? onToggleDisplay;
|
||||||
|
final VoidCallback? onEdit;
|
||||||
|
final Widget? dragHandle;
|
||||||
|
|
||||||
|
void _openTransactions(BuildContext context) {
|
||||||
|
final filter = widgetConfig.filter;
|
||||||
|
Navigator.of(context).push(
|
||||||
|
MaterialPageRoute<void>(
|
||||||
|
builder: (_) => TransactionsScreen(
|
||||||
|
initialLabelIds: filter.labelIds,
|
||||||
|
initialSearchInMonthOnly:
|
||||||
|
widgetConfig.type == HomeWidgetType.budget || filter.monthOnly,
|
||||||
|
initialQuery: filter.query,
|
||||||
|
initialFlow: filter.flow,
|
||||||
|
initialAmountRange: filter.amountRange,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final bank = context.watch<BankController>();
|
||||||
|
final meta = context.watch<TxMetaController>();
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colors = theme.colorScheme;
|
||||||
|
final currency = bank.balance?.currency ??
|
||||||
|
(bank.transactions.isNotEmpty
|
||||||
|
? bank.transactions.first.currency
|
||||||
|
: 'EUR');
|
||||||
|
|
||||||
|
final hidden = editing && !widgetConfig.display;
|
||||||
|
|
||||||
|
return Opacity(
|
||||||
|
opacity: hidden ? 0.45 : 1,
|
||||||
|
child: Card(
|
||||||
|
color: colors.surfaceContainer,
|
||||||
|
elevation: 0,
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||||
|
child: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
onTap: editing ? onEdit : () => _openTransactions(context),
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(
|
||||||
|
14,
|
||||||
|
12,
|
||||||
|
editing ? 4 : 14,
|
||||||
|
12,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
if (dragHandle != null) ...[
|
||||||
|
dragHandle!,
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
],
|
||||||
|
Icon(
|
||||||
|
widgetConfig.icon,
|
||||||
|
color: colors.primary,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: widgetConfig.type == HomeWidgetType.budget
|
||||||
|
? _BudgetBody(
|
||||||
|
widgetConfig: widgetConfig,
|
||||||
|
currency: currency,
|
||||||
|
transactions: bank.transactions,
|
||||||
|
meta: meta,
|
||||||
|
)
|
||||||
|
: _StatsBody(
|
||||||
|
widgetConfig: widgetConfig,
|
||||||
|
currency: currency,
|
||||||
|
transactions: bank.transactions,
|
||||||
|
meta: meta,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (editing && onToggleDisplay != null)
|
||||||
|
IconButton(
|
||||||
|
tooltip: widgetConfig.display
|
||||||
|
? 'Hide from Home'
|
||||||
|
: 'Show on Home',
|
||||||
|
onPressed: () =>
|
||||||
|
onToggleDisplay!(!widgetConfig.display),
|
||||||
|
icon: Icon(
|
||||||
|
widgetConfig.display
|
||||||
|
? Icons.remove_circle_outline
|
||||||
|
: Icons.add_circle_outline,
|
||||||
|
color: widgetConfig.display
|
||||||
|
? colors.error
|
||||||
|
: colors.primary,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StatsBody extends StatelessWidget {
|
||||||
|
const _StatsBody({
|
||||||
|
required this.widgetConfig,
|
||||||
|
required this.currency,
|
||||||
|
required this.transactions,
|
||||||
|
required this.meta,
|
||||||
|
});
|
||||||
|
|
||||||
|
final HomeFilterWidget widgetConfig;
|
||||||
|
final String currency;
|
||||||
|
final List<BankTransaction> transactions;
|
||||||
|
final TxMetaController meta;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colors = theme.colorScheme;
|
||||||
|
final metrics = computeTxFilterMetrics(
|
||||||
|
all: transactions,
|
||||||
|
meta: meta,
|
||||||
|
filter: widgetConfig.filter,
|
||||||
|
);
|
||||||
|
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
widgetConfig.name,
|
||||||
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _BudgetBody extends StatelessWidget {
|
||||||
|
const _BudgetBody({
|
||||||
|
required this.widgetConfig,
|
||||||
|
required this.currency,
|
||||||
|
required this.transactions,
|
||||||
|
required this.meta,
|
||||||
|
});
|
||||||
|
|
||||||
|
final HomeFilterWidget widgetConfig;
|
||||||
|
final String currency;
|
||||||
|
final List<BankTransaction> transactions;
|
||||||
|
final TxMetaController meta;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colors = theme.colorScheme;
|
||||||
|
final budget = computeHomeBudgetMetrics(
|
||||||
|
all: transactions,
|
||||||
|
meta: meta,
|
||||||
|
widget: widgetConfig,
|
||||||
|
);
|
||||||
|
final progress = budget.progress.clamp(0.0, 1.0);
|
||||||
|
final over = budget.overBudget;
|
||||||
|
final fillColor = over ? colors.error : colors.primary;
|
||||||
|
final trackColor = colors.surfaceContainerHighest;
|
||||||
|
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
widgetConfig.name,
|
||||||
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
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),
|
||||||
|
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(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 52,
|
||||||
|
height: 52,
|
||||||
|
child: CustomPaint(
|
||||||
|
painter: _BudgetChartPainter(
|
||||||
|
progress: budget.target <= 0 ? 0 : progress,
|
||||||
|
style: widgetConfig.chartStyle,
|
||||||
|
fillColor: fillColor,
|
||||||
|
trackColor: trackColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _BudgetChartPainter extends CustomPainter {
|
||||||
|
_BudgetChartPainter({
|
||||||
|
required this.progress,
|
||||||
|
required this.style,
|
||||||
|
required this.fillColor,
|
||||||
|
required this.trackColor,
|
||||||
|
});
|
||||||
|
|
||||||
|
final double progress;
|
||||||
|
final HomeWidgetChartStyle style;
|
||||||
|
final Color fillColor;
|
||||||
|
final Color trackColor;
|
||||||
|
|
||||||
|
@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;
|
||||||
|
|
||||||
|
if (style == HomeWidgetChartStyle.pie) {
|
||||||
|
final rect = Rect.fromCircle(center: center, radius: radius);
|
||||||
|
final track = Paint()..color = trackColor;
|
||||||
|
canvas.drawCircle(center, radius, track);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRepaint(covariant _BudgetChartPainter oldDelegate) {
|
||||||
|
return oldDelegate.progress != progress ||
|
||||||
|
oldDelegate.style != style ||
|
||||||
|
oldDelegate.fillColor != fillColor ||
|
||||||
|
oldDelegate.trackColor != trackColor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Metric extends StatelessWidget {
|
||||||
|
const _Metric({
|
||||||
|
required this.label,
|
||||||
|
required this.value,
|
||||||
|
required this.color,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final String value;
|
||||||
|
final Color color;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
label,
|
||||||
|
style: theme.textTheme.labelSmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
value,
|
||||||
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
|
color: color,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,526 @@
|
|||||||
|
/// Manage Home filter widgets: display, metrics, add/remove.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../models/home_filter_widget.dart';
|
||||||
|
import '../models/transaction_meta.dart';
|
||||||
|
import '../providers/bank_provider.dart';
|
||||||
|
import '../providers/preferences_provider.dart';
|
||||||
|
import '../providers/tx_meta_provider.dart';
|
||||||
|
import '../widgets/label_filter_dialog.dart';
|
||||||
|
import '../widgets/overview_favourites_sheet.dart' show promptFavouriteName;
|
||||||
|
|
||||||
|
Future<void> showHomeWidgetsSheet(BuildContext context) {
|
||||||
|
return showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (context) {
|
||||||
|
return Padding(
|
||||||
|
padding: EdgeInsets.only(
|
||||||
|
bottom: MediaQuery.viewInsetsOf(context).bottom,
|
||||||
|
),
|
||||||
|
child: const _HomeWidgetsSheet(),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<HomeFilterWidget?> composeHomeFilterWidget(
|
||||||
|
BuildContext context, {
|
||||||
|
TransactionFilterSelection? initialFilter,
|
||||||
|
HomeFilterWidget? existing,
|
||||||
|
bool skipFilterDialog = false,
|
||||||
|
}) async {
|
||||||
|
// Capture before any modal opens — the caller's element may be rebuilt.
|
||||||
|
final bank = context.read<BankController>();
|
||||||
|
final meta = context.read<TxMetaController>();
|
||||||
|
final navigator = Navigator.of(context);
|
||||||
|
|
||||||
|
TransactionFilterSelection? filter = initialFilter ?? existing?.filter;
|
||||||
|
if (!skipFilterDialog || filter == null) {
|
||||||
|
filter = await showTransactionFilterDialog(
|
||||||
|
navigator.context,
|
||||||
|
available: meta.allLabels,
|
||||||
|
transactions: bank.transactions,
|
||||||
|
initial: filter ?? const TransactionFilterSelection(labelIds: {}),
|
||||||
|
);
|
||||||
|
if (filter == null || !navigator.mounted) return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!navigator.mounted) return null;
|
||||||
|
final 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)
|
||||||
|
: existing.copyWith(
|
||||||
|
name: name,
|
||||||
|
labelIds: filter.labelIds.toList(growable: false),
|
||||||
|
flow: filter.flow,
|
||||||
|
amountRange: filter.amountRange,
|
||||||
|
query: filter.query,
|
||||||
|
monthOnly: filter.monthOnly,
|
||||||
|
);
|
||||||
|
|
||||||
|
return _promptWidgetMetrics(navigator.context, draft);
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: const Text('Save'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
).whenComplete(amountController.dispose);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HomeWidgetsSheet extends StatelessWidget {
|
||||||
|
const _HomeWidgetsSheet();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final prefs = context.watch<PreferencesController>();
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final widgets = prefs.homeFilterWidgets;
|
||||||
|
|
||||||
|
return SafeArea(
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: BoxConstraints(
|
||||||
|
maxHeight: MediaQuery.sizeOf(context).height * 0.72,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Home layout', style: theme.textTheme.titleLarge),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
'Choose which built-in sections and filter widgets appear '
|
||||||
|
'on Home. Check Display to show an item.',
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
CheckboxListTile(
|
||||||
|
value: prefs.homeBuiltInSections.showTransactions,
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value == null) return;
|
||||||
|
prefs.setHomeShowTransactions(value);
|
||||||
|
},
|
||||||
|
title: const Text('Transactions'),
|
||||||
|
subtitle: const Text('Total transaction count'),
|
||||||
|
controlAffinity: ListTileControlAffinity.leading,
|
||||||
|
),
|
||||||
|
CheckboxListTile(
|
||||||
|
value: prefs.homeBuiltInSections.showCategorized,
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value == null) return;
|
||||||
|
prefs.setHomeShowCategorized(value);
|
||||||
|
},
|
||||||
|
title: const Text('Categorized'),
|
||||||
|
subtitle: const Text('Labeled transaction count'),
|
||||||
|
controlAffinity: ListTileControlAffinity.leading,
|
||||||
|
),
|
||||||
|
CheckboxListTile(
|
||||||
|
value: prefs.homeBuiltInSections.showRecent,
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value == null) return;
|
||||||
|
prefs.setHomeShowRecent(value);
|
||||||
|
},
|
||||||
|
title: const Text('Recent transactions'),
|
||||||
|
subtitle: const Text('Latest activity list'),
|
||||||
|
controlAffinity: ListTileControlAffinity.leading,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(height: 1),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||||
|
child: OutlinedButton.icon(
|
||||||
|
onPressed: () async {
|
||||||
|
final preferences = context.read<PreferencesController>();
|
||||||
|
final created = await composeHomeFilterWidget(context);
|
||||||
|
if (created == null) return;
|
||||||
|
await preferences.addHomeFilterWidget(created);
|
||||||
|
},
|
||||||
|
icon: const Icon(Icons.add),
|
||||||
|
label: const Text('Add filter widget'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(height: 1),
|
||||||
|
Expanded(
|
||||||
|
child: widgets.isEmpty
|
||||||
|
? Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: Text(
|
||||||
|
'No filter widgets yet. Add one here, or save a '
|
||||||
|
'filter from Transactions.',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: ListView.separated(
|
||||||
|
padding: const EdgeInsets.fromLTRB(8, 8, 8, 24),
|
||||||
|
itemCount: widgets.length,
|
||||||
|
separatorBuilder: (_, _) => const Divider(height: 1),
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final widgetItem = widgets[index];
|
||||||
|
return CheckboxListTile(
|
||||||
|
value: widgetItem.display,
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value == null) return;
|
||||||
|
prefs.setHomeFilterWidgetDisplay(
|
||||||
|
widgetItem.id,
|
||||||
|
value,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
secondary: PopupMenuButton<String>(
|
||||||
|
tooltip: 'Widget actions',
|
||||||
|
onSelected: (value) async {
|
||||||
|
if (value == 'edit') {
|
||||||
|
final preferences =
|
||||||
|
context.read<PreferencesController>();
|
||||||
|
final updated =
|
||||||
|
await composeHomeFilterWidget(
|
||||||
|
context,
|
||||||
|
existing: widgetItem,
|
||||||
|
);
|
||||||
|
if (updated == null) return;
|
||||||
|
await preferences
|
||||||
|
.updateHomeFilterWidget(updated);
|
||||||
|
} else if (value == 'delete') {
|
||||||
|
await prefs
|
||||||
|
.removeHomeFilterWidget(widgetItem.id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
itemBuilder: (context) => const [
|
||||||
|
PopupMenuItem(
|
||||||
|
value: 'edit',
|
||||||
|
child: Text('Edit'),
|
||||||
|
),
|
||||||
|
PopupMenuItem(
|
||||||
|
value: 'delete',
|
||||||
|
child: Text('Delete'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
title: Text(widgetItem.name),
|
||||||
|
subtitle: Text(
|
||||||
|
'${_subtitle(widgetItem)}\n'
|
||||||
|
'Display on Home',
|
||||||
|
),
|
||||||
|
isThreeLine: true,
|
||||||
|
controlAffinity: ListTileControlAffinity.leading,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _subtitle(HomeFilterWidget w) {
|
||||||
|
final parts = <String>[
|
||||||
|
w.type == HomeWidgetType.budget ? 'Budget' : 'Stats',
|
||||||
|
if (w.type == HomeWidgetType.budget)
|
||||||
|
w.budgetCapMode == HomeBudgetCapMode.fixed
|
||||||
|
? 'Fixed'
|
||||||
|
: 'Avg ${w.budgetAverageMonths}mo',
|
||||||
|
if (w.type == HomeWidgetType.budget) w.chartStyle.name,
|
||||||
|
if (w.monthOnly) 'This month',
|
||||||
|
if (w.flow != TxFlowFilter.all) w.flow.name,
|
||||||
|
if (w.labelIds.isNotEmpty) '${w.labelIds.length} labels',
|
||||||
|
if (w.query.trim().isNotEmpty) '“${w.query.trim()}”',
|
||||||
|
if (w.type == HomeWidgetType.stats && w.showAmountIn) 'In',
|
||||||
|
if (w.type == HomeWidgetType.stats && w.showAmountOut) 'Out',
|
||||||
|
if (w.type == HomeWidgetType.stats && w.showCount) 'Count',
|
||||||
|
if (w.halfWidth) 'Half',
|
||||||
|
];
|
||||||
|
return parts.join(' · ');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -446,6 +446,8 @@ class _SimpleLabelFilterDialogState extends State<_SimpleLabelFilterDialog> {
|
|||||||
onToggle: _toggle,
|
onToggle: _toggle,
|
||||||
allowMove: widget.allowMove,
|
allowMove: widget.allowMove,
|
||||||
shrinkWrap: true,
|
shrinkWrap: true,
|
||||||
|
parentOf: meta.parentIdOf,
|
||||||
|
expandAll: needle.isNotEmpty,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -868,6 +870,8 @@ class _TransactionFilterDialogState extends State<_TransactionFilterDialog> {
|
|||||||
onToggle: _toggle,
|
onToggle: _toggle,
|
||||||
allowMove: false,
|
allowMove: false,
|
||||||
shrinkWrap: true,
|
shrinkWrap: true,
|
||||||
|
parentOf: meta.parentIdOf,
|
||||||
|
expandAll: needle.isNotEmpty,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
],
|
],
|
||||||
@@ -914,14 +918,16 @@ List<LabelTreeEntry> _filterLabelEntries({
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
class _LabelChecklist extends StatelessWidget {
|
class _LabelChecklist extends StatefulWidget {
|
||||||
const _LabelChecklist({
|
const _LabelChecklist({
|
||||||
required this.entries,
|
required this.entries,
|
||||||
required this.showUncategorized,
|
required this.showUncategorized,
|
||||||
required this.selected,
|
required this.selected,
|
||||||
required this.onToggle,
|
required this.onToggle,
|
||||||
required this.allowMove,
|
required this.allowMove,
|
||||||
|
required this.parentOf,
|
||||||
this.shrinkWrap = false,
|
this.shrinkWrap = false,
|
||||||
|
this.expandAll = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
final List<LabelTreeEntry> entries;
|
final List<LabelTreeEntry> entries;
|
||||||
@@ -929,13 +935,62 @@ class _LabelChecklist extends StatelessWidget {
|
|||||||
final Set<String> selected;
|
final Set<String> selected;
|
||||||
final void Function(String id, bool selected) onToggle;
|
final void Function(String id, bool selected) onToggle;
|
||||||
final bool allowMove;
|
final bool allowMove;
|
||||||
|
final String? Function(String id) parentOf;
|
||||||
final bool shrinkWrap;
|
final bool shrinkWrap;
|
||||||
|
final bool expandAll;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_LabelChecklist> createState() => _LabelChecklistState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _LabelChecklistState extends State<_LabelChecklist> {
|
||||||
|
final Set<String> _expanded = {};
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(covariant _LabelChecklist oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
if (widget.expandAll && !oldWidget.expandAll) {
|
||||||
|
_expanded
|
||||||
|
..clear()
|
||||||
|
..addAll({
|
||||||
|
for (final entry in widget.entries)
|
||||||
|
if (_hasChildren(entry.label.id)) entry.label.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _hasChildren(String id) {
|
||||||
|
for (final entry in widget.entries) {
|
||||||
|
if (widget.parentOf(entry.label.id) == id) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _isVisible(String id) {
|
||||||
|
if (widget.expandAll) return true;
|
||||||
|
var parent = widget.parentOf(id);
|
||||||
|
while (parent != null) {
|
||||||
|
if (!_expanded.contains(parent)) return false;
|
||||||
|
parent = widget.parentOf(parent);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _toggleExpanded(String id) {
|
||||||
|
setState(() {
|
||||||
|
if (_expanded.contains(id)) {
|
||||||
|
_expanded.remove(id);
|
||||||
|
} else {
|
||||||
|
_expanded.add(id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final colors = theme.colorScheme;
|
final colors = theme.colorScheme;
|
||||||
if (entries.isEmpty && !showUncategorized) {
|
if (widget.entries.isEmpty && !widget.showUncategorized) {
|
||||||
return DecoratedBox(
|
return DecoratedBox(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: colors.surfaceContainerHighest,
|
color: colors.surfaceContainerHighest,
|
||||||
@@ -958,6 +1013,11 @@ class _LabelChecklist extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final visibleEntries = [
|
||||||
|
for (final entry in widget.entries)
|
||||||
|
if (_isVisible(entry.label.id)) entry,
|
||||||
|
];
|
||||||
|
|
||||||
return DecoratedBox(
|
return DecoratedBox(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: colors.surfaceContainerHighest,
|
color: colors.surfaceContainerHighest,
|
||||||
@@ -969,12 +1029,13 @@ class _LabelChecklist extends StatelessWidget {
|
|||||||
child: ClipRRect(
|
child: ClipRRect(
|
||||||
borderRadius: BorderRadius.circular(10),
|
borderRadius: BorderRadius.circular(10),
|
||||||
child: ListView.separated(
|
child: ListView.separated(
|
||||||
shrinkWrap: shrinkWrap,
|
shrinkWrap: widget.shrinkWrap,
|
||||||
physics: shrinkWrap
|
physics: widget.shrinkWrap
|
||||||
? const NeverScrollableScrollPhysics()
|
? const NeverScrollableScrollPhysics()
|
||||||
: null,
|
: null,
|
||||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
itemCount: entries.length + (showUncategorized ? 1 : 0),
|
itemCount:
|
||||||
|
visibleEntries.length + (widget.showUncategorized ? 1 : 0),
|
||||||
separatorBuilder: (_, _) => Divider(
|
separatorBuilder: (_, _) => Divider(
|
||||||
height: 1,
|
height: 1,
|
||||||
thickness: 1,
|
thickness: 1,
|
||||||
@@ -982,28 +1043,35 @@ class _LabelChecklist extends StatelessWidget {
|
|||||||
color: colors.outlineVariant.withValues(alpha: 0.45),
|
color: colors.outlineVariant.withValues(alpha: 0.45),
|
||||||
),
|
),
|
||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
if (showUncategorized && index == 0) {
|
if (widget.showUncategorized && index == 0) {
|
||||||
return _FilterRow(
|
return _FilterRow(
|
||||||
depth: 0,
|
depth: 0,
|
||||||
icon: kUncategorizedFilterLabel.icon,
|
icon: kUncategorizedFilterLabel.icon,
|
||||||
color: kUncategorizedFilterLabel.color,
|
color: kUncategorizedFilterLabel.color,
|
||||||
name: kUncategorizedFilterLabel.name,
|
name: kUncategorizedFilterLabel.name,
|
||||||
checked: selected.contains(kUncategorizedFilterId),
|
checked: widget.selected.contains(kUncategorizedFilterId),
|
||||||
onToggle: (value) =>
|
onToggle: (value) =>
|
||||||
onToggle(kUncategorizedFilterId, value),
|
widget.onToggle(kUncategorizedFilterId, value),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final entry =
|
final entry = visibleEntries[
|
||||||
entries[showUncategorized ? index - 1 : index];
|
widget.showUncategorized ? index - 1 : index];
|
||||||
final label = entry.label;
|
final label = entry.label;
|
||||||
|
final hasChildren = _hasChildren(label.id);
|
||||||
|
final expanded =
|
||||||
|
widget.expandAll || _expanded.contains(label.id);
|
||||||
return _FilterRow(
|
return _FilterRow(
|
||||||
depth: entry.depth,
|
depth: entry.depth,
|
||||||
icon: label.icon,
|
icon: label.icon,
|
||||||
color: label.color,
|
color: label.color,
|
||||||
name: label.name,
|
name: label.name,
|
||||||
checked: selected.contains(label.id),
|
checked: widget.selected.contains(label.id),
|
||||||
onToggle: (value) => onToggle(label.id, value),
|
onToggle: (value) => widget.onToggle(label.id, value),
|
||||||
onLongPress: allowMove
|
hasChildren: hasChildren,
|
||||||
|
expanded: expanded,
|
||||||
|
onExpandToggle:
|
||||||
|
hasChildren ? () => _toggleExpanded(label.id) : null,
|
||||||
|
onLongPress: widget.allowMove
|
||||||
? () async {
|
? () async {
|
||||||
await showMoveLabelDialog(context, label: label);
|
await showMoveLabelDialog(context, label: label);
|
||||||
}
|
}
|
||||||
@@ -1134,6 +1202,9 @@ class _FilterRow extends StatelessWidget {
|
|||||||
required this.checked,
|
required this.checked,
|
||||||
required this.onToggle,
|
required this.onToggle,
|
||||||
this.onLongPress,
|
this.onLongPress,
|
||||||
|
this.hasChildren = false,
|
||||||
|
this.expanded = false,
|
||||||
|
this.onExpandToggle,
|
||||||
});
|
});
|
||||||
|
|
||||||
final int depth;
|
final int depth;
|
||||||
@@ -1143,26 +1214,52 @@ class _FilterRow extends StatelessWidget {
|
|||||||
final bool checked;
|
final bool checked;
|
||||||
final ValueChanged<bool> onToggle;
|
final ValueChanged<bool> onToggle;
|
||||||
final VoidCallback? onLongPress;
|
final VoidCallback? onLongPress;
|
||||||
|
final bool hasChildren;
|
||||||
|
final bool expanded;
|
||||||
|
final VoidCallback? onExpandToggle;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final colors = theme.colorScheme;
|
final colors = theme.colorScheme;
|
||||||
return InkWell(
|
return InkWell(
|
||||||
onTap: () => onToggle(!checked),
|
onTap: () {
|
||||||
|
if (hasChildren && onExpandToggle != null) {
|
||||||
|
onExpandToggle!();
|
||||||
|
} else {
|
||||||
|
onToggle(!checked);
|
||||||
|
}
|
||||||
|
},
|
||||||
onLongPress: onLongPress,
|
onLongPress: onLongPress,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: EdgeInsets.fromLTRB(8 + depth * 16.0, 2, 4, 2),
|
padding: EdgeInsets.fromLTRB(8 + depth * 16.0, 2, 4, 2),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
if (depth > 0) ...[
|
SizedBox(
|
||||||
Icon(
|
width: 28,
|
||||||
|
height: 32,
|
||||||
|
child: hasChildren
|
||||||
|
? IconButton(
|
||||||
|
tooltip: expanded ? 'Collapse' : 'Expand',
|
||||||
|
onPressed: onExpandToggle,
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
icon: Icon(
|
||||||
|
expanded
|
||||||
|
? Icons.expand_more
|
||||||
|
: Icons.chevron_right,
|
||||||
|
size: 20,
|
||||||
|
color: colors.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: depth > 0
|
||||||
|
? Icon(
|
||||||
Icons.subdirectory_arrow_right,
|
Icons.subdirectory_arrow_right,
|
||||||
size: 14,
|
size: 14,
|
||||||
color: colors.onSurfaceVariant,
|
color: colors.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
: null,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 4),
|
|
||||||
],
|
|
||||||
Icon(icon, size: 18, color: color),
|
Icon(icon, size: 18, color: color),
|
||||||
const SizedBox(width: 10),
|
const SizedBox(width: 10),
|
||||||
Expanded(
|
Expanded(
|
||||||
|
|||||||
@@ -0,0 +1,491 @@
|
|||||||
|
/// Manage Overview favourites: display toggles, rename, delete, save current.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../models/overview_favourite.dart';
|
||||||
|
import '../models/transaction_meta.dart';
|
||||||
|
import '../providers/preferences_provider.dart';
|
||||||
|
import '../providers/tx_meta_provider.dart';
|
||||||
|
import 'label_filter_dialog.dart';
|
||||||
|
|
||||||
|
Future<void> showOverviewFavouritesSheet(
|
||||||
|
BuildContext context, {
|
||||||
|
required OverviewFavourite? Function() currentFilterSnapshot,
|
||||||
|
}) {
|
||||||
|
return showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (context) {
|
||||||
|
return Padding(
|
||||||
|
padding: EdgeInsets.only(
|
||||||
|
bottom: MediaQuery.viewInsetsOf(context).bottom,
|
||||||
|
),
|
||||||
|
child: _OverviewFavouritesSheet(
|
||||||
|
currentFilterSnapshot: currentFilterSnapshot,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> promptFavouriteName(
|
||||||
|
BuildContext context, {
|
||||||
|
String initial = '',
|
||||||
|
String title = 'Name this favourite',
|
||||||
|
}) {
|
||||||
|
return showDialog<String>(
|
||||||
|
context: context,
|
||||||
|
useRootNavigator: true,
|
||||||
|
builder: (dialogContext) {
|
||||||
|
return _FavouriteNameDialog(
|
||||||
|
initial: initial,
|
||||||
|
title: title,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Edit an existing favourite (name, metric, period, labels, display).
|
||||||
|
Future<void> showEditOverviewFavouriteSheet(
|
||||||
|
BuildContext context, {
|
||||||
|
required OverviewFavourite favourite,
|
||||||
|
}) {
|
||||||
|
return showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (context) {
|
||||||
|
return Padding(
|
||||||
|
padding: EdgeInsets.only(
|
||||||
|
bottom: MediaQuery.viewInsetsOf(context).bottom,
|
||||||
|
),
|
||||||
|
child: _EditOverviewFavouriteSheet(favourite: favourite),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FavouriteNameDialog extends StatefulWidget {
|
||||||
|
const _FavouriteNameDialog({
|
||||||
|
required this.initial,
|
||||||
|
required this.title,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String initial;
|
||||||
|
final String title;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_FavouriteNameDialog> createState() => _FavouriteNameDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FavouriteNameDialogState extends State<_FavouriteNameDialog> {
|
||||||
|
late final TextEditingController _controller;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_controller = TextEditingController(text: widget.initial);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_controller.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _submit() {
|
||||||
|
final name = _controller.text.trim();
|
||||||
|
if (name.isEmpty) return;
|
||||||
|
Navigator.of(context).pop(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: Text(widget.title),
|
||||||
|
content: TextField(
|
||||||
|
controller: _controller,
|
||||||
|
autofocus: true,
|
||||||
|
textCapitalization: TextCapitalization.sentences,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Name',
|
||||||
|
hintText: 'e.g. Groceries this year',
|
||||||
|
),
|
||||||
|
onSubmitted: (_) => _submit(),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: _submit,
|
||||||
|
child: const Text('Save'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _OverviewFavouritesSheet extends StatelessWidget {
|
||||||
|
const _OverviewFavouritesSheet({required this.currentFilterSnapshot});
|
||||||
|
|
||||||
|
final OverviewFavourite? Function() currentFilterSnapshot;
|
||||||
|
|
||||||
|
Future<void> _saveCurrent(BuildContext context) async {
|
||||||
|
final prefs = context.read<PreferencesController>();
|
||||||
|
final snap = currentFilterSnapshot();
|
||||||
|
if (snap == null) return;
|
||||||
|
|
||||||
|
final name = await promptFavouriteName(context);
|
||||||
|
if (name == null || !context.mounted) return;
|
||||||
|
|
||||||
|
// Let the dialog route + IME finish tearing down before notifying
|
||||||
|
// dependents (avoids wrong-build-scope / _dependents asserts).
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
if (!context.mounted) return;
|
||||||
|
|
||||||
|
await prefs.addOverviewFavourite(snap.copyWith(name: name));
|
||||||
|
if (!context.mounted) return;
|
||||||
|
|
||||||
|
final messenger = ScaffoldMessenger.maybeOf(context);
|
||||||
|
messenger?.showSnackBar(SnackBar(content: Text('Saved “$name”')));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final prefs = context.watch<PreferencesController>();
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final favourites = prefs.overviewFavourites;
|
||||||
|
|
||||||
|
return SafeArea(
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: BoxConstraints(
|
||||||
|
maxHeight: MediaQuery.sizeOf(context).height * 0.72,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Favourites', style: theme.textTheme.titleLarge),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
'Check Display for each favourite you want on the Favourites '
|
||||||
|
'view — all checked ones show as charts. Save as many filters '
|
||||||
|
'as you like.',
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||||
|
child: OutlinedButton.icon(
|
||||||
|
onPressed: () => _saveCurrent(context),
|
||||||
|
icon: const Icon(Icons.star_outline),
|
||||||
|
label: const Text('Save current filter'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(height: 1),
|
||||||
|
Expanded(
|
||||||
|
child: favourites.isEmpty
|
||||||
|
? Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: Text(
|
||||||
|
'No favourites yet. Set up Flow or Labels on Overview, '
|
||||||
|
'then save the current filter.',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: ListView.separated(
|
||||||
|
padding: const EdgeInsets.fromLTRB(8, 8, 8, 24),
|
||||||
|
itemCount: favourites.length,
|
||||||
|
separatorBuilder: (_, _) => const Divider(height: 1),
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final fav = favourites[index];
|
||||||
|
return CheckboxListTile(
|
||||||
|
value: fav.display,
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value == null) return;
|
||||||
|
prefs.setOverviewFavouriteDisplay(fav.id, value);
|
||||||
|
},
|
||||||
|
secondary: IconButton(
|
||||||
|
tooltip: 'Delete',
|
||||||
|
onPressed: () =>
|
||||||
|
prefs.removeOverviewFavourite(fav.id),
|
||||||
|
icon: const Icon(Icons.delete_outline),
|
||||||
|
),
|
||||||
|
title: Text(fav.name),
|
||||||
|
subtitle: Text(
|
||||||
|
'${_subtitle(fav)}\n'
|
||||||
|
'Display on Favourites view',
|
||||||
|
),
|
||||||
|
isThreeLine: true,
|
||||||
|
controlAffinity: ListTileControlAffinity.leading,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _subtitle(OverviewFavourite fav) {
|
||||||
|
final metric =
|
||||||
|
fav.metric == OverviewMetricMode.flow ? 'Flow' : 'Labels';
|
||||||
|
final period =
|
||||||
|
fav.period == OverviewPeriodMode.monthly ? 'Month' : 'Year';
|
||||||
|
if (fav.metric == OverviewMetricMode.flow) {
|
||||||
|
return '$metric · $period';
|
||||||
|
}
|
||||||
|
final flow = switch (fav.flow) {
|
||||||
|
TxFlowFilter.all => 'All',
|
||||||
|
TxFlowFilter.income => 'Income',
|
||||||
|
TxFlowFilter.expense => 'Expenses',
|
||||||
|
};
|
||||||
|
final labels = fav.labelIds.isEmpty
|
||||||
|
? 'All labels'
|
||||||
|
: '${fav.labelIds.length} labels';
|
||||||
|
return '$metric · $period · $flow · $labels';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _EditOverviewFavouriteSheet extends StatefulWidget {
|
||||||
|
const _EditOverviewFavouriteSheet({required this.favourite});
|
||||||
|
|
||||||
|
final OverviewFavourite favourite;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_EditOverviewFavouriteSheet> createState() =>
|
||||||
|
_EditOverviewFavouriteSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _EditOverviewFavouriteSheetState
|
||||||
|
extends State<_EditOverviewFavouriteSheet> {
|
||||||
|
late OverviewFavourite _draft;
|
||||||
|
late final TextEditingController _nameController;
|
||||||
|
|
||||||
|
static const _segmentStyle = ButtonStyle(
|
||||||
|
visualDensity: VisualDensity(horizontal: -2, vertical: -2),
|
||||||
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 12)),
|
||||||
|
minimumSize: WidgetStatePropertyAll(Size(0, 36)),
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_draft = widget.favourite;
|
||||||
|
_nameController = TextEditingController(text: _draft.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_nameController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _persist(OverviewFavourite next) async {
|
||||||
|
setState(() => _draft = next);
|
||||||
|
await context.read<PreferencesController>().updateOverviewFavourite(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _editLabels() async {
|
||||||
|
final meta = context.read<TxMetaController>();
|
||||||
|
final available = meta.allLabels;
|
||||||
|
|
||||||
|
final initial = <String>{
|
||||||
|
if (_draft.labelIds.isEmpty)
|
||||||
|
...available.map((l) => l.id)
|
||||||
|
else ...[
|
||||||
|
for (final id in _draft.labelIds)
|
||||||
|
if (id == kUncategorizedFilterId ||
|
||||||
|
available.any((l) => l.id == id))
|
||||||
|
id,
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
final result = await showLabelFilterDialog(
|
||||||
|
context,
|
||||||
|
available: available,
|
||||||
|
initiallySelected: initial,
|
||||||
|
title: 'Labels on chart',
|
||||||
|
subtitle: 'Choose which labels appear on this favourite.',
|
||||||
|
allowMove: true,
|
||||||
|
includeUncategorized: true,
|
||||||
|
includeFlow: true,
|
||||||
|
initialFlow: _draft.flow,
|
||||||
|
includeBarStyle: true,
|
||||||
|
initialBarStyle: _draft.barStyle,
|
||||||
|
includeInvertChart: true,
|
||||||
|
initialInvertChart: _draft.invertExpensePerspective,
|
||||||
|
);
|
||||||
|
if (result == null || !mounted) return;
|
||||||
|
|
||||||
|
final allIds = available.map((l) => l.id).toSet();
|
||||||
|
final hasUncategorized =
|
||||||
|
result.labelIds.contains(kUncategorizedFilterId);
|
||||||
|
final realIds = result.labelIds
|
||||||
|
.where((id) => id != kUncategorizedFilterId)
|
||||||
|
.toSet();
|
||||||
|
final allRealSelected =
|
||||||
|
realIds.length == allIds.length && realIds.containsAll(allIds);
|
||||||
|
final labelIds = !hasUncategorized &&
|
||||||
|
(realIds.isEmpty || allRealSelected)
|
||||||
|
? const <String>[]
|
||||||
|
: result.labelIds.toList(growable: false);
|
||||||
|
|
||||||
|
await _persist(
|
||||||
|
_draft.copyWith(
|
||||||
|
metric: OverviewMetricMode.labels,
|
||||||
|
labelIds: labelIds,
|
||||||
|
flow: result.flow,
|
||||||
|
barStyle: result.barStyle,
|
||||||
|
invertExpensePerspective:
|
||||||
|
result.flow == TxFlowFilter.all && result.invertExpensePerspective,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final prefs = context.read<PreferencesController>();
|
||||||
|
|
||||||
|
return SafeArea(
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: BoxConstraints(
|
||||||
|
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
|
||||||
|
),
|
||||||
|
child: ListView(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 4, 20, 24),
|
||||||
|
children: [
|
||||||
|
Text('Edit favourite', style: theme.textTheme.titleLarge),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
TextField(
|
||||||
|
controller: _nameController,
|
||||||
|
textCapitalization: TextCapitalization.sentences,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Name',
|
||||||
|
),
|
||||||
|
textInputAction: TextInputAction.done,
|
||||||
|
onEditingComplete: () {
|
||||||
|
FocusScope.of(context).unfocus();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
Text('Chart type', style: theme.textTheme.titleSmall),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SegmentedButton<OverviewMetricMode>(
|
||||||
|
showSelectedIcon: false,
|
||||||
|
style: _segmentStyle,
|
||||||
|
segments: const [
|
||||||
|
ButtonSegment(
|
||||||
|
value: OverviewMetricMode.flow,
|
||||||
|
label: Text('Flow'),
|
||||||
|
),
|
||||||
|
ButtonSegment(
|
||||||
|
value: OverviewMetricMode.labels,
|
||||||
|
label: Text('Labels'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
selected: {_draft.metric},
|
||||||
|
onSelectionChanged: (selection) {
|
||||||
|
_persist(_draft.copyWith(metric: selection.first));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text('Period', style: theme.textTheme.titleSmall),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SegmentedButton<OverviewPeriodMode>(
|
||||||
|
showSelectedIcon: false,
|
||||||
|
style: _segmentStyle,
|
||||||
|
segments: const [
|
||||||
|
ButtonSegment(
|
||||||
|
value: OverviewPeriodMode.monthly,
|
||||||
|
label: Text('Month'),
|
||||||
|
),
|
||||||
|
ButtonSegment(
|
||||||
|
value: OverviewPeriodMode.yearly,
|
||||||
|
label: Text('Year'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
selected: {_draft.period},
|
||||||
|
onSelectionChanged: (selection) {
|
||||||
|
_persist(_draft.copyWith(period: selection.first));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SwitchListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const Text('Display on Favourites view'),
|
||||||
|
value: _draft.display,
|
||||||
|
onChanged: (value) {
|
||||||
|
_persist(_draft.copyWith(display: value));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
if (_draft.metric == OverviewMetricMode.labels) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: const Icon(Icons.filter_list),
|
||||||
|
title: const Text('Label filter'),
|
||||||
|
subtitle: Text(
|
||||||
|
_draft.labelIds.isEmpty
|
||||||
|
? 'All labels · ${_draft.flow.name}'
|
||||||
|
: '${_draft.labelIds.length} labels · ${_draft.flow.name}',
|
||||||
|
),
|
||||||
|
trailing: const Icon(Icons.chevron_right),
|
||||||
|
onTap: _editLabels,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () async {
|
||||||
|
final name = _nameController.text.trim();
|
||||||
|
final next =
|
||||||
|
name.isEmpty ? _draft : _draft.copyWith(name: name);
|
||||||
|
await prefs.updateOverviewFavourite(next);
|
||||||
|
if (!context.mounted) return;
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
},
|
||||||
|
child: const Text('Done'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: () async {
|
||||||
|
await prefs.removeOverviewFavourite(_draft.id);
|
||||||
|
if (!context.mounted) return;
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
},
|
||||||
|
icon: Icon(
|
||||||
|
Icons.delete_outline,
|
||||||
|
color: theme.colorScheme.error,
|
||||||
|
),
|
||||||
|
label: Text(
|
||||||
|
'Delete favourite',
|
||||||
|
style: TextStyle(color: theme.colorScheme.error),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,10 @@ final RouteObserver<ModalRoute<void>> appRouteObserver =
|
|||||||
RouteObserver<ModalRoute<void>>();
|
RouteObserver<ModalRoute<void>>();
|
||||||
|
|
||||||
/// Builds via [builder] only when this route is not covered by a pushed page.
|
/// Builds via [builder] only when this route is not covered by a pushed page.
|
||||||
|
///
|
||||||
|
/// Only [PageRoute]s count as covering (via [RouteAware]). Modal bottom sheets
|
||||||
|
/// and dialogs must not tear down the subtree — async flows started from Home
|
||||||
|
/// (e.g. compose widget → name → options) need a mounted context between steps.
|
||||||
class SkipBuildWhenCovered extends StatefulWidget {
|
class SkipBuildWhenCovered extends StatefulWidget {
|
||||||
const SkipBuildWhenCovered({
|
const SkipBuildWhenCovered({
|
||||||
super.key,
|
super.key,
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
/// PocketBase migration: Overview chart favourites.
|
||||||
|
///
|
||||||
|
/// Apply on the server (from /opt/pocketbase or wherever the binary lives):
|
||||||
|
///
|
||||||
|
/// sudo cp this_file /opt/pocketbase/pb_migrations/
|
||||||
|
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
|
||||||
|
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
|
||||||
|
/// sudo systemctl restart pocketbase
|
||||||
|
///
|
||||||
|
/// Depends on usersapp (same owner rules as labels / recurring_templates).
|
||||||
|
migrate((app) => {
|
||||||
|
const users = app.findCollectionByNameOrId("usersapp");
|
||||||
|
|
||||||
|
const ownerRules = {
|
||||||
|
listRule: "user = @request.auth.id",
|
||||||
|
viewRule: "user = @request.auth.id",
|
||||||
|
createRule: "@request.auth.id != '' && user = @request.auth.id",
|
||||||
|
updateRule: "user = @request.auth.id",
|
||||||
|
deleteRule: "user = @request.auth.id",
|
||||||
|
};
|
||||||
|
|
||||||
|
const overviewFavourites = new Collection({
|
||||||
|
type: "base",
|
||||||
|
name: "overview_favourites",
|
||||||
|
...ownerRules,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
type: "relation",
|
||||||
|
name: "user",
|
||||||
|
required: true,
|
||||||
|
collectionId: users.id,
|
||||||
|
cascadeDelete: true,
|
||||||
|
maxSelect: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// App-side OverviewFavourite.id
|
||||||
|
type: "text",
|
||||||
|
name: "client_id",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 120,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "name",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Show on Favourites overview view
|
||||||
|
type: "bool",
|
||||||
|
name: "display",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// "flow" | "labels"
|
||||||
|
type: "text",
|
||||||
|
name: "metric",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 32,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// "monthly" | "yearly"
|
||||||
|
type: "text",
|
||||||
|
name: "period",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 32,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Label client_ids included on Labels chart ([] = all)
|
||||||
|
type: "json",
|
||||||
|
name: "label_ids",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// "all" | "income" | "expense"
|
||||||
|
type: "text",
|
||||||
|
name: "flow",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 32,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// "parallel" | "stacked"
|
||||||
|
type: "text",
|
||||||
|
name: "bar_style",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 32,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "bool",
|
||||||
|
name: "invert_expense_perspective",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
indexes: [
|
||||||
|
"CREATE UNIQUE INDEX idx_overview_favourites_user_client ON overview_favourites (user, client_id)",
|
||||||
|
],
|
||||||
|
});
|
||||||
|
app.save(overviewFavourites);
|
||||||
|
}, (app) => {
|
||||||
|
try {
|
||||||
|
const col = app.findCollectionByNameOrId("overview_favourites");
|
||||||
|
app.delete(col);
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
/// PocketBase migration: Home filter widgets.
|
||||||
|
///
|
||||||
|
/// Apply on the server:
|
||||||
|
///
|
||||||
|
/// sudo cp this_file /opt/pocketbase/pb_migrations/
|
||||||
|
/// sudo chown pocketbase:pocketbase /opt/pocketbase/pb_migrations/*.js
|
||||||
|
/// sudo -u pocketbase /opt/pocketbase/pocketbase migrate up
|
||||||
|
/// sudo systemctl restart pocketbase
|
||||||
|
///
|
||||||
|
/// Depends on usersapp (same owner rules as overview_favourites).
|
||||||
|
migrate((app) => {
|
||||||
|
const users = app.findCollectionByNameOrId("usersapp");
|
||||||
|
|
||||||
|
const ownerRules = {
|
||||||
|
listRule: "user = @request.auth.id",
|
||||||
|
viewRule: "user = @request.auth.id",
|
||||||
|
createRule: "@request.auth.id != '' && user = @request.auth.id",
|
||||||
|
updateRule: "user = @request.auth.id",
|
||||||
|
deleteRule: "user = @request.auth.id",
|
||||||
|
};
|
||||||
|
|
||||||
|
const homeFilterWidgets = new Collection({
|
||||||
|
type: "base",
|
||||||
|
name: "home_filter_widgets",
|
||||||
|
...ownerRules,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
type: "relation",
|
||||||
|
name: "user",
|
||||||
|
required: true,
|
||||||
|
collectionId: users.id,
|
||||||
|
cascadeDelete: true,
|
||||||
|
maxSelect: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "client_id",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 120,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "name",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "bool",
|
||||||
|
name: "display",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "number",
|
||||||
|
name: "sort_order",
|
||||||
|
required: false,
|
||||||
|
onlyInt: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "bool",
|
||||||
|
name: "half_width",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "widget_type",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "icon_id",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "chart_style",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "budget_cap_mode",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "number",
|
||||||
|
name: "budget_fixed_amount",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "number",
|
||||||
|
name: "budget_average_months",
|
||||||
|
required: false,
|
||||||
|
onlyInt: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "json",
|
||||||
|
name: "label_ids",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "flow",
|
||||||
|
required: true,
|
||||||
|
min: 1,
|
||||||
|
max: 32,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "json",
|
||||||
|
name: "amount_range",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
name: "query",
|
||||||
|
required: false,
|
||||||
|
max: 400,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "bool",
|
||||||
|
name: "month_only",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "bool",
|
||||||
|
name: "show_amount_in",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "bool",
|
||||||
|
name: "show_amount_out",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "bool",
|
||||||
|
name: "show_count",
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
indexes: [
|
||||||
|
"CREATE UNIQUE INDEX idx_home_filter_widgets_user_client ON home_filter_widgets (user, client_id)",
|
||||||
|
],
|
||||||
|
});
|
||||||
|
app.save(homeFilterWidgets);
|
||||||
|
}, (app) => {
|
||||||
|
try {
|
||||||
|
const col = app.findCollectionByNameOrId("home_filter_widgets");
|
||||||
|
app.delete(col);
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/// PocketBase migration: half_width on home_filter_widgets.
|
||||||
|
///
|
||||||
|
/// Apply after 1740000004 if that collection already exists.
|
||||||
|
migrate((app) => {
|
||||||
|
const col = app.findCollectionByNameOrId("home_filter_widgets");
|
||||||
|
col.fields.add({
|
||||||
|
type: "bool",
|
||||||
|
name: "half_width",
|
||||||
|
required: false,
|
||||||
|
});
|
||||||
|
app.save(col);
|
||||||
|
}, (app) => {
|
||||||
|
try {
|
||||||
|
const col = app.findCollectionByNameOrId("home_filter_widgets");
|
||||||
|
const field = col.fields.getByName("half_width");
|
||||||
|
if (field) {
|
||||||
|
col.fields.remove(field);
|
||||||
|
app.save(col);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
/// PocketBase migration: budget / chart / icon fields on home_filter_widgets.
|
||||||
|
migrate((app) => {
|
||||||
|
const col = app.findCollectionByNameOrId("home_filter_widgets");
|
||||||
|
col.fields.add({
|
||||||
|
type: "text",
|
||||||
|
name: "widget_type",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
});
|
||||||
|
col.fields.add({
|
||||||
|
type: "text",
|
||||||
|
name: "icon_id",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
});
|
||||||
|
col.fields.add({
|
||||||
|
type: "text",
|
||||||
|
name: "chart_style",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
});
|
||||||
|
col.fields.add({
|
||||||
|
type: "text",
|
||||||
|
name: "budget_cap_mode",
|
||||||
|
required: false,
|
||||||
|
max: 40,
|
||||||
|
});
|
||||||
|
col.fields.add({
|
||||||
|
type: "number",
|
||||||
|
name: "budget_fixed_amount",
|
||||||
|
required: false,
|
||||||
|
});
|
||||||
|
col.fields.add({
|
||||||
|
type: "number",
|
||||||
|
name: "budget_average_months",
|
||||||
|
required: false,
|
||||||
|
onlyInt: true,
|
||||||
|
});
|
||||||
|
app.save(col);
|
||||||
|
}, (app) => {
|
||||||
|
try {
|
||||||
|
const col = app.findCollectionByNameOrId("home_filter_widgets");
|
||||||
|
for (const name of [
|
||||||
|
"widget_type",
|
||||||
|
"icon_id",
|
||||||
|
"chart_style",
|
||||||
|
"budget_cap_mode",
|
||||||
|
"budget_fixed_amount",
|
||||||
|
"budget_average_months",
|
||||||
|
]) {
|
||||||
|
const field = col.fields.getByName(name);
|
||||||
|
if (field) col.fields.remove(field);
|
||||||
|
}
|
||||||
|
app.save(col);
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:myapp/models/home_filter_widget.dart';
|
||||||
|
import 'package:myapp/models/transaction_meta.dart';
|
||||||
|
import 'package:myapp/widgets/label_filter_dialog.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('HomeFilterWidget JSON round-trips', () {
|
||||||
|
final widget = HomeFilterWidget.fromFilter(
|
||||||
|
name: 'Groceries out',
|
||||||
|
filter: const TransactionFilterSelection(
|
||||||
|
labelIds: {'groceries'},
|
||||||
|
flow: TxFlowFilter.expense,
|
||||||
|
monthOnly: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final restored = HomeFilterWidget.fromJson(widget.toJson());
|
||||||
|
expect(restored.name, 'Groceries out');
|
||||||
|
expect(restored.flow, TxFlowFilter.expense);
|
||||||
|
expect(restored.monthOnly, isTrue);
|
||||||
|
expect(restored.labelIds, ['groceries']);
|
||||||
|
expect(restored.showAmountOut, isTrue);
|
||||||
|
expect(restored.showAmountIn, isFalse);
|
||||||
|
expect(restored.showCount, isTrue);
|
||||||
|
expect(restored.halfWidth, isFalse);
|
||||||
|
expect(restored.type, HomeWidgetType.stats);
|
||||||
|
|
||||||
|
final budget = widget.copyWith(
|
||||||
|
halfWidth: true,
|
||||||
|
type: HomeWidgetType.budget,
|
||||||
|
iconId: 'cart',
|
||||||
|
chartStyle: HomeWidgetChartStyle.ring,
|
||||||
|
budgetCapMode: HomeBudgetCapMode.averageMonths,
|
||||||
|
budgetAverageMonths: 6,
|
||||||
|
budgetFixedAmount: 250,
|
||||||
|
);
|
||||||
|
final budgetRestored = HomeFilterWidget.fromJson(budget.toJson());
|
||||||
|
expect(budgetRestored.halfWidth, isTrue);
|
||||||
|
expect(budgetRestored.type, HomeWidgetType.budget);
|
||||||
|
expect(budgetRestored.iconId, 'cart');
|
||||||
|
expect(budgetRestored.chartStyle, HomeWidgetChartStyle.ring);
|
||||||
|
expect(budgetRestored.budgetCapMode, HomeBudgetCapMode.averageMonths);
|
||||||
|
expect(budgetRestored.budgetAverageMonths, 6);
|
||||||
|
expect(budgetRestored.budgetFixedAmount, 250);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mergeHomeFilterWidgets unions by id with local wins', () {
|
||||||
|
const local = HomeFilterWidget(
|
||||||
|
id: 'hw_1',
|
||||||
|
name: 'Local',
|
||||||
|
display: true,
|
||||||
|
showAmountIn: false,
|
||||||
|
);
|
||||||
|
const remote = HomeFilterWidget(
|
||||||
|
id: 'hw_1',
|
||||||
|
name: 'Remote',
|
||||||
|
display: false,
|
||||||
|
);
|
||||||
|
const remoteOnly = HomeFilterWidget(
|
||||||
|
id: 'hw_2',
|
||||||
|
name: 'Other',
|
||||||
|
sortOrder: 1,
|
||||||
|
);
|
||||||
|
|
||||||
|
final merged = mergeHomeFilterWidgets([local], [remote, remoteOnly]);
|
||||||
|
expect(merged.length, 2);
|
||||||
|
expect(merged.firstWhere((w) => w.id == 'hw_1').name, 'Local');
|
||||||
|
expect(merged.firstWhere((w) => w.id == 'hw_1').display, isTrue);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:myapp/models/overview_favourite.dart';
|
||||||
|
import 'package:myapp/models/transaction_meta.dart';
|
||||||
|
import 'package:myapp/services/pb_sync_service.dart';
|
||||||
|
import 'package:myapp/widgets/label_filter_dialog.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('OverviewFavourite JSON round-trips', () {
|
||||||
|
const fav = OverviewFavourite(
|
||||||
|
id: 'fav_1',
|
||||||
|
name: 'Groceries',
|
||||||
|
display: true,
|
||||||
|
metric: OverviewMetricMode.labels,
|
||||||
|
period: OverviewPeriodMode.monthly,
|
||||||
|
labelIds: ['groceries', 'custom_ah'],
|
||||||
|
flow: TxFlowFilter.expense,
|
||||||
|
barStyle: LabelChartBarStyle.stacked,
|
||||||
|
invertExpensePerspective: false,
|
||||||
|
);
|
||||||
|
|
||||||
|
final restored = OverviewFavourite.fromJson(fav.toJson());
|
||||||
|
expect(restored.id, fav.id);
|
||||||
|
expect(restored.name, fav.name);
|
||||||
|
expect(restored.display, isTrue);
|
||||||
|
expect(restored.metric, OverviewMetricMode.labels);
|
||||||
|
expect(restored.period, OverviewPeriodMode.monthly);
|
||||||
|
expect(restored.labelIds, ['groceries', 'custom_ah']);
|
||||||
|
expect(restored.flow, TxFlowFilter.expense);
|
||||||
|
expect(restored.barStyle, LabelChartBarStyle.stacked);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mergeOverviewFavourites unions by id with local wins', () {
|
||||||
|
const local = OverviewFavourite(
|
||||||
|
id: 'fav_1',
|
||||||
|
name: 'Local name',
|
||||||
|
display: true,
|
||||||
|
);
|
||||||
|
const remoteOnly = OverviewFavourite(
|
||||||
|
id: 'fav_2',
|
||||||
|
name: 'Remote only',
|
||||||
|
display: false,
|
||||||
|
metric: OverviewMetricMode.labels,
|
||||||
|
);
|
||||||
|
const remoteConflict = OverviewFavourite(
|
||||||
|
id: 'fav_1',
|
||||||
|
name: 'Remote name',
|
||||||
|
display: false,
|
||||||
|
);
|
||||||
|
|
||||||
|
final merged = mergeOverviewFavourites(
|
||||||
|
[local],
|
||||||
|
[remoteConflict, remoteOnly],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(merged.length, 2);
|
||||||
|
final byId = {for (final f in merged) f.id: f};
|
||||||
|
expect(byId['fav_1']!.name, 'Local name');
|
||||||
|
expect(byId['fav_1']!.display, isTrue);
|
||||||
|
expect(byId['fav_2']!.name, 'Remote only');
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user