# Setup

Delpha Email Insight helps you extract valuable insights from emails and link them directly to your Salesforce contacts.\
This guide explains how to set it up and how to use the provided Apex class for processing emails.

## Add Insights to Contact Page (Optional)

To view insights directly on the Contact record:

1. Go to **Setup > Object Manager > Contact > Page Layouts**.
2. Edit your active layout.
3. In the **Related Lists** section, drag & drop **“D Insight”** into the layout.
4. Customize the columns to display useful fields:
   * D Type
   * D Value
   * D Score
   * D Status
5. Save and return to a Contact record → the related list will now appear.

## Activate the Copy Flow (Optional)

A prebuilt Salesforce Flow named **“Delpha Copy Insight Value to Contact”** is included.

* When active, it copies values from Insights to Contact fields (if conditions are met).
* Default rules:
  * The Contact field is empty.
  * The Insight score is **≥ 70**.

**Steps to activate:**

1. Go to **Setup > Flows**.
2. Open the flow **“Delpha Copy Insight Value to Contact”**.
3. Review the “Should Copy” blocks (adjust if needed).
4. Click **Activate** (top-right).

## Using the DDQ\_InsightEmail Apex Class

The class **`DDQ_InsightEmail`** handles sending email text to Delpha servers and storing insights in Salesforce.

**Processing flow:**

1. Send query to Delpha server.
2. Receive response and create **`delpha__DDQ_ContactInsight__c`** records.
3. If the Copy Flow is active and conditions are met → Contact fields get updated automatically.

⚠️ Only **plain text emails** are supported (`EmailMessage.TextBody`).\
HTML bodies (`EmailMessage.HtmlBody`) may cause incomplete or incorrect results.

### 🔹 Single Mode (1 Contact)

```apex
Id contactId = '<contactId>';
String emailBody = 'Full body of your email message';

delpha.DDQ_InsightEmail.getInsights(contactId, emailBody);
```

* 1 API call.
* Up to 3 insights inserted.
* May update the Contact.
* ❌ Cannot call more than once per transaction.

### 🔹 Batch Mode (Up to 10 Contacts)

```apex
List<delpha.DDQ_InsightEmail.EmailInsightInput> inputs = new List<>();

delpha.DDQ_InsightEmail.EmailInsightInput input1 = new delpha.DDQ_InsightEmail.EmailInsightInput();
input1.contactId = '<contactId>';
input1.emailBody = 'Full email body';
inputs.add(input1);

// Repeat for up to 10 inputs

delpha.DDQ_InsightEmail.getInsights(inputs);
```

* 1 API call for all inputs.
* Up to 3 insights per input.
* May update associated Contacts.
* ❌ Cannot call more than once per transaction.

### 🔹 Batch Mode (More than 10 Contacts – up to 500)

* Works the same as above, but if more than 10 inputs are passed:
  * The class creates a **Salesforce Batch Job**.
  * Records are processed 10 at a time.
  * ✅ Can be called up to 50 times per transaction.
  * ❌ Cannot be called from inside another Batch.

***

### 📄 Code Snippets

#### Retrieve Emails Linked to Contacts

```apex
List<EmailMessageRelation> relations = [
  SELECT EmailMessage.TextBody, RelationId 
  FROM EmailMessageRelation 
  WHERE RelationId != NULL 
  LIMIT 500
];

List<delpha.DDQ_InsightEmail.EmailInsightInput> inputs = new List<>();

for(EmailMessageRelation r : relations) {
    delpha.DDQ_InsightEmail.EmailInsightInput input = new delpha.DDQ_InsightEmail.EmailInsightInput();
    input.contactId = r.RelationId;
    input.emailBody = r.EmailMessage.TextBody;
    inputs.add(input);
}
```

***

#### Retrieve Emails Linked to Cases

```apex
List<Id> caseIds = <your case list>;

// Query cases with emails
List<Case> casesWithEmails = [
  SELECT Id, ContactId, (SELECT Id, TextBody FROM EmailMessages) 
  FROM Case 
  WHERE Id IN :caseIds
];

// Build inputs
List<delpha.DDQ_InsightEmail.EmailInsightInput> inputs = new List<>();
for(Case c : casesWithEmails) {
  if(c.ContactId == null || c.EmailMessages == null) continue;

  for(EmailMessage m : c.EmailMessages) {
    delpha.DDQ_InsightEmail.EmailInsightInput input = new delpha.DDQ_InsightEmail.EmailInsightInput();
    input.contactId = c.ContactId;
    input.emailBody = m.TextBody;
    inputs.add(input);
  }
}
```

***

## ✅ Summary

* **Admins**: Add related list & activate the copy flow.
* **Developers**: Use the `DDQ_InsightEmail` class (single, batch ≤10, batch ≤500) to process emails.
* **Limitations**: Plain text only, transaction limits apply.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.delpha.io/delpha-for-salesforce/use-cases-setup/email-insight/setup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
