# 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
Modernize the BuyerKiosk PHP codebase to use PSR-4 autoloading under a unified `BuyerKiosk\` namespace, eliminating manual include chains and enabling modern PHP development practices.

### Problem Statement
The current codebase relies on **228 manual include statements** (151 in BaseModel.php + 77 in initialize.php) to load classes. This creates several pain points:

1. **Developer Friction**: Adding new classes requires manually updating BaseModel.php or initialize.php, and understanding load order dependencies
2. **Maintenance Burden**: Duplicate includes exist (FiveStars loaded twice, EmailReportController loaded twice), and the include order must be carefully managed
3. **Mixed Namespace State**: ~60% of classes use `BuyerKiosk\*` namespaces while ~40% remain non-namespaced (legacy classes like Store, Buy, BuyQueue)
4. **Performance**: Classmap autoloading requires regeneration after adding classes; PSR-4 is more efficient for large codebases
5. **Onboarding Difficulty**: New developers must understand the complex include chain before contributing safely

### Value Proposition
By migrating to PSR-4 autoloading with a unified `BuyerKiosk\` namespace:
- **Developers** can add new classes without touching include files
- **Maintainers** benefit from self-documenting namespace-to-directory mappings
- **The codebase** becomes compatible with modern PHP tooling, static analysis, and IDE features
- **Performance** improves through efficient on-demand class loading

## User Personas

### Primary Persona: PHP Developer
- **Demographics:** Backend developer working on BuyerKiosk features, intermediate to senior PHP experience
- **Goals:** Quickly add features, fix bugs, and understand code organization without fighting the build system
- **Pain Points:** Must manually edit include files when adding classes; unclear which file to edit; fear of breaking load order

### Secondary Personas

#### DevOps Engineer
- **Goals:** Deploy reliable builds, run tests, maintain CI/CD pipelines
- **Pain Points:** Composer classmap regeneration required after code changes; unclear if autoload is current

#### New Team Member
- **Goals:** Understand codebase structure, make first contribution
- **Pain Points:** 228 include statements are overwhelming; mixed namespace conventions confusing

## User Journey Maps

### Primary User Journey: Adding a New Class
1. **Awareness:** Developer needs to create a new service or model class
2. **Consideration:** Currently must decide: add to BaseModel.php? initialize.php? What load order?
3. **Adoption:** With PSR-4, simply create file in correct namespace directory
4. **Usage:** Class is automatically available via Composer autoloader
5. **Retention:** Consistent experience for all new classes; no manual steps required

### Secondary User Journeys

#### Running Tests
1. Developer runs test suite
2. All classes load correctly via PSR-4
3. Tests pass/fail based on logic, not include order issues

#### Code Review
1. Reviewer sees new class added
2. No changes to include files required
3. Namespace matches directory structure (easy to verify)

## Feature Requirements

### Must Have Features

#### Feature 1: Unified BuyerKiosk Namespace
- **User Story:** As a developer, I want all application classes under the `BuyerKiosk\` namespace so that the codebase has consistent organization
- **Acceptance Criteria:**
  - [ ] All ~200 model classes are namespaced under `BuyerKiosk\*`
  - [ ] All ~63 controller classes are namespaced under `BuyerKiosk\*`
  - [ ] Legacy non-namespaced classes (Store, Buy, BuyQueue, Loyalty*, etc.) are migrated to appropriate sub-namespaces
  - [ ] Namespace structure matches directory structure per PSR-4

#### Feature 2: PSR-4 Composer Autoloading
- **User Story:** As a developer, I want Composer to automatically load classes based on namespace so that I never manually edit include files
- **Acceptance Criteria:**
  - [ ] composer.json contains PSR-4 autoload configuration for `BuyerKiosk\`
  - [ ] Running `composer dump-autoload` generates working autoloader
  - [ ] New classes in correct directories are automatically loadable
  - [ ] No manual include statements required in BaseModel.php or initialize.php

#### Feature 3: Elimination of Manual Includes
- **User Story:** As a maintainer, I want BaseModel.php and initialize.php to not contain class includes so that the codebase is simpler
- **Acceptance Criteria:**
  - [ ] BaseModel.php contains zero class include statements (utility functions may remain)
  - [ ] initialize.php contains only framework bootstrap, not class loading
  - [ ] All 228 current include statements are removed or replaced with autoloading

#### Feature 4: Backward Compatibility
- **User Story:** As an operator, I want all existing functionality to continue working so that the refactor doesn't break production
- **Acceptance Criteria:**
  - [ ] All existing tests pass after migration
  - [ ] Queue system continues to function (BuyQueue, SimpleQueue, ServiceQueue)
  - [ ] All integrations work (QuickBooks, FiveStars, Shopify, WhenIWork, Twilio, Vonage)
  - [ ] Workbook system fully functional (Tasks, Notes, KPIs, Schedule, Whiteboard)
  - [ ] Mobile API endpoints respond correctly
  - [ ] Admin and store operations unchanged

#### Feature 5: Test Verification
- **User Story:** As a developer, I want tests to verify the refactor didn't break anything so that I'm confident in the changes
- **Acceptance Criteria:**
  - [ ] Existing test suite runs and passes
  - [ ] New autoload-specific tests verify class loading
  - [ ] Integration tests confirm end-to-end functionality

### Should Have Features

#### Class Alias Compatibility Layer
- **User Story:** As a developer working on incremental migration, I want legacy class names to still work temporarily
- **Acceptance Criteria:**
  - [ ] Class aliases defined for commonly-used legacy class names (e.g., `Store` → `BuyerKiosk\Models\Store`)
  - [ ] Aliases emit deprecation notices to guide migration
  - [ ] Aliases can be removed in future release

### Could Have Features

#### IDE Configuration
- Provide PHPStorm/VSCode configuration for namespace autocomplete
- Document recommended IDE settings

### Won't Have (This Phase)

- **Dependency Injection Container**: Out of scope; current direct instantiation patterns will remain
- **Service Layer Restructuring**: Only namespace changes; no architectural refactoring
- **PHP Version Upgrade**: Composer.json PHP constraint update is out of scope
- **Framework Migration**: UserFrosting/Slim patterns will remain unchanged

## Detailed Feature Specifications

### Feature: Unified BuyerKiosk Namespace

**Description:** Migrate all ~263 PHP classes (200 models + 63 controllers) to use the `BuyerKiosk\` namespace with sub-namespaces matching the current directory structure.

**Namespace Mapping (Feature-Based):**
- `userfrosting/models/Class/Workbook/` → `BuyerKiosk\Workbook\`
- `userfrosting/models/Class/Backstock/` → `BuyerKiosk\Backstock\`
- `userfrosting/models/Class/Employee/` → `BuyerKiosk\Employee\`
- `userfrosting/models/Class/Support/` → `BuyerKiosk\Support\`
- `userfrosting/models/Class/SellerMarketing/` → `BuyerKiosk\SellerMarketing\`
- `userfrosting/models/Class/Cash/` → `BuyerKiosk\Cash\`
- `userfrosting/models/Class/QuickBooks/` → `BuyerKiosk\QuickBooks\`
- `userfrosting/models/Class/` (core) → `BuyerKiosk\Core\` (Store, Buy, BuyQueue, Customer, etc.)
- `userfrosting/controllers/Workbook/` → `BuyerKiosk\Workbook\Controllers\`
- `userfrosting/controllers/Backstock/` → `BuyerKiosk\Backstock\Controllers\`
- `userfrosting/controllers/` (core) → `BuyerKiosk\Core\Controllers\`
- `userfrosting/services/` → `BuyerKiosk\Services\`

**Business Rules:**
- Rule 1: Every PHP class file must declare a namespace
- Rule 2: Namespace must match directory path relative to autoload root
- Rule 3: One class per file, filename matches class name
- Rule 4: All `use` statements must reference fully-qualified class names

**Edge Cases:**
- Legacy classes extending `Store` (e.g., `Buy extends Store`) → Both classes must be namespaced, references updated
- Classes with name conflicts across directories → Sub-namespace disambiguates (e.g., `BuyerKiosk\Models\Employee\Employee` vs legacy)
- Global functions in BaseModel.php → Remain as functions or move to utility class

## Success Metrics

### Key Performance Indicators

- **Adoption:** 100% of classes migrated to BuyerKiosk namespace
- **Engagement:** 0 manual include statements remaining
- **Quality:** 100% test pass rate after migration
- **Business Impact:** No production incidents caused by refactor

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| Class loaded via autoloader | class_name, load_time_ms | Verify autoloading works |
| Deprecation notice triggered | legacy_class, new_class | Track alias usage for removal |
| Test suite execution | tests_run, tests_passed, tests_failed | Verify backward compatibility |

---

## Constraints and Assumptions

### Constraints
- **Zero Downtime**: Production must continue operating during migration
- **Incremental Deployment**: Changes must be deployable incrementally, not all-at-once
- **Existing Tests**: Must use existing test infrastructure (PHPUnit 12.x)
- **Slim 2.6.2 Compatibility**: Framework integration points must continue working

### Assumptions
- Composer autoloader is already loaded early in bootstrap (confirmed in initialize.php)
- All developers have PHP 8.x locally (per CLAUDE.md)
- CI/CD pipeline runs `composer install` before tests/deployment
- Redis, MySQL, and external services unaffected by namespace changes

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Breaking production functionality | High | Medium | Comprehensive test coverage; staged rollout |
| Class name conflicts after namespacing | Medium | Low | Careful namespace planning; sub-namespaces for disambiguation |
| Performance regression from autoloader | Low | Low | PSR-4 is typically faster than classmap; benchmark if needed |
| Third-party integration breaks | High | Low | Integration tests verify external service connections |
| Developer confusion during transition | Medium | Medium | Clear documentation; class aliases for common patterns |

## Open Questions

- [x] Should all classes use `BuyerKiosk\` namespace? **YES - confirmed by user**
- [x] Should legacy class aliases be permanent or deprecated? **DEPRECATED - aliases will emit warnings, plan for removal**
- [x] What is the preferred sub-namespace structure? **FEATURE-BASED - e.g., `BuyerKiosk\Workbook\*`, `BuyerKiosk\Backstock\*`, `BuyerKiosk\Queue\*`**

---

## Supporting Research

### Competitive Analysis
Modern PHP frameworks (Laravel, Symfony) universally use PSR-4 autoloading. This is the industry standard approach that enables:
- IDE autocomplete and navigation
- Static analysis tools (PHPStan, Psalm)
- Package interoperability
- Clear code organization

### User Research
Discovery analysis of current codebase revealed:
- 151 includes in BaseModel.php
- 77 includes in initialize.php
- Duplicate includes exist (FiveStars, EmailReportController)
- ~60% of classes already use BuyerKiosk namespace
- ~40% legacy non-namespaced classes need migration

### Market Data
PSR-4 is the PHP-FIG accepted standard for autoloading (PSR-4: Autoloader, 2013). All major PHP frameworks and packages follow this standard.
