# Test Coverage Analysis & Recommendations

**Document Version:** 1.0
**Date:** December 5, 2025
**Target:** 90% Code Coverage
**Scope:** BuyerKiosk Web Application

---

## Executive Summary

This document presents a comprehensive analysis of the current test coverage state for the BuyerKiosk application and provides a detailed roadmap for achieving 90% test coverage. The analysis reveals significant gaps in the current testing infrastructure, with only ~15% of modules having any test coverage. Achieving the target will require approximately **1,900-2,500 test cases** and **18-24 developer-weeks** of effort.

### Key Findings

| Metric | Current State | Target State |
|--------|--------------|--------------|
| Module Coverage | ~15% | 90% |
| Test Files | 37 | ~200 |
| Test Cases | ~400 (estimated) | ~2,200 |
| Lines of Test Code | ~19,311 | ~60,000+ |

### Investment Required

- **Duration:** 18-24 weeks (1 developer) or 9-12 weeks (2 developers)
- **Effort:** 4.5-6 FTE-months
- **Test Cases to Write:** ~1,800-2,100 new tests

---

## Table of Contents

1. [Current State Assessment](#1-current-state-assessment)
2. [Codebase Analysis](#2-codebase-analysis)
3. [Coverage Gap Analysis](#3-coverage-gap-analysis)
4. [Module-by-Module Requirements](#4-module-by-module-requirements)
5. [Implementation Roadmap](#5-implementation-roadmap)
6. [Infrastructure Requirements](#6-infrastructure-requirements)
7. [Risk Assessment](#7-risk-assessment)
8. [Recommendations](#8-recommendations)
9. [Appendices](#9-appendices)

---

## 1. Current State Assessment

### 1.1 Test Infrastructure

The project has a solid testing foundation in place:

- **Framework:** PHPUnit 12.x (modern, well-supported)
- **Configuration:** `userfrosting/phpunit.xml` properly configured
- **Bootstrap:** `userfrosting/tests/bootstrap.php` handles initialization
- **Base Classes:** `DatabaseTestCase.php` for database-dependent tests
- **Fixtures:** Established patterns in `Employee/Fixtures/` and `Workbook/Fixtures/`

### 1.2 Existing Test Structure

```
userfrosting/tests/
├── bootstrap.php           # Test initialization
├── DatabaseTestCase.php    # Base class for DB tests
├── Unit/
│   ├── ApiNewBuyTest.php
│   ├── BuyQueueTest.php
│   ├── AccessConditionExpressionTest.php
│   ├── KLoggerTest.php
│   ├── UserDatabaseTest.php
│   ├── Autoload/           # 3 autoload tests
│   └── ComebackCash/       # Comprehensive coverage
│       ├── Models/         # 3 model tests
│       ├── Services/       # 4 service tests
│       └── Controllers/    # 2 controller tests
├── Integration/
│   └── ComebackCash/       # 1 lifecycle test
├── Employee/               # Well-structured module tests
│   ├── Unit/               # 2 unit tests
│   └── Integration/        # 3 integration tests
├── Workbook/               # Good coverage
│   └── Unit/               # 11 unit tests
└── Task/                   # Task system tests
    └── Unit/               # 4 unit tests
```

### 1.3 Test Quality Assessment

**Strengths:**
- ComebackCash module demonstrates excellent test patterns
- Business rules documented in test comments
- Good use of mocking (PDO, services)
- Both unit and integration test layers
- Fixture-based test data management

**Example of Good Test Pattern (from ComebackCash):**
```php
/**
 * Business Rules:
 * - Rule 16: Buy-side has NO earning thresholds
 * - Rule 15: Sales-side earning thresholds calculated on net amount
 * - Rule 12: Coupons are bearer instruments
 */
class CouponServiceTest extends TestCase
{
    // Well-structured with setUp, helper methods, and focused tests
}
```

---

## 2. Codebase Analysis

### 2.1 Size Metrics

| Category | Files | Lines of Code |
|----------|-------|---------------|
| BuyerKiosk Source (`src/BuyerKiosk/`) | 252 | ~75,638 |
| Models (`models/`) | 15 | ~4,305 |
| Routes (`routes/`) | 49 | ~14,504 |
| **Total Testable Code** | **316** | **~94,447** |
| Existing Test Code | 37 | ~19,311 |

### 2.2 Module Distribution

| Module | Files | LOC (est.) | Complexity |
|--------|-------|------------|------------|
| Core | 69 | ~22,000 | HIGH |
| Backstock | 22 | ~6,200 | HIGH |
| Workbook | 24 | ~7,500 | MEDIUM |
| ComebackCash | 13 | ~4,000 | MEDIUM |
| Support | 12 | ~3,500 | MEDIUM |
| DigitalSign | 12 | ~3,200 | MEDIUM |
| Cash | 9 | ~1,500 | MEDIUM |
| SMS | 8 | ~2,400 | MEDIUM |
| QuickBooks | 8 | ~2,800 | HIGH |
| FiveStars | 8 | ~2,200 | MEDIUM |
| SellerMarketing | 8 | ~2,500 | MEDIUM |
| Employee | 7 | ~2,000 | LOW |
| ResalePerks | 7 | ~1,800 | LOW |
| Other (18 modules) | 45 | ~12,000 | LOW-MEDIUM |

### 2.3 Complexity Hotspots

The following files have been identified as high-complexity and critical for testing:

| File | Module | LOC | Reason |
|------|--------|-----|--------|
| `EventService.php` | Backstock | 1,325 | Complex event lifecycle, alerts, recommendations |
| `ReportService.php` | Backstock | 1,056 | Aggregations, calculations, exports |
| `Store.php` | Core | ~800 | 9+ integrations, feature flags, tokens |
| `BuyQueue.php` | Core | ~600 | Cross-DB queries, alert enrichment |
| `BaseModel.php` | Models | ~1,200 | Core utilities, DB connections |

---

## 3. Coverage Gap Analysis

### 3.1 Modules WITH Test Coverage

| Module | Source Files | Test Files | Coverage Level | Quality |
|--------|-------------|------------|----------------|---------|
| ComebackCash | 13 | 11 | HIGH (~85%) | Excellent |
| Workbook | 24 | 11 | GOOD (~60%) | Good |
| Employee | 7 | 5 | HIGH (~80%) | Good |
| Core (partial) | 69 | 6 | LOW (~10%) | Mixed |

### 3.2 Modules WITHOUT Test Coverage

| Module | Source Files | Business Criticality | Risk Level |
|--------|-------------|---------------------|------------|
| **Backstock** | 22 | HIGH (inventory mgmt) | CRITICAL |
| **Core** (most) | ~60 | CRITICAL (domain logic) | CRITICAL |
| **SMS** | 8 | HIGH (customer comms) | HIGH |
| **Cash** | 9 | HIGH (financial) | HIGH |
| **QuickBooks** | 8 | HIGH (accounting) | HIGH |
| **FiveStars** | 8 | MEDIUM (loyalty) | MEDIUM |
| **Support** | 12 | MEDIUM (help desk) | MEDIUM |
| **DigitalSign** | 12 | LOW (display) | LOW |
| **SellerMarketing** | 8 | MEDIUM (marketing) | MEDIUM |
| **All Others** | ~85 | VARIES | VARIES |

### 3.3 Coverage by Business Function

| Business Function | Current Coverage | Risk |
|-------------------|-----------------|------|
| Multi-Store Operations | ~5% | CRITICAL |
| Transaction Processing (Buy) | ~15% | CRITICAL |
| Customer Management | ~10% | HIGH |
| Inventory (Backstock) | 0% | CRITICAL |
| Cash Management | 0% | HIGH |
| SMS/Communications | 0% | HIGH |
| Integrations (QB, FS) | 0% | HIGH |
| Reporting/Analytics | ~5% | MEDIUM |
| User Authentication | ~20% | HIGH |

---

## 4. Module-by-Module Requirements

### 4.1 TIER 1: Critical Priority (Weeks 1-15)

#### 4.1.1 Core Module

**Scope:** 69 files, ~500-700 tests needed

**Key Components:**

| Component | Tests Needed | Complexity | Priority |
|-----------|-------------|------------|----------|
| Store Entity | 22-25 | HIGH | P0 |
| Buy Entity | 18-22 | HIGH | P0 |
| Customer Entity | 14-16 | MEDIUM | P0 |
| BuyQueue + QueueItem | 28-34 | HIGH | P0 |
| Employee + Alert | 18-22 | LOW | P1 |
| Loyalty System (11 files) | 60-80 | MEDIUM | P1 |
| Robot Automation (4 files) | 25-35 | MEDIUM | P1 |
| Controllers (8 files) | 100-150 | MEDIUM-HIGH | P2 |
| Reports/Stats (15+ files) | 60-90 | LOW | P2 |

**Critical Test Scenarios:**
- Multi-store database switching
- TypeNum pattern validation (`[a-z][a-z]\d+`)
- Cross-store recent buy detection
- Token refresh workflows (QB, WIW, CC)
- Permission and access control
- Timezone conversions

#### 4.1.2 Backstock Module

**Scope:** 22 files, ~262 tests needed

**Key Components:**

| Component | Tests Needed | Complexity | Priority |
|-----------|-------------|------------|----------|
| EventService | 50 | CRITICAL | P0 |
| ReportService | 35 | HIGH | P0 |
| BackstockFactory | 27 | HIGH | P0 |
| Bin Entity | 20 | HIGH | P1 |
| Note Entity | 22 | MEDIUM | P1 |
| BinNamingService | 22 | MEDIUM | P1 |
| Event Models (4 files) | 54 | MEDIUM | P1 |
| Action/Category/Location | 28 | LOW | P2 |
| Controllers | 8 | LOW | P2 |

**Critical Test Scenarios:**
- Event phase calculations (5 phases)
- Bin age color mapping
- Alert generation and deduplication
- Bulk bin creation with transactions
- Report aggregations and CSV export
- Season detection from categories

#### 4.1.3 SMS Module

**Scope:** 8 files, ~90 tests needed

**Key Components:**

| Component | Tests Needed | Complexity | Priority |
|-----------|-------------|------------|----------|
| TextMessageService | 28 | HIGH | P0 |
| TwilioTextSender | 12 | MEDIUM | P0 |
| VonageTextSender | 14 | HIGH | P0 |
| FloodProtector | 12 | MEDIUM | P1 |
| Legacy Twilio/Vonage | 16 | MEDIUM | P2 |
| BuySMSController | 8 | LOW | P2 |

**Critical Test Scenarios:**
- Phone validation (10-digit)
- Flood protection rate limiting
- Provider selection and fallback
- Message building with customer data
- Do-not-text list checking
- Webhook URL construction

#### 4.1.4 Cash Module

**Scope:** 9 files, ~160 tests needed

**Key Components:**

| Component | Tests Needed | Complexity | Priority |
|-----------|-------------|------------|----------|
| CashActivity | 40 | MEDIUM | P0 |
| CashActivityRepository | 22 | MEDIUM-HIGH | P0 |
| SafeLevelAlert | 22 | MEDIUM-HIGH | P0 |
| CashBalancer | 12 | LOW-MEDIUM | P1 |
| SafeConfiguration + Repo | 33 | MEDIUM | P1 |
| Controllers | 30 | MEDIUM | P2 |

**Critical Test Scenarios:**
- Denomination validation (coins, bills, rolls)
- Variance calculations
- Alert threshold logic
- Safe balance calculations
- Transaction type filtering

### 4.2 TIER 2: High Priority (Weeks 16-20)

| Module | Files | Tests | Key Focus Areas |
|--------|-------|-------|-----------------|
| Support | 12 | 80-100 | Ticket lifecycle, KB articles |
| QuickBooks | 8 | 60-80 | OAuth, sync, error handling |
| FiveStars | 8 | 50-70 | API integration, rewards |
| DigitalSign | 12 | 70-90 | Display rendering, scheduling |
| SellerMarketing | 8 | 50-70 | Campaign management, SMS |
| ResalePerks | 7 | 45-60 | Points, redemption |

### 4.3 TIER 3: Standard Priority (Weeks 21-24)

| Module | Files | Tests | Notes |
|--------|-------|-------|-------|
| Sales | 4 | 25-35 | Sales reporting |
| DailyReport | 4 | 30-40 | Daily summaries |
| CustomerSurvey | 4 | 25-35 | Survey system |
| UserEmployee | 5 | 30-40 | User-employee linking |
| WhenIWork | 3 | 20-30 | Scheduling integration |
| Shopify | 2 | 15-25 | E-commerce sync |
| SimpleQueue | 3 | 20-30 | Basic queue |
| ServiceQueue | 3 | 20-30 | Service queue |
| ConstantContact | 2 | 15-25 | Email marketing |
| Billing | 3 | 20-30 | Subscription billing |
| Other modules | 22 | 100-150 | Various utilities |

---

## 5. Implementation Roadmap

### 5.1 Phase Overview

```
Phase 1 (Weeks 1-8):    Core Domain Foundation
Phase 2 (Weeks 9-12):   Backstock Complete Coverage
Phase 3 (Weeks 13-15):  Communication & Cash
Phase 4 (Weeks 16-20):  Integrations
Phase 5 (Weeks 21-24):  Remaining Modules & Routes
```

### 5.2 Detailed Timeline

#### Phase 1: Core Domain Foundation (Weeks 1-8)

**Week 1-2: Store & Buy Entities**
- Store entity tests (25 tests)
- Buy entity tests (22 tests)
- Database mocking infrastructure
- Test fixtures for stores and buys

**Week 3-4: Queue & Customer**
- BuyQueue tests (24 tests)
- QueueItem tests (10 tests)
- Customer entity tests (16 tests)
- Cross-store query testing

**Week 5-6: Supporting Entities**
- Employee tests (10 tests)
- Alert tests (12 tests)
- Loyalty system tests (40 tests)

**Week 7-8: Core Business Logic**
- Remaining Loyalty tests (40 tests)
- Robot automation tests (35 tests)
- ShiftNotes tests (14 tests)
- Security classes tests (16 tests)

**Deliverable:** ~264 tests, Core entities fully covered

#### Phase 2: Backstock Complete Coverage (Weeks 9-12)

**Week 9-10: Critical Services**
- EventService tests (50 tests)
- ReportService tests (35 tests)
- BackstockFactory tests (27 tests)

**Week 11-12: Models & Utilities**
- Bin entity tests (20 tests)
- Note entity tests (22 tests)
- BinNamingService tests (22 tests)
- Event models tests (54 tests)
- Remaining tests (32 tests)

**Deliverable:** ~262 tests, Backstock fully covered

#### Phase 3: Communication & Cash (Weeks 13-15)

**Week 13: SMS Module**
- TextMessageService tests (28 tests)
- Provider tests (26 tests)
- FloodProtector tests (12 tests)
- Controller tests (8 tests)
- Legacy tests (16 tests)

**Week 14-15: Cash Module**
- CashActivity tests (40 tests)
- Repository tests (22 tests)
- SafeLevelAlert tests (22 tests)
- CashBalancer tests (12 tests)
- Configuration tests (33 tests)
- Controller tests (30 tests)

**Deliverable:** ~250 tests, SMS & Cash fully covered

#### Phase 4: Integrations (Weeks 16-20)

**Week 16-17: QuickBooks & FiveStars**
- QuickBooks OAuth tests (20 tests)
- QuickBooks sync tests (40 tests)
- QuickBooks error handling (20 tests)
- FiveStars API tests (35 tests)
- FiveStars rewards tests (35 tests)

**Week 18-20: Support & Digital**
- Support ticket tests (50 tests)
- Support KB tests (50 tests)
- DigitalSign tests (90 tests)
- SellerMarketing tests (70 tests)
- ResalePerks tests (60 tests)

**Deliverable:** ~470 tests, Integrations covered

#### Phase 5: Remaining Modules (Weeks 21-24)

**Week 21-22: Tier 3 Modules**
- Sales, DailyReport, CustomerSurvey (90 tests)
- UserEmployee, WhenIWork, Shopify (75 tests)
- SimpleQueue, ServiceQueue (50 tests)
- ConstantContact, Billing (45 tests)

**Week 23-24: Routes & Final**
- Route API tests (200 tests)
- BaseModel tests (60 tests)
- Gap coverage and cleanup (100 tests)

**Deliverable:** ~620 tests, 90% coverage achieved

### 5.3 Milestone Summary

| Milestone | Week | Cumulative Tests | Coverage |
|-----------|------|------------------|----------|
| M1: Core Foundation | 8 | ~264 | ~35% |
| M2: Backstock Complete | 12 | ~526 | ~50% |
| M3: SMS & Cash | 15 | ~776 | ~60% |
| M4: Integrations | 20 | ~1,246 | ~75% |
| M5: Full Coverage | 24 | ~1,866 | ~90% |

---

## 6. Infrastructure Requirements

### 6.1 Mocking Strategy

#### Critical Mocks Required

**Database Layer:**
```php
// PDO and PDOStatement mocks
$pdoMock = $this->createMock(PDO::class);
$stmtMock = $this->createMock(PDOStatement::class);
$pdoMock->method('prepare')->willReturn($stmtMock);
```

**Global Functions:**
```php
// Functions requiring mocking or abstraction:
- dbConnectByName($dbName)      // Database connection
- getCurrentDateRange()          // Date utilities
- getStoreType($store)          // Store type detection
- getEmployeeNameArray()        // Employee lookups
- gen_uuid()                    // UUID generation
- sendEncodedData()             // Background job triggers
- secondsToReadable()           // Time formatting
```

**External Services:**
```php
// Twilio
$twilioMock = $this->createMock(\Twilio\Rest\Client::class);

// cURL functions (for Vonage)
// Consider wrapper class for testability

// QuickBooks SDK
$qbMock = $this->createMock(\QuickBooksOnline\API\DataService\DataService::class);

// Redis
$redisMock = $this->createMock(\Predis\Client::class);
```

**Framework Objects:**
```php
// Slim Framework
$appMock = $this->createMock(\Slim\Slim::class);
$appMock->user = (object)['id' => 1, 'checkAccess' => fn() => true];
```

### 6.2 Recommended Directory Structure

```
userfrosting/tests/
├── bootstrap.php
├── DatabaseTestCase.php
├── TestCase.php                    # Base test case with common setup
│
├── Fixtures/
│   ├── StoreFixtures.php          # Store test data
│   ├── CustomerFixtures.php       # Customer test data
│   ├── BuyQueueFixtures.php       # Queue test data
│   ├── BackstockFixtures.php      # Backstock test data
│   ├── CashFixtures.php           # Cash test data
│   └── SMSFixtures.php            # SMS test data
│
├── Mocks/
│   ├── DatabaseMock.php           # PDO mock utilities
│   ├── StoreMock.php              # Store object mocks
│   ├── TwilioMock.php             # Twilio SDK mock
│   ├── VonageMock.php             # Vonage/cURL mock
│   ├── RedisMock.php              # Redis mock
│   └── GlobalFunctionMock.php     # Global function stubs
│
├── Unit/
│   ├── Core/
│   │   ├── StoreTest.php
│   │   ├── BuyTest.php
│   │   ├── CustomerTest.php
│   │   ├── BuyQueueTest.php
│   │   ├── Loyalty/
│   │   ├── Robot/
│   │   └── Controllers/
│   ├── Backstock/
│   │   ├── BinTest.php
│   │   ├── EventServiceTest.php
│   │   ├── ReportServiceTest.php
│   │   └── ...
│   ├── SMS/
│   │   ├── TextMessageServiceTest.php
│   │   ├── TwilioTextSenderTest.php
│   │   ├── VonageTextSenderTest.php
│   │   └── FloodProtectorTest.php
│   ├── Cash/
│   │   ├── CashActivityTest.php
│   │   ├── CashBalancerTest.php
│   │   └── SafeLevelAlertTest.php
│   └── ... (other modules)
│
├── Integration/
│   ├── Core/
│   ├── Backstock/
│   ├── SMS/
│   └── Cash/
│
└── Functional/
    └── API/
        ├── BuyApiTest.php
        ├── BackstockApiTest.php
        └── ...
```

### 6.3 Test Data Strategy

**Fixtures Pattern:**
```php
class StoreFixtures
{
    public static function createTestStore(array $overrides = []): Store
    {
        $defaults = [
            'id' => 1,
            'typeNum' => 'ou00',
            'companyName' => 'Test Store',
            'timeZone' => 'America/Chicago',
            // ... other defaults
        ];

        return Store::fromArray(array_merge($defaults, $overrides));
    }

    public static function createMultiStoreSet(): array
    {
        return [
            self::createTestStore(['typeNum' => 'ou00']),
            self::createTestStore(['typeNum' => 'pa00', 'id' => 2]),
            self::createTestStore(['typeNum' => 'ny01', 'id' => 3]),
        ];
    }
}
```

**Database Seeding:**
```php
trait DatabaseSeeding
{
    protected function seedTestDatabase(): void
    {
        // Use transactions for test isolation
        $this->db->beginTransaction();

        // Seed required lookup tables
        $this->seedEmployees();
        $this->seedCategories();
        $this->seedLocations();
    }

    protected function tearDownDatabase(): void
    {
        $this->db->rollBack();
    }
}
```

### 6.4 CI/CD Integration

**GitHub Actions Workflow:**
```yaml
name: Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    services:
      mysql:
        image: mysql:8.0
        env:
          MYSQL_ROOT_PASSWORD: test
          MYSQL_DATABASE: buyerkiosk_test
        ports:
          - 3306:3306

      redis:
        image: redis:6
        ports:
          - 6379:6379

    steps:
      - uses: actions/checkout@v3

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          extensions: pdo_mysql, redis
          coverage: xdebug

      - name: Install Dependencies
        run: cd userfrosting && composer install

      - name: Run Tests
        run: ./test.sh
        env:
          DB_HOST: 127.0.0.1
          DB_DATABASE: buyerkiosk_test
          DB_USERNAME: root
          DB_PASSWORD: test

      - name: Upload Coverage
        uses: codecov/codecov-action@v3
```

---

## 7. Risk Assessment

### 7.1 Technical Risks

| Risk | Likelihood | Impact | Mitigation |
|------|------------|--------|------------|
| Global function dependencies | HIGH | MEDIUM | Create wrapper classes, use dependency injection |
| Database coupling | HIGH | HIGH | Implement repository pattern, use mocks |
| External API dependencies | MEDIUM | MEDIUM | Mock external services, use VCR patterns |
| Legacy code complexity | MEDIUM | HIGH | Incremental refactoring alongside testing |
| Test environment parity | MEDIUM | MEDIUM | Containerized test environment |

### 7.2 Process Risks

| Risk | Likelihood | Impact | Mitigation |
|------|------------|--------|------------|
| Scope creep | MEDIUM | HIGH | Strict prioritization, time-boxing |
| Developer availability | MEDIUM | HIGH | Cross-training, documentation |
| Changing requirements | LOW | MEDIUM | Modular test design |
| Test maintenance burden | MEDIUM | MEDIUM | Clean test patterns, avoid over-mocking |

### 7.3 Business Risks

| Risk | Likelihood | Impact | Mitigation |
|------|------------|--------|------------|
| Slowed feature development | MEDIUM | MEDIUM | Parallel testing effort, TDD for new features |
| False confidence | LOW | HIGH | Focus on meaningful tests, avoid coverage gaming |
| ROI not realized | LOW | MEDIUM | Track defect metrics, demonstrate value |

---

## 8. Recommendations

### 8.1 Strategic Recommendations

#### R1: Adopt Test-Driven Development (TDD) for New Features
- **Rationale:** Prevents test debt accumulation
- **Action:** Require tests for all new PRs
- **Metric:** 100% coverage on new code

#### R2: Prioritize Business-Critical Modules First
- **Rationale:** Maximize risk reduction early
- **Action:** Follow Tier 1 priority order (Core, Backstock, SMS, Cash)
- **Metric:** Critical modules at 90% by Week 15

#### R3: Invest in Test Infrastructure Early
- **Rationale:** Speeds subsequent test development
- **Action:** Build mocking utilities in Week 1
- **Metric:** All mocks available by end of Week 2

#### R4: Establish Coverage Gates
- **Rationale:** Prevent coverage regression
- **Action:** Configure CI to fail below threshold
- **Metric:** No PR merges below 80% coverage for changed files

### 8.2 Tactical Recommendations

#### R5: Start with Highest-Complexity Files
- Focus on `EventService.php` (1,325 LOC), `ReportService.php` (1,056 LOC)
- These represent significant risk and testing ROI

#### R6: Use Integration Tests for Complex Workflows
- Event lifecycle (create → progress → alerts → complete)
- Buy queue flow (enter → sort → process → complete)
- Cash reconciliation workflow

#### R7: Document Business Rules in Tests
- Follow ComebackCash test pattern
- Tests become living documentation

#### R8: Create Reusable Test Utilities
- `MockBuilder` for common mocks
- `AssertHelper` for complex assertions
- `FixtureLoader` for test data

### 8.3 Team Recommendations

#### R9: Assign Dedicated Test Champion
- **Rationale:** Ensures consistent quality and patterns
- **Action:** Designate senior developer for test architecture decisions
- **Responsibility:** Review test PRs, maintain infrastructure

#### R10: Conduct Test Review Sessions
- **Rationale:** Knowledge sharing, quality assurance
- **Action:** Weekly test code reviews
- **Outcome:** Consistent patterns across team

#### R11: Track Progress Visibly
- **Rationale:** Motivation, stakeholder visibility
- **Action:** Coverage dashboard, weekly reports
- **Tools:** Codecov, GitHub Actions badges

---

## 9. Appendices

### Appendix A: Test Case Estimates by Module

| Module | Unit Tests | Integration Tests | Total |
|--------|------------|-------------------|-------|
| Core | 400-500 | 100-150 | 500-650 |
| Backstock | 200-240 | 40-60 | 240-300 |
| SMS | 70-80 | 15-20 | 85-100 |
| Cash | 130-150 | 25-35 | 155-185 |
| Support | 65-80 | 15-25 | 80-105 |
| QuickBooks | 50-65 | 15-20 | 65-85 |
| FiveStars | 40-55 | 10-15 | 50-70 |
| DigitalSign | 55-70 | 15-20 | 70-90 |
| SellerMarketing | 40-55 | 10-15 | 50-70 |
| ResalePerks | 35-50 | 10-15 | 45-65 |
| Other Modules | 250-350 | 50-80 | 300-430 |
| Routes/API | - | 200-300 | 200-300 |
| **TOTAL** | **1,335-1,695** | **505-755** | **1,840-2,450** |

### Appendix B: Complexity Scoring Criteria

**HIGH Complexity:**
- > 500 LOC
- 5+ external dependencies
- Complex state machines
- Cross-database operations
- Financial calculations

**MEDIUM Complexity:**
- 200-500 LOC
- 2-4 external dependencies
- Multiple code paths
- Database operations

**LOW Complexity:**
- < 200 LOC
- 0-1 external dependencies
- Simple CRUD
- Minimal branching

### Appendix C: Coverage Metrics Definitions

- **Line Coverage:** Percentage of code lines executed during tests
- **Branch Coverage:** Percentage of decision branches (if/else) tested
- **Method Coverage:** Percentage of methods called during tests
- **Class Coverage:** Percentage of classes instantiated during tests

**Target Metrics:**
- Line Coverage: ≥ 90%
- Branch Coverage: ≥ 85%
- Method Coverage: ≥ 90%
- Class Coverage: ≥ 95%

### Appendix D: Test Pattern Examples

**Unit Test Pattern:**
```php
class StoreTest extends TestCase
{
    private Store $store;
    private MockObject $dbMock;

    protected function setUp(): void
    {
        parent::setUp();
        $this->dbMock = $this->createMock(PDO::class);
        $this->store = new Store();
    }

    public function testGetCompanyNameReturnsConfiguredName(): void
    {
        $this->store->setCompanyName('Test Company');
        $this->assertEquals('Test Company', $this->store->getCompanyName());
    }

    public function testCreateStoreLoadsFromDatabase(): void
    {
        // Arrange
        $this->setupDatabaseMock(['id' => 1, 'typeNum' => 'ou00']);

        // Act
        $store = $this->store->createStore(1);

        // Assert
        $this->assertEquals('ou00', $store->getTypeNum());
    }
}
```

**Integration Test Pattern:**
```php
class BuyQueueIntegrationTest extends DatabaseTestCase
{
    public function testQueueItemsIncludeRecentBuysFromOtherStores(): void
    {
        // Arrange: Create buys across multiple stores
        $this->seedStore('ou00');
        $this->seedStore('pa00');
        $this->createBuy('ou00', $this->testCustomer);
        $this->createBuy('pa00', $this->testCustomer);

        // Act: Load queue for ou00
        $queue = new BuyQueue('ou00');
        $items = $queue->getAllCurrentQueueItems($this->db);

        // Assert: Recent buy from pa00 should be detected
        $this->assertNotEmpty($items[0]->getRecentBuys());
    }
}
```

---

## Document Control

| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2025-12-05 | Claude Code Analysis | Initial document |

---

**End of Document**
