# 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 (integration providers like WhenIWork are business decisions)
- [x] A new team member could understand this PRD

---

## Product Overview

### Vision
Empower resale store owners with a native, fully-integrated employee scheduling and time tracking system that eliminates dependency on third-party scheduling tools while providing the flexibility to choose their preferred scheduling provider.

### Problem Statement
Store owners using BuyerKiosk currently rely on external scheduling systems like WhenIWork to manage employee schedules and time tracking. This creates several problems:

1. **Cost burden**: Monthly subscription fees to WhenIWork ($2-4/employee/month) add up across all stores
2. **Integration friction**: Data lives in two systems requiring sync, with potential for discrepancies
3. **Feature gaps**: External tools don't understand BuyerKiosk-specific concepts (buy transactions, sales goals, store events)
4. **Vendor lock-in**: Switching scheduling providers requires significant effort and data migration
5. **Fragmented experience**: Managers must context-switch between BuyerKiosk and their scheduling tool

**Consequences:**
- Stores pay ongoing fees for features they may not fully use
- Time tracking data isn't natively available for labor cost analysis within BuyerKiosk
- Future features like sales-based staffing recommendations require external API calls
- New stores must set up and learn an additional system

### Value Proposition
BuyerKiosk Employee Scheduling provides a native, zero-additional-cost scheduling solution that:

1. **Eliminates third-party fees**: No per-employee subscription costs for basic scheduling
2. **Integrates seamlessly**: Works directly with the unified user system and workbook interface
3. **Offers provider choice**: Stores can choose BuyerKiosk native, WhenIWork, or Homebase as their scheduling provider
4. **Enables future intelligence**: Native data enables future features like sales-based staffing and event integration
5. **Maintains familiar UX**: Uses the existing schedule panel interface employees already know
6. **Accelerates delivery**: Leverages Syncfusion EJ2 Schedule component library for professional-grade UI with minimal custom development

### Technology Decision: Syncfusion EJ2 Schedule

**Decision**: Use Syncfusion EJ2 Schedule as the calendar UI foundation rather than building custom calendar components.

**Why Syncfusion**:
- **Proven Solution**: Enterprise-grade scheduling component used by thousands of organizations
- **Feature Complete**: Day/Week/Month views, drag-drop, resource grouping, recurring events - all built-in
- **Timeline View**: Perfect match for employee scheduling (employees as rows, time as columns)
- **Rapid Development**: 80%+ of calendar UI requirements are satisfied out-of-the-box
- **Mobile Responsive**: Built-in responsive design without additional development
- **Bootstrap 5 Theme**: Native integration with our existing design system

**License**: Community License (free for organizations with <$1M annual revenue and ≤5 developers)

**What Syncfusion Handles**:
- Calendar grid layout (Day, Week, Month, Timeline views)
- Shift block rendering and positioning
- Drag-and-drop shift reassignment
- Event (shift) CRUD dialogs
- Conflict detection (`allowOverlap: false`)
- Resource grouping (employees as resources)
- Date navigation and view switching

**What We Build Custom**:
- Time clock integration with Workbook
- Timesheet approval workflow
- Labor cost calculations
- No-show detection
- Copy Previous Week functionality
- CSV/Excel export
- Position-based color theming

## User Personas

### Primary Persona: Store Owner/Manager (Sarah)
- **Demographics:** 28-50 years old, manages daily operations and payroll for a resale store (Plato's Closet, Clothes Mentor, etc.), moderate technical expertise, cost-conscious small business operator
- **Goals:**
  - Minimize operational costs while maintaining efficient scheduling
  - Ensure accurate time tracking for payroll processing
  - Have clear visibility into labor costs vs. revenue
  - Quickly create and adjust schedules to match business needs
  - Approve timesheets confidently before payroll runs
- **Pain Points:**
  - Paying monthly fees for scheduling software that duplicates data in BuyerKiosk
  - Manual export/import of timesheet data for payroll
  - Can't easily see labor cost impact when scheduling
  - Building schedules from scratch each week is time-consuming

### Secondary Personas

#### Shift Lead (Marcus)
- **Demographics:** 22-35 years old, key holder with partial management responsibilities, uses workbook daily
- **Goals:**
  - Know who's scheduled to work with them each shift
  - Clock team members in/out when needed
  - Track breaks to ensure coverage
  - Quickly identify who's late or missing
- **Pain Points:**
  - Has to check separate app to see today's schedule
  - Uncertainty about whether someone forgot to clock in vs. called out
  - Can't see at a glance who's on break

#### Floor Employee (Taylor)
- **Demographics:** 18-30 years old, part-time or full-time sales associate, uses kiosk for clock operations
- **Goals:**
  - Know their schedule for the upcoming weeks
  - Clock in/out and track breaks accurately
  - Ensure their hours are recorded correctly for pay
- **Pain Points:**
  - Having to use a separate app to check schedule
  - Forgetting to clock in/out and worrying about pay accuracy
  - Uncertainty about whether time punch was recorded

## User Journey Maps

### Primary User Journey: Weekly Schedule Creation
1. **Awareness:** It's Thursday and Sarah needs to create next week's schedule before posting it on Friday
2. **Consideration:** Sarah opens the Scheduling section and sees the Timeline Week view with last week's schedule - decides to copy it as a starting point
3. **Adoption:** Sarah clicks "Copy Previous Week" and the schedule populates with last week's shifts
4. **Usage:** Sarah adjusts shifts using Syncfusion's drag-and-drop to swap employees and reschedule times, sees labor cost updating in real-time as she makes changes
5. **Retention:** Sarah publishes the schedule in under 10 minutes, compared to 30+ minutes building from scratch - becomes her standard workflow

### Secondary User Journeys

#### Daily Time Clock Management Journey
1. Store opens, Sarah checks the schedule panel in workbook
2. Employees arrive and clock in via the workbook kiosk - their avatars turn green
3. Sarah notices Marcus is scheduled but shows grey (not clocked in) 15 minutes after shift start
4. Sarah taps Marcus's avatar and can clock him in with manager override (if he arrived but forgot) or adjust coverage as needed
6. Throughout the day, Sarah monitors the panel - sees break statuses, ensures coverage

#### End-of-Week Timesheet Approval Journey
1. Pay period ends on Sunday night
2. Monday morning, Sarah opens Timesheets section
3. Dashboard shows total hours, overtime alerts, and any time punches needing attention
4. Sarah reviews each employee's timesheet, edits any missed punches with notes
5. Sarah approves timesheets for the week
6. Sarah exports data to CSV for import into QuickBooks payroll

#### Employee Schedule Viewing Journey
1. Taylor wants to know if they work this weekend
2. Taylor logs into BuyerKiosk web panel from home (BuyerKiosk native scheduling stores)
3. Taylor sees their personal schedule for the current and upcoming weeks
4. Taylor notes they work Saturday 10am-6pm and plans accordingly

## Feature Requirements

### Must Have Features

#### Feature 1: Scheduling Provider Selection
- **User Story:** As a store owner, I want to choose my scheduling provider (BuyerKiosk native, WhenIWork, or Homebase) so that I can use the system that best fits my needs
- **Acceptance Criteria:**
  - [ ] Store settings include "Scheduling Provider" dropdown with options: BuyerKiosk, WhenIWork, Homebase (disabled if not configured)
  - [ ] Only one provider can be active at a time per store
  - [ ] Changing providers shows warning about data not transferring automatically
  - [ ] Provider selection determines which backend provider powers schedule data and clock actions
  - [ ] BuyerKiosk provider requires no additional configuration to enable
  - [ ] Workbook UX is consistent regardless of provider (schedule sidebar, clock in/out, breaks, and clocked-in indicators)

**Provider Behavior Matrix (MVP)**

| Active `schedulingProvider` | Workbook Schedule Panel | Workbook Clock/Break UI | Admin Scheduling (Calendar) | Timesheets / Approval / Export |
|---|---|---|---|---|
| `none` | Hidden + setup prompt | Disabled | Hidden | Hidden |
| `wheniwork` | Enabled | Enabled (calls WhenIWork API) | Hidden (managed in WhenIWork) | Hidden (managed in WhenIWork) |
| `homebase` | Enabled | Enabled (calls Homebase API) | Hidden (managed in Homebase) | Hidden (managed in Homebase) |
| `buyerkiosk` | Enabled | Enabled (native) | Enabled (Syncfusion) | Enabled (native) |

#### Feature 2: Schedule Calendar Interface (Syncfusion EJ2 Schedule)
- **User Story:** As a store manager, I want a visual calendar to create and manage employee schedules so that I can easily see coverage and make adjustments
- **Acceptance Criteria:**
  - [ ] Calendar supports Timeline Week view (primary) showing employees as rows, days as columns
  - [ ] Calendar supports Day and Week standard views for alternate perspectives
  - [ ] Month view available for high-level scheduling overview
  - [ ] Employees displayed as "resources" with their names, avatars, and weekly hours
  - [ ] Shifts display as colored blocks showing employee name, time, and position
  - [ ] Clicking empty space opens Syncfusion event editor to create shift
  - [ ] Clicking existing shift opens editor to modify or delete
  - [ ] Calendar loads within 2 seconds for stores with up to 50 employees
  - [ ] Only accessible to users with scheduling permission (manager level and above)
  - [ ] Syncfusion Schedule configured with `allowOverlap: false` to prevent double-booking

#### Feature 3: Shift Management (CRUD)
- **User Story:** As a store manager, I want to create, edit, and delete shifts so that I can build schedules that match my staffing needs
- **Acceptance Criteria:**
  - [ ] Create shift requires: employee, date, start time, end time, position (optional, chosen from the store's Positions list)
  - [ ] System prevents creating overlapping shifts for the same employee (Syncfusion validation)
  - [ ] Shifts can be edited after creation (employee, time, position)
  - [ ] Shifts can be deleted with confirmation dialog
  - [ ] Deleted shifts are soft-deleted (retained for audit) but hidden from calendar
  - [ ] Bulk delete available for multiple selected shifts (Syncfusion multi-select)

#### Feature 4: Copy Previous Week Schedule
- **User Story:** As a store manager, I want to copy last week's schedule to this week so that I don't have to rebuild similar schedules from scratch
- **Acceptance Criteria:**
  - [ ] "Copy Previous Week" button available in Week view
  - [ ] Copying adjusts dates to target week while preserving shift times and assignments
  - [ ] Conflicts are highlighted if an employee is already scheduled in the target week
  - [ ] Manager can choose to skip or overwrite conflicting shifts
  - [ ] Copy operation completes within 5 seconds for up to 100 shifts

#### Feature 5: Drag-and-Drop Schedule Editing (Syncfusion Native)
- **User Story:** As a store manager, I want to drag shifts to different times or employees so that I can quickly adjust schedules
- **Acceptance Criteria:**
  - [ ] Shifts can be dragged to different time slots on the same day (Syncfusion native)
  - [ ] Shifts can be dragged to different days within week view (Syncfusion native)
  - [ ] Shifts can be dragged to different employees/resources (reassignment)
  - [ ] Visual preview shows where shift will land before dropping
  - [ ] Conflict warning appears if drop would create overlap
  - [ ] Multi-select drag supported via Syncfusion `allowMultiDrag` property
- **Syncfusion Note:** Drag-drop is handled entirely by Syncfusion EJ2 Schedule - no custom implementation needed

#### Feature 6: Time Clock Integration (Workbook)
- **User Story:** As an employee, I want to clock in/out from the workbook so that my hours are accurately tracked
- **Acceptance Criteria:**
  - [ ] Schedule panel in workbook shows today's scheduled employees (existing spec 010)
  - [ ] Tapping employee avatar opens action modal with Clock In/Out options
  - [ ] Clock actions require PIN verification (employee's BuyerKiosk PIN)
  - [ ] Successful clock in changes avatar status to green dot
  - [ ] Successful clock out changes avatar to strikethrough style
  - [ ] Clock actions route to the active scheduling provider backend (BuyerKiosk native, WhenIWork API, or Homebase API)
  - [ ] Time punch is recorded with timestamp, employee ID, and action type (in provider system of record)
  - [ ] Real-time updates via Ably when clock actions occur
  - [ ] Store can configure an allowed clock-in window relative to scheduled shift start/end (early/late)
  - [ ] Unscheduled clock-in requires manager approval (manager override PIN at time of clock-in) and is recorded/audited as an approved override

#### Feature 7: Break Tracking
- **User Story:** As a store manager, I want to track employee breaks so that I can ensure compliance and calculate accurate hours
- **Acceptance Criteria:**
  - [ ] Action modal shows "Start Break" for clocked-in employees
  - [ ] Break can be marked as "Paid" or "Unpaid" when starting
  - [ ] On-break employees show yellow status dot on avatar
  - [ ] "End Break" action available for employees on break
  - [ ] Break duration is calculated and stored with time record
  - [ ] Unpaid break time is subtracted from total worked hours

#### Feature 8: Position Management
- **User Story:** As a store manager, I want to assign positions to employees so that I can schedule the right people for the right roles
- **Acceptance Criteria:**
  - [ ] Store has a configurable Positions list (name + color + active flag)
  - [ ] Default positions exist for new stores: Owner, General Manager, Store Manager, Shift Lead, Buyer, Sales Associate
  - [ ] Employee profile supports assigning a default position from the store's Positions list
  - [ ] Shifts can optionally specify a position from the store's Positions list
  - [ ] When creating shifts, employee dropdown can filter by position
  - [ ] Position displays on shift blocks in calendar (Syncfusion event template)
  - [ ] Position is searchable/filterable in employee list
  - [ ] Shift color is driven by the selected shift position color

#### Feature 9: Overtime Configuration
- **User Story:** As a store owner, I want to configure overtime rules for my store so that labor costs are calculated according to my jurisdiction's laws (US state / Canadian province)
- **Acceptance Criteria:**
  - [ ] Store settings include "Overtime Rules" configuration
  - [ ] Store selects jurisdiction: US state (incl. DC) or Canadian province/territory
  - [ ] Store can choose a jurisdiction preset (when available) or "Custom"
  - [ ] Presets are available for all US states and Canadian provinces/territories, and can be updated over time as laws change
  - [ ] Custom option allows configuration of thresholds and multipliers (daily/weekly/double-time as applicable)
  - [ ] Overtime calculations use store's configured rules
  - [ ] Configuration changes apply to future calculations only (not retroactive)
  - [ ] UI includes a disclaimer: "Overtime rules vary and can change. Verify your configuration for compliance."

#### Feature 10: Labor Cost Calculation
- **User Story:** As a store manager, I want to see labor costs while scheduling so that I can stay within budget
- **Acceptance Criteria:**
  - [ ] Each employee has an hourly rate with history (effective-dated changes)
  - [ ] Calendar view shows running total of scheduled labor cost
  - [ ] Labor cost updates in real-time as shifts are added/modified
  - [ ] Overtime premium is included in cost calculation
  - [ ] Cost breakdown available: regular hours cost + overtime cost = total
  - [ ] Cost displayed per day and per week in schedule view
  - [ ] Scheduler shows overtime forecast warnings based on scheduled shifts (forecasted overtime highlighted)

#### Feature 11: Timesheet Dashboard
- **User Story:** As a store manager, I want a dashboard showing employee hours so that I can review and approve timesheets for payroll
- **Acceptance Criteria:**
  - [ ] Timesheet Dashboard is only available when `schedulingProvider='buyerkiosk'` (hidden for external providers)
  - [ ] Dashboard shows summary: total hours, total labor cost, overtime hours
  - [ ] Employee list shows: scheduled hours, actual hours, diff, regular/overtime breakdown, status
  - [ ] Clicking employee opens detailed timesheet view
  - [ ] Date range selector defaults to current workweek (store-configurable week start; default Monday-Sunday)
  - [ ] Filter by: all employees, employees with overtime, employees with missing punches
  - [ ] Dashboard loads within 3 seconds for up to 50 employees
  - [ ] Overtime is highlighted when actual overtime exceeds scheduled overtime forecast (unexpected overtime)
- **Pay Period Clarification:**
  - MVP uses weekly pay periods only, but the week start is configurable per store (default Monday at 00:00 local time)
  - Timesheet boundaries default to align with the configured overtime workweek for the store’s jurisdiction preset when that jurisdiction defines a fixed week (e.g., BC Sunday–Saturday)
  - Pay period configuration (Feature 20) is Could Have and NOT implemented in MVP
  - When Feature 20 is implemented, date range selector will respect configured pay period type
  - Edge case handling for non-weekly periods is deferred to Feature 20 implementation

#### Feature 12: Time Punch Editing
- **User Story:** As a store manager, I want to edit time punches so that I can correct errors when employees forget to clock in/out
- **Acceptance Criteria:**
  - [ ] Time punch editing is only available when `schedulingProvider='buyerkiosk'` (managed in external provider otherwise)
  - [ ] Permission to edit/add/delete punches is role-based and store-configurable (default: Store Manager+)
  - [ ] Detailed timesheet view shows all punches: clock in, break start, break end, clock out
  - [ ] Each punch can be edited (time adjustment) with required note field
  - [ ] Missing punches can be added manually with required note
  - [ ] Punches can be deleted with required note
  - [ ] All edits are logged in audit trail with: editor, timestamp, old value, new value, note
  - [ ] Edited punches show visual indicator (different color or icon)

#### Feature 13: Timesheet Approval Workflow
- **User Story:** As a store manager, I want to approve timesheets before export so that I confirm hours are accurate for payroll
- **Acceptance Criteria:**
  - [ ] Each employee's weekly timesheet has status: Pending, Approved, Exported
  - [ ] Approval permission is role-based and store-configurable (default: Store Manager+)
  - [ ] Manager can approve individual employee timesheets
  - [ ] "Approve All" button available for bulk approval
  - [ ] Approved timesheets are locked from editing (requires manager to unlock first)
  - [ ] Approval action is logged with approver and timestamp

#### Feature 14: Timesheet Export
- **User Story:** As a store manager, I want to export timesheets to CSV so that I can import them into QuickBooks for payroll
- **Acceptance Criteria:**
  - [ ] Export button available in timesheet dashboard
  - [ ] Export format: CSV (Excel format moved to Should Have - see Feature 17d)
  - [ ] Export includes: employee name, employee ID, date, regular hours, overtime hours, total hours, pay rate, total pay
  - [ ] Export only includes approved timesheets by default (option to include all)
  - [ ] Export marks timesheets as "Exported" with timestamp
  - [ ] File naming: `timesheets_{storeName}_{dateRange}.csv`
  - [ ] Export applies store-configured payroll rounding rules (configurable increment + rounding mode), while retaining raw punch times for audit

#### Feature 15: Employee Schedule View
- **User Story:** As an employee, I want to view my schedule from home so that I can plan my week
- **Acceptance Criteria:**
  - [ ] Employee login to web admin shows "My Schedule" section when `schedulingProvider='buyerkiosk'`
  - [ ] Shows current week and future scheduled weeks (up to 4 weeks out)
  - [ ] Read-only view - no editing capability
  - [ ] Shows shift date, start time, end time, position
  - [ ] Shows total scheduled hours for each week
  - [ ] Mobile-responsive design for phone viewing

### Should Have Features

#### Feature 17: Conflict Prevention Warnings
- **User Story:** As a store manager, I want the system to warn me about scheduling conflicts so that I don't accidentally double-book employees
- **Acceptance Criteria:**
  - [ ] System prevents saving overlapping shifts for the same employee (hard block via Syncfusion)
  - [ ] Warning shown if scheduling employee close to overtime threshold
  - [ ] Warning shown if scheduling employee with less than 8 hours between shifts
  - [ ] Warnings can be acknowledged but don't block scheduling

#### Feature 18: Bulk Shift Operations
- **User Story:** As a store manager, I want to create or modify multiple shifts at once so that I can build schedules faster
- **Acceptance Criteria:**
  - [ ] Multi-select shifts with Shift+Click or Ctrl+Click (Syncfusion native)
  - [ ] Bulk delete selected shifts
  - [ ] Bulk reassign selected shifts to different employee
  - [ ] Create recurring shift (same time, multiple days in week)

#### Feature 17b: Month View Calendar
- **User Story:** As a store manager, I want a month view to see the full month's schedule at a glance
- **Acceptance Criteria:**
  - [ ] Month view shows condensed shift indicators per day (Syncfusion Month view)
  - [ ] Click on day opens that day in Day view
  - [ ] Month view loads within 3 seconds for stores with up to 50 employees
- **Syncfusion Note:** Month view is built into EJ2 Schedule - configuration only

#### Feature 17c: Drag-Drop Undo
- **User Story:** As a store manager, I want to undo my last drag-drop action in case I made a mistake
- **Acceptance Criteria:**
  - [ ] Undo button appears after drag-drop action (5-second timeout)
  - [ ] Ctrl+Z keyboard shortcut also triggers undo
  - [ ] Only last action is undoable (not full history)

#### Feature 17d: Excel Export
- **User Story:** As a store manager, I want to export timesheets in Excel format for more flexibility
- **Acceptance Criteria:**
  - [ ] Export option includes Excel (.xlsx) format
  - [ ] Excel export includes same data as CSV
  - [ ] Excel export includes formatting (headers, column widths)

### Could Have Features

#### Feature 19: Schedule Publishing
- **User Story:** As a store manager, I want to publish schedules so that employees know when they can view them
- **Acceptance Criteria:**
  - [ ] Draft/Published status for weekly schedules
  - [ ] Employees only see published schedules
  - [ ] Manager can unpublish to make changes, then republish

#### Feature 20: Payroll Period Configuration
- **User Story:** As a store owner, I want to configure my pay periods so that timesheets align with my payroll schedule
- **Acceptance Criteria:**
  - [ ] Store settings include pay period configuration
  - [ ] Options: Weekly (select start day), Bi-weekly (select start date), Semi-monthly
  - [ ] Timesheet dashboard defaults to current pay period

### Won't Have (This Phase)

The following features are explicitly **out of scope** for MVP but documented for future phases:

1. **Auto-Scheduling Algorithm**: Intelligent automatic shift assignment based on availability, hours, and position
2. **Schedule Templates**: Save and reuse schedule templates (e.g., "Holiday Schedule", "Summer Schedule")
3. **Shift Trading**: Employee-to-employee shift swaps with manager approval
4. **Time-Off Requests**: Employee submission and manager approval of PTO/sick time
5. **Availability Management**: Employees setting their preferred/available hours
6. **Open Shift Pickup**: Employees claiming unassigned shifts
7. **Alerts/Notifications**: Email, SMS, or push notifications for schedule changes, open shifts, etc.
8. **Sales/Buys Forecasting Integration**: Using historical data to recommend staffing levels
9. **Event System Integration**: Auto-generating shifts based on scheduled store events
10. **Multi-Store Unified Scheduling**: Cross-store visibility and scheduling for multi-store employees
11. **Labor Budget Targets**: Setting and tracking against weekly/monthly labor budgets
12. **Advanced Break Policy Enforcement**: Auto-prompting for breaks based on worked hours
13. **Team Tasks**: Assigning tasks to shifts or employees
14. **Mobile App**: Native iOS/Android app for employees (API will be ready for future app)
15. **QuickBooks Direct Integration**: Auto-push timesheets to QuickBooks (CSV export only for MVP)
16. **No-Show Detection**: Automated late/no-show alerts (not needed in MVP)

## Detailed Feature Specifications

### Feature: Time Clock with Break Tracking (Features 6 & 7)

**Description:** Employees clock in/out and manage breaks through the workbook schedule panel. All time punches are recorded with timestamps and require PIN verification for security.

**User Flow:**
1. Employee arrives at store, opens workbook on shared kiosk
2. Employee sees schedule panel on right side, finds their avatar (greyed out = scheduled)
3. Employee taps their avatar, modal opens showing "Clock In" button
4. Employee enters their 4-digit PIN and taps confirm
5. System records clock-in timestamp, avatar turns green with status dot
6. Later, employee taps avatar for break, selects "Start Break", chooses Paid or Unpaid, enters PIN
7. Avatar changes to yellow status, break timer starts
8. Employee returns, taps avatar, "End Break", enters PIN
9. At shift end, employee taps avatar, "Clock Out", enters PIN
10. Avatar changes to strikethrough, shift is complete

**Business Rules:**
- PIN must match the employee's BuyerKiosk PIN stored in their employee record
- Three failed PIN attempts locks action for 5 minutes (prevents brute force)
- Manager override available: manager can clock others in/out using their own PIN
- Clock-in outside the allowed clock-in window requires manager override
- Clock-in without being scheduled requires manager override (manager approval at time of clock-in)
- Clock-out time cannot be before clock-in time
- Break end time cannot be before break start time
- Only one active time session per employee at a time

**Edge Cases:**
- **Forgot to clock in**: Manager uses time punch editing to add missed clock-in with note
- **Forgot to clock out**: System does not auto-clock-out; manager must add missing punch before timesheet approval
- **Double clock-in attempt**: System shows error "Already clocked in at [time]"
- **Clock-in without schedule**: Requires manager override; recorded as "Unscheduled (Manager Approved)"
- **Power outage/system down**: Kiosk unavailable; manager adds punches manually later
- **Wrong PIN entered**: Error message, retry allowed up to 3 times, then locked

### Feature: Overtime Calculation (Feature 9)

**Description:** Labor cost calculations include overtime premiums based on the store's configured overtime rules.

**Business Rules:**
- Overtime rules are selected by jurisdiction (US state / Canadian province/territory) with a "Custom" override option
- The system provides jurisdiction presets and allows store owners to review and customize as needed
- **Custom**: Store defines thresholds and multipliers (daily/weekly/double-time, as applicable)
- Overtime calculated on gross hours (breaks do not reset daily count)
- Unpaid breaks reduce total hours but do not affect overtime threshold calculation

**Calculation Example (California):**
- Employee works 10 hours on Monday
- Regular: 8 hours × $15/hr = $120
- Overtime: 2 hours × $15 × 1.5 = $45
- Total Monday: $165

**Edge Cases:**
- **Spans midnight**: Shift from 10pm-6am counts as two separate days for daily overtime
- **Multiple shifts same day**: Combined for daily overtime calculation
- **Pay rate change mid-week**: Uses rate in effect at time of each shift

## Success Metrics (Directional Targets)

### Key Performance Indicators

**Note:** These metrics are **directional targets** influenced by external factors (staff behavior, store size, management practices). They represent goals we aim toward, not guarantees the system will achieve.

| Metric | Target | Measurement Definition | External Factors |
|--------|--------|----------------------|------------------|
| **Adoption Rate** | 50% of new stores within 6 months | Count stores where `schedulingProvider='buyerkiosk'` divided by total new stores in period | Depends on sales team promotion, existing provider contracts |
| **Manager Engagement** | 2+ sessions per week | Distinct sessions per store per week (session = page views within 30-min window) | Depends on store operating hours, manager work patterns |
| **Scheduling Efficiency** | Target: under 15 minutes | Median time from first `shift_created` to last `shift_created` in a scheduling session | Depends on store size, schedule complexity, user familiarity |
| **Data Quality** | Target: <5% manual edits | Timesheets with `time_punch_edited` events divided by total approved timesheets | Depends on employee compliance, PIN remembrance, clock-in habits |
| **Cost Savings** | $50-100/month | External provider subscription cost (self-reported or from provider API) | Depends on previous provider tier, store negotiated rates |

### Metric Calculation Details

**Scheduling Efficiency Formula:**
```
efficiency_minutes = (last_shift_created_timestamp - first_shift_created_timestamp) / 60
session_boundary = 2+ hours of inactivity between shift_created events
denominator = all scheduling sessions where shift_count >= 5
```

**Data Quality Formula:**
```
edit_rate = COUNT(DISTINCT timesheets with edits) / COUNT(total approved timesheets)
"edit" = any time_punch_edited event on that timesheet
excludes: initial manual punch creation (only edits to existing punches)
```

**Adoption Rate Formula:**
```
adoption_rate = stores_with_buyerkiosk_provider / total_stores_created_in_period
measured_at = end of each month
cohort = stores created in previous 6 months
```

### Instrumentation Requirements

These metrics require the following events to be instrumented (see Tracking Requirements table below):

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| `scheduling_provider_selected` | provider_type, previous_provider | Track provider adoption |
| `schedule_created` | method (manual, copy_week), shift_count, time_taken_seconds | Measure efficiency |
| `shift_created` | source (calendar_click, bulk, copy) | Understand scheduling patterns |
| `shift_modified` | modification_type (time, employee, delete) | Track editing behavior |
| `time_punch_recorded` | punch_type, method (self, manager_override) | Monitor clock usage |
| `time_punch_edited` | edit_type (add, modify, delete), reason_provided | Track data quality |
| `timesheet_approved` | employee_count, total_hours, edits_made | Monitor approval workflow |
| `timesheet_exported` | format, row_count | Track payroll integration |
| `overtime_warning_shown` | threshold_type, acknowledged | Track labor management |

---

## Constraints and Assumptions

### Constraints
- **Provider Architecture:** Must work alongside WhenIWork and Homebase as a provider option - not replace them
- **Unified User System Dependency:** Requires 007-unified-users-auth to be implemented for employee records
- **Schedule Panel Compatibility:** Must power the existing schedule panel (spec 010) without UI changes
- **Single Store Scope:** MVP limited to single-store scheduling (no cross-store features)
- **No Real-Time Sync:** Changing providers does not migrate historical schedule/timesheet data
- **Syncfusion License:** Community License requires <$1M annual revenue and ≤5 developers; larger deployments require commercial license evaluation
- **Jurisdiction Complexity:** Overtime rules vary across US states and Canadian provinces/territories; system supports presets + custom overrides, but stores must verify compliance

### External Provider UX Guidance

When a store uses an **external scheduling provider** (WhenIWork or Homebase), the following UX applies:

**What IS visible when using external provider:**
- Schedule panel (spec 010) - shows employee avatars from external provider data
- Provider selection in store settings - to allow changing providers
- "Powered by [Provider Name]" indicator in schedule panel header
- Clock in/out and break actions in workbook - BuyerKiosk UI remains the same, but calls the external provider API

**What is HIDDEN/DISABLED when using external provider:**
- Schedule calendar interface (Feature 2) - hidden entirely
- Shift management CRUD (Feature 3) - hidden entirely
- Copy Previous Week (Feature 4) - hidden entirely
- Drag-and-drop editing (Feature 5) - hidden entirely
- Timesheet dashboard / approval / export (Feature 11-14) - hidden entirely (managed in external provider)
- Overtime configuration (Feature 9) - hidden (managed in external provider)
- Labor cost calculation (Feature 10) - hidden (managed in external provider)

**Warning when using external provider:**
- Banner in store settings: "Scheduling and timesheets are managed by [Provider Name]. Approvals and exports happen in [Provider Name]."
- If manager tries to access hidden features via URL: Redirect to store settings with message "Enable BuyerKiosk scheduling to use this feature"

**Warning when switching providers:**
- Modal: "Switching from [Current Provider] to BuyerKiosk will not transfer existing schedules or timesheets. You'll start fresh with BuyerKiosk. Are you sure?"
- Reverse warning when switching TO external provider: "Switching to [External Provider] will disable BuyerKiosk scheduling features. Existing BuyerKiosk schedules will be hidden (not deleted)."

**When schedulingProvider='none':**
- All scheduling features hidden
- Schedule panel shows: "Scheduling not configured. Choose a provider in Store Settings to enable."
- Store settings shows provider selection as prominently featured setup step

### Assumptions
- 007-unified-users-auth provides unified employee records with PIN field available
- Schedule panel (010) is implemented and working with WhenIWork provider
- Stores average 10-30 employees for performance considerations
- Managers have reliable internet access when using scheduling features
- QuickBooks is the primary payroll system for most stores
- Syncfusion Community License terms are acceptable for initial deployment

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| 007 unified users delayed | High | Medium | Can stub employee data; prioritize 007 completion |
| WhenIWork feature parity concerns | Medium | High | Clear MVP scope communication; roadmap for post-MVP features |
| Performance with large employee counts | Medium | Low | Pagination, lazy loading; stress test with 100+ employees |
| Time zone handling complexity | Medium | Medium | Store timezone configuration; server-side UTC storage |
| Break law compliance variations | High | Medium | Configurable rules; disclaimer that system assists but doesn't guarantee compliance |
| Manager resistance to new system | Medium | Medium | Smooth migration path; training materials; keep external providers as option |
| Syncfusion license upgrade needed | Low | Low | Monitor revenue growth; budget for commercial license if needed |
| Syncfusion version compatibility | Medium | Low | Pin specific version; test upgrades in staging before production |

## Open Questions

All open questions resolved during requirements gathering:

- [x] MVP scope defined: Basic scheduling with full time tracking (no auto-scheduling)
- [x] Provider model confirmed: One active provider per store
- [x] Employee access confirmed: View-only schedule via web admin, clock-in via workbook only
- [x] Overtime rules: Store-configurable (jurisdiction presets + custom)
- [x] Break tracking: Simple paid/unpaid tracking (no enforcement rules in MVP)
- [x] Multi-store: Separate schedules per store for MVP
- [x] Alerts: Post-MVP feature
- [x] Forecasting integration: Post-MVP feature
- [x] UI Framework: Syncfusion EJ2 Schedule with Community License

---

## Supporting Research

### UI Reference Screenshots

These screenshots are UI references for the Syncfusion scheduling views and the BuyerKiosk native timesheet approval UI.

- Day view: `docs/specs/013-employee-scheduling/day_view.png`
- Week view: `docs/specs/013-employee-scheduling/week_view.png`
- Month view: `docs/specs/013-employee-scheduling/month_view.png`
- Timesheet approval: `docs/specs/013-employee-scheduling/timesheet_approval.png`

![Scheduling Day View](day_view.png)

![Scheduling Week View](week_view.png)

![Scheduling Month View](month_view.png)

![Timesheet Approval](timesheet_approval.png)

### Jurisdiction Coverage (US + Canada)

BuyerKiosk native overtime calculation supports stores in:
- US: all states + District of Columbia (DC)
- Canada: all provinces + territories

Overtime rules are applied based on the store's selected jurisdiction preset (or a custom override when needed).

### Competitive Analysis

**WhenIWork:**
- Strengths: Mobile app, auto-scheduling, shift trading, time-off management, team messaging
- Weaknesses: Per-employee pricing ($2-4/user/month), external system requiring integration
- Key insight: Auto-scheduling is their flagship feature but requires significant data (availability, preferences)

**Homebase:**
- Strengths: Free tier available, hiring/onboarding features, team communication
- Weaknesses: Limited reporting on free tier, push to paid plans for advanced features
- Key insight: Free tier attracts small businesses but lacks features stores need

**Syncfusion EJ2 Schedule:**
- Strengths: Enterprise-grade, full-featured, Bootstrap 5 theme, comprehensive documentation
- Weaknesses: Learning curve for customization, requires JavaScript expertise
- Key insight: Provides 80%+ of needed calendar UI functionality out-of-the-box

**BuyerKiosk Opportunity:**
- Zero additional cost for existing customers
- Native integration with store data (sales, buys, events)
- Foundation for future intelligent features (sales-based staffing)
- Maintains choice - stores can still use WhenIWork/Homebase if preferred
- Rapid delivery via Syncfusion (weeks instead of months)

### User Research

Based on requirements gathering session:
- Store owners want to reduce operational costs where possible
- Full time tracking with overtime is essential, not optional
- Weekly timesheet approval is important for payroll accuracy
- Managers need labor cost visibility while scheduling
- Employees want easy access to view their schedule from home
- Current WhenIWork users expect feature parity over time

### Market Data

- Small business scheduling software market growing ~10% annually
- Increasing labor law complexity (overtime, break requirements) driving need for automated tracking
- Mobile-first workforce expects schedule access on personal devices
- Integration with payroll systems is table-stakes expectation

### Syncfusion Reference

- Documentation: https://ej2.syncfusion.com/javascript/documentation/schedule/
- Resources API: https://ej2.syncfusion.com/javascript/documentation/schedule/resources
- Appointments API: https://ej2.syncfusion.com/javascript/documentation/schedule/appointments
- NPM Package: @syncfusion/ej2-schedule
- License Info: https://www.syncfusion.com/products/communitylicense
