Files
bakery-ia/docs/DASHBOARD_JTBD_ANALYSIS.md
2025-10-24 13:05:04 +02:00

1166 lines
36 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Jobs To Be Done (JTBD) Analysis: Bakery Owner Dashboard Reimagination
**Date:** 2025-10-24
**Status:** Planning Phase
**Objective:** Transform the current "Panel de Control" into a decision support companion aligned with bakery owner workflows
---
## 🎯 MAIN FUNCTIONAL JOB
**When** a bakery owner starts their workday and throughout operations,
**They want to** quickly assess the health of their bakery business and make informed decisions,
**So they can** prevent problems, optimize operations, maximize profitability, and go home confident that tomorrow is under control.
---
## 📊 CURRENT STATE ANALYSIS
### Current Dashboard Components
**Location:** `frontend/src/pages/app/DashboardPage.tsx`
**Existing Widgets:**
1. **StatsGrid** - 4 critical metrics (Sales, Pending Orders, Products Sold, Critical Stock)
2. **RealTimeAlerts** - Today's alerts with filtering/grouping
3. **SustainabilityWidget** - SDG 12.3 compliance and environmental impact
4. **PendingPOApprovals** - Purchase orders needing approval
5. **TodayProduction** - Active production batches
### What's Working Well ✅
- **Real-time data aggregation** from multiple services (sales, inventory, orders, production)
- **Sustainability tracking** aligned with SDG 12.3 (unique value proposition)
- **Action-oriented widgets** (approve POs, start batches directly from dashboard)
- **Multi-language support** (Spanish, Basque, English)
- **Mobile-responsive design** with proper breakpoints
- **Demo tour integration** for onboarding
### Critical Gaps ❌
1. **No narrative/story** - Just data widgets without context
2. **Cognitive overload** - Too many metrics without prioritization
3. **Reactive, not proactive** - Shows problems but doesn't guide actions
4. **No time-based workflow** - Doesn't match bakery daily rhythms
5. **Limited business intelligence** - Raw metrics vs. actionable insights
6. **Missing emotional satisfaction** - No celebration of wins or progress
7. **No financial context** - Metrics without business impact in euros
8. **Team visibility absent** - No view of staff capacity or performance
---
## 🎭 MAIN JOB DECOMPOSITION
### 1. **START THE DAY PREPARED**
**Functional Sub-jobs:**
- Understand what happened yesterday (wins/losses)
- Know what's critical TODAY (time-sensitive priorities)
- See what's coming tomorrow/this week (preparation needs)
- Feel confident about current state (peace of mind)
**Emotional Job:** Feel in control and ready to lead
**Social Job:** Be prepared for team questions and customer commitments
**Current Gaps:**
- No "morning briefing" view
- Yesterday's performance buried in trend percentages
- Tomorrow's needs require navigation to production/procurement pages
- No prioritized action list
**Success Metric:** Owner can answer "What do I need to focus on today?" in <30 seconds
---
### 2. **PREVENT PROBLEMS BEFORE THEY HAPPEN**
**Functional Sub-jobs:**
- Identify risks in real-time (stockouts, delays, quality issues)
- Understand WHY problems are occurring (root cause insights)
- Take immediate action or delegate (integrated workflow)
- Track that actions are being handled (accountability)
**Emotional Job:** Feel proactive and competent, avoid embarrassment of stockouts/delays
**Social Job:** Maintain reputation with customers and team
**Current Gaps:**
- Alerts lack context and prioritization (all treated equally)
- No predictive warnings (only reactive alerts)
- Action tracking disconnected from alerts
- No financial impact shown (which alerts cost money?)
**Success Metric:** 80% of problems prevented before impacting customers
---
### 3. **MAKE PROFITABLE DECISIONS**
**Functional Sub-jobs:**
- See financial impact of daily operations (P&L snapshot)
- Identify waste and inefficiency (cost savings opportunities)
- Understand sales performance vs. targets (goals tracking)
- Forecast cash flow needs (working capital)
**Emotional Job:** Feel financially secure and savvy
**Social Job:** Demonstrate business acumen to partners/investors
**Current Gaps:**
- No financial dashboard view or daily P&L
- Sustainability savings shown but not tied to overall profitability
- No goal/target tracking visible
- Missing cost vs. revenue comparison
- Production costs not visible alongside sales
**Success Metric:** Owner knows daily profit/loss and can explain key drivers
---
### 4. **LEAD THE TEAM EFFECTIVELY**
**Functional Sub-jobs:**
- See team workload and capacity (resource planning)
- Monitor production efficiency (team performance)
- Identify training needs (skill gaps)
- Recognize great work (team morale)
**Social Job:** Be seen as a competent, caring leader by team
**Emotional Job:** Feel confident in team management abilities
**Current Gaps:**
- No team view on dashboard
- No performance recognition system
- Staff assignments buried in batch details (requires drill-down)
- No capacity planning visibility
**Success Metric:** Balanced workload, recognized top performers weekly
---
### 5. **ACHIEVE LONG-TERM GOALS**
**Functional Sub-jobs:**
- Track progress toward sustainability certifications (SDG compliance)
- Monitor business growth trends (month-over-month)
- Prepare for audits/reporting (compliance readiness)
- Build brand reputation (quality, sustainability)
**Emotional Job:** Feel proud and purposeful about their business
**Social Job:** Build reputation as sustainable, quality-focused bakery
**Current Gaps:**
- Sustainability widget is excellent but isolated from other goals
- No long-term trend visualization (only day-over-day)
- Missing quality score trends over time
- No certification readiness indicators
- Growth metrics not prominent
**Success Metric:** Progress visible toward 3-6 month goals, certification-ready data
---
## 🚧 FORCES OF PROGRESS
### Push Forces (Problems with Current Situation)
- "I spend 30 minutes every morning checking different screens to know what's happening"
- "I discover problems too late to fix them without customer impact"
- "I don't know if we're making money until month-end accounting"
- "My team doesn't know what's most important each day"
- "I can't explain our sustainability efforts to certification auditors"
- "I miss opportunities to celebrate team wins"
### Pull Forces (Attraction of New Solution)
- "One glance tells me everything I need to know to start my day"
- "I get early warnings with suggested actions before problems escalate"
- "I see profit impact in real-time and understand what drives it"
- "Clear priorities that everyone on the team can follow"
- "Sustainability progress tracked automatically for certifications"
- "System highlights achievements to share with the team"
### Anxiety Forces (Fears About Change)
- "Will it be overwhelming with too much information?"
- "Will I lose visibility into details I occasionally need?"
- "Will my team resist learning a new interface?"
- "Will setup and configuration take too long?"
- "What if the AI insights are wrong?"
### Habit Forces (What Keeps Them in Current State)
- "I'm used to my morning routine of checking multiple tabs"
- "I know where to find what I need in the current layout"
- "The team knows the current process and workflows"
- "It's working 'well enough' - why risk breaking it?"
- "I don't have time to learn something new right now"
---
## 🎯 DESIGN PRINCIPLES FOR REIMAGINED DASHBOARD
### 1. **Time-Contextualized Design** (vs. Static Metrics)
**Morning View (6-10 AM):**
- Yesterday's summary (what you missed overnight)
- TODAY's priorities (time-ordered, actionable)
- Quick wins available (morale boost, easy completions)
- Team arrival and readiness status
**Midday View (10 AM - 5 PM):**
- Real-time operations status
- Production vs. sales gap analysis
- Critical alerts only (P0/P1)
- Current profitability snapshot
**Evening View (5-8 PM):**
- Tomorrow's preparation checklist
- Today's achievements (celebrate!)
- Delegation status (what's covered for tomorrow)
- Unresolved items requiring attention
**Implementation:** Use `useTimeContext` hook to dynamically adjust widget visibility and content
---
### 2. **Narrative-Driven Metrics** (vs. Raw Numbers)
**Before:**
```
Sales Today: €1,247
↑ 15.2% vs yesterday
```
**After:**
```
€1,247 today — €200 above Tuesday average
On track for best week this month 🎯
Next milestone: €1,500 day (€253 to go)
```
**Implementation Approach:**
- Add context layer to all metrics
- Compare to meaningful benchmarks (not just yesterday)
- Show progress toward goals
- Use natural language, not just percentages
---
### 3. **Action Priority System** (vs. All Alerts Equal)
**Priority Levels:**
- **P0 (NOW - Red Zone):** Revenue-impacting, customer-facing, <2 hours to resolve
- Example: "Stockout on bestseller, 5 customer orders waiting"
- Auto-escalate to owner's phone if not acknowledged in 30 min
- **P1 (TODAY - Amber Zone):** Must be resolved before close of business
- Example: "PO #1847 approval needed for tomorrow's delivery"
- Show on morning briefing
- **P2 (THIS WEEK - Blue Zone):** Optimization opportunities
- Example: "Waste trending up 10% this week"
- Show in evening checklist
- **P3 (BACKLOG - Green Zone):** Nice-to-have improvements
- Example: "Consider alternative supplier for flour (5% cheaper)"
- Show in weekly review only
**Priority Calculation Algorithm:**
```typescript
priority = (financial_impact * 0.4) +
(time_urgency * 0.3) +
(customer_impact * 0.2) +
(compliance_risk * 0.1)
```
---
### 4. **Financial Context Always** (vs. Operational Metrics Only)
**Every widget shows business impact:**
- Inventory: "23 kg waste prevented 187 saved this month"
- Production: "Batch 15% faster 2.5 hours labor saved (€45)"
- Procurement: "3 urgent PO approvals 1,340 in orders unlocked"
- Alerts: "Critical stockout 450 in sales at risk"
- Sustainability: "CO reduction 230 potential grant value"
**Implementation:**
- Create `FinancialImpactBadge` component (reusable)
- Add `impact_euros` field to all data models
- Calculate impact server-side for consistency
---
### 5. **Celebration & Progress** (vs. Problem-Focused)
**Daily Wins Section:**
- All orders fulfilled on time
- Production target met (105%)
- Zero waste day!
- 🔥 3-day quality streak (score >9.0)
**Milestone Tracking:**
- Sustainability: 47% toward SDG 12.3 compliance
- Growth: €2,340 from monthly goal (78% complete)
- Quality: 28 consecutive days >9.0 score
**Visual Design:**
- Confetti animation on milestones
- Streak counters with fire emoji 🔥
- Progress bars with gradients
- Shareable achievement cards for social media
---
## 📋 PROPOSED WIDGET STRUCTURE
### **Hero Section** (Top - First 5 Seconds)
1. **Business Health Score** (0-100)
- Aggregates: Sales, Quality, On-Time, Profitability, Team Morale
- Color-coded: Red <60, Yellow 60-80, Green >80
- Trend: 7-day moving average
2. **Today's Story** (AI-Generated Summary)
- 2-sentence natural language summary
- Example: "Strong start to the week! Sales up 18% and all production on schedule. Watch ingredient costs - flour prices rising."
3. **Critical Actions** (Max 3)
- Sorted by: urgency × impact
- One-click actions inline
- Delegate button with team assignment
---
### **Context Sections** (Scrollable, Priority-Ordered)
#### 1. **Financial Snapshot** (Always Visible)
- **Today's P&L:**
- Revenue: €1,247 (sales completed)
- COGS: €530 (production materials)
- Labor: €280 (staff hours × rates)
- Waste: €18 (spoilage + mistakes)
- **Net Profit: €419** (34% margin) ✅
- **Weekly Trend:** Sparkline chart
- **Cash Flow:** Upcoming payments vs. receivables
#### 2. **Operations Flow** (Production → Inventory → Sales Cycle)
- Production status: 3 batches in progress, 2 completed, 1 pending
- Inventory health: 94% stocked, 2 items low, 0 stockouts
- Sales velocity: 87 units sold today, 13 pending orders
- **Bottleneck indicator:** Highlights slowest stage
#### 3. **Team & Capacity**
- Staff scheduled: 4/5 confirmed for today
- Current workload: Balanced (no one >110% capacity)
- Performance highlights: "María: 115% efficiency this week 🌟"
- Training needs: 2 staff need safety recertification
#### 4. **Quality & Sustainability** (Enhanced Existing Widget)
- Quality score: 9.2/10 (28-day streak)
- Sustainability: SDG 12.3 progress, CO₂ saved, waste reduction
- Certifications: Readiness indicators for audits
- **Grant opportunities:** 3 programs eligible (€12K potential)
#### 5. **Tomorrow's Briefing**
- Scheduled deliveries: Flour (50kg, 8 AM), Eggs (200, 10 AM)
- Production plan: 5 batches, 320 units total
- Staff: 5/5 confirmed, no gaps
- **Preparation checklist:**
- [ ] Review PO #1892 (arrives 8 AM)
- [ ] Assign quality check for batch #489
- [ ] Confirm catering order (pick-up 2 PM)
---
### **Smart Widgets** (Contextual, Time-Based)
These widgets appear/disappear based on context:
- **Morning Briefing** (6-10 AM only)
- **Midday Operations** (10 AM - 5 PM only)
- **Evening Checklist** (5-8 PM only)
- **Weekend Prep** (Friday PM only)
- **Weekly Review** (Monday AM only)
---
## 🚀 INCREMENTAL IMPLEMENTATION PHASES
### **PHASE 1: Quick Wins** (Week 1-2, ~10 hours)
**Goal:** Add context and impact to existing components without breaking changes
#### Deliverables:
1. **Enhanced StatsGrid with Financial Impact**
- File: `frontend/src/pages/app/DashboardPage.tsx` (modify lines 179-264)
- Add `impact` and `actionable` fields to stat objects
- Show financial context in subtitle
**Example Change:**
```typescript
{
title: t('dashboard:stats.critical_stock', 'Critical Stock'),
value: dashboardStats.criticalStock.toString(),
icon: AlertTriangle,
variant: dashboardStats.criticalStock > 0 ? 'error' : 'success',
impact: dashboardStats.criticalStock > 0
? `€${(dashboardStats.criticalStock * 80).toFixed(0)} in delayed orders`
: null, // NEW
actionable: dashboardStats.criticalStock > 0
? 'Review procurement queue'
: null, // NEW
subtitle: dashboardStats.criticalStock > 0
? t('dashboard:messages.action_required', 'Action required')
: t('dashboard:messages.stock_healthy', 'Stock levels healthy')
}
```
2. **Priority System for RealTimeAlerts**
- New hook: `frontend/src/hooks/business/useAlertPriority.ts`
- Modify: `frontend/src/components/domain/dashboard/RealTimeAlerts.tsx`
- Add priority calculation based on urgency + impact
- Group alerts by priority (P0, P1, P2, P3)
**Algorithm:**
```typescript
const calculatePriority = (alert: Notification): Priority => {
const urgency = calculateUrgency(alert.timestamp, alert.type);
const impact = estimateFinancialImpact(alert);
const score = (urgency * 0.6) + (impact * 0.4);
if (score > 80) return 'P0';
if (score > 60) return 'P1';
if (score > 40) return 'P2';
return 'P3';
};
```
3. **Daily Briefing Widget**
- New component: `frontend/src/components/domain/dashboard/DailyBriefing.tsx`
- Uses existing `useDashboardStats` hook
- Simple summary generation (no AI yet)
**Content Structure:**
```typescript
interface DailyBriefing {
headline: string; // "Strong Tuesday!"
summary: string[]; // ["Sales up 15%", "3 tasks need attention"]
sentiment: 'positive' | 'neutral' | 'concern';
topPriority: string; // Most urgent action
}
```
**Success Criteria:**
- [ ] All stats show financial impact where relevant
- [ ] Alerts sorted by priority, not just time
- [ ] Daily briefing loads in <500ms
- [ ] No breaking changes to existing functionality
**User Value:** Owners immediately see "why this matters" in money terms
---
### **PHASE 2: Financial Context Layer** (Week 3-4, ~12 hours)
**Goal:** Add daily profitability visibility and financial badges throughout
#### Deliverables:
1. **FinancialImpactBadge Component**
- New: `frontend/src/components/ui/Badge/FinancialImpactBadge.tsx`
- Reusable component showing € impact with color coding
- Variants: cost (red), savings (green), revenue (blue), neutral (gray)
**Props:**
```typescript
interface FinancialImpactBadgeProps {
amount: number;
type: 'cost' | 'savings' | 'revenue' | 'neutral';
label?: string;
showIcon?: boolean;
}
```
2. **Profit Snapshot Widget**
- New: `frontend/src/components/domain/dashboard/ProfitSnapshot.tsx`
- Shows TODAY's simple P&L
- Backend API needed: `GET /api/v1/tenants/{id}/dashboard/profit-snapshot`
**Data Model:**
```python
class ProfitSnapshot(BaseModel):
date: date
revenue: Decimal # from sales
cogs: Decimal # from production batches
labor_cost: Decimal # from staff hours
waste_cost: Decimal # from inventory
net_profit: Decimal
margin_percentage: float
trend_vs_yesterday: float
```
3. **Backend API Endpoint**
- New: `services/orders/app/api/dashboard.py` - `get_daily_profit_snapshot()`
- Aggregates data from: sales, production, inventory services
- Caches result for 15 minutes
**Implementation:**
```python
@router.get(
"/api/v1/tenants/{tenant_id}/dashboard/profit-snapshot",
response_model=ProfitSnapshot
)
async def get_daily_profit_snapshot(
tenant_id: UUID,
date: Optional[str] = None, # defaults to today
db: AsyncSession = Depends(get_db)
):
# Aggregate: sales.revenue - production.costs - inventory.waste
# Calculate labor from staff_assigned × hourly_rates
return ProfitSnapshot(...)
```
4. **Integrate Financial Badges**
- Add to: AlertCard, PendingPOApprovals, TodayProduction
- Show € impact prominently
- Link to profit snapshot when clicked
**Success Criteria:**
- [ ] Daily profit visible on dashboard
- [ ] All critical alerts show € impact
- [ ] Owner can explain profitability drivers
- [ ] Financial badges consistent across all widgets
**User Value:** Daily profitability visibility (currently hidden until month-end)
---
### **PHASE 3: Time-Based Smart Views** (Week 5-6, ~15 hours)
**Goal:** Dashboard adapts to time of day and workflow rhythms
#### Deliverables:
1. **Time Context Hook**
- New: `frontend/src/hooks/business/useTimeContext.ts`
- Detects time of day and suggests dashboard mode
**Implementation:**
```typescript
type DashboardMode = 'morning' | 'midday' | 'evening' | 'weekend';
const useTimeContext = () => {
const now = new Date();
const hour = now.getHours();
const day = now.getDay();
const mode: DashboardMode =
day === 0 || day === 6 ? 'weekend' :
hour < 10 ? 'morning' :
hour < 17 ? 'midday' : 'evening';
return {
mode,
isWorkingHours: hour >= 6 && hour <= 20,
shouldShowBriefing: hour >= 6 && hour <= 10
};
};
```
2. **Morning Briefing Component**
- New: `frontend/src/components/domain/dashboard/MorningBriefing.tsx`
- Shows 6-10 AM only
**Sections:**
```typescript
interface MorningBriefingData {
yesterday: {
sales: number;
target: number;
orders_completed: number;
issues: string[];
};
today: {
priorities: Array<{
time: string;
action: string;
urgency: Priority;
}>;
team_status: string;
};
quick_wins: Array<{
action: string;
impact: number; // euros
time_required: number; // minutes
}>;
}
```
3. **Evening Checklist Component**
- New: `frontend/src/components/domain/dashboard/EveningChecklist.tsx`
- Shows 5-8 PM only
**Sections:**
- Today's Achievements (wins to celebrate)
- Tomorrow's Prep (deliveries, production schedule)
- Open Items (unresolved alerts, pending approvals)
4. **Weekend View**
- Simplified dashboard for off-hours
- Shows only critical alerts (P0/P1)
- "All quiet" message when no urgent items
**Success Criteria:**
- [ ] Morning briefing shows yesterday recap + today priorities
- [ ] Evening checklist shows tomorrow prep
- [ ] Dashboard mode switches automatically
- [ ] Owner saves 15+ minutes in morning routine
**User Value:** Dashboard anticipates needs based on time of day
---
### **PHASE 4: Team & Capacity View** (Week 7-8, ~12 hours)
**Goal:** Visibility into team workload, performance, and capacity
#### Deliverables:
1. **TeamCapacity Widget**
- New: `frontend/src/components/domain/dashboard/TeamCapacity.tsx`
- Shows staff scheduled, workload, performance
**Data Model:**
```typescript
interface TeamCapacityData {
date: string;
staff_scheduled: Array<{
id: string;
name: string;
role: string;
shift_start: string;
shift_end: string;
workload_percentage: number; // 0-150%
batches_assigned: number;
efficiency_score: number; // vs. baseline
}>;
available_capacity: number; // hours
performance_highlights: Array<{
staff_name: string;
achievement: string;
}>;
}
```
2. **Backend API Endpoint**
- New: `services/production/app/api/dashboard.py` - `get_team_capacity()`
- Aggregates batches by `staff_assigned`
- Calculates workload based on planned_duration_minutes
**Implementation:**
```python
@router.get(
"/api/v1/tenants/{tenant_id}/dashboard/team-capacity",
response_model=TeamCapacityView
)
async def get_team_capacity(
tenant_id: UUID,
date: str,
db: AsyncSession = Depends(get_db)
):
# Query batches for date, group by staff_assigned
# Calculate: workload = sum(planned_duration) / (shift_hours * 60)
# Identify: efficiency = actual_duration / planned_duration
return TeamCapacityView(...)
```
3. **Performance Recognition**
- Automatic detection of:
- High efficiency (actual < planned time consistently)
- Quality scores >9.5
- Zero defects streaks
- Visual: Star icon, highlight in widget
- Action: One-click "Share with team" button
**Success Criteria:**
- [ ] Team workload visible at a glance
- [ ] Performance highlights shown for top performers
- [ ] Owner can identify overloaded staff
- [ ] Capacity planning data available
**User Value:** Resource planning and team recognition
---
### **PHASE 5: Narrative & Intelligence** (Week 9-10, ~16 hours)
**Goal:** AI-enhanced insights and celebration moments
#### Deliverables:
1. **Smart Insights Widget**
- New: `frontend/src/components/domain/dashboard/SmartInsights.tsx`
- Pattern-based suggestions
**Insight Types:**
- **Demand patterns:** "Sales spike Fridays (+30%) → Consider increasing Friday production"
- **Waste trends:** "Flour waste trending up 10% → Check batch sizes"
- **Supplier issues:** "3 late deliveries from SupplierX this month → Consider backup"
- **Opportunities:** "Sustainability metrics qualify for €5K grant → Review eligibility"
**Backend:**
```python
# services/alert_processor/analytics_rules.py (NEW)
class InsightRule:
def detect(self, data: TenantData) -> Optional[Insight]:
# Rule-based pattern detection
pass
rules = [
DemandPatternRule(),
WasteTrendRule(),
SupplierReliabilityRule(),
GrantEligibilityRule(),
]
```
2. **Win Streak Tracker**
- New: `frontend/src/components/domain/dashboard/WinStreak.tsx`
- Tracks consecutive days meeting goals
**Streaks Tracked:**
```typescript
interface WinStreak {
type: 'no_stockouts' | 'sales_target' | 'waste_reduction' | 'quality_score';
current_streak: number; // days
longest_streak: number;
last_broken: string; // date
next_milestone: number; // days
}
```
**Visual:**
- Fire emoji 🔥 for active streaks
- Confetti animation on new records
- Milestone badges (7, 14, 30, 90 days)
3. **AI Summary Enhancement** (Optional)
- Enhance DailyBriefing with OpenAI API
- Generate natural language summary
- Requires: OpenAI API key, backend service
**Example Prompt:**
```
Based on this bakery data:
- Sales: €1,247 (up 15% vs yesterday)
- Critical stock: 2 items
- Pending POs: 3 urgent
- Production: on schedule
Generate a 2-sentence briefing for the owner:
```
**Output:** "Strong sales day with €1,247 revenue, tracking 15% above yesterday. Focus on approving 3 urgent purchase orders to prevent stockouts."
4. **Celebration Moments**
- Auto-detect achievements:
- New sales record
- Longest quality streak
- Sustainability milestone (50% SDG target)
- Zero waste day
- Visual: Full-screen confetti animation
- Shareable: Generate achievement card with bakery branding
**Success Criteria:**
- [ ] At least 3 actionable insights per week
- [ ] Win streaks visible and tracked
- [ ] Owner reports "dashboard anticipates my questions"
- [ ] Achievements celebrated automatically
**User Value:** Proactive guidance and positive reinforcement
---
## 🗂️ FILE STRUCTURE
### New Files
```
frontend/src/
├── components/domain/dashboard/
│ ├── DailyBriefing.tsx # Phase 1 - Today's story summary
│ ├── MorningBriefing.tsx # Phase 3 - Yesterday + today priorities
│ ├── EveningChecklist.tsx # Phase 3 - Tomorrow prep + today wins
│ ├── ProfitSnapshot.tsx # Phase 2 - Daily P&L widget
│ ├── TeamCapacity.tsx # Phase 4 - Staff workload & performance
│ ├── SmartInsights.tsx # Phase 5 - AI-driven suggestions
│ ├── WinStreak.tsx # Phase 5 - Achievement tracking
│ └── FinancialImpactBadge.tsx # Phase 2 - Reusable € badge
├── hooks/business/
│ ├── useTimeContext.ts # Phase 3 - Time-based modes
│ ├── useAlertPriority.ts # Phase 1 - P0-P3 calculation
│ ├── useWinStreak.ts # Phase 5 - Streak tracking
│ └── useProfitSnapshot.ts # Phase 2 - Daily P&L data
└── utils/
├── alertPriority.ts # Phase 1 - Priority algorithms
├── financialCalculations.ts # Phase 2 - Impact calculations
└── insightRules.ts # Phase 5 - Pattern detection
backend/
├── services/orders/app/api/
│ └── dashboard.py # EXTEND - add profit-snapshot endpoint
├── services/production/app/api/
│ └── dashboard.py # EXTEND - add team-capacity endpoint
└── services/alert_processor/
└── analytics_rules.py # NEW - Phase 5 insights engine
```
### Modified Files
```
frontend/src/
├── pages/app/
│ └── DashboardPage.tsx # Orchestrate all new widgets
└── components/domain/dashboard/
├── RealTimeAlerts.tsx # Add priority grouping
└── (existing widgets) # Add financial badges
backend/
└── services/inventory/app/schemas/
└── dashboard.py # Add profit, team schemas
```
---
## 🔄 MIGRATION STRATEGY
### Gradual, Non-Breaking Rollout
#### Week 1-2: Shadow Mode
- Add new components alongside existing ones
- Feature flag: `ENABLE_ENHANCED_DASHBOARD` (environment variable)
- Default: `false` (opt-in testing only)
- No changes to production dashboard
**Implementation:**
```typescript
// DashboardPage.tsx
const useEnhancedDashboard =
import.meta.env.VITE_ENABLE_ENHANCED_DASHBOARD === 'true';
return (
<div>
{useEnhancedDashboard ? (
<>
<DailyBriefing />
<EnhancedStatsGrid />
</>
) : (
<StatsGrid stats={criticalStats} />
)}
{/* Rest of dashboard */}
</div>
);
```
#### Week 3-4: Opt-In Testing
- Add toggle in user settings: `Settings > Preferences > Beta Features`
- Invite bakery owner (you?) to test
- Collect feedback via in-app survey
- Track analytics: time on page, clicks, errors
**User Setting:**
```typescript
// services/auth/app/schemas/users.py
class UserPreferences(BaseModel):
use_enhanced_dashboard: bool = False # NEW
# ... existing preferences
```
#### Week 5-6: Hybrid Mode
- Show enhanced widgets during specific times:
- Morning briefing: 6-10 AM (auto-enabled for all)
- Evening checklist: 5-8 PM (auto-enabled for all)
- Keep existing widgets for midday
- A/B test with 50% of users
**Analytics to Track:**
- Morning briefing usage: % who interact
- Time saved: avg. time to complete daily review
- Errors prevented: P0 alerts resolved before escalation
- User satisfaction: weekly NPS survey
#### Week 7-8: Default On
- Enhanced dashboard becomes default for all users
- Old view available as "Classic Mode" toggle
- Deprecation notice: "Classic mode will be removed in 2 weeks"
#### Week 9-10: Full Migration
- Remove old components if new validated (>80% satisfaction)
- Cleanup feature flags
- Archive old code
- Update documentation
---
## ✅ SUCCESS METRICS
### Phase 1 Success Criteria
- [ ] Owner sees financial impact on all critical stats
- [ ] Alerts sorted by priority, not chronologically
- [ ] Daily briefing widget loads in <500ms
- [ ] 90% of users prefer enhanced stats over old
### Phase 2 Success Criteria
- [ ] Daily profit visible (Revenue - COGS - Waste)
- [ ] All P0/P1 alerts show € impact
- [ ] Owner can explain profitability to investor in <2 minutes
- [ ] Financial badges render in <100ms
### Phase 3 Success Criteria
- [ ] Morning briefing shows yesterday + today priorities
- [ ] Evening checklist shows tomorrow prep
- [ ] Owner saves 15+ minutes in morning routine (self-reported)
- [ ] 85% find time-based views helpful
### Phase 4 Success Criteria
- [ ] Team workload visible at a glance
- [ ] Performance highlights shown weekly
- [ ] Owner can balance assignments without manual calculation
- [ ] Team morale improves (quarterly survey)
### Phase 5 Success Criteria
- [ ] At least 3 actionable insights generated per week
- [ ] Win streaks visible and celebrated
- [ ] Owner reports "dashboard anticipates my questions" (interview)
- [ ] Reduction in reactive firefighting (tracked via alert resolution time)
### Overall Success (End of Phase 5)
- [ ] Dashboard is #1 most-visited page (analytics)
- [ ] Owner satisfaction >4.5/5 (quarterly survey)
- [ ] 30% reduction in time spent on morning review
- [ ] 20% improvement in problem prevention (P0 alerts avoided)
- [ ] 3 month retention: 95% of users still use enhanced dashboard
---
## 🚀 IMMEDIATE NEXT STEPS
### To Start Phase 1 (This Week):
1. **Create feature branch:**
```bash
git checkout -b feature/dashboard-enhancements-phase1
```
2. **Set up feature flag:**
```bash
# frontend/.env.local
VITE_ENABLE_ENHANCED_DASHBOARD=true
```
3. **Implement DailyBriefing component** (2-3 hours):
- Create `frontend/src/components/domain/dashboard/DailyBriefing.tsx`
- Reuse existing `useDashboardStats` hook
- Simple algorithm: compare today vs. yesterday
- Generate 2-3 bullet summary
4. **Add priority to alerts** (3-4 hours):
- Create `frontend/src/hooks/business/useAlertPriority.ts`
- Create `frontend/src/utils/alertPriority.ts` (calculation logic)
- Modify `RealTimeAlerts` to support priority grouping
- Add priority badge to `AlertCard`
5. **Add impact to StatsGrid** (1-2 hours):
- Extend `DashboardStats` type with optional `impact?: string`
- Modify stat card rendering to show impact subtitle
- Populate from existing data (no new API calls yet)
6. **Test and validate** (1-2 hours):
- Unit tests for priority calculation
- Integration tests for DailyBriefing
- Visual regression tests for modified components
- Accessibility audit (keyboard navigation, screen readers)
7. **Deploy to dev and gather feedback** (1 hour):
```bash
npm run build
kubectl apply -f infrastructure/kubernetes/overlays/dev/
```
**Total Phase 1 Effort:** ~10-12 hours (1.5-2 days)
---
## 📚 APPENDIX
### A. Technology Stack
**Frontend:**
- React 18 + TypeScript
- TanStack Query (React Query) for data fetching
- React Router for navigation
- i18next for translations
- Lucide React for icons
**Backend:**
- FastAPI (Python 3.11+)
- PostgreSQL for persistence
- Redis for caching
- SQLAlchemy ORM
**Infrastructure:**
- Kubernetes (local: k3d, prod: managed cluster)
- Nginx Ingress
- Prometheus + Grafana (monitoring)
### B. Existing Dashboard APIs
**Available Data Sources:**
- `GET /api/v1/tenants/{id}/dashboard/summary` - Inventory dashboard
- `GET /api/v1/tenants/{id}/alerts/analytics` - Alert analytics (7-30 days)
- `GET /api/v1/tenants/{id}/orders/dashboard-summary` - Orders metrics
- `GET /api/v1/tenants/{id}/sales/analytics` - Sales data
- `GET /api/v1/tenants/{id}/production/batches/active` - Production batches
- `GET /api/v1/tenants/{id}/sustainability/widget` - Sustainability metrics
**Aggregated via:**
- `useDashboardStats()` hook - Combines all above into single dashboard snapshot
### C. User Roles & Permissions
**Relevant Roles:**
- `owner` (tenant role) - Full access, primary user of dashboard
- `admin` (tenant role) - Full access
- `manager` (global role) - Can view but limited editing
- `member` (tenant role) - Limited view access
**Dashboard Visibility:**
- All roles can view dashboard
- Actions (approve PO, start batch) require `owner` or `admin` role
- Financial data visible to `owner`, `admin`, `manager` only
### D. Performance Considerations
**Current Dashboard Load Time:**
- Initial load: ~800ms (parallel API calls)
- Re-render: <100ms (React Query caching)
- SSE connection: Real-time alerts
**Target Performance (Enhanced):**
- Initial load: <1000ms (same or better)
- Daily briefing: <500ms (cached server-side)
- Financial snapshot: <300ms (15-min cache)
- Win streak: <50ms (localStorage)
**Optimization Strategies:**
- Server-side caching (Redis, 5-15 min TTL)
- Client-side caching (React Query, 30-60s stale time)
- Code splitting (lazy load evening/morning widgets)
- Incremental rendering (Suspense boundaries)
### E. Accessibility Requirements
**WCAG 2.1 AA Compliance:**
- [ ] Keyboard navigation (Tab, Enter, Esc)
- [ ] Screen reader support (ARIA labels)
- [ ] Color contrast >4.5:1
- [ ] Focus indicators visible
- [ ] No content flash <3 times/sec
- [ ] Text scalable to 200%
**Dashboard-Specific:**
- Alert priority communicated via text, not color only
- Financial impact readable by screen readers
- Time-based views announced on change
- All actions have keyboard shortcuts
### F. Internationalization
**Supported Languages:**
- Spanish (es)
- Basque (eu)
- English (en)
**Translation Keys to Add:**
```json
// frontend/src/locales/en/dashboard.json
{
"daily_briefing": {
"title": "Today's Briefing",
"yesterday_recap": "Yesterday's Performance",
"today_priorities": "Today's Priorities",
"quick_wins": "Quick Wins"
},
"financial": {
"profit_snapshot": "Daily Profit",
"revenue": "Revenue",
"costs": "Costs",
"net_profit": "Net Profit",
"margin": "Margin"
},
"priorities": {
"p0": "URGENT",
"p1": "Today",
"p2": "This Week",
"p3": "Backlog"
}
// ... etc
}
```
### G. References & Inspiration
**JTBD Resources:**
- Bob Moesta - "Demand-Side Sales 101"
- Clayton Christensen - "Competing Against Luck"
- Alan Klement - "When Coffee and Kale Compete"
**Dashboard Design Patterns:**
- Intercom Product Updates (narrative-driven)
- Shopify Home (financial context always)
- Linear Dashboard (time-based views)
- Notion Workspace (celebration moments)
**Bakery Domain Expertise:**
- UN SDG 12.3 Food Waste Guidelines
- EU Sustainability Reporting Standards
- Local bakery owner interviews (recommended)
---
## 📝 CONCLUSION
This JTBD analysis transforms the dashboard from a **data display tool** into a **decision support companion** that:
1. **Aligns with bakery workflows** (morning/midday/evening rhythms)
2. **Provides financial context** (every metric tied to profitability)
3. **Guides action** (prioritized by urgency × impact)
4. **Celebrates progress** (wins, streaks, milestones)
5. **Anticipates needs** (time-based smart views)
The incremental implementation approach ensures:
- No breaking changes to existing system
- Value delivered every 2 weeks
- User feedback incorporated continuously
- Low risk, high reward
**Recommendation:** Start with Phase 1 this week to validate core assumptions before committing to full redesign.
---
**Last Updated:** 2025-10-24
**Next Review:** After Phase 1 completion (Week 2)
**Owner:** Development Team + Bakery Owner (Product Validation)