Unit test ExpenseClaimStatusRepository optimistic locking
epic-expense-approval-workflow-foundation-task-012 — Write unit tests for ExpenseClaimStatusRepository covering: successful status update with correct version, OptimisticLockException when concurrent update detected, stream emission on status change, and all valid status transition paths. Mock Supabase responses to simulate concurrent modification. Verify the WHERE clause includes both claim_id and version in update operations.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 3 - 413 tasks
Can start after Tier 2 completes
Implementation Notes
The optimistic lock test is the most critical: simulate the concurrent conflict by configuring the mock to return PostgrestResponse with count=0 (no rows updated). The repository must interpret 0-row updates as a conflict — document this as the implicit lock signal. For status transition tests, consider using a table-driven approach: define a const List<(ClaimStatus from, ClaimStatus to, bool valid)> and loop through it to generate parameterized tests. This ensures all transitions are covered without repetitive code.
The stream test requires careful setup: statusStream() likely starts with an initial fetch, then subscribes to Realtime — mock both the initial select() and the channel subscription in sequence. Use StreamMatcher (emitsInOrder, emitsError) for stream assertions.
Testing Requirements
Unit tests in flutter_test using mocktail and fake_async. Key challenge: mock the Supabase update chain and capture the .eq() filter arguments to verify the WHERE clause contains both claim_id AND version. Use a captor pattern (mocktail verify(mock.from('claim_status').update(any).eq('id', captureAny).eq('version', captureAny))) to assert both filter values. For stream tests, use StreamController in the mock to emit simulated Realtime events and verify they appear in statusStream().
Use fake_async for any timeout-related stream behavior. Structure in group('ExpenseClaimStatusRepository', ...) with nested groups for 'updateStatus', 'statusStream', and 'statusTransitions'. Place at test/infrastructure/repositories/expense_claim_status_repository_test.dart.
Optimistic locking in ExpenseClaimStatusRepository may produce excessive concurrency exceptions in high-volume coordinator sessions where multiple coordinators process the same queue simultaneously, causing confusing UI errors and coordinator frustration.
Mitigation & Contingency
Mitigation: Design the locking strategy with a short retry window (1-2 automatic retries with 200ms back-off) before surfacing the error to the UI. Document the concurrency model clearly so the UI layer can display a contextual 'claim was already actioned' message rather than a generic error.
Contingency: If contention remains high under load testing, switch to a last-writer-wins update with a conflict notification rather than a hard block, and log all concurrent edits for audit purposes.
FCM device tokens stored for peer mentors may be stale (app reinstalled, token rotated) causing push notifications for claim status changes to silently fail, leaving submitters unaware their claim was approved or rejected.
Mitigation & Contingency
Mitigation: Implement token refresh on every app launch and store updated tokens in Supabase. ApprovalNotificationService should fall back to in-app Realtime delivery when FCM returns an invalid-token error and should queue a token refresh request.
Contingency: If FCM delivery rates fall below acceptable thresholds in production monitoring, add a polling fallback in the peer mentor claim list screen that checks status on foreground resume.
Supabase Realtime has per-project channel and connection limits. If many coordinators and peer mentors are simultaneously subscribed across multiple screens, the project may hit quota limits causing subscription failures.
Mitigation & Contingency
Mitigation: Design RealtimeApprovalSubscription to use a single shared channel per user session rather than per-screen subscriptions. Implement subscription reference counting so channels are only opened once and reused across screens.
Contingency: Upgrade the Supabase plan tier if limits are reached, and implement graceful degradation to polling with a 30-second interval when Realtime is unavailable.