# Product Requirements Document: AI Smart Scheduling

## 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 store managers to create optimal employee schedules in minutes instead of hours by leveraging AI to intelligently match employees to shifts while respecting availability, fairness, labor costs, and operational requirements.

### Problem Statement
Store managers spend 2-4 hours per week manually creating schedules. This process involves:
- Cross-referencing employee availability for each shift
- Balancing hours fairly across team members
- Ensuring proper position coverage (buyers, cashiers, shift leads)
- Calculating overtime implications
- Making sure opening/closing shifts have keyed employees
- Accommodating time-off requests

The manual process is error-prone, time-consuming, and often results in suboptimal schedules that either overspend on labor or leave employees frustrated with unfair hour distribution. When managers are rushed, they default to "whoever is available" rather than optimizing for the business or employee satisfaction.

### Value Proposition
AI Smart Scheduling transforms a 2-4 hour manual task into a 5-minute review process:
- **For Managers:** One-click schedule generation that respects all constraints, with granular control to accept/reject individual assignments
- **For Employees:** Fairer hour distribution based on their requested hours, with availability always respected
- **For Owners:** Optimized labor costs while maintaining service levels, with future predictive scheduling based on historical demand data

---

## User Personas

### Primary Persona: Store Manager
- **Demographics:** 25-45 years old, manages a buy/sell retail store, moderate technical proficiency, typically handles scheduling weekly
- **Goals:**
  - Create a complete weekly schedule quickly
  - Ensure all shifts are covered by qualified employees
  - Keep labor costs within budget
  - Keep employees happy with fair hours
  - Avoid overtime surprises
- **Pain Points:**
  - Spends hours cross-referencing availability
  - Difficult to balance everyone's requested hours
  - Frequently forgets who has keys for open/close
  - Overtime sneaks up mid-week
  - Last-minute changes cascade into rework

### Secondary Persona: Store Owner
- **Demographics:** 30-60 years old, may own multiple stores, focused on profitability and operations
- **Goals:**
  - Minimize labor costs while maintaining service quality
  - Understand staffing patterns and efficiency
  - Plan for seasonal demand changes
  - Reduce manager workload on administrative tasks
- **Pain Points:**
  - No visibility into scheduling efficiency across stores
  - Can't correlate staffing levels with sales performance
  - Reactive rather than proactive staffing decisions
  - Inconsistent scheduling quality across managers

### Secondary Persona: Multi-Store Owner (Future)
- **Demographics:** Owns 3+ stores, relies heavily on data and automation
- **Goals:**
  - Standardize scheduling practices across stores
  - Compare staffing efficiency between locations
  - Predictive staffing based on demand forecasting
- **Pain Points:**
  - Each store schedules differently
  - No centralized view of staffing metrics
  - Can't identify over/under-staffing patterns

---

## User Journey Maps

### Primary User Journey: Weekly Schedule Creation

1. **Awareness:** Manager realizes it's time to create next week's schedule (typically 1-2 weeks ahead)

2. **Preparation:** Manager navigates to the scheduling calendar view for the target week
   - Reviews any existing shifts (manager recurring schedules, pre-assigned shifts)
   - Either loads a shift template with open shifts OR manually adds open shifts to the calendar

3. **AI Generation:** Manager clicks "Generate with AI" button
   - Sees a configuration dialog with:
     - Optimization priority selector (labor cost, hours fairness, seniority, position coverage)
     - Custom instructions text field for special considerations
     - Per-owner toggles (with availability status indicators)
     - "Include owners in scheduling" options
   - Clicks "Generate Schedule"

4. **Review:** AI presents proposed schedule in preview mode
   - Each proposed assignment shows employee name, shift details, and accept/reject checkbox
   - Expandable "Why this assignment?" details on demand
   - Summary statistics (total labor cost, hours distribution, unfilled shifts)
   - All proposed assignments are pre-checked for acceptance

5. **Refinement:** Manager reviews and adjusts
   - Unchecks assignments they want to reject
   - Views reasoning for any questionable assignments
   - Notes any unfilled shifts that remain as open shifts

6. **Application:** Manager clicks "Apply Selected Assignments"
   - Confirmed assignments are committed to the schedule
   - Rejected and unfilled shifts remain as open shifts for manual handling or employee claiming

7. **Post-Processing:** Manager handles remaining open shifts manually and publishes the schedule

### Secondary User Journey: Re-optimization

1. **Trigger:** Manager has applied an AI schedule but wants to try different optimization settings

2. **Action:** Manager clicks "Regenerate with AI" on the same week

3. **Warning:** System warns "This will replace X existing AI assignments. Continue?"

4. **Flow:** If confirmed, returns to AI Generation step with current settings as defaults

### Secondary User Journey: Historical Data Analysis (Future Phase)

1. **Trigger:** Owner wants to understand staffing efficiency

2. **Action:** Navigates to staffing analytics dashboard

3. **Insights:** Views hourly staffing levels correlated with:
   - Buy wait times
   - Sales volume
   - Buy transaction count

4. **Outcome:** Makes informed decisions about template adjustments

---

## Feature Requirements

### Must Have Features

#### Feature 1: AI Schedule Generation
- **User Story:** As a store manager, I want to generate employee assignments for open shifts using AI so that I can create optimized schedules in minutes instead of hours
- **Acceptance Criteria:**
  - [ ] Manager can trigger AI generation from calendar view for any week
  - [ ] AI considers: employee availability, time-off requests, role qualifications, requested hours, max hours, min hours, pay rates
  - [ ] AI respects existing assigned shifts (doesn't reassign them)
  - [ ] AI fills open shifts only - doesn't create new shifts
  - [ ] Generation completes within 30 seconds
  - [ ] If AI can't fill a shift, it remains as an open shift

#### Feature 2: Optimization Priority Selection
- **User Story:** As a store manager, I want to choose what the AI optimizes for so that the schedule aligns with my current priorities
- **Acceptance Criteria:**
  - [ ] User can select from: Labor cost minimization, Hours fairness, Seniority preference, Position coverage first
  - [ ] Multiple priorities can be selected (ranked order)
  - [ ] User can add free-text custom instructions for the AI
  - [ ] Settings are remembered as defaults for future generations

#### Feature 3: Role-Based Qualification Matching
- **User Story:** As a store manager, I want the AI to only assign employees to shifts they're qualified for so that I don't have to manually verify qualifications
- **Acceptance Criteria:**
  - [ ] Cashiers (Role 1) can only be assigned to sales/maintenance positions
  - [ ] Buyers (Role 2) can be assigned to sales or buy-side positions but not opening/closing shifts
  - [ ] Shift Leads (Role 3+) can be assigned to any shift including opening/closing
  - [ ] Opening shift (first of day) requires Role 3+ unless manually overridden
  - [ ] Closing shift (last of day) requires Role 3+ unless manually overridden

#### Feature 4: Preview and Accept/Reject Interface
- **User Story:** As a store manager, I want to review AI proposals before they're applied so that I maintain control over the final schedule
- **Acceptance Criteria:**
  - [ ] All proposed assignments shown in preview before applying
  - [ ] Each assignment has individual accept/reject checkbox
  - [ ] Expandable "reasoning" for each assignment on demand
  - [ ] Summary shows: total shifts, labor cost estimate, hours distribution
  - [ ] "Apply Selected" commits only checked assignments
  - [ ] Rejected assignments return to open shift status

#### Feature 5: Employee Hours Management
- **User Story:** As a store manager, I want to set requested hours, max hours, and min hours for each employee so that the AI can optimize fairly
- **Acceptance Criteria:**
  - [ ] Manager can set hoursRequested, hoursMax, minHours per user in admin
  - [ ] Values stored in global users database (not deprecated employee table)
  - [ ] Manager can override these values per-schedule in the AI dialog
  - [ ] Empty/0 hoursRequested = flexible (no target, schedule as needed)
  - [ ] AI respects hoursMax as hard cap
  - [ ] AI tries to meet minHours when possible

#### Feature 6: Overtime-Aware Scheduling
- **User Story:** As a store manager, I want the AI to consider overtime implications so that I avoid unexpected labor cost spikes
- **Acceptance Criteria:**
  - [ ] AI considers hours already scheduled in current pay period
  - [ ] AI applies weekly overtime threshold (40 hrs default)
  - [ ] AI applies daily overtime threshold where applicable (8 hrs/day)
  - [ ] Overtime rules are configurable per store
  - [ ] Preview shows estimated overtime hours per employee

#### Feature 7: Owner Inclusion Controls
- **User Story:** As a store manager, I want to choose which owners to include in AI scheduling so that I can accommodate varying owner involvement levels
- **Acceptance Criteria:**
  - [ ] AI generation dialog shows list of all owners for the store
  - [ ] Each owner has a toggle to include/exclude from scheduling
  - [ ] Each owner shows availability status indicator (available/unavailable/partial)
  - [ ] By default, owners are excluded from AI scheduling
  - [ ] Owners with no availability set show as "No availability data"

#### Feature 8: Manager Schedule Locking
- **User Story:** As a store manager, I want manager recurring schedules to be locked so that the AI doesn't reassign established management shifts
- **Acceptance Criteria:**
  - [ ] Managers with recurring schedules have those shifts treated as "locked"
  - [ ] AI considers locked shifts for labor cost calculations
  - [ ] AI does not propose changes to locked shifts
  - [ ] Locked shifts display differently in preview (greyed out, not editable)

#### Feature 9: Usage Rate Limiting
- **User Story:** As a system administrator, I want to limit AI scheduling runs to control API costs
- **Acceptance Criteria:**
  - [ ] Maximum 5 AI generation runs per pay week per store
  - [ ] Counter resets at start of each pay week
  - [ ] User sees remaining runs available
  - [ ] Clear error message when limit reached
  - [ ] Store admins/owners can see usage across their stores

### Should Have Features

#### Feature 10: AI Reasoning Display
- **User Story:** As a store manager, I want to understand why the AI made specific assignments so that I can trust or override its decisions
- **Acceptance Criteria:**
  - [ ] Each assignment has expandable "Why?" section
  - [ ] Reasoning includes: availability match, hours toward target, cost factor, position qualification
  - [ ] Conflicting factors are explained (e.g., "Lower rate than Sarah but Sarah at max hours")

#### Feature 11: Historical Data Collection - Staffing Levels
- **User Story:** As a store owner, I want the system to track hourly staffing levels so that future AI can make demand-based predictions
- **Acceptance Criteria:**
  - [ ] System records employee count per hour (by position)
  - [ ] Data collected via TaskEngine background job
  - [ ] Hourly granularity (9am-10am, 10am-11am, etc.)
  - [ ] 90-day backfill from existing time punch data
  - [ ] Rolling 1-year retention

#### Feature 12: Historical Data Collection - Performance Metrics
- **User Story:** As a store owner, I want the system to track hourly sales and buy metrics so that future AI can correlate staffing with performance
- **Acceptance Criteria:**
  - [ ] System records hourly: sales volume ($), transaction count, buy count
  - [ ] System records hourly: average buy wait time
  - [ ] Data collected via TaskEngine background job
  - [ ] 90-day backfill where data exists
  - [ ] Rolling 1-year retention

#### Feature 13: Full AI Session Logging
- **User Story:** As a system administrator, I want complete logs of AI scheduling sessions so that I can debug issues and improve the system
- **Acceptance Criteria:**
  - [ ] Log includes: prompt sent to AI, AI response, applied assignments, rejected assignments
  - [ ] Log includes: manual changes made after AI application
  - [ ] Logs tied to store/user/timestamp
  - [ ] Logs accessible to admins for debugging

### Could Have Features

#### Feature 14: Shift Preference Learning
- **User Story:** As an AI system, I want to learn from manager accept/reject patterns so that future suggestions improve over time
- **Acceptance Criteria:**
  - [ ] Track accept/reject rates per employee-shift-type combination
  - [ ] Surface patterns to managers ("You frequently reject Sarah for morning shifts")
  - [ ] Adjust AI weighting based on historical patterns

#### Feature 15: Multi-Week Scheduling
- **User Story:** As a store manager, I want to generate schedules for multiple weeks at once so that I can plan ahead efficiently
- **Acceptance Criteria:**
  - [ ] Option to generate 2-4 weeks at once
  - [ ] Each week previewed separately
  - [ ] Can accept/reject per week or per shift

#### Feature 16: Demand-Based Shift Recommendations (Future)
- **User Story:** As a store manager, I want the AI to recommend how many shifts I need based on historical demand so that I don't need to guess
- **Acceptance Criteria:**
  - [ ] AI analyzes historical hourly data (staffing, sales, wait times)
  - [ ] AI suggests optimal shift template for target week
  - [ ] Considers day-of-week patterns, seasonal trends
  - [ ] Manager can accept/modify recommendations before generation

### Won't Have (This Phase)

- **Demand-based auto-template generation** - Future phase when historical data is collected
- **Cross-store optimization** - Each store scheduled independently
- **Employee self-scheduling** - Employees can claim open shifts but not self-assign
- **Consecutive days off enforcement** - Future enhancement
- **Shift swap AI recommendations** - Swap requests handled manually
- **Integration with external scheduling systems** - BuyerKiosk native scheduling only
- **Mobile AI scheduling interface** - Web only for V1
- **Automatic schedule publishing** - Manager must manually publish after AI application

---

## Detailed Feature Specifications

### Feature: AI Schedule Generation (Core Feature)

**Description:** The core AI scheduling engine that takes open shifts, employee data, and optimization preferences to produce optimal employee-to-shift assignments.

**User Flow:**
1. Manager views calendar for target week
2. Manager ensures open shifts exist (via template or manual creation)
3. Manager clicks "Generate with AI" button
4. System opens configuration dialog:
   - Optimization priorities (multi-select, ranked)
   - Custom instructions (free text)
   - Owner inclusion toggles (per-owner with status)
5. Manager clicks "Generate"
6. System shows loading state (max 30 seconds)
7. System displays preview with proposed assignments
8. Manager reviews, unchecks unwanted assignments
9. Manager clicks "Apply Selected"
10. System commits checked assignments, returns rejected to open shift status

**Business Rules:**

- **Rule 1:** AI only assigns to existing open shifts - never creates new shifts
- **Rule 2:** AI respects existing assigned shifts - never reassigns them
- **Rule 3:** AI respects role qualifications:
  - Role 1 (Cashier): Sales/maintenance positions only
  - Role 2 (Buyer): Sales + buy positions, no opening/closing
  - Role 3+ (Shift Lead/Manager): All positions including opening/closing
- **Rule 4:** Opening shift = first shift of day; Closing shift = last shift of day
- **Rule 5:** AI respects employee availability windows (day + start/end time)
- **Rule 6:** AI respects approved time-off requests
- **Rule 7:** AI considers current pay period hours for overtime calculations
- **Rule 8:** Manager recurring schedules are locked (visible but not editable)
- **Rule 9:** Owners excluded by default unless explicitly toggled on
- **Rule 10:** Empty/0 hoursRequested = flexible scheduling
- **Rule 11:** hoursMax is a hard cap - never exceeded
- **Rule 12:** 5 AI runs per pay week limit per store

**Edge Cases:**

- **Not enough available employees:** Unfilled shifts remain as open shifts. No error - just noted in summary.
- **All employees at max hours:** Shifts remain open. Summary warns "X employees at max hours"
- **No employees with key access for opening:** Shift remains open. Warning shown.
- **Overtime unavoidable:** AI still assigns but clearly flags overtime in preview
- **API timeout/failure:** Immediate error displayed, no partial results applied
- **Conflicting availability data:** Use most recent availability record
- **Employee terminated mid-process:** Skip that employee, continue with others
- **All optimization criteria conflict:** Position coverage takes precedence, then follow user's ranked order
- **Custom instructions conflict with hard rules:** Hard rules always win (availability, max hours, role qualification)

---

## Success Metrics

### Key Performance Indicators

- **Adoption:** 70% of stores use AI scheduling within 3 months of launch
- **Engagement:** Average 3 AI generations per store per month (of 20 allowed)
- **Acceptance Rate:** 85% of AI-proposed assignments are accepted without modification
- **Time Savings:** Manager scheduling time reduced from 2-4 hours to under 30 minutes (surveyed)
- **Quality:** Schedule-related complaints from employees decrease by 25%
- **Business Impact:** Labor cost variance from budget reduced by 15%

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| ai_schedule_started | storeId, weekStart, optimizations[], includeOwners | Track configuration preferences |
| ai_schedule_completed | storeId, duration, proposedCount, errorType? | Measure success rate and performance |
| ai_schedule_assignment_accepted | storeId, shiftId, employeeId, position, reasoning | Track acceptance patterns |
| ai_schedule_assignment_rejected | storeId, shiftId, employeeId, position, reasoning | Identify improvement opportunities |
| ai_schedule_applied | storeId, acceptedCount, rejectedCount, unfilledCount, totalLaborCost | Measure net value delivered |
| ai_schedule_limit_reached | storeId, runsUsed, payWeekStart | Monitor rate limit impact |
| staffing_hourly_snapshot | storeId, hour, positionCounts{}, salesVolume, buyCount, avgWaitTime | Enable future predictive features |

---

## Constraints and Assumptions

### Constraints

- **API Cost:** OpenAI API calls have per-token costs; rate limiting at 5/pay-week controls expenses
- **Model Dependency:** System relies on OpenAI API availability; no fallback algorithm in V1
- **Data Quality:** AI quality depends on accurate availability and time-off data entry
- **Role System:** Must use existing 1-5 role system; no custom qualifications in V1
- **Global Users:** Must use global users database; deprecated store-level employee table not supported

### Assumptions

- **Data Availability:** Stores have employee availability data entered
- **Template Usage:** Managers are comfortable creating/using shift templates with open shifts
- **AI Trust:** Managers will review AI suggestions rather than blindly accepting
- **Pay Period Config:** Stores have pay period configuration set for overtime calculations
- **OpenAI Reliability:** OpenAI API maintains 99%+ uptime during business hours

---

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| AI produces poor quality schedules | High | Medium | Preview mode with accept/reject; reasoning display; user feedback loop |
| OpenAI API costs exceed budget | Medium | Low | Rate limiting (5/pay-week); .env model configuration for cost control |
| Managers don't trust AI suggestions | High | Medium | Transparent reasoning; gradual adoption; high accept rate target |
| Availability data is incomplete | High | Medium | Show warnings for employees without availability; encourage data entry |
| API latency causes poor UX | Medium | Low | 30-second timeout; loading indicator; immediate error on failure |
| Rate limit frustrates power users | Medium | Low | Clear counter display; per-pay-week (not daily) limit |
| Historical data collection impacts performance | Medium | Low | TaskEngine background processing; off-peak scheduling |

---

## Open Questions

- [x] How are positions mapped to roles? → Use existing role (1-5) hierarchy
- [x] Where do hours preferences live? → Global users database with per-schedule override
- [x] What happens with unfilled shifts? → Remain as open shifts
- [x] How handle multiple owners? → Per-owner toggles with availability status
- [x] What data to collect for future? → Hourly staffing, sales, buy count, wait times
- [x] Rate limiting approach? → 5 runs per pay week per store

---

## Supporting Research

### Competitive Analysis

**WhenIWork:** Offers basic auto-scheduling but requires extensive setup. No AI/ML component - uses rule-based assignment. Users report it works for simple schedules but fails with complex constraints.

**Deputy:** Has "Auto-Scheduling" feature using demand forecasting. Requires 3+ months of historical data. Mixed reviews on accuracy. Premium pricing tier.

**Homebase:** No true auto-scheduling. Has "suggested shifts" based on past patterns. Limited optimization capabilities.

**Our Advantage:** Integration with existing BuyerKiosk data (buy wait times, sales, positions) enables unique optimization. GPT-based reasoning provides explainability competitors lack.

### User Research

Based on existing BuyerKiosk customer feedback:
- "Scheduling takes me all Sunday afternoon" - Store Manager, TX
- "I just want to give everyone fair hours without doing math" - Store Manager, CA
- "We're always short on openers because I forget who has keys" - Store Manager, FL
- "I'd pay extra for something that just... figures it out" - Store Owner, OH

### Market Data

- 60% of retail managers spend 3+ hours/week on scheduling (SHRM 2024)
- AI-assisted scheduling market growing 15% annually
- 78% of employees say schedule fairness affects job satisfaction
- Labor costs typically 20-30% of retail store operating expenses
