Files
sure/mobile/lib/widgets/net_worth_card.dart
ghost 401cd6ab08 feat(mobile): privacy mode to mask money values (#2386)
* feat(mobile): add privacy mode to mask money values

Adds an app-wide "privacy mode" so users can hide monetary amounts from
over-the-shoulder view.

- PrivacyProvider (ChangeNotifier) backed by PreferencesService, so the
  choice persists across launches and every money widget rebuilds on
  toggle.
- MoneyMasker.mask() collapses an amount's numeric portion into a short
  fixed run of bullets while keeping the currency symbol and sign
  (e.g. CA$1,234.56 -> CA$••••). A fixed run avoids leaking the value's
  magnitude and reads cleanly without stray separators. Currency- and
  locale-agnostic — it operates on already-formatted strings.
- Masking applied at every money render site: net worth + per-currency
  totals + breakdown sheet (NetWorthCard), account balances (AccountCard,
  AccountDetailHeader, transaction form account selector), and transaction
  amounts (transactions list, recent transactions, calendar).
- Two entry points: a "Hide amounts" switch in Settings -> Security, and a
  quick eye toggle in the top bar (visible on every tab).

Tests: MoneyMasker unit tests (fixed-run mask, magnitude hidden, symbol/
sign kept, passthrough, idempotent) + a widget test asserting the net
worth masks/unmasks as the provider flips; account_card_test updated to
provide the new provider. flutter analyze: no new issues; full suite
(123) green.

* fix(mobile): address privacy-mode review feedback

- Startup masking (Codex P1): read the privacy preference in main() before
  runApp and seed PrivacyProvider with it, so the first frame already has
  the correct value — money is never briefly rendered unmasked for a user
  who enabled "Hide amounts". Provider stays fail-closed otherwise: starts
  masked, SureApp's no-arg default is masked, and a failed read keeps it
  masked. A late-completing initial load no longer clobbers an explicit
  user toggle.
- setHidden() reverts the in-memory state (and logs) if persistence fails,
  keeping the UI consistent with what's actually stored.
- Mask the cash-balance detail chip in AccountDetailHeader (was leaking
  the cash position in privacy mode).
- Privacy top-bar toggle gets a "Toggle privacy" tooltip + icon semantic
  label for accessibility (kept as an InkWell to match the adjacent
  settings control).
- Tests: assert fail-closed initial state; assert the exact masked count;
  test the persistence round-trip (set -> reload); add
  PreferencesService.resetForTest() and reset between tests so the cached
  singleton can't leak state.

125 tests pass; flutter analyze: no new issues.

* refactor(mobile): thread hideAmounts through calendar tiles

Per review: the calendar tile builders read PrivacyProvider via
context.read, relying implicitly on the parent build()'s context.watch to
rebuild them — fragile if a tile is later extracted or wrapped in a
RepaintBoundary. Pass hideAmounts down explicitly instead, matching the
recent_transactions_screen pattern:

- build() (context.watch) -> _buildCalendar -> _buildDayCell
- _showTransactionsDialog reads once when the modal opens ->
  _buildTransactionTile

No more context.read inside tile methods. 125 tests pass; analyze clean.

* fix(mobile): watch PrivacyProvider inside calendar dialog builder

Moving the hideAmounts read inside the showDialog builder and switching
from context.read to context.watch ensures the dialog re-masks transaction
amounts if the user toggles privacy mode while the dialog is open.
2026-06-30 06:49:05 +02:00

371 lines
13 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/privacy_provider.dart';
import '../theme/sure_colors.dart';
import '../theme/sure_tokens.dart';
import '../utils/money_masker.dart';
import 'money_text.dart';
import 'sure_icon.dart';
enum AccountFilter { all, assets, liabilities }
class NetWorthCard extends StatelessWidget {
final Map<String, double> assetTotalsByCurrency;
final Map<String, double> liabilityTotalsByCurrency;
final AccountFilter currentFilter;
final ValueChanged<AccountFilter> onFilterChanged;
final String Function(String currency, double amount) formatAmount;
final String? netWorthFormatted;
final bool isStale;
const NetWorthCard({
super.key,
required this.assetTotalsByCurrency,
required this.liabilityTotalsByCurrency,
required this.currentFilter,
required this.onFilterChanged,
required this.formatAmount,
this.netWorthFormatted,
this.isStale = false,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final sureColors = SureColors.of(context);
final hideAmounts = context.watch<PrivacyProvider>().hidden;
final maskedNetWorth = netWorthFormatted == null
? '--'
: MoneyMasker.mask(netWorthFormatted!, hidden: hideAmounts);
String maskedFormat(String currency, double amount) =>
MoneyMasker.mask(formatAmount(currency, amount), hidden: hideAmounts);
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: colorScheme.outline.withValues(alpha: 0.2),
),
),
child: Column(
children: [
// Net Worth Section
Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Net Worth',
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
if (isStale) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: colorScheme.secondaryContainer.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(4),
),
child: Text(
'Outdated',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: colorScheme.secondary,
fontWeight: SureTokens.weightMedium,
),
),
),
],
],
),
const SizedBox(height: 4),
Text(
maskedNetWorth,
style: SureMoney.tabular(
Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: SureTokens.weightMedium,
color: isStale
? colorScheme.secondary
: colorScheme.onSurface,
),
),
),
],
),
),
// Divider
Divider(
height: 1,
color: colorScheme.outline.withValues(alpha: 0.2),
),
// Assets & Liabilities Row
IntrinsicHeight(
child: Row(
children: [
// Assets
Expanded(
child: _FilterButton(
totals: assetTotalsByCurrency,
color: sureColors.palette.success,
isSelected: currentFilter == AccountFilter.assets,
onTap: () {
if (currentFilter == AccountFilter.assets) {
onFilterChanged(AccountFilter.all);
} else {
onFilterChanged(AccountFilter.assets);
}
},
onLongPress: () => _showCurrencyBreakdown(
context,
'Assets',
assetTotalsByCurrency,
sureColors.palette.success,
maskedFormat,
),
formatAmount: maskedFormat,
),
),
// Vertical Divider
VerticalDivider(
width: 1,
color: colorScheme.outline.withValues(alpha: 0.2),
),
// Liabilities
Expanded(
child: _FilterButton(
totals: liabilityTotalsByCurrency,
color: sureColors.palette.destructive,
isSelected: currentFilter == AccountFilter.liabilities,
onTap: () {
if (currentFilter == AccountFilter.liabilities) {
onFilterChanged(AccountFilter.all);
} else {
onFilterChanged(AccountFilter.liabilities);
}
},
onLongPress: () => _showCurrencyBreakdown(
context,
'Liabilities',
liabilityTotalsByCurrency,
sureColors.palette.destructive,
maskedFormat,
),
formatAmount: maskedFormat,
),
),
],
),
),
],
),
);
}
void _showCurrencyBreakdown(
BuildContext context,
String title,
Map<String, double> totals,
Color color,
String Function(String currency, double amount) formatAmount,
) {
final sortedEntries = totals.entries.toList()
..sort((a, b) => b.value.abs().compareTo(a.value.abs()));
if (sortedEntries.isEmpty) return;
showModalBottomSheet(
context: context,
isScrollControlled: true,
useSafeArea: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (context) {
final colorScheme = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.fromLTRB(24, 16, 24, 32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Handle bar
Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(height: 20),
// Title with icon
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SureIcon(
title == 'Assets'
? SureIcons.trendingUp
: SureIcons.trendingDown,
color: color,
size: SureIconSize.md,
),
const SizedBox(width: 8),
Text(
title,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: SureTokens.weightMedium,
color: color,
),
),
],
),
const SizedBox(height: 20),
// Currency list (scrollable when many entries)
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.5,
),
child: ListView.separated(
shrinkWrap: true,
itemCount: sortedEntries.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (context, index) {
final entry = sortedEntries[index];
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
entry.key,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: SureTokens.weightMedium,
color: colorScheme.onSurfaceVariant,
),
),
Text(
formatAmount(entry.key, entry.value),
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: SureTokens.weightMedium,
),
),
],
);
},
),
),
],
),
);
},
);
}
}
class _FilterButton extends StatelessWidget {
final Map<String, double> totals;
final Color color;
final bool isSelected;
final VoidCallback onTap;
final VoidCallback onLongPress;
final String Function(String currency, double amount) formatAmount;
const _FilterButton({
required this.totals,
required this.color,
required this.isSelected,
required this.onTap,
required this.onLongPress,
required this.formatAmount,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final sortedEntries = totals.entries.toList()
..sort((a, b) => b.value.abs().compareTo(a.value.abs()));
return Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: color.withValues(alpha: 0.6),
width: 3,
),
),
),
child: Material(
color: isSelected ? color.withValues(alpha: 0.1) : Colors.transparent,
child: GestureDetector(
onTap: onTap,
onLongPress: sortedEntries.isNotEmpty ? onLongPress : null,
behavior: HitTestBehavior.opaque,
child: SizedBox(
height: 48,
child: sortedEntries.isEmpty
? Center(
child: Text(
'--',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: SureTokens.weightMedium,
color: colorScheme.onSurface,
),
),
)
: sortedEntries.length == 1
? Center(
child: Text(
formatAmount(sortedEntries.first.key, sortedEntries.first.value),
style: SureMoney.tabular(
Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: SureTokens.weightMedium,
color: colorScheme.onSurface,
),
),
),
)
: NotificationListener<ScrollNotification>(
onNotification: (_) => true,
child: ListWheelScrollView.useDelegate(
itemExtent: 32,
diameterRatio: 1.5,
perspective: 0.003,
physics: const FixedExtentScrollPhysics(),
childDelegate: ListWheelChildBuilderDelegate(
childCount: sortedEntries.length,
builder: (context, index) {
final entry = sortedEntries[index];
return Center(
child: Text(
formatAmount(entry.key, entry.value),
style: SureMoney.tabular(
Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: SureTokens.weightMedium,
color: colorScheme.onSurface,
),
),
),
);
},
),
),
),
),
),
),
);
}
}