# Twenty CRM Integration for HoaLedgerIQ Sales Lead Monitor

## API Configuration

- **Base URL:** `https://salesforce.hoaledgeriq.com/rest`
- **Auth Header:** `Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5M2FmNGFmNS0zZWQ0LTQ1ZDMtOWE5Zi01MDMzZjc3YTY3MjMiLCJ0eXBlIjoiQVBJX0tFWSIsIndvcmtzcGFjZUlkIjoiOTNhZjRhZjUtM2VkNC00NWQzLTlhOWYtNTAzM2Y3N2E2NzIzIiwiaWF0IjoxNzczMzI4NDQzLCJleHAiOjE4MDQ3ODE2NDIsImp0aSI6IjIwZjEyYzkwLTRkMDctNGJmNi1iMzk3LTZjNmU3MzlmMThjOCJ9.zeM5NvwCSGEcz99m2LYtgb0sVD6WUXcCF7SwonFg930`
- **Owner ID:** `ecf52aad-4827-40c9-9475-b68f3ca9a924`

## Lead Sources

### 1. ROI Calculator Submissions
**Endpoint:** `GET https://hoaledgeriq.com/api/calc-submissions`

**Headers:**
```
x-admin-key: K9mP2vL8x4qR7nZ
```

**Response Fields:**
- `email` - Lead email address
- `homesites` - Number of homesites
- `annual_income` - Estimated annual income
- `property_type` - Type of property
- `payment_freq` - Payment frequency
- `reserve_funds` - Reserve funds amount
- `interest_2025` - Interest calculation
- `total_potential` - Total potential value
- `opt_in` - Whether user opted in
- `ai_recommendation` - AI-generated recommendation
- `created_at` - Submission timestamp

### 2. Direct Lead Form (localhost:3000)
**Endpoint:** `GET http://localhost:3000/api/leads`

**Headers:**
```
x-admin-key: K9mP2vL8x4qR7nZ
```

*Note: This endpoint is only available when the dev server is running locally.*

## CRM Create Flow: Calc Submission → Notes → Sales Review → Opportunity

Updated flow based on your sales process:
1. Leads go to **Notes** attached to People (not Opportunities)
2. Sales team reviews Notes and decides who to qualify
3. Qualified leads get promoted to Opportunities

### Previous Flow (Opportunity-first) - DEPRECATED

The integration previously created Opportunities directly. Now leads are queued in Notes for review.

### Step 1: Check if Person Exists

```bash
curl -s "https://salesforce.hoaledgeriq.com/rest/people" \
  -H "Authorization: Bearer <token>"
```

Filter response for matching email.

### Step 2: Create Person (if not exists)

```bash
curl -s -X POST "https://salesforce.hoaledgeriq.com/rest/people" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": {
      "firstName": "<email_local_part>",
      "lastName": "(Lead)"
    },
    "emails": {
      "primaryEmail": "<email>",
      "additionalEmails": []
    }
  }'
```

Returns person ID (e.g., `2c28136a-2ba1-4234-be50-0130da851d3e`)

### Step 3: Create Note (Lead Queue)

```bash
curl -s -X POST "$TWENTY_BASE/notes" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Lead: <email> | <homesites> homes | $<annual_income>/y",
    "body": "## 🏘️ ROI Calculator Lead\n\n**Email:** <email>\n**Homesites:** <homesites>\n...",
    "personId": "<person_id>"
  }'
```

Note goes to your Notes/Lead Review area in Twenty. Sales team promotes to Opportunity when qualified.

```bash
curl -s -X POST "https://salesforce.hoaledgeriq.com/rest/opportunities" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "ROI Calc - <email>",
    "stage": "NEW",
    "amount": {
      "amountMicros": <annual_income * 1000000>,
      "currencyCode": "USD"
    },
    "closeDate": "<date_90_days_from_now>",
    "pointOfContactId": "<person_id>",
    "ownerId": "ecf52aad-4827-40c9-9475-b68f3ca9a924"
  }'
```

## Field Mappings

### Calc Submission → CRM

| Source Field | CRM Field | Notes |
|--------------|-----------|-------|
| email | Person.emails.primaryEmail | Primary identifier |
| email (before @) | Person.name.firstName | Parsed from email |
| "(Lead)" | Person.name.lastName | Default value |
| annual_income | Opportunity.amount.amountMicros | Multiplied by 1,000,000 |
| created_at + 90 days | Opportunity.closeDate | Auto-calculated |
| "NEW" | Opportunity.stage | Default stage |
| "ROI Calc - {email}" | Opportunity.name | Auto-generated |

### Calc Details → Opportunity Notes

Additional calc fields saved as notes:
- Homesites count
- Property type  
- Payment frequency
- Reserve funds
- 2025 interest
- Total potential
- AI recommendation

## State Tracking

File: `/Users/claw/.openclaw/workspace/agents/sales-lead/state.json`

```json
{
  "processed_leads": ["local_lead_id_1", "local_lead_id_2"],
  "processed_calc_ids": [1, 2, 3, 4],
  "crm_pushed": {
    "calc_ids": [1],
    "lead_ids": []
  },
  "last_check": "2026-03-12T13:00:00Z",
  "status": "active"
}
```

## Testing

Test person created: `2c28136a-2ba1-4234-be50-0130da851d3e`
Test opportunity created: Validated working
