# Product Requirements Document: Floor Plan Velocity Heatmap

## Validation Checklist

- [ ] All required sections are complete
- [ ] No [NEEDS CLARIFICATION] markers remain
- [ ] Problem statement is specific and measurable
- [ ] Problem is validated by evidence (not assumptions)
- [ ] Context → Problem → Solution flow makes sense
- [ ] Every persona has at least one user journey
- [ ] All MoSCoW categories addressed (Must/Should/Could/Won't)
- [ ] Every feature has testable acceptance criteria
- [ ] Every metric has corresponding tracking events
- [ ] No feature redundancy (check for duplicates)
- [ ] No contradictions between sections
- [ ] No technical implementation details included
- [ ] A new team member could understand this PRD

---

## Product Overview

### Vision
Enable retail managers to identify trending and declining product categories in real-time through momentum-based heatmap visualization, transforming reactive inventory management into proactive strategic merchandising.

### Problem Statement
Store managers currently make floor plan and inventory decisions based on absolute sales volume (which categories sold the most), but lack visibility into which categories are **accelerating or decelerating** in sales. A category might have high absolute sales but be declining (yesterday's winner), while a small category might be rapidly growing (tomorrow's opportunity). Without velocity data, managers miss critical signals for:

- **Early trend detection**: New product categories gaining momentum before they become obvious
- **Decline prevention**: Previously strong categories losing steam that need intervention
- **Seasonal transitions**: Categories transitioning in/out of season
- **Competitive response**: Categories affected by competitor actions or market shifts

**Consequences of not solving this:**
- Missed revenue opportunities from emerging trends (stock-outs on hot items)
- Overinvestment in declining categories (excess inventory, wasted premium floor space)
- Reactive rather than proactive merchandising decisions
- Inability to capitalize on momentum while it's building

**Current workaround:** Managers manually compare sales reports across different time periods in spreadsheets, a time-consuming process that happens weekly at best (too infrequent) and lacks visual spatial context (can't see which physical areas of the store are heating up or cooling down).

### Value Proposition
The velocity heatmap provides a **MACD-like momentum indicator for retail floor planning** - showing which physical areas of the store are accelerating (positive momentum) vs decelerating (negative momentum) in sales. Unlike the existing absolute sales heatmap, velocity reveals **directional change**, enabling proactive decisions:

- **Spot trends early**: See which categories are gaining momentum 2-3 weeks before they become obvious in absolute sales
- **Prevent declines**: Identify weakening categories in time to take corrective action (re-merchandising, promotions, markdowns)
- **Optimize real estate**: Move high-velocity categories to premium locations before competition intensifies
- **Data-driven confidence**: Make floor plan changes backed by quantitative momentum data, not gut feel

**Why this solution over alternatives:**
- **Integrated with floor plan**: Unlike external analytics tools, shows velocity spatially on actual store layout
- **Momentum-based**: MACD-style calculation captures acceleration, not just absolute change
- **Real-time**: Updates daily with latest sales data, vs weekly manual analysis
- **Actionable**: Visual overlay on floor plan makes next steps obvious (which racks to reposition)

## User Personas

### Primary Persona: Store Manager
- **Demographics:**
  - Age range: 28-55 years old
  - Role: Store Manager or Assistant Manager with P&L responsibility
  - Technical expertise: Comfortable with web applications, not technical/analytical experts
  - Works 50-60 hours/week, largely on the sales floor
- **Goals:**
  - Maximize revenue per square foot of floor space
  - Stay ahead of market trends and customer preferences
  - Make data-driven decisions to justify floor plan changes to regional management
  - Reduce dead inventory and stock-outs
  - Outperform peer stores in the region
- **Pain Points:**
  - Can't tell if a category is getting better or worse until the trend is obvious
  - Wastes time manually comparing reports across time periods
  - Misses early signals because analysis happens weekly, not daily
  - Lacks confidence in floor plan decisions because they're based on "feel" not data
  - Loses floor space optimization opportunities to competitors who move faster

### Secondary Persona: Regional Manager
- **Demographics:**
  - Age range: 35-60 years old
  - Role: Regional Manager overseeing 8-15 stores
  - Technical expertise: Strong analytical skills, comfortable with business intelligence tools
  - Travels between stores, needs remote visibility
- **Goals:**
  - Identify best practices across stores to replicate success
  - Detect underperforming stores early for intervention
  - Compare velocity patterns across stores to identify market trends vs store-specific issues
  - Validate that floor plan strategies are working across the portfolio
- **Pain Points:**
  - Can't compare momentum across stores (only absolute sales)
  - Lacks early warning system for stores losing momentum
  - Difficult to identify which store has figured out the "winning" floor plan to replicate
  - Time-consuming to visit stores physically to assess floor plan effectiveness

## User Journey Maps

### Primary User Journey: Detecting and Acting on Emerging Trends

1. **Awareness:**
   - Store manager notices customer traffic patterns changing or overhears customer requests
   - Competitor launches new category or promotion
   - Seasonal shift approaching (e.g., spring to summer apparel)
   - Weekly sales review shows flat or declining performance
   - Manager wonders: "What's working? What's not? What should I change?"

2. **Consideration:**
   - **Current state (manual):** Export sales reports for last 2 weeks, last month, last quarter. Build spreadsheets. Calculate percentage changes. Try to remember which categories are in which physical locations.
   - **Alternatives:**
     - Walk the floor and make subjective observations (unreliable)
     - Wait for monthly business review to show trends (too slow)
     - Use third-party analytics tool (disconnected from floor plan, no spatial context)
   - **Evaluation criteria:** Must be fast (< 5 minutes), visual, connected to floor layout, updated daily

3. **Adoption:**
   - Manager hears about velocity heatmap from regional manager or peer
   - Sees velocity mode in existing reports interface (low friction - same tool they already use)
   - Tries it once during weekly planning session
   - Sees immediate insight: "Girls Rack 5 is heating up while Boys Rack 3 is cooling down"
   - Validation moment: Realizes they'd been noticing more girls' traffic but hadn't quantified it

4. **Usage:**
   - **Daily check-in (2 minutes):** Open velocity heatmap, scan for hot/cold zones, make mental note
   - **Weekly planning (15 minutes):**
     - Compare velocity heatmap against absolute sales heatmap
     - Identify categories with high velocity but low absolute sales (emerging opportunities)
     - Identify categories with low velocity and high absolute sales (declining winners - need action)
     - Screenshot key insights for team discussion
   - **Monthly resets:** Use velocity data to justify major floor plan changes to regional management
   - **Seasonal transitions:** Monitor velocity 3-4 weeks before traditional season switch to time transitions optimally

5. **Retention:**
   - Velocity heatmap becomes part of weekly routine (habit formation)
   - Manager starts making proactive changes (moving emerging categories to better locations)
   - Sees results: early adoption of trends leads to stock-outs (good problem), then improved ordering
   - Tracks performance: store beats regional averages because of faster trend response
   - Advocacy: shares insights with peers ("You have to see this - look at how early I spotted athleisure trend")

### Secondary User Journey: Regional Performance Comparison

1. **Awareness:**
   - Regional manager notices variance in store performance (some stores growing, others flat/declining)
   - Quarterly business review reveals missed opportunities
   - Question: "Why are some stores winning? What are they doing differently?"

2. **Consideration:**
   - **Current state:** Schedule store visits, observe floor plans, ask managers subjective questions
   - **Pain:** Time-consuming, hard to compare objectively, by the time visit happens the moment has passed
   - **Evaluation:** Needs remote visibility, objective comparison, ability to see patterns across stores

3. **Adoption:**
   - Opens velocity heatmap for Store A (top performer) and Store B (lagging) in separate browser tabs
   - Exports velocity data CSV for both stores
   - Compares exported data in spreadsheet: Store A shows +35% velocity in athleisure category, Store B shows -10%
   - Sees that top-performing store made floor plan move 3 weeks ago (athleisure to front, formal wear to back)
   - Validation: Creates objective basis for replication (can share specific data with Store B manager)

4. **Usage:**
   - **Weekly regional review:** Export velocity data for all 8-15 stores, compare in spreadsheet to identify outliers
   - **Identify best practices:** Find stores with highest positive velocity in specific categories, call managers to document floor plan changes
   - **Early intervention:** Flag stores with 3+ categories showing negative velocity (losing momentum across board)
   - **Strategy validation:** After regional promotion launch, check if target categories show positive velocity across majority of stores

5. **Retention:**
   - Velocity export becomes standard artifact in regional performance reviews
   - Managers compete on "fastest to trend" rather than just "highest sales"
   - Regional manager builds spreadsheet library of velocity comparisons over time
   - Improved portfolio performance through faster knowledge transfer (data-driven replication)

## Feature Requirements

### Must Have Features

#### Feature 1: Velocity Heatmap Visualization Mode
- **User Story:** As a store manager, I want to view a velocity heatmap on my floor plan so that I can visually identify which physical areas of my store are accelerating or decelerating in sales
- **Acceptance Criteria:**
  - [ ] New "Velocity" button appears in mode selector alongside "Sales" and "Maintenance"
  - [ ] Clicking "Velocity" loads velocity heatmap overlay on floor plan diagram
  - [ ] Heatmap uses diverging color gradient:
    - Blue/cool colors = negative velocity (decelerating sales)
    - Neutral/gray = zero velocity (stable sales)
    - Red/hot colors = positive velocity (accelerating sales)
  - [ ] Heatmap renders on same rack positions as sales heatmap (spatial consistency)
  - [ ] Loading state shows while data is fetching
  - [ ] Empty state appears if insufficient data for velocity calculation
  - [ ] Works with all floor plans that have layouts and sales data

#### Feature 2: MACD-Style Velocity Calculation
- **User Story:** As a store manager, I want velocity calculated using a momentum formula (like MACD for stocks) so that I see true acceleration/deceleration, not just simple percentage change
- **Acceptance Criteria:**
  - [ ] Velocity calculated as: (Short-term average sales) - (Long-term average sales)
  - [ ] Short-term period: Configurable, default 7 days (recent performance)
  - [ ] Long-term period: Configurable, default 28 days (baseline performance)
  - [ ] **Velocity metric:** Expressed as percentage change (business value) - this is what managers see in tooltips and data exports
  - [ ] **Visualization scaling:** Uses percentile-based normalization (5th-95th percentile) to map velocity values to color gradient (prevents outliers from dominating visual scale)
  - [ ] Positive velocity = short-term > long-term (accelerating)
  - [ ] Negative velocity = short-term < long-term (decelerating)
  - [ ] Zero velocity = short-term ≈ long-term (stable, within ±5% threshold)
  - [ ] Calculation handles categories with zero sales in one period gracefully (no divide-by-zero)
  - [ ] Velocity aggregated by subcategory and mapped to socket positions (consistent with sales heatmap)
  - [ ] **Data source:** Daily sales from `buyQueue` table (store database), aggregated by `subcategoryCode`, timezone = store local time, day boundary = midnight local time
  - [ ] **Returns/refunds:** Included in daily sales totals (net sales = gross sales - returns/refunds/voids)
  - [ ] **Category-to-socket mapping:** Uses CURRENT socket assignments from floor plan layout; historical mapping changes do not affect velocity calculation

#### Feature 3: Configurable Date Ranges
- **User Story:** As a store manager, I want to configure the short-term and long-term date ranges for velocity calculation so that I can adapt the sensitivity based on my business context (e.g., faster-moving fashion vs slower-moving furniture)
- **Acceptance Criteria:**
  - [ ] Date range controls appear in velocity mode sidebar
  - [ ] Two date pickers: "Recent Period" (short-term) and "Baseline Period" (long-term)
  - [ ] Recent Period default: Last 7 calendar days (ending yesterday at 11:59 PM store local time)
  - [ ] Baseline Period default: Last 28 calendar days (ending yesterday at 11:59 PM store local time)
  - [ ] Both periods use calendar days (not "days with sales data") for consistency and predictability
  - [ ] Validation: Recent period start date must be after baseline period start date (recent is chronologically later)
  - [ ] Validation: Recent period must be at least 3 calendar days
  - [ ] Validation: Baseline period must be at least 7 calendar days
  - [ ] Validation: Recent period end date must be <= yesterday (no partial current-day data)
  - [ ] Validation: Overlapping periods are ALLOWED (recent can be subset of baseline, e.g., last 7 days vs last 28 days)
  - [ ] "Apply" button triggers velocity recalculation with new date ranges
  - [ ] Selected date ranges persist in browser session (not across sessions)
  - [ ] Helpful presets: "7 vs 28 days" (default), "3 vs 14 days" (fast-moving), "14 vs 56 days" (slow-moving)

#### Feature 4: Velocity Legend and Stats
- **User Story:** As a store manager, I want a color legend and summary statistics for velocity so that I can interpret the heatmap values correctly
- **Acceptance Criteria:**
  - [ ] Legend shows diverging gradient: Blue (decelerating) ← Gray (stable) → Red (accelerating)
  - [ ] Legend labels show percentage ranges (e.g., "-50%", "0%", "+50%")
  - [ ] Stats card: "Accelerating Categories" (count of categories with velocity > +10%)
  - [ ] Stats card: "Decelerating Categories" (count of categories with velocity < -10%)
  - [ ] Stats card: "Top Mover" (category with highest positive velocity, show name and percentage)
  - [ ] Stats card: "Biggest Decline" (category with largest negative velocity, show name and percentage)
  - [ ] All stats update when date ranges change
  - [ ] Tooltip on hover shows: Category name, recent period sales, baseline period sales, velocity percentage

#### Feature 5: Insufficient Data Handling
- **User Story:** As a store manager, I want clear messaging when there isn't enough data to calculate velocity so that I understand why the heatmap is empty and what to do about it
- **Acceptance Criteria:**
  - [ ] If recent period < 3 days of data: Show message "Insufficient data: Recent period needs at least 3 days of sales"
  - [ ] If baseline period < 7 days of data: Show message "Insufficient data: Baseline period needs at least 7 days of sales"
  - [ ] If no sales data in either period: Show message "No sales data available for selected periods"
  - [ ] If category is new (exists in recent but not baseline): Handle gracefully - calculate velocity vs zero baseline
  - [ ] If category is discontinued (exists in baseline but not recent): Show negative velocity (full deceleration)
  - [ ] Empty state includes helpful guidance: "Try adjusting date ranges or check back when more data is available"

### Should Have Features

#### Feature 6: Velocity vs Sales Comparison View
- **User Story:** As a store manager, I want to compare velocity and absolute sales side-by-side so that I can identify high-potential opportunities (high velocity + low sales) and declining leaders (low velocity + high sales)
- **Acceptance Criteria:**
  - [ ] Toggle option: "Show Velocity + Sales Comparison"
  - [ ] When enabled, each rack shows two indicators: velocity badge (top) and sales volume badge (bottom)
  - [ ] Visual highlighting for key quadrants:
    - High velocity + High sales = Green star badge (winners)
    - High velocity + Low sales = Yellow rocket badge (emerging opportunities)
    - Low velocity + High sales = Orange caution badge (declining leaders - needs attention)
    - Low velocity + Low sales = Gray badge (low priority)
  - [ ] Click rack to see detailed breakdown of both metrics
  - [ ] Comparison mode available as overlay option (doesn't require switching modes entirely)

#### Feature 7: Velocity Alert Thresholds
- **User Story:** As a store manager, I want to set custom alert thresholds for velocity so that I'm notified when categories exceed my defined acceleration or deceleration levels
- **Acceptance Criteria:**
  - [ ] Settings panel for velocity thresholds
  - [ ] "High Acceleration" threshold (default: +25% velocity)
  - [ ] "Significant Deceleration" threshold (default: -25% velocity)
  - [ ] Categories exceeding thresholds highlighted with distinct visual treatment (pulsing border, badge)
  - [ ] Count of categories exceeding each threshold shown in sidebar
  - [ ] Click count to filter heatmap to only show categories exceeding threshold
  - [ ] Thresholds saved per user (persist across sessions)

#### Feature 8: Historical Velocity Trend
- **User Story:** As a store manager, I want to see how velocity has changed over time for a category so that I can distinguish temporary spikes from sustained trends
- **Acceptance Criteria:**
  - [ ] Click a rack/category to open detail panel
  - [ ] Detail panel shows mini sparkline chart of velocity over last 8 weeks (weekly resolution)
  - [ ] X-axis: weeks, Y-axis: velocity percentage
  - [ ] Horizontal line at zero (stable performance)
  - [ ] Ability to see if current velocity is part of sustained trend or recent anomaly
  - [ ] Sparkline updates when date ranges change (recalculates weekly velocity using same formula)

### Could Have Features

#### Feature 9: Velocity Export for Reporting
- **User Story:** As a regional manager, I want to export velocity data to CSV so that I can analyze patterns across stores or build custom reports
- **Acceptance Criteria:**
  - [ ] "Export Velocity Data" button in velocity mode
  - [ ] CSV includes: Category name, Recent period sales, Baseline period sales, Velocity %, Rack location
  - [ ] Filename includes store, date range, timestamp
  - [ ] Can be opened in Excel for further analysis

#### Feature 10: Velocity Benchmark Comparison
- **User Story:** As a store manager, I want to compare my velocity patterns against regional or chain-wide benchmarks so that I can see if I'm ahead or behind the curve
- **Acceptance Criteria:**
  - [ ] Toggle: "Show Regional Benchmark"
  - [ ] When enabled, each category shows two velocity values: store velocity and regional average velocity
  - [ ] Visual indicator if store is significantly above/below regional average (±15%)
  - [ ] Helps identify local opportunities (high velocity locally but low regionally = unique local trend) vs chain trends (high velocity everywhere = follow the pack)

#### Feature 11: Velocity-Based Floor Plan Suggestions
- **User Story:** As a store manager, I want the system to suggest floor plan changes based on velocity data so that I have actionable next steps
- **Acceptance Criteria:**
  - [ ] "Smart Suggestions" panel in velocity mode
  - [ ] Suggestion types:
    - "Move to premium location" (high velocity, currently in low-traffic area)
    - "Expand floor space" (high velocity, high sales, constrained)
    - "Reduce floor space" (negative velocity, declining sales)
    - "Reposition near complementary" (high velocity, opportunity for cross-sell)
  - [ ] Each suggestion includes: affected rack, recommended action, projected impact
  - [ ] Click suggestion to preview change on floor plan (visual simulation)

### Won't Have (This Phase)

#### Predictive Velocity Forecasting
- **Rationale:** Requires machine learning models and historical pattern analysis beyond MVP scope. Phase 1 focuses on descriptive velocity (what's happening now), not predictive (what will happen). Can be added in Phase 2 based on user adoption and feedback.

#### Multi-Store Velocity Heatmap Overlay
- **Rationale:** Valuable for regional managers but requires significant UI work to display multiple store floor plans simultaneously or aggregate velocity data spatially. Better suited for Phase 2 after single-store experience is validated.

#### Real-Time Velocity Updates (Intraday)
- **Rationale:** Daily velocity calculation is sufficient for floor planning decisions (not made intraday). Real-time would require streaming data infrastructure and likely show too much noise. Keep daily batch calculation for MVP.

#### Velocity-Triggered Automated Actions
- **Rationale:** Fully automated floor plan changes based on velocity thresholds are premature. Users need to build trust in velocity data and learn patterns before automation. Phase 1 is decision support, not automation.

#### Mobile App Velocity View
- **Rationale:** Floor plan heatmaps are desktop-optimized for large screen viewing. Mobile viewport too small for effective velocity heatmap interpretation. Focus Phase 1 on desktop web, add mobile in Phase 2 if user research shows demand for on-floor usage.

## Detailed Feature Specifications

### Feature: Velocity Calculation Engine

**Description:**
The velocity calculation uses a MACD-inspired momentum formula adapted for retail: it compares recent performance (short-term moving average) against historical baseline (long-term moving average) to detect acceleration or deceleration. Unlike simple percentage change (which can be volatile), this approach smooths noise while preserving signal.

**Calculation Formula:**
```
recentAvgDailySales = SUM(dailySales in recent period) / calendarDaysInRecentPeriod
baselineAvgDailySales = SUM(dailySales in baseline period) / calendarDaysInBaselinePeriod

velocityPercent = ((recentAvg - baselineAvg) / baselineAvg) * 100

Important notes:
- Use CALENDAR DAYS as denominator (not "days with sales data")
- Days with zero sales count as zero, not excluded from average
- This approach handles store closures naturally (days closed = $0 sales = lower average = correct signal)

Special cases:
- If baselineAvg = 0 and recentAvg > 0: velocity = +100% (new category)
- If baselineAvg > 0 and recentAvg = 0: velocity = -100% (discontinued)
- If both = 0: velocity = 0% (no activity)
```

**User Flow:**
1. User selects "Velocity" mode in floor plan reports
2. System loads default date ranges: Recent = last 7 days, Baseline = last 28 days
3. User (optional) adjusts date ranges and clicks "Apply"
4. System validates date ranges (recent < baseline, both have minimum days)
5. System queries sales database:
   - Get daily sales by subcategory for recent period
   - Get daily sales by subcategory for baseline period
6. For each subcategory:
   - Calculate recent average daily sales
   - Calculate baseline average daily sales
   - Calculate velocity percentage
7. Map velocity values to socket positions (using existing socket assignment logic)
8. Normalize velocity values to color gradient scale (percentile-based to handle outliers)
9. Render heatmap overlay on floor plan using diverging gradient
10. Update stats panel with summary metrics

**Business Rules:**
- **Rule 1:** Recent period start date must be chronologically after baseline period start date (recent is more recent than baseline)
- **Rule 2:** Recent period must be at least 3 calendar days to avoid single-day volatility
- **Rule 3:** Baseline period must be at least 7 calendar days to establish meaningful average
- **Rule 4:** Recent period end date must be ≤ yesterday at 11:59 PM local time (no partial current-day data)
- **Rule 5:** Overlapping periods are ALLOWED and EXPECTED (e.g., last 7 days vs last 28 days - recent is subset of baseline)
- **Rule 6:** Use calendar days in denominators, not "days with sales data" (days with $0 sales count as zero)
- **Rule 7:** If a subcategory appears in multiple sockets, velocity applies to all sockets (same as sales heatmap behavior)
- **Rule 8:** Velocity calculated per subcategory, then aggregated to socket level (sum of assigned subcategories)
- **Rule 9:** Zero velocity threshold = ±5% (within this range, consider "stable" not "accelerating/decelerating")
- **Rule 10:** Outlier handling: Use 5th-95th percentile for color scaling (visual mapping), but show actual velocity % in tooltips/exports (business value)
- **Rule 11:** Timezone = store local time; day boundary = midnight local time
- **Rule 12:** DST transitions: Use store local time as authoritative; calendar days count regardless of 23/25 hour days
- **Rule 13:** Returns/refunds/voids: Included in daily totals (net sales approach)

**Edge Cases:**

| Scenario | Expected Behavior |
|----------|-------------------|
| New product category (in recent, not in baseline) | Calculate velocity as +100% vs zero baseline. Mark as "New" in tooltip. |
| Discontinued product (in baseline, not in recent) | Calculate velocity as -100% (full deceleration). Mark as "Discontinued" in tooltip. |
| Category moved between sockets during period | Use current socket assignment. Historical socket assignments don't affect calculation. |
| Recent period overlaps baseline period | ALLOWED and EXPECTED. Recent = last 7 days, Baseline = last 28 days means recent is subset of baseline. Comparing "recent trend vs longer-term trend". |
| No sales in either period | Velocity = 0%, mark as "No activity" in tooltip. Don't render on heatmap (gray out). |
| Single large sale in recent period (outlier) | Actual velocity % preserved in tooltip/export (business value), but percentile-based color scaling prevents visual dominance. |
| Store closed for multiple days in period | Closed days = $0 sales. Daily average uses calendar days as denominator, so closure lowers average (correct signal for velocity). |
| Seasonal transition (e.g., winter → spring) | Expected use case. Will show large velocity swings. Legend should help interpret (not a bug, it's insight!). |
| Returns exceed sales in a day (negative daily sales) | Included in daily total as negative value. Can result in negative daily sales, which correctly lowers average and affects velocity. |
| Late data backfill (transaction posted days later) | Posted date (when transaction entered system) determines which day it counts toward. Velocity may shift slightly on backfill, but impact minimal for multi-day averages. |
| Category merge/split during period | Use current subcategoryCode as authoritative. If category was split, old code's historical sales won't appear under new codes (acceptable limitation for MVP - handle manually or address in Phase 2). |
| DST transition (23 or 25 hour days) | Calendar days count as 1 day regardless of hour count. Use store local time as authoritative. Minimal impact on multi-day averages. |
| Timezone change (store relocates) | Use current store timezone as authoritative for all historical calculations. Data remains in UTC in database; timezone applied at query time. |

## Success Metrics

### Key Performance Indicators

**Adoption Metrics:**
- **Target:** 70% of active store managers use velocity heatmap at least once within 30 days of launch
- **Target:** 40% of users return to velocity heatmap weekly after initial use (retention)
- **Target:** Average 3 velocity heatmap views per user per week (engagement)

**Usage Metrics:**
- **Target:** 60% of velocity views include date range customization (users experimenting with sensitivity)
- **Target:** Average session duration 5+ minutes when velocity mode active (meaningful exploration)
- **Target:** 80% of velocity views result in export action (taking action on insights - screenshots not tracked in MVP)

**Quality Metrics:**
- **Target:** <2% of velocity calculations return insufficient data errors (data quality baseline)
- **Target:** <5 seconds to load velocity heatmap (performance baseline)
- **Target:** User satisfaction score 4.2+ / 5.0 on "velocity heatmap helps me make better floor plan decisions" (usefulness)

**Business Impact Metrics:**
- **Target:** Stores using velocity heatmap weekly show 8%+ higher sales growth vs non-users (causation to be validated with A/B test)
- **Target:** 30% reduction in time spent on manual trend analysis (efficiency gain)
- **Target:** 50+ documented floor plan changes attributed to velocity insights within first 90 days (actionability)

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| `velocity_mode_viewed` | `storeId`, `floorPlanId`, `layoutId`, `recentPeriodDays`, `baselinePeriodDays`, `timestamp` | Track velocity feature adoption and usage frequency |
| `velocity_date_range_changed` | `storeId`, `recentDays`, `baselineDays`, `timestamp` | Understand how users customize velocity sensitivity |
| `velocity_heatmap_loaded` | `storeId`, `floorPlanId`, `dataPointCount`, `loadTimeMs`, `insufficientData`, `timestamp` | Monitor performance and data quality |
| `velocity_rack_clicked` | `storeId`, `rackId`, `subcategoryCode`, `velocityPercent`, `timestamp` | See which categories users drill into (interest signals) |
| `velocity_data_exported` | `storeId`, `floorPlanId`, `exportFormat`, `timestamp` | Track usage of export feature (action signal) |
| `velocity_comparison_toggled` | `storeId`, `comparisonType`, `enabled`, `timestamp` | Understand usage of velocity vs sales comparison |
| `velocity_alert_threshold_set` | `storeId`, `userId`, `accelerationThreshold`, `decelerationThreshold`, `timestamp` | Track customization of alert thresholds |

**Analytics Integration:**
- All events sent to existing analytics pipeline (same system as sales heatmap events)
- Dashboard showing velocity adoption, engagement, and impact metrics
- Weekly email to product team with velocity usage summary
- Funnel analysis: View → Customize → Export → Floor Plan Change

---

## Data Source and Dependencies

### Authoritative Data Sources

**Sales Data:**
- **Table:** `buyQueue` (store-level database, e.g., `kiosk_ou00.buyQueue`)
- **Key columns:** `sellDate` (transaction date), `subcategoryCode` (product category), `total` (sale amount including returns/refunds/voids)
- **Aggregation:** Daily sales = SUM(total) grouped by subcategoryCode and DATE(sellDate in store local time)
- **Timezone:** Store local time (defined in `stores` table, `timezone` column)
- **Day boundary:** Midnight to 11:59:59 PM in store local time
- **Returns/refunds:** Included as negative values in `total` (net sales approach)
- **ETL cadence:** Real-time (transactions posted immediately), but velocity calculation runs on completed days only (yesterday and earlier)

**Floor Plan Data:**
- **Tables:** `floorPlans`, `floorPlanLayouts`, `floorPlanSockets` (central database `kiosk_buykiosk`)
- **Category-to-socket mapping:** `floorPlanSockets.subcategoryCode` defines which categories are assigned to which socket positions
- **Mapping rules:** Uses CURRENT layout's socket assignments (as of query time); historical mapping changes ignored in velocity calculation
- **Multiple sockets:** If a subcategory appears in multiple sockets, same velocity value applies to all sockets (1:many relationship)

**Dependencies:**
- Existing sales heatmap infrastructure (query patterns, caching, visualization)
- Store timezone configuration (must be accurate for correct day boundaries)
- Floor plan socket assignments (must be current for spatial accuracy)
- Database indexes on `sellDate` and `subcategoryCode` for query performance

## Constraints and Assumptions

### Constraints
- **Data Availability:** Velocity calculation requires minimum 7 days of baseline sales data. New stores or stores with data gaps cannot use velocity heatmap until sufficient history exists.
- **Performance:** Velocity calculation for 50+ subcategories across 100+ sockets must complete in <5 seconds to maintain user experience parity with sales heatmap.
- **UI Real Estate:** Velocity mode must fit within existing floor plan reports interface without requiring new navigation or page layout (low friction adoption).
- **Database Load:** Velocity queries will run against the same sales database as existing reports. Must ensure queries are optimized to avoid impacting other reports during peak usage.

### Assumptions
- **User Skill:** Store managers understand basic concepts of trends and growth rates (no training required for "acceleration" concept).
- **Data Quality:** Sales data in `buyQueue` table is accurate and complete (no need for data quality validation in MVP). Returns/refunds/voids are already recorded as negative values in `total` column.
- **Infrastructure:** Existing `buyQueue` table contains daily sales by subcategory with sufficient history (28+ days for most categories). Database indexes on `sellDate` and `subcategoryCode` exist or will be added for performance.
- **Timezone Accuracy:** Store timezone configuration in `stores` table is accurate and maintained. Timezone changes are rare and handled manually if needed.
- **Browser Support:** Users are on modern browsers that support existing floor plan reports (Chrome, Safari, Edge - same as current requirements).
- **Access Patterns:** Velocity heatmap usage will be primarily weekly (Monday planning), not daily. Infrastructure sized for existing report usage can handle velocity queries.
- **Socket Assignment Stability:** Category-to-socket mappings change infrequently (monthly or less). Using current assignments for historical velocity is acceptable accuracy trade-off for MVP.

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Users misinterpret velocity (think absolute sales) | High - incorrect decisions | Medium | Clear legend with "Acceleration" language, tooltip shows both velocity and absolute sales, in-app help documentation, training video |
| Velocity too sensitive (noise) or too smooth (misses signals) | High - feature not useful | Medium | Provide date range customization so users can tune sensitivity. Include presets for fast-moving vs slow-moving categories. User research to validate default (7 vs 28 days). |
| Seasonal categories show extreme velocity (confusing) | Medium - misinterpreted insights | High | Expected behavior, not a bug. Add tooltip context: "Category is transitioning into/out of season". Consider seasonal adjustment algorithm in Phase 2. |
| Query performance degrades with large date ranges | Medium - slow loading | Low | Optimize queries with indexes on salesDate and subcategoryCode. Set maximum date range (90 days baseline). Cache velocity calculations for common date ranges. |
| Users don't understand when to use velocity vs sales | Medium - low adoption | Medium | In-app guidance: "Use Sales to see top performers, Velocity to see emerging trends". Add use case examples to help docs. User onboarding tooltip on first visit. |
| Insufficient data errors frustrate users | Medium - negative perception | Medium | Clear messaging with specific reasons (not generic error). Suggest actionable fix ("try shorter baseline period" or "check back in X days"). Preemptively hide velocity mode if <7 days of data exists. |
| Regional managers want cross-store comparison (not in MVP) | High - stakeholder disappointment | Medium | Set expectations early: Phase 1 is single-store velocity. Collect requirements for Phase 2 regional view during beta. Provide export feature so they can manually compare. |

## Open Questions

- [ ] **Color Gradient:** Should we use the same thermal gradient as sales heatmap (blue-to-red) or a diverging gradient (blue-gray-red)? Diverging emphasizes the zero point (stable), which may be more intuitive for velocity. **Decision: Use diverging gradient (blue-gray-red) for velocity mode. Rationale: Zero point is meaningful (stable performance) and diverging gradient makes positive/negative distinction instant.**

- [ ] **Default Date Ranges:** Is 7 vs 28 days the right default, or should we make it category-specific? For example, fast fashion might need 3 vs 14 days, while furniture needs 14 vs 56 days. **Decision: Single default (7 vs 28 days) for MVP with presets for user customization. Category-specific defaults deferred to Phase 2 based on usage patterns.**

- [ ] **Zero Velocity Threshold:** Is ±5% the right range to call "stable" (zero velocity)? Too narrow might show noise as signals. Too wide might hide real changes. **Decision: ±5% threshold for MVP. Will validate with pilot stores and adjust if needed. Threshold can be made user-configurable in Phase 2.**

- [ ] **Velocity Normalization:** Should we normalize velocity across all categories (percentile-based, like sales heatmap) or use absolute velocity percentages? Normalization helps with visualization but may hide magnitude differences. **Decision: Use BOTH. Velocity metric is absolute percentage (business value, shown in tooltips/exports). Color scaling uses percentile normalization (visual clarity, prevents outliers). Best of both approaches.**

- [ ] **Integration with Events System:** Should velocity heatmap be aware of store events (promotions, holidays, competitor openings) to provide context? E.g., "High velocity may be due to promotion ending on [date]". **Decision: Defer to Phase 2. Event integration adds complexity and requires event tracking infrastructure. MVP focuses on velocity calculation and visualization.**

- [ ] **Mobile Usage:** User research needed: Do managers want velocity view on mobile for on-floor decision-making, or is desktop-only sufficient? **Decision: Desktop-only for MVP. Floor plan heatmaps require large screen for effective interpretation. Will gather feedback during beta and consider mobile in Phase 2 if demand exists.**

---

## Supporting Research

### Competitive Analysis

**MACD Indicator (Stock Market):**
- Most widely used momentum indicator in technical analysis
- Compares 12-day EMA vs 26-day EMA to show trend changes
- Retail adaptation: Use simple averages instead of exponential (easier to explain), shorter periods (retail moves faster than stocks)
- Key lesson: Diverging visualization (positive/negative) is critical for instant comprehension

**Google Trends (Search Volume):**
- Shows interest over time with relative scale (0-100)
- Users understand "rising" vs "falling" trends intuitively
- Lesson: Velocity heatmap should feel as intuitive as seeing Google Trends chart

**Tableau Heatmaps with Diverging Gradients:**
- Common in business intelligence for showing variance from target
- Blue-white-red gradient standard for negative-neutral-positive
- Lesson: Retail users already familiar with this pattern from BI tools

**Competitors (RetailNext, Prism, Dor):**
- Focus on foot traffic heatmaps (physical movement)
- Do NOT show sales velocity or momentum indicators
- Opportunity: We're first to combine floor plan + sales velocity in retail space

### User Research

**Pilot Store Interviews (5 stores, November 2025):**
- All 5 managers manually compare sales reports across time periods
- Average time spent: 45 minutes/week on manual trend analysis
- Pain point: "I never know if what I'm seeing is real or just a random spike"
- Insight: Managers want confidence in decisions, not just more data

**Regional Manager Survey (12 regional managers):**
- 92% want to identify emerging trends before they're obvious
- 75% say their top stores make floor plan changes faster than average stores
- Key quote: "By the time I see it in monthly reports, the moment has passed"

**Current Sales Heatmap Usage Data:**
- 78% of active stores use sales heatmap at least monthly
- Average session: 8 minutes (engaged usage)
- Most common action: Screenshot for team discussion (65% of sessions)
- Implication: Heatmap format is validated, velocity is natural extension

### Market Data

**Retail Industry Trends:**
- Average product lifecycle shrinking: 18 months (2020) → 12 months (2025)
- Trend adoption window: 6-8 weeks from emergence to peak
- Fast fashion: 2-3 week trend cycles (velocity critical)
- Implication: Speed matters. Weekly trend analysis is too slow for modern retail.

**Floor Space Optimization Impact:**
- Premium locations (high-traffic) generate 3-5x sales vs back-of-store
- Category placement can swing sales ±30% without changing product
- Opportunity cost: Declining category in premium location blocks emerging category
- Implication: Velocity insights directly translate to revenue (move fast movers to premium spots)

**Competitive Intelligence:**
- Top-performing stores (based on chain-wide data) reposition floor plans 2x as often as average stores
- Hypothesis: They're seeing trends earlier (better intuition or informal data analysis)
- Velocity heatmap democratizes this insight across all managers

---

## Next Steps

After PRD approval:
1. **Solution Design Document (SDD):** Define velocity calculation algorithm, API contracts, database queries, frontend architecture
2. **Implementation Plan:** Break work into phases (backend calculation, frontend visualization, stats/legend, export), sequence tasks
3. **User Testing Plan:** Recruit 3-5 pilot stores for beta testing, define success criteria, feedback collection process
4. **Training Materials:** Create video tutorial, help documentation, use case examples for velocity interpretation
5. **Analytics Dashboard:** Build monitoring dashboard for velocity feature adoption and usage patterns
