> ## Documentation Index
> Fetch the complete documentation index at: https://developers.pleo.io/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Sync Accounts

export const FetchAndMatchAccountsDiagram = () => {
  const [isDark, setIsDark] = useState(false);
  useEffect(() => {
    const check = () => setIsDark(document.documentElement.classList.contains("dark"));
    check();
    const observer = new MutationObserver(check);
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["class"]
    });
    return () => observer.disconnect();
  }, []);
  const nodeFill = isDark ? "#212222" : "#EEF4F4";
  const nodeStroke = isDark ? "#848989" : "#E1E6E6";
  const nodeTextStyle = isDark ? ",color:#EEF4F4" : ",color:#131414";
  const s4Fill = isDark ? "#212222" : "#EEF4F4";
  const s4Stroke = isDark ? "#848989" : "#212222";
  const s4TextStyle = isDark ? ",color:#EEF4F4" : ",color:#212222";
  const linkStyle = isDark ? "" : "linkStyle default stroke:#848989,stroke-width:1px;";
  const diagram = `
%%{init: {"themeVariables": {"fontSize": "20px"}}}%%
flowchart LR
    S1["1. Fetch Active Accounts from AS"] --> S2["2. Fetch All Accounts from Pleo"] --> S3["3. Match by externalId"] --> S4["Create, Update,\nand Archive Accounts"]

click S1 "#1-retrieve-active-accounts-from-the-accounting-system"
click S2 "#2-retrieve-all-accounts-from-pleo"
click S3 "#3-match-as-accounts-to-pleo-accounts-by-externalid"

style S1 white-space:normal,fill:${nodeFill},stroke:${nodeStroke}${nodeTextStyle}
style S2 white-space:normal,fill:${nodeFill},stroke:${nodeStroke}${nodeTextStyle}
style S3 white-space:normal,fill:${nodeFill},stroke:${nodeStroke}${nodeTextStyle}
style S4 white-space:normal,fill:${s4Fill},stroke:${s4Stroke},stroke-dasharray:5 5${s4TextStyle}
${linkStyle}
`;
  return <Mermaid chart={diagram} />;
};

export const CoASyncWorkflowDiagramTopNav = ({highlight}) => {
  const [isDark, setIsDark] = useState(false);
  useEffect(() => {
    const check = () => setIsDark(document.documentElement.classList.contains("dark"));
    check();
    const observer = new MutationObserver(check);
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["class"]
    });
    return () => observer.disconnect();
  }, []);
  const nodeFill = isDark ? "#212222" : "#EEF4F4";
  const nodeStroke = isDark ? "#848989" : "#E1E6E6";
  const nodeTextStyle = isDark ? ",color:#EEF4F4" : ",color:#131414";
  const subgraphFill = isDark ? "#131414" : "#ffffff";
  const subgraphStroke = isDark ? "#848989" : "#6B7070";
  const subgraphTextStyle = isDark ? ",color:#EEF4F4" : ",color:#6B7070";
  const linkStyle = isDark ? "" : "linkStyle default stroke:#848989,stroke-width:1px;";
  const highlightStyle = highlight ? `style ${highlight} stroke:#FEB6FE,stroke-width:2px` : "";
  const shape = (id, label) => `${id}["${label}"]`;
  const diagram = `
%%{init: {"themeVariables": {"fontSize": "14px"}}}%%
flowchart LR

subgraph AS["Accounting System"]
    ${shape("source", "Chart of Accounts")}
end

subgraph Pleo["Pleo APIs"]
    ${shape("A", "1. Fetch and Match Accounts")}
    ${shape("B", "2. Create, Update, and Archive Accounts")}
    A --> B
end

source --> A

click A "/docs/current/how-tos/accounting-integrations/imports/accounts/how-to-sync-accounts"
click B "/docs/current/how-tos/accounting-integrations/imports/accounts/how-to-create-update-archive-accounts"

style A white-space:normal,fill:${nodeFill},stroke:${nodeStroke}${nodeTextStyle}
style B white-space:normal,fill:${nodeFill},stroke:${nodeStroke}${nodeTextStyle}
style source white-space:normal,fill:${nodeFill},stroke:${nodeStroke}${nodeTextStyle}
style AS fill:${subgraphFill},stroke:${subgraphStroke}${subgraphTextStyle}
style Pleo fill:${subgraphFill},stroke:${subgraphStroke}${subgraphTextStyle}

${highlightStyle}
${linkStyle}
`;
  return <Mermaid chart={diagram} />;
};

export const WhatComesNext = ({children, href}) => <div className="mt-4">
    <a href={href} className="btn-primary">
      {children} →
    </a>
  </div>;

export const RememberCallout = ({title, children}) => <div className="callout-box callout-remember">
    <div className="callout-row">
      <span className="callout-icon">
        <svg width="22" height="22" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M229.66,98.34,172.39,155.8c11.46,22.93-1.72,45.86-10.11,57a8,8,0,0,1-12,.83L42.34,105.76A8,8,0,0,1,43,93.85c29.65-23.92,57.4-10,57.4-10l57.27-57.46a8,8,0,0,1,11.31,0L229.66,87A8,8,0,0,1,229.66,98.34Z" opacity="0.2" /><path d="M235.32,81.37,174.63,20.69a16,16,0,0,0-22.63,0L98.37,74.49c-10.66-3.34-35-7.37-60.4,13.14a16,16,0,0,0-1.29,23.78L85,159.71,42.34,202.34a8,8,0,0,0,11.32,11.32L96.29,171l48.29,48.29A16,16,0,0,0,155.9,224c.38,0,.75,0,1.13,0a15.93,15.93,0,0,0,11.64-6.33c19.64-26.1,17.75-47.32,13.19-60L235.33,104A16,16,0,0,0,235.32,81.37ZM224,92.69h0l-57.27,57.46a8,8,0,0,0-1.49,9.22c9.46,18.93-1.8,38.59-9.34,48.62L48,100.08c12.08-9.74,23.64-12.31,32.48-12.31A40.13,40.13,0,0,1,96.81,91a8,8,0,0,0,9.25-1.51L163.32,32,224,92.68Z" /></svg>
      </span>
      <div>
        {title && <div className="callout-title">
            {title}
          </div>}
        <div className="callout-body">
          {children}
        </div>
      </div>
    </div>
  </div>;

<CoASyncWorkflowDiagramTopNav highlight="A" />

<div className="border-[1px] rounded-none p-4 bg-[#ffffff] border-[#FEB6FE] dark:bg-[#131414] dark:border-[#FEB6FE]">
  <FetchAndMatchAccountsDiagram />
</div>

This how-to covers the fetch and match phase of Chart of Accounts Sync: retrieving accounts from the Accounting System and Pleo, then determining what action is needed for each. For the write operations, see [How to Create, Update, and Archive Accounts](/docs/current/how-tos/accounting-integrations/imports/accounts/how-to-create-update-archive-accounts).

Your integration must:

* Retrieve active accounts from the AS
* Retrieve all Accounts (active and archived) from Pleo
* Match AS accounts to Pleo Accounts by `externalId` to determine what action is needed

## Prerequisites

Before you begin:

* You're familiar with the [Chart of Accounts Sync Overview](/docs/current/integration-design/accounting-integrations/imports/accounts/integration-design-accounts-overview) and the [Integration Design for Syncing Accounts](/docs/current/integration-design/accounting-integrations/imports/accounts/integration-design-accounts-sync)
* Your integration is authenticated using one of the [supported authentication methods](/docs/current/integration-design/auth/integration-design-auth-overview#authentication-policy-overview)
* Your integration can call Pleo's Chart of Accounts API endpoints

## Scenario

This how-to uses a consistent example to illustrate each step. The table below shows the starting state in both systems before this sync runs.

| Account (AS)           | externalId | AS Status | Account (Pleo)         | Pleo Status    |
| ---------------------- | ---------- | --------- | ---------------------- | -------------- |
| 1000 - Office Supplies | ext-1000   | Active    | 1000 - Office Supplies | Active         |
| 2000 - Travel          | ext-2000   | Active    | 2000 - Travel          | Archived       |
| 3000 - Software        | ext-3000   | Active    | —                      | Does not exist |
| 4000 - Marketing       | ext-4000   | Active    | 4000 - Advertising     | Active         |
| —                      | 5000       | —         | 5000 - Entertainment   | Active         |

## Steps

### 1. Retrieve Active Accounts from the Accounting System

Fetch all active accounts from the Chart of Accounts in the AS.

**Example Pseudo:**

```pseudo theme={null}
activeASAccounts = fetchActiveAccountsFromAS()
```

#### Example Result

| Account                | externalId | AS Status |
| ---------------------- | ---------- | --------- |
| 1000 - Office Supplies | ext-1000   | Active    |
| 2000 - Travel          | ext-2000   | Active    |
| 3000 - Software        | ext-3000   | Active    |
| 4000 - Marketing       | ext-4000   | Active    |

***

### 2. Retrieve All Accounts from Pleo

**API Endpoint**: POST [`/v1/chart-of-accounts:search`](/reference/accounts/fetch-a-list-of-accounts)

**Example parameters:**

* companyId: `12abc3d4-e567-890e-1234-abc56e78fabc`
* includeArchived: `true`

Fetch both active and archived Accounts from Pleo. Including archived Accounts allows unarchiving rather than creating duplicates.

**Example Pseudo:**

```pseudo theme={null}
pleoAccounts = fetchAccountsFromPleo(includeArchived: true)
```

#### Example Request

<Tabs>
  <Tab title="OAuth 2.0">
    ```bash theme={null}
    curl -X POST "https://external.staging.pleo.io/v1/chart-of-accounts:search" \
      -H "Authorization: Bearer <access_token>" \
      -H "Content-Type: application/json" \
      -d '{
            "companyId": "12abc3d4-e567-890e-1234-abc56e78fabc",
            "includeArchived": true
          }'
    ```
  </Tab>

  <Tab title="API Key">
    ```bash theme={null}
    curl --request POST \
      -u "pls_1ab2cd3e4f5g6h7a89b012c34de56f78_gabc90:" \
      -H "Accept: application/json;charset=UTF-8" \
      -H "Content-Type: application/json" \
      "https://external.staging.pleo.io/v1/chart-of-accounts:search" \
      -d '{
            "companyId": "12abc3d4-e567-890e-1234-abc56e78fabc",
            "includeArchived": true
          }' \
    | jq
    ```
  </Tab>
</Tabs>

#### Example Response

```json theme={null}
{
  "data": [
    {
      "id": "7ea2006f-180e-4c52-a2bb-562d3a62fd48",
      "companyId": "12abc3d4-e567-890e-1234-abc56e78fabc",
      "code": "5000",
      "externalId": "5000",
      "name": "Entertainment",
      "archived": false
    },
    {
      "id": "a470bfbe-8046-4b43-a4d9-4f5796acdd93",
      "companyId": "12abc3d4-e567-890e-1234-abc56e78fabc",
      "code": "4000",
      "externalId": "ext-4000",
      "name": "Advertising",
      "archived": false
    },
    {
      "id": "d8371c2d-3f62-47df-a8d6-6a3ba6387e00",
      "companyId": "12abc3d4-e567-890e-1234-abc56e78fabc",
      "code": "2000",
      "externalId": "ext-2000",
      "name": "Travel",
      "archived": true
    },
    {
      "id": "77049275-e102-4ce4-84e5-c90852765fcd",
      "companyId": "12abc3d4-e567-890e-1234-abc56e78fabc",
      "code": "1000",
      "externalId": "ext-1000",
      "name": "Office Supplies",
      "archived": false
    }
  ],
  "pagination": {
    "hasPreviousPage": false,
    "hasNextPage": false,
    "currentRequestPagination": {
      "sortingKeys": [],
      "sortingOrder": [],
      "parameters": {}
    },
    "startCursor": "AAAAAADKHEEOIDOJO34A=AAAAAADKHEEOIDOJO34A=P2RAA3YYBZGFFIV3KYWTUYX5JA",
    "endCursor": "AAAAAADKCVM2UIAPLIEA=AAAAAADKHEETOMBB2K4A=BLNKLWE6ZBBDLLU24XGZ4GAFAI",
    "total": 4
  }
}
```

#### Example Result

| Account (Pleo)         | externalId | Pleo Status |
| ---------------------- | ---------- | ----------- |
| 1000 - Office Supplies | ext-1000   | Active      |
| 2000 - Travel          | ext-2000   | Archived    |
| 4000 - Advertising     | ext-4000   | Active      |
| 5000 - Entertainment   | 5000       | Active      |

#### What it looks like in Pleo Web App

<div style={{ textAlign: "center" }}>
  <img src="https://mintcdn.com/pleo-61d4d38b/VP2WvZ7pPDGk7Esn/images/current/accounting-integrations/imports/chart-of-accounts/ui-chart-of-accounts-tab-active.png?fit=max&auto=format&n=VP2WvZ7pPDGk7Esn&q=85&s=f2ca2646fd5043359b34cca0e95c8581" alt="Active Accounts Tab" width="100%" style={{ display: "block", margin: "0 auto" }} data-path="images/current/accounting-integrations/imports/chart-of-accounts/ui-chart-of-accounts-tab-active.png" />
</div>

<br />

<div style={{ textAlign: "center" }}>
  <img src="https://mintcdn.com/pleo-61d4d38b/VP2WvZ7pPDGk7Esn/images/current/accounting-integrations/imports/chart-of-accounts/ui-chart-of-accounts-tab-archived.png?fit=max&auto=format&n=VP2WvZ7pPDGk7Esn&q=85&s=5e1b64869ce2c41e67925aebd4c84e58" alt="Unarchived Accounts Tab" width="100%" style={{ display: "block", margin: "0 auto" }} data-path="images/current/accounting-integrations/imports/chart-of-accounts/ui-chart-of-accounts-tab-archived.png" />
</div>

***

### 3. Match AS Accounts to Pleo Accounts by externalId

For each active AS account, attempt to find a matching Account in Pleo using `externalId`.

**Example Pseudo:**

```pseudo theme={null}
pleoAccountsByExternalId = index pleoAccounts by externalId

for account in activeASAccounts:
    matchedAccount = pleoAccountsByExternalId[account.externalId]

    if matchedAccount is null:
        createAccount(account)
    else if matchedAccount.archived == true:
        unarchiveAndUpdate(matchedAccount, account)
    else if matchedAccount.name != account.name or matchedAccount.code != account.code:
        updateAccount(matchedAccount, account)
    // else: no action needed
```

#### Example Result

| AS Account             | Pleo Account           | Pleo Status     | Action    |
| ---------------------- | ---------------------- | --------------- | --------- |
| 1000 - Office Supplies | 1000 - Office Supplies | Active, matches | No action |
| 2000 - Travel          | 2000 - Travel          | Archived        | Unarchive |
| 3000 - Software        | —                      | Does not exist  | Create    |
| 4000 - Marketing       | 4000 - Advertising     | Active, differs | Update    |
| —                      | 5000 - Entertainment   | Active          | Archive   |

***

## What Comes Next?

<WhatComesNext href="/docs/current/how-tos/accounting-integrations/imports/accounts/how-to-create-update-archive-accounts">
  How to Create, Update, and Archive Accounts
</WhatComesNext>

***

<div className="text-xs uppercase" style={{ fontVariant: 'small-caps' }}>
  this how-to is part of:
</div>

<div className="mt-4 flex flex-wrap gap-2">
  <a
    href="/docs/current/guides/accounting-integrations/imports/accounts-sync-workflow-guide"
    className="inline-flex items-center rounded-full border border-gray-300 dark:border-gray-600
px-3 py-1 text-xs font-medium
bg-white dark:bg-[#1f262b] text-black dark:text-white
hover:bg-gray-100 dark:hover:bg-[#2b2f33]
transition-colors"
  >
    Chart of Accounts Sync Workflow Guide
  </a>
</div>

***

## Related Reading

* [How to Create, Update, and Archive Accounts](/docs/current/how-tos/accounting-integrations/imports/accounts/how-to-create-update-archive-accounts)
* [Sync Accounts Integration Design](/docs/current/integration-design/accounting-integrations/imports/accounts/integration-design-accounts-sync)
* [Data Mapping](/docs/current/integration-design/accounting-integrations/imports/accounts/integration-design-accounts-data-mapping)
* [Platform Capabilities: Chart of Accounts Sync](/docs/current/platform/accounting-integrations/imports/accounts/accounts-sync-overview)

***
