---
created: 2026-03-12
source: Rivet
tags: [agent-archive, rivet]
---

# Growth Engine to RateRight Platform Integration Specification

## 1. Integration Overview

### Data Flow Between Systems
The integration enables bidirectional data synchronization between RateRight's contractor marketplace and Growth Engine's lead management system, supporting the full contractor lifecycle from acquisition to revenue tracking.

**Primary Data Flows:**
- **Outbound from RateRight:** Contractor profiles, job postings, hires, payments
- **Inbound to RateRight:** Lead conversions, campaign attribution, growth metrics
- **Bidirectional:** User identity mapping, status updates, engagement tracking

### Authentication Approach
- **Growth Engine API:** API key authentication via `X-API-Key` header
- **RateRight Webhooks:** HMAC signature verification using shared secret
- **RateRight API:** OAuth 2.0 client credentials flow for service-to-service calls
- **Token Management:** Automatic refresh with 5-minute buffer before expiry

### Sync Frequency
- **Real-time (webhooks):** Lead conversions, new contractors, job status changes
- **Near real-time (1-5 min):** Payment processing, profile updates
- **Batch (hourly):** Analytics data, engagement metrics, campaign performance
- **Daily:** Revenue reconciliation, attribution calculations

## 2. Data Mappings

### Growth Engine Lead → RateRight Contractor
```json
{
  "growth_engine": {
    "lead_id": "ge_lead_123",
    "email": "contractor@example.com",
    "phone": "+61400123456",
    "first_name": "John",
    "last_name": "Smith",
    "trade": "electrician",
    "location": {
      "suburb": "Sydney",
      "state": "NSW",
      "postcode": "2000"
    },
    "source": "facebook_campaign",
    "campaign_id": "fb_123",
    "lead_score": 85,
    "custom_fields": {
      "experience_years": 5,
      "license_number": "EC123456",
      "preferred_work_radius": 25
    }
  },
  "rateright_mapping": {
    "user_id": "rr_user_456",
    "profile_status": "pending_verification",
    "verification_priority": "high",
    "onboarding_step": "license_upload"
  }
}
```

### RateRight Job Posting → Growth Engine Activity
```json
{
  "rateright": {
    "job_id": "rr_job_789",
    "title": "Residential Electrical Installation",
    "description": "Full house wiring for new construction",
    "trade": "electrician",
    "location": {
      "suburb": "Bondi",
      "state": "NSW",
      "postcode": "2026"
    },
    "budget": 5000,
    "timeline": "2 weeks",
    "property_type": "residential",
    "job_type": "installation"
  },
  "growth_engine_mapping": {
    "activity_id": "ge_act_321",
    "activity_type": "job_posted",
    "lead_id": "ge_lead_123",
    "value": 5000,
    "attributes": {
      "job_category": "residential",
      "urgency": "standard",
      "contractor_match_score": 92
    }
  }
}
```

### RateRight Hire → Growth Engine Conversion
```json
{
  "rateright": {
    "hire_id": "rr_hire_555",
    "job_id": "rr_job_789",
    "contractor_id": "rr_user_456",
    "hire_date": "2024-01-15T10:30:00Z",
    "completion_date": "2024-01-29T16:00:00Z",
    "total_value": 5000,
    "status": "completed",
    "rating": 5
  },
  "growth_engine_mapping": {
    "conversion_id": "ge_conv_999",
    "lead_id": "ge_lead_123",
    "conversion_value": 5000,
    "conversion_date": "2024-01-15T10:30:00Z",
    "attribution": {
      "campaign_id": "fb_123",
      "source": "facebook_campaign",
      "medium": "paid_social"
    },
    "metrics": {
      "time_to_convert": 7,
      "customer_lifetime_value": 15000
    }
  }
}
```

### RateRight Payment → Growth Engine Revenue Tracking
```json
{
  "rateright": {
    "payment_id": "rr_pay_777",
    "hire_id": "rr_hire_555",
    "amount": 5000,
    "platform_fee": 500,
    "contractor_payout": 4500,
    "payment_date": "2024-01-30T09:00:00Z",
    "payment_method": "bank_transfer",
    "status": "completed"
  },
  "growth_engine_mapping": {
    "revenue_id": "ge_rev_888",
    "conversion_id": "ge_conv_999",
    "gross_revenue": 5000,
    "platform_revenue": 500,
    "revenue_date": "2024-01-30T09:00:00Z",
    "revenue_type": "platform_fee",
    "attribution": {
      "campaign_id": "fb_123",
      "roi": 5.0,
      "cac": 100
    }
  }
}
```

## 3. API Endpoints Needed

### Growth Engine Endpoints to Call

#### Lead Management
- `POST /api/v1/leads` - Create new lead from RateRight signup
- `PUT /api/v1/leads/{id}` - Update lead information
- `GET /api/v1/leads/{id}` - Retrieve lead details
- `POST /api/v1/leads/{id}/convert` - Mark lead as converted

#### Activity Tracking
- `POST /api/v1/activities` - Log contractor activities
- `GET /api/v1/activities/{lead_id}` - Get activity timeline

#### Revenue Tracking
- `POST /api/v1/revenue` - Record revenue from completed jobs
- `PUT /api/v1/revenue/{id}` - Update revenue records

#### Analytics
- `GET /api/v1/analytics/campaigns/{id}` - Get campaign performance
- `GET /api/v1/analytics/attribution` - Get attribution data

### RateRight Webhooks to Expose

#### Contractor Events
- `POST /webhooks/contractor/created` - New contractor signup
- `POST /webhooks/contractor/updated` - Profile updates
- `POST /webhooks/contractor/verified` - Verification completion

#### Job Events
- `POST /webhooks/job/created` - New job posting
- `POST /webhooks/job/updated` - Job modifications
- `POST /webhooks/job/awarded` - Contractor selected

#### Transaction Events
- `POST /webhooks/payment/completed` - Payment processed
- `POST /webhooks/dispute/created` - Dispute initiated
- `POST /webhooks/refund/processed` - Refund issued

### Error Handling and Retry Logic

#### Retry Configuration
```json
{
  "max_retries": 5,
  "retry_delay": "exponential",
  "initial_delay_ms": 1000,
  "max_delay_ms": 30000,
  "backoff_multiplier": 2,
  "retryable_status_codes": [429, 500, 502, 503, 504]
}
```

#### Error Categories
- **Transient Errors (retry):** Network timeouts, 5xx server errors, rate limits
- **Permanent Errors (no retry):** 4xx client errors, authentication failures
- **Business Errors (alert):** Data validation failures, state conflicts

#### Dead Letter Queue
- Failed messages after max retries go to DLQ
- Manual review required for DLQ items
- Alert notification sent to operations team

## 4. User Experience Flows

### Flow 1: Contractor Signs Up in RateRight → Appears in Growth Engine
1. User completes RateRight signup form
2. RateRight creates user profile and triggers webhook
3. Integration service receives webhook and validates data
4. Service calls Growth Engine API to create lead
5. Growth Engine returns lead ID and tracking information
6. Integration stores mapping between RateRight user and Growth Engine lead
7. User receives welcome email with next steps

### Flow 2: Lead Converted in Growth Engine → Auto-invite to RateRight
1. Growth Engine marks lead as qualified
2. Triggers webhook to RateRight integration service
3. Service checks if user exists in RateRight
4. If not exists, creates pre-verified account
5. Sends invitation email with magic link
6. User clicks link and completes RateRight onboarding
7. Updates Growth Engine with conversion status

### Flow 3: Job Posted in RateRight → Tracked in Growth Engine
1. Customer posts job on RateRight platform
2. RateRight creates job posting and triggers webhook
3. Integration service receives job details
4. Maps job to relevant contractors in Growth Engine
5. Creates activity records for matched leads
6. Updates contractor profiles with job opportunities
7. Tracks engagement metrics for campaign optimization

### Flow 4: Hire Completed → Updates Growth Engine Lead Status
1. Customer hires contractor through RateRight
2. RateRight updates job status to "completed"
3. Triggers webhook with hire and payment details
4. Integration service processes completion data
5. Updates Growth Engine lead status to "converted"
6. Records revenue and attribution data
7. Calculates ROI for originating campaign

## 5. Technical Implementation Notes

### Database Schema Changes

#### New Tables in RateRight
```sql
-- Growth Engine mapping table
CREATE TABLE growth_engine_mappings (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  rateright_user_id UUID NOT NULL REFERENCES users(id),
  growth_engine_lead_id VARCHAR(255) UNIQUE NOT NULL,
  mapping_type VARCHAR(50) NOT NULL, -- 'lead', 'conversion', 'revenue'
  metadata JSONB DEFAULT '{}',
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  UNIQUE(rateright_user_id, mapping_type)
);

-- Webhook events tracking
CREATE TABLE webhook_events (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  event_type VARCHAR(100) NOT NULL,
  payload JSONB NOT NULL,
  status VARCHAR(50) DEFAULT 'pending',
  retry_count INTEGER DEFAULT 0,
  error_message TEXT,
  processed_at TIMESTAMP WITH TIME ZONE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Integration configuration
CREATE TABLE integration_configs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  service_name VARCHAR(100) UNIQUE NOT NULL,
  config_data JSONB NOT NULL,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```

### Background Job Processing

#### Queue Configuration
- **Redis-based job queue** for reliable processing
- **Separate queues** for different event types
- **Priority processing** for revenue-related events
- **Rate limiting** to respect API quotas

#### Job Types
1. **Lead Sync Jobs** - Sync contractor data to Growth Engine
2. **Activity Jobs** - Track job posting and engagement
3. **Conversion Jobs** - Process hire completions
4. **Revenue Jobs** - Sync payment and revenue data
5. **Retry Jobs** - Handle failed operations

### Monitoring and Logging

#### Key Metrics to Track
- API response times and success rates
- Webhook delivery success rate
- Data sync latency
- Error rates by type and endpoint
- Revenue attribution accuracy

#### Alerting Thresholds
- Webhook failure rate > 5%
- API response time > 2 seconds
- Queue backlog > 1000 jobs
- Error rate > 1% for revenue operations
- Data sync delay > 10 minutes

#### Log Structure
```json
{
  "timestamp": "2024-01-15T10:30:00Z",
  "level": "info",
  "service": "growth-engine-integration",
  "trace_id": "uuid",
  "span_id": "uuid",
  "event": "lead_sync_completed",
  "data": {
    "lead_id": "ge_lead_123",
    "user_id": "rr_user_456",
    "duration_ms": 250
  }
}
```

### Security Considerations
- All API calls use TLS 1.3 minimum
- Webhook payloads signed with HMAC-SHA256
- API keys stored in encrypted secrets manager
- Rate limiting per API key
- PII data encrypted at rest
- Audit logs for all data transfers

### Deployment Strategy
1. **Feature flags** for gradual rollout
2. **Blue-green deployment** for zero downtime
3. **Circuit breakers** for external service failures
4. **Database migration** scripts versioned
5. **Rollback procedures** documented and tested