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

683 lines
22 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../models/account.dart';
import '../models/transaction.dart';
import '../providers/accounts_provider.dart';
import '../providers/transactions_provider.dart';
import '../providers/auth_provider.dart';
import '../providers/privacy_provider.dart';
import '../services/log_service.dart';
import '../utils/amount_parser.dart';
import '../l10n/app_localizations.dart';
import '../utils/money_masker.dart';
class CalendarScreen extends StatefulWidget {
const CalendarScreen({super.key});
@override
State<CalendarScreen> createState() => _CalendarScreenState();
}
class _CalendarScreenState extends State<CalendarScreen> {
final LogService _log = LogService.instance;
Account? _selectedAccount;
DateTime _currentMonth = DateTime.now();
Map<String, double> _dailyChanges = {};
bool _isLoading = false;
String _accountType = 'asset'; // 'asset' or 'liability'
DateTime? _selectedDate; // Track selected date for tap interaction
List<Transaction> _transactions = []; // Store transactions for filtering
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadInitialData();
});
}
Future<void> _loadInitialData() async {
final accountsProvider = context.read<AccountsProvider>();
final authProvider = context.read<AuthProvider>();
final accessToken = await authProvider.getValidAccessToken();
if (accountsProvider.accounts.isEmpty && accessToken != null) {
await accountsProvider.fetchAccounts(
accessToken: accessToken,
forceSync: false,
);
}
if (accountsProvider.accounts.isNotEmpty) {
// Select first account of the selected type
final filteredAccounts = _getFilteredAccounts(accountsProvider.accounts);
setState(() {
_selectedAccount =
filteredAccounts.isNotEmpty ? filteredAccounts.first : null;
});
if (_selectedAccount != null) {
await _loadTransactionsForAccount();
}
}
}
List<Account> _getFilteredAccounts(List<Account> accounts) {
if (_accountType == 'asset') {
return accounts.where((a) => a.isAsset).toList();
} else {
return accounts.where((a) => a.isLiability).toList();
}
}
Future<void> _loadTransactionsForAccount() async {
if (_selectedAccount == null) return;
setState(() {
_isLoading = true;
});
final authProvider = context.read<AuthProvider>();
final transactionsProvider = context.read<TransactionsProvider>();
final accessToken = await authProvider.getValidAccessToken();
if (accessToken != null) {
await transactionsProvider.fetchTransactions(
accessToken: accessToken,
accountId: _selectedAccount!.id,
forceSync: false,
);
final transactions = transactionsProvider.transactions;
_log.info(
'CalendarScreen',
'Loaded ${transactions.length} transactions for selected account',
);
// Store transactions for date filtering
_transactions = List.from(transactions);
_calculateDailyChanges(transactions);
_log.info('CalendarScreen',
'Calculated ${_dailyChanges.length} days with changes');
}
setState(() {
_isLoading = false;
});
}
void _calculateDailyChanges(List<Transaction> transactions) {
final changes = <String, double>{};
_log.debug('CalendarScreen',
'Starting to calculate daily changes for ${transactions.length} transactions');
for (var transaction in transactions) {
try {
final date = DateTime.parse(transaction.date);
final dateKey = DateFormat('yyyy-MM-dd').format(date);
var amount = AmountParser.parse(transaction.amount).value;
// For asset accounts, flip the sign to match accounting conventions
// For liability accounts, also flip the sign
if (_selectedAccount?.isAsset == true ||
_selectedAccount?.isLiability == true) {
amount = -amount;
}
changes[dateKey] = (changes[dateKey] ?? 0.0) + amount;
} catch (e) {
final sanitizedError = LogService.sanitize(e.toString());
final errorSummary = sanitizedError.length > 120
? '${sanitizedError.substring(0, 120)}...'
: sanitizedError;
_log.error('CalendarScreen',
'Failed to process transaction for calendar: $errorSummary');
}
}
_log.info(
'CalendarScreen', 'Final changes map has ${changes.length} entries');
setState(() {
_dailyChanges = changes;
});
}
void _previousMonth() {
setState(() {
_currentMonth = DateTime(_currentMonth.year, _currentMonth.month - 1);
_selectedDate = null; // Clear selection when changing month
});
}
void _nextMonth() {
setState(() {
_currentMonth = DateTime(_currentMonth.year, _currentMonth.month + 1);
_selectedDate = null; // Clear selection when changing month
});
}
void _onDayCellTap(DateTime date) {
if (_selectedDate != null &&
_selectedDate!.year == date.year &&
_selectedDate!.month == date.month &&
_selectedDate!.day == date.day) {
// Second tap on same date - show transactions dialog
_showTransactionsDialog(date);
} else {
// First tap - select the date
setState(() {
_selectedDate = date;
});
}
}
List<Transaction> _getTransactionsForDate(DateTime date) {
final dateKey = DateFormat('yyyy-MM-dd').format(date);
return _transactions.where((transaction) {
try {
final transactionDate = DateTime.parse(transaction.date);
final transactionDateKey =
DateFormat('yyyy-MM-dd').format(transactionDate);
return transactionDateKey == dateKey;
} catch (e) {
return false;
}
}).toList();
}
void _showTransactionsDialog(DateTime date) {
final transactions = _getTransactionsForDate(date);
final formattedDate = DateFormat.yMMMd(
Localizations.localeOf(context).toString(),
).format(date);
final colorScheme = Theme.of(context).colorScheme;
final l = AppLocalizations.of(context);
showDialog(
context: context,
builder: (BuildContext context) {
// Watch inside the dialog builder so the amounts re-mask if the user
// toggles privacy while the dialog is open.
final hideAmounts = context.watch<PrivacyProvider>().hidden;
return AlertDialog(
title: Text(
formattedDate,
style: Theme.of(context).textTheme.titleLarge,
),
content: SizedBox(
width: double.maxFinite,
child: transactions.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
l.calendarNoTransactions,
style: TextStyle(
color: colorScheme.onSurfaceVariant,
),
),
),
)
: ListView.builder(
shrinkWrap: true,
itemCount: transactions.length,
itemBuilder: (context, index) {
final transaction = transactions[index];
return _buildTransactionTile(transaction, hideAmounts);
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l.commonClose),
),
],
);
},
);
}
Widget _buildTransactionTile(Transaction transaction, bool hideAmounts) {
// Parse amount to determine if positive or negative
var isNegative = false;
try {
isNegative = AmountParser.parse(transaction.amount).value < 0;
} on FormatException {
// Keep the dialog renderable if the server returns a malformed amount.
}
// For asset accounts, flip the sign interpretation
if (_selectedAccount?.isAsset == true ||
_selectedAccount?.isLiability == true) {
isNegative = !isNegative;
}
final isExpense = isNegative;
final iconData = isExpense ? Icons.remove_circle : Icons.add_circle;
final iconColor = isExpense ? Colors.red : Colors.green;
final amountColor = isExpense ? Colors.red.shade700 : Colors.green.shade700;
return ListTile(
leading: Icon(
iconData,
color: iconColor,
size: 28,
),
title: Text(
transaction.name,
style: const TextStyle(
fontWeight: FontWeight.w500,
),
),
subtitle: transaction.notes != null && transaction.notes!.isNotEmpty
? Text(
transaction.notes!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: 12,
),
)
: null,
trailing: Text(
MoneyMasker.mask(
transaction.amount,
hidden: hideAmounts,
),
style: TextStyle(
color: amountColor,
fontWeight: FontWeight.bold,
),
),
);
}
double _getTotalForMonth() {
double total = 0.0;
final yearMonth = DateFormat('yyyy-MM').format(_currentMonth);
_dailyChanges.forEach((date, change) {
if (date.startsWith(yearMonth)) {
total += change;
}
});
return total;
}
@override
Widget build(BuildContext context) {
final l = AppLocalizations.of(context);
final colorScheme = Theme.of(context).colorScheme;
final accountsProvider = context.watch<AccountsProvider>();
final hideAmounts = context.watch<PrivacyProvider>().hidden;
return Scaffold(
appBar: AppBar(
title: Text(l.calendarTitle),
),
body: Column(
children: [
// Account type selector
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surface,
border: Border(
bottom: BorderSide(
color: colorScheme.outlineVariant,
width: 1,
),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l.calendarAccountTypeSection,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 8),
SegmentedButton<String>(
segments: [
ButtonSegment<String>(
value: 'asset',
label: Text(l.calendarSegmentAssets),
icon: const Icon(Icons.account_balance_wallet),
),
ButtonSegment<String>(
value: 'liability',
label: Text(l.calendarSegmentLiabilities),
icon: const Icon(Icons.credit_card),
),
],
selected: {_accountType},
onSelectionChanged: (Set<String> newSelection) {
setState(() {
_accountType = newSelection.first;
// Switch to first account of new type
final filteredAccounts =
_getFilteredAccounts(accountsProvider.accounts);
_selectedAccount = filteredAccounts.isNotEmpty
? filteredAccounts.first
: null;
_dailyChanges = {};
_transactions = [];
_selectedDate =
null; // Clear selection when changing account type
});
if (_selectedAccount != null) {
_loadTransactionsForAccount();
}
},
),
],
),
),
// Account selector
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surface,
border: Border(
bottom: BorderSide(
color: colorScheme.outlineVariant,
width: 1,
),
),
),
child: DropdownButtonFormField<Account>(
value: _selectedAccount,
decoration: InputDecoration(
labelText: l.calendarSelectAccount,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
),
items: _getFilteredAccounts(accountsProvider.accounts)
.map((account) {
return DropdownMenuItem(
value: account,
child: Text('${account.name} (${account.currency})'),
);
}).toList(),
onChanged: (Account? newAccount) {
setState(() {
_selectedAccount = newAccount;
_dailyChanges = {};
_transactions = [];
_selectedDate = null; // Clear selection when changing account
});
_loadTransactionsForAccount();
},
),
),
// Month selector
Container(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
border: Border(
bottom: BorderSide(
color: colorScheme.outlineVariant,
width: 1,
),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: const Icon(Icons.chevron_left),
onPressed: _previousMonth,
),
Text(
DateFormat.yMMM(
Localizations.localeOf(context).toString(),
).format(_currentMonth),
style: Theme.of(context).textTheme.titleLarge,
),
IconButton(
icon: const Icon(Icons.chevron_right),
onPressed: _nextMonth,
),
],
),
),
// Monthly total
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
border: Border(
bottom: BorderSide(
color: colorScheme.outlineVariant,
width: 1,
),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
l.calendarMonthlyChange,
style: Theme.of(context).textTheme.titleMedium,
),
Text(
MoneyMasker.mask(
_formatCurrency(_getTotalForMonth()),
hidden: hideAmounts,
),
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: _getTotalForMonth() >= 0
? Colors.green
: Colors.red,
fontWeight: FontWeight.bold,
),
),
],
),
),
// Calendar
Expanded(
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _buildCalendar(colorScheme, hideAmounts),
),
],
),
);
}
Widget _buildCalendar(ColorScheme colorScheme, bool hideAmounts) {
final firstDayOfMonth =
DateTime(_currentMonth.year, _currentMonth.month, 1);
final lastDayOfMonth =
DateTime(_currentMonth.year, _currentMonth.month + 1, 0);
final daysInMonth = lastDayOfMonth.day;
final startWeekday = firstDayOfMonth.weekday % 7; // 0 = Sunday
// Localized narrow weekday labels, Sunday→Saturday to match the
// Sunday-anchored grid math above. 2024-01-07 is a Sunday, so indices
// 0..6 map Sunday..Saturday.
final localeName = Localizations.localeOf(context).toString();
final weekdayLabels = List.generate(
7,
(i) => DateFormat.E(localeName)
.format(DateTime(2024, 1, 7 + i))
.substring(0, 1),
);
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: [
// Weekday headers
SizedBox(
height: 40,
child: Row(
children: weekdayLabels.map((day) {
return Expanded(
child: Center(
child: Text(
day,
style: TextStyle(
fontWeight: FontWeight.bold,
color: colorScheme.onSurfaceVariant,
),
),
),
);
}).toList(),
),
),
// Calendar grid
...List.generate((daysInMonth + startWeekday + 6) ~/ 7,
(weekIndex) {
return SizedBox(
height: 70,
child: Row(
children: List.generate(7, (dayIndex) {
final dayNumber =
weekIndex * 7 + dayIndex - startWeekday + 1;
if (dayNumber < 1 || dayNumber > daysInMonth) {
return const Expanded(child: SizedBox.shrink());
}
final date = DateTime(
_currentMonth.year, _currentMonth.month, dayNumber);
final dateKey = DateFormat('yyyy-MM-dd').format(date);
final change = _dailyChanges[dateKey] ?? 0.0;
final hasChange = _dailyChanges.containsKey(dateKey);
return Expanded(
child: _buildDayCell(
date,
dayNumber,
change,
hasChange,
colorScheme,
hideAmounts,
),
);
}).toList(),
),
);
}),
],
),
),
);
}
Widget _buildDayCell(DateTime date, int day, double change, bool hasChange,
ColorScheme colorScheme, bool hideAmounts) {
Color? backgroundColor;
Color? textColor;
// Check if this date is selected
final isSelected = _selectedDate != null &&
_selectedDate!.year == date.year &&
_selectedDate!.month == date.month &&
_selectedDate!.day == date.day;
if (hasChange) {
if (change > 0) {
backgroundColor = Colors.green.withValues(alpha: 0.2);
textColor = Colors.green.shade700;
} else if (change < 0) {
backgroundColor = Colors.red.withValues(alpha: 0.2);
textColor = Colors.red.shade700;
}
}
return GestureDetector(
onTap: () => _onDayCellTap(date),
child: Container(
margin: const EdgeInsets.all(2),
decoration: BoxDecoration(
color: backgroundColor ?? colorScheme.surface,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: isSelected
? Theme.of(context).primaryColor
: colorScheme.outlineVariant,
width: isSelected ? 3 : 1,
),
),
child: Padding(
padding: const EdgeInsets.all(4),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
day.toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
color: colorScheme.onSurface,
),
),
if (hasChange) ...[
const SizedBox(height: 2),
Flexible(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
MoneyMasker.mask(
_formatAmount(change),
hidden: hideAmounts,
),
style: TextStyle(
fontSize: 10,
color: textColor,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
),
),
],
],
),
),
),
);
}
String _formatAmount(double amount) {
// Support up to 8 decimal places, but omit unnecessary trailing zeros
final formatter = NumberFormat('#,##0.########');
final sign = amount >= 0 ? '+' : '';
return '$sign${formatter.format(amount)}';
}
String _formatCurrency(double amount) {
final currencySymbol = _selectedAccount?.currency ?? '';
// Support up to 8 decimal places for monthly total
final formatter = NumberFormat('#,##0.########');
final sign = amount >= 0 ? '+' : '';
return '$sign$currencySymbol${formatter.format(amount.abs())}';
}
}