# 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
A secure, robust, and maintainable FiveStars loyalty integration that meets modern code standards, provides reliable POS connectivity, and gives store operators confidence in their loyalty program data.

### Problem Statement
The current FiveStars integration has critical security vulnerabilities (production API credentials hardcoded in source code), duplicate code that causes maintenance burden, inconsistent error handling that leads to silent failures, and zero test coverage making changes risky. These issues create:
- **Security risk**: Exposed credentials could be exploited, requiring emergency rotation
- **Reliability risk**: External API failures can block operations with no retry logic
- **Maintenance burden**: Two separate API clients with diverging implementations
- **Quality risk**: No tests means any change could break functionality

### Value Proposition
This modernization delivers:
1. **Security confidence** - Credentials managed via environment variables, no secrets in code
2. **Operational reliability** - Retry logic, timeouts, and circuit breakers prevent cascading failures
3. **Developer productivity** - Unified codebase with modern patterns matches Chat system architecture
4. **Quality assurance** - 80%+ test coverage enables safe future changes
5. **Maintainability** - Clear separation of concerns reduces onboarding time for new developers

## User Personas

### Primary Persona: Store Administrator
- **Demographics:** Store owner/manager, 30-55 years old, moderate technical expertise, uses admin interface daily
- **Goals:** View accurate points reports, ensure customers receive loyalty rewards reliably, configure FiveStars settings easily
- **Pain Points:** Unexplained "Error" status on points reports, no visibility when API is failing, unclear configuration options

### Secondary Personas

#### POS System Integrator
- **Demographics:** External developer at POS vendor, high technical expertise, integrates via API
- **Goals:** Reliable API endpoints for loyalty operations, clear error messages when things fail
- **Pain Points:** Silent failures, inconsistent error responses, missing documentation

#### BuyerKiosk Developer
- **Demographics:** Internal developer maintaining the codebase, high technical expertise
- **Goals:** Make changes safely, understand the codebase quickly, add new features without breaking existing functionality
- **Pain Points:** Duplicate code to maintain, no tests to verify changes, hardcoded values scattered throughout

## User Journey Maps

### Primary User Journey: Points Verification
1. **Awareness:** Store admin notices a customer complaint about missing points
2. **Consideration:** Admin checks the FiveStars Points Report in admin panel
3. **Adoption:** Admin filters by date range and customer phone number
4. **Usage:** Admin sees points status (Posted, Pending, Error) with timestamps
5. **Retention:** Admin trusts the report because errors are clearly explained with actionable messages

### Secondary User Journeys

#### API Integration Setup
1. **Awareness:** POS developer receives integration requirements from store
2. **Consideration:** Developer reviews API documentation and authentication requirements
3. **Adoption:** Developer configures API key and tests with sandbox environment
4. **Usage:** POS sends sales data, receives clear success/error responses
5. **Retention:** Integration runs reliably with automatic retries handling transient failures

#### Developer Onboarding
1. **Awareness:** New developer assigned to FiveStars feature work
2. **Consideration:** Developer reads code, runs tests to understand behavior
3. **Adoption:** Developer makes changes with confidence due to test coverage
4. **Usage:** Developer follows established patterns (Services/Models/Controllers)
5. **Retention:** Developer contributes improvements that don't break existing functionality

## Feature Requirements

### Must Have Features

#### Feature 1: Secure Credential Management
- **User Story:** As a system administrator, I want API credentials stored securely so that our FiveStars integration cannot be compromised by credential exposure
- **Acceptance Criteria:**
  - [ ] No API credentials exist in source code (FSRunner or main app)
  - [ ] All credentials are loaded from environment variables
  - [ ] Missing credentials produce clear error messages (not silent failures)
  - [ ] Application fails fast on startup if required credentials are missing

#### Feature 2: Unified API Client
- **User Story:** As a developer, I want a single FiveStars API client so that I only maintain one implementation
- **Acceptance Criteria:**
  - [ ] Single `FiveStarsApiClient` class used by both main app and FSRunner
  - [ ] Client supports dev/production environment detection via configuration
  - [ ] All existing API operations continue to function correctly
  - [ ] FSRunner can use the shared client without code duplication

#### Feature 3: Protected Reports Endpoint
- **User Story:** As a security-conscious operator, I want all API endpoints to require authentication so that unauthorized access is prevented
- **Acceptance Criteria:**
  - [ ] `/reports/points/getByDateRange` requires API key validation
  - [ ] Unauthorized requests return 401 status with clear error message
  - [ ] Valid requests continue to return report data as before

#### Feature 4: Comprehensive Test Coverage
- **User Story:** As a developer, I want comprehensive tests so that I can make changes without fear of breaking existing functionality
- **Acceptance Criteria:**
  - [ ] Unit tests exist for Points calculation logic
  - [ ] Unit tests exist for Reward redemption flow
  - [ ] Integration tests exist for API client (with mocked external calls)
  - [ ] Overall test coverage is 80% or higher for FiveStars module
  - [ ] Tests run successfully in CI pipeline

### Should Have Features

#### Feature 5: Retry Logic with Exponential Backoff
- **User Story:** As a store operator, I want the system to automatically retry failed API calls so that transient network issues don't cause data loss
- **Acceptance Criteria:**
  - [ ] Failed API calls are retried up to 3 times
  - [ ] Retry delays follow exponential backoff (1s, 2s, 4s)
  - [ ] Permanent failures (4xx errors) are not retried
  - [ ] All retry attempts are logged for troubleshooting

#### Feature 6: Request Timeouts
- **User Story:** As a system operator, I want API calls to timeout so that slow responses don't block the entire system
- **Acceptance Criteria:**
  - [ ] Connection timeout is set to 10 seconds
  - [ ] Request timeout is set to 30 seconds
  - [ ] Timeout errors are logged with endpoint details
  - [ ] Timeouts trigger retry logic (if retries remain)

#### Feature 7: Modern Code Structure
- **User Story:** As a developer, I want FiveStars code organized like the Chat system so that patterns are consistent across the codebase
- **Acceptance Criteria:**
  - [ ] Services layer handles business logic
  - [ ] Models are pure data containers
  - [ ] Controllers are thin (delegate to services)
  - [ ] All classes have type hints and return types
  - [ ] PHPDoc comments document public methods

### Could Have Features

#### Feature 8: Circuit Breaker Pattern
- **User Story:** As a system operator, I want the system to stop calling a failing API so that we don't overwhelm it with requests
- **Acceptance Criteria:**
  - [ ] After 5 consecutive failures, circuit opens
  - [ ] Open circuit returns cached data or graceful error
  - [ ] Circuit tests recovery every 60 seconds
  - [ ] Circuit state is visible in logs/monitoring

#### Feature 9: Structured Logging
- **User Story:** As a DevOps engineer, I want structured JSON logs so that I can query and alert on specific events
- **Acceptance Criteria:**
  - [ ] All FiveStars logs are JSON formatted
  - [ ] Logs include correlation IDs for request tracing
  - [ ] Error logs include stack traces and context

### Won't Have (This Phase)

- **FiveStars API version upgrade** - Current unified API will be maintained
- **New FiveStars features** - Only existing functionality will be preserved
- **Admin UI redesign** - Settings page will remain unchanged visually
- **Real-time monitoring dashboard** - Observability improvements limited to logging
- **Multi-tenant credential management** - Each store will continue using shared credentials

## Detailed Feature Specifications

### Feature: Unified API Client
**Description:** A single, well-tested API client class that handles all FiveStars API communication with proper error handling, timeouts, and retry logic. This replaces both the current main app client and the FSRunner client.

**User Flow:**
1. System needs to call FiveStars API (points posting, reward lookup, etc.)
2. System instantiates FiveStarsApiClient (or uses factory method)
3. Client loads credentials from environment variables
4. Client makes request with configured timeout
5. On failure, client retries with exponential backoff
6. Client returns result or throws typed exception

**Business Rules:**
- Rule 1: Credentials MUST come from environment variables, never hardcoded
- Rule 2: All requests MUST have timeout configured (no indefinite waits)
- Rule 3: Transient failures (5xx, network errors) MUST be retried
- Rule 4: Permanent failures (4xx) MUST NOT be retried
- Rule 5: All API calls MUST be logged (success and failure)
- Rule 6: Phone number hashing MUST use SHA1 (FiveStars API requirement)

**Edge Cases:**
- Scenario 1: Environment variable missing → Expected: Throw configuration exception with clear message
- Scenario 2: API returns invalid JSON → Expected: Log error, throw ParseException
- Scenario 3: All retries exhausted → Expected: Log final failure, throw ApiException with details
- Scenario 4: Network timeout → Expected: Retry up to 3 times, then fail
- Scenario 5: FiveStars API rate limited (429) → Expected: Respect Retry-After header if present

## Success Metrics

### Key Performance Indicators

- **Adoption:** 100% of stores using unified client within 1 week of deployment
- **Engagement:** API call success rate maintained at 99%+ (matching or exceeding current)
- **Quality:** Zero security vulnerabilities related to credential exposure
- **Business Impact:** 50% reduction in points-related support tickets

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| fivestars_api_call | endpoint, method, status_code, duration_ms, retry_count | Monitor API health and performance |
| fivestars_api_error | endpoint, error_type, error_message, retry_exhausted | Track failure patterns |
| fivestars_points_posted | store_id, points_count, customer_count | Verify business operations |
| fivestars_reward_redeemed | store_id, reward_uid, point_cost | Track redemption volume |

---

## Constraints and Assumptions

### Constraints
- **Timeline:** Must complete security fixes (credential removal) within 1 sprint
- **Backward Compatibility:** All existing API endpoints must continue working
- **FSRunner Architecture:** Cannot fundamentally change Beanstalkd queue pattern
- **Testing Infrastructure:** Must work with existing PHPUnit setup

### Assumptions
- FiveStars unified API will remain stable (no breaking changes)
- Environment variables will be properly configured in all environments
- Developers will rotate the exposed credentials after deployment
- CI/CD pipeline supports running tests

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Credential rotation causes downtime | High | Medium | Coordinate rotation with deployment, test in staging first |
| Retry logic causes rate limiting | Medium | Low | Implement exponential backoff, respect 429 responses |
| Breaking change in refactored code | High | Medium | Comprehensive test coverage, staged rollout |
| FSRunner shared library complexity | Medium | Medium | Clear dependency injection, factory methods |

## Open Questions

- [x] Should we rotate the exposed credentials immediately or wait for deployment? → **Rotate after deployment with new credential management**
- [x] What is the maximum acceptable API timeout? → **30 seconds for requests, 10 seconds for connection**
- [x] Should retry logic apply to all endpoints or just points posting? → **All endpoints with transient failures**

---

## Supporting Research

### Competitive Analysis
Modern loyalty integrations (Square Loyalty, Shopify Loyalty) use:
- OAuth2 or API key authentication with secure storage
- Retry logic with exponential backoff
- Comprehensive SDKs with typed responses
- Webhook-based async operations

### User Research
Based on support tickets and admin feedback:
- "Error" status on points report without explanation causes confusion
- Silent failures in points posting lead to customer complaints
- Developers spend extra time understanding duplicate code

### Market Data
- 78% of security breaches involve credential exposure (Verizon DBIR 2023)
- API retry logic reduces failed transactions by 15-25% (industry average)
- Test coverage above 70% correlates with 40% fewer production incidents
