# Onboarding Wizard Implementation

## Overview

A comprehensive multi-step onboarding wizard that guides new tenants through setting up their business after registration. The wizard helps configure branches, admin users, product categories, payment types, and VAT settings.

## Features

- **6-Step Guided Setup**: Business profile, branches, users, product coding, payment types, VAT
- **Progress Tracking**: Visual progress indicator with completion percentage
- **Skip & Resume**: Users can skip and resume later from settings
- **Auto-redirect**: Automatically shows wizard on first login if not completed
- **Multi-language**: Full English and Arabic support with RTL
- **Persistent State**: Progress saved in database and can be resumed

## Architecture

### Backend Components

#### 1. Database Migration

**File**: `database/migrations/2026_01_25_221217_create_onboarding_progress_table.php`

Creates `onboarding_progress` table with:

- `user_id` - Links to user
- `current_step` - Current wizard step
- `completed_steps` - JSON array of completed steps
- `step_data` - JSON object storing form data for each step
- `is_completed` - Whether onboarding is finished
- `is_skipped` - Whether user skipped onboarding
- Timestamps for completion and skip

#### 2. OnboardingProgress Model

**File**: `app/Models/User/OnboardingProgress.php`

Methods:

- `isCompleted()` - Check if onboarding is done
- `isSkipped()` - Check if user skipped
- `getCurrentStep()` - Get current step name
- `getCompletedSteps()` - Get array of completed steps
- `isStepCompleted($step)` - Check if specific step is done
- `markStepComplete($step, $data)` - Mark step complete and advance
- `skip()` - Skip onboarding
- `complete()` - Mark as complete
- `reset()` - Resume after skip
- `getProgressPercentage()` - Calculate completion %
- `getStepData($step)` - Get saved data for step

#### 3. OnboardingController

**File**: `app/Http/Controllers/Api/OnboardingController.php`

Endpoints:

- `GET /api/onboarding/status` - Get current onboarding state
- `POST /api/onboarding/step/{step}` - Save step data and mark complete
- `POST /api/onboarding/skip` - Skip onboarding
- `POST /api/onboarding/complete` - Mark as complete
- `POST /api/onboarding/resume` - Resume after skip

Validates step data based on step type with appropriate rules.

#### 4. AuthController Update

**File**: `app/Http/Controllers/Auth/AuthController.php`

The `me()` endpoint now includes `onboarding_status` in response:

```json
{
  "user": {...},
  "onboarding_status": {
    "is_completed": false,
    "is_skipped": false,
    "current_step": "business_profile",
    "progress_percentage": 0
  }
}
```

#### 5. API Routes

**File**: `routes/api.php`

Added onboarding routes under `auth:sanctum` middleware.

### Frontend Components

#### 1. Onboarding Store (Zustand)

**File**: `resources/js/stores/onboardingStore.ts`

State management for:

- Onboarding status
- Current step data
- Loading states
- Actions: fetchStatus, saveStep, skip, complete, resume

#### 2. Onboarding Service

**File**: `resources/js/services/onboardingService.ts`

API client with TypeScript interfaces for:

- Getting status
- Saving steps
- Skipping/completing/resuming

#### 3. Main Wizard Component

**File**: `resources/js/components/Onboarding/OnboardingWizard.tsx`

Features:

- Left sidebar with progress steps
- Visual progress indicator (numbered circles)
- Completion percentage bar
- Skip confirmation modal
- Dynamic step rendering
- Auto-redirect when complete/skipped

#### 4. Step Components

All located in `resources/js/components/Onboarding/steps/`:

**BusinessProfileStep.tsx**

- Company display name
- Business address
- Contact phone/email
- Currency selection

**BranchesStep.tsx**

- Fetch existing branches
- Add new branches with name, short name, address, phone
- Validation for required fields
- Creates branches via API

**AdminUsersStep.tsx**

- Simplified step (can be enhanced)
- Info about adding users later
- Skip-friendly

**ProductCodingStep.tsx**

- Three presets: Fashion, Electronics, General
- Auto-creates categories and brands based on selection
- Visual preset cards with checkmark

**PaymentTypesStep.tsx**

- Shows default payment types (Cash, Card, Bank Transfer)
- Info about customizing later
- Quick confirmation step

**VatSettingsStep.tsx**

- VAT rate input (0-100%)
- Prices include VAT toggle
- Live calculation example
- Final step - triggers completion

#### 5. Route Integration

**App.tsx**

- Added `/onboarding` route with ProtectedRoute wrapper
- Imported OnboardingWizard component

**ProtectedRoute.tsx**

- Checks `user.onboarding_status` from authStore
- Redirects to `/onboarding` if not completed and not skipped
- Skips check for `/onboarding` route itself

**AuthStore.ts**

- Updated User interface to include `onboarding_status`

**AuthService.ts**

- Updated to use `/auth/me` endpoint
- Includes onboarding_status in user data

#### 6. Translations

**English**: `resources/js/i18n/locales/en/onboarding.json`
**Arabic**: `resources/js/i18n/locales/ar/onboarding.json`

Complete translations for all wizard text, steps, labels, and messages.

## User Flow

### First-Time User Journey

```
1. User registers → Tenant created
2. User logs in → AuthController returns onboarding_status (null or incomplete)
3. ProtectedRoute detects incomplete onboarding → Redirects to /onboarding
4. User sees wizard with 6 steps
5. User completes each step (or skips)
6. After last step → Onboarding marked complete
7. User redirected to /dashboard
```

### Skip & Resume Flow

```
1. User clicks "Skip for now" → Confirmation modal
2. User confirms → is_skipped = true
3. User redirected to dashboard
4. Later: User can resume from settings (future enhancement)
5. Resume → is_skipped = false, wizard shows again
```

## Step Details

### Step 1: Business Profile

- **Optional fields**: Company name, address, phone, email, currency
- **Purpose**: Customize business information
- **Data stored**: In `step_data.business_profile`

### Step 2: Branches

- **Required**: At least one branch
- **Fetches**: Existing branches from API
- **Creates**: New branches via `/api/admin/stores/create`
- **Validation**: Name and short_name required

### Step 3: Admin Users

- **Optional**: Can skip
- **Purpose**: Add additional admin/manager users
- **Note**: Currently simplified, can be enhanced

### Step 4: Product Coding

- **Presets**: Fashion, Electronics, General
- **Creates**: Categories and brands based on selection
- **Purpose**: Quick setup for product catalog

### Step 5: Payment Types

- **Shows**: Default payment types (Cash, Card, Bank Transfer)
- **Purpose**: Confirm payment methods
- **Note**: Default types already created during registration

### Step 6: VAT Settings

- **Required**: VAT rate (0-100%)
- **Toggle**: Prices include VAT
- **Preview**: Live calculation example
- **Final step**: Marks onboarding as complete

## API Endpoints

### Get Status

```
GET /api/onboarding/status
Response: {
  success: true,
  data: {
    current_step: "business_profile",
    completed_steps: [],
    step_data: {},
    is_completed: false,
    is_skipped: false,
    progress_percentage: 0,
    available_steps: [...]
  }
}
```

### Save Step

```
POST /api/onboarding/step/{step}
Body: { ...step-specific data... }
Response: {
  success: true,
  message: "Step saved successfully",
  data: {
    current_step: "branches",
    completed_steps: ["business_profile"],
    is_completed: false,
    progress_percentage: 16
  }
}
```

### Skip

```
POST /api/onboarding/skip
Response: {
  success: true,
  message: "Onboarding skipped..."
}
```

### Complete

```
POST /api/onboarding/complete
Response: {
  success: true,
  message: "Onboarding completed successfully!"
}
```

### Resume

```
POST /api/onboarding/resume
Response: {
  success: true,
  message: "Onboarding resumed",
  data: {
    current_step: "business_profile",
    completed_steps: []
  }
}
```

## Database Schema

```sql
CREATE TABLE onboarding_progress (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    user_id BIGINT NOT NULL,
    current_step VARCHAR(255) DEFAULT 'business_profile',
    completed_steps JSON,
    step_data JSON,
    is_completed BOOLEAN DEFAULT FALSE,
    is_skipped BOOLEAN DEFAULT FALSE,
    completed_at TIMESTAMP NULL,
    skipped_at TIMESTAMP NULL,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX (user_id)
);
```

## Testing

### Manual Testing Steps

1. **Register new tenant**

   - Go to `/register`
   - Fill form and submit
   - Should redirect to tenant subdomain

2. **First login**

   - Login with registered credentials
   - Should auto-redirect to `/onboarding`

3. **Complete wizard**

   - Go through each step
   - Fill forms and click Continue
   - Verify progress updates
   - Complete last step
   - Should redirect to dashboard

4. **Skip flow**

   - Start onboarding
   - Click "Skip for now"
   - Confirm skip
   - Should redirect to dashboard
   - Login again - should NOT show wizard

5. **Resume flow** (future)
   - After skipping, go to settings
   - Click "Resume Onboarding"
   - Should show wizard again

### API Testing

```bash
# Get status
curl -H "Authorization: Bearer {token}" \
  http://localhost/api/onboarding/status

# Save step
curl -X POST -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  -d '{"company_display_name":"Test Co"}' \
  http://localhost/api/onboarding/step/business_profile

# Skip
curl -X POST -H "Authorization: Bearer {token}" \
  http://localhost/api/onboarding/skip
```

## Future Enhancements

1. **Resume from Settings**: Add UI in settings to resume skipped onboarding
2. **Enhanced User Step**: Full user creation form with role selection
3. **Logo Upload**: Add image upload for business profile
4. **Progress Persistence**: Save partial form data as user types
5. **Validation**: More robust validation for each step
6. **Analytics**: Track which steps users skip most
7. **Tooltips**: Add helpful tooltips for each field
8. **Preview Mode**: Show what data will be created before submission

## Files Created

### Backend

- `database/migrations/2026_01_25_221217_create_onboarding_progress_table.php`
- `app/Models/User/OnboardingProgress.php`
- `app/Http/Controllers/Api/OnboardingController.php`

### Frontend

- `resources/js/components/Onboarding/OnboardingWizard.tsx`
- `resources/js/components/Onboarding/steps/BusinessProfileStep.tsx`
- `resources/js/components/Onboarding/steps/BranchesStep.tsx`
- `resources/js/components/Onboarding/steps/AdminUsersStep.tsx`
- `resources/js/components/Onboarding/steps/ProductCodingStep.tsx`
- `resources/js/components/Onboarding/steps/PaymentTypesStep.tsx`
- `resources/js/components/Onboarding/steps/VatSettingsStep.tsx`
- `resources/js/stores/onboardingStore.ts`
- `resources/js/services/onboardingService.ts`
- `resources/js/i18n/locales/en/onboarding.json`
- `resources/js/i18n/locales/ar/onboarding.json`

### Modified

- `routes/api.php` - Added onboarding routes
- `app/Http/Controllers/Auth/AuthController.php` - Added onboarding_status to me() response
- `resources/js/App.tsx` - Added /onboarding route
- `resources/js/components/Auth/ProtectedRoute.tsx` - Added onboarding check
- `resources/js/stores/authStore.ts` - Added onboarding_status to User interface
- `resources/js/services/authService.ts` - Updated to fetch onboarding_status

## Deployment Steps

1. **Run migration**:

   ```bash
   php artisan migrate
   ```

2. **Build frontend**:

   ```bash
   npm run react:build
   # or for development
   npm run react:dev
   ```

3. **Clear cache**:

   ```bash
   php artisan cache:clear
   php artisan config:clear
   php artisan route:clear
   ```

4. **Test**: Register a new tenant and verify wizard appears

## Notes

- Onboarding is tracked per user (not per tenant)
- Admin users created during registration will see the wizard on first login
- The wizard uses existing API endpoints where possible (e.g., `/api/admin/stores/create` for branches)
- Step data is stored in JSON for flexibility
- All steps can be enhanced with more fields and validation as needed

---

**Implementation Date**: January 25, 2026  
**Status**: Ready for Testing  
**Version**: 1.0
