# Salesforce Requirements & Setup Guide

This document describes the Salesforce configuration required for the Customer Portal integration.

---

## Table of Contents

1. [Overview](#overview)
2. [Required Objects & Fields](#required-objects--fields)
3. [Platform Events](#platform-events)
4. [Record-Triggered Flows](#record-triggered-flows)
5. [Connected App (JWT Auth)](#connected-app-jwt-auth)
6. [Integration User Permissions](#integration-user-permissions)
7. [Data Flow Summary](#data-flow-summary)

---

## Overview

The Customer Portal integrates with Salesforce for:

- **Customer Data** – Account, Contact information
- **Order Management** – Order creation, approval, and tracking
- **Opportunity Lifecycle** – Sales pipeline and service lifecycle tracking
- **Eligibility & Verification** – Internet eligibility checks, ID verification status
- **Support Cases** – Eligibility requests, cancellation requests, support tickets

### Integration Architecture

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         SALESFORCE                                       │
│                                                                          │
│  ┌──────────────┐    ┌───────────────────┐    ┌───────────────────────┐ │
│  │   Objects    │    │  Platform Events  │    │  Record-Triggered     │ │
│  │              │    │                   │    │  Flows                │ │
│  │  • Account   │    │  OrderProvision   │    │                       │ │
│  │  • Contact   │    │  Requested__e     │    │  • On Order Approved  │ │
│  │  • Order     │    │                   │    │    → Publish Event    │ │
│  │  • Opportunity│   │                   │    │                       │ │
│  │  • Case      │    │                   │    │                       │ │
│  └──────────────┘    └───────────────────┘    └───────────────────────┘ │
│         ▲                     │                                          │
│         │                     ▼                                          │
└─────────┼─────────────────────┼──────────────────────────────────────────┘
          │                     │
          │ REST API            │ Pub/Sub gRPC
          │ (jsforce)           │ (salesforce-pubsub-api-client)
          │                     │
          ▼                     ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                         PORTAL BFF (NestJS)                              │
│                                                                          │
│  ┌───────────────────────┐    ┌───────────────────────────────────────┐ │
│  │  SalesforceService    │    │  Platform Events Subscriber           │ │
│  │                       │    │                                       │ │
│  │  • Query/Update       │    │  • Subscribes to OrderProvision...    │ │
│  │  • Create Orders      │    │  • Enqueues provisioning job          │ │
│  │  • Create Cases       │    │  • Durable replay (Redis)             │ │
│  └───────────────────────┘    └───────────────────────────────────────┘ │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘
```

---

## Required Objects & Fields

### Account Object

The Account stores customer information and status fields.

#### Standard Fields Used

| Field            | API Name           | Purpose                      |
| ---------------- | ------------------ | ---------------------------- |
| Account Name     | `Name`             | Customer name                |
| Customer Number  | `SF_Account_No__c` | Unique customer identifier   |
| WHMCS Account ID | `WH_Account__c`    | Link to WHMCS billing system |

#### Custom Fields Required

**Internet Eligibility Fields:**

| Field              | API Name                                    | Type          | Purpose                |
| ------------------ | ------------------------------------------- | ------------- | ---------------------- |
| Eligibility Value  | `Internet_Eligibility__c`                   | Text/Picklist | The eligibility result |
| Eligibility Status | `Internet_Eligibility_Status__c`            | Picklist      | `Pending`, `Checked`   |
| Request Date       | `Internet_Eligibility_Request_Date_Time__c` | DateTime      | When request was made  |
| Checked Date       | `Internet_Eligibility_Checked_Date_Time__c` | DateTime      | When checked by CS     |

**Notes:**

- The portal does **not** require Account-level fields for a Case ID or agent notes.
- Agent notes should live in the **Case Description** / Case activity history.

**ID Verification Fields:**

| Field             | API Name                                 | Type      | Purpose                           |
| ----------------- | ---------------------------------------- | --------- | --------------------------------- |
| Status            | `Id_Verification_Status__c`              | Picklist  | `Pending`, `Verified`, `Rejected` |
| Submitted Date    | `Id_Verification_Submitted_Date_Time__c` | DateTime  | When documents submitted          |
| Verified Date     | `Id_Verification_Verified_Date_Time__c`  | DateTime  | When verified                     |
| Notes             | `Id_Verification_Note__c`                | Text Area | Agent notes                       |
| Rejection Message | `Id_Verification_Rejection_Message__c`   | Text      | Reason if rejected                |

**Portal Status Fields:**

| Field               | API Name                        | Type     | Purpose                 |
| ------------------- | ------------------------------- | -------- | ----------------------- |
| Portal Status       | `Portal_Status__c`              | Picklist | `Active`, `Inactive`    |
| Registration Source | `Portal_Registration_Source__c` | Picklist | How customer registered |

**Portal Registration Source Picklist Values:**

- `Legacy` – Existing customer before portal
- `Portal Signup` – Standard portal registration
- `Portal Checkout` – Registered during checkout

---

### Order Object

Orders represent customer purchases.

#### Standard Fields Used

| Field          | API Name        | Purpose                     |
| -------------- | --------------- | --------------------------- |
| Order Number   | `OrderNumber`   | Auto-generated order number |
| Account        | `AccountId`     | Linked customer account     |
| Opportunity    | `OpportunityId` | Linked opportunity          |
| Status         | `Status`        | Order status                |
| Effective Date | `EffectiveDate` | Order date                  |

#### Custom Fields Required

| Field                 | API Name                       | Type     | Purpose                    |
| --------------------- | ------------------------------ | -------- | -------------------------- |
| Activation Status     | `Activation_Status__c`         | Picklist | Portal provisioning status |
| Activation Error      | `Activation_Error__c`          | Text     | Error message if failed    |
| Activation Error Time | `Activation_Error_DateTime__c` | DateTime | When error occurred        |
| WHMCS Order ID        | `WHMCS_Order_Id__c`            | Number   | WHMCS order reference      |

**Activation Status Picklist Values:**

- `Pending Review` – Awaiting CS approval
- `Activating` – Being provisioned to WHMCS
- `Provisioned` – Successfully provisioned
- `Failed` – Provisioning failed

**Order Status Picklist Values:**

- `Draft` – Order being created
- `Pending Review` – Awaiting approval
- `Approved` – Approved by CS (triggers provisioning)
- `Activated` – Successfully activated
- `Cancelled` – Order cancelled

---

### Opportunity Object

Opportunities track the customer lifecycle from lead to active service.

#### Standard Fields Used

| Field      | API Name    | Purpose             |
| ---------- | ----------- | ------------------- |
| Stage      | `StageName` | Opportunity stage   |
| Account    | `AccountId` | Linked account      |
| Close Date | `CloseDate` | Expected close date |

#### Custom Fields Required

| Field              | API Name                | Type     | Purpose                     |
| ------------------ | ----------------------- | -------- | --------------------------- |
| Commodity Type     | `CommodityType`         | Picklist | Product type                |
| Application Stage  | `Application_Stage__c`  | Picklist | Internal CS workflow        |
| Opportunity Source | `Opportunity_Source__c` | Picklist | How opportunity was created |
| WHMCS Service ID   | `WHMCS_Service_ID__c`   | Number   | Link to WHMCS service       |

**Internet Cancellation Fields:**

| Field                  | API Name                              | Type     | Purpose                       |
| ---------------------- | ------------------------------------- | -------- | ----------------------------- |
| Cancellation Notice    | `CancellationNotice__c`               | Picklist | Internet cancellation status  |
| Scheduled Cancellation | `ScheduledCancellationDateAndTime__c` | DateTime | Internet cancellation date    |
| Line Return Status     | `LineReturn__c`                       | Picklist | Equipment return status (ONU) |

**SIM Cancellation Fields:**

| Field                      | API Name                                 | Type     | Purpose                 |
| -------------------------- | ---------------------------------------- | -------- | ----------------------- |
| SIM Cancellation Notice    | `SIMCancellationNotice__c`               | Picklist | SIM cancellation status |
| SIM Scheduled Cancellation | `SIMScheduledCancellationDateAndTime__c` | DateTime | SIM cancellation date   |

_Note: SIM customer comments are stored on the Cancellation Case, same as Internet._

**Stage Picklist Values (Customer Journey):**

1. `Introduction` – Initial inquiry/eligibility request
2. `Ready` – Eligible and ready to order
3. `Post Processing` – Order placed, being processed
4. `Active` – Service is active
5. `△Cancelling` – Cancellation requested
6. `△Cancelled` – Service cancelled
7. `Void` – Not eligible or abandoned

**Commodity Type Picklist Values:**

- `Personal SonixNet Home Internet`
- `Corporate SonixNet Home Internet`
- `SIM`
- `VPN`

**Opportunity Source Picklist Values:**

- `Portal - Internet Eligibility Request`
- `Portal - Order Placement`
- `Sales - Manual`

---

### Case Object

Cases are used for customer requests and support tickets.

#### Fields Used

| Field       | API Name        | Purpose                            |
| ----------- | --------------- | ---------------------------------- |
| Subject     | `Subject`       | Case subject                       |
| Description | `Description`   | Case details                       |
| Type        | `Type`          | Case type                          |
| Status      | `Status`        | Case status                        |
| Account     | `AccountId`     | Customer account                   |
| Opportunity | `OpportunityId` | Linked opportunity (if applicable) |

**Case Type Values (Portal-Created):**

- `Eligibility Check` – Internet eligibility request
- `ID Verification` – Manual ID verification review
- `Cancellation Request` – Service cancellation
- `General Inquiry` – Support ticket

---

### OrderItem Object

Order line items with product details.

#### Fields Used

| Field      | API Name     | Purpose           |
| ---------- | ------------ | ----------------- |
| Order      | `OrderId`    | Parent order      |
| Product2   | `Product2Id` | Product reference |
| Quantity   | `Quantity`   | Item quantity     |
| Unit Price | `UnitPrice`  | Item price        |

---

### Product2 Object

Product catalog synchronized from Salesforce.

#### Custom Fields Required

| Field               | API Name                       | Type      | Purpose                           |
| ------------------- | ------------------------------ | --------- | --------------------------------- |
| WHMCS Product ID    | `WHMCS_Product_Id__c`          | Text      | WHMCS product mapping             |
| Billing Cycle       | `Billing_Cycle__c`             | Picklist  | `Monthly`, `Annually`, `One-time` |
| Item Class          | `Item_Class__c`                | Picklist  | `Service`, `Activation`, `Add-on` |
| Config Options JSON | `Portal_ConfigOptions_JSON__c` | Long Text | WHMCS config options              |

---

## Platform Events

### OrderProvisionRequested\_\_e

High-Volume Platform Event for order provisioning.

**Purpose:** Notifies the portal when an order is approved and ready for WHMCS provisioning.

#### Event Fields

| Field           | API Name           | Type     | Required | Purpose                      |
| --------------- | ------------------ | -------- | -------- | ---------------------------- |
| Order ID        | `OrderId__c`       | Text(18) | Yes      | Salesforce Order ID          |
| Idempotency Key | `IdemKey__c`       | Text(80) | No       | Prevent duplicate processing |
| Correlation ID  | `CorrelationId__c` | Text(80) | No       | Request tracing              |
| Requested By    | `RequestedBy__c`   | Text(80) | No       | User who approved            |
| Version         | `Version__c`       | Number   | No       | Event schema version         |

#### Event Retention

- **Retention Period:** 72 hours (default for High-Volume Platform Events)
- **Replay:** Portal uses durable replay to resume from last processed event

---

## Record-Triggered Flows

### Order Approval Flow

**Trigger:** Record-Triggered Flow on Order object

**Entry Conditions:**

- `Status` changed to `Approved`
- OR `Activation_Status__c` changed to `Activating` (for retry)

**Actions:**

1. **Update Order Fields:**

   ```
   Activation_Status__c = "Activating"
   Activation_Error__c = null
   Activation_Error_DateTime__c = null
   ```

2. **Create Platform Event:**
   ```
   Create Record: OrderProvisionRequested__e
   OrderId__c = {!$Record.Id}
   IdemKey__c = {!$Record.Id} + "-" + {!$Flow.CurrentDateTime}
   ```

**Flow Diagram:**

```
┌─────────────────────────────────────────────────────────────────────────┐
│              ORDER APPROVAL FLOW (Record-Triggered)                      │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  TRIGGER: Order Status changed to "Approved"                             │
│           OR Activation_Status__c changed to "Activating"                │
│                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐│
│  │ 1. UPDATE ORDER                                                      ││
│  │    └─ Activation_Status__c = "Activating"                            ││
│  │    └─ Activation_Error__c = null                                     ││
│  │    └─ Activation_Error_DateTime__c = null                            ││
│  └─────────────────────────────────────────────────────────────────────┘│
│                           │                                              │
│                           ▼                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐│
│  │ 2. CREATE PLATFORM EVENT                                             ││
│  │    └─ OrderProvisionRequested__e                                     ││
│  │    └─ OrderId__c = Order.Id                                          ││
│  │    └─ IdemKey__c = Order.Id + timestamp                              ││
│  └─────────────────────────────────────────────────────────────────────┘│
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘
```

---

## Connected App (JWT Auth)

The portal authenticates to Salesforce using JWT Bearer Flow.

### Connected App Settings

| Setting         | Value                                     |
| --------------- | ----------------------------------------- |
| Name            | `Customer Portal Integration`             |
| OAuth Scopes    | `api`, `refresh_token`, `offline_access`  |
| Certificate     | Upload public certificate                 |
| Permitted Users | `Admin approved users are pre-authorized` |

### Pre-Authorized Profile/User

Assign the integration user to the Connected App.

### Environment Variables (Portal)

```bash
SF_LOGIN_URL=https://login.salesforce.com  # or https://test.salesforce.com for sandbox
SF_CLIENT_ID=<connected_app_consumer_key>
SF_USERNAME=integration.user@company.com
SF_PRIVATE_KEY_PATH=/path/to/private-key.pem
# OR base64 encoded:
SF_PRIVATE_KEY_BASE64=<base64_encoded_private_key>
```

---

## Integration User Permissions

### Required Object Permissions

| Object         | Create | Read | Update | Delete |
| -------------- | ------ | ---- | ------ | ------ |
| Account        | ✅     | ✅   | ✅     | ❌     |
| Contact        | ✅     | ✅   | ✅     | ❌     |
| Order          | ✅     | ✅   | ✅     | ❌     |
| OrderItem      | ✅     | ✅   | ✅     | ❌     |
| Opportunity    | ✅     | ✅   | ✅     | ❌     |
| Case           | ✅     | ✅   | ✅     | ❌     |
| Product2       | ❌     | ✅   | ❌     | ❌     |
| PricebookEntry | ❌     | ✅   | ❌     | ❌     |

### Required Field-Level Security

All custom fields listed above must be **Visible** and **Editable** (where applicable) for the integration user's profile.

### Platform Event Permissions

| Event                        | Subscribe | Publish             |
| ---------------------------- | --------- | ------------------- |
| OrderProvisionRequested\_\_e | ✅        | ❌ (Flow publishes) |

### API Limits

- **Daily API Requests:** Ensure sufficient API call limits
- **Platform Event Allocations:** High-Volume Platform Events have separate limits

---

## Data Flow Summary

### 1. Customer Registration

```
Portal → Salesforce
├─ Create Account (if new)
├─ Create Contact
└─ Update Portal_Status__c = "Active"
```

### 2. Internet Eligibility Request

```
Portal → Salesforce
├─ Find/Create Opportunity (Stage: Introduction)
├─ Create Case (Type: Eligibility Check)
└─ Update Account eligibility status = "Pending"

CS Action (Manual) → Salesforce
├─ Update Account eligibility result
└─ Update Opportunity stage (Ready or Void)
```

### 3. Order Placement

```
Portal → Salesforce
├─ Find/Create Opportunity (Stage: Post Processing)
├─ Create Order (Status: Pending Review)
└─ Create OrderItems
```

### 4. Order Approval & Provisioning

```
CS Action → Salesforce
└─ Update Order Status = "Approved"

Salesforce Flow → Platform Event
└─ Publish OrderProvisionRequested__e

Portal BFF (Subscriber)
├─ Receive event
├─ Provision to WHMCS
├─ Update Order (Provisioned/Failed)
└─ Update Opportunity (Stage: Active, WHMCS_Service_ID__c)
```

### 5. Cancellation Request

```
Portal → Salesforce
├─ Create Case (Type: Cancellation Request)
├─ Find Opportunity (via WHMCS_Service_ID__c)
├─ Update Opportunity Stage = "△Cancelling"
└─ Set ScheduledCancellationDateAndTime__c

CS Action (Manual)
└─ Process cancellation in WHMCS
```

---

## Checklist for Salesforce Setup

### Objects & Fields

- [ ] All Account custom fields created
- [ ] All Order custom fields created
- [ ] All Opportunity custom fields created
- [ ] Product2 WHMCS mapping fields created

### Platform Events

- [ ] `OrderProvisionRequested__e` event created
- [ ] Event fields configured

### Flows

- [ ] Order Approval Flow created and activated
- [ ] Flow publishes Platform Event on Order approval

### Security

- [ ] Connected App created with JWT settings
- [ ] Certificate uploaded
- [ ] Integration user created
- [ ] Profile permissions assigned
- [ ] Field-Level Security configured
- [ ] Platform Event subscribe permission granted

### Testing

- [ ] Test order approval → event published
- [ ] Test portal subscription → event received
- [ ] Test full provisioning flow end-to-end

---

## Related Documentation

- [Salesforce Order Communication](./SALESFORCE-ORDER-COMMUNICATION.md) – Detailed order flow
- [Opportunity Lifecycle Guide](./OPPORTUNITY-LIFECYCLE-GUIDE.md) – Opportunity stages and matching
- [Salesforce-WHMCS Mapping](./SALESFORCE-WHMCS-MAPPING-REFERENCE.md) – Data mapping reference
