Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(mobile): show account detail context (#2231)

ghost2fc85345c424
diff --git a/mobile/lib/models/account.dart b/mobile/lib/models/account.dart
index 046aa06011..23bf00bbdf 100644
--- a/mobile/lib/models/account.dart
+++ b/mobile/lib/models/account.dart
@@ -1,28 +1,66 @@
+import '../utils/json_parsing.dart';
+
class Account {
final String id;
final String name;
final String balance;
+ final int? balanceCents;
+ final String? cashBalance;
+ final int? cashBalanceCents;
final String currency;
final String? classification;
final String accountType;
+ final String? subtype;
+ final String? status;
+ final String? institutionName;
+ final String? institutionDomain;
+ final DateTime? createdAt;
+ final DateTime? updatedAt;
Account({
required this.id,
required this.name,
required this.balance,
+ this.balanceCents,
+ this.cashBalance,
+ this.cashBalanceCents,
required this.currency,
this.classification,
required this.accountType,
+ this.subtype,
+ this.status,
+ this.institutionName,
+ this.institutionDomain,
+ this.createdAt,
+ this.updatedAt,
});
factory Account.fromJson(Map<String, dynamic> json) {
return Account(
id: json['id'].toString(),
- name: json['name'] as String,
- balance: json['balance'] as String,
- currency: json['currency'] as String,
- classification: json['classification'] as String?,
- accountType: json['account_type'] as String,
+ name: JsonParsing.parseRequiredString(json['name'], 'account name'),
+ balance: JsonParsing.parseRequiredString(
+ json['balance'],
+ 'account balance',
+ ),
+ balanceCents: JsonParsing.parseInt(json['balance_cents']),
+ cashBalance: JsonParsing.parseString(json['cash_balance']),
+ cashBalanceCents: JsonParsing.parseInt(json['cash_balance_cents']),
+ currency: JsonParsing.parseRequiredString(
+ json['currency'],
+ 'account currency',
+ ),
+ classification: JsonParsing.parseString(json['classification']),
+ accountType: JsonParsing.parseRequiredString(
+ json['account_type'],
+ 'account type',
+ ),
+ subtype: JsonParsing.parseString(json['subtype']),
+ status: JsonParsing.parseString(json['status']),
+ institutionName: JsonParsing.parseString(json['institution_name']),
+ institutionDomain: JsonParsing.parseString(json['institution_domain']),
+ createdAt: JsonParsing.parseDateTime(json['created_at']),
+ updatedAt: JsonParsing.parseDateTime(json['updated_at']),
);
}
diff --git a/mobile/lib/models/account_balance.dart b/mobile/lib/models/account_balance.dart
new file mode 100644
index 0000000000..66d1711523
--- /dev/null
+++ b/mobile/lib/models/account_balance.dart
@@ -0,0 +1,39 @@
+import '../utils/json_parsing.dart';
+
+class AccountBalance {
+ final String id;
+ final DateTime date;
+ final String currency;
+ final String balance;
+ final int? balanceCents;
+ final String? cashBalance;
+ final int? cashBalanceCents;
+
+ AccountBalance({
+ required this.id,
+ required this.date,
+ required this.currency,
+ required this.balance,
+ this.balanceCents,
+ this.cashBalance,
+ this.cashBalanceCents,
+ });
+
+ factory AccountBalance.fromJson(Map<String, dynamic> json) {
+ return AccountBalance(
+ id: json['id'].toString(),
+ date: JsonParsing.parseRequiredDateTime(json['date'], 'account balance'),
+ currency: JsonParsing.parseRequiredString(
+ json['currency'],
+ 'account balance currency',
+ ),
+ balance: JsonParsing.parseRequiredString(
+ json['balance'],
+ 'account balance',
+ ),
+ balanceCents: JsonParsing.parseInt(json['balance_cents']),
+ cashBalance: JsonParsing.parseString(json['cash_balance']),
+ cashBalanceCents: JsonParsing.parseInt(json['cash_balance_cents']),
+ );
+ }
+}
diff --git a/mobile/lib/models/account_holding.dart b/mobile/lib/models/account_holding.dart
new file mode 100644
index 0000000000..dc2537b2ce
--- /dev/null
+++ b/mobile/lib/models/account_holding.dart
@@ -0,0 +1,51 @@
+import '../utils/json_parsing.dart';
+
+class AccountHolding {
+ final String id;
+ final DateTime date;
+ final String quantity;
+ final String price;
+ final String amount;
+ final String currency;
+ final String? ticker;
+ final String? securityName;
+
+ AccountHolding({
+ required this.id,
+ required this.date,
+ required this.quantity,
+ required this.price,
+ required this.amount,
+ required this.currency,
+ this.ticker,
+ this.securityName,
+ });
+
+ factory AccountHolding.fromJson(Map<String, dynamic> json) {
+ final securityJson = json['security'];
+ final security = securityJson is Map<String, dynamic> ? securityJson : null;
+
+ return AccountHolding(
+ id: json['id'].toString(),
+ date: JsonParsing.parseRequiredDateTime(json['date'], 'account holding'),
+ quantity: JsonParsing.parseRequiredString(
+ json['qty'],
+ 'account holding quantity',
+ ),
+ price: JsonParsing.parseRequiredString(
+ json['price'],
+ 'account holding price',
+ ),
+ amount: JsonParsing.parseRequiredString(
+ json['amount'],
+ 'account holding amount',
+ ),
+ currency: JsonParsing.parseRequiredString(
+ json['currency'],
+ 'account holding currency',
+ ),
+ ticker: JsonParsing.parseString(security?['ticker']),
+ securityName: JsonParsing.parseString(security?['name']),
+ );
+ }
+}
diff --git a/mobile/lib/screens/transactions_list_screen.dart b/mobile/lib/screens/transactions_list_screen.dart
index 9369fe35c1..8e9cb41001 100644
--- a/mobile/lib/screens/transactions_list_screen.dart
+++ b/mobile/lib/screens/transactions_list_screen.dart
@@ -8,6 +8,7 @@ import '../providers/categories_provider.dart';
import '../providers/transactions_provider.dart';
import '../screens/transaction_edit_screen.dart';
import '../screens/transaction_form_screen.dart';
+import '../widgets/account_detail_header.dart';
import '../widgets/category_filter.dart';
import '../widgets/sync_status_badge.dart';
import '../services/log_service.dart';
@@ -356,8 +357,12 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
),
],
),
- body: Consumer<TransactionsProvider>(
- builder: (context, transactionsProvider, child) {
+ body: Column(
+ children: [
+ AccountDetailHeader(account: widget.account),
+ Expanded(
+ child: Consumer<TransactionsProvider>(
+ builder: (context, transactionsProvider, child) {
if (transactionsProvider.isLoading) {
return const Center(child: CircularProgressIndicator());
}
@@ -708,7 +713,10 @@ class _TransactionsListScreenState extends State<TransactionsListScreen> {
],
),
);
- },
+ },
+ ),
+ ),
+ ],
),
floatingActionButton: FloatingActionButton(
onPressed: _showAddTransactionForm,
diff --git a/mobile/lib/services/account_detail_service.dart b/mobile/lib/services/account_detail_service.dart
new file mode 100644
index 0000000000..378d85effd
--- /dev/null
+++ b/mobile/lib/services/account_detail_service.dart
@@ -0,0 +1,258 @@
+import 'dart:convert';
+import 'package:http/http.dart' as http;
+import '../models/account.dart';
+import '../models/account_balance.dart';
+import '../models/account_holding.dart';
+import '../utils/json_parsing.dart';
+import 'api_config.dart';
+import 'log_service.dart';
+
+class AccountDetailService {
+ static const int _holdingsPageSize = 100;
+
+ final http.Client _client;
+ final bool _ownsClient;
+
+ AccountDetailService({http.Client? client})
+ : _client = client ?? http.Client(),
+ _ownsClient = client == null;
+
+ void close() {
+ if (_ownsClient) {
+ _client.close();
+ }
+ }
+
+ Future<Map<String, dynamic>> getAccountDetail({
+ required String accessToken,
+ required String accountId,
+ }) async {
+ final accountPathId = Uri.encodeComponent(accountId);
+ final url =
+ Uri.parse('${ApiConfig.baseUrl}/api/v1/accounts/$accountPathId');
+
+ try {
+ final response = await _client
+ .get(url, headers: ApiConfig.getAuthHeaders(accessToken))
+ .timeout(const Duration(seconds: 30));
+
+ if (response.statusCode == 200) {
+ return {
+ 'success': true,
+ 'account': Account.fromJson(jsonDecode(response.body)),
+ };
+ }
+
+ return _failureFromStatus(response.statusCode, 'Failed to fetch account');
+ } catch (e) {
+ _logFailure('getAccountDetail', e);
+ return {
+ 'success': false,
+ 'error': 'Unable to load account details. Please try again later.',
+ };
+ }
+ }
+
+ Future<Map<String, dynamic>> getBalances({
+ required String accessToken,
+ required String accountId,
+ int perPage = 30,
+ }) async {
+ final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/balances').replace(
+ queryParameters: {
+ 'account_id': accountId,
+ 'per_page': perPage.toString(),
+ },
+ );
+
+ try {
+ final response = await _client
+ .get(url, headers: ApiConfig.getAuthHeaders(accessToken))
+ .timeout(const Duration(seconds: 30));
+
+ if (response.statusCode == 200) {
+ final responseData = jsonDecode(response.body) as Map<String, dynamic>;
+ final balances = (responseData['balances'] as List<dynamic>? ?? [])
+ .map(
+ (json) => AccountBalance.fromJson(json as Map<String, dynamic>),
+ )
+ .toList();
+
+ return {'success': true, 'balances': balances};
+ }
+
+ return _failureFromStatus(
+ response.statusCode,
+ 'Failed to fetch balances',
+ );
+ } catch (e) {
+ _logFailure('getBalances', e);
+ return {
+ 'success': false,
+ 'error': 'Unable to load balance history. Please try again later.',
+ };
+ }
+ }
+
+ Future<Map<String, dynamic>> getHoldings({
+ required String accessToken,
+ required String accountId,
+ int perPage = 5,
+ }) async {
+ final displayLimit = perPage.clamp(1, _holdingsPageSize).toInt();
+
+ try {
+ final firstPage = await _getHoldingsPage(
+ accessToken: accessToken,
+ accountId: accountId,
+ page: 1,
+ );
+
+ if (!firstPage.success) {
+ return _failureFromStatus(
+ firstPage.statusCode,
+ 'Failed to fetch holdings',
+ );
+ }
+
+ final currentHoldings = <AccountHolding>[];
+ DateTime? currentDate;
+ final totalPages = firstPage.totalPages < 1 ? 1 : firstPage.totalPages;
+
+ // Holdings are chronological, so the latest positions are at the end of
+ // the final page. Walk backward only until the date changes; this keeps
+ // the common case to page 1 + latest page while still handling accounts
+ // whose current positions span a page boundary.
+ for (var page = totalPages; page >= 1; page -= 1) {
+ final holdingsPage = page == 1
+ ? firstPage
+ : await _getHoldingsPage(
+ accessToken: accessToken,
+ accountId: accountId,
+ page: page,
+ );
+
+ if (!holdingsPage.success) {
+ return _failureFromStatus(
+ holdingsPage.statusCode,
+ 'Failed to fetch holdings',
+ );
+ }
+
+ for (final holding in holdingsPage.holdings.reversed) {
+ currentDate ??= holding.date;
+ if (!_sameDate(holding.date, currentDate)) {
+ return {
+ 'success': true,
+ 'holdings': _topHoldings(currentHoldings, displayLimit),
+ };
+ }
+ currentHoldings.add(holding);
+ }
+ }
+
+ return {
+ 'success': true,
+ 'holdings': _topHoldings(currentHoldings, displayLimit),
+ };
+ } catch (e) {
+ _logFailure('getHoldings', e);
+ return {
+ 'success': false,
+ 'error': 'Unable to load holdings. Please try again later.',
+ };
+ }
+ }
+
+ Future<_HoldingsPage> _getHoldingsPage({
+ required String accessToken,
+ required String accountId,
+ required int page,
+ }) async {
+ final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/holdings').replace(
+ queryParameters: {
+ 'account_id': accountId,
+ 'page': page.toString(),
+ 'per_page': _holdingsPageSize.toString(),
+ },
+ );
+
+ final response = await _client
+ .get(url, headers: ApiConfig.getAuthHeaders(accessToken))
+ .timeout(const Duration(seconds: 30));
+
+ if (response.statusCode != 200) {
+ return _HoldingsPage.failure(response.statusCode);
+ }
+
+ final responseData = jsonDecode(response.body) as Map<String, dynamic>;
+ final holdings = (responseData['holdings'] as List<dynamic>? ?? [])
+ .map(
+ (json) => AccountHolding.fromJson(json as Map<String, dynamic>),
+ )
+ .toList();
+ final pagination = responseData['pagination'] as Map<String, dynamic>?;
+ final totalPages = JsonParsing.parseInt(pagination?['total_pages']) ?? 1;
+
+ return _HoldingsPage.success(
+ holdings: holdings,
+ totalPages: totalPages,
+ );
+ }
+
+ List<AccountHolding> _topHoldings(
+ List<AccountHolding> holdings,
+ int displayLimit,
+ ) {
+ final sorted = holdings.toList()
+ ..sort(
+ (left, right) =>
+ _amountValue(right.amount).compareTo(_amountValue(left.amount)),
+ );
+ return sorted.take(displayLimit).toList();
+ }
+
+ double _amountValue(String amount) {
+ final numeric = amount.replaceAll(RegExp(r'[^\d.-]'), '');
+ return double.tryParse(numeric) ?? 0;
+ }
+
+ bool _sameDate(DateTime left, DateTime right) {
+ return left.year == right.year &&
+ left.month == right.month &&
+ left.day == right.day;
+ }
+
+ Map<String, dynamic> _failureFromStatus(int statusCode, String fallback) {
+ if (statusCode == 401) {
+ return {'success': false, 'error': 'unauthorized'};
+ }
+
+ return {'success': false, 'error': fallback};
+ }
+
+ void _logFailure(String operation, Object error) {
+ LogService.instance.error(
+ 'AccountDetailService',
+ '$operation failed with ${error.runtimeType}',
+ );
+ }
+}
+
+class _HoldingsPage {
+ final bool success;
+ final int statusCode;
+ final List<AccountHolding> holdings;
+ final int totalPages;
+
+ _HoldingsPage.success({
+ required this.holdings,
+ required this.totalPages,
+ }) : success = true,
+ statusCode = 200;
+
+ _HoldingsPage.failure(this.statusCode)
+ : success = false,
+ holdings = const [],
+ totalPages = 1;
+}
diff --git a/mobile/lib/utils/json_parsing.dart b/mobile/lib/utils/json_parsing.dart
new file mode 100644
index 0000000000..fb372a16f6
--- /dev/null
+++ b/mobile/lib/utils/json_parsing.dart
@@ -0,0 +1,33 @@
+class JsonParsing {
+ static String? parseString(dynamic value) {
+ if (value == null) return null;
+ return value.toString();
+ }
+
+ static String parseRequiredString(dynamic value, String fieldName) {
+ final parsed = parseString(value);
+ if (parsed == null) {
+ throw FormatException('Missing $fieldName');
+ }
+ return parsed;
+ }
+
+ static int? parseInt(dynamic value) {
+ if (value == null) return null;
+ if (value is int) return value;
+ return int.tryParse(value.toString());
+ }
+
+ static DateTime? parseDateTime(dynamic value) {
+ if (value == null) return null;
+ return DateTime.tryParse(value.toString());
+ }
+
+ static DateTime parseRequiredDateTime(dynamic value, String fieldName) {
+ final parsed = parseDateTime(value);
+ if (parsed == null) {
+ throw FormatException('Invalid $fieldName date');
+ }
+ return parsed;
+ }
+}
diff --git a/mobile/lib/widgets/account_detail_header.dart b/mobile/lib/widgets/account_detail_header.dart
new file mode 100644
index 0000000000..5264efba8d
--- /dev/null
+++ b/mobile/lib/widgets/account_detail_header.dart
@@ -0,0 +1,436 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:intl/intl.dart';
+import 'package:provider/provider.dart';
+import '../models/account.dart';
+import '../models/account_balance.dart';
+import '../models/account_holding.dart';
+import '../providers/auth_provider.dart';
+import '../services/account_detail_service.dart';
+
+class AccountDetailHeader extends StatefulWidget {
+ final Account account;
+ final AccountDetailService? accountDetailService;
+
+ const AccountDetailHeader({
+ super.key,
+ required this.account,
+ this.accountDetailService,
+ });
+
+ @override
+ State<AccountDetailHeader> createState() => _AccountDetailHeaderState();
+}
+
+class _AccountDetailHeaderState extends State<AccountDetailHeader> {
+ late final AccountDetailService _accountDetailService =
+ widget.accountDetailService ?? AccountDetailService();
+ late final bool _ownsAccountDetailService =
+ widget.accountDetailService == null;
+ late Account _account;
+ bool _isLoading = false;
+ String? _error;
+ List<AccountBalance> _balances = [];
+ List<AccountHolding> _holdings = [];
+ bool _disposed = false;
+ bool _accountDetailServiceClosed = false;
+ int _activeDetailLoads = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ _account = widget.account;
+ _loadDetails();
+ }
+
+ Future<void> _loadDetails() async {
+ if (_disposed) return;
+
+ final authProvider = Provider.of<AuthProvider>(context, listen: false);
+ final accessToken = await authProvider.getValidAccessToken();
+ if (_disposed) return;
+
+ if (accessToken == null) {
+ await authProvider.logout();
+ return;
+ }
+
+ _activeDetailLoads += 1;
+
+ if (mounted) {
+ setState(() {
+ _isLoading = true;
+ _error = null;
+ });
+ }
+
+ try {
+ final results = await Future.wait([
+ _accountDetailService.getAccountDetail(
+ accessToken: accessToken,
+ accountId: widget.account.id,
+ ),
+ _accountDetailService.getBalances(
+ accessToken: accessToken,
+ accountId: widget.account.id,
+ ),
+ ]);
+
+ final accountResult = results[0];
+ final balancesResult = results[1];
+ final resolvedAccount = accountResult['success'] == true &&
+ accountResult['account'] is Account
+ ? accountResult['account'] as Account
+ : _account;
+
+ Map<String, dynamic>? holdingsResult;
+ if (_supportsHoldings(resolvedAccount)) {
+ holdingsResult = await _accountDetailService.getHoldings(
+ accessToken: accessToken,
+ accountId: widget.account.id,
+ );
+ }
+
+ if (!mounted || _disposed) return;
+
+ if (accountResult['error'] == 'unauthorized' ||
+ balancesResult['error'] == 'unauthorized' ||
+ holdingsResult?['error'] == 'unauthorized') {
+ await authProvider.logout();
+ return;
+ }
+
+ setState(() {
+ if (accountResult['success'] == true &&
+ accountResult['account'] is Account) {
+ _account = resolvedAccount;
+ }
+ if (balancesResult['success'] == true) {
+ _balances = (balancesResult['balances'] as List<dynamic>? ?? [])
+ .whereType<AccountBalance>()
+ .toList();
+ }
+ if (holdingsResult?['success'] == true) {
+ _holdings = (holdingsResult?['holdings'] as List<dynamic>? ?? [])
+ .whereType<AccountHolding>()
+ .toList();
+ }
+ if (accountResult['success'] != true &&
+ balancesResult['success'] != true) {
+ _error = 'Account details are temporarily unavailable';
+ }
+ _isLoading = false;
+ });
+ } finally {
+ _activeDetailLoads -= 1;
+ _closeOwnedAccountDetailServiceIfIdle();
+ }
+ }
+
+ bool _supportsHoldings(Account account) {
+ return account.accountType == 'investment' ||
+ account.accountType == 'crypto';
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _closeOwnedAccountDetailServiceIfIdle();
+ super.dispose();
+ }
+
+ void _closeOwnedAccountDetailServiceIfIdle() {
+ if (_ownsAccountDetailService &&
+ _disposed &&
+ _activeDetailLoads == 0 &&
+ !_accountDetailServiceClosed) {
+ _accountDetailService.close();
+ _accountDetailServiceClosed = true;
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = Theme.of(context).colorScheme;
+ final latestBalance = _balances.isNotEmpty ? _balances.first : null;
+
+ return Card(
+ margin: const EdgeInsets.fromLTRB(16, 8, 16, 8),
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ _account.displayAccountType,
+ style: Theme.of(context).textTheme.labelLarge?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ _account.balance,
+ style: Theme.of(context)
+ .textTheme
+ .headlineSmall
+ ?.copyWith(
+ fontWeight: FontWeight.bold,
+ color: _account.isLiability ? Colors.red : null,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (_isLoading)
+ const SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ else
+ IconButton(
+ icon: const Icon(Icons.refresh),
+ tooltip: 'Refresh account details',
+ onPressed: _loadDetails,
+ ),
+ ],
+ ),
+ if (_account.institutionName != null ||
+ _account.subtype != null ||
+ _account.cashBalance != null ||
+ _account.status != null) ...[
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ if (_account.institutionName != null)
+ _DetailChip(
+ label: _account.institutionName!,
+ icon: Icons.account_balance,
+ ),
+ if (_account.subtype != null)
+ _DetailChip(
+ label: _account.subtype!,
+ icon: Icons.category_outlined,
+ ),
+ if (_account.cashBalance != null)
+ _DetailChip(
+ label: 'Cash ${_account.cashBalance}',
+ icon: Icons.payments_outlined,
+ ),
+ if (_account.status != null)
+ _DetailChip(
+ label: _account.status!,
+ icon: Icons.sync,
+ ),
+ ],
+ ),
+ ],
+ if (_balances.length >= 2) ...[
+ const SizedBox(height: 16),
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Recent balance history',
+ style: Theme.of(context).textTheme.titleSmall,
+ ),
+ ),
+ Text(
+ latestBalance == null
+ ? ''
+ : DateFormat.yMMMd(
+ Localizations.localeOf(context).toString(),
+ ).format(latestBalance.date),
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ SizedBox(
+ height: 56,
+ child: _BalanceSparkline(balances: _balances),
+ ),
+ ],
+ if (_holdings.isNotEmpty) ...[
+ const SizedBox(height: 16),
+ Text(
+ 'Top holdings',
+ style: Theme.of(context).textTheme.titleSmall,
+ ),
+ const SizedBox(height: 8),
+ ..._holdings.take(3).map(
+ (holding) => Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ holding.ticker?.isNotEmpty == true
+ ? holding.ticker!
+ : holding.securityName ?? 'Holding',
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ Text(
+ holding.amount,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ if (_error != null) ...[
+ const SizedBox(height: 8),
+ Text(
+ _error!,
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: colorScheme.error,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _DetailChip extends StatelessWidget {
+ final String label;
+ final IconData icon;
+
+ const _DetailChip({
+ required this.label,
+ required this.icon,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = Theme.of(context).colorScheme;
+
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(
+ color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(icon, size: 14, color: colorScheme.onSurfaceVariant),
+ const SizedBox(width: 4),
+ Text(
+ label,
+ style: Theme.of(context).textTheme.labelSmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _BalanceSparkline extends StatelessWidget {
+ final List<AccountBalance> balances;
+
+ const _BalanceSparkline({required this.balances});
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = Theme.of(context).colorScheme;
+ final points = balances
+ .where((balance) => balance.balanceCents != null)
+ .toList()
+ .reversed
+ .toList();
+
+ if (points.length < 2) {
+ return const SizedBox.shrink();
+ }
+
+ return CustomPaint(
+ painter: _BalanceSparklinePainter(
+ values:
+ points.map((balance) => balance.balanceCents!.toDouble()).toList(),
+ color: colorScheme.primary,
+ ),
+ child: const SizedBox.expand(),
+ );
+ }
+}
+
+class _BalanceSparklinePainter extends CustomPainter {
+ final List<double> values;
+ final Color color;
+
+ const _BalanceSparklinePainter({
+ required this.values,
+ required this.color,
+ });
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ if (values.length < 2) return;
+
+ var minValue = values.first;
+ var maxValue = values.first;
+ for (final value in values) {
+ if (value < minValue) minValue = value;
+ if (value > maxValue) maxValue = value;
+ }
+
+ final range = maxValue - minValue;
+ final path = Path();
+ for (var index = 0; index < values.length; index++) {
+ final x = size.width * (index / (values.length - 1));
+ final normalized = range == 0 ? 0.5 : (values[index] - minValue) / range;
+ final y = size.height - (normalized * size.height);
+
+ if (index == 0) {
+ path.moveTo(x, y);
+ } else {
+ path.lineTo(x, y);
+ }
+ }
+
+ final guidePaint = Paint()
+ ..color = color.withValues(alpha: 0.12)
+ ..strokeWidth = 1;
+ canvas.drawLine(
+ Offset(0, size.height / 2),
+ Offset(size.width, size.height / 2),
+ guidePaint,
+ );
+
+ final linePaint = Paint()
+ ..color = color
+ ..strokeWidth = 2
+ ..style = PaintingStyle.stroke
+ ..strokeCap = StrokeCap.round
+ ..strokeJoin = StrokeJoin.round;
+ canvas.drawPath(path, linePaint);
+ }
+
+ @override
+ bool shouldRepaint(covariant _BalanceSparklinePainter oldDelegate) {
+ return !listEquals(oldDelegate.values, values) ||
+ oldDelegate.color != color;
+ }
+}
diff --git a/mobile/test/services/account_detail_service_test.dart b/mobile/test/services/account_detail_service_test.dart
new file mode 100644
index 0000000000..ab1a440bf7
--- /dev/null
+++ b/mobile/test/services/account_detail_service_test.dart
@@ -0,0 +1,394 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/testing.dart';
+import 'package:sure_mobile/services/account_detail_service.dart';
+
+void main() {
+ group('AccountDetailService', () {
+ test('fetches account metadata from the account show endpoint', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/accounts/acct_1');
+ expect(request.headers['Authorization'], 'Bearer token');
+ return http.Response(
+ '{"id":"acct_1","name":"Brokerage","balance":"\$1,200.00",'
+ '"balance_cents":120000,"cash_balance":"\$200.00",'
+ '"cash_balance_cents":20000,"currency":"USD",'
+ '"classification":"asset","account_type":"investment",'
+ '"subtype":"brokerage","status":"active",'
+ '"institution_name":"Sure Bank",'
+ '"institution_domain":"sure.local",'
+ '"created_at":"2026-06-01T00:00:00Z",'
+ '"updated_at":"2026-06-02T00:00:00Z"}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], true);
+ expect(result['account'].cashBalance, r'$200.00');
+ expect(result['account'].institutionName, 'Sure Bank');
+ });
+
+ test('returns unauthorized for account detail 401 responses', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/accounts/acct_1');
+ expect(request.headers['Authorization'], 'Bearer token');
+ return http.Response('{"error":"Unauthorized"}', 401);
+ }),
+ );
+
+ final result = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], false);
+ expect(result['error'], 'unauthorized');
+ });
+
+ test('encodes account ids in account detail paths', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.toString(), contains('/api/v1/accounts/acct%2F1'));
+ return http.Response(
+ '{"id":"acct/1","name":"Brokerage","balance":"\$1,200.00",'
+ '"currency":"USD","classification":"asset",'
+ '"account_type":"investment"}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'acct/1',
+ );
+
+ expect(result['success'], true);
+ expect(result['account'].id, 'acct/1');
+ });
+
+ test('returns fallback error for account detail 404 responses', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/accounts/missing');
+ return http.Response('{"error":"Not found"}', 404);
+ }),
+ );
+
+ final result = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'missing',
+ );
+
+ expect(result['success'], false);
+ expect(result['error'], 'Failed to fetch account');
+ });
+
+ test('returns fallback error for account detail server failures', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/accounts/acct_1');
+ return http.Response('{"error":"Server error"}', 500);
+ }),
+ );
+
+ final result = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], false);
+ expect(result['error'], 'Failed to fetch account');
+ });
+
+ test('returns generic error for account detail network failures', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ throw http.ClientException('connection failed');
+ }),
+ );
+
+ final result = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], false);
+ expect(
+ result['error'],
+ 'Unable to load account details. Please try again later.',
+ );
+ });
+
+ test('returns generic error for malformed account detail JSON', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/accounts/acct_1');
+ return http.Response('{', 200);
+ }),
+ );
+
+ final result = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], false);
+ expect(
+ result['error'],
+ 'Unable to load account details. Please try again later.',
+ );
+ });
+
+ test('fetches scoped balance history', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/balances');
+ expect(request.url.queryParameters['account_id'], 'acct_1');
+ expect(request.url.queryParameters['per_page'], '30');
+ return http.Response(
+ '{"balances":[{"id":"bal_1","date":"2026-06-01",'
+ '"currency":"USD","balance":"\$1,200.00",'
+ '"balance_cents":120000,"cash_balance":"\$200.00",'
+ '"cash_balance_cents":20000}]}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getBalances(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], true);
+ expect(result['balances'].single.balanceCents, 120000);
+ });
+
+ test('returns generic error for malformed balance dates', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/balances');
+ return http.Response(
+ '{"balances":[{"id":"bal_1","date":"not-a-date",'
+ '"currency":"USD","balance":"\$1,200.00"}]}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getBalances(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], false);
+ expect(
+ result['error'],
+ 'Unable to load balance history. Please try again later.',
+ );
+ });
+
+ test('fetches scoped holdings for investment accounts', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/holdings');
+ expect(request.url.queryParameters['account_id'], 'acct_1');
+ expect(request.url.queryParameters['page'], '1');
+ expect(request.url.queryParameters['per_page'], '100');
+ return http.Response(
+ '{"holdings":[{"id":"holding_1","date":"2026-06-01",'
+ '"qty":"4.0","price":"\$10.00","amount":"\$40.00",'
+ '"currency":"USD","security":{"ticker":"SURE",'
+ '"name":"Sure Inc."}}],'
+ '"pagination":{"page":1,"per_page":100,"total_count":1,'
+ '"total_pages":1}}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getHoldings(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], true);
+ expect(result['holdings'].single.ticker, 'SURE');
+ expect(result['holdings'].single.amount, r'$40.00');
+ });
+
+ test('fetches latest holdings page before returning top holdings',
+ () async {
+ var requestCount = 0;
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ requestCount += 1;
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/holdings');
+ expect(request.url.queryParameters['account_id'], 'acct_1');
+ expect(request.url.queryParameters['per_page'], '100');
+
+ if (requestCount == 1) {
+ expect(request.url.queryParameters['page'], '1');
+ return http.Response(
+ '{"holdings":[{"id":"old_holding","date":"2025-01-01",'
+ '"qty":"1.0","price":"\$5.00","amount":"\$5.00",'
+ '"currency":"USD","security":{"ticker":"OLD",'
+ '"name":"Old Holding"}}],'
+ '"pagination":{"page":1,"per_page":100,"total_count":4,'
+ '"total_pages":2}}',
+ 200,
+ );
+ }
+
+ expect(request.url.queryParameters['page'], '2');
+ return http.Response(
+ '{"holdings":[{"id":"stale_same_page","date":"2026-05-31",'
+ '"qty":"1.0","price":"\$5.00","amount":"\$5.00",'
+ '"currency":"USD","security":{"ticker":"STALE",'
+ '"name":"Stale Holding"}},'
+ '{"id":"small_current","date":"2026-06-01",'
+ '"qty":"1.0","price":"\$10.00","amount":"\$10.00",'
+ '"currency":"USD","security":{"ticker":"SMALL",'
+ '"name":"Small Holding"}},'
+ '{"id":"large_current","date":"2026-06-01",'
+ '"qty":"1.0","price":"\$125.00","amount":"\$125.00",'
+ '"currency":"USD","security":{"ticker":"LARGE",'
+ '"name":"Large Holding"}}],'
+ '"pagination":{"page":2,"per_page":100,"total_count":4,'
+ '"total_pages":2}}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getHoldings(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ perPage: 1,
+ );
+
+ expect(result['success'], true);
+ expect(requestCount, 2);
+ expect(result['holdings'], hasLength(1));
+ expect(result['holdings'].single.ticker, 'LARGE');
+ });
+
+ test('parses non-string account balance and holding scalar values',
+ () async {
+ var requestCount = 0;
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ requestCount += 1;
+
+ if (request.url.path == '/api/v1/accounts/acct_1') {
+ return http.Response(
+ '{"id":"acct_1","name":123,"balance":1200.5,'
+ '"cash_balance":200,"currency":840,'
+ '"classification":true,"account_type":"investment",'
+ '"subtype":42,"status":1,"institution_name":987,'
+ '"institution_domain":654}',
+ 200,
+ );
+ }
+
+ if (request.url.path == '/api/v1/balances') {
+ return http.Response(
+ '{"balances":[{"id":"bal_1","date":"2026-06-01",'
+ '"currency":840,"balance":1200.5,'
+ '"cash_balance":200}]}',
+ 200,
+ );
+ }
+
+ if (request.url.path == '/api/v1/holdings') {
+ return http.Response(
+ '{"holdings":[{"id":"holding_1","date":"2026-06-01",'
+ '"qty":4,"price":10,"amount":40,"currency":840,'
+ '"security":{"ticker":123,"name":456}}],'
+ '"pagination":{"page":1,"per_page":100,"total_count":1,'
+ '"total_pages":1}}',
+ 200,
+ );
+ }
+
+ return http.Response('{}', 404);
+ }),
+ );
+
+ final accountResult = await service.getAccountDetail(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+ final balancesResult = await service.getBalances(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+ final holdingsResult = await service.getHoldings(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(requestCount, 3);
+ expect(accountResult['success'], true);
+ expect(accountResult['account'].cashBalance, '200');
+ expect(accountResult['account'].subtype, '42');
+ expect(accountResult['account'].institutionDomain, '654');
+ expect(balancesResult['success'], true);
+ expect(balancesResult['balances'].single.currency, '840');
+ expect(balancesResult['balances'].single.balance, '1200.5');
+ expect(balancesResult['balances'].single.cashBalance, '200');
+ expect(holdingsResult['success'], true);
+ expect(holdingsResult['holdings'].single.price, '10');
+ expect(holdingsResult['holdings'].single.amount, '40');
+ expect(holdingsResult['holdings'].single.currency, '840');
+ expect(holdingsResult['holdings'].single.ticker, '123');
+ expect(holdingsResult['holdings'].single.securityName, '456');
+ });
+
+ test('returns generic error for malformed holding dates', () async {
+ final service = AccountDetailService(
+ client: MockClient((request) async {
+ expect(request.method, 'GET');
+ expect(request.url.path, '/api/v1/holdings');
+ expect(request.url.queryParameters['page'], '1');
+ return http.Response(
+ '{"holdings":[{"id":"holding_1","date":"not-a-date",'
+ '"qty":"4.0","price":"\$10.00","amount":"\$40.00",'
+ '"currency":"USD"}],'
+ '"pagination":{"page":1,"per_page":100,"total_count":1,'
+ '"total_pages":1}}',
+ 200,
+ );
+ }),
+ );
+
+ final result = await service.getHoldings(
+ accessToken: 'token',
+ accountId: 'acct_1',
+ );
+
+ expect(result['success'], false);
+ expect(
+ result['error'], 'Unable to load holdings. Please try again later.');
+ });
+ });
+}