Unit test BadgeAwardService idempotency and atomicity
epic-achievement-badges-services-task-015 — Write unit tests for BadgeAwardService covering: successful badge award returns EarnedBadge with server timestamp, duplicate award returns existing record without error, conflict handling for concurrent award attempts, and that invalid mentorId or badgeDefinitionId throw typed exceptions. Use flutter_test and mock Supabase RPC client.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 3 - 413 tasks
Can start after Tier 2 completes
Implementation Notes
If BadgeAwardService calls a Supabase RPC function (e.g., award_badge_idempotent), the mock must implement the rpc() method of the SupabaseClient interface. Use a fake class rather than mockito generated mocks if the Supabase client has a complex generic interface that is hard to mock. For the concurrent conflict test, simulate the scenario sequentially in the test (first call throws conflict, second call returns existing record) since true concurrency is not testable in unit tests. Ensure exception classes (InvalidMentorIdException, MentorNotFoundException, etc.) are defined as typed Dart exceptions (implementing Exception) before writing tests — coordinate with task-010 implementer if not yet defined.
Testing Requirements
Pure unit tests using flutter_test. Mock the Supabase RPC client by implementing a fake that records invocations and returns configurable responses. For idempotency tests, configure the fake to return a pre-existing EarnedBadge on the second invocation. For conflict simulation, configure the fake to throw a PostgrestException with code '23505' (unique violation) on the first call and a valid record on a follow-up fetch.
Assert on the type of thrown exceptions using expect(..., throwsA(isA
peer-mentor-stats-aggregator must compute streaks and threshold counts across potentially hundreds of activity records per peer mentor. Naive queries (full table scans or N+1 patterns) will cause slow badge evaluation, especially when triggered on every activity save for all active peer mentors.
Mitigation & Contingency
Mitigation: Design aggregation queries using Supabase RPCs with window functions or materialised views from the start. Add database indexes on (peer_mentor_id, activity_date, activity_type) before writing any service code. Profile all aggregation queries against a dataset of 500+ activities during development.
Contingency: If query performance is insufficient at launch, implement incremental stat caching: maintain a peer_mentor_stats snapshot table updated on each activity insert via a database trigger, so the aggregator reads from pre-computed values rather than scanning raw activity rows.
badge-award-service must be idempotent, but if two concurrent edge function invocations evaluate the same peer mentor simultaneously (e.g., from a rapid double-save), both could pass the uniqueness check before either commits, resulting in duplicate badge records.
Mitigation & Contingency
Mitigation: Rely on the database-level uniqueness constraint (peer_mentor_id, badge_definition_id) as the final guard. In the service layer, use an upsert with ON CONFLICT DO NOTHING and return the existing record. Add a Postgres advisory lock or serialisable transaction for the award sequence during the edge function integration epic.
Contingency: If duplicate records are discovered in production, run a deduplication migration to remove extras (keeping earliest earned_at) and add a unique index if not already present. Alert engineering via Supabase database webhook on constraint violations.
The badge-configuration-service must validate org admin-supplied criteria JSON on save, but the full range of valid criteria types (threshold, streak, training-completion, tier-based) may not be fully enumerated during development, leading to either over-permissive or over-restrictive validation that frustrates admins.
Mitigation & Contingency
Mitigation: Define a versioned Dart sealed class hierarchy for CriteriaType before writing the validation logic. Review the hierarchy with product against all known badge types across NHF, Blindeforbundet, and HLF before implementation. Build the validator against the sealed class so new criteria types require an explicit code addition.
Contingency: If admins encounter validation rejections for legitimate criteria, expose a 'criteria_raw' escape hatch (JSON passthrough, admin-only) with a product warning, and schedule a sprint to formalise the new criteria type properly.