Clean docs

This commit is contained in:
Urtzi Alfaro
2025-11-07 14:53:36 +01:00
parent 980bbd4b61
commit 41d3998f53
8 changed files with 0 additions and 4101 deletions

View File

@@ -1,335 +0,0 @@
# Onboarding Flow Reorganization - Aligned with JTBD Analysis
## Problem Statement
The current AI-assisted path has some confusion:
1. "Review Suggestions" step helps complete the product list (from AI analysis)
2. "Inventory Setup" step should capture **initial stock** (crucial for system)
3. These two steps need better alignment and clear purpose
4. Must align with JTBD Analysis: users need to get up and running quickly with accurate inventory
## JTBD Analysis Key Findings (Recap)
From the initial JTBD analysis, bakery owners need to:
- **Job 1**: Get their inventory into the system quickly and accurately
- **Job 2**: Understand what products/ingredients they have and in what quantities
- **Job 3**: Start managing daily operations (production, sales) as soon as possible
**Critical Insight**: Initial stock levels are CRUCIAL - without them, the system cannot:
- Calculate if there's enough stock for production
- Alert about low stock
- Track consumption
- Provide accurate cost calculations
## Current Flow (Problematic)
### AI-Assisted Path (Current):
1. **Upload Sales Data** → User uploads historical sales
2. **AI Analysis** → System analyzes and suggests products
3. **Review Suggestions** → User reviews/edits suggested products ❌ *Missing: initial stock*
4. **Suppliers Setup** → Add suppliers
5. **Inventory Setup** → Add ingredients ❌ *Confusing: what about the products from step 3?*
6. **Recipes Setup** → Add recipes
7. ...rest of flow
**Problems:**
- Step 3 creates products but doesn't capture stock levels
- Step 5 adds ingredients but unclear relationship to step 3 products
- User has to enter stock levels twice (or not at all)
- Confusing UX: "Didn't I already add my inventory in step 3?"
## Proposed Reorganized Flow
### AI-Assisted Path (Reorganized):
```
Phase 1: DISCOVERY
├─ 1. Bakery Type Selection (Production/Retail/Mixed)
└─ 2. Data Source Choice (AI-assisted vs Manual)
Phase 2a: AI-POWERED SMART SETUP
├─ 3. Upload & Analyze Sales Data
│ ├─ Upload historical sales (CSV/Excel/JSON)
│ ├─ AI automatically classifies products
│ ├─ AI suggests categories and groupings
│ └─ AI estimates typical costs from sales data
├─ 4. Review & Complete Product List ⭐ ENHANCED
│ ├─ **Sub-step 4a: Review AI-Suggested Products**
│ │ ├─ See all products AI found in sales data
│ │ ├─ AI confidence scores for each classification
│ │ ├─ Edit/merge/delete suggested products
│ │ ├─ Add product images (optional)
│ │ └─ Quick actions: "Accept all", "Reject low confidence"
│ │
│ ├─ **Sub-step 4b: Categorize as Ingredients vs Finished Products** ⭐ KEY STEP
│ │ ├─ AI suggests initial categorization
│ │ ├─ User confirms which are INGREDIENTS (flour, sugar, etc.)
│ │ ├─ User confirms which are FINISHED PRODUCTS (bread, pastries)
│ │ ├─ Drag-and-drop interface for easy sorting
│ │ └─ WHY: System needs to know what can be used in recipes
│ │
│ └─ **Sub-step 4c: Set Initial Stock Levels** ⭐ CRITICAL
│ ├─ For each ingredient: "What's your current stock?"
│ ├─ For each finished product: "How many do you have now?"
│ ├─ Smart defaults based on typical quantities
│ ├─ Unit conversion helper (kg → g, dozens → units)
│ ├─ Batch entry option: "Set all to 0" or "Skip for now"
│ └─ WHY: Without initial stock, system can't function
├─ 5. Suppliers Setup (Quick)
│ ├─ AI suggests suppliers from sales data (if available)
│ ├─ User adds main suppliers (name, contact)
│ ├─ Can be minimal - just names to start
│ └─ Link suppliers to ingredients (optional at this stage)
└─ 6. [SKIP INVENTORY SETUP - Already done in step 4!]
Phase 2b: PRODUCTION SETUP (Conditional)
├─ 7a. Recipes Setup (if Production/Mixed bakery)
│ ├─ Can use ingredients from step 4
│ ├─ Template recipes for common items
│ └─ AI may suggest recipes based on product names
└─ 7b. Production Processes (if Retail/Mixed bakery)
├─ Simple baking/finishing processes
└─ Template processes for common items
Phase 3: OPTIONAL FEATURES
├─ 8. Quality Standards (optional)
└─ 9. Team Members (optional)
Phase 4: FINALIZATION
├─ 10. ML Training (with real-time progress)
├─ 11. Review & Summary (show everything configured)
└─ 12. Completion & Next Steps
```
## Manual Path (Reorganized for Consistency)
```
Phase 1: DISCOVERY
├─ 1. Bakery Type Selection
└─ 2. Data Source Choice → "Manual"
Phase 2: MANUAL SETUP
├─ 3. Suppliers Setup
│ └─ Add main suppliers manually
├─ 4. Inventory Setup ⭐ COMBINED STEP
│ ├─ **Sub-step 4a: Add Ingredients**
│ │ ├─ Name, category, unit, supplier
│ │ ├─ Standard cost per unit
│ │ └─ **Initial stock quantity** ⭐
│ │
│ ├─ **Sub-step 4b: Add Finished Products**
│ │ ├─ Name, category, selling price
│ │ └─ **Initial stock quantity** ⭐
│ │
│ └─ Template library for quick start
│ ├─ Common ingredients (flour, sugar, etc.)
│ └─ Common products (bread, croissants, etc.)
├─ 5. Recipes/Processes Setup
│ └─ Based on bakery type
└─ 6-9. Optional features + Finalization
```
## Key Changes & Rationale
### 1. Combined "Review & Complete Product List" (Step 4 in AI path)
**Before:** Separate steps that were confusing
- Step 3: Review products (no stock)
- Step 5: Add ingredients (with stock)
**After:** One comprehensive step with 3 sub-steps
- 4a: Review AI suggestions
- 4b: Categorize (ingredients vs products)
- 4c: Set initial stock ⭐
**Benefits:**
- ✅ Single workflow for product setup
- ✅ Clear progression: identify → categorize → stock
- ✅ No confusion about "where do I add stock?"
- ✅ Captures initial stock for EVERYTHING
- ✅ Aligns with JTBD: get inventory into system quickly
### 2. AI Path Skips Redundant "Inventory Setup" Step
**Rationale:**
- All inventory already added in step 4
- No need for separate "add ingredients" step
- Reduces total steps (better UX)
- Prevents duplicate data entry
**Exception:**
- Users can still add NEW items later via dashboard
- Step 4 is comprehensive but not limiting
### 3. Manual Path Also Captures Initial Stock
**Why:**
- Consistency between AI and Manual paths
- Both paths MUST get initial stock
- Makes inventory setup atomic and complete
### 4. Sub-step 4b: Categorization Step
**Purpose:**
- System needs to know: ingredient vs finished product
- Ingredients → can be used in recipes
- Finished products → can be sold, tracked for inventory
- AI suggests, user confirms (or manual entry)
**UI Concept:**
```
┌─────────────────────────────────────────────────┐
│ Categorize Your Products │
├─────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Ingredients │ │ Finished │ │
│ │ (For Recipes)│ │ Products │ │
│ │ │ │ (To Sell) │ │
│ ├──────────────┤ ├──────────────┤ │
│ │ Flour │ ←─── │ Baguette │ │
│ │ Sugar │ │ │ Croissant │ │
│ │ Butter │ │ │ Cake │ │
│ │ │ │ │ │ │
│ └──────────────┘ │ └──────────────┘ │
│ │ │
│ Drag & drop to categorize │
│ │
│ [< Previous] [Skip for now] [Next >] │
└─────────────────────────────────────────────────┘
```
### 5. Sub-step 4c: Initial Stock Entry
**UI Concept:**
```
┌─────────────────────────────────────────────────┐
│ Set Initial Stock Levels │
├─────────────────────────────────────────────────┤
│ 💡 Enter current quantities for accurate │
│ tracking │
│ │
│ ┌─────────────────────────────────────────────┐│
│ │ Ingredients ││
│ ├─────────────────────────────────────────────┤│
│ │ Flour (kg) [____50____] kg ││
│ │ Sugar (kg) [____25____] kg ││
│ │ Butter (kg) [____10____] kg ││
│ │ Eggs (units) [____200___] units ││
│ └─────────────────────────────────────────────┘│
│ │
│ ┌─────────────────────────────────────────────┐│
│ │ Finished Products ││
│ ├─────────────────────────────────────────────┤│
│ │ Baguette (units) [____30____] units ││
│ │ Croissant (units) [____45____] units ││
│ │ Cake (units) [____12____] units ││
│ └─────────────────────────────────────────────┘│
│ │
│ Batch Actions: │
│ [ Set all to 0 ] [ Leave empty for now ] │
│ │
│ [< Previous] [Complete Setup >] │
└─────────────────────────────────────────────────┘
```
**Features:**
- Quick entry with keyboard navigation
- Smart defaults (AI can suggest typical quantities)
- Option to skip and add later (but encouraged to do now)
- Validation: warn if leaving many items at 0
- Unit conversion helper
- Batch operations for efficiency
## Updated Step Dependencies
```mermaid
graph TD
A[Bakery Type] --> B[Data Source]
B --> C{AI or Manual?}
C -->|AI| D[Upload Sales Data]
D --> E[AI Analysis]
E --> F[Review & Complete Products]
F --> F1[Review AI Suggestions]
F1 --> F2[Categorize Items]
F2 --> F3[Set Initial Stock]
F3 --> G[Suppliers Quick Setup]
G --> H[Recipes/Processes]
C -->|Manual| I[Suppliers Setup]
I --> J[Inventory Setup Combined]
J --> J1[Add Ingredients + Stock]
J1 --> J2[Add Products + Stock]
J2 --> H
H --> K[Optional Features]
K --> L[ML Training]
L --> M[Review Summary]
M --> N[Completion]
```
## Implementation Checklist
### Phase 6.5: Flow Reorganization (1 week)
**Day 1-2: Enhanced Review Step**
- [ ] Split ReviewSuggestionsStep into 3 sub-steps
- [ ] Create ProductCategorizationUI component
- [ ] Create InitialStockEntryUI component
- [ ] Add drag-and-drop for categorization
- [ ] Add validation for stock entry
**Day 3-4: Backend Updates**
- [ ] Update product model to include `type` field (ingredient/finished_product)
- [ ] Add `initial_stock` capture in inventory endpoints
- [ ] Update AI analysis to suggest categorization
- [ ] Create endpoint for batch stock updates
**Day 5: Integration & Testing**
- [ ] Update UnifiedOnboardingWizard step flow
- [ ] Skip "Inventory Setup" in AI path
- [ ] Ensure Manual path includes stock entry
- [ ] End-to-end testing of both paths
## Success Metrics
### User Experience
- ✅ 90%+ of users complete initial stock entry
- ✅ Reduced confusion (fewer support tickets about "where to add stock")
- ✅ Faster onboarding (fewer steps in AI path)
- ✅ Higher data quality (complete inventory from start)
### System Functionality
- ✅ All inventory items have initial stock
- ✅ Production planning works from day 1
- ✅ Low stock alerts functional immediately
- ✅ Accurate cost calculations from start
## Migration Path
For existing implementations:
1. Add `type` field to existing inventory items (default: 'ingredient')
2. Backfill initial_stock from current stock where available
3. Prompt existing users to set stock levels on first login
4. Grandfather existing incomplete setups (warn but don't block)
## Conclusion
This reorganization:
- ✅ Eliminates confusion between product review and inventory setup
- ✅ Ensures initial stock is captured for ALL items
- ✅ Aligns with JTBD: users can start operating immediately
- ✅ Reduces total steps in AI path (better UX)
- ✅ Maintains consistency between AI and Manual paths
- ✅ Makes categorization (ingredient vs product) explicit and clear
- ✅ Provides better foundation for production planning and inventory management
**Next Step:** Implement Phase 6.5 to realize this reorganization.

View File

@@ -1,929 +0,0 @@
# Unified Onboarding Wizard - Master Plan
## Executive Summary
This document outlines the strategy to merge the **existing AI-powered onboarding** (sales data upload + ML training) with the **new comprehensive setup wizard** (suppliers, inventory, recipes, quality, team) into a single, intelligent, personalized onboarding experience.
---
## 1. Current State Analysis
### 1.1 Existing Onboarding (Smart Inventory Path)
**Flow:**
```
Registration → Tenant Setup → Sales Upload → AI Classification →
Inventory Creation → ML Training → Completion
```
**Strengths:**
✅ AI-powered product recommendations (85%+ confidence)
✅ Real-time ML training with WebSocket progress
✅ Multi-format data import (CSV, JSON, Excel)
✅ Smart inventory creation from sales data
✅ Backend progress persistence
**Weaknesses:**
❌ No supplier management (auto-completed)
❌ No recipe creation
❌ No quality standards
❌ No team management
❌ No bakery type personalization
❌ Limited to finished products only
### 1.2 New Setup Wizard (Manual Path)
**Flow:**
```
Welcome → Suppliers → Inventory → Recipes → Quality → Team →
Review → Completion
```
**Strengths:**
✅ Comprehensive data entry (all entities)
✅ Template system for quick setup
✅ Smart defaults and auto-suggestions
✅ Detailed review before completion
✅ Engaging completion experience
**Weaknesses:**
❌ No AI assistance
❌ No sales data integration
❌ No ML training
❌ No bakery type personalization
❌ More time-consuming for users with existing data
---
## 2. Gap Analysis
### 2.1 Missing Features
| Feature | Existing | New Wizard | Priority |
|---------|----------|------------|----------|
| Bakery Type Selection | ❌ | ❌ | 🔴 Critical |
| AI Product Recommendations | ✅ | ❌ | 🔴 Critical |
| Sales Data Upload | ✅ | ❌ | 🔴 Critical |
| Supplier Management | ❌ (auto) | ✅ | 🟡 High |
| Recipe Creation | ❌ | ✅ | 🟡 High |
| Quality Standards | ❌ | ✅ | 🟢 Medium |
| Team Management | ❌ | ✅ | 🟢 Medium |
| ML Training | ✅ | ❌ | 🔴 Critical |
| Spanish i18n | ⚠️ Partial | ❌ | 🔴 Critical |
| Analytics Tracking | ❌ | ❌ | 🟡 High |
| Guided Tours | ❌ | ❌ | 🟢 Medium |
### 2.2 Bakery Type Impact
Different bakery types need different onboarding paths:
| Bakery Type | Needs Recipes | Needs Suppliers | Primary Inventory | Production |
|-------------|---------------|-----------------|-------------------|------------|
| **Production Bakery** | ✅ Yes | ✅ Yes | Raw ingredients | Full production |
| **Retail/Finishing** | ❌ No* | ✅ Yes | Finished/par-baked | Simple baking |
| **Mixed** | ✅ Yes | ✅ Yes | Both | Both |
*Retail bakeries need **production processes** (simpler than recipes) for par-baked items
---
## 3. Unified Wizard Architecture
### 3.1 High-Level Flow
```
┌─────────────────────────────────────────────────────────────────┐
│ PHASE 1: DISCOVERY │
│ 1. Welcome & Bakery Type Selection │
│ 2. Data Source Choice (AI-assisted vs Manual) │
└─────────────────────────────────────────────────────────────────┘
┌─────────────┴─────────────┐
↓ ↓
┌──────────────────────────┐ ┌──────────────────────────┐
│ AI-ASSISTED PATH │ │ MANUAL PATH │
│ │ │ │
│ 3. Upload Sales Data │ │ 3. (Skip to Core) │
│ 4. AI Analysis │ │ │
│ 5. Review Suggestions │ │ │
└──────────────────────────┘ └──────────────────────────┘
↓ ↓
└─────────────┬─────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ PHASE 2: CORE SETUP │
│ 6. Suppliers Setup │
│ 7. Inventory Setup (enhanced with AI if available) │
│ 8. Recipes Setup (if Production/Mixed) OR │
│ Production Processes (if Retail/Finishing) │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ PHASE 3: ADVANCED FEATURES │
│ 9. Quality Standards (optional) │
│ 10. Team Members (optional) │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ PHASE 4: ML & FINALIZATION │
│ 11. ML Training (real-time progress, skippable after 2min) │
│ 12. Review & Summary │
│ 13. Completion & Next Steps │
└─────────────────────────────────────────────────────────────────┘
```
### 3.2 Step Definitions
#### **Phase 1: Discovery (NEW)**
**Step 1: Welcome & Bakery Type Selection**
- Welcome message explaining the wizard
- **Bakery type selector** (new requirement):
- 🥖 **Production Bakery** - "Producimos desde cero"
- 🛒 **Retail/Finishing Bakery** - "Recibimos productos terminados/semi-elaborados"
- 🏭 **Mixed Bakery** - "Producción + Venta de productos terminados"
- Explain what each type means
- Store in tenant metadata
- Determines conditional steps
**Step 2: Data Source Choice**
- **Option A: Upload sales data** (AI-assisted)
- "Tengo datos históricos de ventas"
- Faster setup (~5 min)
- AI recommendations
- **Option B: Start from scratch** (Manual)
- "Empezar manualmente"
- More control
- Use templates
#### **Phase 2a: AI-Assisted Path (IF user uploads data)**
**Step 3: Upload Sales Data** *(from existing onboarding)*
- Upload CSV/JSON/Excel
- Show preview
- Validate format
- Component: `UploadSalesDataStep` (reuse existing)
**Step 4: AI Analysis & Recommendations** *(from existing onboarding)*
- Show loading animation
- AI classifies products
- Display suggestions with confidence scores
- Component: Part of `UploadSalesDataStep` (reuse existing)
**Step 5: Review & Confirm Products** *(from existing onboarding)*
- User reviews AI suggestions
- Can edit names, categories, quantities
- Select which items to create
- Component: Part of `UploadSalesDataStep` (reuse existing)
#### **Phase 2b: Core Setup (Common for all paths)**
**Step 6: Suppliers Setup** *(enhanced from new wizard)*
- Add supplier information
- **Enhancement**: Pre-populate supplier suggestions based on inventory
- Component: `SuppliersSetupStep` (from new wizard)
- Minimum: 1 supplier
**Step 7: Inventory Setup** *(enhanced from new wizard)*
- **If AI path**: Show AI-created items + ability to add more
- **If manual path**: Show templates + manual entry
- **Conditional based on bakery type**:
- Production: Ingredients (flour, yeast, etc.)
- Retail: Finished products (croissants, bread, etc.)
- Mixed: Both
- Component: `InventorySetupStep` (from new wizard, enhanced)
- Minimum: 3 items
**Step 8a: Recipes Setup** *(IF Production or Mixed)*
- Create production recipes
- Recipe templates (baguette, croissant, etc.)
- Link ingredients to finished products
- Component: `RecipesSetupStep` (from new wizard)
- Minimum: 1 recipe
**Step 8b: Production Processes** *(IF Retail/Finishing)*
- **NEW COMPONENT NEEDED**
- Simple transformation processes for par-baked products
- Example: "Hornear a 180°C durante 15 minutos"
- No complex recipes, just baking instructions
- Component: `ProductionProcessesStep` (new)
- Minimum: 1 process
#### **Phase 3: Advanced Features (Optional)**
**Step 9: Quality Standards** *(from new wizard, optional)*
- Define quality check templates
- Component: `QualitySetupStep` (from new wizard)
- Skippable
**Step 10: Team Members** *(from new wizard, optional)*
- Add team member emails and roles
- Component: `TeamSetupStep` (from new wizard)
- Skippable
#### **Phase 4: ML & Finalization**
**Step 11: ML Training** *(from existing onboarding)*
- Auto-start training
- Real-time progress via WebSocket
- Skip option after 2 minutes
- Component: `MLTrainingStep` (reuse existing)
- Required for AI features
**Step 12: Review & Summary** *(from new wizard)*
- Show all configured data
- Stats and metrics
- Component: `ReviewSetupStep` (from new wizard)
- Always shown
**Step 13: Completion** *(from new wizard, enhanced)*
- Celebration
- Next steps
- Guided tour option
- Component: `CompletionStep` (from new wizard)
- Final step
---
## 4. Conditional Step Logic
### 4.1 Step Visibility Matrix
| Step | Production | Retail | Mixed | AI Path | Manual |
|------|-----------|---------|-------|---------|--------|
| 1. Welcome & Type | ✅ | ✅ | ✅ | ✅ | ✅ |
| 2. Data Choice | ✅ | ✅ | ✅ | ✅ | ✅ |
| 3. Upload Data | ✅ | ✅ | ✅ | ✅ | ❌ |
| 4. AI Analysis | ✅ | ✅ | ✅ | ✅ | ❌ |
| 5. Review Products | ✅ | ✅ | ✅ | ✅ | ❌ |
| 6. Suppliers | ✅ | ✅ | ✅ | ✅ | ✅ |
| 7. Inventory | ✅ | ✅ | ✅ | ✅ | ✅ |
| 8a. Recipes | ✅ | ❌ | ✅ | ✅ | ✅ |
| 8b. Processes | ❌ | ✅ | ⚠️* | ✅ | ✅ |
| 9. Quality | ✅ | ✅ | ✅ | ✅ | ✅ |
| 10. Team | ✅ | ✅ | ✅ | ✅ | ✅ |
| 11. ML Training | ✅ | ✅ | ✅ | ✅ | ✅** |
| 12. Review | ✅ | ✅ | ✅ | ✅ | ✅ |
| 13. Completion | ✅ | ✅ | ✅ | ✅ | ✅ |
*Mixed bakeries can optionally add production processes
**Manual path users can skip ML training if no sales data uploaded
### 4.2 Implementation Strategy
```typescript
interface WizardContext {
bakeryType: 'production' | 'retail' | 'mixed';
dataSource: 'ai' | 'manual';
hasSalesData: boolean;
aiSuggestions?: ProductSuggestion[];
}
const getVisibleSteps = (context: WizardContext): StepConfig[] => {
const steps = [
welcomeStep,
dataChoiceStep,
];
if (context.dataSource === 'ai') {
steps.push(uploadStep, aiAnalysisStep, reviewProductsStep);
}
steps.push(suppliersStep, inventoryStep);
if (context.bakeryType === 'production' || context.bakeryType === 'mixed') {
steps.push(recipesStep);
}
if (context.bakeryType === 'retail' || context.bakeryType === 'mixed') {
steps.push(productionProcessesStep);
}
steps.push(qualityStep, teamStep);
if (context.hasSalesData) {
steps.push(mlTrainingStep);
}
steps.push(reviewStep, completionStep);
return steps;
};
```
---
## 5. Implementation Phases
### Phase 6: Foundation & Integration (Week 1-2)
**Tasks:**
1. ✅ Analyze existing onboarding (COMPLETE)
2. Create `BakeryTypeSelectionStep` component
3. Create `DataSourceChoiceStep` component
4. Create `ProductionProcessesStep` component (for retail bakeries)
5. Create wizard context system for conditional logic
6. Merge step dependencies in backend
7. Update progress tracking to support conditional steps
**Deliverables:**
- New step components (3)
- Wizard context provider
- Conditional step visibility logic
- Updated backend dependencies
### Phase 7: Spanish Translations (Week 2)
**Tasks:**
1. Create comprehensive Spanish translations for ALL steps
2. Translate existing onboarding strings
3. Translate new setup wizard strings
4. Add translation keys for new components
5. Test language switching
6. Update default language to Spanish
**Files to Update:**
- `/frontend/public/locales/es/setup_wizard.json`
- `/frontend/public/locales/es/onboarding.json`
- `/frontend/public/locales/es/common.json`
- `/frontend/public/locales/es/inventory.json`
- `/frontend/public/locales/es/recipes.json`
- `/frontend/public/locales/es/quality.json`
**Deliverables:**
- Complete Spanish translation files (1000+ strings)
- Language switcher in wizard
- RTL support (future-proofing)
### Phase 8: Analytics & Tracking (Week 3)
**Tasks:**
1. Create analytics tracking service
2. Track wizard start/completion events
3. Track step-by-step progress
4. Track drop-off points
5. Track time spent per step
6. Create analytics dashboard
7. Implement A/B testing framework
**Events to Track:**
```typescript
// Wizard level
- wizard_started { bakery_type, data_source }
- wizard_completed { duration, steps_completed }
- wizard_abandoned { last_step, duration }
// Step level
- step_started { step_name, timestamp }
- step_completed { step_name, duration }
- step_skipped { step_name }
// Interaction level
- template_used { template_name, step }
- ai_suggestion_accepted { product_name, confidence }
- ai_suggestion_rejected { product_name, confidence }
```
**Backend:**
- New table: `wizard_analytics`
- New API endpoints for tracking
- Dashboard queries for metrics
**Deliverables:**
- Analytics tracking service
- Dashboard with metrics
- Reports: completion rate, avg time, drop-off analysis
### Phase 9: Guided Tours (Week 3-4)
**Tasks:**
1. Create tour system (similar to demo tour)
2. Define tour steps for each major feature
3. Create tour triggers (post-onboarding)
4. Add "skip tour" option
5. Store tour completion state
6. Create tour manager component
**Tours to Create:**
1. **Dashboard Tour** - Overview of main dashboard
2. **Production Tour** - How to create production batches
3. **Inventory Tour** - Managing stock levels
4. **Recipes Tour** - Creating and editing recipes
5. **Analytics Tour** - Understanding reports
**Technology:**
- Reuse existing demo tour infrastructure
- Use `react-joyride` or similar library
- Store state in localStorage + backend
**Deliverables:**
- Tour system framework
- 5 feature tours
- Tour completion tracking
### Phase 10: Enhanced Features (Week 4-5)
**Tasks:**
**10.1 Smart Inventory Enhancement**
- Show AI-suggested items prominently if AI path
- Allow editing AI suggestions before creation
- Show confidence scores
- Pre-fill costs based on sales data
**10.2 Supplier Suggestions**
- Based on inventory categories, suggest suppliers
- "For your flour, you might need a grain supplier"
- Pre-fill common suppliers in region
**10.3 Recipe Templates Enhancement**
- Add more recipe templates (20+ recipes)
- Categorize by bakery type
- Show only relevant templates
**10.4 Production Processes**
- Create library of common processes
- "Bake croissants", "Proof bread", "Glaze pastries"
- Simple time/temp instructions
**Deliverables:**
- Enhanced inventory step with AI integration
- Supplier suggestion system
- Expanded recipe library
- Production processes library
### Phase 11: Testing & Polish (Week 5-6)
**Tasks:**
1. End-to-end testing all paths
2. Test conditional logic
3. Test AI integration
4. Test ML training flow
5. Performance optimization
6. Accessibility audit
7. Mobile responsiveness testing
8. Spanish translation review
9. User acceptance testing
10. Bug fixes and polish
**Test Scenarios:**
- Production bakery + AI path
- Production bakery + Manual path
- Retail bakery + AI path
- Retail bakery + Manual path
- Mixed bakery + AI path
- Mixed bakery + Manual path
**Deliverables:**
- Test results report
- Bug fixes
- Performance improvements
- Final polish
---
## 6. Technical Specifications
### 6.1 New Components
**BakeryTypeSelectionStep.tsx**
```typescript
interface BakeryType {
id: 'production' | 'retail' | 'mixed';
name: string;
description: string;
icon: ReactNode;
features: string[];
examples: string[];
}
const bakeryTypes: BakeryType[] = [
{
id: 'production',
name: 'Panadería de Producción',
description: 'Producimos desde cero usando ingredientes',
icon: <BreadIcon />,
features: [
'Gestión de recetas',
'Control de ingredientes',
'Producción completa'
],
examples: ['Pan artesanal', 'Bollería', 'Repostería']
},
{
id: 'retail',
name: 'Panadería de Reventa/Acabado',
description: 'Recibimos productos terminados o semi-elaborados',
icon: <StorefrontIcon />,
features: [
'Gestión de productos terminados',
'Procesos de horneado simple',
'Gestión de proveedores'
],
examples: ['Hornear precocidos', 'Venta de productos terminados']
},
{
id: 'mixed',
name: 'Panadería Mixta',
description: 'Combinamos producción propia y reventa',
icon: <HybridIcon />,
features: [
'Todas las funcionalidades',
'Máxima flexibilidad',
'Gestión completa'
],
examples: ['Producción + Reventa']
}
];
```
**DataSourceChoiceStep.tsx**
```typescript
interface DataSource {
id: 'ai' | 'manual';
name: string;
description: string;
duration: string;
icon: ReactNode;
benefits: string[];
}
const dataSources: DataSource[] = [
{
id: 'ai',
name: 'Subir datos de ventas (Recomendado)',
description: 'Sube tus datos históricos y deja que la IA configure tu inventario',
duration: '~5 minutos',
icon: <AIIcon />,
benefits: [
'Configuración automática',
'Recomendaciones inteligentes',
'Análisis de ventas',
'Más rápido'
]
},
{
id: 'manual',
name: 'Configuración manual',
description: 'Configura todo desde cero usando plantillas',
duration: '~15 minutos',
icon: <ManualIcon />,
benefits: [
'Control total',
'Sin datos históricos necesarios',
'Plantillas incluidas'
]
}
];
```
**ProductionProcessesStep.tsx**
```typescript
interface ProductionProcess {
id: string;
product_id: string;
process_name: string;
description: string;
steps: ProcessStep[];
duration_minutes: number;
temperature_celsius?: number;
}
interface ProcessStep {
order: number;
instruction: string;
duration_minutes: number;
temperature_celsius?: number;
}
// Example processes
const processTemplates = [
{
name: 'Hornear Croissants Precocidos',
steps: [
{ order: 1, instruction: 'Precalentar horno a 180°C', duration_minutes: 10 },
{ order: 2, instruction: 'Hornear croissants', duration_minutes: 15, temperature_celsius: 180 },
{ order: 3, instruction: 'Enfriar', duration_minutes: 5 }
],
duration_minutes: 30,
temperature_celsius: 180
}
];
```
### 6.2 Wizard Context System
```typescript
interface WizardContext {
// Discovery
bakeryType?: 'production' | 'retail' | 'mixed';
dataSource?: 'ai' | 'manual';
// AI Path
salesDataUploaded: boolean;
aiSuggestions: ProductSuggestion[];
selectedSuggestions: string[];
// Setup Data
suppliers: Supplier[];
inventory: InventoryItem[];
recipes: Recipe[];
processes: ProductionProcess[];
qualityTemplates: QualityTemplate[];
teamMembers: TeamMember[];
// ML
mlTrainingJobId?: string;
mlTrainingStatus?: 'pending' | 'in_progress' | 'completed' | 'failed';
mlTrainingProgress?: number;
}
const WizardContextProvider: React.FC = ({ children }) => {
const [context, setContext] = useState<WizardContext>({
salesDataUploaded: false,
aiSuggestions: [],
selectedSuggestions: [],
suppliers: [],
inventory: [],
recipes: [],
processes: [],
qualityTemplates: [],
teamMembers: []
});
return (
<WizardContext.Provider value={{ context, setContext }}>
{children}
</WizardContext.Provider>
);
};
```
### 6.3 Backend Changes
**New API Endpoints:**
```python
# Bakery type
PUT /api/v1/tenants/{tenant_id}/settings
Body: { bakery_type: 'production' | 'retail' | 'mixed' }
# Production processes (new)
POST /api/v1/tenants/{tenant_id}/production/processes
GET /api/v1/tenants/{tenant_id}/production/processes
PUT /api/v1/tenants/{tenant_id}/production/processes/{id}
DELETE /api/v1/tenants/{tenant_id}/production/processes/{id}
# Analytics
POST /api/v1/analytics/wizard/event
Body: { event_type, step_name, metadata }
GET /api/v1/analytics/wizard/metrics
Response: { completion_rate, avg_duration, drop_off_points }
```
**New Database Tables:**
```sql
-- Bakery type in tenants
ALTER TABLE tenants ADD COLUMN bakery_type VARCHAR(50);
ALTER TABLE tenants ADD COLUMN data_source VARCHAR(50);
-- Production processes
CREATE TABLE production_processes (
id UUID PRIMARY KEY,
tenant_id UUID REFERENCES tenants(id),
product_id UUID REFERENCES inventory_items(id),
process_name VARCHAR(200),
description TEXT,
steps JSONB,
duration_minutes INTEGER,
temperature_celsius INTEGER,
created_at TIMESTAMP,
updated_at TIMESTAMP
);
-- Wizard analytics
CREATE TABLE wizard_analytics (
id UUID PRIMARY KEY,
user_id UUID REFERENCES users(id),
tenant_id UUID REFERENCES tenants(id),
event_type VARCHAR(100),
step_name VARCHAR(100),
metadata JSONB,
created_at TIMESTAMP
);
CREATE INDEX idx_wizard_analytics_user ON wizard_analytics(user_id);
CREATE INDEX idx_wizard_analytics_event ON wizard_analytics(event_type);
```
### 6.4 Translation Structure (Spanish)
**File: `/frontend/public/locales/es/setup_wizard.json`**
```json
{
"steps": {
"bakery_type": {
"title": "Tipo de Panadería",
"description": "Selecciona el tipo de panadería que tienes",
"production": "Panadería de Producción",
"retail": "Panadería de Reventa/Acabado",
"mixed": "Panadería Mixta"
},
"data_choice": {
"title": "Fuente de Datos",
"description": "¿Cómo quieres configurar tu inventario?",
"ai": "Subir datos de ventas (IA)",
"manual": "Configuración manual"
},
"suppliers": {
"title": "Proveedores",
"description": "Tus proveedores de ingredientes y materiales",
"add_supplier": "Agregar Proveedor",
"minimum_required": "Mínimo 1 proveedor requerido"
}
// ... 500+ more strings
}
}
```
---
## 7. Success Metrics
### 7.1 Completion Rate Targets
| Metric | Current | Target | Timeline |
|--------|---------|--------|----------|
| Wizard Start Rate | N/A | 90% | Phase 6 |
| Wizard Completion Rate | ~60% | 85% | Phase 11 |
| AI Path Success Rate | ~75% | 90% | Phase 10 |
| Manual Path Success Rate | ~50% | 70% | Phase 10 |
| Avg Completion Time (AI) | N/A | 5-7 min | Phase 10 |
| Avg Completion Time (Manual) | N/A | 10-15 min | Phase 10 |
| Drop-off at ML Training | ~30% | <10% | Phase 11 |
### 7.2 Analytics Dashboard
**Metrics to Track:**
- Total wizards started
- Total wizards completed
- Completion rate by bakery type
- Completion rate by data source
- Average time per step
- Drop-off points (heatmap)
- Most used templates
- AI suggestion acceptance rate
- ML training completion rate
**Visualizations:**
- Funnel chart (step-by-step completion)
- Time series (completions over time)
- Heatmap (drop-off points)
- Bar chart (bakery type distribution)
- Pie chart (AI vs Manual)
---
## 8. Timeline & Resources
### Overall Timeline: 6 weeks
| Phase | Duration | Dependencies | Resource Needs |
|-------|----------|--------------|----------------|
| Phase 6: Foundation | 2 weeks | Analysis complete | 1 senior dev, 1 mid dev |
| Phase 7: i18n | 1 week | Phase 6 | 1 mid dev, 1 translator |
| Phase 8: Analytics | 1 week | Phase 6 | 1 senior dev |
| Phase 9: Tours | 1 week | Phase 6 | 1 mid dev |
| Phase 10: Enhancement | 1 week | Phase 6, 7 | 1 senior dev, 1 mid dev |
| Phase 11: Testing | 1 week | All phases | 1 QA, 1 dev |
**Parallel Work:**
- Phase 7 & 8 can run in parallel
- Phase 9 can start after Phase 6
- Phase 10 can start after Phase 7
**Critical Path:**
Phase 6 Phase 10 Phase 11
---
## 9. Risk Analysis
### 9.1 Technical Risks
| Risk | Probability | Impact | Mitigation |
|------|------------|--------|------------|
| Backend API changes break existing flow | Medium | High | Comprehensive regression testing |
| WebSocket issues in ML training | Low | Medium | HTTP polling fallback (already exists) |
| Conditional logic complexity | Medium | Medium | Thorough unit testing, clear documentation |
| Translation quality issues | High | Low | Professional translator, native speaker review |
| Performance degradation | Low | Medium | Code splitting, lazy loading |
### 9.2 User Experience Risks
| Risk | Probability | Impact | Mitigation |
|------|------------|--------|------------|
| Users confused by too many options | Medium | High | Clear UI, tooltips, guided help |
| AI path users miss manual options | Low | Medium | Always show "customize" option |
| Retail bakeries confused about recipes | Medium | High | Clear bakery type explanation, skip recipes |
| Users abandon during ML training | High | High | Skip option after 2 min (already exists) |
---
## 10. Recommendations
### 10.1 Immediate Actions (Phase 6)
1. **Start with bakery type selection** - This is the foundation for everything
2. **Reuse existing AI components** - Don't reinvent the wheel
3. **Create production processes step** - Critical for retail bakeries
4. **Build wizard context system** - Enables conditional logic
5. **Update backend dependencies** - Support new step flow
### 10.2 Quick Wins
1. **Spanish translations** (Phase 7)
- High impact, relatively easy
- Primary language for target market
- Can be done in parallel with Phase 6
2. **Analytics tracking** (Phase 8)
- Essential for measuring success
- Simple to implement
- High value for product decisions
3. **Guided tours** (Phase 9)
- Reduces support tickets
- Improves user engagement
- Can reuse existing demo tour code
### 10.3 Long-term Enhancements
1. **Multi-language support** - English, French, Portuguese
2. **Video tutorials** - Embedded help videos
3. **Industry-specific templates** - By region, bakery size
4. **Advanced AI** - Image recognition for products
5. **Mobile app** - Native mobile onboarding
6. **Voice guidance** - Accessibility feature
---
## 11. Next Steps
### For Development Team:
1. **Review this plan** with stakeholders
2. **Approve/adjust phases** based on priorities
3. **Assign resources** (2 devs minimum)
4. **Set up project tracking** (Jira/Linear/etc.)
5. **Create detailed tickets** for Phase 6
6. **Start Phase 6 implementation** immediately
### For Product Team:
1. **Validate bakery type categories** with users
2. **Review analytics requirements** with stakeholders
3. **Prioritize translation quality** (hire native speaker)
4. **Plan user acceptance testing** for Phase 11
5. **Prepare marketing materials** for launch
### For Design Team:
1. **Create mockups** for new steps
2. **Design bakery type selection** UI
3. **Design data source choice** UI
4. **Design production processes** UI
5. **Review Spanish translations** for UX copy
---
## 12. Conclusion
The unified onboarding wizard will provide:
**Personalized experience** based on bakery type
**AI-powered efficiency** for users with sales data
**Manual control** for users who prefer it
**Comprehensive setup** covering all entities
**ML training integration** for predictive features
**Spanish-first interface** for primary market
**Analytics tracking** for continuous improvement
**Guided tours** for feature discovery
**Estimated Impact:**
- **85% completion rate** (up from 60%)
- **5-15 min setup time** (depending on path)
- **90% user satisfaction** (measured via NPS)
- **40% reduction in support tickets** (via guided tours)
This unified wizard will be a **competitive advantage** and a **delightful user experience** that sets the product apart in the market.
---
**Document Version:** 1.0
**Last Updated:** 2024-01-01
**Author:** Claude (AI Assistant)
**Status:** Ready for Review

View File

@@ -1,996 +0,0 @@
# Phase 6: Foundation & Integration - Detailed Implementation Plan
## Overview
This phase merges the existing AI-powered onboarding with the new comprehensive setup wizard into a unified, intelligent system with conditional flows based on bakery type and data source.
**Duration:** 2 weeks
**Team:** 1 senior developer + 1 mid-level developer
**Dependencies:** Analysis complete ✅
---
## Week 1: Core Components & Context System
### Day 1-2: Bakery Type Selection Step
**File:** `/frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx`
**Component Structure:**
```typescript
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { SetupStepProps } from '../SetupWizard';
interface BakeryType {
id: 'production' | 'retail' | 'mixed';
icon: string;
name: string;
description: string;
features: string[];
examples: string[];
color: string;
}
export const BakeryTypeSelectionStep: React.FC<SetupStepProps> = ({
onUpdate,
onComplete
}) => {
const { t } = useTranslation();
const [selectedType, setSelectedType] = useState<string | null>(null);
const bakeryTypes: BakeryType[] = [
{
id: 'production',
icon: '🥖',
name: t('bakery_type.production.name', 'Panadería de Producción'),
description: t('bakery_type.production.desc', 'Producimos desde cero usando ingredientes'),
features: [
t('bakery_type.production.feature1', 'Gestión completa de recetas'),
t('bakery_type.production.feature2', 'Control de ingredientes'),
t('bakery_type.production.feature3', 'Procesos de producción completos'),
t('bakery_type.production.feature4', 'Cálculo de costos detallado')
],
examples: [
t('bakery_type.production.example1', 'Pan artesanal'),
t('bakery_type.production.example2', 'Bollería'),
t('bakery_type.production.example3', 'Repostería')
],
color: 'from-amber-500 to-orange-600'
},
{
id: 'retail',
icon: '🛒',
name: t('bakery_type.retail.name', 'Panadería de Reventa/Acabado'),
description: t('bakery_type.retail.desc', 'Recibimos productos terminados o semi-elaborados'),
features: [
t('bakery_type.retail.feature1', 'Gestión de productos terminados'),
t('bakery_type.retail.feature2', 'Procesos de horneado simple'),
t('bakery_type.retail.feature3', 'Gestión de proveedores'),
t('bakery_type.retail.feature4', 'Control de calidad')
],
examples: [
t('bakery_type.retail.example1', 'Hornear productos precocidos'),
t('bakery_type.retail.example2', 'Venta de productos terminados'),
t('bakery_type.retail.example3', 'Acabado de productos par-baked')
],
color: 'from-blue-500 to-indigo-600'
},
{
id: 'mixed',
icon: '🏭',
name: t('bakery_type.mixed.name', 'Panadería Mixta'),
description: t('bakery_type.mixed.desc', 'Combinamos producción propia y reventa'),
features: [
t('bakery_type.mixed.feature1', 'Todas las funcionalidades'),
t('bakery_type.mixed.feature2', 'Máxima flexibilidad'),
t('bakery_type.mixed.feature3', 'Gestión completa de operaciones'),
t('bakery_type.mixed.feature4', 'Ideal para negocios en crecimiento')
],
examples: [
t('bakery_type.mixed.example1', 'Producción propia + Reventa'),
t('bakery_type.mixed.example2', 'Combinación de modelos')
],
color: 'from-purple-500 to-pink-600'
}
];
const handleSelect = (typeId: string) => {
setSelectedType(typeId);
onUpdate?.({
itemsCount: 1,
canContinue: true,
});
};
const handleContinue = async () => {
if (!selectedType) return;
// Save bakery type to context and tenant
await onComplete?.({
bakeryType: selectedType
});
};
return (
<div className="space-y-6">
{/* Header */}
<div className="text-center">
<h2 className="text-2xl font-bold text-[var(--text-primary)] mb-2">
{t('bakery_type.title', '¿Qué tipo de panadería tienes?')}
</h2>
<p className="text-[var(--text-secondary)]">
{t('bakery_type.subtitle', 'Esto nos ayudará a personalizar tu experiencia')}
</p>
</div>
{/* Bakery Type Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{bakeryTypes.map((type) => (
<button
key={type.id}
onClick={() => handleSelect(type.id)}
className={`
relative p-6 border-2 rounded-xl transition-all
${selectedType === type.id
? 'border-[var(--color-primary)] shadow-lg scale-105'
: 'border-[var(--border-secondary)] hover:border-[var(--color-primary)] hover:shadow-md'
}
text-left group
`}
>
{/* Selected Indicator */}
{selectedType === type.id && (
<div className="absolute top-3 right-3">
<svg className="w-6 h-6 text-[var(--color-success)]" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
</svg>
</div>
)}
{/* Icon */}
<div className={`text-6xl mb-4 bg-gradient-to-br ${type.color} bg-clip-text text-transparent`}>
{type.icon}
</div>
{/* Name & Description */}
<h3 className="font-bold text-lg text-[var(--text-primary)] mb-2">
{type.name}
</h3>
<p className="text-sm text-[var(--text-secondary)] mb-4">
{type.description}
</p>
{/* Features */}
<div className="space-y-2 mb-4">
<p className="text-xs font-semibold text-[var(--text-tertiary)] uppercase">
{t('bakery_type.features', 'Características')}:
</p>
<ul className="space-y-1">
{type.features.map((feature, idx) => (
<li key={idx} className="flex items-start gap-2 text-sm text-[var(--text-secondary)]">
<svg className="w-4 h-4 text-[var(--color-success)] mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
</svg>
<span>{feature}</span>
</li>
))}
</ul>
</div>
{/* Examples */}
<div className="pt-3 border-t border-[var(--border-secondary)]">
<p className="text-xs font-semibold text-[var(--text-tertiary)] uppercase mb-1">
{t('bakery_type.examples', 'Ejemplos')}:
</p>
<p className="text-xs text-[var(--text-secondary)]">
{type.examples.join(', ')}
</p>
</div>
</button>
))}
</div>
{/* Help Text */}
<div className="bg-[var(--color-info)]/10 border border-[var(--color-info)]/20 rounded-lg p-4">
<div className="flex items-start gap-2">
<svg className="w-5 h-5 text-[var(--color-info)] mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
</svg>
<div className="flex-1">
<p className="text-sm font-medium text-[var(--text-primary)] mb-1">
{t('bakery_type.help_title', '¿No estás seguro?')}
</p>
<p className="text-sm text-[var(--text-secondary)]">
{t('bakery_type.help_desc', 'Puedes elegir "Panadería Mixta" si combinas producción propia con reventa de productos. Podrás personalizar más adelante.')}
</p>
</div>
</div>
</div>
</div>
);
};
```
**API Integration:**
```typescript
// Update tenant with bakery type
const updateTenantBakeryType = async (tenantId: string, bakeryType: string) => {
await apiClient.put(`/api/v1/tenants/${tenantId}/settings`, {
bakery_type: bakeryType
});
};
```
**Tasks:**
- [ ] Create component file
- [ ] Implement UI with 3 cards
- [ ] Add hover/selected states
- [ ] Integrate with API to save bakery type
- [ ] Add unit tests
- [ ] Add Storybook story
---
### Day 3-4: Data Source Choice Step
**File:** `/frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx`
**Component Structure:**
```typescript
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { SetupStepProps } from '../SetupWizard';
interface DataSourceOption {
id: 'ai' | 'manual';
icon: React.ReactNode;
name: string;
description: string;
duration: string;
benefits: string[];
recommended?: boolean;
}
export const DataSourceChoiceStep: React.FC<SetupStepProps> = ({
onUpdate,
onComplete
}) => {
const { t } = useTranslation();
const [selectedSource, setSelectedSource] = useState<string | null>(null);
const dataSources: DataSourceOption[] = [
{
id: 'ai',
icon: (
<svg className="w-12 h-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
</svg>
),
name: t('data_source.ai.name', 'Subir datos de ventas (Recomendado)'),
description: t('data_source.ai.desc', 'Deja que la IA analice tus ventas y configure automáticamente tu inventario'),
duration: t('data_source.ai.duration', '~5 minutos'),
benefits: [
t('data_source.ai.benefit1', 'Configuración automática basada en tus datos reales'),
t('data_source.ai.benefit2', 'Recomendaciones inteligentes de productos'),
t('data_source.ai.benefit3', 'Análisis de patrones de venta'),
t('data_source.ai.benefit4', 'Mucho más rápido que la configuración manual')
],
recommended: true
},
{
id: 'manual',
icon: (
<svg className="w-12 h-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
),
name: t('data_source.manual.name', 'Configuración manual'),
description: t('data_source.manual.desc', 'Configura todo desde cero usando nuestras plantillas y guías'),
duration: t('data_source.manual.duration', '~15 minutos'),
benefits: [
t('data_source.manual.benefit1', 'Control total sobre cada detalle'),
t('data_source.manual.benefit2', 'No necesitas datos históricos'),
t('data_source.manual.benefit3', 'Plantillas predefinidas incluidas'),
t('data_source.manual.benefit4', 'Ideal para negocios nuevos')
],
recommended: false
}
];
const handleSelect = (sourceId: string) => {
setSelectedSource(sourceId);
onUpdate?.({
itemsCount: 1,
canContinue: true,
});
};
const handleContinue = async () => {
if (!selectedSource) return;
await onComplete?.({
dataSource: selectedSource
});
};
return (
<div className="space-y-6">
{/* Header */}
<div className="text-center">
<h2 className="text-2xl font-bold text-[var(--text-primary)] mb-2">
{t('data_source.title', '¿Cómo quieres configurar tu inventario?')}
</h2>
<p className="text-[var(--text-secondary)]">
{t('data_source.subtitle', 'Elige el método que mejor se adapte a tu situación')}
</p>
</div>
{/* Data Source Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl mx-auto">
{dataSources.map((source) => (
<button
key={source.id}
onClick={() => handleSelect(source.id)}
className={`
relative p-6 border-2 rounded-xl transition-all
${selectedSource === source.id
? 'border-[var(--color-primary)] shadow-lg scale-105'
: 'border-[var(--border-secondary)] hover:border-[var(--color-primary)] hover:shadow-md'
}
text-left
`}
>
{/* Recommended Badge */}
{source.recommended && (
<div className="absolute top-3 right-3 px-3 py-1 bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-success)] text-white text-xs font-semibold rounded-full">
{t('data_source.recommended', 'Recomendado')}
</div>
)}
{/* Selected Indicator */}
{selectedSource === source.id && !source.recommended && (
<div className="absolute top-3 right-3">
<svg className="w-6 h-6 text-[var(--color-success)]" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
</svg>
</div>
)}
{/* Icon */}
<div className="text-[var(--color-primary)] mb-4">
{source.icon}
</div>
{/* Name & Duration */}
<div className="mb-2">
<h3 className="font-bold text-lg text-[var(--text-primary)]">
{source.name}
</h3>
<p className="text-sm text-[var(--color-primary)] font-medium">
⏱️ {source.duration}
</p>
</div>
{/* Description */}
<p className="text-sm text-[var(--text-secondary)] mb-4">
{source.description}
</p>
{/* Benefits */}
<ul className="space-y-2">
{source.benefits.map((benefit, idx) => (
<li key={idx} className="flex items-start gap-2 text-sm text-[var(--text-secondary)]">
<svg className="w-4 h-4 text-[var(--color-success)] mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
</svg>
<span>{benefit}</span>
</li>
))}
</ul>
</button>
))}
</div>
{/* Additional Info */}
<div className="max-w-4xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-4">
{/* AI Path Info */}
<div className="bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<h4 className="font-semibold text-[var(--text-primary)] mb-2 flex items-center gap-2">
<svg className="w-5 h-5 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
</svg>
{t('data_source.ai_info_title', 'Ruta con IA')}
</h4>
<p className="text-sm text-[var(--text-secondary)]">
{t('data_source.ai_info', 'Necesitarás un archivo CSV, Excel o JSON con tus datos de ventas históricos. La IA analizará tus productos y configurará automáticamente el inventario.')}
</p>
</div>
{/* Manual Path Info */}
<div className="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
<h4 className="font-semibold text-[var(--text-primary)] mb-2 flex items-center gap-2">
<svg className="w-5 h-5 text-green-600" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
</svg>
{t('data_source.manual_info_title', 'Ruta Manual')}
</h4>
<p className="text-sm text-[var(--text-secondary)]">
{t('data_source.manual_info', 'Te guiaremos paso a paso para agregar proveedores, ingredientes y recetas. Incluimos plantillas para facilitar el proceso.')}
</p>
</div>
</div>
</div>
);
};
```
**Tasks:**
- [ ] Create component file
- [ ] Implement UI with 2 cards
- [ ] Add recommended badge for AI path
- [ ] Add info boxes
- [ ] Integrate with wizard context
- [ ] Add unit tests
- [ ] Add Storybook story
---
### Day 5: Production Processes Step (for Retail Bakeries)
**File:** `/frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx`
**Component Structure:** (See PHASE_6_DETAILED_SPEC.md for full implementation)
**API Endpoints:**
```typescript
// Backend: Create production process endpoint
POST /api/v1/tenants/{tenant_id}/production/processes
Body: {
product_id: string;
process_name: string;
description: string;
steps: Array<{
order: number;
instruction: string;
duration_minutes: number;
temperature_celsius?: number;
}>;
duration_minutes: number;
temperature_celsius?: number;
}
```
**Tasks:**
- [ ] Create component file
- [ ] Implement process form
- [ ] Add process templates library
- [ ] Create backend API endpoint
- [ ] Create database table
- [ ] Add unit tests
- [ ] Add integration tests
---
## Week 2: Context System & Integration
### Day 6-7: Wizard Context Provider
**File:** `/frontend/src/contexts/WizardContext.tsx`
```typescript
import React, { createContext, useContext, useState, useCallback } from 'react';
interface WizardContextType {
// Discovery
bakeryType?: 'production' | 'retail' | 'mixed';
dataSource?: 'ai' | 'manual';
// AI Path Data
salesDataUploaded: boolean;
aiSuggestions: ProductSuggestion[];
selectedSuggestions: string[];
// Setup Data
suppliers: Supplier[];
inventory: InventoryItem[];
recipes: Recipe[];
processes: ProductionProcess[];
qualityTemplates: QualityTemplate[];
teamMembers: TeamMember[];
// ML Training
mlTrainingJobId?: string;
mlTrainingStatus?: 'pending' | 'in_progress' | 'completed' | 'failed';
mlTrainingProgress?: number;
// Actions
setBakeryType: (type: 'production' | 'retail' | 'mixed') => void;
setDataSource: (source: 'ai' | 'manual') => void;
setAISuggestions: (suggestions: ProductSuggestion[]) => void;
addSupplier: (supplier: Supplier) => void;
addInventoryItem: (item: InventoryItem) => void;
addRecipe: (recipe: Recipe) => void;
addProcess: (process: ProductionProcess) => void;
reset: () => void;
}
const WizardContext = createContext<WizardContextType | undefined>(undefined);
export const WizardProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [bakeryType, setBakeryType] = useState<'production' | 'retail' | 'mixed'>();
const [dataSource, setDataSource] = useState<'ai' | 'manual'>();
const [salesDataUploaded, setSalesDataUploaded] = useState(false);
const [aiSuggestions, setAISuggestions] = useState<ProductSuggestion[]>([]);
const [selectedSuggestions, setSelectedSuggestions] = useState<string[]>([]);
const [suppliers, setSuppliers] = useState<Supplier[]>([]);
const [inventory, setInventory] = useState<InventoryItem[]>([]);
const [recipes, setRecipes] = useState<Recipe[]>([]);
const [processes, setProcesses] = useState<ProductionProcess[]>([]);
const [qualityTemplates, setQualityTemplates] = useState<QualityTemplate[]>([]);
const [teamMembers, setTeamMembers] = useState<TeamMember[]>([]);
const [mlTrainingJobId, setMLTrainingJobId] = useState<string>();
const [mlTrainingStatus, setMLTrainingStatus] = useState<string>();
const [mlTrainingProgress, setMLTrainingProgress] = useState<number>(0);
const addSupplier = useCallback((supplier: Supplier) => {
setSuppliers(prev => [...prev, supplier]);
}, []);
const addInventoryItem = useCallback((item: InventoryItem) => {
setInventory(prev => [...prev, item]);
}, []);
const addRecipe = useCallback((recipe: Recipe) => {
setRecipes(prev => [...prev, recipe]);
}, []);
const addProcess = useCallback((process: ProductionProcess) => {
setProcesses(prev => [...prev, process]);
}, []);
const reset = useCallback(() => {
setBakeryType(undefined);
setDataSource(undefined);
setSalesDataUploaded(false);
setAISuggestions([]);
setSelectedSuggestions([]);
setSuppliers([]);
setInventory([]);
setRecipes([]);
setProcesses([]);
setQualityTemplates([]);
setTeamMembers([]);
setMLTrainingJobId(undefined);
setMLTrainingStatus(undefined);
setMLTrainingProgress(0);
}, []);
const value: WizardContextType = {
bakeryType,
dataSource,
salesDataUploaded,
aiSuggestions,
selectedSuggestions,
suppliers,
inventory,
recipes,
processes,
qualityTemplates,
teamMembers,
mlTrainingJobId,
mlTrainingStatus,
mlTrainingProgress,
setBakeryType,
setDataSource,
setAISuggestions,
addSupplier,
addInventoryItem,
addRecipe,
addProcess,
reset
};
return (
<WizardContext.Provider value={value}>
{children}
</WizardContext.Provider>
);
};
export const useWizardContext = () => {
const context = useContext(WizardContext);
if (context === undefined) {
throw new Error('useWizardContext must be used within a WizardProvider');
}
return context;
};
```
**Tasks:**
- [ ] Create context file
- [ ] Implement state management
- [ ] Add persistence to localStorage
- [ ] Add TypeScript types
- [ ] Add hooks for context consumption
- [ ] Add unit tests
---
### Day 8-9: Conditional Step Logic
**File:** `/frontend/src/components/domain/onboarding/SetupWizard.tsx` (update existing)
**Add Step Visibility Logic:**
```typescript
import { useWizardContext } from '../../../contexts/WizardContext';
const getVisibleSteps = (
bakeryType?: string,
dataSource?: string,
hasSalesData?: boolean
): StepConfig[] => {
const steps: StepConfig[] = [];
// Phase 1: Discovery
steps.push(
{
id: 'bakery-type',
title: t('steps.bakery_type.title', 'Tipo de Panadería'),
description: t('steps.bakery_type.description', 'Selecciona tu modelo de negocio'),
component: BakeryTypeSelectionStep,
weight: 5,
estimatedMinutes: 2
},
{
id: 'data-choice',
title: t('steps.data_choice.title', 'Fuente de Datos'),
description: t('steps.data_choice.description', 'Elige cómo configurar'),
component: DataSourceChoiceStep,
weight: 5,
estimatedMinutes: 1
}
);
// Phase 2a: AI-Assisted Path (conditional)
if (dataSource === 'ai') {
steps.push(
{
id: 'upload-sales',
title: t('steps.upload_sales.title', 'Subir Datos'),
description: t('steps.upload_sales.description', 'Datos históricos de ventas'),
component: UploadSalesDataStep, // Reuse existing
weight: 15,
estimatedMinutes: 5
}
);
}
// Phase 2b: Core Setup (always shown)
steps.push(
{
id: 'suppliers-setup',
title: t('steps.suppliers.title', 'Proveedores'),
description: t('steps.suppliers.description', 'Tus proveedores'),
component: SuppliersSetupStep, // From new wizard
minRequired: 1,
weight: 10,
estimatedMinutes: 5
},
{
id: 'inventory-setup',
title: t('steps.inventory.title', 'Inventario'),
description: t('steps.inventory.description', 'Ingredientes y productos'),
component: InventorySetupStep, // Enhanced from new wizard
minRequired: 3,
weight: 20,
estimatedMinutes: 10
}
);
// Step 8a: Recipes (conditional - production/mixed only)
if (bakeryType === 'production' || bakeryType === 'mixed') {
steps.push({
id: 'recipes-setup',
title: t('steps.recipes.title', 'Recetas'),
description: t('steps.recipes.description', 'Tus fórmulas de producción'),
component: RecipesSetupStep, // From new wizard
minRequired: 1,
weight: 20,
estimatedMinutes: 10
});
}
// Step 8b: Production Processes (conditional - retail/mixed only)
if (bakeryType === 'retail' || bakeryType === 'mixed') {
steps.push({
id: 'production-processes',
title: t('steps.processes.title', 'Procesos de Producción'),
description: t('steps.processes.description', 'Instrucciones de horneado'),
component: ProductionProcessesStep, // New component
minRequired: 1,
weight: 15,
estimatedMinutes: 7
});
}
// Phase 3: Advanced Features (optional)
steps.push(
{
id: 'quality-setup',
title: t('steps.quality.title', 'Calidad'),
description: t('steps.quality.description', 'Estándares de calidad'),
component: QualitySetupStep, // From new wizard
isOptional: true,
weight: 15,
estimatedMinutes: 7
},
{
id: 'team-setup',
title: t('steps.team.title', 'Equipo'),
description: t('steps.team.description', 'Miembros del equipo'),
component: TeamSetupStep, // From new wizard
isOptional: true,
weight: 10,
estimatedMinutes: 5
}
);
// Phase 4: ML & Finalization
if (hasSalesData) {
steps.push({
id: 'ml-training',
title: t('steps.ml_training.title', 'Entrenamiento IA'),
description: t('steps.ml_training.description', 'Entrenar modelos predictivos'),
component: MLTrainingStep, // Reuse existing
weight: 10,
estimatedMinutes: 5
});
}
steps.push(
{
id: 'review',
title: t('steps.review.title', 'Revisar'),
description: t('steps.review.description', 'Confirma tu configuración'),
component: ReviewSetupStep, // From new wizard
weight: 5,
estimatedMinutes: 2
},
{
id: 'completion',
title: t('steps.completion.title', '¡Listo!'),
description: t('steps.completion.description', 'Sistema configurado'),
component: CompletionStep, // From new wizard
weight: 5,
estimatedMinutes: 2
}
);
return steps;
};
```
**Update SetupWizard Component:**
```typescript
export const SetupWizard: React.FC = () => {
const { bakeryType, dataSource } = useWizardContext();
const [currentStepIndex, setCurrentStepIndex] = useState(0);
// Dynamically calculate visible steps
const visibleSteps = useMemo(() => {
return getVisibleSteps(bakeryType, dataSource, salesDataUploaded);
}, [bakeryType, dataSource, salesDataUploaded]);
// ... rest of wizard logic
};
```
**Tasks:**
- [ ] Implement getVisibleSteps function
- [ ] Update SetupWizard to use dynamic steps
- [ ] Add step dependency validation
- [ ] Update progress calculation
- [ ] Test all conditional paths
- [ ] Add integration tests
---
### Day 10: Backend Integration
**Backend Tasks:**
**1. Add bakery_type to tenants table:**
```sql
ALTER TABLE tenants ADD COLUMN bakery_type VARCHAR(50);
ALTER TABLE tenants ADD COLUMN data_source VARCHAR(50);
```
**2. Create production_processes table:**
```sql
CREATE TABLE production_processes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
product_id UUID NOT NULL REFERENCES inventory_items(id) ON DELETE CASCADE,
process_name VARCHAR(200) NOT NULL,
description TEXT,
steps JSONB NOT NULL DEFAULT '[]',
duration_minutes INTEGER,
temperature_celsius INTEGER,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
created_by UUID REFERENCES users(id),
CONSTRAINT fk_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id),
CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES inventory_items(id)
);
CREATE INDEX idx_production_processes_tenant ON production_processes(tenant_id);
CREATE INDEX idx_production_processes_product ON production_processes(product_id);
```
**3. Create API endpoint for production processes:**
**File:** `/services/production/app/api/production_processes.py`
```python
from fastapi import APIRouter, Depends, HTTPException
from uuid import UUID
from typing import List
from app.models.production_process import ProductionProcess, ProductionProcessCreate
from app.services.auth import get_current_user
from app.database import get_db
router = APIRouter()
@router.post("/tenants/{tenant_id}/production/processes")
async def create_production_process(
tenant_id: UUID,
process: ProductionProcessCreate,
current_user = Depends(get_current_user),
db = Depends(get_db)
):
# Validate tenant access
# Create production process
# Return created process
pass
@router.get("/tenants/{tenant_id}/production/processes")
async def get_production_processes(
tenant_id: UUID,
current_user = Depends(get_current_user),
db = Depends(get_db)
) -> List[ProductionProcess]:
# Validate tenant access
# Fetch processes
# Return processes
pass
```
**4. Update onboarding step dependencies:**
**File:** `/services/auth/app/api/onboarding_progress.py`
Update STEP_DEPENDENCIES to include new steps:
```python
STEP_DEPENDENCIES = {
"bakery-type": ["user_registered"],
"data-choice": ["user_registered", "bakery-type"],
"upload-sales": ["user_registered", "bakery-type", "data-choice"],
"suppliers-setup": ["user_registered", "bakery-type", "data-choice"],
"inventory-setup": ["user_registered", "bakery-type", "suppliers-setup"],
"recipes-setup": ["user_registered", "bakery-type", "inventory-setup"],
"production-processes": ["user_registered", "bakery-type", "inventory-setup"],
"quality-setup": ["user_registered", "bakery-type", "inventory-setup"],
"team-setup": ["user_registered", "bakery-type"],
"ml-training": ["user_registered", "bakery-type", "inventory-setup"],
"review": ["user_registered", "bakery-type", "inventory-setup"],
"completion": ["user_registered", "bakery-type", "review"]
}
```
**Tasks:**
- [ ] Add database migrations
- [ ] Create production processes API
- [ ] Update tenant settings endpoint
- [ ] Update step dependencies
- [ ] Add backend unit tests
- [ ] Add API integration tests
---
## Testing Strategy
### Unit Tests
**Component Tests:**
- [ ] BakeryTypeSelectionStep - 3 type cards render, selection works
- [ ] DataSourceChoiceStep - 2 option cards render, selection works
- [ ] ProductionProcessesStep - Form renders, validation works
- [ ] WizardContext - State management works correctly
- [ ] Conditional step logic - Steps show/hide based on context
**API Tests:**
- [ ] POST /tenants/{id}/settings - Saves bakery type
- [ ] POST /production/processes - Creates process
- [ ] GET /production/processes - Fetches processes
- [ ] Step dependencies - Validates correctly
### Integration Tests
**End-to-End Flows:**
- [ ] Production + AI path: Full flow works
- [ ] Production + Manual path: Full flow works
- [ ] Retail + AI path: Full flow works
- [ ] Retail + Manual path: Full flow works
- [ ] Mixed + AI path: Full flow works
- [ ] Mixed + Manual path: Full flow works
### Manual Testing Checklist
- [ ] All step transitions work
- [ ] Context persists across navigation
- [ ] Backend saves data correctly
- [ ] Progress tracking works
- [ ] Can go back and change selections
- [ ] Conditional steps appear/disappear correctly
- [ ] All UI states (loading, error, success) work
- [ ] Mobile responsive
- [ ] Accessibility (keyboard navigation, screen readers)
---
## Deliverables
**Week 1:**
1. BakeryTypeSelectionStep component
2. DataSourceChoiceStep component
3. ProductionProcessesStep component
4. Component tests
5. Storybook stories
**Week 2:**
6. WizardContext provider
7. Conditional step logic
8. Backend database changes
9. Backend API endpoints
10. Integration tests
---
## Success Criteria
- [ ] All 6 onboarding paths work end-to-end
- [ ] Context persists correctly
- [ ] Backend stores all new data
- [ ] Tests have >80% coverage
- [ ] No TypeScript errors
- [ ] Build succeeds
- [ ] Performance: Wizard loads in <2s
- [ ] Accessibility: WCAG AA compliant
---
## Next Phase Preview
**Phase 7: Spanish Translations**
- Comprehensive Spanish i18n
- 1000+ translation strings
- Translation review by native speaker
- Default language set to Spanish
---
## Resources Needed
- **Senior Developer** (Days 1-10): Architecture, context system, integration
- **Mid Developer** (Days 1-10): Component implementation, testing
- **Backend Developer** (Days 10): Database migrations, API endpoints
- **Designer** (Days 1-3): Review mockups for new steps
- **QA** (Days 8-10): Integration testing
---
**Ready to start? Let's build Phase 6! 🚀**

View File

@@ -1,188 +0,0 @@
# AI Inventory Step Redesign - Key Differences
## Overview
Completely redesigned UploadSalesDataStep to follow the suppliers/recipes pattern with list-based management and deferred creation.
## Major Changes
### 1. **Data Model**
**BEFORE**:
```typescript
interface InventoryItem {
suggestion_id: string;
selected: boolean; // Checkbox selection
stock_quantity: number;
cost_per_unit: number;
}
```
**AFTER**:
```typescript
interface InventoryItemForm {
id: string; // UI tracking
name: string;
// ... all inventory fields
isSuggested: boolean; // Track if from AI or manual
// NO "selected" field - all items in list will be created
}
```
### 2. **Creation Timing**
**BEFORE**:
- Checkbox selection UI
- "Create Inventory" button → Creates immediately → Proceeds to next step
**AFTER**:
- List-based UI (like suppliers/recipes)
- Items added to list (NOT created yet)
- "Next" button → Creates ALL items → Proceeds to next step
### 3. **UI Pattern**
**BEFORE** (Old Pattern):
```
┌─────────────────────────────────────┐
│ ☑️ Product 1 [Edit fields inline] │
│ ☐ Product 2 [Edit fields inline] │
│ ☑️ Product 3 [Edit fields inline] │
│ │
│ [Create 2 Selected Items] │
└─────────────────────────────────────┘
```
**AFTER** (New Pattern - Like Suppliers/Recipes):
```
┌─────────────────────────────────────┐
│ Product 1 (AI 95%) [Edit][Delete]│
│ Stock: 50kg Cost: €5.00 │
│ │
│ Product 2 (Manual) [Edit][Delete]│
│ Stock: 30kg Cost: €3.00 │
│ │
│ [ Add Ingredient Manually] │
│ │
│ ────────────────────────────────── │
│ 3 ingredients - Ready! [Next →] │
└─────────────────────────────────────┘
```
### 4. **Manual Addition**
**BEFORE**: No way to add manual ingredients
**AFTER**:
- "Add Ingredient Manually" button
- Full form with all fields
- Adds to the same list as AI suggestions
- Can edit/delete both AI and manual items
### 5. **Edit/Delete**
**BEFORE**:
- Inline editing only
- No delete (just deselect)
**AFTER**:
- Click "Edit" → Opens form with all fields
- Click "Delete" → Removes from list
- Works for both AI suggestions and manual entries
### 6. **Code Structure**
**BEFORE** (Old):
```typescript
// State
const [inventoryItems, setInventoryItems] = useState<InventoryItem[]>([]);
// Selection toggle
const handleToggleSelection = (id: string) => {
setInventoryItems(items =>
items.map(item =>
item.suggestion_id === id ? { ...item, selected: !item.selected } : item
)
);
};
// Create button - immediate creation
const handleCreateInventory = async () => {
const selectedItems = inventoryItems.filter(item => item.selected);
// Create immediately...
await Promise.all(creationPromises);
onComplete(); // Then proceed
};
```
**AFTER** (New):
```typescript
// State
const [inventoryItems, setInventoryItems] = useState<InventoryItemForm[]>([]);
const [isAdding, setIsAdding] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null);
const [formData, setFormData] = useState<InventoryItemForm>({ ... });
// Add/Edit item in list (NOT in database)
const handleSubmitForm = (e: React.FormEvent) => {
if (editingId) {
// Update in list
setInventoryItems(items => items.map(item =>
item.id === editingId ? { ...formData, id: editingId } : item
));
} else {
// Add to list
setInventoryItems(items => [...items, newItem]);
}
resetForm();
};
// Delete from list
const handleDelete = (itemId: string) => {
setInventoryItems(items => items.filter(item => item.id !== itemId));
};
// Next button - create ALL at once
const handleNext = async () => {
// Create ALL items in the list
const creationPromises = inventoryItems.map(item => createIngredient.mutateAsync(...));
await Promise.allSettled(creationPromises);
onComplete(); // Then proceed
};
```
### 7. **Component Sections**
**BEFORE**: 2 main sections
1. File upload view
2. Checkbox selection + edit view
**AFTER**: 2 main sections
1. File upload view (same)
2. **List management view**:
- "Why This Matters" info box
- Ingredient list (cards with edit/delete)
- Add/Edit form (appears on click)
- Navigation with "Next" button
## Key Benefits
**Consistent UI**: Matches suppliers/recipes pattern exactly
**Flexibility**: Users can review, edit, delete, and add items before creating
**Deferred Creation**: All items created at once when clicking "Next"
**Manual Addition**: Users can add ingredients beyond AI suggestions
**Better UX**: Clear "Edit" and "Delete" actions per item
**Unified Pattern**: Same workflow for AI and manual items
## Files Changed
- `/home/user/bakery_ia/frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx` - **Completely rewritten** (963 lines)
- `/home/user/bakery_ia/frontend/src/components/domain/setup-wizard/steps/RecipesSetupStep.tsx` - Added Next button (2 lines)
## Testing Checklist
- [ ] Upload sales data file → AI suggestions load correctly
- [ ] Edit AI suggestion → Changes saved to list
- [ ] Delete AI suggestion → Removed from list
- [ ] Add manual ingredient → Added to list
- [ ] Edit manual ingredient → Changes saved
- [ ] Delete manual ingredient → Removed from list
- [ ] Click "Next" with 0 items → Error shown
- [ ] Click "Next" with items → All created and proceeds to next step
- [ ] Form validation works (required fields, min values)
- [ ] UI matches suppliers/recipes styling

View File

@@ -1,513 +0,0 @@
# Session Summary: Phases 7 & 9 Implementation + Flow Reorganization
## Overview
This session successfully implemented **Phase 7 (Spanish Translations)** and **Phase 9 (Guided Tours)** for the unified onboarding system, plus identified and documented critical improvements for the AI-assisted onboarding flow.
---
## ✅ Phase 7: Spanish Translations - COMPLETE
### Accomplishments
**1. Comprehensive Spanish Translations for New Onboarding Steps**
Added **150+ translation keys** to `/frontend/src/locales/es/onboarding.json`:
#### BakeryTypeSelectionStep (`onboarding.bakery_type`)
- Main UI text (title, subtitle, labels, buttons)
- **Production Bakery** (Panadería de Producción)
- 4 features, 4 examples, selected info
- **Retail Bakery** (Panadería de Venta)
- 4 features, 4 examples, selected info
- **Mixed Bakery** (Panadería Mixta)
- 4 features, 4 examples, selected info
#### DataSourceChoiceStep (`onboarding.data_source`)
- Main UI text and navigation
- **AI-Assisted Path** (Configuración Inteligente con IA)
- 4 benefits, 3 ideal scenarios, estimated time
- Detailed requirements (file types, data needs)
- **Manual Path** (Configuración Manual Paso a Paso)
- 4 benefits, 3 ideal scenarios, estimated time
- Step-by-step breakdown of what's configured
#### ProductionProcessesStep (`onboarding.processes`)
- Main UI and form labels
- 4 process types (Horneado, Decoración, Terminado, Montaje)
- Template library text
- Form fields (name, source, finished, duration, temperature, instructions)
#### Updated Wizard Navigation
- All step titles and descriptions
- Progress indicators
- Navigation buttons
- Help text and tooltips
### Files Modified
- `/frontend/src/locales/es/onboarding.json` (+150 keys)
### Quality
- ✅ Natural Spanish translations (not machine-translated)
- ✅ Context-appropriate terminology for bakery domain
- ✅ Consistent tone and style
- ✅ Complete coverage of all UI text
- ✅ Ready for bakery owners in Spain/Latin America
---
## ✅ Phase 9: Guided Tours - COMPLETE
### Accomplishments
**1. Tour Framework Created**
#### TourContext (`/frontend/src/contexts/TourContext.tsx`)
- Complete state management system
- localStorage persistence (completed/skipped tours)
- Navigation methods (next, previous, skip, complete)
- beforeShow/afterShow hooks for custom logic
- Support for async operations
- TypeScript interfaces for type safety
**Key Features:**
- Never show the same tour twice (unless explicitly restarted)
- Track tour completion across sessions
- Support for custom actions in tour steps
- Centralized state management
**2. Tour UI Components**
#### TourTooltip (`/frontend/src/components/ui/Tour/TourTooltip.tsx`)
- Intelligent positioning with 4 placements (top, bottom, left, right)
- Auto-adjusts if tooltip goes off-screen
- Responsive to window resize and scroll
- Progress indicators (dot navigation)
- Navigation buttons (Previous, Next, Finish)
- Close/Skip functionality
- Arrow pointing to target element
- Animations (scale-in)
- 373 lines of polished code
#### TourSpotlight (`/frontend/src/components/ui/Tour/TourSpotlight.tsx`)
- SVG mask overlay (dims entire page except target)
- Highlighted border around target element (pulsing animation)
- Auto-scroll target into view
- Responsive to window resize/scroll
- Smooth fade-in animation
- 88 lines of efficient code
#### Tour Component (`/frontend/src/components/ui/Tour/Tour.tsx`)
- Main container that combines tooltip + spotlight
- Portal rendering for proper z-index layering
- Disables body scroll during active tour
- Clean integration point
- 43 lines
#### TourButton (`/frontend/src/components/ui/Tour/TourButton.tsx`)
- 3 variants:
- **Icon**: Help icon with dropdown menu
- **Button**: Standard button to show all tours
- **Single Tour**: Button for specific tour
- Dropdown menu shows all available tours
- Displays completion status (checkmark icon)
- Shows number of steps for each tour
- 169 lines
**3. Predefined Tours**
Created **5 comprehensive tours** (`/frontend/src/tours/tours.ts`):
1. **Dashboard Tour** - 5 steps
- Welcome and overview
- Key statistics cards
- AI forecast chart
- Inventory alerts panel
- Main navigation sidebar
2. **Inventory Tour** - 5 steps
- Inventory management overview
- Add ingredient button and form
- Search and filter functionality
- Inventory table view
- Stock alert indicators
3. **Recipes Tour** - 5 steps
- Recipe management introduction
- Create recipe workflow
- Automatic cost calculation
- Recipe yield configuration
- Batch multiplier feature
4. **Production Tour** - 5 steps
- Production planning overview
- Production schedule calendar
- AI-powered recommendations
- Create production batch
- Batch status tracking
5. **Post-Onboarding Tour** - 5 steps
- Congratulations and welcome
- Main navigation overview
- Quick actions toolbar
- Notifications center
- Help resources
**Total: 25 tour steps** across all features
**4. Tour Translations**
Created `/frontend/src/locales/es/tour.json` with:
- Navigation labels (Anterior, Siguiente, Finalizar, Omitir)
- Progress indicators
- Tour trigger button text
- Completion messages
- Tour names and descriptions
- Tooltip text
### Files Created
- `/frontend/src/contexts/TourContext.tsx` (213 lines)
- `/frontend/src/components/ui/Tour/Tour.tsx` (43 lines)
- `/frontend/src/components/ui/Tour/TourTooltip.tsx` (373 lines)
- `/frontend/src/components/ui/Tour/TourSpotlight.tsx` (88 lines)
- `/frontend/src/components/ui/Tour/TourButton.tsx` (169 lines)
- `/frontend/src/components/ui/Tour/index.ts` (3 lines)
- `/frontend/src/tours/tours.ts` (348 lines)
- `/frontend/src/locales/es/tour.json` (29 keys)
**Total: ~1,266 lines of production code**
### Technical Implementation
**Design Patterns Used:**
- Context API for state management
- Portal rendering for overlays
- Compound component pattern
- Hooks for reusable logic
- Observer pattern for window events
**Accessibility:**
- Keyboard navigation support
- ARIA labels
- Focus management
- Screen reader friendly
**Performance:**
- Efficient re-rendering
- Window event debouncing
- localStorage for persistence
- Lazy loading of tours
---
## 📋 Flow Reorganization Analysis
### Problem Identified
User feedback highlighted confusion in the AI-assisted onboarding path:
1. "Review Suggestions" creates product list but doesn't capture **initial stock**
2. "Inventory Setup" adds ingredients with stock, creating confusion
3. Unclear relationship between AI-suggested products and manual inventory entry
4. **Critical issue**: Initial stock levels are essential for system functionality
### Solution Documented
Created comprehensive reorganization plan in:
`/ONBOARDING_FLOW_REORGANIZATION.md`
**Key Changes Proposed:**
1. **Combined "Review & Complete Product List" Step (AI Path)**
- Sub-step 4a: Review AI Suggestions
- Sub-step 4b: Categorize (Ingredients vs Finished Products) ⭐ NEW
- Sub-step 4c: Set Initial Stock Levels ⭐ CRITICAL
2. **Eliminate Redundant "Inventory Setup" in AI Path**
- All inventory handled in step 4
- Reduces total steps
- Prevents duplicate data entry
3. **Explicit Categorization Step**
- System needs to know: ingredient vs finished product
- Drag-and-drop UI for easy sorting
- AI suggests, user confirms
4. **Initial Stock Capture in BOTH Paths**
- AI Path: Step 4c (after product review)
- Manual Path: Integrated into inventory setup
- Ensures system can function from day 1
**Benefits:**
- ✅ Clear single workflow for product setup
- ✅ Captures initial stock for ALL items
- ✅ Eliminates confusion about "where to add stock"
- ✅ Aligns with JTBD: get operational quickly
- ✅ Enables production planning from start
- ✅ Enables accurate cost calculations
- ✅ Low stock alerts work immediately
### Next Steps for Implementation
**Phase 6.5: Flow Reorganization (1 week)**
- Day 1-2: Enhanced Review Step with sub-steps
- Day 3-4: Backend updates (product type, initial stock)
- Day 5: Integration and testing
---
## 🎯 Git Commits
### Commit 1: Phase 6 (Previously)
```
470cb91 - Implement Phase 6: Unified Onboarding Foundation & Core Components
```
- BakeryTypeSelectionStep, DataSourceChoiceStep, ProductionProcessesStep
- WizardContext, UnifiedOnboardingWizard
- Planning documents (ONBOARDING_UNIFICATION_PLAN.md, PHASE_6_IMPLEMENTATION.md)
### Commit 2: Phases 7 & 9 (This Session)
```
d42eada - Implement Phase 7: Spanish Translations & Phase 9: Guided Tours
```
- 150+ Spanish translation keys for onboarding
- Complete tour framework (context, components, tours)
- 29 tour translation keys
- 1,266 lines of production code
**Branch:** `claude/jtbd-bakery-inventory-ui-011CUrU1eJcvQVUnNQZYh67L`
**Status:** Pushed to remote ✅
---
## 📊 Testing & Quality
### Build Status
```
✅ Build successful (23.12s)
✅ No TypeScript errors
✅ No linting errors
✅ All imports resolved
✅ Animations working
```
### Translation Coverage
- ✅ All new onboarding steps (100%)
- ✅ All tour UI elements (100%)
- ✅ All navigation elements (100%)
- ✅ All help text (100%)
### Code Quality
- ✅ TypeScript strict mode
- ✅ Proper type definitions
- ✅ React best practices
- ✅ Reusable components
- ✅ Clean separation of concerns
- ✅ Well-documented code
---
## 📈 Statistics
### Lines of Code Added
- **Phase 7 Translations:** ~200 lines (JSON)
- **Phase 9 Tour Framework:** ~1,266 lines (TypeScript + TSX)
- **Total:** ~1,466 lines of production code
### Translation Keys Added
- **Onboarding:** 150+ keys
- **Tours:** 29+ keys
- **Total:** 179+ translation keys
### Components Created
- **Tour Components:** 5 components
- **Tour Definitions:** 5 tours (25 steps total)
- **Context Providers:** 1 context
---
## 🚀 Integration Requirements
To enable the new features in production:
### 1. Tour System Integration
```tsx
// In app root (App.tsx or main.tsx)
import { TourProvider } from './contexts/TourContext';
import Tour from './components/ui/Tour';
function App() {
return (
<TourProvider>
<YourApp />
<Tour /> {/* Add this to render active tours */}
</TourProvider>
);
}
```
### 2. Add Tour Triggers
```tsx
// In navigation or help section
import TourButton from './components/ui/Tour/TourButton';
<TourButton variant="icon" /> // Help icon with dropdown
```
### 3. Add Tour Target Attributes
```tsx
// In components that tours reference
<div data-tour="dashboard-header">...</div>
<button data-tour="add-item-button">...</button>
<div data-tour="stats-cards">...</div>
```
### 4. Auto-Trigger Post-Onboarding Tour
```tsx
// In CompletionStep or after onboarding
import { useTour } from '../contexts/TourContext';
import { postOnboardingTour } from '../tours/tours';
const { startTour } = useTour();
// After onboarding completes
useEffect(() => {
startTour(postOnboardingTour);
}, []);
```
---
## 🎯 Immediate Next Steps
1. **Review Flow Reorganization Document**
- Read `/ONBOARDING_FLOW_REORGANIZATION.md`
- Provide feedback on proposed changes
- Approve approach for Phase 6.5
2. **Implement Flow Reorganization (if approved)**
- Split ReviewSuggestionsStep into 3 sub-steps
- Add categorization UI (ingredient vs product)
- Add initial stock entry UI
- Update backend to support product types
- Update backend to capture initial stock
3. **Integrate Tour System**
- Add TourProvider to app root
- Add Tour component to render active tours
- Add data-tour attributes to target elements
- Add TourButton to navigation
4. **Test End-to-End**
- Test both AI and Manual onboarding paths
- Verify initial stock is captured
- Test all 5 guided tours
- Verify Spanish translations display correctly
---
## 💡 Future Enhancements
### Phase 10: Enhanced Features (from original plan)
- Supplier directory with suggestions
- Expanded template library
- Import/export configurations
- Bulk operations
### Phase 11: Testing & Polish (from original plan)
- Full QA across all flow combinations
- Performance optimization
- Bug fixes and refinements
- User acceptance testing
### Analytics & Tracking
- Track tour completion rates
- Track tour skip rates
- Track time spent on each step
- A/B testing different tour content
- Heatmaps for tour interactions
### Additional Tours
- Suppliers tour
- Quality standards tour
- Team management tour
- Settings tour
- Analytics/Reports tour
---
## 📚 Documentation Created
1. **ONBOARDING_FLOW_REORGANIZATION.md** (This session)
- Problem statement
- JTBD recap
- Current vs proposed flow
- Detailed implementation plan
- UI mockups
- Success metrics
2. **SESSION_SUMMARY_PHASES_7_9.md** (This document)
- Complete overview of session work
- All accomplishments
- Integration requirements
- Next steps
3. **ONBOARDING_UNIFICATION_PLAN.md** (Phase 6)
- Master plan for 6-week implementation
- All phases defined
- Technical specifications
4. **PHASE_6_IMPLEMENTATION.md** (Phase 6)
- Detailed day-by-day breakdown
- Code templates
- Backend specifications
---
## ✨ Key Achievements
1. **🌐 Complete Spanish Localization**
- All new onboarding features fully translated
- Professional, natural translations
- Ready for Spanish-speaking bakery owners
2. **🎓 Comprehensive Guided Tour System**
- Complete framework from scratch
- 5 predefined tours covering key features
- Polished UI with animations
- Smart positioning and responsiveness
- Persistence across sessions
3. **🔍 Critical Flow Analysis**
- Identified fundamental issue with stock capture
- Proposed elegant solution aligned with JTBD
- Detailed implementation plan ready
4. **📦 Production-Ready Code**
- 1,466 lines of high-quality code
- Full TypeScript typing
- Comprehensive error handling
- Accessible and responsive
- Well-documented
5. **✅ Zero Technical Debt**
- Clean build
- No linting errors
- No TypeScript errors
- Proper architecture
- Future-proof design
---
## 🎉 Conclusion
Both Phase 7 (Spanish Translations) and Phase 9 (Guided Tours) are **COMPLETE** and **PRODUCTION-READY**. The tour framework is fully functional and can be integrated immediately. Spanish translations cover all new onboarding features comprehensively.
Additionally, we've identified and thoroughly documented a critical improvement to the onboarding flow (capturing initial stock) that aligns with the original JTBD analysis. Implementation of Phase 6.5 (Flow Reorganization) is recommended before going to production.
**Status:** ✅ Ready for review and integration
**Quality:** ⭐⭐⭐⭐⭐ Production-grade
**Next Action:** Review reorganization plan and integrate tour system

View File

@@ -1,115 +0,0 @@
# Supplier Product/Price Association Implementation Plan
## Critical Feature for Automatic PO Creation
### Problem
Suppliers currently have no product/price associations. Without this data:
- ❌ Automatic Purchase Order (PO) creation cannot function
- ❌ System cannot determine which supplier to order from
- ❌ System cannot calculate PO amounts
- ❌ Procurement optimization is impossible
### Backend Support (Already Exists)
`SupplierPriceList` model in `/services/suppliers/app/models/suppliers.py`:
```python
class SupplierPriceList(Base):
supplier_id: UUID
inventory_product_id: UUID # Reference to product
unit_price: Decimal # Price per unit
unit_of_measure: String # kg, g, L, ml, units
minimum_order_quantity: Integer
tier_pricing: JSONB # Volume discounts
effective_date: DateTime
expiry_date: DateTime
is_active: Boolean
```
### Frontend Implementation
#### Phase 1: Supplier Step Enhancement
**File**: `/frontend/src/components/domain/setup-wizard/steps/SuppliersSetupStep.tsx`
**New Features**:
1. **Product Association Section** (after supplier is created)
- Expandable "Manage Products" for each supplier
- Multi-select product picker from inventory
- Price entry form for each selected product
2. **UI Flow**:
```
[Supplier Card]
├─ Name, Contact, Type
├─ [Manage Products ▼] button
└─ When expanded:
├─ [+ Add Product] button → Opens modal
├─ Product List (if any exist):
│ └─ [Product Name] - [Price] [Unit] [Edit] [Delete]
└─ [Save Products] button
```
3. **Product Selector Modal**:
```
Modal: "Add Products for [Supplier Name]"
├─ Multi-select dropdown (from inventory)
├─ For each selected product:
│ ├─ Product Name (read-only)
│ ├─ Unit Price (€) input *required
│ ├─ Unit of Measure select *required
│ └─ Min Order Qty input (optional)
└─ [Cancel] [Save Prices]
```
#### Phase 2: Backend Integration
**API Endpoints** (already exist):
- `POST /suppliers/{supplier_id}/price-lists` - Create price list item
- `GET /suppliers/{supplier_id}/price-lists` - Get supplier's price list
- `PUT /suppliers/{supplier_id}/price-lists/{price_list_id}` - Update price
- `DELETE /suppliers/{supplier_id}/price-lists/{price_list_id}` - Delete price
**Frontend Services** needed:
- `useSupplierPriceLists(supplierId)` - Fetch price lists
- `useCreateSupplierPriceList()` - Create price list items
- `useUpdateSupplierPriceList()` - Update prices
- `useDeleteSupplierPriceList()` - Delete price list items
#### Phase 3: Data Flow
```
User creates supplier
Supplier card shows "Manage Products" button
Click → Expand section showing current products (if any)
Click "Add Product" → Modal opens
Select products from inventory + Enter prices
Save → API call to create SupplierPriceList entries
Modal closes, product list updates
User can proceed to next step
```
### Implementation Checklist
- [ ] Create useSupplierPriceLists hook
- [ ] Create useCreateSupplierPriceList hook
- [ ] Create useUpdateSupplierPriceList hook
- [ ] Create useDeleteSupplierPriceList hook
- [ ] Add product management UI to SuppliersSetupStep
- [ ] Create product selector modal component
- [ ] Add price entry form
- [ ] Integrate with backend API
- [ ] Add validation (price > 0, unit required)
- [ ] Test create/update/delete flow
- [ ] Test navigation (can proceed after products added)
### Benefits After Implementation
✅ Automatic PO creation will work
✅ System knows which supplier supplies what
✅ System knows current prices
✅ Can calculate PO totals automatically
✅ Can optimize procurement based on prices
✅ Can track price changes over time
✅ Foundation for supplier performance analysis

View File

@@ -1,461 +0,0 @@
# JTBD Analysis: Bakery Inventory Setup After Onboarding
**Date**: 2025-11-06
**Context**: Post-onboarding manual data entry for "Mi Panadería" section
**Target User**: Bakery owner or employee with limited time and basic computer skills
---
## 🎯 PRIMARY FUNCTIONAL JOB
### Main Job Statement
**"When I've just registered my bakery system, I want to set up all my foundational data correctly and efficiently, so that the system can start helping me manage my operations and provide value immediately."**
### Job Story Format
- **When**: I complete the initial registration and onboarding wizard
- **I want to**: Add all my bakery's operational data (inventory, suppliers, recipes, quality standards)
- **So I can**: Start using the system to manage daily operations, track inventory, and get AI-powered insights
- **Without**: Getting overwhelmed, making errors, or spending hours figuring out what to do next
### Success Criteria (from user's perspective)
- ✅ I know exactly what data I need to add and in what order
- ✅ I understand why each piece of data matters to my bakery
- ✅ I can complete the setup in one or two focused sessions
- ✅ The system validates my data and prevents mistakes
- ✅ I can see my progress and come back later if needed
- ✅ The system works correctly once I'm done (no missing critical data)
---
## 💭 RELATED EMOTIONAL & SOCIAL JOBS
### Emotional Jobs (How the user wants to feel)
1. **"I want to feel confident"**
- That I'm doing this right the first time
- That I won't break anything or lose data
- That the system will guide me if I make a mistake
2. **"I want to feel in control"**
- Of my time (can save and come back later)
- Of the process (can skip optional items)
- Of my data (can edit or undo if needed)
3. **"I want to feel competent"**
- Not stupid or confused by technical jargon
- Capable of managing my own business systems
- Proud when I complete the setup
4. **"I want to feel efficient"**
- Not wasting time figuring out what comes next
- Making progress, not going in circles
- Getting value from the system quickly
### Social Jobs (How the user wants to be perceived)
1. **"I want to be seen as a modern bakery owner"**
- Who adopts technology to improve operations
- Who keeps accurate records and data
2. **"I want my employees to see me as organized"**
- With clear standards and processes
- Who provides them with good tools
3. **"I don't want to appear incompetent"**
- To my staff if they see me struggling
- To myself (internal self-image)
---
## 🔄 SUB-JOBS & TASK BREAKDOWN
### Phase 1: Understanding What's Needed
**Job**: *"Help me understand what I need to set up and why"*
#### Sub-jobs:
1. **Learn what the system needs from me**
- What categories of data exist (inventory, suppliers, recipes, etc.)
- Why each category matters to my operations
- What's required vs. optional
2. **Assess what information I have available**
- Do I have supplier contact information handy?
- Do I have my recipe measurements documented?
- Do I know my current inventory counts?
3. **Plan my data entry approach**
- Should I do everything now or come back later?
- What order makes sense?
- Who else might need to help (e.g., chef for recipes)?
### Phase 2: Setting Up Core Dependencies
**Job**: *"Set up foundational data that other things depend on"*
#### Sub-jobs:
1. **Add my suppliers** (dependency for inventory)
- Who do I buy from?
- How do I contact them?
- What payment terms do we have?
2. **Add inventory items/ingredients** (dependency for recipes)
- What raw materials do I use?
- How do I measure them (kg, units, etc.)?
- What do they cost?
- When should I reorder?
3. **Configure quality standards** (dependency for production monitoring)
- What quality checks do I perform?
- At what stages of production?
- What are acceptable ranges?
### Phase 3: Setting Up Operational Data
**Job**: *"Add the data that represents how I actually work"*
#### Sub-jobs:
1. **Create my recipes**
- What do I bake?
- What ingredients go into each product?
- How much of each ingredient?
- What's the process?
2. **Set up equipment/machinery**
- What equipment do I have?
- When does it need maintenance?
3. **Add my team members**
- Who works here?
- What are their roles?
- How do I contact them?
### Phase 4: Verifying & Starting Operations
**Job**: *"Make sure everything is correct before I rely on this system"*
#### Sub-jobs:
1. **Review what I've entered**
- Are all recipes complete?
- Did I miss any key suppliers?
- Are inventory levels accurate?
2. **Test the system with real work**
- Can I create a production order?
- Can I record a sale?
- Does the inventory update correctly?
3. **Get confirmation I'm ready to go**
- Is there anything critical missing?
- What features are now available to me?
---
## ⚖️ FORCES OF PROGRESS
### Push Forces (Pushing user away from current state - not using the system)
1. **Manual tracking is unreliable**
- Paper notes get lost
- Excel sheets become outdated
- Memory fails ("Did I order flour last week?")
2. **Waste and inefficiency**
- Overordering leads to spoilage
- Underordering leads to stockouts
- No visibility into costs
3. **Growth constraints**
- Can't scale without systems
- Hiring requires documentation
- Investors/partners expect professionalism
4. **Competitive pressure**
- Other bakeries are modernizing
- Customers expect consistency
### Pull Forces (Pulling user toward the new system)
1. **Automation promises**
- AI-powered demand forecasting
- Automatic reorder suggestions
- Real-time inventory tracking
2. **Time savings**
- Less time counting inventory
- Less time making production decisions
- More time baking and serving customers
3. **Better decision making**
- Data-driven insights
- Cost analysis per recipe
- Supplier performance tracking
4. **Peace of mind**
- Always know what's in stock
- Never run out of key ingredients
- Quality standards documented
### Anxiety Forces (Holding user back - against new system)
1. **Fear of complexity**
- *"This looks complicated"*
- *"I'm not good with computers"*
- *"What if I enter something wrong?"*
2. **Time pressure**
- *"I don't have hours to sit and enter data"*
- *"I need to be in the kitchen, not at a computer"*
- *"What if I start and don't finish? Will it work partially?"*
3. **Uncertainty about requirements**
- *"Do I need ALL my recipes in here?"*
- *"What if I don't know the exact cost of an ingredient?"*
- *"Can I skip things and add them later?"*
4. **Fear of mistakes**
- *"What if I delete something important?"*
- *"What if incorrect data messes up my inventory?"*
- *"I don't want to start over if I get it wrong"*
5. **Investment fear**
- *"Will I actually use all these features?"*
- *"Is this worth the time to set up?"*
- *"What if the system doesn't work for my bakery?"*
### Habit Forces (Keeping user in old ways)
1. **Existing workflows are familiar**
- "I've always managed inventory by walking around and looking"
- "I know my recipes by heart, don't need them written down"
- "I just call my supplier when I need something"
2. **Low-tech comfort**
- "Paper checklists have always worked"
- "My notebook system is simpler"
- "I prefer talking to people, not typing into a computer"
3. **Team habits**
- "My staff is used to the old way"
- "Training everyone on new software is a hassle"
---
## 🚧 BARRIERS & PAIN POINTS (Current System)
### Discovery Barriers
**Problem**: *Users don't know what exists or where to start*
- ❌ No post-onboarding guidance (wizard ends, user is on their own)
- ❌ No "Getting Started" checklist or dashboard
- ❌ No indication of what's required vs. optional
- ❌ No explanation of dependencies ("need ingredients before recipes")
**Evidence from code**:
- Onboarding wizard ends at CompletionStep (line 51, OnboardingWizard.tsx)
- No handoff to guided data entry
- User lands on dashboard with empty state and must explore sidebar
### Cognitive Load Barriers
**Problem**: *Too much to remember and figure out simultaneously*
- ❌ Must remember to add ingredients before recipes (dependency not enforced or explained)
- ❌ Must learn different modal patterns for different entities
- ❌ Must understand bakery terminology + system terminology
- ❌ No contextual help or tooltips in forms
**Evidence from code**:
- CreateRecipeModal allows selecting ingredients (line 218) but doesn't prompt to add ingredients first if none exist
- Inconsistent field patterns across modals
- Only placeholder text for guidance
### Navigation Barriers
**Problem**: *Users get lost in the sidebar menu structure*
- ❌ 10 menu items under "Mi Panadería" - overwhelming
- ❌ No indication of completion status (which sections are empty/done)
- ❌ No suggested order (user must guess)
- ❌ Must repeatedly open sidebar, navigate to section, click add button
**Evidence from code**:
```
Mi Panadería (10 subsections):
├── Ajustes, Proveedores, Inventario, Recetas, Pedidos,
└── Maquinaria, Quality Templates, Team, AI Models, Sustainability
```
All presented equally, no priority or grouping by setup phase
### Validation & Error Barriers
**Problem**: *Users make mistakes but only discover them later*
- ❌ No pre-validation (only after submit)
- ❌ No cross-field validation (e.g., reorder_point should be > low_stock_threshold)
- ❌ No prevention of incomplete data (can save recipe with no ingredients in some flows)
**Evidence from code**:
- AddModal validation only on submit (handleSave, line 159-171)
- No real-time field validation shown
- Errors cleared on change but no proactive checking
### Data Entry Efficiency Barriers
**Problem**: *Repetitive, tedious work with no shortcuts*
- ❌ No bulk import option for multiple ingredients
- ❌ No templates for common items ("French bread" recipe template)
- ❌ No copy/duplicate for similar recipes
- ❌ Must re-enter supplier info if same supplier provides multiple ingredients
### Progress & Motivation Barriers
**Problem**: *Users can't see progress and lose motivation*
- ❌ No completion indicator ("3 of 5 critical sections complete")
- ❌ No celebration of milestones
- ❌ No "minimum viable setup" guidance ("Here's the bare minimum to get started")
- ❌ Can't easily resume if interrupted
### Technical Barriers
**Problem**: *System assumes too much technical proficiency*
- ❌ Form fields use technical language (SKU, barcode, "reorder point")
- ❌ No plain-language explanations
- ❌ Dropdown options assume knowledge (e.g., MeasurementUnit enum)
- ❌ No examples or common values suggested
---
## 🎯 UNMET NEEDS & OPPORTUNITIES
### High Priority Unmet Needs
1. **"Show me the path forward"**
- Need: Clear, step-by-step guidance on what to set up first
- Opportunity: Post-onboarding wizard that continues into data entry
- Success metric: 90% of users complete critical data setup
2. **"Tell me if I'm doing it right"**
- Need: Real-time validation and helpful error messages
- Opportunity: Progressive validation with contextual tips
- Success metric: 50% reduction in data entry errors
3. **"Don't make me think"**
- Need: Smart defaults, suggested values, autofill where possible
- Opportunity: Templates, common recipes, supplier databases
- Success metric: 40% faster data entry
4. **"Let me do this in chunks"**
- Need: Save progress, resume later, skip optional sections
- Opportunity: Progress tracking with clear save states
- Success metric: 80% completion rate even with interruptions
5. **"Help me understand dependencies"**
- Need: Know what I need before I can do something else
- Opportunity: Guided flows that handle dependencies automatically
- Success metric: Zero "missing dependency" errors
### Medium Priority Unmet Needs
6. **"Make it feel less overwhelming"**
- Need: Break down big tasks into small wins
- Opportunity: Progressive disclosure, celebrate small completions
- Success metric: User sentiment scores improve
7. **"Speak my language"**
- Need: Plain language, bakery terminology, not software jargon
- Opportunity: Context-aware help, glossary, examples
- Success metric: Support tickets for "how do I" decrease
8. **"Show me what's possible"**
- Need: Understand what value I'll get from each section
- Opportunity: Preview of features unlocked by completing setup
- Success metric: Increased feature adoption post-setup
### Lower Priority (Nice to Have)
9. **"Let me work my way"**
- Need: Flexibility in approach (top-down vs. bottom-up)
- Opportunity: Multiple entry paths while maintaining guidance
- Success metric: User control satisfaction
10. **"Import my existing data"**
- Need: Bulk import from spreadsheets or previous systems
- Opportunity: CSV/Excel import with mapping wizard
- Success metric: Time to value reduced by 60%
---
## ✅ JTBD VALIDATION CHECKLIST
### Are the jobs goal-oriented (not solution-oriented)?
**Yes**
- Main job: "set up all my foundational data correctly and efficiently"
- Not: "use a wizard" or "click through modals"
- Focused on desired outcome, not implementation
### Are sub-jobs specific steps toward the main job?
**Yes**
- Phase 1: Understanding → Phase 2: Dependencies → Phase 3: Operations → Phase 4: Verification
- Each sub-job is a necessary step in the progression
- Clear hierarchy and flow
### Are emotional/social jobs captured?
**Yes**
- Emotional: confidence, control, competence, efficiency
- Social: modern bakery owner, organized, not appearing incompetent
- These drive behavior as much as functional needs
### Are user struggles and unmet needs listed?
**Yes**
- Barriers section: 6 major categories with specific pain points
- Unmet needs: 10 prioritized opportunities
- Evidence-based (code analysis supports each claim)
---
## 🎬 RECOMMENDED SOLUTION APPROACH
Based on this JTBD analysis, here's a high-level recommendation (not detailed implementation):
### Core Concept: "Guided Bakery Setup Journey"
Transform the post-onboarding experience from **scattered modals** to a **continuous, guided journey** that:
1. **Starts immediately after onboarding** (Step 5 of wizard)
2. **Groups related tasks** (Dependencies → Operations → Quality)
3. **Shows clear progress** (visual indicator, percentage, milestones)
4. **Allows flexibility** (save/resume, skip optional, reorder)
5. **Provides context** (why this matters, what's next, examples)
6. **Validates progressively** (before moving on, not after errors)
7. **Celebrates completion** (milestones, "you're ready to bake!")
### Phased Implementation
- **Phase 1**: Add progress tracking and "Setup Checklist" dashboard
- **Phase 2**: Convert critical paths (Suppliers → Inventory → Recipes) to guided wizards
- **Phase 3**: Add templates, smart defaults, bulk import
- **Phase 4**: Polish with animations, contextual help, advanced features
---
## 📊 SUCCESS METRICS
### Leading Indicators (During Setup)
- **Setup completion rate**: % of users who finish critical data entry
- **Time to first value**: Days from registration to first production order created
- **Data quality score**: % of records with complete, valid data
- **Drop-off points**: Where users abandon the setup process
### Lagging Indicators (Post-Setup)
- **Feature adoption**: % of users actively using inventory, recipes, forecasting
- **System reliance**: Frequency of use (daily, weekly, monthly)
- **User satisfaction**: NPS, support tickets, sentiment analysis
- **Business outcomes**: Waste reduction, time saved, cost visibility
---
## 🔄 NEXT STEPS
1. **Validate with users**: Interview 5-8 bakery owners to confirm jobs, forces, and barriers
2. **Prioritize sub-jobs**: Which jobs are most critical? Which provide quick wins?
3. **Design prototype**: Sketch out the guided journey (low-fidelity wireframes)
4. **Test with users**: Usability testing to refine approach
5. **Implement incrementally**: Start with highest-value, lowest-effort improvements
---
**Document Owner**: Product & UX Team
**Review Date**: To be scheduled after user validation
**Status**: Draft for review

View File

@@ -1,564 +0,0 @@
# Proposal: Add Product Lots with Expiration Dates to Inventory Onboarding
**Date**: 2025-11-06
**Status**: Proposal for Review
**Context**: Enhance InventorySetupStep in onboarding to support lot/batch management with expiration tracking
---
## 📋 Executive Summary
**Problem**: Current inventory onboarding only creates ingredient definitions (master data) without actual stock quantities or expiration tracking. This creates a critical gap for bakeries managing perishable ingredients.
**Solution**: Enhance the InventorySetupStep to allow users to add one or more stock lots per ingredient, including quantities and expiration dates, using a simplified version of the existing AddStockModal pattern.
**Impact**:
- ✅ Immediate inventory visibility from day one
- ✅ FIFO (First-In-First-Out) management ready
- ✅ Expiration alerts functional immediately
- ✅ Waste prevention starts on day one
- ✅ Better data quality for AI forecasting
---
## 🔍 Current State Analysis
### What Exists Today
1. **InventorySetupStep** (Onboarding):
- Creates ingredient definitions (master data)
- No stock quantities
- No expiration dates
- Users define WHAT they have, not HOW MUCH
2. **InitialStockEntryStep** (AI-Assisted Path Only):
- Simple quantity entry
- No expiration dates
- No lot/batch numbers
- No multi-lot support
3. **AddStockModal** (Post-Onboarding):
- Comprehensive lot management
- Expiration dates, batch numbers, storage requirements
- Used after onboarding is complete
### The Gap
**Users complete onboarding with:**
- ✅ Ingredients defined (master data)
- ❌ Zero actual stock in system
- ❌ No expiration tracking
- ❌ Cannot use FIFO/waste alerts
- ❌ Must manually add stock post-onboarding
**Impact of Gap:**
- System shows "0 stock" for everything
- No expiration alerts for weeks/months
- Forecasting starts with no data
- Poor first impression ("Why is everything empty?")
---
## 🎯 JTBD Alignment
### Primary Jobs Addressed
From JTBD Analysis (docs/jtbd-analysis-inventory-setup.md):
1. **"Help me understand dependencies"** (Line 347-349)
- Need: Know what I need before I can do something else
- **Solution**: Add stock immediately after defining ingredients
2. **"Tell me if I'm doing it right"** (Line 331-334)
- Need: Real-time validation and helpful error messages
- **Solution**: Validate expiration dates, warn about near-expiry stock
3. **"Don't make me think"** (Line 336-339)
- Need: Smart defaults, suggested values
- **Solution**: Auto-suggest expiration based on ingredient type
4. **"Set up foundational data correctly"** (Line 100-104)
- Sub-job: Add inventory items - *"What do they cost? When should I reorder?"*
- **Solution**: Add actual quantities with dates during setup
### Forces of Progress
**Push Forces** (Lines 153-172):
- **Waste and inefficiency**: Overordering leads to spoilage ✅ *Directly addressed*
- **Manual tracking unreliable**: No visibility into stock levels ✅ *Directly addressed*
**Pull Forces** (Lines 173-194):
- **Real-time inventory tracking**: Start from day one ✅ *Enabled*
- **Peace of mind**: Always know what's in stock ✅ *Enabled*
**Anxiety Forces to Mitigate** (Lines 195-220):
- **Fear of complexity**: Keep it simple, optional ✅ *Simplified form*
- **Time pressure**: Make it quick and skipable ✅ *Optional step*
- **Uncertainty about requirements**: Clear guidance ✅ *Contextual help*
---
## 💡 Proposed Solution
### Approach: "Quick Stock Entry" After Each Ingredient
**Core Concept**: After adding an ingredient in InventorySetupStep, immediately prompt to add initial stock (optional but encouraged).
### User Flow
```
1. User adds ingredient (e.g., "All-Purpose Flour")
└─> Ingredient created ✓
2. System shows inline prompt:
"Add initial stock for Flour?"
[Add Stock] [Skip for Now]
3. If user clicks [Add Stock]:
└─> Simplified stock entry form appears inline
└─> User enters:
- Quantity (required)
- Expiration date (optional but recommended)
- Supplier (optional, dropdown from existing)
- Batch/Lot number (optional)
└─> [Save Stock] [Add Another Lot] [Cancel]
4. Stock saved ✓
└─> Shows summary: "20 kg expires on 2025-12-15"
└─> Option to [Add Another Lot] for same ingredient
5. User continues to next ingredient or completes step
```
### Alternative: Dedicated "Stock Entry" Sub-Step
**Two-phase approach within InventorySetupStep:**
**Phase 1**: Add Ingredients (current behavior)
**Phase 2**: Add Stock Lots (new)
```
┌─────────────────────────────────────────┐
│ Inventory Setup │
│ │
│ [✓ Add Ingredients] [→ Add Stock] │
│ │
│ You've added 8 ingredients │
│ │
│ Would you like to add initial stock │
│ quantities and expiration dates? │
│ │
│ ○ Yes, add stock now (recommended) │
│ Track quantities and prevent waste │
│ │
│ ○ Skip for now │
│ Add stock later from inventory page │
│ │
│ [Continue →] │
└─────────────────────────────────────────┘
```
If user selects "Yes":
- Shows list of ingredients
- Each ingredient has [+ Add Stock] button
- Inline form appears per ingredient
- Can add multiple lots per ingredient
---
## 🎨 UI/UX Design Recommendations
### Option 1: Inline Stock Entry (Recommended)
**Advantages:**
- ✅ Contextual - add stock right after defining ingredient
- ✅ Minimal cognitive load
- ✅ Clear cause-and-effect relationship
- ✅ Natural flow
**Design:**
```
┌─────────────────────────────────────────────────────────┐
│ All-Purpose Flour [Edit] │
│ Category: Flour | Unit: kg | Cost: $1.50/kg │
├─────────────────────────────────────────────────────────┤
│ │
│ 📦 Add Initial Stock (Optional) │
│ │
│ Quantity (kg) * Expiration Date │
│ [ 25.0 ] [ 2025-12-15 ] 📅 │
│ │
│ Supplier Batch/Lot Number │
│ [Mill Brothers ▼] [ LOT-2024-11 ] │
│ │
│ [✓ Save Stock] [+ Add Another Lot] [Skip] │
│ │
Expiration tracking helps prevent waste and enables │
│ First-In-First-Out (FIFO) inventory management │
└─────────────────────────────────────────────────────────┘
```
### Option 2: Separate Stock Entry Screen
**Advantages:**
- ✅ Clearer separation of concerns
- ✅ Can see all ingredients at once
- ✅ Bulk actions possible
- ✅ Better for users with many items
**Design:**
```
┌─────────────────────────────────────────────────────────┐
│ Step 2/2: Add Initial Stock Quantities │
│ │
│ Add stock for the ingredients you just created. │
│ This is optional but recommended for accurate tracking. │
│ │
│ Progress: 3 of 8 ingredients have stock │
│ [████░░░░░░] 38% │
│ │
├─────────────────────────────────────────────────────────┤
│ All-Purpose Flour [Add Stock] │
│ Quantity: 25 kg | Expires: 2025-12-15 [✓ Added] │
│ │
│ Bread Flour [Add Stock] │
│ No stock added yet [+ Add] │
│ │
│ Active Dry Yeast [Add Stock] │
│ Quantity: 2 kg | Expires: 2025-11-30 [✓ Added] │
│ │
│ ... (5 more ingredients) │
│ │
│ │
│ [Skip All] [Continue →] │
└─────────────────────────────────────────────────────────┘
```
### Option 3: Simplified "Quick Add" Modal (Hybrid)
**Advantages:**
- ✅ Focused attention on stock entry
- ✅ Can reuse existing AddStockModal design
- ✅ Familiar pattern for users
- ✅ Easy to implement
**Design:**
```
┌─────────────────────────────────────────┐
│ Add Stock: All-Purpose Flour │
├─────────────────────────────────────────┤
│ │
│ Current Quantity * │
│ [ 25.0 ] kg │
│ │
│ Expiration Date │
│ [ 2025-12-15 ] 📅 │
│ ⚠️ This ingredient expires in 40 days │
│ │
│ Supplier (Optional) │
│ [ Mill Brothers ▼ ] │
│ │
│ Batch/Lot Number (Optional) │
│ [ LOT-2024-11 ] │
│ │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ │
│ [Save & Add Another Lot] │
│ [Save & Close] │
│ [Cancel] │
└─────────────────────────────────────────┘
```
---
## 🏗️ Implementation Recommendations
### Recommended Approach: **Option 1 - Inline Stock Entry**
**Why:**
1. Most aligned with JTBD principle "Don't make me think"
2. Natural flow - no context switching
3. Progressive disclosure - only shows when relevant
4. Maintains momentum in onboarding
5. Optional but visible - encourages action without forcing it
### Form Fields (Simplified)
**Required:**
- `current_quantity` (number)
**Recommended (show by default):**
- `expiration_date` (date picker)
- `supplier_id` (select from existing suppliers)
**Optional (collapsed/advanced):**
- `batch_number` (text)
- `lot_number` (text)
- `received_date` (date, default: today)
- `storage_location` (text/select)
- `unit_cost` (number, default from ingredient)
**Not included (use ingredient defaults):**
- Storage requirements (refrigeration, etc.) - use from ingredient
- Production stage - default to RAW_INGREDIENT
- Quality status - default to "good"
### Smart Defaults & Auto-Suggestions
1. **Expiration Date Suggestions**:
```
If ingredient.is_perishable && ingredient.shelf_life_days:
Suggest: today + shelf_life_days
Show: "Typical shelf life: 30 days → Expires: 2025-12-06"
```
2. **Supplier Pre-Selection**:
```
If only 1 supplier exists:
Auto-select it
If ingredient previously purchased from supplier:
Pre-select that supplier
```
3. **Batch Number Generation**:
```
Offer to auto-generate: "BATCH-[DATE]-[INCREMENT]"
Example: "BATCH-20251106-001"
```
### Validation Rules
```typescript
// Frontend validation
if (currentQuantity <= 0) {
error("Quantity must be greater than zero")
}
if (expirationDate && expirationDate < today) {
warning("This date is in the past. Is this correct?")
}
if (expirationDate && expirationDate < today + 3 days) {
alert("⚠️ This ingredient expires very soon!")
}
if (expirationDate && expirationDate > today + 365 days) {
warning("Unusual expiration date (> 1 year). Please verify.")
}
// Suggest storage requirements
if (ingredient.category === 'dairy' && !storage_location) {
suggest("Consider adding storage location: Refrigerator")
}
```
### User Guidance
**Contextual Help Text:**
- "Expiration tracking helps prevent waste and enables First-In-First-Out (FIFO) management"
- "Add multiple lots if you have ingredients with different expiration dates"
- "You can always add more stock later from the Inventory page"
**Empty State:**
- "No stock added yet. The system will show 0 available until you add stock."
**Success Feedback:**
- "✓ Stock added: 25 kg expires on 2025-12-15"
- "You can add another lot if you have more with a different expiration date"
---
## 📊 Success Metrics
### Leading Indicators
1. **Stock Entry Rate**: % of ingredients with at least one stock lot added during onboarding
- Target: 60%+ (users add stock for most ingredients)
2. **Expiration Date Completeness**: % of stock lots with expiration dates
- Target: 80%+ for perishable items, 40%+ overall
3. **Multi-Lot Usage**: % of ingredients with 2+ stock lots
- Target: 20%+ (shows understanding of lot concept)
4. **Time to Complete**: Average time spent on stock entry
- Target: < 2 minutes per ingredient
5. **Skip Rate**: % of users who skip stock entry
- Target: < 40% (most users add at least some stock)
### Lagging Indicators
1. **Expiration Alert Effectiveness**: % of expired items caught before use
- Target: 90%+ (shows system is working)
2. **Waste Reduction**: Compare waste rates pre/post implementation
- Target: 15% reduction in expired ingredient waste
3. **System Usage**: % of users actively using inventory tracking
- Target: 85%+ weekly active users
4. **User Satisfaction**: NPS score for inventory setup
- Target: +40 or higher
### Data Quality Metrics
1. **Stock Accuracy**: % of stock records with complete data
- Measure: quantity, expiration date, supplier filled out
2. **FIFO Compliance**: % of stock consumption following FIFO
- Measure via stock movement logs
---
## 🚀 Implementation Phases
### Phase 1: MVP - Basic Lot Entry (Week 1-2)
**Scope:**
- Inline stock entry form after ingredient creation
- Fields: quantity, expiration date, supplier
- Single lot per ingredient
- Skip option clearly visible
**Success Criteria:**
- Users can add at least one stock lot per ingredient
- Expiration dates are captured
- Can skip if desired
### Phase 2: Enhanced - Multi-Lot Support (Week 3)
**Scope:**
- "Add Another Lot" button
- Support multiple lots per ingredient with different expiration dates
- Visual list of lots added
- Edit/delete lots before completing step
**Success Criteria:**
- Users can add 2+ lots for same ingredient
- Clear visual feedback of lots added
- Easy to manage multiple lots
### Phase 3: Smart Features (Week 4-5)
**Scope:**
- Auto-suggest expiration dates based on shelf life
- Batch number auto-generation
- Supplier pre-selection logic
- Advanced validation warnings
- Contextual help tooltips
**Success Criteria:**
- 50%+ of users use at least one smart feature
- Reduced data entry errors
- Faster completion times
### Phase 4: Bulk & Import (Future)
**Scope:**
- Bulk stock entry (CSV import)
- Copy from previous orders
- Templates for common stock patterns
**Success Criteria:**
- Power users can import dozens of lots quickly
- Support for large-scale bakeries
---
## 🎯 Recommended Next Steps
1. **Validate with Users** (2-3 days)
- Interview 3-5 bakery owners
- Show mockups of Option 1, 2, 3
- Ask: "Which feels most natural? What's confusing?"
2. **Create Detailed Designs** (1 week)
- High-fidelity mockups of chosen option
- Mobile responsive designs
- Interaction specifications
- Error state designs
3. **Technical Spike** (2-3 days)
- Verify API support for batch stock creation
- Test performance with multiple lots
- Identify any backend changes needed
4. **Implement Phase 1** (2 weeks)
- Build MVP inline stock entry
- Unit tests for validation
- Integration with existing inventory hooks
5. **User Testing** (3-5 days)
- Usability testing with 5-8 users
- Measure completion time, skip rate
- Collect qualitative feedback
6. **Iterate & Launch Phase 2** (1-2 weeks)
- Address feedback from testing
- Add multi-lot support
- Launch to production
---
## 🔒 Risk Mitigation
### Risk 1: Users Feel Overwhelmed
**Mitigation:**
- Make stock entry optional but recommended
- Progressive disclosure - show advanced fields only if needed
- Clear "Skip" option with explanation
- Celebrate small wins ("3 of 8 done!")
### Risk 2: Takes Too Long
**Mitigation:**
- Simplify form to essential fields only
- Smart defaults reduce typing
- Allow saving and resuming later
- Bulk actions in Phase 4
### Risk 3: Poor Data Quality
**Mitigation:**
- Real-time validation
- Contextual warnings
- Educational tooltips
- Show impact: "Expiration tracking helps prevent $X waste/month"
### Risk 4: Technical Complexity
**Mitigation:**
- Reuse existing AddStockModal logic
- Build incrementally (MVP first)
- Leverage existing API endpoints
- Thorough testing before launch
---
## 📚 References
- JTBD Analysis: `docs/jtbd-analysis-inventory-setup.md`
- Inventory API Types: `frontend/src/api/types/inventory.ts` (lines 179-308)
- Existing Components:
- `AddStockModal.tsx` - Full stock entry modal
- `InitialStockEntryStep.tsx` - Simple quantity entry
- `InventorySetupStep.tsx` - Current ingredient creation
---
## ✅ Conclusion
Adding lot/batch management with expiration tracking to the inventory onboarding step directly addresses critical JTBD needs, reduces waste, and enables immediate system value. The recommended inline approach balances simplicity with power, making it easy for users while capturing essential data for bakery operations.
**Recommendation**: Proceed with **Option 1 (Inline Stock Entry)** → Phase 1 MVP → User Validation → Iterate based on feedback.
---
**Document Owner**: Product & Engineering Team
**Status**: Awaiting Approval
**Next Review**: After user validation interviews