Files
sure/mobile/lib/screens/recent_transactions_screen.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

304 lines
9.4 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../models/transaction.dart';
import '../models/account.dart';
import '../providers/transactions_provider.dart';
import '../providers/accounts_provider.dart';
import '../providers/auth_provider.dart';
import '../theme/sure_tokens.dart';
import '../providers/privacy_provider.dart';
import '../utils/amount_parser.dart';
import '../utils/money_masker.dart';
import '../widgets/money_text.dart';
import '../l10n/app_localizations.dart';
class RecentTransactionsScreen extends StatefulWidget {
const RecentTransactionsScreen({super.key});
@override
State<RecentTransactionsScreen> createState() => _RecentTransactionsScreenState();
}
class _RecentTransactionsScreenState extends State<RecentTransactionsScreen> {
int _transactionLimit = 20;
final List<int> _limitOptions = [10, 20, 50, 100];
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadAllTransactions();
});
}
Future<void> _loadAllTransactions() async {
final authProvider = context.read<AuthProvider>();
final transactionsProvider = context.read<TransactionsProvider>();
final accessToken = await authProvider.getValidAccessToken();
if (accessToken != null) {
// Load transactions for all accounts
await transactionsProvider.fetchTransactions(
accessToken: accessToken,
forceSync: false,
);
}
}
Future<void> _refreshTransactions() async {
final authProvider = context.read<AuthProvider>();
final transactionsProvider = context.read<TransactionsProvider>();
final accessToken = await authProvider.getValidAccessToken();
if (accessToken != null) {
await transactionsProvider.fetchTransactions(
accessToken: accessToken,
forceSync: true,
);
}
}
Account? _getAccount(String accountId) {
final accountsProvider = context.read<AccountsProvider>();
try {
return accountsProvider.accounts.firstWhere(
(a) => a.id == accountId,
);
} catch (e) {
return null;
}
}
List<Transaction> _getSortedTransactions(List<Transaction> transactions) {
final sorted = List<Transaction>.from(transactions);
sorted.sort((a, b) {
try {
final dateA = DateTime.parse(a.date);
final dateB = DateTime.parse(b.date);
return dateB.compareTo(dateA); // Most recent first
} catch (e) {
return 0;
}
});
return sorted.take(_transactionLimit).toList();
}
@override
Widget build(BuildContext context) {
final l = AppLocalizations.of(context);
final colorScheme = Theme.of(context).colorScheme;
final transactionsProvider = context.watch<TransactionsProvider>();
final hideAmounts = context.watch<PrivacyProvider>().hidden;
final recentTransactions = _getSortedTransactions(
transactionsProvider.transactions,
);
return Scaffold(
appBar: AppBar(
title: Text(l.recentTransactionsTitle),
actions: [
PopupMenuButton<int>(
initialValue: _transactionLimit,
icon: const Icon(Icons.filter_list),
tooltip: l.recentTransactionsDisplayLimit,
onSelected: (int value) {
setState(() {
_transactionLimit = value;
});
},
itemBuilder: (context) => _limitOptions.map((limit) {
return PopupMenuItem<int>(
value: limit,
child: Row(
children: [
if (limit == _transactionLimit)
Icon(Icons.check, color: colorScheme.primary, size: 20)
else
const SizedBox(width: 20),
const SizedBox(width: 8),
Text(l.recentTransactionsShowN(limit)),
],
),
);
}).toList(),
),
],
),
body: RefreshIndicator(
onRefresh: _refreshTransactions,
child: transactionsProvider.isLoading
? const Center(child: CircularProgressIndicator())
: recentTransactions.isEmpty
? _buildEmptyState(colorScheme)
: ListView.separated(
itemCount: recentTransactions.length,
separatorBuilder: (context, index) => Divider(
height: 1,
color: colorScheme.outlineVariant,
),
itemBuilder: (context, index) {
final transaction = recentTransactions[index];
return _buildTransactionItem(
context,
transaction,
colorScheme,
hideAmounts,
);
},
),
),
);
}
Widget _buildEmptyState(ColorScheme colorScheme) {
final l = AppLocalizations.of(context);
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.receipt_long_outlined,
size: 64,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
l.recentTransactionsEmpty,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
l.recentTransactionsPullToRefresh,
style: TextStyle(color: colorScheme.onSurfaceVariant),
),
],
),
),
);
}
Widget _buildTransactionItem(BuildContext context, Transaction transaction,
ColorScheme colorScheme, bool hideAmounts) {
final account = _getAccount(transaction.accountId);
final accountName = account?.name ??
AppLocalizations.of(context).recentTransactionsUnknownAccount;
double? amount;
try {
amount = AmountParser.parse(transaction.amount).value;
} on FormatException {
// Keep the list renderable if the server returns a malformed amount.
}
// For asset accounts and liability accounts, flip the sign to match accounting conventions
if (amount != null &&
(account?.isAsset == true || account?.isLiability == true)) {
amount = -amount;
}
// Determine display properties based on final amount. The semantic color
// comes from the Sure design-system tokens (success/destructive/subdued)
// via MoneyTrend, instead of raw Colors.green/red.
final isPositive = amount == null || amount >= 0;
final moneyTrend = SureMoney.trendForAmount(amount);
final amountColor = SureMoney.color(context, moneyTrend);
final sign = amount == null
? ''
: isPositive
? '+'
: '-';
String formattedDate;
try {
final date = DateTime.parse(transaction.date);
formattedDate = DateFormat('yyyy-MM-dd HH:mm',
Localizations.localeOf(context).toString())
.format(date);
} catch (e) {
formattedDate = transaction.date;
}
return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: amountColor.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
amount == null
? Icons.help_outline
: isPositive
? Icons.arrow_upward
: Icons.arrow_downward,
color: amountColor,
),
),
title: Text(
transaction.name,
style: const TextStyle(fontWeight: SureTokens.weightMedium),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
Text(
accountName,
style: TextStyle(
fontSize: 12,
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(
formattedDate,
style: TextStyle(
fontSize: 11,
color: colorScheme.onSurfaceVariant,
),
),
if (transaction.notes != null && transaction.notes!.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
transaction.notes!,
style: TextStyle(
fontSize: 11,
color: colorScheme.onSurfaceVariant,
fontStyle: FontStyle.italic,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
),
trailing: MoneyText(
MoneyMasker.mask(
amount == null
? transaction.amount
: '$sign${transaction.currency} ${_formatAmount(amount.abs())}',
hidden: hideAmounts,
),
trend: moneyTrend,
style: const TextStyle(
fontWeight: SureTokens.weightMedium,
fontSize: 16,
),
),
);
}
String _formatAmount(double amount) {
// Support up to 8 decimal places, but omit unnecessary trailing zeros
final formatter = NumberFormat('#,##0.########');
return formatter.format(amount);
}
}