# VOZEX Multi-Product Purchase Flow

## Overview

Complete implementation flow for multiple product types in VOZEX marketplace, supporting SaaS, self-hosted, and service-based products with unified checkout and fulfillment.

## 1) Product Types Supported

### SaaS Products (Multi-tenant)
- 🍽 **Restaurant POS** - Complete restaurant management system
- 🏪 **Retail POS** - Retail point of sale with inventory
- 🔧 **Service POS** - Service business management
- 🏨 **Hotel Management** - Hotel booking and management
- 💇 **Salon & Spa** - Appointment scheduling system
- 🏋 **Gym Management** - Membership and facility management
- 🏥 **Clinic Management** - Medical clinic system
- 🍽 **Restaurant Management** - Restaurant without POS hardware

### Self-Hosted Products
- 💻 **Software Downloads** - One-time software licenses
- 🔧 **Development Tools** - Developer tools and libraries
- 📊 **Analytics Platform** - Self-hosted analytics
- 🔒 **Security Tools** - Security and monitoring software

### Service-Based Products
- 🎨 **Design Services** - Graphic design and branding
- 📱 **Mobile Development** - Custom app development
- 🌐 **Web Development** - Website development services
- 🔧 **Technical Support** - IT support and maintenance

## 2) Product Catalog Flow

### 2.1 Product Discovery
```mermaid
graph TD
    A[Customer Visits Marketplace] --> B[Browse Categories]
    B --> C[Filter by Product Type]
    C --> D[View Product Details]
    D --> E[Compare Features & Pricing]
    E --> F[Select Product]
```

### 2.2 Product Display Components
```javascript
// Product Card with Type-Specific Information
const ProductCard = ({ product }) => {
  const productType = getProductTypeConfig(product.product_type);
  
  return (
    <div className="product-card">
      {/* Product Header */}
      <div className="product-header">
        <span className="product-icon">{productType.icon}</span>
        <h3>{product.name}</h3>
        <span className="product-type-badge">{productType.name}</span>
      </div>
      
      {/* Product Description */}
      <p className="product-description">{product.description}</p>
      
      {/* Type-Specific Features */}
      <div className="product-features">
        {productType.features.map(feature => (
          <div key={feature} className="feature-item">
            <span className="feature-icon">✓</span>
            <span>{formatFeatureName(feature)}</span>
          </div>
        ))}
      </div>
      
      {/* Pricing Display */}
      <div className="product-pricing">
        <div className="price">${product.base_price}</div>
        <div className="billing-cycle">/{product.billing_cycle}</div>
      </div>
      
      {/* Call-to-Action */}
      <button 
        onClick={() => navigateToCheckout(product)}
        className="product-cta"
      >
        Get Started
      </button>
    </div>
  );
};
```

### 2.3 Category Navigation
```javascript
// Category-based product filtering
const ProductCategories = () => {
  const categories = [
    {
      id: 'saas_products',
      name: 'SaaS Products',
      icon: '☁️',
      description: 'Cloud-based software solutions',
      productTypes: ['pos_restaurant', 'pos_retail', 'hotel_management', 'salon_spa', 'gym_management']
    },
    {
      id: 'self_hosted',
      name: 'Self-Hosted',
      icon: '💻',
      description: 'Download and host yourself',
      productTypes: ['software_download', 'development_tools', 'analytics_platform', 'security_tools']
    },
    {
      id: 'services',
      name: 'Services',
      icon: '🎨',
      description: 'Professional services and consulting',
      productTypes: ['design_services', 'mobile_development', 'web_development', 'technical_support']
    }
  ];
  
  return (
    <div className="category-navigation">
      {categories.map(category => (
        <button
          key={category.id}
          onClick={() => filterByCategory(category.productTypes)}
          className="category-button"
        >
          <span className="category-icon">{category.icon}</span>
          <div>
            <div className="category-name">{category.name}</div>
            <div className="category-description">{category.description}</div>
          </div>
        </button>
      ))}
    </div>
  );
};
```

## 3) Checkout Flow

### 3.1 Checkout Entry Points
```mermaid
graph TD
    A[Product Page] --> B[Click Get Started]
    B --> C{Product Type?}
    C -->|SaaS| D[SaaS Checkout Flow]
    C -->|Self-Hosted| E[Download Checkout Flow]
    C -->|Services| F[Service Checkout Flow]
```

### 3.2 SaaS Product Checkout
```javascript
const SaaSCheckout = ({ product }) => {
  const [config, setConfig] = useState({
    plan: 'basic',
    domain: '',
    features: [],
    billing_cycle: 'monthly'
  });

  return (
    <div className="saas-checkout">
      {/* Plan Selection */}
      <div className="checkout-section">
        <h3>Choose Your Plan</h3>
        <div className="plan-options">
          {product.pricing_plans.map(plan => (
            <div key={plan.id} className="plan-card">
              <h4>{plan.name}</h4>
              <div className="price">${plan.price}/month</div>
              <ul className="plan-features">
                {plan.features.map(feature => (
                  <li key={feature}>{feature}</li>
                ))}
              </ul>
              <button 
                onClick={() => setConfig({...config, plan: plan.id})}
                className={config.plan === plan.id ? 'selected' : ''}
              >
                Select Plan
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* Domain Configuration */}
      <div className="checkout-section">
        <h3>Configure Your Instance</h3>
        <input
          type="text"
          value={config.domain}
          onChange={(e) => setConfig({...config, domain: e.target.value})}
          placeholder="your-instance.vozex.cloud"
        />
        <p className="help-text">
          Leave empty for subdomain: your-instance.vozex.cloud
        </p>
      </div>

      {/* Feature Selection */}
      <div className="checkout-section">
        <h3>Select Features</h3>
        <div className="feature-options">
          {product.available_features.map(feature => (
            <label key={feature.id} className="feature-option">
              <input
                type="checkbox"
                checked={config.features.includes(feature.id)}
                onChange={(e) => toggleFeature(feature.id, e.target.checked)}
              />
              <div>
                <span className="feature-name">{feature.name}</span>
                <span className="feature-price">+${feature.price}/month</span>
              </div>
            </label>
          ))}
        </div>
      </div>

      {/* Billing Cycle */}
      <div className="checkout-section">
        <h3>Billing Cycle</h3>
        <div className="billing-options">
          {['monthly', 'quarterly', 'annual'].map(cycle => (
            <label key={cycle} className="billing-option">
              <input
                type="radio"
                value={cycle}
                checked={config.billing_cycle === cycle}
                onChange={(e) => setConfig({...config, billing_cycle: e.target.value})}
              />
              <div>
                <span className="cycle-name">{cycle.charAt(0).toUpperCase() + cycle.slice(1)}</span>
                {cycle === 'annual' && <span className="discount">Save 20%</span>}
              </div>
            </label>
          ))}
        </div>
      </div>
    </div>
  );
};
```

### 3.3 Self-Hosted Product Checkout
```javascript
const SelfHostedCheckout = ({ product }) => {
  const [config, setConfig] = useState({
    license_type: 'standard',
    support_plan: 'basic',
    updates: '1_year'
  });

  return (
    <div className="self-hosted-checkout">
      {/* License Selection */}
      <div className="checkout-section">
        <h3>License Type</h3>
        <div className="license-options">
          {product.license_types.map(type => (
            <div key={type.id} className="license-card">
              <h4>{type.name}</h4>
              <div className="price">${type.price}</div>
              <div className="description">{type.description}</div>
              <button 
                onClick={() => setConfig({...config, license_type: type.id})}
                className={config.license_type === type.id ? 'selected' : ''}
              >
                Select License
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* Support Plan */}
      <div className="checkout-section">
        <h3>Support & Updates</h3>
        <div className="support-options">
          <label className="support-option">
            <input
              type="radio"
              value="basic"
              checked={config.support_plan === 'basic'}
              onChange={(e) => setConfig({...config, support_plan: e.target.value})}
            />
            <div>
              <span className="plan-name">Basic Support</span>
              <span className="price">+$50/year</span>
            </div>
          </label>
          <label className="support-option">
            <input
              type="radio"
              value="priority"
              checked={config.support_plan === 'priority'}
              onChange={(e) => setConfig({...config, support_plan: e.target.value})}
            />
            <div>
              <span className="plan-name">Priority Support</span>
              <span className="price">+$150/year</span>
            </div>
          </label>
        </div>
      </div>

      {/* Update Period */}
      <div className="checkout-section">
        <h3>Update Period</h3>
        <select
          value={config.updates}
          onChange={(e) => setConfig({...config, updates: e.target.value})}
        >
          <option value="1_year">1 Year Updates</option>
          <option value="lifetime">Lifetime Updates</option>
        </select>
      </div>
    </div>
  );
};
```

### 3.4 Service Product Checkout
```javascript
const ServiceCheckout = ({ product }) => {
  const [config, setConfig] = useState({
    package: 'basic',
    duration: '1_month',
    requirements: '',
    timeline: 'standard'
  });

  return (
    <div className="service-checkout">
      {/* Service Package */}
      <div className="checkout-section">
        <h3>Service Package</h3>
        <div className="package-options">
          {product.service_packages.map(pkg => (
            <div key={pkg.id} className="package-card">
              <h4>{pkg.name}</h4>
              <div className="price">${pkg.price}</div>
              <div className="description">{pkg.description}</div>
              <div className="duration">{pkg.duration}</div>
              <button 
                onClick={() => setConfig({...config, package: pkg.id})}
                className={config.package === pkg.id ? 'selected' : ''}
              >
                Select Package
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* Project Requirements */}
      <div className="checkout-section">
        <h3>Project Requirements</h3>
        <textarea
          value={config.requirements}
          onChange={(e) => setConfig({...config, requirements: e.target.value})}
          placeholder="Describe your project requirements..."
          rows="4"
        />
      </div>

      {/* Timeline */}
      <div className="checkout-section">
        <h3>Project Timeline</h3>
        <div className="timeline-options">
          {['standard', 'expedited', 'rush'].map(timeline => (
            <label key={timeline} className="timeline-option">
              <input
                type="radio"
                value={timeline}
                checked={config.timeline === timeline}
                onChange={(e) => setConfig({...config, timeline: e.target.value})}
              />
              <div>
                <span className="timeline-name">{timeline.charAt(0).toUpperCase() + timeline.slice(1)}</span>
                <span className="timeline-desc">{getTimelineDescription(timeline)}</span>
              </div>
            </label>
          ))}
        </div>
      </div>
    </div>
  );
};
```

## 4) Payment Processing

### 4.1 Unified Payment Gateway Integration
```javascript
const PaymentProcessor = ({ product, config, onPaymentSuccess }) => {
  const [paymentMethod, setPaymentMethod] = useState('dodo');
  const [processing, setProcessing] = useState(false);

  const calculateTotal = () => {
    let total = product.base_price;
    
    // Add plan pricing for SaaS
    if (product.product_type.startsWith('pos_')) {
      const selectedPlan = product.pricing_plans.find(p => p.id === config.plan);
      total += selectedPlan.price;
    }
    
    // Add feature costs
    config.features.forEach(featureId => {
      const feature = product.available_features.find(f => f.id === featureId);
      if (feature) total += feature.price;
    });
    
    // Apply billing cycle discount
    if (config.billing_cycle === 'annual') {
      total *= 0.8; // 20% annual discount
    }
    
    return total;
  };

  const handlePayment = async () => {
    setProcessing(true);
    
    try {
      const paymentData = {
        product_id: product.id,
        product_type: product.product_type,
        configuration: config,
        total_amount: calculateTotal(),
        payment_gateway: paymentMethod,
        billing_cycle: config.billing_cycle
      };

      const response = await api.post('/checkout/create', paymentData);
      
      if (response.data.success) {
        // Redirect to payment gateway
        window.location.href = response.data.checkout_url;
      }
    } catch (error) {
      console.error('Payment processing failed:', error);
    } finally {
      setProcessing(false);
    }
  };

  return (
    <div className="payment-processor">
      <div className="order-summary">
        <h3>Order Summary</h3>
        <div className="line-item">
          <span>{product.name}</span>
          <span>${product.base_price}</span>
        </div>
        {config.plan && (
          <div className="line-item">
            <span>{config.plan} Plan</span>
            <span>${getPlanPrice(product, config.plan)}</span>
          </div>
        )}
        <div className="total">
          <span>Total</span>
          <span>${calculateTotal()}</span>
        </div>
      </div>

      <div className="payment-methods">
        <h3>Payment Method</h3>
        <div className="payment-options">
          <label className="payment-option">
            <input
              type="radio"
              value="dodo"
              checked={paymentMethod === 'dodo'}
              onChange={(e) => setPaymentMethod(e.target.value)}
            />
            <div className="payment-info">
              <img src="/images/dodo-payments.png" alt="Dodo Payments" />
              <span>Credit Card, Bank Transfer</span>
            </div>
          </label>
          <label className="payment-option">
            <input
              type="radio"
              value="paypal"
              checked={paymentMethod === 'paypal'}
              onChange={(e) => setPaymentMethod(e.target.value)}
            />
            <div className="payment-info">
              <img src="/images/paypal.png" alt="PayPal" />
              <span>PayPal, Credit Card</span>
            </div>
          </label>
        </div>
      </div>

      <button
        onClick={handlePayment}
        disabled={processing}
        className="payment-button"
      >
        {processing ? 'Processing...' : `Pay $${calculateTotal()}`}
      </button>
    </div>
  );
};
```

## 5) Post-Purchase Fulfillment Flow

### 5.1 Fulfillment Trigger
```mermaid
graph TD
    A[Payment Success] --> B[Webhook Received]
    B --> C{Product Type?}
    C -->|SaaS| D[Provision Tenant]
    C -->|Self-Hosted| E[Generate License]
    C -->|Services| F[Create Service Order]
    D --> G[Send Tenant Credentials]
    E --> H[Send Download Link]
    F --> I[Assign Service Provider]
```

### 5.2 SaaS Product Fulfillment
```php
// backend/app/Services/Fulfillment/SaaSFulfillmentService.php
class SaaSFulfillmentService
{
    public function fulfill($order, $orderItem, $payment)
    {
        $product = $orderItem->product;
        $config = $orderItem->configuration;
        
        // Create tenant database
        $tenant = $this->createTenant($order, $config);
        
        // Provision tenant with features
        $this->provisionTenant($tenant, $config);
        
        // Send credentials to customer
        $this->sendTenantCredentials($order->customer, $tenant);
        
        // Update fulfillment record
        $fulfillment = FulfillmentRecord::create([
            'order_id' => $order->id,
            'order_item_id' => $orderItem->id,
            'product_id' => $product->id,
            'driver' => 'saas_tenant_provisioning',
            'status' => 'active',
            'external_reference_id' => $tenant->id,
            'external_workspace_url' => $tenant->domains->first()->domain,
            'payload_snapshot' => $config
        ]);
        
        return [
            'success' => true,
            'tenant_id' => $tenant->id,
            'tenant_domain' => $tenant->domains->first()->domain,
            'admin_url' => "https://{$tenant->domains->first()->domain}/admin",
            'fulfillment_id' => $fulfillment->id
        ];
    }

    private function createTenant($order, $config)
    {
        // Use stancl/tenancy to create tenant
        $tenant = Tenant::create([
            'id' => $this->generateTenantId($order),
            'plan' => $config['plan'],
            'customer_id' => $order->customer_id,
            'product_id' => $orderItem->product_id
        ]);
        
        // Create tenant database
        Artisan::call('tenants:create', [
            '--id' => $tenant->id
        ]);
        
        // Run tenant migrations
        Artisan::call('tenants:migrate', [
            '--tenants' => $tenant->id
        ]);
        
        return $tenant;
    }

    private function provisionTenant($tenant, $config)
    {
        // Configure tenant based on selected plan and features
        $tenantDatabase = Tenant::find($tenant->id);
        
        // Seed tenant with basic data
        Artisan::call('tenants:seed', [
            '--tenants' => $tenant->id,
            '--class' => 'TenantSeeder'
        ]);
        
        // Install selected features
        foreach ($config['features'] as $feature) {
            $this->installFeature($tenant, $feature);
        }
        
        // Create admin user for tenant
        $this->createTenantAdmin($tenant, $config);
    }

    private function sendTenantCredentials($customer, $tenant)
    {
        $credentials = [
            'tenant_id' => $tenant->id,
            'domain' => $tenant->domains->first()->domain,
            'admin_url' => "https://{$tenant->domains->first()->domain}/admin",
            'username' => 'admin',
            'temp_password' => $this->generateTempPassword()
        ];
        
        // Send email with credentials
        $customer->notify(new TenantCredentialsNotification($credentials));
        
        // Store credentials securely
        TenantCredential::create([
            'tenant_id' => $tenant->id,
            'customer_id' => $customer->id,
            'credentials' => encrypt(json_encode($credentials)),
            'expires_at' => now()->addDays(7)
        ]);
    }
}
```

### 5.3 Self-Hosted Product Fulfillment
```php
// backend/app/Services/Fulfillment/SelfHostedFulfillmentService.php
class SelfHostedFulfillmentService
{
    public function fulfill($order, $orderItem, $payment)
    {
        $product = $orderItem->product;
        $config = $orderItem->configuration;
        
        // Generate license key
        $license = $this->generateLicense($order, $config);
        
        // Create download link
        $downloadLink = $this->createDownloadLink($license);
        
        // Send download instructions
        $this->sendDownloadInstructions($order->customer, $license, $downloadLink);
        
        // Update fulfillment record
        $fulfillment = FulfillmentRecord::create([
            'order_id' => $order->id,
            'order_item_id' => $orderItem->id,
            'product_id' => $product->id,
            'driver' => 'self_hosted_license',
            'status' => 'active',
            'external_reference_id' => $license->key,
            'payload_snapshot' => $config
        ]);
        
        return [
            'success' => true,
            'license_key' => $license->key,
            'download_url' => $downloadLink,
            'fulfillment_id' => $fulfillment->id
        ];
    }

    private function generateLicense($order, $config)
    {
        return License::create([
            'key' => $this->generateLicenseKey(),
            'product_id' => $orderItem->product_id,
            'customer_id' => $order->customer_id,
            'license_type' => $config['license_type'],
            'support_plan' => $config['support_plan'],
            'updates' => $config['updates'],
            'expires_at' => $this->calculateExpiryDate($config['updates']),
            'features' => $config['features'] ?? []
        ]);
    }

    private function createDownloadLink($license)
    {
        // Generate secure download link
        $token = Str::random(32);
        
        DownloadLink::create([
            'license_id' => $license->id,
            'token' => $token,
            'expires_at' => now()->addHours(24),
            'download_count' => 0,
            'max_downloads' => 5
        ]);
        
        return url("/download/{$token}");
    }
}
```

### 5.4 Service Product Fulfillment
```php
// backend/app/Services/Fulfillment/ServiceFulfillmentService.php
class ServiceFulfillmentService
{
    public function fulfill($order, $orderItem, $payment)
    {
        $product = $orderItem->product;
        $config = $orderItem->configuration;
        
        // Create service order
        $serviceOrder = ServiceOrder::create([
            'order_id' => $order->id,
            'product_id' => $product->id,
            'customer_id' => $order->customer_id,
            'service_package' => $config['package'],
            'requirements' => $config['requirements'],
            'timeline' => $config['timeline'],
            'status' => 'pending_assignment',
            'estimated_completion' => $this->calculateCompletionDate($config['timeline'])
        ]);
        
        // Assign to service provider
        $provider = $this->assignServiceProvider($serviceOrder);
        
        // Notify customer and provider
        $this->notifyServiceAssignment($order->customer, $provider, $serviceOrder);
        
        // Update fulfillment record
        $fulfillment = FulfillmentRecord::create([
            'order_id' => $order->id,
            'order_item_id' => $orderItem->id,
            'product_id' => $product->id,
            'driver' => 'service_fulfillment',
            'status' => 'processing',
            'external_reference_id' => $serviceOrder->id,
            'payload_snapshot' => $config
        ]);
        
        return [
            'success' => true,
            'service_order_id' => $serviceOrder->id,
            'provider_id' => $provider->id,
            'estimated_completion' => $serviceOrder->estimated_completion,
            'fulfillment_id' => $fulfillment->id
        ];
    }

    private function assignServiceProvider($serviceOrder)
    {
        // Find available provider with required skills
        $provider = ServiceProvider::whereHas('skills', function ($query) use ($serviceOrder) {
            $query->whereIn('skill_id', $serviceOrder->product->required_skills);
        })
        ->where('availability', true)
        ->orderBy('rating', 'desc')
        ->first();
        
        if ($provider) {
            $serviceOrder->update([
                'provider_id' => $provider->id,
                'status' => 'assigned',
                'assigned_at' => now()
            ]);
        }
        
        return $provider;
    }
}
```

## 6) Customer Dashboard Integration

### 6.1 Unified Product Management
```javascript
const CustomerDashboard = () => {
  const [activeTab, setActiveTab] = useState('overview');
  
  return (
    <div className="customer-dashboard">
      <div className="dashboard-header">
        <h1>My Products & Services</h1>
        <div className="tab-navigation">
          <button 
            className={activeTab === 'overview' ? 'active' : ''}
            onClick={() => setActiveTab('overview')}
          >
            Overview
          </button>
          <button 
            className={activeTab === 'saas' ? 'active' : ''}
            onClick={() => setActiveTab('saas')}
          >
            SaaS Products
          </button>
          <button 
            className={activeTab === 'licenses' ? 'active' : ''}
            onClick={() => setActiveTab('licenses')}
          >
            Licenses
          </button>
          <button 
            className={activeTab === 'services' ? 'active' : ''}
            onClick={() => setActiveTab('services')}
          >
            Services
          </button>
        </div>
      </div>

      <div className="dashboard-content">
        {activeTab === 'overview' && <ProductOverview />}
        {activeTab === 'saas' && <SaaSDashboard />}
        {activeTab === 'licenses' && <LicenseDashboard />}
        {activeTab === 'services' && <ServiceDashboard />}
      </div>
    </div>
  );
};
```

### 6.2 SaaS Product Dashboard
```javascript
const SaaSDashboard = () => {
  const [tenants, setTenants] = useState([]);
  
  return (
    <div className="saas-dashboard">
      <h2>Your SaaS Instances</h2>
      <div className="tenant-grid">
        {tenants.map(tenant => (
          <div key={tenant.id} className="tenant-card">
            <div className="tenant-header">
              <h3>{tenant.product_name}</h3>
              <span className={`status-badge ${tenant.status}`}>
                {tenant.status.replace('_', ' ')}
              </span>
            </div>
            
            <div className="tenant-info">
              <div className="info-item">
                <span className="label">Domain:</span>
                <a href={`https://${tenant.domain}`} target="_blank">
                  {tenant.domain}
                </a>
              </div>
              <div className="info-item">
                <span className="label">Plan:</span>
                <span>{tenant.plan}</span>
              </div>
              <div className="info-item">
                <span className="label">Created:</span>
                <span>{formatDate(tenant.created_at)}</span>
              </div>
            </div>
            
            <div className="tenant-actions">
              <a href={`https://${tenant.domain}/admin`} className="admin-button">
                Open Admin
              </a>
              <button className="settings-button">
                Settings
              </button>
              <button className="support-button">
                Get Support
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
```

## 7) Implementation Checklist

### Phase 1: Product Catalog (Week 1)
- [ ] Create product type configuration system
- [ ] Implement product category navigation
- [ ] Build product display components
- [ ] Add product filtering and search
- [ ] Test product discovery flow

### Phase 2: Checkout System (Week 2)
- [ ] Implement SaaS checkout flow
- [ ] Create self-hosted checkout flow
- [ ] Build service checkout flow
- [ ] Integrate payment gateways
- [ ] Test checkout end-to-end

### Phase 3: Fulfillment System (Week 3)
- [ ] Create SaaS tenant provisioning service
- [ ] Build self-hosted license generation
- [ ] Implement service order assignment
- [ ] Set up webhook processing
- [ ] Test fulfillment flows

### Phase 4: Customer Dashboard (Week 4)
- [ ] Build unified customer dashboard
- [ ] Create SaaS tenant management
- [ ] Implement license tracking
- [ ] Add service order monitoring
- [ ] Test customer experience

### Phase 5: Admin Management (Week 5)
- [ ] Create multi-product admin interface
- [ ] Build fulfillment monitoring
- [ ] Add analytics and reporting
- [ ] Implement bulk operations
- [ ] Test admin workflows

## 8) Database Schema Updates

### 8.1 Products Table Extensions
```sql
ALTER TABLE products ADD COLUMN product_type VARCHAR(50) NULL AFTER delivery_model;
ALTER TABLE products ADD COLUMN pricing_plans JSON NULL AFTER fulfillment_config;
ALTER TABLE products ADD COLUMN available_features JSON NULL AFTER pricing_plans;
ALTER TABLE products ADD COLUMN license_types JSON NULL AFTER available_features;
ALTER TABLE products ADD COLUMN service_packages JSON NULL AFTER license_types;
ALTER TABLE products ADD COLUMN required_skills JSON NULL AFTER service_packages;

CREATE INDEX idx_products_type ON products(product_type);
CREATE INDEX idx_products_delivery_model ON products(delivery_model, product_type);
```

### 8.2 New Tables
```sql
-- Tenant credentials storage
CREATE TABLE tenant_credentials (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    tenant_id VARCHAR(255) NOT NULL,
    customer_id BIGINT NOT NULL,
    credentials TEXT NOT NULL,
    expires_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (customer_id) REFERENCES users(id),
    INDEX idx_tenant_credentials_tenant (tenant_id),
    INDEX idx_tenant_credentials_customer (customer_id)
);

-- License management
CREATE TABLE licenses (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    key VARCHAR(255) UNIQUE NOT NULL,
    product_id BIGINT NOT NULL,
    customer_id BIGINT NOT NULL,
    license_type VARCHAR(50) NOT NULL,
    support_plan VARCHAR(50) NULL,
    updates VARCHAR(50) NOT NULL,
    features JSON NULL,
    expires_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (product_id) REFERENCES products(id),
    FOREIGN KEY (customer_id) REFERENCES users(id),
    INDEX idx_licenses_key (key),
    INDEX idx_licenses_customer (customer_id),
    INDEX idx_licenses_product (product_id)
);

-- Download links
CREATE TABLE download_links (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    license_id BIGINT NOT NULL,
    token VARCHAR(255) UNIQUE NOT NULL,
    expires_at TIMESTAMP NOT NULL,
    download_count INT DEFAULT 0,
    max_downloads INT DEFAULT 5,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (license_id) REFERENCES licenses(id),
    INDEX idx_download_links_token (token),
    INDEX idx_download_links_license (license_id)
);

-- Service orders
CREATE TABLE service_orders (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    order_id BIGINT NOT NULL,
    product_id BIGINT NOT NULL,
    customer_id BIGINT NOT NULL,
    provider_id BIGINT NULL,
    service_package VARCHAR(100) NOT NULL,
    requirements TEXT NULL,
    timeline VARCHAR(50) NOT NULL,
    status VARCHAR(50) DEFAULT 'pending_assignment',
    estimated_completion TIMESTAMP NULL,
    assigned_at TIMESTAMP NULL,
    completed_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (order_id) REFERENCES orders(id),
    FOREIGN KEY (product_id) REFERENCES products(id),
    FOREIGN KEY (customer_id) REFERENCES users(id),
    FOREIGN KEY (provider_id) REFERENCES users(id),
    INDEX idx_service_orders_customer (customer_id),
    INDEX idx_service_orders_status (status),
    INDEX idx_service_orders_provider (provider_id)
);
```

## 9) Success Metrics

### 9.1 Key Performance Indicators
- Product catalog conversion rate
- Checkout completion rate
- Payment success rate
- Fulfillment processing time
- Customer satisfaction scores
- Support ticket resolution time

### 9.2 Monitoring Requirements
- Real-time order status tracking
- Payment gateway health monitoring
- Fulfillment service performance
- Customer engagement metrics
- Revenue analytics by product type

---

This comprehensive flow enables VOZEX to handle multiple product types seamlessly, providing a unified marketplace experience for SaaS, self-hosted, and service-based products with proper fulfillment and customer management.
