2 Commits
Author SHA1 Message Date
davmar 86b5f1e09b new widget types 2026-09-10 17:31:18 +02:00
davmar 2727f1baf2 custom filters 2026-09-10 17:23:07 +02:00
17 changed files with 1525 additions and 272 deletions
+43
View File
@@ -0,0 +1,43 @@
/// Visibility flags for built-in Home screen sections.
library;
class HomeBuiltInSections {
const HomeBuiltInSections({
this.showTransactions = true,
this.showCategorized = true,
this.showRecent = true,
});
static const defaults = HomeBuiltInSections();
final bool showTransactions;
final bool showCategorized;
final bool showRecent;
HomeBuiltInSections copyWith({
bool? showTransactions,
bool? showCategorized,
bool? showRecent,
}) {
return HomeBuiltInSections(
showTransactions: showTransactions ?? this.showTransactions,
showCategorized: showCategorized ?? this.showCategorized,
showRecent: showRecent ?? this.showRecent,
);
}
Map<String, dynamic> toJson() => {
'showTransactions': showTransactions,
'showCategorized': showCategorized,
'showRecent': showRecent,
};
factory HomeBuiltInSections.fromJson(Map<String, dynamic>? json) {
if (json == null) return defaults;
return HomeBuiltInSections(
showTransactions: json['showTransactions'] as bool? ?? true,
showCategorized: json['showCategorized'] as bool? ?? true,
showRecent: json['showRecent'] as bool? ?? true,
);
}
}
+137 -2
View File
@@ -1,16 +1,90 @@
/// Named transaction-filter widgets pinned on the Home screen. /// Named transaction-filter widgets pinned on the Home screen.
library; library;
import 'package:flutter/material.dart';
import '../widgets/label_filter_dialog.dart'; import '../widgets/label_filter_dialog.dart';
import 'transaction_meta.dart'; import 'transaction_meta.dart';
/// A saved [TransactionFilterSelection] plus which metrics to show on Home. /// 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 { class HomeFilterWidget {
const HomeFilterWidget({ const HomeFilterWidget({
required this.id, required this.id,
required this.name, required this.name,
this.display = true, this.display = true,
this.sortOrder = 0, 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.labelIds = const [],
this.flow = TxFlowFilter.all, this.flow = TxFlowFilter.all,
this.amountRange = const TxAmountRange(), this.amountRange = const TxAmountRange(),
@@ -26,6 +100,20 @@ class HomeFilterWidget {
final bool display; final bool display;
final int sortOrder; 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 List<String> labelIds;
final TxFlowFilter flow; final TxFlowFilter flow;
final TxAmountRange amountRange; final TxAmountRange amountRange;
@@ -36,6 +124,8 @@ class HomeFilterWidget {
final bool showAmountOut; final bool showAmountOut;
final bool showCount; final bool showCount;
IconData get icon => HomeWidgetIcons.iconFor(iconId);
TransactionFilterSelection get filter => TransactionFilterSelection( TransactionFilterSelection get filter => TransactionFilterSelection(
labelIds: labelIds.toSet(), labelIds: labelIds.toSet(),
flow: flow, flow: flow,
@@ -49,6 +139,13 @@ class HomeFilterWidget {
String? name, String? name,
bool? display, bool? display,
int? sortOrder, int? sortOrder,
bool? halfWidth,
HomeWidgetType? type,
String? iconId,
HomeWidgetChartStyle? chartStyle,
HomeBudgetCapMode? budgetCapMode,
double? budgetFixedAmount,
int? budgetAverageMonths,
List<String>? labelIds, List<String>? labelIds,
TxFlowFilter? flow, TxFlowFilter? flow,
TxAmountRange? amountRange, TxAmountRange? amountRange,
@@ -63,6 +160,13 @@ class HomeFilterWidget {
name: name ?? this.name, name: name ?? this.name,
display: display ?? this.display, display: display ?? this.display,
sortOrder: sortOrder ?? this.sortOrder, 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, labelIds: labelIds ?? this.labelIds,
flow: flow ?? this.flow, flow: flow ?? this.flow,
amountRange: amountRange ?? this.amountRange, amountRange: amountRange ?? this.amountRange,
@@ -103,6 +207,13 @@ class HomeFilterWidget {
'name': name, 'name': name,
'display': display, 'display': display,
'sortOrder': sortOrder, 'sortOrder': sortOrder,
'halfWidth': halfWidth,
'type': type.name,
'iconId': iconId,
'chartStyle': chartStyle.name,
'budgetCapMode': budgetCapMode.name,
'budgetFixedAmount': budgetFixedAmount,
'budgetAverageMonths': budgetAverageMonths,
'labelIds': labelIds, 'labelIds': labelIds,
'flow': flow.name, 'flow': flow.name,
'amountRange': { 'amountRange': {
@@ -127,6 +238,12 @@ class HomeFilterWidget {
return null; 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( return HomeFilterWidget(
id: json['id'] as String? ?? id: json['id'] as String? ??
'hw_${DateTime.now().millisecondsSinceEpoch}', 'hw_${DateTime.now().millisecondsSinceEpoch}',
@@ -134,7 +251,25 @@ class HomeFilterWidget {
? (json['name'] as String).trim() ? (json['name'] as String).trim()
: 'Filter', : 'Filter',
display: json['display'] as bool? ?? true, display: json['display'] as bool? ?? true,
sortOrder: json['sortOrder'] as int? ?? 0, 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: [ labelIds: [
for (final id in (json['labelIds'] as List? ?? const [])) for (final id in (json['labelIds'] as List? ?? const []))
if (id is String && id.isNotEmpty) id, if (id is String && id.isNotEmpty) id,
+41
View File
@@ -3,6 +3,7 @@ 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/home_filter_widget.dart';
import '../models/overview_favourite.dart'; import '../models/overview_favourite.dart';
import '../services/storage_service.dart'; import '../services/storage_service.dart';
@@ -12,12 +13,14 @@ class PreferencesController extends ChangeNotifier {
_lookAheadMaxYears = _storage.lookAheadMaxYears; _lookAheadMaxYears = _storage.lookAheadMaxYears;
_overviewFavourites = _storage.loadOverviewFavourites(); _overviewFavourites = _storage.loadOverviewFavourites();
_homeFilterWidgets = _storage.loadHomeFilterWidgets(); _homeFilterWidgets = _storage.loadHomeFilterWidgets();
_homeBuiltInSections = _storage.loadHomeBuiltInSections();
} }
final StorageService _storage; final StorageService _storage;
late int _lookAheadMaxYears; late int _lookAheadMaxYears;
late List<OverviewFavourite> _overviewFavourites; late List<OverviewFavourite> _overviewFavourites;
late List<HomeFilterWidget> _homeFilterWidgets; late List<HomeFilterWidget> _homeFilterWidgets;
late HomeBuiltInSections _homeBuiltInSections;
/// Fired after favourites are persisted (for cloud push debounce). /// Fired after favourites are persisted (for cloud push debounce).
VoidCallback? onFavouritesPersisted; VoidCallback? onFavouritesPersisted;
@@ -50,6 +53,31 @@ class PreferencesController extends ChangeNotifier {
bool get hasDisplayedHomeFilterWidgets => bool get hasDisplayedHomeFilterWidgets =>
_homeFilterWidgets.any((w) => w.display); _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;
@@ -149,6 +177,19 @@ class PreferencesController extends ChangeNotifier {
await updateHomeFilterWidget(current.copyWith(display: display)); 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( Future<void> replaceHomeFilterWidgets(
List<HomeFilterWidget> widgets, { List<HomeFilterWidget> widgets, {
bool notify = true, bool notify = true,
+107 -34
View File
@@ -39,9 +39,9 @@ class SyncController extends ChangeNotifier {
_bank = bank, _bank = bank,
_prefs = prefs { _prefs = prefs {
_wasLoggedIn = auth.isLoggedIn; _wasLoggedIn = auth.isLoggedIn;
_meta.onPersisted = _schedulePush; _meta.onPersisted = _scheduleMetaPush;
_prefs.onFavouritesPersisted = _schedulePush; _prefs.onFavouritesPersisted = _scheduleFavouritesPush;
_prefs.onHomeWidgetsPersisted = _schedulePush; _prefs.onHomeWidgetsPersisted = _scheduleHomeWidgetsPush;
_auth.addListener(_onAuthChanged); _auth.addListener(_onAuthChanged);
_bank.onAfterSuccessfulLoad = _onBankDataLoaded; _bank.onAfterSuccessfulLoad = _onBankDataLoaded;
if (_auth.isLoggedIn) { if (_auth.isLoggedIn) {
@@ -58,6 +58,9 @@ class SyncController extends ChangeNotifier {
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;
@@ -187,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;
@@ -224,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());
@@ -370,53 +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 summary = await service.push( final parts = <String>[];
_meta.exportStore(), var done = 0;
progressStart: 0.05, final total = (pushMeta ? 1 : 0) +
progressEnd: 0.9, (pushFavourites ? 1 : 0) +
onProgress: _setProgress, (pushHomeWidgets ? 1 : 0);
onStatus: _setStatus, void bump() {
); done++;
try { _setProgress(done / total);
await service.pushOverviewFavourites( }
_prefs.overviewFavourites,
if (pushMeta) {
_setStatus('Pushing annotations…');
final summary = await service.push(
_meta.exportStore(),
progressStart: done / total,
progressEnd: (done + 1) / total,
onProgress: _setProgress,
onStatus: _setStatus, onStatus: _setStatus,
); );
} catch (error) { parts.add(summary);
debugPrint( bump();
'SyncController: overview_favourites push skipped ($error)',
);
} }
try { if (pushFavourites) {
await service.pushHomeFilterWidgets( _setStatus('Pushing favourites…');
_prefs.homeFilterWidgets, try {
onStatus: _setStatus, await service.pushOverviewFavourites(
); _prefs.overviewFavourites,
} catch (error) { onStatus: _setStatus,
debugPrint( );
'SyncController: home_filter_widgets push skipped ($error)', 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); _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) {
+300 -90
View File
@@ -4,6 +4,7 @@ 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/preferences_provider.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
@@ -45,11 +46,11 @@ class _HomeScreenState extends State<HomeScreen> {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(_editingWidgets ? 'Edit widgets' : 'Home'), title: Text(_editingWidgets ? 'Edit Home' : 'Home'),
actions: [ actions: [
if (bank.isLinked || bank.hasData) if (bank.isLinked || bank.hasData)
IconButton( IconButton(
tooltip: _editingWidgets ? 'Done' : 'Edit Home widgets', tooltip: _editingWidgets ? 'Done' : 'Edit Home layout',
onPressed: () => onPressed: () =>
setState(() => _editingWidgets = !_editingWidgets), setState(() => _editingWidgets = !_editingWidgets),
icon: Icon( icon: Icon(
@@ -218,41 +219,74 @@ class _HomeBody extends StatelessWidget {
), ),
), ),
), ),
const SizedBox(height: 20), if (_showBuiltIn(
Row( editing: editingWidgets,
children: [ enabled: prefs.homeBuiltInSections.showTransactions,
Expanded( ) ||
child: _StatChip( _showBuiltIn(
label: 'Transactions', editing: editingWidgets,
value: '${bank.transactions.length}', enabled: prefs.homeBuiltInSections.showCategorized,
icon: Icons.list_alt, )) ...[
), const SizedBox(height: 20),
),
const SizedBox(width: 10),
Expanded(
child: _StatChip(
label: 'Categorized',
value: '$categorized',
icon: Icons.label_outline,
),
),
],
),
if (editingWidgets || widgets.isNotEmpty) ...[
const SizedBox(height: 24),
Row( Row(
children: [ children: [
Text('Widgets', style: theme.textTheme.titleMedium), if (_showBuiltIn(
const Spacer(), editing: editingWidgets,
if (editingWidgets) enabled: prefs.homeBuiltInSections.showTransactions,
TextButton.icon( ))
onPressed: () => showHomeWidgetsSheet(context), Expanded(
icon: const Icon(Icons.add, size: 18), child: _EditableHomeBlock(
label: const Text('Add'), editing: editingWidgets,
visible: prefs.homeBuiltInSections.showTransactions,
onToggleVisible: (value) =>
prefs.setHomeShowTransactions(value),
child: _StatChip(
label: 'Transactions',
value: '${bank.transactions.length}',
icon: Icons.list_alt,
),
),
),
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showTransactions,
) &&
_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showCategorized,
))
const SizedBox(width: 10),
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showCategorized,
))
Expanded(
child: _EditableHomeBlock(
editing: editingWidgets,
visible: prefs.homeBuiltInSections.showCategorized,
onToggleVisible: (value) =>
prefs.setHomeShowCategorized(value),
child: _StatChip(
label: 'Categorized',
value: '$categorized',
icon: Icons.label_outline,
),
),
), ),
], ],
), ),
const SizedBox(height: 8), ],
if (editingWidgets || widgets.isNotEmpty) ...[
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) if (widgets.isEmpty)
Text( Text(
'No widgets yet. Tap Add to pin a transaction filter.', 'No widgets yet. Tap Add to pin a transaction filter.',
@@ -260,68 +294,137 @@ class _HomeBody extends StatelessWidget {
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
) )
else else if (editingWidgets)
for (final widgetConfig in widgets) ...[ ReorderableListView.builder(
HomeFilterWidgetCard( shrinkWrap: true,
widgetConfig: widgetConfig, physics: const NeverScrollableScrollPhysics(),
editing: editingWidgets, buildDefaultDragHandles: false,
onRemove: editingWidgets itemCount: widgets.length,
? () => prefs.removeHomeFilterWidget(widgetConfig.id) onReorderItem: prefs.reorderHomeFilterWidgets,
: null, proxyDecorator: (child, index, animation) {
), return Material(
const SizedBox(height: 10), elevation: 2,
], color: Colors.transparent,
], borderRadius: BorderRadius.circular(16),
if (recent.isNotEmpty) ...[ child: child,
const SizedBox(height: 24), );
Row( },
children: [ itemBuilder: (context, index) {
Text('Recent', style: theme.textTheme.titleMedium), final widgetConfig = widgets[index];
const Spacer(), return Padding(
TextButton( key: ValueKey(widgetConfig.id),
onPressed: () => _openTransactions(context), padding: const EdgeInsets.only(bottom: 10),
child: const Text('See all'), child: _HomeWidgetSlot(
), halfWidth: widgetConfig.halfWidth,
], child: HomeFilterWidgetCard(
), widgetConfig: widgetConfig,
const SizedBox(height: 4), editing: true,
for (final tx in recent) onToggleDisplay: (display) =>
ListTile( prefs.setHomeFilterWidgetDisplay(
contentPadding: EdgeInsets.zero, widgetConfig.id,
dense: true, display,
leading: Builder( ),
builder: (context) { onEdit: () async {
final labels = final preferences =
meta.leafLabelsFor(meta.metaFor(tx)); context.read<PreferencesController>();
final label = labels.isEmpty ? null : labels.first; final updated = await composeHomeFilterWidget(
return Icon( context,
label?.icon ?? Icons.receipt_long_outlined, existing: widgetConfig,
color: label?.color, );
); if (updated == null) return;
}, await preferences.updateHomeFilterWidget(updated);
), },
title: Text( dragHandle: ReorderableDragStartListener(
tx.description, index: index,
maxLines: 1, child: Icon(
overflow: TextOverflow.ellipsis, Icons.drag_handle,
), color: colors.onSurfaceVariant,
subtitle: Text(formatIsoDate(tx.date)), ),
trailing: Text( ),
formatMoney(tx.amount, tx.currency), ),
style: theme.textTheme.titleSmall?.copyWith(
color: tx.amount >= 0
? AppTheme.accent
: AppTheme.expense,
),
),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => TransactionDetailScreen(tx: tx),
), ),
); );
}, },
)
else
..._packedHomeWidgetRows(widgets),
],
if (_showBuiltIn(
editing: editingWidgets,
enabled: prefs.homeBuiltInSections.showRecent,
) &&
(recent.isNotEmpty || editingWidgets)) ...[
const SizedBox(height: 24),
_EditableHomeBlock(
editing: editingWidgets,
visible: prefs.homeBuiltInSections.showRecent,
onToggleVisible: (value) => prefs.setHomeShowRecent(value),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Text('Recent', style: theme.textTheme.titleMedium),
const Spacer(),
TextButton(
onPressed: () => _openTransactions(context),
child: const Text('See all'),
),
],
),
const SizedBox(height: 4),
if (recent.isEmpty)
Text(
'No recent transactions yet.',
style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant,
),
)
else
for (final tx in recent)
ListTile(
contentPadding: EdgeInsets.zero,
dense: true,
leading: Builder(
builder: (context) {
final labels =
meta.leafLabelsFor(meta.metaFor(tx));
final label =
labels.isEmpty ? null : labels.first;
return Icon(
label?.icon ?? Icons.receipt_long_outlined,
color: label?.color,
);
},
),
title: Text(
tx.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: Text(formatIsoDate(tx.date)),
trailing: Text(
formatMoney(tx.amount, tx.currency),
style: theme.textTheme.titleSmall?.copyWith(
color: tx.amount >= 0
? AppTheme.accent
: AppTheme.expense,
),
),
onTap: editingWidgets
? null
: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) =>
TransactionDetailScreen(tx: tx),
),
);
},
),
],
), ),
),
], ],
if (bank.error != null) ...[ if (bank.error != null) ...[
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -382,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;
}
+3 -2
View File
@@ -241,6 +241,7 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
} }
Future<void> _saveAsHomeWidget() async { Future<void> _saveAsHomeWidget() async {
final preferences = context.read<PreferencesController>();
final created = await composeHomeFilterWidget( final created = await composeHomeFilterWidget(
context, context,
initialFilter: TransactionFilterSelection( initialFilter: TransactionFilterSelection(
@@ -252,8 +253,8 @@ class _TransactionsScreenState extends State<TransactionsScreen> {
), ),
skipFilterDialog: true, skipFilterDialog: true,
); );
if (created == null || !mounted) return; if (created == null) return;
await context.read<PreferencesController>().addHomeFilterWidget(created); await preferences.addHomeFilterWidget(created);
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Added “${created.name}” to Home')), SnackBar(content: Text('Added “${created.name}” to Home')),
+31
View File
@@ -520,6 +520,17 @@ class PbSyncService {
'name': r.getStringValue('name'), 'name': r.getStringValue('name'),
'display': r.getBoolValue('display', true), 'display': r.getBoolValue('display', true),
'sortOrder': r.getIntValue('sort_order', 0), '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')), 'labelIds': _jsonStringList(r.get<dynamic>('label_ids')),
'flow': r.getStringValue('flow'), 'flow': r.getStringValue('flow'),
'amountRange': rangeRaw is Map 'amountRange': rangeRaw is Map
@@ -1197,6 +1208,13 @@ class PbSyncService {
'name': _clip(w.name.isEmpty ? 'Filter' : w.name, 200), 'name': _clip(w.name.isEmpty ? 'Filter' : w.name, 200),
'display': w.display, 'display': w.display,
'sort_order': w.sortOrder, 'sort_order': w.sortOrder,
'half_width': w.halfWidth,
'widget_type': w.type.name,
'icon_id': w.iconId,
'chart_style': w.chartStyle.name,
'budget_cap_mode': w.budgetCapMode.name,
'budget_fixed_amount': w.budgetFixedAmount,
'budget_average_months': w.budgetAverageMonths,
'label_ids': w.labelIds, 'label_ids': w.labelIds,
'flow': w.flow.name, 'flow': w.flow.name,
'amount_range': { 'amount_range': {
@@ -1294,9 +1312,22 @@ class PbSyncService {
? Map<String, dynamic>.from(rangeRaw) ? Map<String, dynamic>.from(rangeRaw)
: const <String, dynamic>{}; : const <String, dynamic>{};
double? asDouble(dynamic value) => value is num ? value.toDouble() : null; 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 && return remote.getStringValue('name') == w.name &&
remote.getBoolValue('display', true) == w.display && remote.getBoolValue('display', true) == w.display &&
remote.getIntValue('sort_order', 0) == w.sortOrder && 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) && _sameIdList(remoteIds, w.labelIds) &&
remote.getStringValue('flow') == w.flow.name && remote.getStringValue('flow') == w.flow.name &&
asDouble(rangeMap['exact']) == w.amountRange.exact && asDouble(rangeMap['exact']) == w.amountRange.exact &&
+22
View File
@@ -7,6 +7,7 @@ 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/home_filter_widget.dart';
import '../models/overview_favourite.dart'; import '../models/overview_favourite.dart';
import '../models/transaction_meta.dart'; import '../models/transaction_meta.dart';
@@ -183,6 +184,27 @@ class StorageService {
return _prefs.setString(StorageKeys.homeFilterWidgets, encoded); 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) {
+3
View File
@@ -57,6 +57,9 @@ abstract final class StorageKeys {
/// Home screen filter widgets (JSON list). /// Home screen filter widgets (JSON list).
static const homeFilterWidgets = 'home_filter_widgets_v1'; 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].
+73 -1
View File
@@ -2,6 +2,7 @@
library; library;
import '../models/bank.dart'; import '../models/bank.dart';
import '../models/home_filter_widget.dart';
import '../models/transaction_meta.dart'; import '../models/transaction_meta.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
import '../utils/tx_calendar.dart'; import '../utils/tx_calendar.dart';
@@ -23,15 +24,40 @@ class TxFilterMetrics {
double get net => amountIn - amountOut; 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). /// Filter [all] the same way Transactions does (pool → search → flow/amount).
List<BankTransaction> applyTransactionFilter({ List<BankTransaction> applyTransactionFilter({
required List<BankTransaction> all, required List<BankTransaction> all,
required TxMetaController meta, required TxMetaController meta,
required TransactionFilterSelection filter, required TransactionFilterSelection filter,
DateTime? month, DateTime? month,
bool forceMonthOnly = false,
}) { }) {
final nowMonth = monthStart(month ?? DateTime.now()); final nowMonth = monthStart(month ?? DateTime.now());
final pool = filter.monthOnly final limitToMonth = forceMonthOnly || filter.monthOnly;
final pool = limitToMonth
? [ ? [
for (final tx in all) for (final tx in all)
if (_txInMonth(tx, nowMonth)) tx, if (_txInMonth(tx, nowMonth)) tx,
@@ -55,12 +81,14 @@ TxFilterMetrics computeTxFilterMetrics({
required TxMetaController meta, required TxMetaController meta,
required TransactionFilterSelection filter, required TransactionFilterSelection filter,
DateTime? month, DateTime? month,
bool forceMonthOnly = false,
}) { }) {
final filtered = applyTransactionFilter( final filtered = applyTransactionFilter(
all: all, all: all,
meta: meta, meta: meta,
filter: filter, filter: filter,
month: month, month: month,
forceMonthOnly: forceMonthOnly,
); );
var amountIn = 0.0; var amountIn = 0.0;
var amountOut = 0.0; var amountOut = 0.0;
@@ -80,6 +108,50 @@ TxFilterMetrics computeTxFilterMetrics({
); );
} }
/// 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) { bool _txInMonth(BankTransaction tx, DateTime month) {
final date = DateTime.tryParse(tx.date); final date = DateTime.tryParse(tx.date);
if (date == null) return false; if (date == null) return false;
+295 -73
View File
@@ -1,9 +1,12 @@
/// Home card for a saved transaction-filter widget. /// Home card for a saved transaction-filter widget.
library; library;
import 'dart:math' as math;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../models/bank.dart';
import '../models/home_filter_widget.dart'; import '../models/home_filter_widget.dart';
import '../providers/bank_provider.dart'; import '../providers/bank_provider.dart';
import '../providers/tx_meta_provider.dart'; import '../providers/tx_meta_provider.dart';
@@ -17,20 +20,25 @@ class HomeFilterWidgetCard extends StatelessWidget {
super.key, super.key,
required this.widgetConfig, required this.widgetConfig,
this.editing = false, this.editing = false,
this.onRemove, this.onToggleDisplay,
this.onEdit,
this.dragHandle,
}); });
final HomeFilterWidget widgetConfig; final HomeFilterWidget widgetConfig;
final bool editing; final bool editing;
final VoidCallback? onRemove; final ValueChanged<bool>? onToggleDisplay;
final VoidCallback? onEdit;
final Widget? dragHandle;
void _open(BuildContext context) { void _openTransactions(BuildContext context) {
final filter = widgetConfig.filter; final filter = widgetConfig.filter;
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute<void>( MaterialPageRoute<void>(
builder: (_) => TransactionsScreen( builder: (_) => TransactionsScreen(
initialLabelIds: filter.labelIds, initialLabelIds: filter.labelIds,
initialSearchInMonthOnly: filter.monthOnly, initialSearchInMonthOnly:
widgetConfig.type == HomeWidgetType.budget || filter.monthOnly,
initialQuery: filter.query, initialQuery: filter.query,
initialFlow: filter.flow, initialFlow: filter.flow,
initialAmountRange: filter.amountRange, initialAmountRange: filter.amountRange,
@@ -50,78 +58,68 @@ class HomeFilterWidgetCard extends StatelessWidget {
? bank.transactions.first.currency ? bank.transactions.first.currency
: 'EUR'); : 'EUR');
final metrics = computeTxFilterMetrics( final hidden = editing && !widgetConfig.display;
all: bank.transactions,
meta: meta,
filter: widgetConfig.filter,
);
return Card( return Opacity(
color: colors.surfaceContainer, opacity: hidden ? 0.45 : 1,
elevation: 0, child: Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), color: colors.surfaceContainer,
child: InkWell( elevation: 0,
borderRadius: BorderRadius.circular(16), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
onTap: editing ? null : () => _open(context), child: InkWell(
child: Padding( borderRadius: BorderRadius.circular(16),
padding: const EdgeInsets.fromLTRB(14, 12, 8, 12), onTap: editing ? onEdit : () => _openTransactions(context),
child: Row( child: Padding(
children: [ padding: EdgeInsets.fromLTRB(
Expanded( 14,
child: Column( 12,
crossAxisAlignment: CrossAxisAlignment.start, editing ? 4 : 14,
children: [ 12,
Text( ),
widgetConfig.name, child: Row(
style: theme.textTheme.titleSmall?.copyWith( children: [
fontWeight: FontWeight.w700, if (dragHandle != null) ...[
), dragHandle!,
maxLines: 1, const SizedBox(width: 4),
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,
),
],
),
],
),
),
if (editing)
IconButton(
tooltip: 'Remove from Home',
onPressed: onRemove,
icon: Icon(
Icons.remove_circle_outline,
color: colors.error,
),
)
else
Icon( Icon(
Icons.chevron_right, widgetConfig.icon,
color: colors.onSurfaceVariant, 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,
),
),
],
),
), ),
), ),
), ),
@@ -129,6 +127,230 @@ class HomeFilterWidgetCard extends StatelessWidget {
} }
} }
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 { class _Metric extends StatelessWidget {
const _Metric({ const _Metric({
required this.label, required this.label,
+324 -58
View File
@@ -34,28 +34,33 @@ Future<HomeFilterWidget?> composeHomeFilterWidget(
HomeFilterWidget? existing, HomeFilterWidget? existing,
bool skipFilterDialog = false, bool skipFilterDialog = false,
}) async { }) 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; TransactionFilterSelection? filter = initialFilter ?? existing?.filter;
if (!skipFilterDialog || filter == null) { if (!skipFilterDialog || filter == null) {
final bank = context.read<BankController>();
final meta = context.read<TxMetaController>();
filter = await showTransactionFilterDialog( filter = await showTransactionFilterDialog(
context, navigator.context,
available: meta.allLabels, available: meta.allLabels,
transactions: bank.transactions, transactions: bank.transactions,
initial: filter ?? const TransactionFilterSelection(labelIds: {}), initial: filter ?? const TransactionFilterSelection(labelIds: {}),
); );
if (filter == null || !context.mounted) return null; if (filter == null || !navigator.mounted) return null;
} }
if (!navigator.mounted) return null;
final name = await promptFavouriteName( final name = await promptFavouriteName(
context, navigator.context,
initial: existing?.name ?? '', initial: existing?.name ?? '',
title: existing == null ? 'Name this widget' : 'Rename widget', title: existing == null ? 'Name this widget' : 'Rename widget',
); );
if (name == null || !context.mounted) return null; if (name == null || !navigator.mounted) return null;
await Future<void>.delayed(Duration.zero); // Let the name dialog finish popping before presenting options.
if (!context.mounted) return null; await WidgetsBinding.instance.endOfFrame;
if (!navigator.mounted) return null;
final draft = existing == null final draft = existing == null
? HomeFilterWidget.fromFilter(name: name, filter: filter) ? HomeFilterWidget.fromFilter(name: name, filter: filter)
@@ -68,16 +73,30 @@ Future<HomeFilterWidget?> composeHomeFilterWidget(
monthOnly: filter.monthOnly, monthOnly: filter.monthOnly,
); );
return _promptWidgetMetrics(context, draft); return _promptWidgetMetrics(navigator.context, draft);
} }
Future<HomeFilterWidget?> _promptWidgetMetrics( Future<HomeFilterWidget?> _promptWidgetMetrics(
BuildContext context, BuildContext context,
HomeFilterWidget draft, 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 showIn = draft.showAmountIn;
var showOut = draft.showAmountOut; var showOut = draft.showAmountOut;
var showCount = draft.showCount; 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>( return showDialog<HomeFilterWidget>(
context: context, context: context,
@@ -85,33 +104,195 @@ Future<HomeFilterWidget?> _promptWidgetMetrics(
builder: (context) { builder: (context) {
return StatefulBuilder( return StatefulBuilder(
builder: (context, setState) { builder: (context, setState) {
final theme = Theme.of(context);
return AlertDialog( return AlertDialog(
title: const Text('Widget metrics'), title: const Text('Widget options'),
content: Column( content: SizedBox(
mainAxisSize: MainAxisSize.min, width: 360,
children: [ child: SingleChildScrollView(
CheckboxListTile( child: Column(
contentPadding: EdgeInsets.zero, mainAxisSize: MainAxisSize.min,
title: const Text('Amount in'), crossAxisAlignment: CrossAxisAlignment.stretch,
value: showIn, children: [
onChanged: (value) => Text('Type', style: theme.textTheme.titleSmall),
setState(() => showIn = value ?? false), 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,
),
),
],
],
), ),
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),
),
],
), ),
actions: [ actions: [
TextButton( TextButton(
@@ -120,12 +301,33 @@ Future<HomeFilterWidget?> _promptWidgetMetrics(
), ),
FilledButton( FilledButton(
onPressed: () { onPressed: () {
if (!showIn && !showOut && !showCount) return; 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( Navigator.of(context).pop(
draft.copyWith( draft.copyWith(
type: type,
iconId: iconId,
chartStyle: chartStyle,
budgetCapMode: budgetCapMode,
budgetFixedAmount: fixed,
budgetAverageMonths: budgetAverageMonths,
showAmountIn: showIn, showAmountIn: showIn,
showAmountOut: showOut, showAmountOut: showOut,
showCount: showCount, showCount: showCount,
halfWidth: halfWidth,
), ),
); );
}, },
@@ -136,7 +338,7 @@ Future<HomeFilterWidget?> _promptWidgetMetrics(
}, },
); );
}, },
); ).whenComplete(amountController.dispose);
} }
class _HomeWidgetsSheet extends StatelessWidget { class _HomeWidgetsSheet extends StatelessWidget {
@@ -161,11 +363,11 @@ class _HomeWidgetsSheet extends StatelessWidget {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text('Home widgets', style: theme.textTheme.titleLarge), Text('Home layout', style: theme.textTheme.titleLarge),
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
'Pin saved transaction filters on Home. Check Display to ' 'Choose which built-in sections and filter widgets appear '
'show a widget; edit metrics or remove anytime.', 'on Home. Check Display to show an item.',
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant, color: theme.colorScheme.onSurfaceVariant,
), ),
@@ -174,12 +376,51 @@ class _HomeWidgetsSheet extends StatelessWidget {
), ),
), ),
Padding( Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), 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( child: OutlinedButton.icon(
onPressed: () async { onPressed: () async {
final preferences = context.read<PreferencesController>();
final created = await composeHomeFilterWidget(context); final created = await composeHomeFilterWidget(context);
if (created == null || !context.mounted) return; if (created == null) return;
await prefs.addHomeFilterWidget(created); await preferences.addHomeFilterWidget(created);
}, },
icon: const Icon(Icons.add), icon: const Icon(Icons.add),
label: const Text('Add filter widget'), label: const Text('Add filter widget'),
@@ -192,8 +433,8 @@ class _HomeWidgetsSheet extends StatelessWidget {
child: Padding( child: Padding(
padding: const EdgeInsets.all(24), padding: const EdgeInsets.all(24),
child: Text( child: Text(
'No widgets yet. Add a filter, or save one from ' 'No filter widgets yet. Add one here, or save a '
'Transactions.', 'filter from Transactions.',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant, color: theme.colorScheme.onSurfaceVariant,
@@ -216,17 +457,35 @@ class _HomeWidgetsSheet extends StatelessWidget {
value, value,
); );
}, },
secondary: IconButton( secondary: PopupMenuButton<String>(
tooltip: 'Edit', tooltip: 'Widget actions',
onPressed: () async { onSelected: (value) async {
final updated = await composeHomeFilterWidget( if (value == 'edit') {
context, final preferences =
existing: widgetItem, context.read<PreferencesController>();
); final updated =
if (updated == null || !context.mounted) return; await composeHomeFilterWidget(
await prefs.updateHomeFilterWidget(updated); context,
existing: widgetItem,
);
if (updated == null) return;
await preferences
.updateHomeFilterWidget(updated);
} else if (value == 'delete') {
await prefs
.removeHomeFilterWidget(widgetItem.id);
}
}, },
icon: const Icon(Icons.edit_outlined), itemBuilder: (context) => const [
PopupMenuItem(
value: 'edit',
child: Text('Edit'),
),
PopupMenuItem(
value: 'delete',
child: Text('Delete'),
),
],
), ),
title: Text(widgetItem.name), title: Text(widgetItem.name),
subtitle: Text( subtitle: Text(
@@ -247,14 +506,21 @@ class _HomeWidgetsSheet extends StatelessWidget {
static String _subtitle(HomeFilterWidget w) { static String _subtitle(HomeFilterWidget w) {
final parts = <String>[ 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.monthOnly) 'This month',
if (w.flow != TxFlowFilter.all) w.flow.name, if (w.flow != TxFlowFilter.all) w.flow.name,
if (w.labelIds.isNotEmpty) '${w.labelIds.length} labels', if (w.labelIds.isNotEmpty) '${w.labelIds.length} labels',
if (w.query.trim().isNotEmpty) '“${w.query.trim()}”', if (w.query.trim().isNotEmpty) '“${w.query.trim()}”',
if (w.showAmountIn) 'In', if (w.type == HomeWidgetType.stats && w.showAmountIn) 'In',
if (w.showAmountOut) 'Out', if (w.type == HomeWidgetType.stats && w.showAmountOut) 'Out',
if (w.showCount) 'Count', if (w.type == HomeWidgetType.stats && w.showCount) 'Count',
if (w.halfWidth) 'Half',
]; ];
return parts.isEmpty ? 'All transactions' : parts.join(' · '); return parts.join(' · ');
} }
} }
+9 -12
View File
@@ -9,8 +9,9 @@ final RouteObserver<ModalRoute<void>> appRouteObserver =
/// 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.
/// ///
/// Uses [ModalRoute.isCurrent] so nested dialogs above a bottom sheet do not /// Only [PageRoute]s count as covering (via [RouteAware]). Modal bottom sheets
/// falsely "uncover" the page when the dialog pops (sheet still open). /// 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,
@@ -29,13 +30,6 @@ class _SkipBuildWhenCoveredState extends State<SkipBuildWhenCovered>
with RouteAware { with RouteAware {
var _covered = false; var _covered = false;
void _syncCovered() {
final route = ModalRoute.of(context);
final covered = route != null && !route.isCurrent;
if (covered == _covered) return;
setState(() => _covered = covered);
}
@override @override
void didChangeDependencies() { void didChangeDependencies() {
super.didChangeDependencies(); super.didChangeDependencies();
@@ -43,7 +37,6 @@ class _SkipBuildWhenCoveredState extends State<SkipBuildWhenCovered>
if (route is PageRoute) { if (route is PageRoute) {
appRouteObserver.subscribe(this, route); appRouteObserver.subscribe(this, route);
} }
_syncCovered();
} }
@override @override
@@ -53,10 +46,14 @@ class _SkipBuildWhenCoveredState extends State<SkipBuildWhenCovered>
} }
@override @override
void didPushNext() => _syncCovered(); void didPushNext() {
if (!_covered) setState(() => _covered = true);
}
@override @override
void didPopNext() => _syncCovered(); void didPopNext() {
if (_covered) setState(() => _covered = false);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -57,6 +57,46 @@ migrate((app) => {
required: false, required: false,
onlyInt: true, 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", type: "json",
name: "label_ids", name: "label_ids",
@@ -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 (_) {}
});
+20
View File
@@ -22,6 +22,26 @@ void main() {
expect(restored.showAmountOut, isTrue); expect(restored.showAmountOut, isTrue);
expect(restored.showAmountIn, isFalse); expect(restored.showAmountIn, isFalse);
expect(restored.showCount, isTrue); expect(restored.showCount, isTrue);
expect(restored.halfWidth, isFalse);
expect(restored.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', () { test('mergeHomeFilterWidgets unions by id with local wins', () {