# Product Requirements Document

## Validation Checklist

- [x] All required sections are complete
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Problem statement is specific and measurable
- [x] Problem is validated by evidence (not assumptions)
- [x] Context → Problem → Solution flow makes sense
- [x] Every persona has at least one user journey
- [x] All MoSCoW categories addressed (Must/Should/Could/Won't)
- [x] Every feature has testable acceptance criteria
- [x] Every metric has corresponding tracking events
- [x] No feature redundancy (check for duplicates)
- [x] No contradictions between sections
- [x] No technical implementation details included
- [x] A new team member could understand this PRD

---

## Product Overview

### Vision
Establish a comprehensive, production-grade testing foundation that enables the BuyerKiosk Live Flutter app to ship with confidence, catch regressions before users do, and maintain code quality as the team scales.

### Problem Statement
The BuyerKiosk Live Flutter app is a **production-grade application with ~0% test coverage** despite handling critical retail operations including financial transactions, buyer queues, and performance metrics. The single existing smoke test provides no protection against:

- **Regression bugs**: Changes to currency parsing, date formatting, or permission logic could break silently
- **Business logic errors**: Division by zero, incorrect access control, or data mapping failures go undetected
- **Integration failures**: API changes, auth token handling, or real-time updates can break without warning

**Evidence of Risk (from Analysis Findings)**:
- 179 source files with ZERO unit tests
- High-severity risk: Permission hierarchy bugs could expose manager-only features to employees
- Medium-severity risk: Currency/date parsing edge cases affect financial displays
- Auth error handling relies on untested 30-second caching logic

**Consequences of Not Solving**:
- Production bugs discovered by end users (store managers, employees)
- Reduced confidence in deployments → slower release cycles
- Technical debt compounds as untested code grows
- New team members can't refactor safely without test safety net

### Value Proposition
This testing foundation provides:

1. **Deployment Confidence**: Ship new features knowing existing functionality won't break
2. **Fast Feedback Loops**: Catch bugs in development, not production
3. **Living Documentation**: Tests document expected behavior and edge cases
4. **Safe Refactoring**: Improve code quality without fear of silent regressions
5. **CI/CD Integration**: Automated quality gates prevent broken code from merging

## User Personas

### Primary Persona: Flutter Developer (Internal Team)
- **Demographics:** Software developer working on the BuyerKiosk Live app, intermediate to senior Flutter/Dart experience
- **Goals:**
  - Ship features quickly without breaking existing functionality
  - Refactor code confidently with test coverage as a safety net
  - Understand expected behavior through test documentation
  - Pass PR reviews with evidence that changes work correctly
- **Pain Points:**
  - No existing tests to validate changes don't break other features
  - Manual testing is time-consuming and error-prone
  - Can't refactor legacy code without risk of silent regressions
  - CI/CD provides no quality gates - broken code can merge

### Secondary Personas

#### QA Engineer / Release Manager
- **Demographics:** Quality assurance professional responsible for release readiness
- **Goals:**
  - Verify release candidates meet quality standards
  - Identify regressions before users do
  - Reduce manual testing burden through automation
- **Pain Points:**
  - No automated regression testing exists
  - Manual test cycles delay releases
  - Edge cases discovered in production, not QA

#### New Team Member / Contributor
- **Demographics:** Developer joining the project or occasional contributor
- **Goals:**
  - Understand how features should behave
  - Make changes without fear of breaking things
  - Learn codebase patterns through test examples
- **Pain Points:**
  - No tests to document expected behavior
  - Risk of introducing bugs when unfamiliar with codebase
  - No examples of how to test project-specific patterns

## User Journey Maps

### Primary User Journey: Developer Implementing a Feature Change
1. **Awareness:** Developer receives task to modify currency parsing logic or add new API endpoint
2. **Consideration:**
   - "Will this change break existing functionality?"
   - "How do I verify my changes work correctly?"
   - "What edge cases should I handle?"
3. **Adoption:**
   - Run existing tests to establish baseline: `flutter test`
   - Review relevant test files for expected behavior
   - Write/update tests for new functionality
4. **Usage:**
   - Write test cases covering happy path and edge cases
   - Run tests locally before committing
   - CI/CD validates changes don't break other tests
   - PR includes test coverage for new code
5. **Retention:**
   - Confidence in changes increases with test feedback
   - Faster PR reviews with automated validation
   - Reduced production bugs builds trust in test suite

### Secondary User Journeys

#### Journey: Debugging a Production Issue
1. **Trigger:** Production bug reported (e.g., "currency displays wrong for negative values")
2. **Investigation:** Review tests for currency parsing - discover gap in negative value handling
3. **Resolution:** Write failing test that reproduces bug, fix code, verify test passes
4. **Prevention:** Test remains as regression protection for future changes

#### Journey: Onboarding New Developer
1. **Orientation:** New developer clones repo, runs `flutter test` to validate setup
2. **Learning:** Reviews test files to understand expected behavior of components
3. **First Contribution:** Uses existing test patterns as templates for new tests
4. **Integration:** Submits PR with tests, CI validates, team reviews with confidence

## Feature Requirements

### Must Have Features

#### Feature 1: Test Infrastructure Foundation
- **User Story:** As a developer, I want a properly structured test directory with shared fixtures and mock utilities so that I can write tests efficiently without duplicating setup code.
- **Acceptance Criteria:**
  - [ ] Test directory structure follows Flutter conventions: `test/unit/`, `test/widget/`, `test/integration/`, `test/fixtures/`
  - [ ] Shared mock factories exist for all repositories (using Mocktail)
  - [ ] Test helper utilities exist for common operations (ProviderContainer setup, async pumping)
  - [ ] Sample JSON fixtures exist for API response testing
  - [ ] `flutter test` runs successfully with no failures

#### Feature 2: Core Utilities Unit Tests
- **User Story:** As a developer, I want unit tests for critical utility functions so that currency, date, and hash operations are validated.
- **Acceptance Criteria:**
  - [ ] `currency_utils_test.dart`: 15+ tests covering parsing ($1,234.56, ($1,234.56), negative values), formatting, compact notation
  - [ ] `date_utils_test.dart`: 20+ tests covering format/parse round-trips, relative time, edge cases (DST, month boundaries)
  - [ ] `time_utils_test.dart`: 15+ tests covering wait time formatting, duration parsing
  - [ ] `hash_utils_test.dart`: 10+ tests covering SHA256/512, MD5, HMAC, checksum operations
  - [ ] All tests pass with no flaky failures

#### Feature 3: Permission System Unit Tests
- **User Story:** As a developer, I want comprehensive tests for the permission system so that access control logic is validated and secure.
- **Acceptance Criteria:**
  - [ ] `permission_constants_test.dart`: Tests for AccessLevel enum, `canAccess()` privilege logic, role mapping
  - [ ] Verify owner(1) can access all pages, employee(4) only basic pages
  - [ ] Verify `fromRole()` handles all role values correctly, defaults to employee
  - [ ] All 12 AppPage defaults are validated
  - [ ] Edge cases: invalid role values, boundary conditions

#### Feature 4: Error Handling Unit Tests
- **User Story:** As a developer, I want tests for the exception and failure hierarchy so that errors are classified and displayed correctly.
- **Acceptance Criteria:**
  - [ ] `exceptions_test.dart`: Tests for all 11 exception types, `toString()` formatting, context preservation
  - [ ] `failures_test.dart`: Tests for all 13 failure types, `userMessage` output, `canRetry` logic, `requiresAuth` flag
  - [ ] Verify error classification maps correctly (401/403 → AuthFailure, 5xx → ServerFailure)
  - [ ] Equatable equality tests for all failure types

#### Feature 5: Provider Unit Tests (Riverpod 3.x)
- **User Story:** As a developer, I want tests for critical AsyncNotifier providers so that state management logic is validated.
- **Acceptance Criteria:**
  - [ ] `auth_provider_test.dart` covering:
    - Initial state: `AsyncLoading` on first build
    - `checkInstallation()`: Returns true/false based on storage
    - `validateApiKey()`: Success → stores credentials; Failure → preserves old state
    - 403 Error handling: Clears storage, transitions to error state
  - [ ] `dashboard_provider_test.dart` covering:
    - Initial fetch: `AsyncLoading` → `AsyncData<List<Store>>`
    - Empty response: Returns `AsyncData([])`, UI shows empty state
    - Auth error caching: Second call within 30s returns cached error (prevents API spam)
    - Manual refresh: Clears cache, fetches fresh data
    - Network timeout: Correct error classification
  - [ ] `permission_provider_test.dart` covering:
    - Initial load from storage: Loads saved permissions or defaults
    - `canAccess(page)`: Respects access level hierarchy (owner=1 < manager=2 < shiftLead=3 < employee=4)
    - Owner-only updates: Non-owners cannot call `updatePagePermission()`
    - `resetToDefaults()`: Restores default permission map
  - [ ] All tests use `ProviderContainer` with mock repository overrides
  - [ ] All tests call `addTearDown(container.dispose)` to prevent memory leaks
  - [ ] Async operations awaited with `await container.pump()` or `await Future<void>.value()`
  - [ ] All tests pass 5 consecutive local runs without intermittent failures

#### Feature 6: Data Mapper Unit Tests (Priority Mappers)
- **User Story:** As a developer, I want tests for model-to-entity mappers so that API data transforms correctly.
- **Acceptance Criteria:**
  - [ ] `today_performance_mapper_test.dart` (8 nested KPI mappers):
    - Sales, AvgTrans, TradePercent, Labor, Backstock, Buys, Activity, DailyGoals
    - Null fields return sensible defaults (0.0 for numbers, empty string for labels)
    - String-to-number parsing: "1234.56" → 1234.56
  - [ ] `workbook_note_mapper_test.dart`:
    - Date parsing: "2025-12-01" and "2025-12-01 14:30:00" formats
    - Fallback to DateTime.now() on invalid dates
    - Reactions list mapping (empty and populated)
  - [ ] `task_mapper_test.dart`:
    - Recurrence days: ["MON", "TUE", "WED"] mapping
    - Priority levels: high(1), normal(2), low(3)
    - Optional date fields (startDate, endDate can be null)
  - [ ] Test fixtures created in `test/fixtures/api_responses/`:
    - `today_performance_success.json` - valid API response
    - `workbook_notes_page1.json` - paginated notes response
    - `tasks_list.json` - tasks with various configurations
    - `null_fields.json` - response with null/missing fields
    - `string_numbers.json` - numbers as strings (API quirk)
  - [ ] All tests pass with no time-dependent failures (mock DateTime where needed)

#### Feature 7: CI/CD Test Pipeline
- **User Story:** As a developer, I want automated testing in CI/CD so that broken code cannot merge to main.
- **Acceptance Criteria:**
  - [ ] GitHub Actions workflow (`.github/workflows/test.yml`) runs on every PR and push to main
  - [ ] Workflow steps: checkout → setup Flutter → get dependencies → analyze → test with coverage
  - [ ] Coverage report generated with `flutter test --coverage`
  - [ ] Coverage threshold enforcement:
    - **60% minimum** on changed files in PR (blocks merge if not met)
    - Warning if total coverage drops below 60% (does not block initially)
    - Coverage tracked per PR diff, not just total repository coverage
  - [ ] Coverage exclusions configured in workflow:
    - Generated files: `**/*.g.dart`, `**/*.freezed.dart`
    - Main entry points: `lib/main.dart`, `lib/main_*.dart`
    - Router configuration: `lib/router/app_router.dart`
  - [ ] Test results visible as PR check with pass/fail status
  - [ ] Workflow fails fast: stops on first test failure
  - [ ] Test run completes in < 5 minutes (target: < 2 minutes)

### Should Have Features

#### Feature 8: API Interceptor Unit Tests
- **User Story:** As a developer, I want tests for Dio interceptors so that auth injection and retry logic are validated.
- **Acceptance Criteria:**
  - [ ] `api_interceptors_test.dart`: Tests for APIKey injection on all request types
  - [ ] 403 response handling triggers credential cleanup
  - [ ] Retry logic with exponential backoff validated
  - [ ] Max retry attempts respected
  - [ ] Sensitive data (APIKey) not logged

#### Feature 9: Widget Tests for Key Screens
- **User Story:** As a developer, I want widget tests for main screens so that UI rendering and interactions are validated.
- **Acceptance Criteria:**
  - [ ] `dashboard_screen_test.dart`: Tests for loading state, store list rendering, navigation
  - [ ] `store_detail_screen_test.dart`: Tests for metrics display, navigation to sub-screens
  - [ ] GoRouter navigation mocked with Mocktail
  - [ ] User interactions (tap, scroll) validated
  - [ ] Error state rendering tested

#### Feature 10: Remaining Mapper Tests (8 Additional Mappers)
- **User Story:** As a developer, I want tests for all remaining mappers so that data layer is fully covered.
- **Acceptance Criteria:**
  - [ ] `store_mapper_test.dart`: Store model → Store entity (typeNum, storeName, metrics)
  - [ ] `store_detail_mapper_test.dart`: StoreDetail model → entity (transaction counts, timing)
  - [ ] `queue_item_mapper_test.dart`: QueueItem model → entity (customer, containers, status)
  - [ ] `completed_buy_mapper_test.dart`: CompletedBuy model → entity (totals, timestamps)
  - [ ] `buyer_stats_mapper_test.dart`: BuyerStats model → entity (performance metrics)
  - [ ] `workbook_comment_mapper_test.dart`: Comment model → entity (author, timestamp)
  - [ ] `task_group_mapper_test.dart`: TaskGroup model → entity (name, tasks list)
  - [ ] `workbook_task_list_mapper_test.dart`: TaskList model → entity (completion status, carryover)
  - [ ] All mappers handle null fields gracefully (default values, not crashes)
  - [ ] String-to-number conversions validated (API quirk: numbers as strings)

**Master Mapper List (11 total):**
| Mapper | Feature | Priority |
|--------|---------|----------|
| TodayPerformanceMapper | Feature 6 | Must Have |
| WorkbookNoteMapper | Feature 6 | Must Have |
| TaskMapper | Feature 6 | Must Have |
| StoreMapper | Feature 10 | Should Have |
| StoreDetailMapper | Feature 10 | Should Have |
| QueueItemMapper | Feature 10 | Should Have |
| CompletedBuyMapper | Feature 10 | Should Have |
| BuyerStatsMapper | Feature 10 | Should Have |
| WorkbookCommentMapper | Feature 10 | Should Have |
| TaskGroupMapper | Feature 10 | Should Have |
| WorkbookTaskListMapper | Feature 10 | Should Have |

### Could Have Features

#### Feature 11: Integration Tests for Critical Flows
- **User Story:** As a QA engineer, I want integration tests for critical user journeys so that end-to-end flows are validated.
- **Acceptance Criteria:**
  - [ ] `auth_flow_integration_test.dart`: Full authentication flow (install → validate → dashboard)
  - [ ] `store_navigation_integration_test.dart`: Store selection and sub-screen navigation
  - [ ] Permission-based access control validated in integration context
  - [ ] Tests run in < 2 minutes total

#### Feature 12: Coverage Reporting with Codecov
- **User Story:** As a tech lead, I want coverage trends tracked over time so that test quality can be monitored.
- **Acceptance Criteria:**
  - [ ] Codecov integration configured
  - [ ] Coverage badge added to README
  - [ ] PR comments show coverage diff
  - [ ] Historical coverage trends available

### Won't Have (This Phase)

- **Visual regression testing** (screenshot comparisons) - requires additional tooling setup
- **Performance/load testing** - out of scope for foundational testing
- **E2E device testing** (real device farms) - too complex for initial phase
- **Mutation testing** - advanced technique for later optimization
- **Contract testing for API** - requires backend coordination
- **Accessibility testing automation** - future enhancement after foundation is solid

## Detailed Feature Specifications

### Feature: Provider Unit Tests (Feature 5 - Most Complex)
**Description:** Testing Riverpod 3.x AsyncNotifier providers requires specialized patterns for handling async state, mock injection, and state verification. This is the most complex feature due to the async nature and Riverpod-specific testing requirements.

**User Flow:**
1. Developer identifies provider to test (e.g., `dashboardProvider`)
2. Developer creates test file in `test/unit/presentation/providers/`
3. Developer sets up `ProviderContainer` with mock repository overrides
4. Developer writes tests covering: loading state, success state, error state, refresh behavior
5. Developer runs `flutter test` to validate
6. CI/CD enforces tests pass before merge

**Business Rules:**
- Rule 1: All provider tests MUST use `ProviderContainer` with `overrides` for mock injection
- Rule 2: All provider tests MUST call `addTearDown(container.dispose)` to prevent memory leaks
- Rule 3: Async operations MUST use `await container.pump()` or `await Future<void>.value()` to complete
- Rule 4: State verification SHOULD use listener-based approach, not direct state checks
- Rule 5: Mock repositories MUST be created using Mocktail (`class MockDashboardRepository extends Mock implements DashboardRepository {}`)
- Rule 6: Dashboard provider auth error caching MUST respect 30-second throttle

**Edge Cases:**
- Scenario 1: Provider receives error from repository → Expected: State transitions to `AsyncError`, error is accessible
- Scenario 2: Multiple rapid refresh calls → Expected: Dashboard provider caches auth errors for 30s, prevents API spam
- Scenario 3: Provider disposed mid-request → Expected: No state update after disposal, no memory leaks
- Scenario 4: Empty response from API → Expected: State transitions to `AsyncData` with empty list, UI shows empty state
- Scenario 5: Network timeout → Expected: Error classified correctly, retry available if appropriate

## Success Metrics

### Key Performance Indicators

| Metric | Baseline | Target (Phase 1) | Stretch Goal |
|--------|----------|------------------|--------------|
| **Test Coverage** | 0% | 60% | 75% |
| **Test Count** | 1 test | 150+ tests | 250+ tests |
| **Test Execution Time** | N/A | < 60 seconds | < 30 seconds |
| **CI Pass Rate** | N/A | 95%+ | 99%+ |
| **Mean Time to Detect Bug** | Production | Development | Pre-commit |

- **Adoption:** 100% of new PRs include tests for changed code (enforced via CI)
- **Engagement:** Developers run tests locally before every commit (measured by developer survey)
- **Quality:** Zero regressions in tested code paths after test suite is established
- **Business Impact:** Reduced production bug reports by 50% within 3 months of implementation

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| CI Test Run | pass/fail, duration, coverage%, test_count | Track test suite health over time |
| Coverage Change | delta%, files_changed, lines_added | Monitor coverage trends on PRs |
| Test Failure | test_name, error_type, file_path | Identify flaky or problematic tests |
| PR Merge | has_tests, coverage_threshold_met | Enforce testing culture |
| Production Bug | had_test_coverage, test_gap_identified | Connect bugs to test gaps |

---

## Constraints and Assumptions

### Constraints
- **Technical Stack:** Tests must use Flutter's built-in testing framework with Mocktail (already in pubspec)
- **Platform Compatibility:** Tests must run on macOS, Linux, and Windows CI environments
- **Execution Time:** Full test suite must complete in under 2 minutes to maintain developer velocity
- **No External Dependencies:** Tests must not require network access, real APIs, or external services
- **Backward Compatibility:** Tests must work with current Flutter 3.38.3 / Dart 3.10.1 versions
- **Resource Constraints:** Implementation by existing development team without dedicated QA resources

### Assumptions
- Developers have basic familiarity with writing Dart tests
- GitHub Actions is available for CI/CD (or equivalent CI platform)
- Mocktail 1.0.3+ patterns are acceptable (no migration to Mockito needed)
- Existing code does not need significant refactoring to be testable (dependency injection already in place via Riverpod)
- API response structures are stable and documented in existing API documentation files

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| **Flaky tests** - Time-dependent tests fail intermittently | Medium | Medium | Mock `DateTime.now()` and all time-dependent operations; use deterministic test data |
| **Slow test execution** - Tests take too long, developers skip them | High | Medium | Set 2-minute max target; parallelize test execution; profile slow tests |
| **Incomplete mocking** - Tests pass but don't test real behavior | High | Medium | Code review test quality; ensure mocks match interface contracts; integration tests validate |
| **Test maintenance burden** - Tests break with every code change | Medium | Low | Write behavior-focused tests, not implementation-focused; avoid over-mocking |
| **Coverage gaming** - High coverage but poor test quality | Medium | Low | Enforce meaningful acceptance criteria beyond line coverage; mutation testing in future |
| **Provider testing complexity** - Riverpod 3.x patterns are unfamiliar | Medium | Medium | Provide example tests and templates; document patterns in TESTING_GUIDE.md |

## Open Questions

- [x] Which mocking library to use? → **Resolved: Mocktail (already in project, no code generation needed)**
- [x] What coverage threshold to enforce? → **Resolved: 60% initial, 75% stretch goal**
- [x] Where should test files live? → **Resolved: `test/unit/`, `test/widget/`, `test/integration/`**
- [x] Should we enforce coverage on PR diffs or total coverage? → **Decision: PR diff initially** (changed files must meet 60%; total coverage is advisory)
- [x] Who reviews test quality in PRs? → **Decision: All reviewers** verify test coverage; tech lead for architecture-level test decisions
- [x] Should we add pre-commit hooks for local test enforcement? → **Decision: Optional in Phase 1**, mandatory after 60% coverage achieved

## Problem-to-Feature Traceability

| Problem Statement Risk | Features That Address It |
|------------------------|--------------------------|
| **Regression bugs** (currency, date, permission logic) | Feature 2 (currency_utils), Feature 3 (permissions), Feature 6 (mappers) |
| **Business logic errors** (division by zero, access control) | Feature 3 (permission tests), Feature 4 (error handling), Feature 5 (provider tests) |
| **Integration failures** (API changes, auth handling) | Feature 5 (dashboard provider), Feature 7 (CI/CD), Feature 8 (interceptors) |
| **No safety net for refactoring** | All features provide regression protection |
| **Production bugs discovered by users** | Feature 7 (CI/CD) + Feature 11 (integration tests) catch before deploy |

---

## Supporting Research

### Competitive Analysis

| Standard | Our Status | Industry Best Practice |
|----------|------------|----------------------|
| Unit Test Coverage | 0% | 70-80% for business logic |
| Widget Test Coverage | 0% | 50-60% for UI components |
| Integration Test Coverage | 0% | 10-20% for critical flows |
| CI/CD Test Automation | None | 100% of PRs tested |
| Test Execution Time | N/A | < 5 minutes for full suite |

**Flutter ecosystem standards:**
- Most production Flutter apps target 60-80% coverage
- Mocktail is the preferred mocking library (no code generation)
- Riverpod testing uses `ProviderContainer` with overrides
- GoRouter testing typically mocks the router for unit/widget tests

### User Research

**Developer Pain Points (from analysis):**
- "I'm afraid to refactor because there are no tests"
- "PR reviews take longer because we manually verify edge cases"
- "Production bugs that could have been caught with simple unit tests"
- "New team members struggle to understand expected behavior without test documentation"

**Desired Outcomes:**
- "I want to know my changes don't break other features"
- "I want CI to catch issues before code review"
- "I want tests as documentation for complex business logic"

### Market Data

**Flutter Testing Adoption (2025):**
- 78% of professional Flutter teams use automated testing
- Average coverage for production Flutter apps: 65%
- Teams with 70%+ coverage report 40% fewer production bugs
- CI/CD adoption in Flutter projects: 85% (GitHub Actions most common)

**ROI of Testing:**
- Bug found in development: $100 to fix
- Bug found in QA: $1,000 to fix
- Bug found in production: $10,000+ to fix (including customer impact)

Sources: Flutter Developer Survey 2024, State of Mobile Development 2025
