The personal finance app for everyone (by everyone)
Ruby
fix(mobile): make offline transaction replay idempotent (#2232)
ghost8822eab583e1
diff --git a/mobile/lib/providers/transactions_provider.dart b/mobile/lib/providers/transactions_provider.dartindex b34a77765d..e273641032 100644--- a/mobile/lib/providers/transactions_provider.dart+++ b/mobile/lib/providers/transactions_provider.dart@@ -225,6 +225,8 @@ class TransactionsProvider with ChangeNotifier {categoryId: categoryId,merchantId: merchantId,tagIds: tagIds == null || tagIds.isEmpty ? null : tagIds,+ externalId: localTransaction.localId,+ source: TransactionsService.mobileIdempotencySource,).then((result) async {if (_isDisposed) return;diff --git a/mobile/lib/services/offline_storage_service.dart b/mobile/lib/services/offline_storage_service.dartindex 10ccbab335..bf2fc3cb8d 100644--- a/mobile/lib/services/offline_storage_service.dart+++ b/mobile/lib/services/offline_storage_service.dart@@ -28,6 +28,9 @@ class OfflineStorageService {String? serverId,SyncStatus syncStatus = SyncStatus.pending,}) async {+ // Generated once when the transaction enters the offline queue, then+ // persisted as transactions.local_id and reused as the mobile idempotency+ // key on every replay attempt.final localId = _uuid.v4();_log.info(diff --git a/mobile/lib/services/sync_service.dart b/mobile/lib/services/sync_service.dartindex ced804f405..8b9fa0b1ec 100644--- a/mobile/lib/services/sync_service.dart+++ b/mobile/lib/services/sync_service.dart@@ -179,6 +179,8 @@ class SyncService with ChangeNotifier {categoryId: transaction.categoryId,merchantId: transaction.merchantId,tagIds: transaction.tagIds,+ externalId: transaction.localId,+ source: TransactionsService.mobileIdempotencySource,);if (result['success'] == true) {diff --git a/mobile/lib/services/transactions_service.dart b/mobile/lib/services/transactions_service.dartindex 233bde1783..38bd912797 100644--- a/mobile/lib/services/transactions_service.dart+++ b/mobile/lib/services/transactions_service.dart@@ -4,6 +4,8 @@ import '../models/transaction.dart';import 'api_config.dart';class TransactionsService {+ static const String mobileIdempotencySource = 'sure_mobile';+final http.Client _client;TransactionsService({http.Client? client})@@ -21,8 +23,15 @@ class TransactionsService {String? categoryId,String? merchantId,List<String>? tagIds,+ String? externalId,+ String? source,}) async {final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/transactions');+ // Idempotency is only valid when both halves of the key are present.+ final hasIdempotencyKey = externalId != null &&+ externalId.isNotEmpty &&+ source != null &&+ source.isNotEmpty;final body = {'transaction': {@@ -36,6 +45,8 @@ class TransactionsService {if (categoryId != null) 'category_id': categoryId,if (merchantId != null) 'merchant_id': merchantId,if (tagIds != null) 'tag_ids': tagIds,+ if (hasIdempotencyKey) 'external_id': externalId,+ if (hasIdempotencyKey) 'source': source,}};diff --git a/mobile/test/models/transaction_metadata_test.dart b/mobile/test/models/transaction_metadata_test.dartindex b657279501..c74f01306e 100644--- a/mobile/test/models/transaction_metadata_test.dart+++ b/mobile/test/models/transaction_metadata_test.dart@@ -57,6 +57,26 @@ void main() {expect(restored.syncStatus, SyncStatus.synced);});+ test('pending offline replay keeps the stored local id', () {+ final pendingTransaction = OfflineTransaction(+ localId: 'local_123',+ accountId: 'acct_1',+ name: 'Coffee',+ date: '2026-06-01',+ amount: r'$4.50',+ currency: 'USD',+ nature: 'expense',+ syncStatus: SyncStatus.pending,+ );++ final restored = OfflineTransaction.fromDatabaseMap(+ pendingTransaction.toDatabaseMap(),+ );++ expect(restored.localId, 'local_123');+ expect(restored.syncStatus, SyncStatus.pending);+ });+test('preserves omitted tag state for stored rows without tag columns', () {final restored = OfflineTransaction.fromDatabaseMap({'server_id': 'tx_1',diff --git a/mobile/test/services/transactions_service_test.dart b/mobile/test/services/transactions_service_test.dartindex abc2e54a42..db66d69f57 100644--- a/mobile/test/services/transactions_service_test.dart+++ b/mobile/test/services/transactions_service_test.dart@@ -1,3 +1,5 @@+import 'dart:convert';+import 'package:flutter_test/flutter_test.dart';import 'package:http/http.dart' as http;import 'package:http/testing.dart';@@ -5,38 +7,149 @@ import 'package:sure_mobile/services/transactions_service.dart';void main() {group('TransactionsService', () {- test('preserves field-level update errors', () async {+ test(+ 'sends idempotency fields when creating mobile transactions',+ () async {+ final service = TransactionsService(+ client: MockClient((request) async {+ expect(request.method, 'POST');+ expect(request.url.path, '/api/v1/transactions');+ expect(request.body, contains('"external_id":"local_123"'));+ expect(request.body, contains('"source":"sure_mobile"'));+ return http.Response(+ '{"id":"tx_1","account":{"id":"acct_1"},"name":"Coffee",'+ '"date":"2026-06-01","amount":"\$4.50","currency":"USD",'+ '"classification":"expense"}',+ 201,+ );+ }),+ );++ final result = await service.createTransaction(+ accessToken: 'token',+ accountId: 'acct_1',+ name: 'Coffee',+ date: '2026-06-01',+ amount: '4.50',+ currency: 'USD',+ nature: 'expense',+ externalId: 'local_123',+ source: TransactionsService.mobileIdempotencySource,+ );++ expect(result['success'], true);+ expect(result['transaction'].id, 'tx_1');+ },+ );++ test('omits idempotency fields when creating regular transactions',+ () async {final service = TransactionsService(client: MockClient((request) async {- expect(request.method, 'PATCH');+ final payload = jsonDecode(request.body) as Map<String, dynamic>;+ final transaction = payload['transaction'] as Map<String, dynamic>;++ expect(transaction.containsKey('external_id'), false);+ expect(transaction.containsKey('source'), false);+return http.Response(- '{"message":"Transaction could not be updated",'- '"errors":{"name":["is too long"],'- '"notes":["contains unsupported characters"]}}',- 422,+ '{"id":"tx_1","account":{"id":"acct_1"},"name":"Coffee",'+ '"date":"2026-06-01","amount":"\$4.50","currency":"USD",'+ '"classification":"expense"}',+ 201,);}),);- final result = await service.updateTransaction(+ final result = await service.createTransaction(accessToken: 'token',- transactionId: 'tx_1',+ accountId: 'acct_1',name: 'Coffee',+ date: '2026-06-01',+ amount: '4.50',+ currency: 'USD',+ nature: 'expense',);- expect(result['success'], false);- expect(- result['error'],- 'Transaction could not be updated: Name is too long; Notes contains unsupported characters',+ expect(result['success'], true);+ });++ test('omits empty idempotency fields when creating transactions', () async {+ final service = TransactionsService(+ client: MockClient((request) async {+ final payload = jsonDecode(request.body) as Map<String, dynamic>;+ final transaction = payload['transaction'] as Map<String, dynamic>;++ expect(transaction.containsKey('external_id'), false);+ expect(transaction.containsKey('source'), false);++ return http.Response(+ '{"id":"tx_1","account":{"id":"acct_1"},"name":"Coffee",'+ '"date":"2026-06-01","amount":"\$4.50","currency":"USD",'+ '"classification":"expense"}',+ 201,+ );+ }),+ );++ final result = await service.createTransaction(+ accessToken: 'token',+ accountId: 'acct_1',+ name: 'Coffee',+ date: '2026-06-01',+ amount: '4.50',+ currency: 'USD',+ nature: 'expense',+ externalId: '',+ source: '',);++ expect(result['success'], true);});- test('returns null transaction for empty successful update responses',+ test('omits partial idempotency fields when creating transactions',() async {+ final service = TransactionsService(+ client: MockClient((request) async {+ final payload = jsonDecode(request.body) as Map<String, dynamic>;+ final transaction = payload['transaction'] as Map<String, dynamic>;++ expect(transaction.containsKey('external_id'), false);+ expect(transaction.containsKey('source'), false);++ return http.Response(+ '{"id":"tx_1","account":{"id":"acct_1"},"name":"Coffee",'+ '"date":"2026-06-01","amount":"\$4.50","currency":"USD",'+ '"classification":"expense"}',+ 201,+ );+ }),+ );++ final result = await service.createTransaction(+ accessToken: 'token',+ accountId: 'acct_1',+ name: 'Coffee',+ date: '2026-06-01',+ amount: '4.50',+ currency: 'USD',+ nature: 'expense',+ externalId: 'local_123',+ );++ expect(result['success'], true);+ });++ test('preserves field-level update errors', () async {final service = TransactionsService(client: MockClient((request) async {expect(request.method, 'PATCH');- return http.Response('', 204);+ return http.Response(+ '{"message":"Transaction could not be updated",'+ '"errors":{"name":["is too long"],'+ '"notes":["contains unsupported characters"]}}',+ 422,+ );}),);@@ -46,10 +159,34 @@ void main() {name: 'Coffee',);- expect(result['success'], true);- expect(result['transaction'], isNull);+ expect(result['success'], false);+ expect(+ result['error'],+ 'Transaction could not be updated: Name is too long; Notes contains unsupported characters',+ );});+ test(+ 'returns null transaction for empty successful update responses',+ () async {+ final service = TransactionsService(+ client: MockClient((request) async {+ expect(request.method, 'PATCH');+ return http.Response('', 204);+ }),+ );++ final result = await service.updateTransaction(+ accessToken: 'token',+ transactionId: 'tx_1',+ name: 'Coffee',+ );++ expect(result['success'], true);+ expect(result['transaction'], isNull);+ },+ );+test('fetches one transaction after an empty update response', () async {var requestCount = 0;final service = TransactionsService(