# Product Requirements Document

## Validation Checklist

- [x] All required sections are complete
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Problem statement is specific and measurable (30-45 min weekly, conflicts after publish)
- [x] Problem is validated by evidence (existing UI/backend disconnect mentioned, Copy Previous Week limitations)
- [x] Context → Problem → Solution flow makes sense
- [x] Every persona has at least one user journey (Sarah: 4 journeys, Marcus/James referenced)
- [x] All MoSCoW categories addressed (8 Must Have, 4 Should Have, 4 Could Have, 8 Won't Have)
- [x] Every feature has testable acceptance criteria
- [x] Every metric has corresponding tracking events (8 events defined)
- [x] No feature redundancy (checked - no duplicates)
- [x] No contradictions between sections
- [x] No technical implementation details included (data sources referenced but no code)
- [x] A new team member could understand this PRD

---

## Product Overview

### Vision
Empower store managers to build schedules in minutes instead of hours by providing reusable templates, intelligent conflict detection, and contextual overlays that surface employee availability, time-off requests, and historical business patterns directly on the scheduling calendar.

### Problem Statement
Store managers using BuyerKiosk's native scheduling (Spec 013) currently face several time-consuming challenges:

1. **Repetitive Schedule Building**: Managers rebuild similar schedules week after week. While "Copy Previous Week" exists, it doesn't account for recurring patterns (e.g., a manager who always works Mon/Wed/Fri) or event-specific staffing needs.

2. **Hidden Conflicts**: When scheduling, managers can't see employee availability preferences or approved time-off at a glance. This leads to:
   - Scheduling employees during their unavailable times
   - Scheduling over approved time-off (requiring rework)
   - Phone calls/texts to verify availability

3. **Scheduling Blind to Business Patterns**: Managers schedule based on memory rather than data. They can't see:
   - Which days/times historically had long customer wait times
   - Sales patterns that indicate high-traffic periods
   - How busy an upcoming day is expected to be

4. **Template Inflexibility**: No way to save "busy day" or "holiday" staffing patterns. Every event requires manual schedule building.

5. **Repeat Shift UI Disconnect**: The UI supports repeat shift configuration, but backend/calendar behavior may not properly handle recurring patterns.

**Consequences:**
- 30-45 minutes spent weekly rebuilding schedules
- Scheduling conflicts discovered after schedule is published
- Understaffed during unexpectedly busy periods
- Employee frustration when scheduled during unavailable times
- Manager time spent resolving conflicts instead of managing store

### Value Proposition
Schedule Templates & Overlays transforms schedule creation from a weekly chore into a strategic advantage:

1. **One-Click Week Setup**: Save any week as a template, load it in seconds, automatically handling employee departures as open shifts
2. **Conflict Prevention**: See availability, time-off, and blocking requests before scheduling - prevent conflicts, don't just detect them
3. **Data-Driven Staffing**: Overlay historical wait times and sales data on the calendar to staff appropriately for expected demand
4. **Event-Ready Scheduling**: Load special templates (busy day, sale, holiday) through the event system
5. **Repeat Shift Reliability**: Recurring shifts work consistently across calendar and backend

## User Personas

### Primary Persona: Store Manager (Sarah)
- **Demographics:** 28-45 years old, manages 10-25 employees, creates weekly schedules, moderate technical expertise
- **Goals:**
  - Build next week's schedule in under 10 minutes
  - Avoid scheduling conflicts with availability/time-off
  - Staff appropriately for expected business levels
  - Handle special events (sales, busy periods) without rebuilding schedules from scratch
- **Pain Points:**
  - Spends 30+ minutes weekly recreating similar schedules
  - Discovers conflicts after publishing (employee unavailable, has approved time-off)
  - Guesses at staffing needs - no visibility into historical patterns
  - When an employee leaves, their template shifts become invalid

### Secondary Personas

#### Shift Lead (Marcus)
- **Demographics:** 22-35, key holder, views schedules daily
- **Goals:**
  - Quickly see who's working with them
  - Understand coverage during peak times
  - Know when they're working next
- **Pain Points:**
  - Doesn't know when busy periods are expected
  - Can't see if coverage is adequate for anticipated demand

#### Store Owner (James)
- **Demographics:** 40-55, operates 1-3 stores, reviews schedules weekly
- **Goals:**
  - Ensure labor is aligned with expected revenue
  - Reduce scheduling-related complaints from staff
  - Standardize scheduling patterns across stores
- **Pain Points:**
  - Inconsistent staffing across locations
  - Can't quickly assess if schedule matches expected business
  - Time-off conflicts lead to last-minute scrambling

## User Journey Maps

### Primary User Journey: Template-Based Weekly Scheduling

1. **Awareness:** It's Thursday, Sarah needs next week's schedule. She remembers last week worked well.
2. **Consideration:** Sarah opens the scheduling calendar and clicks "Templates" - sees her saved "Standard Week" template
3. **Adoption:** Sarah loads the template. System notifies: "2 shifts assigned to Taylor (terminated) → converted to open shifts"
4. **Usage:**
   - Sarah toggles on "Availability" overlay - sees Marcus is unavailable Tuesday evening
   - Marcus's Tuesday shift shows yellow warning - Sarah drags it to an available employee
   - Sarah toggles on "Wait Time" overlay - sees Friday afternoons have historically high wait times
   - Sarah adds an additional shift Friday 2-6pm
5. **Retention:** Schedule built in 8 minutes with zero conflicts. Sarah saves this as "Updated Standard Week"

### Secondary User Journeys

#### Event-Based Schedule Loading Journey
1. Store has an upcoming "50% Off Sale" event created in the event system
2. When viewing schedule week containing the event, Sarah sees event indicator on calendar
3. Sarah clicks "Load Event Template" and selects "Big Sale Day" template she previously created
4. Template applies to event days, staffing automatically increased
5. Sarah makes minor adjustments and publishes

#### Availability-Aware Scheduling Journey
1. Sarah opens scheduling calendar for next week
2. Sarah enables "Availability & Time-Off" overlay
3. Calendar shows:
   - Green: Employee preferred/available times
   - Yellow: Employee available but not preferred
   - Red: Employee unavailable (recurring pattern)
   - Red striped: Approved time-off (blocking)
   - Orange dashed: Pending time-off request
4. Sarah schedules shifts, avoiding red/striped areas
5. If she creates a shift in a red zone, warning appears: "Conflicts with time-off request - convert to open shift?"

#### Analytics-Driven Staffing Journey
1. Sarah opens scheduling calendar and toggles "Business Insights" overlay
2. Calendar shows heat map intensity based on:
   - Historical wait times (darker = longer waits = need more staff)
   - Historical sales volume (higher = busier = need more staff)
3. Sarah notices Saturday 1-3pm shows deep red (high wait times last month)
4. Sarah adds an extra shift Saturday 12-4pm to provide coverage
5. Tooltip shows: "Average wait time: 8.5 min (last 4 Saturdays)"

## Feature Requirements

### Must Have Features

#### Feature 1: Schedule Template Save
- **User Story:** As a store manager, I want to save a week's schedule as a named template so that I can quickly recreate it for future weeks
- **Acceptance Criteria:**
  - [ ] "Save as Template" button available in week view when at least one shift exists
  - [ ] Save dialog prompts for template name (required) and description (optional)
  - [ ] Template names must be unique per store
  - [ ] Template stores: shift day-of-week, start time, end time, employee ID (nullable), position, open shift flag
  - [ ] Saving a template with same name as existing prompts to overwrite or cancel
  - [ ] Templates are visible only to users with scheduling permission
  - [ ] Template count limit per store: 20 templates

#### Feature 2: Schedule Template Load
- **User Story:** As a store manager, I want to load a saved template to the current week so that I can set up schedules quickly
- **Acceptance Criteria:**
  - [ ] "Load Template" button available in week view
  - [ ] Template picker shows all saved templates with name, description, shift count
  - [ ] Loading shows preview of shifts that will be created
  - [ ] Option: "Replace current schedule" or "Merge with existing"
  - [ ] "Replace" deletes all current week shifts, then creates template shifts
  - [ ] "Merge" adds template shifts, warns of conflicts with existing shifts
  - [ ] Load operation completes within 3 seconds for up to 100 shifts

#### Feature 3: Template Employee Handling
- **User Story:** As a store manager, I want the system to handle employees who have left since the template was created so that templates remain usable
- **Acceptance Criteria:**
  - [ ] When loading template, check each employee ID against current active employees
  - [ ] If employee is inactive/terminated, convert their shifts to open shifts
  - [ ] Notification shown: "X shifts converted to open shifts (employee no longer active)"
  - [ ] Original employee name shown in notification for context
  - [ ] Manager can choose to cancel load if too many employees missing

#### Feature 4: Load Template as All Open Shifts
- **User Story:** As a store manager, I want an option to load a template with all shifts as open shifts so that I can let employees claim them
- **Acceptance Criteria:**
  - [ ] "Load as Open Shifts" checkbox available in template load dialog
  - [ ] When checked, all shifts created with employee = null, marked as open
  - [ ] Open shifts display distinctly on calendar (different color/pattern)
  - [ ] Open shift claims follow existing claim policy (from Spec 023)

#### Feature 5: Employee Availability Overlay
- **User Story:** As a store manager, I want to see employee availability patterns on the calendar so that I can schedule when employees are available
- **Acceptance Criteria:**
  - [ ] "Availability" toggle in calendar toolbar enables overlay
  - [ ] Overlay shows each employee's weekly availability pattern from `scheduleAvailability` table
  - [ ] Available times show green shading
  - [ ] Unavailable times show red shading
  - [ ] Preferred times (if tracked) show darker green
  - [ ] Overlay updates when date range changes
  - [ ] Overlay visible in Timeline Week view (primary view)

#### Feature 6: Time-Off Request Overlay
- **User Story:** As a store manager, I want to see time-off requests on the calendar so that I don't schedule over approved time off
- **Acceptance Criteria:**
  - [ ] Time-off requests from `scheduleTimeOffRequests` displayed on calendar
  - [ ] Approved time-off shown as red striped blocks (blocking - cannot schedule over)
  - [ ] Pending time-off shown as orange dashed blocks (warning - may conflict)
  - [ ] Denied time-off not shown
  - [ ] Clicking time-off block shows details: employee, request type, dates, status
  - [ ] Time-off overlay can be combined with availability overlay

#### Feature 7: Template Conflict Detection on Load
- **User Story:** As a store manager, I want the system to detect conflicts when loading a template so that I don't accidentally schedule over time-off or unavailable times
- **Acceptance Criteria:**
  - [ ] On template load, check each shift against:
    - Employee availability patterns
    - Approved time-off requests
    - Exception dates
  - [ ] Conflicting shifts highlighted in preview
  - [ ] Options per conflict: "Skip", "Create as Open Shift", "Create Anyway"
  - [ ] Bulk option: "Convert all conflicts to open shifts"
  - [ ] Summary shown: "X of Y shifts loaded, Z converted to open, W skipped"

#### Feature 8: Template Management
- **User Story:** As a store manager, I want to manage my saved templates so that I can keep them organized and up-to-date
- **Acceptance Criteria:**
  - [ ] "Manage Templates" option in templates menu
  - [ ] List view shows all templates: name, description, shift count, last used, created date
  - [ ] Edit template name and description
  - [ ] Delete template with confirmation
  - [ ] Preview template shifts without loading
  - [ ] Templates sorted by last used (most recent first)

### Should Have Features

#### Feature 9: Repeat/Recurring Shift Support (ELEVATED TO MUST HAVE)
- **User Story:** As a store manager, I want to create shifts that repeat on specific days every week so that regular schedules are automatically maintained
- **Acceptance Criteria:**
  - [ ] When creating/editing shift, option to "Make Recurring"
  - [ ] Recurring options: Select days of week (e.g., Mon, Wed, Fri)
  - [ ] Recurring end options: "Until end of schedule" or "Specific end date"
  - [ ] Recurring shifts display with repeat icon on calendar
  - [ ] Editing one instance prompts: "Edit this shift only" or "Edit all future shifts"
  - [ ] Deleting recurring shift prompts: "Delete this instance" or "Delete series"
  - [ ] Backend properly generates individual shift records from recurrence pattern
  - [ ] Verify existing UI functionality matches backend capabilities
  - [ ] Fix any disconnects between UI expectations and backend behavior

#### Feature 10: Event System Template Integration
- **User Story:** As a store manager, I want to associate templates with events so that I can quickly load appropriate staffing for special occasions
- **Acceptance Criteria:**
  - [ ] Events (from event system) visible on scheduling calendar
  - [ ] When clicking event, option to "Load Template for Event"
  - [ ] Template picker shows available templates
  - [ ] Selected template applies to days covered by event
  - [ ] Event can have a default template association (pre-configured)
  - [ ] When creating event, optional "Staffing Template" field

#### Feature 11: Wait Time Overlay
- **User Story:** As a store manager, I want to see historical wait time data on the calendar so that I can staff appropriately for busy periods
- **Acceptance Criteria:**
  - [ ] "Wait Time" toggle in calendar toolbar enables overlay
  - [ ] Overlay shows color-coded intensity based on historical average wait times
  - [ ] Color scale: Green (low wait <3min) → Yellow (moderate 3-6min) → Red (high >6min)
  - [ ] **Day View**: Hourly granularity showing wait time intensity per hour
  - [ ] **Week View**: Daily granularity showing daily average wait times
  - [ ] **Month View**: Daily granularity showing daily average wait times
  - [ ] **Timeline View**: Hourly granularity within each day
  - [ ] Tooltip on hover shows: "Avg wait: X min (last N weeks, Y transactions)"
  - [ ] Configurable lookback period: 4, 8, 12 weeks
  - [ ] Data source: Existing `WaitTimeRepository.fetchWaitTimeHeatmap()` infrastructure
  - [ ] Event days (from `events` table) excluded from averages by default

#### Feature 12: Sales Volume Overlay
- **User Story:** As a store manager, I want to see historical sales data on the calendar so that I can align staffing with expected revenue
- **Acceptance Criteria:**
  - [ ] "Sales" toggle in calendar toolbar enables overlay
  - [ ] Overlay shows intensity based on historical sales count or revenue
  - [ ] Toggle between: "Transaction Count" or "Revenue"
  - [ ] **Day View**: Hourly granularity (requires HOUR() grouping on transaction timestamps)
  - [ ] **Week View**: Daily granularity from dailySalesData aggregation
  - [ ] **Month View**: Daily granularity from dailySalesData aggregation
  - [ ] **Timeline View**: Hourly granularity within each day
  - [ ] Color scale matches wait time overlay for consistency
  - [ ] Tooltip shows: "Avg sales: $X / Y transactions (last N weeks)"
  - [ ] Same configurable lookback period as wait time overlay
  - [ ] Data source: `dailySalesData` table with hourly aggregation via transaction timestamps
  - [ ] Event days (from `events` table) excluded from averages by default

### Could Have Features

#### Feature 13: Template Sharing Across Stores
- **User Story:** As a multi-store owner, I want to share templates between my stores so that I can standardize scheduling patterns
- **Acceptance Criteria:**
  - [ ] "Share Template" option for store owners with multiple stores
  - [ ] Select target stores to share template with
  - [ ] Shared templates appear in target store's template list with "Shared" badge
  - [ ] Employee IDs in shared templates marked as open shifts (different employee base)

#### Feature 14: Template Version History
- **User Story:** As a store manager, I want to see the history of changes to a template so that I can revert if needed
- **Acceptance Criteria:**
  - [ ] Each template save creates a version record
  - [ ] "View History" shows versions with timestamp and user
  - [ ] Can preview any version
  - [ ] Can restore any version as current

#### Feature 15: Combined Analytics Overlay
- **User Story:** As a store manager, I want to see a combined view of wait times and sales together for complete business context
- **Acceptance Criteria:**
  - [ ] "Business Insights" toggle enables combined overlay
  - [ ] Combines wait time and sales data into single staffing recommendation
  - [ ] Shows staffing level indicator: "Understaffed", "Optimal", "Overstaffed"
  - [ ] Recommendations based on configurable thresholds

#### Feature 16: Template Recommendations
- **User Story:** As a store manager, I want the system to suggest which template to use based on upcoming events or patterns
- **Acceptance Criteria:**
  - [ ] When loading template, system suggests relevant template
  - [ ] Suggestions based on: upcoming events, day of week patterns, seasonal patterns
  - [ ] Suggestion shows reason: "Similar to last Black Friday"

### Won't Have (This Phase)

1. **Automatic Template Application**: System automatically loads templates without manager action
2. **AI-Generated Templates**: Machine learning to create optimal templates from historical data
3. **Cross-Store Scheduling**: Single view scheduling across multiple stores
4. **External Calendar Integration**: Sync templates with Google Calendar or Outlook
5. **Employee Template Preferences**: Employees voting on preferred templates
6. **Labor Budget Enforcement**: Hard blocks when template exceeds labor budget
7. **Real-time Collaboration**: Multiple managers editing templates simultaneously
8. **Template Marketplace**: Sharing templates between different organizations

## Detailed Feature Specifications

### Feature: Template Load with Conflict Detection (Features 2, 3, 4, 7)

**Description:** Loading a template is a multi-step process that checks for employee validity, availability conflicts, and time-off conflicts before creating shifts.

**User Flow:**
1. Manager clicks "Load Template" in calendar toolbar
2. Template picker dialog opens showing saved templates
3. Manager selects a template, clicks "Load"
4. System shows loading preview with:
   - All shifts that will be created
   - Warnings for inactive employees (will become open shifts)
   - Conflicts with availability/time-off highlighted
5. Manager chooses handling for each conflict category:
   - Inactive employees: "Convert to Open Shifts" (default) or "Skip"
   - Availability conflicts: "Convert to Open Shift" / "Create Anyway" / "Skip"
   - Time-off conflicts: "Convert to Open Shift" / "Skip" (cannot override approved time-off)
6. Manager can toggle "Load as All Open Shifts" to bypass employee assignment
7. Manager clicks "Apply Template"
8. System creates shifts according to selections
9. Summary displayed: "Created X shifts, Y open shifts, Z skipped"

**Business Rules:**
- Approved time-off is blocking - cannot schedule over (only skip or open shift)
- Pending time-off shows warning but can be overridden
- Availability is advisory - can be overridden with warning
- Template shifts inherit original positions; if position inactive, use default
- "Replace" mode deletes current week shifts before loading (soft delete)
- Template load logged in audit with template name, conflicts, decisions

**Edge Cases:**
- **All template employees gone**: Warning "No active employees in template - load as open shifts?" with confirmation
- **Template position no longer exists**: Shift created without position, warning shown
- **Week already has shifts**: "Replace" or "Merge" options; Replace deletes existing
- **Template exceeds open shift limit**: If policy limits open shifts, warn and cap
- **Recurring shifts in template**: Expand to individual shifts for template week only

### Feature: Availability & Time-Off Overlay (Features 5, 6)

**Description:** Visual overlay on the scheduling calendar showing when employees are available, unavailable, or have time-off requests.

**User Flow:**
1. Manager opens scheduling calendar in Timeline Week view
2. Manager clicks "Overlays" dropdown in toolbar
3. Manager enables "Availability" toggle
4. Calendar background shows color-coded availability for each employee row:
   - Green shading: Available
   - Red shading: Unavailable (recurring pattern)
   - Gray shading: No availability data set
5. Manager enables "Time-Off" toggle
6. Calendar shows time-off blocks overlaid:
   - Red striped: Approved (blocking)
   - Orange dashed: Pending (warning)
7. Manager can hover over blocks for details
8. Manager can click pending time-off to approve/deny inline

**Business Rules:**
- Availability patterns from `scheduleAvailability` table (dayOfWeek, startTime, endTime)
- Exception dates from `scheduleAvailabilityExceptions` override base patterns
- Time-off from `scheduleTimeOffRequests` table (status: pending, approved, denied)
- Overlays update when navigating to different weeks
- Overlays respect current date - past availability not relevant
- Performance: Load availability/time-off in single query per employee per week

**Edge Cases:**
- **No availability set**: Employee row shows gray (treat as fully available)
- **Overlapping time-off requests**: Show most restrictive (approved > pending)
- **Availability + time-off conflict**: Time-off takes precedence visually
- **Multi-day time-off**: Spans across days on calendar appropriately
- **Midnight-crossing availability**: Handle start time > end time (overnight)

### Feature: Analytics Overlays (Features 11, 12)

**Description:** Color-coded heat maps on the scheduling calendar showing historical wait times and sales patterns to inform staffing decisions.

**User Flow:**
1. Manager opens scheduling calendar
2. Manager clicks "Overlays" dropdown
3. Manager enables "Wait Time" toggle
4. Calendar shows heat map overlay based on historical wait time data:
   - Background color intensity indicates average wait time
   - Green = low wait (<3 min), Yellow = moderate (3-6 min), Red = high (>6 min)
5. Manager hovers over time slot to see tooltip: "Avg wait: 5.2 min (last 4 weeks, N visits)"
6. Manager can switch to "Sales Volume" overlay
7. Calendar shows heat map based on historical sales:
   - Intensity indicates transaction count or revenue
8. Manager adjusts lookback period in overlay settings (4/8/12 weeks)
9. Manager uses insights to add shifts during historically busy periods

**Business Rules:**
- Data aggregated by: store, day of week, hour block (for Day/Timeline) or day (for Week/Month)
- Wait time source: `WaitTimeRepository.fetchWaitTimeHeatmap()` using `buyQueue` table
  - Calculates: `sortStarted - timeEntered` (or `timeStarted - timeEntered` if no sort)
  - Minimum 3 buys per bucket to display (existing threshold)
- Sales source: `dailySalesData` table with `FinancialRepository` methods
  - Hourly aggregation via `HOUR()` function on transaction timestamps
- Lookback period applies to same day-of-week (last N Mondays, etc.)
- **Outlier Detection**: Days with active events (from `events` table where `phase='active'` or `phase='build_up'`) excluded from averages
- Minimum data threshold: Need at least 2 data points for time slot to show overlay
- Thresholds configurable per store (default: low <3min, moderate 3-6min, high >6min)
- Timezone handling: Timestamps stored in UTC, converted to store timezone using `Store::getTimezone()`

**Edge Cases:**
- **No historical data**: Time slot shows no overlay, tooltip: "Insufficient data"
- **Store recently opened**: Show "Limited data - X weeks available"
- **Extreme outlier**: Cap display at max value, tooltip shows actual
- **Different operating hours**: Only show overlay for store's operating hours (via `storeOperatingHours`)
- **DST transitions**: Match day-of-week + hour, not exact timestamps
- **Event exclusion toggle**: Option to include/exclude event days (default: exclude)

## Success Metrics

### Key Performance Indicators

| Metric | Target | Measurement Definition | External Factors |
|--------|--------|----------------------|------------------|
| **Template Adoption** | 60% of schedule sessions use templates | Sessions with `template_loaded` / total schedule sessions | Depends on manager training, template quality |
| **Scheduling Time Reduction** | 50% reduction | Median time to complete schedule (with template vs without) | Depends on schedule complexity, store size |
| **Conflict Prevention** | 80% reduction in post-publish changes | Schedule changes after publish date / total shifts | Depends on employee communication |
| **Overlay Usage** | 40% of sessions use overlays | Sessions with any overlay enabled / total sessions | Depends on data availability, manager awareness |
| **Template Reuse** | 3+ loads per template | Average loads per template | Depends on schedule stability |

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| `template_saved` | template_id, name, shift_count, has_description | Track template creation |
| `template_loaded` | template_id, load_mode (replace/merge/open_shifts), conflicts_found | Track template usage |
| `template_conflict_resolved` | conflict_type (employee/availability/timeoff), resolution (open_shift/skip/override) | Understand conflict patterns |
| `template_deleted` | template_id, shift_count, times_used | Track template lifecycle |
| `overlay_enabled` | overlay_type (availability/timeoff/waittime/sales) | Track overlay adoption |
| `overlay_insight_clicked` | overlay_type, detail_viewed | Track engagement with data |
| `repeat_shift_created` | days_selected, duration_weeks | Track recurring shift usage |
| `event_template_loaded` | event_id, template_id | Track event integration |

---

## Constraints and Assumptions

### Constraints
- **BuyerKiosk Provider Only**: Features only available when `schedulingProvider='buyerkiosk'`
- **Spec 013 Dependency**: Requires existing scheduling system (Syncfusion EJ2 Schedule)
- **Spec 022 Dependency**: Requires availability and time-off tables from mobile scheduling spec
- **Data Availability**: Analytics overlays require historical wait time and sales data (existing reports)
- **Performance**: Must handle stores with up to 50 employees and 100+ shifts per week
- **Storage**: Template limit of 20 per store to manage database growth

### Assumptions
- Spec 013 (Employee Scheduling) is fully implemented with Syncfusion calendar
- Spec 022 (Mobile Scheduling API) tables exist: `scheduleAvailability`, `scheduleTimeOffRequests`
- Wait time report infrastructure exists and provides hourly aggregated data
- Sales report infrastructure exists and provides hourly aggregated data
- Repeat shift UI exists (mentioned in request) - need to verify backend support
- Managers are comfortable with overlay-style interfaces (common in scheduling tools)

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Template bloat (too many templates) | Medium | Medium | 20 template limit per store; usage-based sorting |
| Performance with large templates | High | Low | Lazy loading; batch insert for template load |
| Overlay visual clutter | Medium | Medium | Single overlay at a time; clear visual hierarchy |
| Data quality for analytics overlays | High | Medium | Minimum data thresholds; clear "insufficient data" messaging |
| Conflict detection false positives | Medium | Low | Clear conflict categorization; easy override options |
| Repeat shift complexity | High | Medium | Start with simple day-of-week pattern; defer complex patterns |
| Historical data not representative | Medium | Medium | Configurable lookback; exclude outlier detection |

## Open Questions

All clarifications resolved during requirements gathering:

- [x] **Outlier Detection**: Use events table - days with active events (phase='active' or 'build_up') excluded from averages
- [x] **Repeat Shift Priority**: MUST HAVE - verify and fix existing UI/backend disconnect before launch
- [x] **Wait Time Data Source**: `WaitTimeRepository.fetchWaitTimeHeatmap()` using `buyQueue` table (existing infrastructure)
- [x] **Sales Data Granularity**: View-dependent: Day/Timeline views use hourly, Week/Month views use daily
- [ ] **Overlay Performance**: Need to benchmark availability data load for 25+ employees during SDD phase
- [ ] **Repeat Shift Current State**: Need to audit existing repeat shift UI during implementation to identify gaps

---

## Supporting Research

### Competitive Analysis

**When I Work Templates:**
- Offers "Schedule Templates" feature
- Can save and load weekly templates
- No availability overlay integration
- No historical analytics overlay

**Deputy:**
- Advanced template system with "Auto-Scheduling"
- Availability shown on schedule
- Demand-based staffing recommendations
- Premium feature tier

**Homebase:**
- Basic template functionality
- Shows conflicts with availability
- No historical analytics overlay

**BuyerKiosk Opportunity:**
- Native integration with existing availability/time-off system (Spec 022)
- Unique analytics overlay using existing wait time and sales data
- Event system integration for event-based templates
- Deep integration with BuyerKiosk ecosystem

### User Research

Based on the feature request:
- Managers spend significant time rebuilding similar schedules weekly
- Visibility into availability/time-off is currently siloed
- Historical patterns (wait times, sales) exist but aren't surfaced during scheduling
- Event-based scheduling is manual and disconnected from staffing
- Repeat shifts are expected but may not work reliably

### Existing Infrastructure

**From Spec 022 (Mobile Scheduling API):**
- `scheduleAvailability`: Recurring weekly patterns
- `scheduleAvailabilityExceptions`: Date-specific overrides
- `scheduleTimeOffRequests`: Time-off request workflow

**From Spec 013 (Employee Scheduling):**
- Syncfusion EJ2 Schedule calendar
- `scheduleShifts` table with full CRUD
- Position management
- Overtime configuration

**Wait Time Reports:**
- **Table**: `buyQueue` (store database)
- **Repository**: `WaitTimeRepository.fetchWaitTimeHeatmap()`
- **Calculation**: `sortStarted - timeEntered` (or `timeStarted - timeEntered`)
- **Pre-aggregated**: `statsStoreDaily.avgDelay` for daily averages
- **Granularity**: Hourly aggregation via `HOUR()` + `DAYOFWEEK()` grouping
- **File**: `userfrosting/src/BuyerKiosk/Analytics/Repositories/WaitTimeRepository.php`

**Sales Reports:**
- **Table**: `dailySalesData` (store database)
- **Repository**: `FinancialRepository.fetchDailyBuysToSales()`
- **Granularity**: Daily records; hourly possible via `HOUR()` on transaction timestamps
- **Metrics**: salesAmount, buyAmount, transactionCount
- **File**: `userfrosting/src/BuyerKiosk/Analytics/Repositories/FinancialRepository.php`

**Events System:**
- **Table**: `events` (store database)
- **Fields**: eventType, startDate, endDate, buildUpDays, phase, status
- **Outlier Detection**: Filter by `phase IN ('active', 'build_up')` to exclude event days
- **File**: `userfrosting/migrations/input/20251210_002_events_core.json`
