The personal finance app for everyone (by everyone)
Ruby
fix(mobile): load every page of accounts, not just the first 25 (#4545)
alexcastgonz544b3531541f
diff --git a/mobile/lib/providers/accounts_provider.dart b/mobile/lib/providers/accounts_provider.dartindex 885163c408..f3b3e175c8 100644--- a/mobile/lib/providers/accounts_provider.dart+++ b/mobile/lib/providers/accounts_provider.dart@@ -95,8 +95,6 @@ class AccountsProvider with ChangeNotifier {/// Fetch accounts (offline-first approach)Future<bool> fetchAccounts({required String accessToken,- int page = 1,- int perPage = 25,bool forceSync = false,}) async {_isLoading = true;@@ -112,13 +110,15 @@ class AccountsProvider with ChangeNotifier {notifyListeners();}- // If online and (force sync or no cached data), fetch from server+ // If online and (force sync, no cached data, or a cache that may be the+ // truncated first page older versions saved), fetch from serverfinal isOnline = _connectivityService?.isOnline ?? false;- if (isOnline && (forceSync || cachedAccounts.isEmpty)) {- final result = await _accountsService.getAccounts(+ final maybeTruncated =+ cachedAccounts.length == AccountsService.legacyPageSize;+ if (isOnline &&+ (forceSync || cachedAccounts.isEmpty || maybeTruncated)) {+ final result = await _accountsService.getAllAccounts(accessToken: accessToken,- page: page,- perPage: perPage,);if (result['success'] == true && result.containsKey('accounts')) {diff --git a/mobile/lib/services/accounts_service.dart b/mobile/lib/services/accounts_service.dartindex a98f31d288..7d16392e09 100644--- a/mobile/lib/services/accounts_service.dart+++ b/mobile/lib/services/accounts_service.dart@@ -4,6 +4,63 @@ import '../models/account.dart';import 'api_config.dart';class AccountsService {+ AccountsService({http.Client? client}) : _client = client ?? http.Client();++ final http.Client _client;++ /// The page size older versions fetched; a cache of exactly this many+ /// accounts may be a truncated first page.+ static const int legacyPageSize = 25;++ /// The API caps `per_page` at 100.+ static const int maxPerPage = 100;++ /// Upper bound on the pages [getAllAccounts] follows, so a bad `total_pages`+ /// cannot loop forever.+ static const int maxPages = 100;++ /// Fetches every page of accounts the user can access.+ ///+ /// Returns the same shape as [getAccounts], with all pages' accounts in+ /// `accounts` and the last page's `pagination`. If any page fails, that+ /// page's failure is returned and no accounts are, so a caller never+ /// replaces its cache with a partial list.+ Future<Map<String, dynamic>> getAllAccounts({+ required String accessToken,+ int perPage = maxPerPage,+ }) async {+ final accounts = <Account>[];+ Map<String, dynamic>? pagination;+ var page = 1;+ var totalPages = 1;++ while (page <= totalPages && page <= maxPages) {+ final result = await getAccounts(+ accessToken: accessToken,+ page: page,+ perPage: perPage,+ );+ if (result['success'] != true) return result;++ accounts.addAll((result['accounts'] as List<dynamic>).cast<Account>());+ pagination = result['pagination'] as Map<String, dynamic>?;+ totalPages = (pagination?['total_pages'] as num?)?.toInt() ?? 1;+ if (totalPages > maxPages) {+ return {+ 'success': false,+ 'error': 'Too many account pages to load ($totalPages)',+ };+ }+ page++;+ }++ return {+ 'success': true,+ 'accounts': accounts,+ 'pagination': pagination,+ };+ }+Future<Map<String, dynamic>> getAccounts({required String accessToken,int page = 1,@@ -14,10 +71,12 @@ class AccountsService {'${ApiConfig.baseUrl}/api/v1/accounts?page=$page&per_page=$perPage',);- final response = await http.get(- url,- headers: ApiConfig.getAuthHeaders(accessToken),- ).timeout(const Duration(seconds: 30));+ final response = await _client+ .get(+ url,+ headers: ApiConfig.getAuthHeaders(accessToken),+ )+ .timeout(const Duration(seconds: 30));if (response.statusCode == 200) {final responseData = jsonDecode(response.body);diff --git a/mobile/lib/services/sync_service.dart b/mobile/lib/services/sync_service.dartindex 8b9fa0b1ec..2e5b8d3075 100644--- a/mobile/lib/services/sync_service.dart+++ b/mobile/lib/services/sync_service.dart@@ -494,7 +494,7 @@ class SyncService with ChangeNotifier {Future<SyncResult> syncAccounts(String accessToken) async {try {final result =- await _accountsService.getAccounts(accessToken: accessToken);+ await _accountsService.getAllAccounts(accessToken: accessToken);if (result['success'] == true) {final accountsList = result['accounts'] as List<dynamic>? ?? [];diff --git a/mobile/test/services/accounts_service_test.dart b/mobile/test/services/accounts_service_test.dartnew file mode 100644index 0000000000..4b0716c019--- /dev/null+++ b/mobile/test/services/accounts_service_test.dart@@ -0,0 +1,127 @@+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:http/http.dart' as http;+import 'package:http/testing.dart';+import 'package:sure_mobile/models/account.dart';+import 'package:sure_mobile/services/accounts_service.dart';++/// Serves `/api/v1/accounts` the way the API pages it: `per_page` capped at+/// 100, accounts named `Account 001`, `Account 002`, ... in order.+MockClient accountsClient({+ required int total,+ List<http.Request>? log,+ int? failOnPage,+}) {+ return MockClient((request) async {+ log?.add(request);+ final page = int.parse(request.url.queryParameters['page'] ?? '1');+ final perPage = int.parse(request.url.queryParameters['per_page'] ?? '25');+ if (page == failOnPage) {+ return http.Response(jsonEncode({'error': 'Server error'}), 500);+ }+ final first = (page - 1) * perPage;+ final last = (first + perPage).clamp(0, total);+ final accounts = [+ for (var i = first; i < last; i++)+ {+ 'id': 'acct_$i',+ 'name': 'Account ${(i + 1).toString().padLeft(3, '0')}',+ 'balance': r'$10.00',+ 'currency': 'USD',+ 'classification': 'asset',+ 'account_type': 'depository',+ },+ ];+ return http.Response(+ jsonEncode({+ 'accounts': accounts,+ 'pagination': {+ 'page': page,+ 'per_page': perPage,+ 'total_count': total,+ 'total_pages': (total / perPage).ceil(),+ },+ }),+ 200,+ );+ });+}++void main() {+ group('AccountsService.getAllAccounts', () {+ test('returns every account of a family with more than one page of 25',+ () async {+ final requests = <http.Request>[];+ final service = AccountsService(+ client: accountsClient(total: 26, log: requests),+ );++ final result = await service.getAllAccounts(accessToken: 'token');++ expect(result['success'], isTrue);+ final accounts = result['accounts'] as List<Account>;+ expect(accounts, hasLength(26));+ expect(accounts.last.name, 'Account 026');+ });++ test('follows total_pages for a family with more than 100 accounts',+ () async {+ final requests = <http.Request>[];+ final service = AccountsService(+ client: accountsClient(total: 230, log: requests),+ );++ final result = await service.getAllAccounts(accessToken: 'token');++ final accounts = result['accounts'] as List<Account>;+ expect(accounts, hasLength(230));+ expect(accounts.map((a) => a.id).toSet(), hasLength(230));+ expect(+ requests.map((r) => r.url.queryParameters['page']),+ ['1', '2', '3'],+ );+ expect(requests.first.url.queryParameters['per_page'], '100');+ });++ test('makes a single request when everything fits on one page', () async {+ final requests = <http.Request>[];+ final service = AccountsService(+ client: accountsClient(total: 3, log: requests),+ );++ final result = await service.getAllAccounts(accessToken: 'token');++ expect(result['accounts'] as List<Account>, hasLength(3));+ expect(requests, hasLength(1));+ });++ test('fails without partial accounts when a later page fails', () async {+ final service = AccountsService(+ client: accountsClient(total: 230, failOnPage: 2),+ );++ final result = await service.getAllAccounts(accessToken: 'token');++ expect(result['success'], isFalse);+ expect(result['error'], 'Server error');+ expect(result.containsKey('accounts'), isFalse);+ });++ test('stops instead of following an absurd total_pages', () async {+ final log = <http.Request>[];+ final service = AccountsService(+ client: accountsClient(+ total: AccountsService.maxPages * 100 + 1,+ log: log,+ ),+ );++ final result = await service.getAllAccounts(accessToken: 'token');++ expect(result['success'], isFalse);+ expect(result.containsKey('accounts'), isFalse);+ expect(log, hasLength(1));+ });+ });+}