# Basic Dealer Editor - Design Document

**Date:** 2025-01-19
**Feature:** Basic dealer information editor for post-registration updates
**Route:** `/dashboard/editor`

## Overview

A single-page form that allows authenticated dealers to edit their business information after completing initial registration. This editor provides access to all display fields that appear on their public dealer site.

## User Requirements

From stakeholder feedback:

> Basic Editor [ZO Account Number (they will provide this), Business Name, Contact Name, Street Address, City, State, Zipcode, Country, Phone, Email, Description]
> \*Cannot change domain subdomain slug once set. Can change custom domain at any time.

## Key Design Decisions

### 1. UI Layout

- **Single page form** - No accordion/steps (simpler for quick edits)
- **Consistent dashboard header** - Shared layout across all dashboard pages
- **Card-based design** - Reuses registration theme styling
- **Responsive layout** - Works on mobile and desktop

### 2. Domain Management

- **Subdomain: READ-ONLY** - Cannot change after initial setup (prevents broken links, SEO issues)
- **Custom Domain: EDITABLE** - Can be changed anytime (just DNS pointing)

### 3. Email Separation

- **Login Email** (User.email) - OAuth email, used for authentication only
- **Display Email** (Dealer.contactEmail) - Public contact email, fully editable

### 4. Save Behavior

- **Simple "Save Changes" button** - Updates database without publishing workflow
- **Success message** - Confirms save completed
- **Error handling** - Shows field-specific validation errors

## Database Schema Changes

### New Fields for Dealer Model

```prisma
model Dealer {
  // ... existing fields ...

  // NEW: Contact information for public display
  contactName   String?      // Contact person name (separate from business name)
  contactEmail  String?      // Display email (separate from User.email OAuth)
  description   String?  @db.Text  // Long text for business description
}
```

### Field Mappings

| Display Name      | Database Field | Type    | Required | Notes                          |
| ----------------- | -------------- | ------- | -------- | ------------------------------ |
| ZO Account Number | dealerNumber   | String? | No       | Existing field                 |
| Business Name     | businessName   | String? | Yes      | Existing field                 |
| Contact Name      | contactName    | String? | No       | **NEW**                        |
| Street Address    | address        | String  | Yes      | Existing field                 |
| City              | city           | String  | Yes      | Existing field                 |
| State/Province    | state          | String  | Yes      | Existing field (2-letter code) |
| Zipcode           | zip            | String  | Yes      | Existing field                 |
| Country           | country        | String  | Yes      | Existing field                 |
| Phone             | phone          | String  | Yes      | Existing field                 |
| Email             | contactEmail   | String? | No       | **NEW** (display email)        |
| Description       | description    | String? | No       | **NEW** (long text)            |
| Subdomain         | subdomain      | String? | N/A      | Read-only display              |
| Custom Domain     | customDomain   | String? | No       | Editable                       |

## Architecture

### Component Structure

```
app/
├── dashboard/
│   ├── layout.tsx          # NEW: Shared dashboard layout
│   ├── page.tsx            # Updated: Add "Basic Editor" button
│   └── editor/
│       ├── page.tsx        # NEW: Server component - fetch dealer data
│       └── EditorForm.tsx  # NEW: Client component - form logic
└── api/
    └── dealer/
        └── update/
            └── route.ts    # NEW: API endpoint for updates
```

### API Endpoint

**Route:** `POST /api/dealer/update`

**Request Body:**

```json
{
  "dealerNumber": "1472175",
  "businessName": "Mike Marx",
  "contactName": "Mike Marx",
  "address": "123 Main St",
  "city": "Oakmont",
  "state": "PA",
  "zip": "15139",
  "country": "United States",
  "phone": "(717) 495-5726",
  "contactEmail": "mike@example.com",
  "customDomain": "www.example.com",
  "description": "Business description..."
}
```

**Response (Success):**

```json
{
  "success": true,
  "dealer": {
    /* updated dealer record */
  }
}
```

**Response (Error):**

```json
{
  "error": "Validation failed",
  "fields": {
    "phone": "Invalid phone format",
    "state": "Must be 2-letter code"
  }
}
```

### Security & Validation

**Authentication:**

- User must be signed in (enforced by middleware)
- User can only update their own dealer record (verified by userId)

**Validation Rules:**

- **Required fields:** businessName, address, city, state, zip, country, phone
- **State:** Must be 2-letter code (e.g., "MN", "ON")
- **Email:** Valid email format if provided
- **Phone:** Valid phone format
- **Custom Domain:** Must be unique if provided (check availability)
- **Subdomain:** Not included in update (cannot be changed)

### Data Flow

```
User loads /dashboard/editor
    ↓
Server fetches dealer data (getServerSession → userId → Dealer)
    ↓
Pre-fill form with existing values
    ↓
User edits fields
    ↓
User clicks "Save Changes"
    ↓
POST to /api/dealer/update
    ↓
Validate & update database
    ↓
Show success message / errors
```

## User Experience

### Navigation Flow

1. User on dashboard sees "Basic Editor" button in header
2. Click navigates to `/dashboard/editor`
3. Form loads with pre-filled data
4. User edits desired fields
5. Click "Save Changes"
6. Success message appears
7. Header provides navigation back to dashboard

### Form Layout

```
┌─────────────────────────────────────────────┐
│  Dashboard Header (Logo, Nav, Sign Out)     │
├─────────────────────────────────────────────┤
│                                             │
│   ┌───────────────────────────────────┐    │
│   │  EDIT DEALER INFORMATION          │    │
│   │                                   │    │
│   │  Domain Settings                  │    │
│   │  ├─ Subdomain: [read-only]        │    │
│   │  └─ Custom Domain: [input]        │    │
│   │                                   │    │
│   │  Business Information             │    │
│   │  ├─ ZO Account Number: [input]    │    │
│   │  ├─ Business Name: [input]        │    │
│   │  ├─ Contact Name: [input]         │    │
│   │  ├─ Street Address: [input]       │    │
│   │  ├─ City: [input]                 │    │
│   │  ├─ State: [input]                │    │
│   │  ├─ Zipcode: [input]              │    │
│   │  ├─ Country: [input]              │    │
│   │  ├─ Phone: [input]                │    │
│   │  ├─ Email: [input]                │    │
│   │  └─ Description: [textarea]       │    │
│   │                                   │    │
│   │  [Save Changes]                   │    │
│   └───────────────────────────────────┘    │
│                                             │
└─────────────────────────────────────────────┘
```

## Future Enhancements (Out of Scope)

- Save & Publish workflow
- Change history / audit log
- Field-level permissions
- Bulk editing for multi-location dealers
- Image upload for logos/photos
- Social media link management

## Implementation Phases

### Phase 1: Database Migration

1. Add new fields to Dealer model
2. Run Prisma migration
3. Update type definitions

### Phase 2: API Endpoint

1. Create `/api/dealer/update` route
2. Implement validation logic
3. Test with Postman/curl

### Phase 3: UI Components

1. Create shared dashboard layout
2. Build editor page and form component
3. Add form validation and error handling

### Phase 4: Integration

1. Update dashboard with "Basic Editor" button
2. Test end-to-end flow
3. Handle edge cases (no dealer, suspended account, etc.)

## Success Criteria

- ✅ Dealers can edit all specified fields
- ✅ Subdomain is displayed but not editable
- ✅ Custom domain can be changed (with uniqueness check)
- ✅ Form pre-fills with existing data
- ✅ Validation prevents invalid data
- ✅ Success/error messages provide clear feedback
- ✅ Changes persist to database
- ✅ Only authenticated dealers can access
- ✅ Users can only edit their own data

## Technical Debt / Considerations

1. **Email field confusion** - User.email (OAuth) vs Dealer.contactEmail (display). Consider renaming for clarity.
2. **Phone validation** - Support multiple formats (US, CA, international)?
3. **Country field** - Currently free text. Should it be a dropdown with ISO codes?
4. **Description length** - Should we enforce a character limit for descriptions?
5. **Custom domain validation** - Should we verify DNS configuration or just check uniqueness?

## References

- Existing onboarding flow: `app/registration/onboarding/OnboardingForm.tsx`
- Dealer model: `prisma/schema.prisma`
- Dashboard: `app/dashboard/page.tsx`
- Scraped data structure: `SCRAPED-DATA.csv` (shows real-world dealer data format)
