# Website Flow: SIMPLIFIED PLAN (Revised)

**Status**: ✅ APPROVED CHANGES  
**Date**: 2026-08-18  
**Complexity**: Reduced (5 phases → 3 phases)  
**Timeline**: ~10-12 days (down from 17)

---

## 📋 REVISED APPROACH

### ✅ What Was Approved
```
GET /api/v1/dashboard              ✅ Required (same UI flow)
GET /website                       ✅ Modify to select-only
POST /api/v1/websites              ✅ Reuse existing API
"Create Project" button in dashboard → Opens modal

Removed (Simplification):
GET /onboard                       ❌ Not needed
POST /api/v1/onboarding/...        ❌ Not needed
```

---

## 🎯 NEW FLOW

### User Journey (Simplified)

```
┌─────────────────────────────────────────────────────────────┐
│                  NEW USER LOGIN                             │
└────────────────────────┬──────────────────────────────────┘
                         ↓
        ┌────────────────────────────────┐
        │  Check: Has website?           │
        │  (via middleware)              │
        └────────┬────────────┬──────────┘
             NO  │            │  YES
                 ↓            ↓
        ┌──────────────┐  ┌──────────────────┐
        │ /dashboard   │  │  /dashboard      │
        │ (show modal) │  │  (normal view)   │
        │             │  │  [Create Project]│
        │ "First time?"│  │                  │
        │ Add a site   │  │  [Website ▼]     │
        │             │  └──────────────────┘
        └────┬────────┘
             ↓
      ┌─────────────────────────────┐
      │  Modal: Create Project      │
      │  [Domain input]             │
      │  [Max pages slider]         │
      │  [Verify method]            │
      │  [Create] button            │
      └────┬────────────────────────┘
           ↓
      ┌─────────────────────────────┐
      │  POST /api/v1/websites      │
      │  (existing API)             │
      └────┬────────────────────────┘
           ↓
      ┌─────────────────────────────┐
      │  Modal closes               │
      │  Dashboard reloads          │
      │  Website selector shows new │
      │  "Create Project" → inactive│
      └─────────────────────────────┘
```

---

## 🏗️ IMPLEMENTATION PHASES (3 Phases, ~10-12 Days)

### PHASE 1: Access Control (2-3 Days)

#### 1.1 Add WebsiteRequiredFilter
**File**: `app/Filters/WebsiteRequiredFilter.php`

Checks if user has ≥1 website. If not:
- Show dashboard with "Create Project" button active
- Other routes redirect to dashboard

**Routes that need filter**:
- GET /dashboard (allow, but show create button if no websites)
- GET /website (allow select-only)
- GET /crawl/* (require website)
- GET /audit/* (require website)
- GET /reports/* (require website)
- etc.

#### 1.2 Update DashboardModule
- Add website check in initController()
- Pass `hasWebsites` and `websiteCount` to view

---

### PHASE 2: Dashboard Completion (4-5 Days)

#### 2.1 Create Dashboard API
**Endpoint**: `GET /api/v1/dashboard`

Returns:
```json
{
  "kpis": {
    "organic_clicks": 48120,
    "organic_clicks_delta": 12.4,
    "impressions": 1240000,
    "impressions_delta": 8.1,
    "conversions": 1043,
    "conversions_delta": 5.6,
    "attributed_revenue": 312400,
    "attributed_revenue_delta": 9.3
  },
  "pipeline": {
    "open_opportunities": 37,
    "pending_approvals": 6,
    "crawl_coverage_pct": 92,
    "connector_health_status": "3 of 4",
    "next_job": {
      "type": "full_crawl",
      "scheduled_time": "2026-08-18T23:00:00Z"
    }
  },
  "recent_activity": [
    {
      "type": "deployment",
      "title": "Deployment published",
      "description": "Emergency plumbing — Austin · v14",
      "tone": "success",
      "timestamp": "12m ago"
    }
  ]
}
```

**File**: `app/Controllers/Api/V1/DashboardController.php`

#### 2.2 Update Dashboard View
**File**: `app/Views/dashboard/index.php`

Changes:
- Remove placeholders
- Add data attributes for JS hydration
- Add "Create Project" button (modal trigger)
- Show KPI tiles, pipeline, activity grid
- Add loading spinners

#### 2.3 Create Dashboard JS
**File**: `public/assets/js/dashboard.js`

Functions:
- boot()
- loadDashboard()
- hydratKpis()
- hydratePipeline()
- hydrateActivity()
- renderTrendChart()

#### 2.4 Create Modal Component
**File**: `app/Views/dashboard/components/create-project-modal.php`

Contents:
- Title: "Create Project"
- Domain input + protocol dropdown
- Max pages slider
- Verification method radio buttons
- Create button
- Close button

**Reuse**: Form markup from `/website` page

#### 2.5 Create Modal JS
**File**: `public/assets/js/create-project-modal.js`

Functions:
- openModal()
- closeModal()
- submitForm()
- POST to /api/v1/websites (existing)
- Handle success/error
- Reload dashboard on success

---

### PHASE 3: Website Page Consolidation (2-3 Days)

#### 3.1 Modify GET /website View
**File**: `app/Views/dashboard/website.php`

Changes:
- Remove "Add a website" form
- Add "+ Create Project" button → opens modal
- Keep only: website list, edit, delete, primary selector
- Show "Learn more" link to create project modal

#### 3.2 Update /website Controller
**File**: `app/Controllers/WebsiteController.php`

No changes needed (just remove create form from view).

#### 3.3 Keep API Endpoints as-is
**Existing endpoints unchanged**:
- POST /api/v1/websites (already works)
- GET /api/v1/websites (list)
- POST /api/v1/websites/(:num) (update)
- POST /api/v1/websites/(:num)/remove (delete)
- etc.

---

## 📂 FILES TO CREATE

```
NEW FILES (4):
├─ app/Controllers/Api/V1/DashboardController.php
├─ app/Views/dashboard/components/create-project-modal.php
├─ public/assets/js/dashboard.js
└─ public/assets/js/create-project-modal.js

MODIFIED FILES (5):
├─ app/Filters/WebsiteRequiredFilter.php (create new)
├─ app/Controllers/DashboardModule.php
├─ app/Views/dashboard/index.php
├─ app/Views/dashboard/website.php
└─ app/Config/Routes.php (apply filter)

ROUTES:
├─ GET /api/v1/dashboard (NEW)
└─ GET /website (no route change, view modified)
```

---

## ✅ IMPLEMENTATION CHECKLIST

### Phase 1: Access Control (2-3 days)
- [ ] Create WebsiteRequiredFilter
  - [ ] Count websites for user
  - [ ] Redirect logic for missing website
  - [ ] Write tests
- [ ] Update DashboardModule
  - [ ] Query website count
  - [ ] Pass to views
  - [ ] Handle redirect edge cases
- [ ] Apply filter to routes
  - [ ] All dashboard routes get filter
  - [ ] Test each route
  - [ ] Verify redirects work

### Phase 2: Dashboard Completion (4-5 days)
- [ ] Create GET /api/v1/dashboard endpoint
  - [ ] Query Google Search Console cache (KPIs)
  - [ ] Query opportunities (open count)
  - [ ] Query approvals (pending count)
  - [ ] Query crawl status (coverage %)
  - [ ] Query integrations (connector health)
  - [ ] Query jobs (next scheduled)
  - [ ] Query audit log (recent activity)
  - [ ] Error handling (graceful empty arrays)
  - [ ] Tests
- [ ] Update dashboard/index.php view
  - [ ] KPI tiles with data attributes
  - [ ] Pipeline health grid
  - [ ] Activity list
  - [ ] Trend chart container
  - [ ] "Create Project" button
  - [ ] Loading spinner states
- [ ] Create dashboard.js
  - [ ] Fetch from /api/v1/dashboard
  - [ ] Hydrate all sections
  - [ ] Error handling
  - [ ] Performance (cache results)
- [ ] Create create-project-modal.php
  - [ ] Modal structure (overlay + box)
  - [ ] Form fields (domain, pages, verify)
  - [ ] Buttons (create, cancel)
  - [ ] Close on escape/outside click
  - [ ] Styling (responsive)
- [ ] Create create-project-modal.js
  - [ ] Open modal function
  - [ ] Close modal function
  - [ ] Form validation
  - [ ] POST to /api/v1/websites
  - [ ] Handle success (reload dashboard)
  - [ ] Handle error (show message)

### Phase 3: Website Page Consolidation (2-3 days)
- [ ] Modify /website view
  - [ ] Remove form elements
  - [ ] Add "+ Create Project" button
  - [ ] Keep list + edit + delete
  - [ ] Test design
- [ ] Test full flow
  - [ ] New user: clicks Create Project
  - [ ] Modal opens
  - [ ] Fill form, submit
  - [ ] Website created
  - [ ] Dashboard reloads
  - [ ] New website in selector
  - [ ] Existing user: /website shows list only

---

## 📊 COMPARISON: OLD vs NEW PLAN

| Aspect | Original Plan | Simplified Plan |
|--------|---------------|-----------------|
| **Onboarding routes** | GET /onboard + POST endpoint | Modal in dashboard |
| **Website creation** | Separate page at /onboard | Modal popup |
| **Website page** | Still has create form | Create form removed |
| **Dashboard** | Empty at first | Shows button, fills with data |
| **API endpoints** | Create new onboarding endpoint | Reuse existing POST /api/v1/websites |
| **Files to create** | 9+ files | 4 files |
| **Files to modify** | 6+ files | 5 files |
| **Routes to add** | 2 new routes | 1 new route (/api/v1/dashboard) |
| **Timeline** | 17 days | 10-12 days |
| **Complexity** | High (5 phases) | Medium (3 phases) |

---

## 🎨 MODAL DESIGN (Sketch)

```
┌───────────────────────────────────────────┐
│  Create Project                        [×] │
├───────────────────────────────────────────┤
│                                           │
│  <-- Start crawling & optimizing your domain  │
│                                           │
│  Website domain *                         │
│  [https://] [example.com          ]      │
│  "Enter the root domain"                  │
│                                           │
│  Max pages per crawl *                    │
│  [████████░░░░░░░░░░░░░░░░░░] 500 pages  │
│  "100 - 10,000 pages"                     │
│                                           │
│  Verify ownership                         │
│  ○ DNS TXT record                         │
│  ○ HTML file upload                       │
│  ○ Google Search Console                  │
│                                           │
│                    [Cancel] [Create]     │
│                                           │
└───────────────────────────────────────────┘
```

---

## 🔐 Security Considerations

1. **Modal doesn't need separate auth** - uses same session/token as dashboard
2. **POST /api/v1/websites already validates** - domain ownership, rate limiting, plan limits
3. **Website selector validates** - X-Website-Id header checked on API calls
4. **No new security holes** - reusing existing, proven endpoints

---

## 📈 BENEFITS OF SIMPLIFIED APPROACH

✅ **Faster Implementation** (10-12 days vs 17 days)
✅ **Less Code** (4 files to create vs 9+)
✅ **Fewer Routes** (1 new route vs 2)
✅ **Reuse Existing APIs** (no new endpoints)
✅ **Simpler UX** (modal vs separate page)
✅ **Fewer Edge Cases** (less code = less bugs)
✅ **Easier to Maintain** (familiar patterns)
✅ **Better Mobile UX** (modal vs full page)

---

## 🧪 TESTING PLAN

### Unit Tests
- [ ] WebsiteRequiredFilter with 0/1+ websites
- [ ] DashboardController returns correct data
- [ ] Modal JS handles form validation
- [ ] Modal JS handles API response

### Integration Tests
- [ ] New user flow: login → see Create Project button
- [ ] Click Create Project → modal opens
- [ ] Fill form → submit → website created
- [ ] Dashboard reloads → shows new website
- [ ] Existing user → website page has no create form

### E2E Tests
- [ ] Full onboarding: signup → create project → dashboard
- [ ] Multiple projects: create 2nd, switch via selector
- [ ] Modal close: ESC key, outside click, cancel button
- [ ] Form validation: invalid domain, page limits

---

## 🚀 ROLLOUT PHASES

### Development (3-4 days)
- Build & test all components
- Staging deployment
- Internal QA

### Beta (3-4 days)
- Deploy to 10% of users
- Monitor errors/feedback
- Iterate if needed

### Production (1-2 days)
- Full rollout
- Monitor dashboards
- Ready for support

---

## 📋 FINAL CHECKLIST

- [ ] All code written
- [ ] All tests passing
- [ ] Code review approved
- [ ] Performance verified (<500ms)
- [ ] Security review passed
- [ ] Documentation updated
- [ ] Support team trained
- [ ] Rollout plan confirmed
- [ ] Monitoring/alerts set up
- [ ] ✅ READY TO DEPLOY

---

## 🎯 SUCCESS METRICS

| Metric | Target |
|--------|--------|
| Dashboard load time | <500ms |
| Modal open/close | <100ms |
| Onboarding completion rate | >90% |
| New user drop-off | <5% |
| Support tickets (first week) | <5 |

---

**Status**: ✅ REVISED PLAN APPROVED & READY FOR IMPLEMENTATION
