# Implementation Plan

## Validation Checklist

- [x] All specification file paths are correct and exist
- [x] Context priming section is complete
- [x] All implementation phases are defined
- [x] Each phase follows TDD: Prime → Test → Implement → Validate
- [x] Dependencies between phases are clear (no circular dependencies)
- [x] Parallel work is properly tagged with `[parallel: true]`
- [x] Activity hints provided for specialist selection `[activity: type]`
- [x] Every phase references relevant SDD sections
- [x] Every test references PRD acceptance criteria
- [x] Integration & E2E tests defined in final phase
- [x] Project commands match actual project setup
- [x] A developer could follow this plan independently

---

## Specification Compliance Guidelines

### How to Ensure Specification Adherence

1. **Before Each Phase**: Complete the Pre-Implementation Specification Gate
2. **During Implementation**: Reference specific SDD sections in each task
3. **After Each Task**: Run Specification Compliance checks
4. **Phase Completion**: Verify all specification requirements are met

### Deviation Protocol

If implementation cannot follow specification exactly:
1. Document the deviation and reason
2. Get approval before proceeding
3. Update SDD if the deviation is an improvement
4. Never deviate without documentation

## Metadata Reference

- `[parallel: true]` - Tasks that can run concurrently
- `[component: component-name]` - For multi-component features
- `[ref: document/section; lines: 1, 2-3]` - Links to specifications, patterns, or interfaces and (if applicable) line(s)
- `[activity: type]` - Activity hint for specialist agent selection

---

## Context Priming

*GATE: You MUST fully read all files mentioned in this section before starting any implementation.*

**Specification**:

- `docs/specs/022-admin-reporting-refresh/product-requirements.md` - Product Requirements (10 features across MoSCoW)
- `docs/specs/022-admin-reporting-refresh/solution-design.md` - Solution Design (5 ADRs confirmed)

**Source Analysis Documents**:

- `docs/analytics/analytics-enhancement-report.md` - Discovery analysis with data insights
- `docs/analytics/report-recommendations.md` - Prioritized recommendations
- `docs/analytics/velocity-macd-specification.md` - Detailed MACD algorithm spec

**Key Design Decisions** (from SDD ADRs):

- **ADR-1**: Pre-aggregation via TaskEngine jobs for sub-second queries
- **ADR-2**: Store-level analysis first (no category breakdown until POS data fixed)
- **ADR-3**: Syncfusion EJ2 for visualization (native MACD/stock charts, heat maps, DataGrid)
- **ADR-4**: Central kiosk_sales storage for MACD; per-store for velocity
- **ADR-5**: 60-second Redis cache TTL (balance freshness and performance)

**Implementation Context**:

- Commands to run:
  ```bash
  ./test.sh                              # Run all tests
  ./test.sh --testsuite unit             # Unit tests only
  ./test.sh --coverage                   # With coverage report
  php userfrosting/conductor run         # Run migrations
  php userfrosting/conductor build-css --minify  # Build CSS
  cd userfrosting && ./vendor/bin/phpstan analyse src/BuyerKiosk/Analytics/
  ```
- Patterns to follow:
  - `userfrosting/src/BuyerKiosk/Workbook/KPIService.php` - Multi-source KPI aggregation with caching
  - `userfrosting/src/BuyerKiosk/EventManagement/Controllers/EventReportController.php` - Multi-metric report with YoY comparison
  - `userfrosting/src/BuyerKiosk/TaskEngine/Jobs/AggregateStatsJob.php` - Daily aggregation job pattern
  - `userfrosting/migrations/input/20251202_001_store_stats_aggregate.json` - Migration JSON pattern
- Interfaces to implement: See SDD "Interface Specifications" section for all API contracts

**Performance Targets**:

- Dashboard load: < 2 seconds
- API response (cached): < 200ms
- API response (uncached): < 1 second
- Daily aggregation job: < 5 minutes per store

---

## Implementation Phases

### Phase Dependencies

```
Phase 1 (Foundation) ──► Phase 2 (Velocity) ──► Phase 4 (Retention)
                    └──► Phase 3 (Momentum) ──► Phase 4
                                               ↓
                                          Phase 5 (Integration)
```

- Phase 1 must complete before Phase 2 or 3 (provides infrastructure)
- Phase 2 and Phase 3 can run in parallel after Phase 1
- Phase 4 depends on Phase 1 foundation
- Phase 5 runs after all feature phases complete

---

- [x] **T1 Phase 1: Foundation Infrastructure** - Database tables, core services, base controllers, route setup ✅ COMPLETED 2024-12-30 (includes Codex review improvements)

    - [x] T1.1 Prime Context
        - [x] T1.1.1 Read SDD "Data Storage Changes" section for table schemas `[ref: SDD/Interface Specifications; lines: 378-438]`
        - [x] T1.1.2 Read SDD "Directory Map" for file structure `[ref: SDD/Building Block View; lines: 315-371]`
        - [x] T1.1.3 Review existing migration pattern `[ref: userfrosting/migrations/input/20251202_001_store_stats_aggregate.json]`
        - [x] T1.1.4 Review existing job pattern `[ref: userfrosting/src/BuyerKiosk/TaskEngine/Jobs/AggregateStatsJob.php]`

    - [x] T1.2 Write Tests - Database & Repository Layer
        - [x] T1.2.1 Test VelocityRepository::fetchDistribution returns correct bucket structure `[ref: PRD/Feature 1; lines: 127-137]` `[activity: backend-test]`
        - [x] T1.2.2 Test VelocityRepository handles empty date ranges gracefully `[ref: PRD/Edge Cases; lines: 254-258]` `[activity: backend-test]`
        - [x] T1.2.3 Test MomentumRepository::fetchCategoryData returns valid MACD structure `[ref: PRD/Feature 3; lines: 148-156]` `[activity: backend-test]`
        - [x] T1.2.4 Test RetentionRepository::fetchCohorts returns seller cohort data `[ref: PRD/Feature 4; lines: 158-166]` `[activity: backend-test]`

    - [x] T1.3 Implement Database Migrations `[activity: backend-db]`
        - [x] T1.3.1 Create migration: `20251230_001_analytics_velocity.json` for `analytics_item_velocity` and `analytics_velocity_daily` tables `[ref: SDD; lines: 379-405]`
        - [x] T1.3.2 Create migration: `20251230_002_analytics_momentum.json` for `analytics_category_momentum` table in central DB `[ref: SDD; lines: 406-420]`
        - [x] T1.3.3 Create migration: `20251230_003_analytics_retention.json` for `analytics_seller_cohorts` table `[ref: SDD; lines: 421-437]`
        - [x] T1.3.4 Run migrations on dev environment: `php userfrosting/conductor run` (13 operations across 5 databases)

    - [x] T1.4 Implement Repository Classes `[activity: backend-api]`
        - [x] T1.4.1 Create `BuyerKiosk\Analytics\Repositories\VelocityRepository.php` with fetchDistribution, fetchTrend methods `[ref: SDD; lines: 327-328]`
        - [x] T1.4.2 Create `BuyerKiosk\Analytics\Repositories\MomentumRepository.php` with fetchCategoryData, fetchHeatmapData methods `[ref: SDD; lines: 328]`
        - [x] T1.4.3 Create `BuyerKiosk\Analytics\Repositories\RetentionRepository.php` with fetchCohorts, fetchOverview methods `[ref: SDD; lines: 329]`

    - [x] T1.5 Implement Base Controllers & Routes `[activity: backend-api]`
        - [x] T1.5.1 Create `BuyerKiosk\Analytics\Controllers\AnalyticsPageController.php` with store access validation `[ref: SDD; lines: 319]`
        - [x] T1.5.2 Create `BuyerKiosk\Analytics\Controllers\AnalyticsApiController.php` with JSON response patterns `[ref: SDD; lines: 320]`
        - [x] T1.5.3 Create route file `userfrosting/routes/analytics/pages.php` for admin pages `[ref: SDD; lines: 339-340]`
        - [x] T1.5.4 Create route file `userfrosting/routes/analytics/api.php` for API endpoints `[ref: SDD; lines: 340]`
        - [x] T1.5.5 Register routes in main application bootstrap

    - [x] T1.6 Implement Entity Models `[activity: backend-api]`
        - [x] T1.6.1 Create `BuyerKiosk\Analytics\Models\VelocityBucket.php` entity `[ref: SDD; lines: 573-585]`
        - [x] T1.6.2 Create `BuyerKiosk\Analytics\Models\MomentumSignal.php` entity `[ref: SDD; lines: 587-608]`
        - [x] T1.6.3 Create `BuyerKiosk\Analytics\Models\SellerCohort.php` entity `[ref: SDD; lines: 610-620]`

    - [x] T1.7 Validate Phase 1 ✅
        - [x] T1.7.1 Run repository unit tests: `./test.sh --testsuite unit --filter Analytics` → 57 tests, 249 assertions, ALL PASS `[activity: run-tests]`
        - [x] T1.7.2 Verify migrations create correct table structures: 4 tables across 5 DBs `[activity: backend-db]`
        - [x] T1.7.3 Verify routes are accessible (return 200/401 appropriately) `[activity: backend-api]`
        - [x] T1.7.4 Run PHPStan on new code: `./vendor/bin/phpstan analyse src/BuyerKiosk/Analytics/` → [OK] No errors `[activity: lint-code]`
        - [x] T1.7.5 Verify all T1.2 tests pass `[activity: run-tests]`

    - [x] T1.8 Codex Code Review & Improvements ✅ (Added post-Phase 1)
        - [x] T1.8.1 **HIGH**: Add explicit typeNum validation in routes (don't rely on route conditions)
            - Routes now use `preg_match('/^[a-z]{2}\d+$/', $typeNum)` for explicit validation
        - [x] T1.8.2 **HIGH**: Add `checkAccess('uri_dashboard')` permission check before `checkStoreGroup()`
            - Both page and API routes now check dashboard permission
        - [x] T1.8.3 **MEDIUM**: Fix velocity distribution "average of averages" → weighted averages
            - `VelocityRepository::fetchDistribution()` now uses `SUM(totalMargin)/SUM(itemCount)` for statistically correct averages
        - [x] T1.8.4 **MEDIUM**: Optimize retention overview query (was using correlated subqueries)
            - `RetentionRepository::fetchOverview()` rewritten as set-based JOIN, index-friendly
        - [x] T1.8.5 **MEDIUM**: Add consistent date validation to retention endpoints
            - Added `isValidDate()` + `startDate <= endDate` checks to `getRetentionOverview`, `getRetentionCohorts`
        - [x] T1.8.6 **MEDIUM**: Standardize JSON error responses with proper headers
            - All errors now set `Content-Type: application/json` and return `{success: false, error: ...}`
        - [x] T1.8.7 **LOW**: Clamp days parameter in `getMomentumCrossovers` (1-90)
        - [x] T1.8.8 **LOW**: Add category validation in `getMomentumDetail` (non-empty, max 100 chars)
        - [x] T1.8.9 **LOW**: Add bucket validation in `VelocityBucket` constructor
        - [x] T1.8.10 **LOW**: Add signal/crossover validation in `MomentumSignal` constructor
        - [x] T1.8.11 Re-run tests and PHPStan → 57 tests passing, [OK] No errors

### Phase 1 Review Summary ✅

**Date Completed**: 2024-12-30

**Review Method**: Codex MCP code review (T1.8) + secondary review

**Findings Summary**:
| Priority | Count | Status |
|----------|-------|--------|
| Critical | 0 | N/A |
| High | 2 | ✅ Fixed (T1.8.1, T1.8.2) |
| Medium | 4 | ✅ Fixed (T1.8.3-T1.8.6) |
| Low | 4 | ✅ Fixed (T1.8.7-T1.8.10) |

**Secondary Review Findings** (2024-12-30):
- ✅ No additional critical or important issues found
- ℹ️ Minor: AnalyticsPageController duplicates access checks (routes already validate) - acceptable defensive coding
- ℹ️ Expected: Redis caching not implemented in repositories (deferred to Phase 2 VelocityService)
- ℹ️ Expected: Integration tests deferred to Phase 6

**Quality Metrics**:
- Unit Tests: 57 tests, 249 assertions, ALL PASS
- PHPStan: [OK] No errors
- Code Coverage: Repositories fully covered, Models covered

**Specification Changes During Phase 1**:
- ADR-3 updated: Chart.js → Syncfusion EJ2 Charts + DataGrid (license owned)

**Phase 1 Deliverables**:
- [x] 4 database migration files
- [x] 3 Repository classes
- [x] 3 Entity models
- [x] 2 Controller classes
- [x] 2 Route files
- [x] 3 Unit test classes

**Phase 2 Readiness**: ✅ CONFIRMED
- All blocking issues resolved
- Foundation infrastructure tested and working
- No dependencies on incomplete work

---

- [x] **T2 Phase 2: Velocity Dashboard** - PRD Features 1-3 (Must Have) `[parallel: true after T1]` ✅ BACKEND COMPLETE, FRONTEND COMBINED

    - [x] T2.1 Velocity Aggregation Job `[component: velocity-backend]` ✅ COMPLETED 2024-12-30

        - [x] T2.1.1 Prime Context
            - [x] T2.1.1.1 Read MACD algorithm specification `[ref: docs/analytics/velocity-macd-specification.md]`
            - [x] T2.1.1.2 Read SDD velocity aggregation example `[ref: SDD/Implementation Examples; lines: 757-843]`
            - [x] T2.1.1.3 Review existing AggregateStatsJob pattern `[ref: userfrosting/src/BuyerKiosk/TaskEngine/Jobs/AggregateStatsJob.php]`

        - [x] T2.1.2 Write Tests
            - [x] T2.1.2.1 Test VelocityAggregationJob calculates correct bucket distribution `[ref: PRD/Business Rules; lines: 246-252]` `[activity: backend-test]`
            - [x] T2.1.2.2 Test job handles missing buyDate gracefully (excludes from analysis) `[ref: PRD/Edge Case 4; lines: 258]` `[activity: backend-test]`
            - [x] T2.1.2.3 Test job correctly calculates margin erosion vs baseline `[ref: PRD/Feature 1; lines: 132-133]` `[activity: backend-test]`
            - [x] T2.1.2.4 Test job upserts daily summary correctly `[ref: SDD; lines: 396-405]` `[activity: backend-test]`

        - [x] T2.1.3 Implement
            - [x] T2.1.3.1 Create `BuyerKiosk\Analytics\Jobs\VelocityAggregationJob.php` `[ref: SDD; lines: 757-843]` `[activity: backend-api]`
            - [x] T2.1.3.2 Implement velocity bucket calculation (0-7, 8-14, 15-30, 31-60, 61-90, 91-180, 180+) `[activity: backend-api]`
            - [x] T2.1.3.3 Implement margin erosion calculation algorithm `[ref: SDD/Complex Logic; lines: 950-969]` `[activity: backend-api]`
            - [x] T2.1.3.4 Register job in TaskEngine job registry `[activity: backend-api]`

        - [x] T2.1.4 Validate ✅ COMPLETED 2025-12-30
            - [x] T2.1.4.1 Run job tests: Unit tests pass (121 tests, 624 assertions) `[activity: run-tests]`
            - [x] T2.1.4.2 Manual test: dispatch job for one store - Job completed successfully (no sales data for date, as expected) `[activity: backend-api]`
            - [x] T2.1.4.3 Job registered in TaskEngine: `20251230_004_analytics_jobs.json` migration added `[activity: backend-db]`

    - [x] T2.2 Velocity Service Layer `[component: velocity-backend]` ✅ COMPLETED 2024-12-30

        - [x] T2.2.1 Prime Context
            - [x] T2.2.1.1 Read SDD API contracts for velocity endpoints `[ref: SDD/Internal API Changes; lines: 443-500]`
            - [x] T2.2.1.2 Review KPIService caching pattern `[ref: userfrosting/src/BuyerKiosk/Workbook/KPIService.php]`

        - [x] T2.2.2 Write Tests
            - [x] T2.2.2.1 Test VelocityService::getDistribution returns correct structure `[ref: SDD; lines: 443-467]` `[activity: backend-test]`
            - [x] T2.2.2.2 Test VelocityService::getTrend returns daily trend data `[ref: SDD; lines: 469-480]` `[activity: backend-test]`
            - [x] T2.2.2.3 Test VelocityService::comparePeriods returns comparison metrics `[ref: SDD; lines: 482-499]` `[activity: backend-test]`
            - [x] T2.2.2.4 Test Redis caching behavior (cache hit vs miss) `[ref: ADR-5]` `[activity: backend-test]`
            - [x] T2.2.2.5 Test empty date range returns appropriate message `[ref: PRD/Edge Case 1; lines: 254-255]` `[activity: backend-test]`

        - [x] T2.2.3 Implement
            - [x] T2.2.3.1 Create `BuyerKiosk\Analytics\Services\VelocityService.php` `[ref: SDD; lines: 322]` `[activity: backend-api]`
            - [x] T2.2.3.2 Implement getDistribution with Redis caching (60s TTL) `[activity: backend-api]`
            - [x] T2.2.3.3 Implement getTrend for time-series data `[activity: backend-api]`
            - [x] T2.2.3.4 Implement comparePeriods for Period A vs Period B `[activity: backend-api]`
            - [x] T2.2.3.5 Create `BuyerKiosk\Analytics\Services\ComparisonService.php` for reusable comparison logic `[ref: SDD; lines: 325]` `[activity: backend-api]`

        - [x] T2.2.4 Validate
            - [x] T2.2.4.1 Run service tests: `./test.sh --filter VelocityService` → 18 tests passing `[activity: run-tests]`
            - [ ] T2.2.4.2 Verify caching works correctly with Redis CLI `[activity: backend-api]`

    - [x] T2.3 Velocity API Endpoints `[component: velocity-backend]` ✅ COMPLETED 2024-12-30

        - [x] T2.3.1 Prime Context
            - [x] T2.3.1.1 Review SDD error handling patterns `[ref: SDD/Error Handling; lines: 930-948]`

        - [ ] T2.3.2 Write Tests (Integration tests deferred to Phase 6)
            - [ ] T2.3.2.1 Test GET /api/:typeNum/analytics/velocity/distribution returns JSON `[activity: integration-test]`
            - [ ] T2.3.2.2 Test GET /api/:typeNum/analytics/velocity/trend returns trend data `[activity: integration-test]`
            - [ ] T2.3.2.3 Test GET /api/:typeNum/analytics/velocity/compare returns comparison `[activity: integration-test]`
            - [ ] T2.3.2.4 Test GET /api/:typeNum/analytics/velocity/export returns CSV `[ref: PRD/Feature 1; line: 137]` `[activity: integration-test]`
            - [ ] T2.3.2.5 Test unauthorized access returns 403 `[activity: integration-test]`
            - [ ] T2.3.2.6 Test invalid date format returns 400 `[ref: SDD/Error Handling; lines: 930-934]` `[activity: integration-test]`

        - [x] T2.3.3 Implement
            - [x] T2.3.3.1 Add velocity endpoints to AnalyticsApiController `[activity: backend-api]`
            - [x] T2.3.3.2 Implement CSV export functionality `[ref: SDD; lines: 558-568]` `[activity: backend-api]`
            - [x] T2.3.3.3 Add input validation and error handling `[activity: backend-api]`

        - [ ] T2.3.4 Validate
            - [ ] T2.3.4.1 Run integration tests: `./test.sh --testsuite integration --filter Velocity` `[activity: run-tests]`
            - [ ] T2.3.4.2 Test all endpoints with curl/Postman `[activity: backend-api]`

    - [x] T2.4 Velocity Dashboard Frontend `[component: velocity-frontend]` ✅ COMBINED WITH T3.3

        **Note**: T2.4 and T3.3 were combined into a unified Inventory Analytics Dashboard.
        See "T2.4 + T3.3: Unified Inventory Analytics Dashboard" section below for implementation details.

    - [ ] T2.5 Phase 2 Final Validation
        - [x] Velocity chart implemented in unified dashboard
        - [ ] Verify PRD Feature 1 acceptance criteria complete `[ref: PRD; lines: 130-137]` `[activity: business-acceptance]`
        - [ ] Run all Phase 2 tests: `./test.sh --filter Velocity` `[activity: run-tests]`
        - [ ] Review code against SDD architecture patterns `[activity: review-code]`

---

- [x] **T3 Phase 3: Momentum Dashboard** - PRD Features 2-3 (Must Have) `[parallel: true after T1]` ✅ BACKEND COMPLETE, FRONTEND COMBINED

    - [x] T3.1 Momentum Aggregation Job `[component: momentum-backend]` ✅ COMPLETED 2024-12-30

        - [x] T3.1.1 Prime Context
            - [x] T3.1.1.1 Read MACD algorithm specification in detail `[ref: docs/analytics/velocity-macd-specification.md]`
            - [x] T3.1.1.2 Read SDD MACD implementation example `[ref: SDD/Implementation Examples; lines: 627-755]`

        - [x] T3.1.2 Write Tests
            - [x] T3.1.2.1 Test MomentumService::calculateEMA returns correct values `[ref: SDD; lines: 642-658]` `[activity: backend-test]`
            - [x] T3.1.2.2 Test MomentumService::calculateMACD with known inputs `[ref: SDD; lines: 660-725]` `[activity: backend-test]`
            - [x] T3.1.2.3 Test crossover detection (bullish and bearish) `[ref: SDD; lines: 729-744]` `[activity: backend-test]`
            - [x] T3.1.2.4 Test momentum classification (strong_bullish to strong_bearish) `[ref: SDD; lines: 746-754]` `[activity: backend-test]`
            - [x] T3.1.2.5 Test insufficient data handling (< 35 days) `[ref: PRD/Business Rule 6; line: 277]` `[activity: backend-test]`

        - [x] T3.1.3 Implement
            - [x] T3.1.3.1 Create `BuyerKiosk\Analytics\Services\MomentumService.php` with EMA/MACD algorithms `[ref: SDD; lines: 627-755]` `[activity: backend-api]`
            - [x] T3.1.3.2 Create `BuyerKiosk\Analytics\Jobs\MomentumAggregationJob.php` `[ref: SDD; line: 332]` `[activity: backend-api]`
            - [x] T3.1.3.3 Implement daily MACD calculation for all categories `[activity: backend-api]`
            - [x] T3.1.3.4 Implement crossover event detection and storage `[activity: backend-api]`
            - [x] T3.1.3.5 Register job in TaskEngine job registry `[activity: backend-api]`

        - [x] T3.1.4 Validate ✅ COMPLETED 2025-12-30
            - [x] T3.1.4.1 Run MACD algorithm tests with known financial data → 42 tests, 308 assertions `[activity: run-tests]`
            - [x] T3.1.4.2 Manual test: dispatch job - Job completed successfully (no category data, as expected for dev store) `[activity: backend-api]`
            - [x] T3.1.4.3 Job registered in TaskEngine: `20251230_004_analytics_jobs.json` migration added `[activity: backend-db]`
            - [x] T3.1.4.4 Bug fix: `getStoreId()` column name corrected from `storeId` to `id` `[activity: backend-api]`

    - [x] T3.2 Momentum API Endpoints `[component: momentum-backend]` ✅ COMPLETED 2024-12-30

        - [x] T3.2.1 Prime Context
            - [x] T3.2.1.1 Read SDD API contracts for momentum endpoints `[ref: SDD/Internal API Changes; lines: 502-535]`

        - [ ] T3.2.2 Write Tests (Integration tests deferred to Phase 6)
            - [ ] T3.2.2.1 Test GET /api/:typeNum/analytics/momentum/heatmap returns all categories `[activity: integration-test]`
            - [ ] T3.2.2.2 Test GET /api/:typeNum/analytics/momentum/detail/:category returns MACD data `[activity: integration-test]`
            - [ ] T3.2.2.3 Test concept filter (pc/ou/se/pa) works correctly `[ref: PRD/Feature 2; line: 145]` `[activity: integration-test]`
            - [ ] T3.2.2.4 Test insufficient data returns appropriate message `[ref: PRD/Edge Case; lines: 281-282]` `[activity: integration-test]`

        - [x] T3.2.3 Implement
            - [x] T3.2.3.1 Add momentum endpoints to AnalyticsApiController `[activity: backend-api]`
            - [x] T3.2.3.2 Implement heatmap aggregation with signal classification `[activity: backend-api]`
            - [x] T3.2.3.3 Implement category detail with MACD line, signal line, histogram `[activity: backend-api]`

        - [ ] T3.2.4 Validate
            - [ ] T3.2.4.1 Run integration tests: `./test.sh --testsuite integration --filter Momentum` `[activity: run-tests]`

### Phase 2 & 3 Backend Progress Summary ✅

**Date**: 2024-12-30

**Backend Implementation Complete:**
| Component | Status | Files Created |
|-----------|--------|---------------|
| VelocityAggregationJob | ✅ | `Jobs/VelocityAggregationJob.php` |
| VelocityService | ✅ | `Services/VelocityService.php` |
| ComparisonService | ✅ | `Services/ComparisonService.php` |
| MomentumService | ✅ | `Services/MomentumService.php` |
| MomentumAggregationJob | ✅ | `Jobs/MomentumAggregationJob.php` |
| Velocity API Endpoints | ✅ | Modified `Controllers/AnalyticsApiController.php` |
| Momentum API Endpoints | ✅ | Modified `Controllers/AnalyticsApiController.php` |

**Test Coverage:**
- Unit Tests: **155 tests, 735 assertions** (up from 57 in Phase 1)
- New test files:
  - `tests/Unit/Analytics/Services/VelocityServiceTest.php` (18 tests)
  - `tests/Unit/Analytics/Services/ComparisonServiceTest.php` (40 tests)
  - `tests/Unit/Analytics/Services/MomentumServiceTest.php` (42 tests)
- PHPStan: **[OK] No errors**
- Skipped: 4 (Redis caching tests - graceful skip when extension unavailable)

**API Endpoints Implemented:**

*Velocity (4 endpoints):*
- `GET /api/:typeNum/analytics/velocity/distribution` - Bucket distribution
- `GET /api/:typeNum/analytics/velocity/trend` - Time-series trend
- `GET /api/:typeNum/analytics/velocity/compare` - Period comparison
- `GET /api/:typeNum/analytics/velocity/export` - CSV export

*Momentum (3 endpoints):*
- `GET /api/:typeNum/analytics/momentum/heatmap` - Category heatmap
- `GET /api/:typeNum/analytics/momentum/detail/:category` - MACD detail
- `GET /api/:typeNum/analytics/momentum/crossovers` - Recent crossovers

**Remaining for Phase 2 & 3:**
- [x] T2.4 + T3.3 Combined → Unified Inventory Analytics Dashboard ✅ COMPLETED 2024-12-30
- [ ] Integration tests (deferred to Phase 6)
- [ ] Manual job validation on dev environment

---

### T2.4 + T3.3: Unified Inventory Analytics Dashboard ✅ COMPLETED 2024-12-30

**Design Decision**: Combined velocity and momentum frontend into a single unified dashboard for better UX.

- [x] T2.4/T3.3.1 Prime Context
    - [x] Query Syncfusion MCP for DashboardLayout component configuration
    - [x] Query Syncfusion MCP for Chart (ColumnSeries) and HeatMap components
    - [x] Review design tokens `[ref: public_html/css/admin/tokens.css]`
    - [x] Review existing admin template patterns

- [x] T2.4/T3.3.2 Implement Syncfusion Integration
    - [x] Add DashboardLayout import to `resources/js/syncfusion.js`
    - [x] Add HeatMap, Legend, Tooltip, Adaptor imports to `resources/js/syncfusion.js`
    - [x] Inject HeatMap features and expose on `window.ej.heatmap`
    - [x] Expose DashboardLayout on `window.ej.layouts`
    - [x] Rebuild Vite bundle: `npm run build`

- [x] T2.4/T3.3.3 Implement Unified Dashboard
    - [x] Create `templates/themes/default/analytics/inventory.html` with Syncfusion DashboardLayout
    - [x] Create partials folder structure `templates/themes/default/analytics/partials/`
    - [x] Implement 4-panel responsive layout:
        - Panel 1: KPI Cards (Avg Days to Sale, Items Sold, Avg Margin, Active Categories)
        - Panel 2: Velocity Distribution (Syncfusion Column Chart with color-coded buckets)
        - Panel 3: Category Momentum (Signal cards with Hot/Cold indicators)
        - Panel 4: Recent Signals (Crossover events list)
    - [x] Implement date range selector with presets (7, 30, 90 days, YTD)
    - [x] Implement empty state handling for all panels
    - [x] Add refresh button functionality

- [x] T2.4/T3.3.4 Update Routes & Controller
    - [x] Rename `pageDashboard` → `pageInventory` in AnalyticsPageController
    - [x] Update routes: `/admin/:typeNum/analytics/inventory` (main dashboard)
    - [x] Add redirect: `/admin/:typeNum/analytics/` → `/analytics/inventory`
    - [x] Keep `pageRetention` method for future retention dashboard

- [x] T2.4/T3.3.5 Validate
    - [x] Manual UI testing in Chrome DevTools - Dashboard renders correctly
    - [x] Verify Vite build integration (no CDN dependencies)
    - [x] Verify all API endpoints return 200 (velocity/distribution, momentum/heatmap, momentum/crossovers)
    - [x] Verify empty states display correctly when no aggregated data
    - [x] Verify no console errors

**Files Created/Modified:**
| File | Action |
|------|--------|
| `templates/themes/default/analytics/inventory.html` | Created (unified dashboard) |
| `templates/themes/default/analytics/partials/` | Created (directory) |
| `resources/js/syncfusion.js` | Modified (added DashboardLayout, HeatMap) |
| `src/BuyerKiosk/Analytics/Controllers/AnalyticsPageController.php` | Modified (pageInventory, cleaned up) |
| `routes/analytics/pages.php` | Modified (inventory route, redirect) |

**Route Structure:**
```
/admin/:typeNum/analytics/           → Redirects to /inventory
/admin/:typeNum/analytics/inventory  → Inventory Analytics Dashboard
/admin/:typeNum/analytics/retention  → Seller Retention (future - Phase 4)
```

- [ ] T3.4 Phase 3 Final Validation
    - [x] Verify velocity chart renders with bucket distribution when data available
    - [x] Verify momentum cards display with signal classification (Hot/Rising/Stable/Cooling/Cold)
    - [ ] Verify PRD Feature 2 acceptance criteria complete `[ref: PRD; lines: 141-147]` `[activity: business-acceptance]`
    - [ ] Verify PRD Feature 3 acceptance criteria complete `[ref: PRD; lines: 151-157]` `[activity: business-acceptance]`
    - [ ] Run aggregation jobs to populate test data

---

- [x] **T4 Phase 4: Retention Dashboard & Should Have Features** - PRD Features 4-7 *(Core retention complete, Should Have deferred)*

    - [x] T4.1 Seller Retention Analytics `[component: retention-backend]` ✅ COMPLETE

        - [x] T4.1.1 Prime Context
            - [x] T4.1.1.1 Read SDD retention API contracts `[ref: SDD/Internal API Changes; lines: 537-556]`
            - [x] T4.1.1.2 Review seller cohort table schema `[ref: SDD; lines: 421-437]`

        - [x] T4.1.2 Write Tests
            - [x] T4.1.2.1 Test RetentionService::getOverview returns new vs returning ratio `[ref: PRD/Feature 4; line: 163]` `[activity: backend-test]`
            - [x] T4.1.2.2 Test RetentionService::getCohorts returns cohort retention data `[ref: PRD/Feature 4; line: 164]` `[activity: backend-test]`
            - [x] T4.1.2.3 Test visit frequency distribution calculation `[ref: PRD/Feature 4; line: 165]` `[activity: backend-test]`

        - [x] T4.1.3 Implement
            - [x] T4.1.3.1 Create `BuyerKiosk\Analytics\Services\RetentionService.php` `[ref: SDD; line: 324]` `[activity: backend-api]`
            - [x] T4.1.3.2 Create `BuyerKiosk\Analytics\Jobs\RetentionAggregationJob.php` `[ref: SDD; line: 333]` `[activity: backend-api]`
            - [x] T4.1.3.3 Implement cohort analysis from buys table `[activity: backend-api]`
            - [x] T4.1.3.4 Add retention API endpoints to controller `[activity: backend-api]`

        - [x] T4.1.4 Validate
            - [x] T4.1.4.1 Run retention tests: `./test.sh --filter Retention` `[activity: run-tests]`
            - [x] T4.1.4.2 Verify cohort data matches expected patterns `[activity: backend-api]`

    - [x] T4.2 Retention Dashboard Frontend `[component: retention-frontend]` ✅ COMPLETE

        - [x] T4.2.1 Prime Context
            - [x] T4.2.1.1 Research cohort chart visualization patterns `[activity: frontend-research]`

        - [x] T4.2.2 Write Tests (Manual test cases)
            - [x] T4.2.2.1 Define test case: New vs returning ratio displayed `[ref: PRD/Feature 4; line: 163]`
            - [x] T4.2.2.2 Define test case: Cohort retention chart renders `[ref: PRD/Feature 4; line: 164]`
            - [x] T4.2.2.3 Define test case: Date range selector works `[ref: PRD/Feature 4; line: 166]`

        - [x] T4.2.3 Implement
            - [x] T4.2.3.1 Create Twig template `templates/themes/default/analytics/retention.html` `[activity: frontend-ui]`
            - [x] T4.2.3.2 Create partial `templates/themes/default/analytics/partials/retention-chart.html` `[activity: frontend-ui]` *(inline in retention.html)*
            - [x] T4.2.3.3 Create `public_html/js/analytics/modules/retention-chart.js` `[activity: frontend-js]` *(inline in template)*

        - [x] T4.2.4 Validate
            - [x] T4.2.4.1 Manual UI testing of retention visualizations `[activity: frontend-test]`

    - [x] T4.7 Codex Code Review - Phase 4 ✅ COMPLETE
        > **Review Date**: 2025-12-30
        > **Reviewer**: Codex (o3 model)
        >
        > **Findings Fixed:**
        > - 🔴 **CRITICAL**: getCohorts() now selects LATEST analysisDate per cohort (not oldest)
        > - 🔴 **CRITICAL**: Added typeNum format validation in constructor (prevents cache key injection)
        > - 🟠 **IMPORTANT**: invalidateCache() now uses SCAN instead of KEYS (non-blocking Redis)
        > - 🟠 **IMPORTANT**: getFromCache() now verifies json_decode returns array
        > - 🟠 **IMPORTANT**: RetentionAggregationJob uses DateTimeImmutable with explicit timezone
        > - 🟠 **IMPORTANT**: Added division-by-zero guard in progress calculation
        > - 🟠 **IMPORTANT**: Catch \Throwable instead of \Exception
        > - 🟢 **MINOR**: Removed unused RETENTION_MONTHS constant
        >
        > **Validation**: 33 tests, 120 assertions, PHPStan [OK] No errors

    - [ ] T4.3 Should Have: Wait Time Correlation (Feature 5) `[component: wait-time]`

        - [ ] T4.3.1 Prime Context
            - [ ] T4.3.1.1 Review waitTime data in store database `[activity: backend-research]`

        - [ ] T4.3.2 Write Tests
            - [ ] T4.3.2.1 Test heat map generation for wait times by day/hour `[ref: PRD/Feature 5; line: 174]` `[activity: backend-test]`
            - [ ] T4.3.2.2 Test correlation calculation with NPS scores `[ref: PRD/Feature 5; line: 175]` `[activity: backend-test]`

        - [ ] T4.3.3 Implement
            - [ ] T4.3.3.1 Add wait time analysis methods to RetentionService or new WaitTimeService `[activity: backend-api]`
            - [ ] T4.3.3.2 Create wait time API endpoints `[activity: backend-api]`
            - [ ] T4.3.3.3 Create wait time frontend components `[activity: frontend-ui]`

        - [ ] T4.3.4 Validate
            - [ ] T4.3.4.1 Verify PRD Feature 5 acceptance criteria `[ref: PRD; lines: 174-177]` `[activity: business-acceptance]`

    - [ ] T4.4 Should Have: Enhanced P&L Dashboard (Feature 6) `[component: financial]`

        - [ ] T4.4.1 Prime Context
            - [ ] T4.4.1.1 Review existing financial reporting `[ref: userfrosting/src/BuyerKiosk/EventManagement/Controllers/EventReportController.php]`

        - [ ] T4.4.2 Write Tests
            - [ ] T4.4.2.1 Test YoY comparison calculation `[ref: PRD/Feature 6; line: 181]` `[activity: backend-test]`
            - [ ] T4.4.2.2 Test variance highlighting logic `[ref: PRD/Feature 6; line: 182]` `[activity: backend-test]`

        - [ ] T4.4.3 Implement
            - [ ] T4.4.3.1 Create P&L service extending existing patterns `[activity: backend-api]`
            - [ ] T4.4.3.2 Create P&L dashboard frontend `[activity: frontend-ui]`

        - [ ] T4.4.4 Validate
            - [ ] T4.4.4.1 Verify PRD Feature 6 acceptance criteria `[ref: PRD; lines: 180-185]` `[activity: business-acceptance]`

    - [x] T4.5 Should Have: Peer Comparison Dashboard (Feature 7) `[component: comparison]` ✅ COMPLETE + PRIVACY PIVOT

        > **Privacy Pivot (2024-12-31)**: Original "Store Comparison" design exposed individual store data
        > (typeNums visible). Redesigned to "Peer Comparison" with anonymized peer benchmarks only.
        > Store owners see their metrics vs peer averages - no individual peer store data exposed.

        - [x] T4.5.1 Prime Context
            - [x] T4.5.1.1 Understand cross-store data access patterns `[ref: ADR-4]` `[activity: backend-research]`
            - [x] T4.5.1.2 Reviewed storeMetricsDaily table (central DB), StoreMetricsAggregatorJob, getAllStoresData()
            - [x] T4.5.1.3 Identified privacy concern: multi-tenant stores shouldn't see each other's data

        - [x] T4.5.2 Write Tests
            - [x] T4.5.2.1 Test store ranking by selected metric `[ref: PRD/Feature 7; line: 189]` `[activity: backend-test]`
            - [x] T4.5.2.2 Test concept grouping (pc/ou/se/pa) `[ref: PRD/Feature 7; line: 190]` `[activity: backend-test]`
            - [x] T4.5.2.3 Test quartile calculation `[activity: backend-test]`
            - [x] T4.5.2.4 Test variance from average calculation `[activity: backend-test]`
            - [x] T4.5.2.5 Test peer benchmark returns anonymized data only `[activity: backend-test]`
            - [x] T4.5.2.6 Test revenue tier grouping ($1k-2.5k, $2.5k-5k, $5k+) `[activity: backend-test]`
            - [x] T4.5.2.7 Test volume tier grouping (starter, low, medium, high) `[activity: backend-test]`

        - [x] T4.5.3 Implement
            - [x] T4.5.3.1 Create `StoreComparisonRepository.php` (queries central kiosk_buykiosk DB) `[activity: backend-api]`
            - [x] T4.5.3.2 Create `StoreComparisonService.php` (ranking, quartiles, variance logic) `[activity: backend-api]`
            - [x] T4.5.3.3 Add API endpoints: `/api/:typeNum/analytics/stores/ranking`, `/concepts`, `/metadata` `[activity: backend-api]`
            - [x] T4.5.3.4 Add anonymized peer benchmark endpoint: `/api/:typeNum/analytics/stores/benchmark` `[activity: backend-api]`
            - [x] T4.5.3.5 Add `getPeerBenchmark()` method to StoreComparisonService (returns only aggregates) `[activity: backend-api]`
            - [x] T4.5.3.6 Add `getAvailablePeerGroups()` for UI peer group tabs `[activity: backend-api]`
            - [x] T4.5.3.7 Add tier calculation methods: `calculateRevenueTier()`, `calculateVolumeTier()` `[activity: backend-api]`
            - [x] T4.5.3.8 Create peer comparison dashboard `templates/themes/default/analytics/stores.html` `[activity: frontend-ui]`
            - [x] T4.5.3.9 Add page route `/admin/:typeNum/analytics/stores` `[activity: backend-api]`
            - [x] T4.5.3.10 Add sidebar menu item "Peer Comparison" `[activity: frontend-ui]`

        - [x] T4.5.4 Validate
            - [x] T4.5.4.1 Verify PRD Feature 7 acceptance criteria `[ref: PRD; lines: 189-194]` `[activity: business-acceptance]`
            - [x] All 13 unit tests pass (StoreComparisonService - updated with peer benchmark methods)
            - [x] PHPStan analysis passes with no errors
            - [x] Cleaned up phantom test data in storeMetricsDaily table

        **Privacy-Safe Design:**
        | What Store Owners See | What They DON'T See |
        |----------------------|---------------------|
        | Their own store metrics | Other stores' typeNums |
        | Peer group average | Individual peer data |
        | Percentile rank (Top 25%, etc.) | Who is ranked above/below |
        | Variance from average | Specific competitor metrics |

        **Peer Grouping Options:**
        | Group Type | Description |
        |------------|-------------|
        | Same Concept | Compare to stores of same type (ou, pc, se, pa) |
        | Revenue Tier | Compare to similar daily revenue ($1k-2.5k, $2.5k-5k, $5k+) |
        | Volume Tier | Compare to similar daily buys (starter, low, medium, high) |

        **Files Created/Modified:**
        | File | Action |
        |------|--------|
        | `tests/Unit/Analytics/Repositories/StoreComparisonRepositoryTest.php` | Created |
        | `tests/Unit/Analytics/Services/StoreComparisonServiceTest.php` | Created (13 tests) |
        | `src/BuyerKiosk/Analytics/Repositories/StoreComparisonRepository.php` | Created |
        | `src/BuyerKiosk/Analytics/Services/StoreComparisonService.php` | Created (with peer benchmark methods) |
        | `src/BuyerKiosk/Analytics/Controllers/AnalyticsApiController.php` | Modified (added 4 endpoints including getPeerBenchmark) |
        | `src/BuyerKiosk/Analytics/Controllers/AnalyticsPageController.php` | Modified (pageStoreComparison simplified) |
        | `routes/analytics/api.php` | Modified (added 4 stores/ routes including /benchmark) |
        | `routes/analytics/pages.php` | Modified (added /stores route) |
        | `templates/themes/default/analytics/stores.html` | Created (anonymized peer comparison UI) |
        | `templates/themes/default/menus/sidebar.html` | Modified (added "Peer Comparison" menu item) |

    - [ ] T4.6 Phase 4 Final Validation
        - [ ] T4.6.1 Verify all PRD Feature 4-7 acceptance criteria complete `[activity: business-acceptance]`
        - [ ] T4.6.2 Run all Phase 4 tests: `./test.sh --filter Retention` `[activity: run-tests]`
        - [ ] T4.6.3 Review code against SDD patterns `[activity: review-code]`

---

- [ ] **T5 Phase 5: Could Have Features & Polish**

    - [ ] T5.1 Could Have: NPS Dashboard (Feature 8) `[component: nps]`
        - [ ] T5.1.1 Create NPS visualization from customerSurvey data `[ref: PRD/Feature 8; lines: 198-204]` `[activity: backend-api]`
        - [ ] T5.1.2 Create NPS dashboard frontend `[activity: frontend-ui]`

    - [ ] T5.2 Could Have: In-App Alert Notifications (Feature 9) `[component: alerts]`
        - [ ] T5.2.1 Implement notification badge on menu item `[ref: PRD/Feature 9; line: 210]` `[activity: frontend-ui]`
        - [ ] T5.2.2 Create notification panel for crossover events `[ref: PRD/Feature 9; line: 211]` `[activity: frontend-ui]`
        - [ ] T5.2.3 Implement alert threshold configuration `[ref: PRD/Feature 9; line: 212]` `[activity: frontend-js]`
        - [ ] T5.2.4 Persist unread alert state `[ref: PRD/Feature 9; line: 214]` `[activity: backend-api]`

    - [ ] T5.3 Could Have: Pricing Optimization Analysis (Feature 10) `[component: pricing]`
        - [ ] T5.3.1 Create price vs days-to-sale scatter plot `[ref: PRD/Feature 10; line: 218]` `[activity: frontend-js]`
        - [ ] T5.3.2 Implement sweet spot price band identification `[ref: PRD/Feature 10; line: 219]` `[activity: backend-api]`

    - [ ] T5.4 Analytics Dashboard Navigation
        - [ ] T5.4.1 Create main analytics dashboard landing page with tab navigation `[activity: frontend-ui]`
        - [ ] T5.4.2 Add analytics menu items to admin navigation `[activity: frontend-ui]`
        - [ ] T5.4.3 Implement lazy loading of dashboard components `[ref: SDD/Performance; line: 1053]` `[activity: frontend-js]`

    - [ ] T5.5 TaskEngine Scheduler Setup
        - [ ] T5.5.1 Configure daily velocity aggregation job schedule (2 AM) `[ref: SDD/Deployment View; line: 905]` `[activity: backend-config]`
        - [ ] T5.5.2 Configure daily momentum aggregation job schedule `[activity: backend-config]`
        - [ ] T5.5.3 Configure retention aggregation job schedule `[activity: backend-config]`
        - [ ] T5.5.4 Set up job monitoring and alerting `[activity: backend-config]`

    - [ ] T5.6 Phase 5 Final Validation
        - [ ] T5.6.1 Verify Could Have features work correctly `[activity: business-acceptance]`
        - [ ] T5.6.2 Run all tests: `./test.sh` `[activity: run-tests]`

---

- [ ] **T6 Phase 6: Integration & End-to-End Validation**

    - [ ] T6.1 All Unit Tests Passing
        - [ ] T6.1.1 Run full test suite: `./test.sh --testsuite unit` `[activity: run-tests]`
        - [ ] T6.1.2 Verify test coverage > 80% for new code: `./test.sh --coverage` `[activity: run-tests]`

    - [ ] T6.2 Integration Tests
        - [ ] T6.2.1 Test velocity aggregation → API → frontend flow `[activity: integration-test]`
        - [ ] T6.2.2 Test momentum aggregation → API → frontend flow `[activity: integration-test]`
        - [ ] T6.2.3 Test retention aggregation → API → frontend flow `[activity: integration-test]`
        - [ ] T6.2.4 Test cross-store comparison data aggregation `[activity: integration-test]`
        - [ ] T6.2.5 Test Redis cache invalidation on job completion `[activity: integration-test]`

    - [ ] T6.3 End-to-End Test Scenarios `[ref: SDD/Test Specifications; lines: 1216-1286]`
        - [ ] T6.3.1 Scenario 1: Velocity Dashboard Load `[ref: SDD; lines: 1216-1224]` `[activity: e2e-test]`
        - [ ] T6.3.2 Scenario 2: Period Comparison `[ref: SDD; lines: 1226-1235]` `[activity: e2e-test]`
        - [ ] T6.3.3 Scenario 3: MACD Crossover Detection `[ref: SDD; lines: 1237-1247]` `[activity: e2e-test]`
        - [ ] T6.3.4 Scenario 4: Insufficient Data Handling `[ref: SDD; lines: 1249-1255]` `[activity: e2e-test]`
        - [ ] T6.3.5 Scenario 5: Export Functionality `[ref: SDD; lines: 1257-1265]` `[activity: e2e-test]`
        - [ ] T6.3.6 Scenario 6: Aggregation Job Success `[ref: SDD; lines: 1267-1277]` `[activity: e2e-test]`
        - [ ] T6.3.7 Scenario 7: Aggregation Job Retry `[ref: SDD; lines: 1279-1286]` `[activity: e2e-test]`

    - [ ] T6.4 Performance Validation `[ref: SDD/Quality Requirements; lines: 1168-1173]`
        - [ ] T6.4.1 Verify dashboard initial load < 2 seconds `[activity: performance-test]`
        - [ ] T6.4.2 Verify API response (cached) < 200ms `[activity: performance-test]`
        - [ ] T6.4.3 Verify API response (uncached) < 1 second `[activity: performance-test]`
        - [ ] T6.4.4 Verify daily aggregation job < 5 minutes per store `[activity: performance-test]`

    - [ ] T6.5 Security Validation `[ref: SDD/Cross-Cutting Concepts; lines: 1036-1040]`
        - [ ] T6.5.1 Verify store-level access control on all endpoints `[activity: security-test]`
        - [ ] T6.5.2 Verify no PII in exports (aggregate data only) `[activity: security-test]`
        - [ ] T6.5.3 Verify CSRF protection on state-changing operations `[activity: security-test]`
        - [ ] T6.5.4 Test unauthorized access returns 403 `[activity: security-test]`

    - [ ] T6.6 Acceptance Criteria Verification `[ref: PRD/Feature Requirements; lines: 124-230]`
        - [ ] T6.6.1 Feature 1 (Velocity Dashboard) - 7 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.2 Feature 2 (Category Momentum Heat Map) - 6 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.3 Feature 3 (Category MACD Detail) - 6 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.4 Feature 4 (Seller Retention) - 5 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.5 Feature 5 (Wait Time Correlation) - 4 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.6 Feature 6 (Enhanced P&L) - 5 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.7 Feature 7 (Store Comparison) - 5 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.8 Feature 8 (NPS Dashboard) - 4 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.9 Feature 9 (Alerts) - 5 acceptance criteria `[activity: business-acceptance]`
        - [ ] T6.6.10 Feature 10 (Pricing Analysis) - 3 acceptance criteria `[activity: business-acceptance]`

    - [ ] T6.7 Documentation & Handoff
        - [ ] T6.7.1 Update API documentation for new endpoints `[activity: documentation]`
        - [ ] T6.7.2 Create user guide for analytics dashboards `[activity: documentation]`
        - [ ] T6.7.3 Document aggregation job schedules and monitoring `[activity: documentation]`

    - [ ] T6.8 Build & Deployment Verification
        - [ ] T6.8.1 Build CSS: `php userfrosting/conductor build-css --minify` `[activity: build]`
        - [ ] T6.8.2 Run full test suite: `./test.sh` `[activity: run-tests]`
        - [ ] T6.8.3 Run static analysis: `./vendor/bin/phpstan analyse src/BuyerKiosk/Analytics/` `[activity: lint-code]`
        - [ ] T6.8.4 Deploy to staging environment `[activity: deploy]`
        - [ ] T6.8.5 Run initial aggregation jobs (backfill historical data) `[activity: deploy]`
        - [ ] T6.8.6 Enable scheduler for daily aggregation `[activity: deploy]`
        - [ ] T6.8.7 Verify staging environment functionality `[activity: deploy]`

    - [ ] T6.9 Final Sign-Off
        - [ ] T6.9.1 All PRD requirements implemented `[activity: business-acceptance]`
        - [ ] T6.9.2 Implementation follows SDD design `[activity: review-code]`
        - [ ] T6.9.3 Test coverage meets standards `[activity: run-tests]`
        - [ ] T6.9.4 Ready for production deployment `[activity: deploy]`

---

## Success Metrics Tracking

Reference PRD Success Metrics section for post-launch tracking:

| Metric | Target | Tracking Event |
|--------|--------|---------------|
| Adoption | 80% stores viewing Velocity Dashboard in 30 days | `dashboard_view` |
| Engagement | 3+ views per store per week | `dashboard_view` |
| Quality | <5% error rate | Error logs |
| Days-to-Sale | Reduce from 85 to 70 days in 6 months | `analytics_velocity_daily` |
| Trend Detection | Identify trends 2 weeks earlier | User feedback |
| Seller Retention | 10% improvement in 3-month retention | `analytics_seller_cohorts` |

---

## Rollback Strategy

If issues arise post-deployment:

1. **Disable scheduler jobs** - Stop daily aggregation
2. **Revert code deployment** - Standard deployment rollback
3. **Aggregation tables remain** - No harm, will be overwritten on re-deploy
4. **No schema rollback needed** - All changes are additive

---

*This plan enables phased implementation with Phase 2 (Velocity) and Phase 3 (Momentum) running in parallel after Phase 1 Foundation completes.*

---

## Current Progress Summary

**Last Updated**: 2024-12-31

### Phase Status Overview

| Phase | Status | Notes |
|-------|--------|-------|
| Phase 1: Foundation | ✅ COMPLETE | 57 tests, migrations, repositories, controllers |
| Phase 2: Velocity Backend | ✅ COMPLETE | Aggregation job, service, API endpoints |
| Phase 2: Velocity Frontend | ✅ COMPLETE | Combined with Phase 3 into unified dashboard |
| Phase 3: Momentum Backend | ✅ COMPLETE | MACD algorithm, aggregation job, API endpoints |
| Phase 3: Momentum Frontend | ✅ COMPLETE | Combined into unified Inventory Analytics Dashboard |
| Phase 4: Retention Core | ✅ COMPLETE | Backend + Retention dashboard (T4.1, T4.2) |
| Phase 4: Peer Comparison | ✅ COMPLETE | Privacy-safe peer benchmarking (T4.5) |
| Phase 4: Wait Time | 🔲 NOT STARTED | T4.3 - Wait time correlation |
| Phase 4: Enhanced P&L | 🔲 NOT STARTED | T4.4 - YoY P&L dashboard |
| Phase 5: Could Have | 🔲 NOT STARTED | NPS, Alerts, Pricing Analysis |
| Phase 6: Integration | 🔲 NOT STARTED | E2E tests, performance validation |

### Test Coverage

- **Unit Tests**: 168+ tests (ALL PASS)
- **PHPStan**: [OK] No errors
- **New Tests Added**: StoreComparisonService (13 tests with peer benchmark coverage)

### Design Decisions Made

1. **Unified Inventory Dashboard**: Combined velocity and momentum into single dashboard for better UX
2. **Separate Retention Dashboard**: Seller retention has its own dashboard (different focus)
3. **Privacy-Safe Peer Comparison**: Pivoted from "Store Comparison" (exposed typeNums) to "Peer Comparison" (anonymized only)
4. **Peer Grouping Options**: Three ways to compare - Concept, Revenue Tier, Volume Tier
5. **Syncfusion Integration**: Using Vite build system, not CDN
6. **Route Structure**: `/analytics/inventory`, `/analytics/retention`, `/analytics/stores` (peer comparison)

### Analytics Dashboards Available

| Dashboard | Route | Status |
|-----------|-------|--------|
| Inventory Analytics | `/admin/:typeNum/analytics/inventory` | ✅ Live |
| Seller Retention | `/admin/:typeNum/analytics/retention` | ✅ Live |
| Wait Time Analysis | `/admin/:typeNum/analytics/waittime` | 🔲 Pending |
| P&L Dashboard | `/admin/:typeNum/analytics/financial` | 🔲 Pending |
| Peer Comparison | `/admin/:typeNum/analytics/stores` | ✅ Live |

### Immediate Next Steps

1. [ ] Run store-metrics-aggregator job to populate real peer data
2. [ ] Implement T4.3 Wait Time Correlation (Feature 5)
3. [ ] Implement T4.4 Enhanced P&L Dashboard (Feature 6)
4. [ ] Schedule aggregation jobs in TaskEngine
