# Facebook Ads

## Getting Started

1. **Sign In:** A Facebook login window will appear, sign in and proceed to granting permissions
2. **Grant Permissions:** Review the requested permissions, such as access to your ad accounts and campaigns. Click **Allow** to grant the necessary permissions.
3. **Confirmation:** After granting permissions, you'll be redirected back to the ad reporting platform, confirming the successful connection

## What Data Gets Tracked as Metadata

The following fields are tracked and stored during the integration process:

| **Field**           | **Description**                                                       |
| ------------------- | --------------------------------------------------------------------- |
| `account_id_hashed` | A hashed version of the account ID for secure storage.                |
| `type`              | The type of tracked data, such as `paid-ads`.                         |
| `date`              | The date of the ad activity, formatted as `YYYY-MM-DD`.               |
| `id`                | A unique identifier for each data row, generated as an MD5 hash.      |
| `metadata`          | A JSON object containing detailed metadata about the campaign and ad. |
| `account_id`        | The original account ID associated with the ad.                       |
| `network`           | The advertising network, such as `Facebook Ads`.                      |
| `campaign_id`       | The unique ID of the campaign.                                        |
| `adgroup_id`        | The unique ID of the ad group.                                        |
| `ad_id`             | The unique ID of the ad.                                              |
| `campaign_name`     | The name of the campaign.                                             |
| `adgroup_name`      | The name of the ad group.                                             |
| `ad_name`           | The name of the ad.                                                   |
| `utm_source`        | The source of the traffic, such as `facebook`.                        |
| `utm_campaign`      | The campaign name, URL-encoded if necessary.                          |
| `utm_medium`        | The medium of the traffic, such as `paid`.                            |
| `utm_content`       | Content-specific identifier for the campaign.                         |
| `utm_term`          | The keyword associated with the campaign, if applicable.              |
| `impressions`       | The total number of impressions for the ad.                           |
| `clicks`            | The total number of clicks for the ad.                                |
| `cost`              | The total cost of the ad campaign in the specified currency.          |
| `currency`          | The currency in which the ad costs are measured (e.g., `USD`).        |

## High-Level Integration Flow

1. **Validate Integration**:
   * Ensure the `integration` object contains required fields like `facebookUserId` and `accessToken`.
2. **Fetch Ad Accounts**:
   * Retrieve ad accounts linked to the user’s `facebookUserId` using `facebookApiRequest`.
   * Handle token expiration or invalid tokens by marking the integration as expired.
3. **Retrieve Currencies**:
   * Fetch account currencies using `fetchAccountCurrencies`.
   * Update stored currencies with the `updateCurrencies` function.
4. **Process Ad Accounts**:
   * Iterate through all ad accounts in the integration object.
   * Skip accounts marked as `paused` to optimize processing.
5. **Fetch Insights and Ads**:
   * Fetch ad insights (e.g., impressions, clicks, and spend) for a specific date range.
   * Retrieve associated ad data and format it for storage.
6. **Process Lead Forms**:
   * Identify and process any lead forms linked to ads using `fetchLeads`.
   * Create lead actions from submissions and store them.

## Tracking Lead Forms

The integration tracks Facebook lead form submissions and creates a **"Facebook Lead Form Submit"** action that can be used as part of Goal building

**Action Properties Tracked**:

| **Field**                | **Description**                                |
| ------------------------ | ---------------------------------------------- |
| `facebook_lead_id`       | Unique identifier for the Facebook lead.       |
| `facebook_form_id`       | Identifier for the lead form submitted.        |
| `facebook_campaign_name` | Name of the campaign associated with the lead. |
| `facebook_campaign_id`   | Unique ID of the campaign.                     |
| `facebook_adgroup_name`  | Name of the ad group associated with the lead. |
| `facebook_adgroup_id`    | Unique ID of the ad group.                     |
| `facebook_ad_name`       | Name of the ad generating the lead.            |
| `facebook_ad_id`         | Unique ID of the ad.                           |
| `facebook_creative_name` | Name of the creative asset used in the ad.     |
| `facebook_creative_id`   | Unique ID of the creative asset.               |
| `utm_source`             | Traffic source, defaulting to `facebook`.      |
| `utm_medium`             | Traffic medium, defaulting to `paid`.          |
| `utm_campaign`           | Encoded campaign name for tracking.            |
| `submitted_at`           | Timestamp when the lead form was submitted.    |

**Company Properties Tracked**:

| **Field**      | **Description**                       |
| -------------- | ------------------------------------- |
| `company_name` | The name of the company, if provided. |

**Other Properties Tracked**:

| **Field**            | **Description**                                                        |
| -------------------- | ---------------------------------------------------------------------- |
| `userId`             | Email address of the user, derived from the lead form.                 |
| `identity`           | Same as `userId`, used for identifying the user.                       |
| `session_start_date` | Timestamp of when the lead form submission occurred.                   |
| `actionDate`         | JavaScript `Date` object representation of the lead submission time.   |
| `actionType`         | Always set to `custom` for lead forms.                                 |
| `actionName`         | Always set to `Facebook Lead Form Submit`.                             |
| `shared`             | Additional metadata including submission ID and associated properties. |

## Notes and Caveats

* **Token Expiration**:
  * Handle authentication errors (codes `190` and `102`) by marking the integration as expired and prompting re-authentication.
* **Rate Limits**:
  * For rate limit errors (`error code 17`), retry up to 3 times with exponential backoff.
* **Large Data Requests**:
  * Split date ranges or reduce data volume for errors related to excessive data (`error code 1`).
* **Default Processing Period**:
  * The integration processes the last 28 days by default, with adjustments for specific accounts as needed.
* **Batch Limits**:
  * Data is processed in batches of 1000 records to optimize performance.
* **Campaign Name Tracking**:
  * Track and handle changes in campaign names to ensure data consistency.
