# 🎯 Complete Workflow Example: Adding User Dashboard to Recipe App

*A real-world walkthrough from idea to implementation with automated git commits*

---

## 📋 Scenario

You have an existing recipe sharing app and users have been asking for a personal dashboard. Let's walk through the complete process of understanding your app, defining the feature, and implementing it step-by-step with clean git history.

---

## 🔍 Step 1: Understand Your Current App

### Simple Starting Prompt

Just ask your AI agent:

```
Please tell me about my app - analyze the codebase and give me an overview of the tech stack, database structure, and current features.
```

### What Your AI Will Return

```markdown
## App Overview

**Tech Stack:**
- Framework: Next.js 14.0.4 with App Router
- Database: Supabase (PostgreSQL)
- Styling: Tailwind CSS 3.3.0
- Language: TypeScript 5.3.3
- Authentication: Supabase Auth

**Database Tables:**
- `user_profiles` - stores username, bio, avatar
- `recipes` - main recipe data with ingredients, instructions
- `favorites` - tracks which users favorited which recipes
- `recipe_views` - analytics for recipe views

**Current Features:**
- User authentication (login/signup)
- Browse all recipes at /recipes
- View individual recipes at /recipes/[id]
- User profiles at /profile/[username]
- Users can favorite recipes
- Basic view tracking

**Project Structure:**
- Modern Next.js 14 app directory structure
- Server components for data fetching
- Supabase RLS for security
- Modular component organization
```

---

## 💭 Step 2: Discuss the New Feature

### Your Next Message

```
Users have been asking for a personal dashboard. Based on the current app structure you just showed me, let's discuss what this dashboard could include. What would make sense given our existing data and tables?
```

### AI Discussion Response

```markdown
Based on your current app structure, here are dashboard features that would work well:

**Possible Dashboard Sections:**

1. **Recipe Statistics** (using existing data)
   - Total recipes published (count from `recipes` table)
   - Total views across all recipes (sum from `recipe_views`)
   - Total favorites received (count from `favorites`)
   - Most popular recipe

2. **Recipe Management** (leveraging current tables)
   - List of user's own recipes
   - Quick edit/delete actions
   - View counts per recipe
   - See who favorited each recipe

3. **Favorites Collection** (using `favorites` table)
   - Recipes the user has favorited
   - Quick navigation to favorited recipes
   - Organize by date favorited

4. **Profile Quick Edit** (using `user_profiles`)
   - Update bio
   - Change avatar
   - Edit username

Since you already have all the necessary tables and tracking in place, we wouldn't need major database changes - mostly views and functions to aggregate the data efficiently.

What aspects are most important to your users?
```

---

## 📝 Step 3: Define Requirements Together

### Your Response

```
Let's focus on statistics overview, recipe management, and the favorites collection. I don't need profile editing right now. Can you help me define the specific requirements for these three sections?
```

### AI Requirements Definition

```markdown
## Dashboard Requirements

### 1. Statistics Overview
**Display Requirements:**
- Total recipes published by the user
- Total views across all their recipes
- Total favorites received on their recipes
- Average views per recipe

**Technical Needs:**
- Create a database view to aggregate these stats efficiently
- Real-time updates when data changes

### 2. Recipe Management
**Display Requirements:**
- Table/list of user's recipes showing:
  - Recipe title
  - Created date
  - View count
  - Favorite count
  - Quick actions (edit, delete, view)
- Sort by: date, views, favorites
- Search within user's recipes

**Technical Needs:**
- Efficient query with counts
- Soft delete consideration
- Link to edit pages

### 3. Favorites Collection  
**Display Requirements:**
- Grid of favorited recipes showing:
  - Recipe card with image
  - Recipe title and author
  - When it was favorited
- Remove from favorites action
- Link to full recipe

**Technical Needs:**
- Join favorites with recipes and user_profiles
- Order by favorited date
- Handle unfavoriting

### General Requirements
- Dashboard must be authenticated route
- Mobile responsive design
- Loading states for data fetching
- Empty states for new users

Does this capture what you're looking for?
```

---

## 🛠️ Step 4: Create Development Plan

### Your Request

```
Perfect! Now create a development plan for these requirements. Remember to combine all database changes into a single migration to keep things clean. Structure the plan as: Database setup → Page creation → Components → Integration
```

### AI Development Plan

```markdown
## Dashboard Development Plan

### Phase 1: Database Setup (Single Migration)
**Task:** Create comprehensive migration with all database changes
- User stats view for aggregating statistics  
- Optimized query function for user's recipes with counts
- Function to get favorited recipes with author info
- Add necessary indexes for performance
- Set up RLS policies for all new objects

### Phase 2: Dashboard Page Structure
**Tasks:**
1. Create dashboard page at /dashboard/page.tsx
2. Set up authentication middleware for protection
3. Create dashboard layout with sections

### Phase 3: Component Development
**Tasks:**
1. StatsOverview component
   - Display cards for each statistic
   - Use the user_stats view
   - Add loading skeletons

2. RecipeManagementTable component
   - Sortable table with recipe data
   - Action buttons for each recipe
   - Search/filter functionality

3. FavoritesGrid component
   - Recipe cards in responsive grid
   - Unfavorite functionality
   - Link to full recipes

### Phase 4: Integration & Polish
**Tasks:**
1. Create dashboard service layer
   - Functions to fetch all dashboard data
   - Error handling
   - Data caching strategy

2. Wire up all components
   - Connect to real data
   - Add loading states
   - Handle errors gracefully
   - Test empty states
```

---

## 📋 Step 5: Convert to JSON Structure

### Your Request

```
Now please convert this plan into the Mirror Magi JSON structure. Use these task types:
- supabase_migration: for database changes
- component_creation: for React components  
- configuration: for routing/middleware
- api_integration: for service layers
- feature_development: for wiring everything together

Include all the specific SQL, file paths, and dependencies.
```

### AI JSON Response

```json
{
  "id": "plan_dashboard_1703095432",
  "goal": "Add user dashboard with statistics, recipe management, and favorites",
  "status": "ready",
  "phases": [
    {
      "id": "phase_1",
      "name": "Database Setup",
      "description": "Complete database setup in single migration",
      "tasks": [
        {
          "id": "task_001",
          "description": "Create comprehensive dashboard database migration",
          "type": "supabase_migration",
          "dependencies": [],
          "specifics": {
            "migrationName": "add_dashboard_functionality",
            "sql": "-- User Dashboard: Complete Database Setup\n\n-- 1. Create view for user statistics\nCREATE OR REPLACE VIEW user_stats AS\nSELECT \n  u.id as user_id,\n  COUNT(DISTINCT r.id) as total_recipes,\n  COALESCE(SUM(rv.view_count), 0) as total_views,\n  COUNT(DISTINCT f.id) as total_favorites,\n  CASE \n    WHEN COUNT(DISTINCT r.id) > 0 \n    THEN COALESCE(SUM(rv.view_count), 0) / COUNT(DISTINCT r.id)\n    ELSE 0 \n  END as avg_views_per_recipe\nFROM user_profiles u\nLEFT JOIN recipes r ON r.user_id = u.id\nLEFT JOIN (\n  SELECT recipe_id, COUNT(*) as view_count\n  FROM recipe_views\n  GROUP BY recipe_id\n) rv ON rv.recipe_id = r.id\nLEFT JOIN favorites f ON f.recipe_id = r.id\nGROUP BY u.id;\n\n-- 2. Function to get user's recipes with stats\nCREATE OR REPLACE FUNCTION get_user_recipes_with_stats(user_uuid UUID)\nRETURNS TABLE (\n  id UUID,\n  title TEXT,\n  description TEXT,\n  created_at TIMESTAMPTZ,\n  view_count BIGINT,\n  favorite_count BIGINT\n) AS $$\nBEGIN\n  RETURN QUERY\n  SELECT \n    r.id,\n    r.title,\n    r.description,\n    r.created_at,\n    COUNT(DISTINCT rv.id) as view_count,\n    COUNT(DISTINCT f.id) as favorite_count\n  FROM recipes r\n  LEFT JOIN recipe_views rv ON rv.recipe_id = r.id\n  LEFT JOIN favorites f ON f.recipe_id = r.id\n  WHERE r.user_id = user_uuid\n  GROUP BY r.id, r.title, r.description, r.created_at\n  ORDER BY r.created_at DESC;\nEND;\n$$ LANGUAGE plpgsql SECURITY DEFINER;\n\n-- 3. Function to get user's favorited recipes\nCREATE OR REPLACE FUNCTION get_user_favorites(user_uuid UUID)\nRETURNS TABLE (\n  recipe_id UUID,\n  title TEXT,\n  description TEXT,\n  author_id UUID,\n  author_username TEXT,\n  favorited_at TIMESTAMPTZ\n) AS $$\nBEGIN\n  RETURN QUERY\n  SELECT \n    r.id,\n    r.title,\n    r.description,\n    r.user_id,\n    u.username,\n    f.created_at\n  FROM favorites f\n  JOIN recipes r ON f.recipe_id = r.id\n  JOIN user_profiles u ON r.user_id = u.id\n  WHERE f.user_id = user_uuid\n  ORDER BY f.created_at DESC;\nEND;\n$$ LANGUAGE plpgsql SECURITY DEFINER;\n\n-- 4. Add RLS policies\nALTER TABLE user_stats ENABLE ROW LEVEL SECURITY;\n\nCREATE POLICY \"Users can view own stats\"\n  ON user_stats FOR SELECT\n  USING (auth.uid() = user_id);\n\n-- 5. Grant permissions\nGRANT SELECT ON user_stats TO authenticated;\nGRANT EXECUTE ON FUNCTION get_user_recipes_with_stats TO authenticated;\nGRANT EXECUTE ON FUNCTION get_user_favorites TO authenticated;\n\n-- 6. Performance indexes\nCREATE INDEX IF NOT EXISTS idx_recipe_views_recipe_id ON recipe_views(recipe_id);\nCREATE INDEX IF NOT EXISTS idx_favorites_user_id ON favorites(user_id);\nCREATE INDEX IF NOT EXISTS idx_favorites_recipe_id ON favorites(recipe_id);",
            "rollback": "-- Rollback dashboard functionality\nDROP VIEW IF EXISTS user_stats CASCADE;\nDROP FUNCTION IF EXISTS get_user_recipes_with_stats CASCADE;\nDROP FUNCTION IF EXISTS get_user_favorites CASCADE;\nDROP INDEX IF EXISTS idx_recipe_views_recipe_id;\nDROP INDEX IF EXISTS idx_favorites_user_id;\nDROP INDEX IF EXISTS idx_favorites_recipe_id;"
          }
        }
      ]
    },
    {
      "id": "phase_2", 
      "name": "Dashboard Page Structure",
      "description": "Create dashboard page and routing",
      "tasks": [
        {
          "id": "task_002",
          "description": "Create dashboard page component",
          "type": "component_creation",
          "dependencies": ["task_001"],
          "specifics": {
            "componentName": "DashboardPage",
            "filePath": "src/app/dashboard/page.tsx",
            "features": ["stats section", "recipes section", "favorites section"],
            "props": {}
          }
        },
        {
          "id": "task_003",
          "description": "Configure authentication middleware for dashboard",
          "type": "configuration",
          "dependencies": ["task_002"],
          "specifics": {
            "configFile": "src/middleware.ts",
            "settings": {
              "protectedRoutes": ["/dashboard"]
            }
          }
        }
      ]
    }
  ]
}
```

---

## ✅ Step 6: Validate and Execute

### Initial Setup
```bash
# First, configure git integration preferences
npm run plan:config autoCommit true      # Enable auto-commit
npm run plan:config interactive false    # Skip prompts for faster workflow
```

### Validate Your Plan
```bash
npm run plan:validate
# Choose option 1 (paste JSON)
# Paste your JSON plan
# Type END

# Output: ✅ PLAN IS VALID!
```

---

## 🎮 Step 7: Execute with Git Integration

### Task 1: Database Migration

```bash
# Get the first command
npm run plan:continue

# OUTPUT:
📊 Progress: 0/11 tasks (0%)

🎯 NEXT TASK: Create comprehensive dashboard database migration
📋 Type: supabase_migration
📋 Task ID: task_001

🔄 GIT INTEGRATION:
✅ Auto-commit is enabled. Changes will be committed automatically when you complete this task.

📝 To save Claude's response for better commit messages:
   npm run plan:save-response task_001 "Claude's final message"

🚀 GENERATED COMMAND:
[Supabase migration command appears here]
```

#### After Claude Implements:

Claude responds: *"I've successfully created the dashboard database migration with user statistics view, functions for fetching user recipes and favorites with counts, proper RLS policies, and performance indexes. The migration includes a complete rollback script for safety."*

```bash
# Save Claude's response
npm run plan:save-response task_001 "I've successfully created the dashboard database migration with user statistics view, functions for fetching user recipes and favorites with counts, proper RLS policies, and performance indexes."

# Complete the task (auto-commits)
npm run plan:complete task_001

# OUTPUT:
🔄 Committing changes...
✅ Changes committed!
   abc123d feat(db): Created the dashboard database migration with user statistics view (task_001)

✅ Task task_001 marked as complete!
📊 Progress: 1/11 tasks (9%)

🎯 Next task: Create dashboard page component
Run: npm run plan:continue
```

### Task 2: Dashboard Page

```bash
npm run plan:continue

# Implement with Claude...
# Claude: "I've successfully created the dashboard page component with sections for statistics, recipe management, and favorites collection. The component includes proper authentication checks and responsive layout."

npm run plan:save-response task_002 "I've successfully created the dashboard page component with sections for statistics, recipe management, and favorites collection. The component includes proper authentication checks and responsive layout."

npm run plan:complete task_002

# Automatically commits: "feat(ui): Created the dashboard page component with sections for statistics (task_002)"
```

### Continue Through All Tasks

The workflow continues similarly for each task:
1. `npm run plan:continue` - Get next command
2. Implement with Claude
3. `npm run plan:save-response` - Save Claude's summary
4. `npm run plan:complete` - Complete & auto-commit

---

## 📊 Final Git History

After completing all tasks, your git log shows:

```bash
git log --oneline

# Clean, meaningful commit history:
f8a9c3d feat(ui): Connected dashboard components with real data and error handling (task_011)
e7b6d4a feat(api): Created dashboard service layer with data fetching functions (task_010)
c5f2a8e feat(ui): Created FavoritesGrid component with recipe cards and unfavorite action (task_009)
b4d1e7c feat(ui): Created RecipeManagementTable component with sorting and actions (task_008)
a9c3f2b feat(ui): Created StatsOverview component with statistic cards (task_007)
6e5d4f1 style(ui): Created responsive dashboard layout with Tailwind CSS (task_006)
4b3c2d0 feat(ui): Created dashboard loading skeleton component (task_005)
3a2b1c9 feat(ui): Created empty states for new users (task_004)
2d1a0b8 chore(config): Configure authentication middleware for dashboard (task_003)
1c0d9e7 feat(ui): Created dashboard page component with sections for statistics (task_002)
0ab8f6g feat(db): Created the dashboard database migration with user statistics view (task_001)
```

---

## 🎯 Task Management Commands

### Core Commands
```bash
# Continue to next task
npm run plan:continue

# Complete task with commit
npm run plan:complete task_001 --commit

# Complete without commit (if auto-commit enabled)
npm run plan:complete task_001 --no-commit

# Save Claude's response
npm run plan:save-response task_001 "Claude's implementation summary..."
```

### Status Commands
```bash
# Check progress
npm run plan:progress
npm run plan:status      # Same as progress

# View entire plan
npm run plan:view
```

### Git Configuration
```bash
# View current settings
npm run plan:config

# Configure preferences
npm run plan:config autoCommit true       # Auto-commit on completion
npm run plan:config interactive false     # Skip commit prompts
npm run plan:config includeTaskId true    # Add (task_001) to commits
```

### Advanced Options
```bash
# Custom commit message
npm run plan:complete task_001 --commit --message "feat: Add dashboard with complete user analytics

- Created comprehensive statistics view
- Added recipe management table
- Implemented favorites grid
- Full mobile responsiveness"

# Save response from file
npm run plan:save-response task_001 --file claude-response.txt
```

---

## 💡 Pro Tips

### 1. Quick Workflow Setup
```bash
# Enable auto-commit for speed
npm run plan:config autoCommit true
npm run plan:config interactive false
```

### 2. Batch Processing
```bash
# Work through multiple tasks quickly
npm run plan:continue && npm run plan:save-response task_001 "..." && npm run plan:complete task_001
```

### 3. Review Before Push
```bash
# After completing several tasks
git log --oneline -10    # Review commits
git push origin main      # Push clean history
```

---

## 🎉 Complete!

You've successfully:
1. ✅ Understood your existing app structure
2. ✅ Defined feature requirements collaboratively
3. ✅ Created a structured development plan
4. ✅ Validated the plan structure
5. ✅ Executed step-by-step with Claude
6. ✅ Maintained clean git history automatically
7. ✅ Built a complete user dashboard!

Your recipe app now has a fully functional user dashboard with:
- Real-time statistics
- Recipe management
- Favorites collection
- Clean, atomic commits for each feature

The git integration ensures every step is documented with meaningful commit messages derived from Claude's implementation summaries! 