# 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
Empower retail store managers and owners to efficiently manage team schedules, approve requests, and maintain labor visibility directly from the BuyerKiosk Live mobile app, reducing the friction of switching between web and mobile tools for daily scheduling operations.

### Problem Statement
Store managers and owners currently must use the BuyerKiosk web portal to handle scheduling administration tasks (approving shift swaps, time-off requests, managing shifts), while the mobile app only provides store performance metrics. This creates:

1. **Response delays**: Pending requests sit unapproved because managers aren't at their desk
2. **Context switching friction**: Managers check store metrics on mobile, then must switch to web for scheduling
3. **Missed visibility**: No mobile view of who's working, labor costs, or their own upcoming shifts
4. **Authentication inconsistency**: The Live app uses API key auth while the Team app uses proper user login, creating a fragmented experience

**Baseline Metrics:**
- Current average request approval time: 4+ hours (target: 30 minutes)
- 85% of managers already check BuyerKiosk Live daily for store metrics
- Average manager handles 3-5 schedule requests per day

The result: slower request turnaround times, frustrated employees waiting for approvals, and managers lacking real-time scheduling visibility when away from their computers.

### Value Proposition
BuyerKiosk Live becomes the single mobile command center for managers/owners by:
- **Instant approvals**: Approve/deny shift swaps, time-off, and overrides in seconds from anywhere
- **Complete visibility**: See who's working, labor costs, and your own schedule at a glance
- **Unified auth**: Modern login experience matching the Team app (email/password + biometrics)
- **Multi-store efficiency**: Manage multiple stores from one login, switching seamlessly

## User Personas

### Primary Persona: Store Manager
- **Demographics:** 28-45 years old, manages 5-20 employees, moderate technical proficiency, uses smartphone daily
- **Goals:**
  - Keep the store fully staffed without gaps
  - Respond quickly to employee schedule requests
  - Stay on top of labor costs vs budget
  - Balance their own shifts with management duties
- **Pain Points:**
  - Gets request notifications but can't approve from phone
  - Has to remember to check web portal for pending items
  - Can't see who's actually working right now when not in store
  - Juggles multiple stores and loses track of which needs attention

### Secondary Persona: Franchise Owner
- **Demographics:** 35-55 years old, owns 1-5 stores, business-focused, values efficiency
- **Goals:**
  - Oversee scheduling health across all stores
  - Ensure labor costs stay within budget
  - Empower managers while maintaining visibility
  - Make quick decisions when managers escalate
- **Pain Points:**
  - No aggregated view of pending requests across stores
  - Must log into web portal separately for each store
  - Can't quickly assess staffing levels when visiting stores
  - Current API key auth feels outdated and less secure

## User Journey Maps

### Primary User Journey: Daily Request Approval Flow
1. **Trigger:** Manager receives push notification "Sarah requested to swap shifts with Mike"
2. **Open App:** Taps notification, app opens to Scheduling section (or login if needed)
3. **Review Request:** Sees swap details - both shifts, any conflicts flagged
4. **Take Action:** Approves with one tap (or denies with optional note)
5. **Confirmation:** Success message shown, employees notified automatically
6. **Continue:** Can review other pending requests or return to dashboard

### Secondary User Journey: Morning Store Check
1. **Trigger:** Manager arrives at work, wants to see today's staffing
2. **Open App:** Opens BuyerKiosk Live, navigates to Scheduling
3. **View Dashboard:** Sees at-a-glance: 5 scheduled, 3 clocked in, 1 late, 2 pending requests
4. **Drill Down:** Taps "Who's Working" to see names, positions, clock-in times
5. **Review Requests:** Notices 2 pending time-off requests, reviews and approves both (batch)
6. **Check Labor:** Views this week's labor cost vs budget before planning next week

### Tertiary User Journey: Shift Management
1. **Trigger:** Employee calls in sick, manager needs coverage
2. **Open App:** Opens Scheduling section
3. **Create Open Shift:** Creates new shift for the vacant time slot (no employee assigned)
4. **Or Modify:** Extends another employee's shift to cover
5. **Notify:** System shows shift is created/modified
6. **Monitor:** Checks if anyone claims the open shift (if applicable)

### Quaternary User Journey: First-Time Login
1. **Install/Update:** User opens updated app, sees login screen instead of API key entry
2. **Enter Credentials:** Types email and password (same as Team app/web portal)
3. **Store Selection:** Sees list of stores they have access to, selects one
4. **Enable Biometrics:** Prompted to enable Face ID/Touch ID for future logins
5. **Dashboard:** Lands on main dashboard with scheduling section now available
6. **Future Logins:** Uses biometrics, goes straight to last-used store

## Feature Requirements

### Must Have Features

#### Feature 1: JWT Authentication Migration
- **User Story:** As a manager, I want to log in with my email and password so that I have a secure, personalized experience matching the Team app.
- **Acceptance Criteria:**
  - [ ] Login screen accepts email and password
  - [ ] Invalid credentials show clear error message
  - [ ] Successful login stores JWT tokens securely
  - [ ] Access token refreshes automatically before expiry
  - [ ] Refresh token (30-day TTL) enables persistent sessions
  - [ ] Existing API key users see migration prompt on app update
  - [ ] Existing API key is immediately invalidated upon successful JWT login (server-side invalidation)
  - [ ] All existing features work with JWT auth (API endpoints accept JWT tokens)

#### Feature 2: Biometric Authentication
- **User Story:** As a manager, I want to use Face ID or Touch ID after my first login so that I can access the app quickly without typing my password.
- **Acceptance Criteria:**
  - [ ] After successful login, user is prompted to enable biometrics
  - [ ] Biometric auth uses stored refresh token to get new access token
  - [ ] User can disable biometrics in settings
  - [ ] Falls back to password if biometrics fail 3 times
  - [ ] Works on both iOS (Face ID/Touch ID) and Android (fingerprint/face)

#### Feature 3: Multi-Store Selection
- **User Story:** As an owner managing multiple stores, I want to select which store to manage after login so that I can switch between stores without re-authenticating.
- **Acceptance Criteria:**
  - [ ] After login, shows list of stores user has access to
  - [ ] Each store shows name, role (Manager/Owner), and pending request count
  - [ ] User can switch stores from settings or header
  - [ ] Store context persists between sessions (remembers last store)
  - [ ] Switching stores reloads scheduling data for new store

#### Feature 4: Manager Dashboard
- **User Story:** As a manager, I want to see a dashboard overview of today's staffing and pending requests so that I can quickly assess what needs my attention.
- **Acceptance Criteria:**
  - [ ] Shows today's stats: scheduled employees, clocked in, late, absent
  - [ ] Shows pending request counts: time-off, swaps, overrides
  - [ ] Shows this week's labor cost and budget variance (if available)
  - [ ] Tapping any stat navigates to relevant detail screen
  - [ ] Dashboard refreshes on pull-down

#### Feature 5: Pending Request Approval
- **User Story:** As a manager, I want to view and approve/deny pending requests so that employees get timely responses to their schedule change requests.
- **Acceptance Criteria:**
  - [ ] Lists all pending requests (time-off, swaps, overrides) in one view
  - [ ] Can filter by request type
  - [ ] Each request shows: employee name, request type, dates/times, reason
  - [ ] Shift swaps show both employees' shifts and any conflicts
  - [ ] Can approve or deny with one tap
  - [ ] Optional note field when denying
  - [ ] Confirmation shown after action
  - [ ] Push notification sent to employee
  - [ ] Full audit trail captured: device ID, timestamp, manager ID, location (if available)
  - [ ] Location permission: soft prompt on first approval action; proceed without location if denied (capture null)
  - [ ] Self-approval of time-off requests controlled by store setting (can be enabled/disabled per store)

#### Feature 6: Batch Request Approval
- **User Story:** As a manager with many pending requests, I want to approve or deny multiple requests at once so that I can process them efficiently.
- **Acceptance Criteria:**
  - [ ] Can enter "select mode" to choose multiple requests
  - [ ] Maximum of 10 requests can be selected at once
  - [ ] Shows count of selected items (X/10 selected)
  - [ ] Batch approve or batch deny buttons
  - [ ] Single note applies to all denied requests
  - [ ] Shows summary of successful/failed actions
  - [ ] Partial failure handling: show per-item error, keep failed items pending, allow retry
  - [ ] At least one request type must be same for batch (can't mix time-off and swaps)

#### Feature 7: Who's Working View
- **User Story:** As a manager, I want to see who's currently working at the store so that I know the current staffing situation.
- **Acceptance Criteria:**
  - [ ] Shows list of today's scheduled employees
  - [ ] Each employee shows: name, position, scheduled time, status (scheduled/clocked in/late/absent)
  - [ ] Clocked-in employees show actual clock-in time
  - [ ] Late defined as: clocked in >5 minutes after scheduled start time (in store timezone)
  - [ ] Late employees highlighted with minutes late
  - [ ] Can pull to refresh for real-time status

#### Feature 8: My Schedule View
- **User Story:** As a manager who also works shifts, I want to see my own upcoming schedule so that I can plan my week.
- **Acceptance Criteria:**
  - [ ] Shows list of manager's upcoming shifts (next 5 by default)
  - [ ] Each shift shows: date, start/end time, position, total hours
  - [ ] Can tap to see shift details
  - [ ] Shows weekly hour total for current period

### Should Have Features

#### Feature 9: Shift CRUD (Create/Edit/Delete)
- **User Story:** As a manager, I want to create, modify, and delete shifts so that I can adjust the schedule when needed.
- **Acceptance Criteria:**
  - [ ] Can create new shift: select employee (or leave open), date, start/end time, position
  - [ ] Can edit existing shift: change times, reassign to different employee
  - [ ] Can delete shift with required reason
  - [ ] Shows informational warning if shift conflicts (does not block save)
  - [ ] Shows warning if employee has time-off approved for that date
  - [ ] Cannot edit/delete shifts in the past
  - [ ] Shift edits follow same rules as web: immediate for published weeks, draft for unpublished

#### Feature 10: Labor Cost View
- **User Story:** As a manager/owner, I want to see labor costs for the current week so that I can manage within budget.
- **Acceptance Criteria:**
  - [ ] Shows weekly labor cost breakdown by day
  - [ ] Shows total scheduled hours and estimated cost
  - [ ] Shows budget target and variance (if configured); shows "Budget not configured" message if unavailable
  - [ ] Can navigate to previous/next weeks

#### Feature 11: Request History
- **User Story:** As a manager, I want to see past request decisions so that I can reference previous approvals/denials.
- **Acceptance Criteria:**
  - [ ] Shows list of resolved requests (approved/denied)
  - [ ] Can filter by type, status, date range
  - [ ] Shows who processed the request and when
  - [ ] Shows any notes attached to decision

### Could Have Features

#### Feature 12: Employee Schedule View
- **User Story:** As a manager, I want to view any employee's schedule so that I can see their upcoming shifts when planning.
- **Acceptance Criteria:**
  - [ ] Can search/select any employee in store
  - [ ] Shows employee's shifts for selected date range
  - [ ] Shows total hours for period

#### Feature 13: Schedule Conflicts Detection
- **User Story:** As a manager, I want to be alerted to schedule conflicts so that I can resolve them proactively.
- **Acceptance Criteria:**
  - [ ] Dashboard shows conflict count if any exist
  - [ ] Conflicts include: overlapping shifts, overtime threshold exceeded
  - [ ] Can tap to see conflict details and resolve

#### Feature 14: Quick Actions from Notifications
- **User Story:** As a manager, I want to approve/deny requests directly from push notifications so that I can respond without opening the app.
- **Acceptance Criteria:**
  - [ ] Rich notification shows request summary
  - [ ] Action buttons: "Approve" and "View Details"
  - [ ] Approve action works from notification (iOS/Android)

### Won't Have (This Phase)

1. **Clock In/Out Functionality** - Employees use BuyerKiosk Team app for time punches
2. **Employee Self-Service Requests** - Swap/time-off requests made in Team app
3. **Schedule Publishing** - Publishing schedules remains a web-only feature
4. **Schedule Copy Week** - Copying schedules week-to-week stays on web
5. **Team Notifications** - Bulk notifications to team remain on web
6. **Availability Management** - Employee availability editing stays in Team app
7. **Pay Period Reporting** - Detailed payroll reports remain on web

## Detailed Feature Specifications

### Feature: Pending Request Approval (Most Complex)
**Description:** Unified view where managers can see all pending requests that need their attention, review details, and take action. This is the core workflow that replaces the web portal for daily request management.

**User Flow:**
1. Manager navigates to Scheduling → Pending Requests (or taps pending count on dashboard)
2. System displays list of pending requests, newest first
3. Manager taps a request to see full details
4. System shows request detail sheet with:
   - Employee name and photo (if available)
   - Request type badge (Time Off / Shift Swap / Clock Override)
   - For Time Off: dates, type (vacation/sick/personal), reason
   - For Shift Swap: both shifts side-by-side, any conflicts highlighted
   - For Override: requested punch type, time, reason, location (if provided)
5. Manager taps "Approve" or "Deny"
6. If Deny: optional note modal appears
7. System processes request, shows success/error
8. System sends push notification to employee(s)
9. Request moves to history, list refreshes

**Business Rules:**
- Rule 1: Only managers (role >= Manager) can see pending requests
- Rule 2: Shift swaps require both employees' shifts to be in the future
- Rule 3: Clock overrides must include a reason from the employee
- Rule 4: Time-off requests cannot be approved if overlapping with already-approved time-off
- Rule 5: Approving a shift swap automatically updates both employees' schedules
- Rule 6: Request expires after configured time (shown as "Expired" status if applicable)
- Rule 7: Self-approval of time-off is controlled by store setting (`allow_self_approval`)
- Rule 8: All approval actions must capture audit trail (device ID, location, timestamp)
- Rule 9: Batch processing limited to maximum 10 requests per action

**Edge Cases:**
- Scenario: Request was already processed by another manager → Expected: Show "Already processed" message, remove from list
- Scenario: Shift being swapped was deleted → Expected: Show error "Shift no longer exists", auto-deny request
- Scenario: Network error during approval → Expected: Show retry option, don't mark as processed
- Scenario: Manager tries to approve their own time-off request → Expected: Check store `allow_self_approval` setting; if enabled, allow; if disabled, show "Cannot approve your own request" message
- Scenario: Store switched while approval action in progress → Expected: Cancel pending action, refresh data for new store
- Scenario: Quick action from notification when session expired → Expected: Show login screen, after login navigate to request detail
- Scenario: Quick action from notification for different store → Expected: Switch store context, show request detail
- Scenario: Timezone mismatch (device vs store) → Expected: All schedule times displayed in store timezone with clear indicator
- Scenario: Large request list (100+ items) → Expected: Paginate with 20 items per page, show loading indicator
- Scenario: Location permission denied → Expected: Proceed with approval, capture null for location in audit trail

### Feature: JWT Authentication Migration
**Description:** Replace the current API key authentication with email/password login using JWT tokens, matching the authentication flow used in the BuyerKiosk Team app.

**User Flow:**
1. User opens app (first time after update)
2. If user had API key stored: Show migration screen explaining the change
3. System displays login screen with email and password fields
4. User enters credentials and taps "Sign In"
5. System validates credentials against `/auth/login`
6. On success: Store access token (15 min TTL) and refresh token (30 day TTL)
7. System displays store selection if user has access to multiple stores
8. User selects a store
9. System prompts to enable biometric authentication
10. User lands on dashboard with full access

**Business Rules:**
- Rule 1: Access tokens expire after 15 minutes and auto-refresh
- Rule 2: Refresh tokens expire after 30 days, requiring re-login
- Rule 3: Failed login attempts should show specific error (invalid credentials vs account locked)
- Rule 4: Device fingerprint is captured for security tracking
- Rule 5: FCM token is registered after successful login for push notifications

**Edge Cases:**
- Scenario: User has no stores assigned → Expected: Show "No store access" error, contact admin
- Scenario: Refresh token expired while app in background → Expected: Show login screen on next open
- Scenario: Account disabled mid-session → Expected: API returns 403, force logout, show message
- Scenario: Password changed on another device → Expected: Refresh fails, require re-login

## Success Metrics

### Key Performance Indicators

- **Adoption:** 80% of managers use mobile app for approvals within 3 months of launch
- **Engagement:** Average 5+ approval actions per manager per week
- **Speed:** Average request approval time reduced from 4 hours to 30 minutes (measured as request_created → approval event, 30-day rolling median)
- **Quality:** <2% error rate on approval actions (errors ÷ total approval attempts)
- **Satisfaction:** Manager NPS score for scheduling features > 40
- **Migration:** 90% JWT migration completion within 60 days of release
- **Biometric Opt-in:** 70% of users enable biometric authentication

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| `auth_login_started` | `auth_method: password\|biometric` | Track login attempts |
| `auth_login_success` | `store_count, auth_method, device_type` | Measure successful logins |
| `auth_login_failed` | `error_code, auth_method` | Debug login issues |
| `store_selected` | `store_id, store_count` | Track multi-store usage |
| `dashboard_viewed` | `pending_count, store_id` | Measure dashboard engagement |
| `request_list_viewed` | `request_count, filter_type` | Track request queue usage |
| `request_detail_viewed` | `request_type, request_id` | Track detail views |
| `request_approved` | `request_type, request_id, batch_size, device_id, location_lat, location_lng` | Track approvals with audit trail |
| `request_denied` | `request_type, request_id, has_note, device_id, location_lat, location_lng` | Track denials with audit trail |
| `batch_action_completed` | `action_type, count, success_count` | Track batch efficiency |
| `whos_working_viewed` | `employee_count, clocked_in_count` | Track staffing views |
| `my_schedule_viewed` | `shift_count` | Track self-schedule usage |
| `shift_created` | `is_open_shift, has_conflicts` | Track shift creation |
| `shift_updated` | `fields_changed` | Track shift edits |
| `shift_deleted` | `reason_provided` | Track deletions |
| `labor_cost_viewed` | `week_offset, has_budget` | Track labor views |

---

## Permission Matrix

| Action | Owner | Manager | Assistant Manager | Employee |
|--------|-------|---------|-------------------|----------|
| View Manager Dashboard | ✓ | ✓ | ✓ | ✗ |
| Approve/Deny Requests | ✓ | ✓ | ✓ | ✗ |
| Batch Approve Requests | ✓ | ✓ | ✗ | ✗ |
| View Who's Working | ✓ | ✓ | ✓ | ✗ |
| View My Schedule | ✓ | ✓ | ✓ | ✗ |
| Create/Edit/Delete Shifts | ✓ | ✓ | ✗ | ✗ |
| View Labor Costs | ✓ | ✓ | ✗ | ✗ |
| Switch Stores | ✓ | ✓ (own stores) | ✓ (own stores) | ✗ |
| Configure Store Settings | ✓ | ✗ | ✗ | ✗ |

**Note:** Employees use the BuyerKiosk Team app for schedule viewing and request submission.

## UX State Handling

All scheduling screens must handle these states consistently:

| State | Behavior |
|-------|----------|
| **Loading** | Show centered spinner with subtle animation; skeleton loaders for lists |
| **Empty** | Show friendly illustration + message (e.g., "No pending requests - you're all caught up!") |
| **Error** | Show error message with "Retry" button; include error code for support |
| **Offline** | Show "No connection" banner at top; disable action buttons; show cached data if available |
| **Partial Load** | Show loaded content + loading indicator for pagination |

## Constraints and Assumptions

### Constraints
- **API Dependency:** All scheduling features require the Mobile Scheduling API (documented in `docs/api/mobile-scheduling-openapi.yaml`)
- **Platform Support:** Must support iOS 14+ and Android 8+
- **Offline:** No offline support for this phase - requires network connectivity; show clear "No connection" error state
- **Existing Features:** Cannot break existing store metrics, queue, completed buys functionality
- **Timeline:** Target release ASAP (Q1 2025)
- **Feature Flag Rollout:** Mobile scheduling access controlled by feature flag for gradual rollout

### Assumptions
- The Mobile Scheduling API is production-ready and matches the OpenAPI spec
- All managers already have user accounts in the system (same credentials as web portal)
- Push notifications (FCM) infrastructure is already configured
- Store timezone configuration exists and is accurate
- Labor cost/budget data is available via the API for stores that use it

### Dependencies
- **Location Services:** Optional location permission for audit trail (iOS Core Location, Android Fused Location)
- **Secure Storage:** flutter_secure_storage for JWT token storage
- **Biometric Auth:** local_auth package for Face ID/Touch ID support (iOS 11+, Android 6+)
- **Push Actions:** iOS/Android notification action support for quick approvals from notifications
- **API SLA:** Mobile Scheduling API must maintain 99.5% uptime, <500ms p95 response time

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| API not ready for production | High | Medium | Coordinate with backend team on API readiness, test against dev environment |
| Users confused by auth migration | Medium | Medium | Clear migration messaging, support documentation, gradual rollout |
| Biometric auth issues on older devices | Low | Low | Graceful fallback to password, device compatibility testing |
| Request conflicts from concurrent approvals | Medium | Low | API handles conflicts, show clear error messages |
| Performance issues with large request lists | Medium | Low | Implement pagination, lazy loading |
| Push notification delivery failures | Medium | Medium | Fallback to in-app notification center, retry logic |

## Open Questions

- [x] Should managers be able to approve their own time-off requests? → **RESOLVED: Store setting controls this (`allow_self_approval`)**
- [x] Should we track device/location when manager takes approval actions (audit trail)? → **RESOLVED: Yes, full audit trail (device ID, location if available, timestamp)**
- [x] What happens to existing API key after migration? → **RESOLVED: Immediate server-side invalidation upon successful JWT login**
- [x] Is there a maximum number of requests that can be batch-processed? → **RESOLVED: Cap at 10 requests per batch action**
- [x] What is the target release date/timeline? → **RESOLVED: ASAP (Q1 2025)**
- [x] Are there any stores that should NOT have mobile scheduling access? → **RESOLVED: Feature flag rollout - gradual enablement for pilot stores first**
- [x] How do mobile shift edits relate to schedule publishing? → **RESOLVED: Same as web - immediate for published weeks, draft for unpublished**
- [x] What if location permission is denied? → **RESOLVED: Soft prompt, allow proceeding without (capture null)**

---

## Supporting Research

### Competitive Analysis
- **7shifts:** Mobile-first scheduling with approval workflows, highly rated UX
- **When I Work:** Strong manager mobile app, batch approvals, labor forecasting
- **Homebase:** Simple approval flow, good notification system
- **Key Insight:** All major competitors have robust mobile manager experiences; BuyerKiosk Live is catching up to market standard

### User Research
- Existing managers report frustration with web-only approvals
- Average time to approve requests is 4+ hours due to web portal access delays
- 85% of managers check BuyerKiosk Live app daily for store metrics
- Request from franchise owners to manage multiple stores more efficiently

### Market Data
- Mobile workforce management market growing 15% annually
- 78% of retail managers prefer mobile apps for quick administrative tasks
- Average retail manager handles 3-5 schedule-related requests per day
