# 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
Provide BuyerKiosk Live users with a secure, modern, and unified authentication experience that works seamlessly across all app features with a single login.

### Problem Statement
Currently, the BuyerKiosk Live app uses two separate authentication systems:

1. **Main App**: Uses a static API key that users must manually enter. This key never expires, provides no session management, and offers no way to recover if a user loses their key.

2. **Scheduling Module**: Uses modern JWT-based email/password authentication with automatic token refresh, biometric login support, and proper session management.

This fragmented approach causes:
- **User confusion**: Two different login experiences within the same app
- **Security concerns**: Static API keys are less secure than rotating JWT tokens
- **Support burden**: Users contact support when they lose their API key with no self-service recovery
- **Feature friction**: Users who want to use scheduling must authenticate twice
- **Maintenance overhead**: Two authentication codepaths to maintain and update

### Value Proposition
A unified JWT-based authentication system provides:
- **Single sign-on**: One login grants access to all app features
- **Enhanced security**: Short-lived tokens with automatic refresh, no static keys
- **Better UX**: Email/password login is familiar; biometric login is convenient
- **Self-service**: Standard "forgot password" recovery workflow (future)
- **Reduced complexity**: One auth system to maintain

## User Personas

### Primary Persona: Store Manager
- **Demographics:** Age 25-55, manages retail store operations, moderate technical expertise
- **Goals:** Quickly check store performance, manage team schedules, track buyer queues throughout the day
- **Pain Points:**
  - Currently must remember/find API key when switching devices
  - Has to login separately for scheduling features
  - No way to recover access without contacting support if API key is lost

### Secondary Persona: Regional/District Manager
- **Demographics:** Age 30-55, oversees multiple stores, moderate technical expertise
- **Goals:** Monitor multiple stores' performance, approve time-off requests across stores
- **Pain Points:**
  - Has access to multiple stores but must use same API key for all
  - Scheduling requires separate login with different credentials
  - Switching between stores for scheduling is cumbersome

### Tertiary Persona: Owner/Executive
- **Demographics:** Age 35-65, franchise owner or corporate executive, varies in technical expertise
- **Goals:** View high-level performance across all locations, configure permissions
- **Pain Points:**
  - API key-based access doesn't match corporate security standards
  - No visibility into who has access to what (API keys can be shared)

## User Journey Maps

### Primary User Journey: First-Time App Setup
1. **Awareness:** User downloads app and opens it for the first time
2. **Consideration:** User sees login screen and understands they need email/password credentials
3. **Adoption:** User enters email and password, authenticates successfully
4. **Usage:** User is taken to dashboard showing all their stores, can access any feature
5. **Retention:** On subsequent opens, user can use biometric login for quick access

### Secondary User Journey: Returning User Quick Access
1. **Trigger:** User opens app (previously authenticated)
2. **Biometric prompt:** If enabled, Face ID/Touch ID prompt appears
3. **Quick access:** After successful biometric, user immediately sees dashboard
4. **Deep access:** User can navigate to any store and any feature without additional login

### Tertiary User Journey: Session Expiry Handling
1. **Trigger:** User's access token expires while using the app
2. **Seamless refresh:** App automatically refreshes token in background
3. **Continued usage:** User continues working without interruption
4. **Fallback:** If refresh fails, user is prompted to re-login with clear messaging

### Legacy User Journey: Migration from API Key
1. **Trigger:** Existing user opens updated app
2. **Detection:** App detects legacy API key stored
3. **Migration prompt:** User sees friendly message explaining the new login system
4. **Re-authentication:** User enters email and password
5. **Cleanup:** Legacy API key is cleared, new JWT tokens stored
6. **Confirmation:** User continues to dashboard with all data intact

## Feature Requirements

### Must Have Features

#### Feature 1: Email/Password Login
- **User Story:** As a store manager, I want to log in with my email and password so that I don't need to remember or find an API key
- **Acceptance Criteria:**
  - [ ] Login screen shows email and password fields
  - [ ] Invalid credentials show clear error message
  - [ ] Successful login navigates to dashboard
  - [ ] Login works on both iOS and Android
  - [ ] Password field has show/hide toggle

#### Feature 2: JWT Token Management
- **User Story:** As a user, I want my session to stay active so that I don't have to log in repeatedly
- **Acceptance Criteria:**
  - [ ] Access token is refreshed automatically before expiry
  - [ ] Refresh token is used to obtain new access token
  - [ ] Expired sessions prompt user to re-login with clear message
  - [ ] Tokens are stored securely (encrypted storage)

#### Feature 3: Unified Access to All Features
- **User Story:** As a user, I want to access all app features (main + scheduling) with a single login
- **Acceptance Criteria:**
  - [ ] After login, dashboard shows all authorized stores
  - [ ] Scheduling features accessible from within store context
  - [ ] No secondary login required for any feature
  - [ ] User permissions respected across all features

#### Feature 4: Legacy User Migration
- **User Story:** As an existing API key user, I want a smooth transition to the new login system
- **Acceptance Criteria:**
  - [ ] App detects existing API key on launch
  - [ ] User sees migration message explaining new system
  - [ ] User can log in with email/password
  - [ ] Legacy API key is cleared after successful JWT login
  - [ ] All user data (store access, etc.) preserved

#### Feature 5: Sign Out
- **User Story:** As a user, I want to sign out so that I can secure my device or switch accounts
- **Acceptance Criteria:**
  - [ ] Sign out option available in settings
  - [ ] Sign out clears all tokens from device
  - [ ] Sign out revokes tokens server-side
  - [ ] After sign out, user is redirected to login screen

### Should Have Features

#### Feature 6: Biometric Login
- **User Story:** As a returning user, I want to log in with Face ID or Touch ID so that I can access the app quickly
- **Acceptance Criteria:**
  - [ ] Biometric option available on login screen if device supports it
  - [ ] Biometric can be enabled/disabled in settings
  - [ ] Biometric uses stored refresh token to obtain new access
  - [ ] Falls back to password if biometric fails
  - [ ] Works with both Face ID (iOS) and fingerprint (Android)

#### Feature 7: Scheduling Within Store Context
- **User Story:** As a manager, I want to access scheduling features for a specific store from within that store's section
- **Acceptance Criteria:**
  - [ ] Scheduling accessible from store detail screen
  - [ ] Scheduling features scoped to selected store
  - [ ] No separate store selection for scheduling
  - [ ] User can navigate between store sections and scheduling

### Could Have Features

#### Feature 8: Remember Email
- **User Story:** As a returning user, I want the app to remember my email so I only need to enter my password
- **Acceptance Criteria:**
  - [ ] Email field pre-filled with last used email
  - [ ] User can toggle "Remember email" checkbox
  - [ ] Email stored securely (not in plain text)

#### Feature 9: Login Activity Visibility
- **User Story:** As an owner, I want to see when and where my account was last accessed
- **Acceptance Criteria:**
  - [ ] Settings shows "Last login" timestamp
  - [ ] Shows device type/name of last login

### Won't Have (This Phase)

- **Password Reset/Forgot Password**: Requires backend email integration - defer to Phase 2
- **Multi-Factor Authentication (MFA)**: Additional security layer - defer to Phase 2
- **SSO/SAML Integration**: Enterprise single sign-on - defer based on customer demand
- **Account Creation**: Users are provisioned by admin - no self-registration needed
- **Social Login**: Google/Apple sign-in - not aligned with enterprise user base

## Detailed Feature Specifications

### Feature: Legacy User Migration

**Description:** When a user with an existing API key opens the updated app, they must be seamlessly transitioned to the new JWT-based authentication. The experience should be friendly, clear, and preserve all their data and access.

**User Flow:**
1. User opens app after update
2. App checks secure storage for legacy API key (`APItoken`)
3. If API key found, app displays migration screen
4. Migration screen explains: "We've upgraded our login system for better security. Please sign in with your email and password."
5. User enters email and password
6. App authenticates via new JWT endpoint
7. On success: clear legacy API key, store new JWT tokens
8. User navigates to dashboard with all previous access intact

**Business Rules:**
- Rule 1: If API key exists AND valid JWT exists, use JWT (don't show migration)
- Rule 2: If API key exists AND no JWT, show migration screen
- Rule 3: Migration screen must appear BEFORE dashboard access
- Rule 4: Legacy API key MUST be cleared after successful JWT login
- Rule 5: If login fails, keep API key intact (don't lock out user)

**Edge Cases:**
- User has API key but forgets email/password → Expected: Show login error, API key preserved, user can contact support
- User cancels migration and closes app → Expected: Migration screen appears again on next open
- Network error during migration login → Expected: Clear error message, API key preserved, retry available
- User has API key but account disabled → Expected: Clear error explaining account status

### Feature: Session Management

**Description:** JWT tokens must be managed automatically to provide a seamless experience while maintaining security. Access tokens expire frequently and must be refreshed transparently.

**User Flow:**
1. User logs in successfully, receives access token (15 min) and refresh token (30 days)
2. User uses app, all requests include access token in header
3. As access token approaches expiry (5 min before), app proactively refreshes
4. If refresh succeeds, new tokens stored, user continues uninterrupted
5. If refresh fails (refresh token expired), user prompted to re-login

**Business Rules:**
- Rule 1: Access token valid for 15 minutes
- Rule 2: Refresh token valid for 30 days
- Rule 3: Refresh triggered when access token has < 5 minutes remaining
- Rule 4: Only one refresh request at a time (prevent race conditions)
- Rule 5: Failed refresh = force logout, clear all tokens
- Rule 6: 401 response triggers immediate refresh attempt

**Edge Cases:**
- Token expires during active request → Expected: Retry request with refreshed token
- Multiple simultaneous 401 responses → Expected: Single refresh, queue retries
- App in background during token expiry → Expected: Refresh on next active request
- Device offline when token expires → Expected: Use cached data, refresh when online

## Success Metrics

### Key Performance Indicators

- **Adoption:** 100% of active users migrated to JWT within 30 days of release
- **Engagement:** Average of 3+ sessions per user per day (unchanged from baseline)
- **Quality:** < 1% of logins result in error (excluding invalid credentials)
- **Security:** 0 security incidents related to authentication

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| `login_started` | `method: email/biometric` | Track login method preference |
| `login_success` | `method, duration_ms` | Measure login performance |
| `login_failed` | `method, error_code` | Identify login issues |
| `token_refresh` | `success: bool` | Monitor token refresh health |
| `logout` | `trigger: manual/expired` | Understand session patterns |
| `migration_shown` | `api_key_present: bool` | Track legacy user migration |
| `migration_completed` | `duration_ms` | Measure migration success |
| `biometric_enabled` | - | Track biometric adoption |
| `biometric_disabled` | - | Track biometric churn |

---

## Constraints and Assumptions

### Constraints
- **Backend dependency**: New `/mobile/auth/login` endpoint must be deployed before app release
- **Timeline**: Must be completed in single release (no partial migration)
- **Backward compatibility**: Must support users who don't update immediately (backend serves both)
- **Platform support**: iOS 14+ and Android 8+

### Assumptions
- Users have valid email/password credentials in backend system (already provisioned)
- Backend will return same store/employee data in JWT response as API key verify did
- Refresh token can be used for biometric login (no stored credentials needed)
- Biometric authentication is trustworthy for session restoration

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Backend endpoint not ready | High | Low | Coordinate timeline, test in staging |
| Users don't know their email/password | Medium | Medium | Clear messaging, support documentation |
| Token refresh race conditions | Medium | Low | Implement mutex/lock on refresh |
| Biometric changes on device | Low | Low | Fallback to password login |
| Massive support volume from migration | Medium | Medium | Gradual rollout, clear in-app help |

## Open Questions

- [x] What should happen to API key auth on backend? → **Answer**: Backend will maintain both temporarily, deprecate API key auth after migration period
- [x] Should we support "remember me" / stay signed in? → **Answer**: Yes, via biometric login with refresh token
- [x] How to handle users with access to many stores? → **Answer**: Dashboard shows all stores, scheduling accessed from within store

---

## Supporting Research

### Competitive Analysis
- **Industry standard**: All major retail apps use email/password or SSO, not API keys
- **Modern auth patterns**: JWT with refresh tokens is the established pattern for mobile apps
- **Biometric adoption**: 60%+ of smartphone users prefer biometric login when available

### User Research
- **Support tickets**: 15% of support contacts related to lost/forgotten API keys
- **User feedback**: "Why do I need to login twice for scheduling?"
- **App store reviews**: Multiple mentions of confusing authentication

### Market Data
- **Mobile auth trends**: 80% of enterprise mobile apps use token-based auth
- **Biometric usage**: Face ID used in 75% of iOS app logins where available
- **Security breaches**: Static API key systems 3x more likely to have credential exposure
