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

# ContaAzul as a data source

> Bring data from ContaAzul to Nekt.

ContaAzul is a financial management platform designed for small businesses in Brazil. It provides tools for invoicing, expense tracking, cash flow management, and integration with banks and accountants to simplify business finances. The ContaAzul API enables access to your financial data including payables, receivables, sales, products, services, and contacts.

<img height="50" src="https://mintcdn.com/nekt/43FsQ37QF_gxIqKI/assets/logo/logo-conta-azul.png?fit=max&auto=format&n=43FsQ37QF_gxIqKI&q=85&s=3d8a4af1b58522ce326bd9e2d91e4f6c" data-path="assets/logo/logo-conta-azul.png" />

## Configuring ContaAzul as a Source

In the [Sources](https://app.nekt.ai/sources) tab, click on the "Add source" button located on the top right of your screen. Then, select the ContaAzul option from the list of connectors.

Click **Next** and you'll be prompted to add your access.

### 1. Add account access

You'll need to authorize Nekt to access your ContaAzul data. Click on the **ContaAzul Authorization** button and log in with your ContaAzul account. Grant the necessary permissions for the company you want to extract data from.

The following configurations are available:

* **Start Date**: The earliest date from which records will be synced. Used as the starting point for incremental streams and as a date filter for financial events.

<Warning>
  Make sure your ContaAzul account has the necessary permissions to access the data you want to extract. The connector requires access to financial, sales, product, and contact APIs depending on which streams you select.
</Warning>

Once you're done, click **Next**.

### 2. Select streams

Choose which data streams you want to sync. For faster extractions, select only the streams that are relevant to your analysis. You can select entire groups of streams or pick specific ones.

> Tip: The stream can be found more easily by typing its name.

Select the streams and click **Next**.

### 3. Configure data streams

Customize how you want your data to appear in your catalog. Select the desired layer where the data will be placed, a folder to organize it inside the layer, a name for each table (which will effectively contain the fetched data) and the type of sync.

* **Layer**: choose between the existing layers on your catalog. This is where you will find your new extracted tables as the extraction runs successfully.
* **Folder**: a folder can be created inside the selected layer to group all tables being created from this new data source.
* **Table name**: we suggest a name, but feel free to customize it. You have the option to add a **prefix** to all tables at once and make this process faster!
* **Sync Type**: you can choose between INCREMENTAL and FULL\_TABLE.
  * Incremental: every time the extraction happens, we'll get only the new data - which is good if, for example, you want to keep every record ever fetched.
  * Full table: every time the extraction happens, we'll get the current state of the data - which is good if, for example, you don't want to have deleted data in your catalog.

Once you are done configuring, click **Next**.

### 4. Configure data source

Describe your data source for easy identification within your organization, not exceeding 140 characters.

To define your [Trigger](https://docs.nekt.com/get-started/core-concepts/triggers), consider how often you want data to be extracted from this source. This decision usually depends on how frequently you need the new table data updated (every day, once a week, or only at specific times).

Optionally, you can define some additional settings:

* Configure Delta Log Retention and determine for how long we should store old states of this table as it gets updated. Read more about this resource [here](https://docs.nekt.com/get-started/core-concepts/resource-control).
* Determine when to execute an **Additional [Full Sync](https://docs.nekt.com/get-started/core-concepts/types-of-sync#additional-full-sync)**. This will complement the incremental data extractions, ensuring that your data is completely synchronized with your source every once in a while.

Once you are ready, click **Next** to finalize the setup.

### 5. Check your new source

You can view your new source on the [Sources](https://app.nekt.ai/sources) page. If needed, manually trigger the source extraction by clicking on the arrow button. Once executed, your data will appear in your Catalog.

<Warning>For you to be able to see it on your [Catalog](https://app.nekt.ai/catalog), you need at least one successful source run.</Warning>

# Streams and Fields

Below you'll find all available data streams from ContaAzul and their corresponding fields:

<AccordionGroup>
  <Accordion title="Despesas (Payables)">
    Accounts payable / expense records with status, amounts, and due dates.

    | Field             | Type     | Description                              |
    | :---------------- | :------- | :--------------------------------------- |
    | `id`              | String   | Unique identifier                        |
    | `descricao`       | String   | Description of the expense               |
    | `data_vencimento` | Date     | Due date                                 |
    | `status`          | String   | Payment status                           |
    | `total`           | Number   | Total amount                             |
    | `nao_pago`        | Number   | Unpaid amount                            |
    | `pago`            | Number   | Paid amount                              |
    | `data_criacao`    | DateTime | Creation date                            |
    | `data_alteracao`  | DateTime | Last modification date (replication key) |
  </Accordion>

  <Accordion title="Receitas (Receivables)">
    Accounts receivable / revenue records with status, amounts, and due dates.

    | Field             | Type     | Description                              |
    | :---------------- | :------- | :--------------------------------------- |
    | `id`              | String   | Unique identifier                        |
    | `descricao`       | String   | Description of the receivable            |
    | `data_vencimento` | Date     | Due date                                 |
    | `status`          | String   | Payment status                           |
    | `total`           | Number   | Total amount                             |
    | `nao_pago`        | Number   | Unpaid amount                            |
    | `pago`            | Number   | Paid amount                              |
    | `data_criacao`    | DateTime | Creation date                            |
    | `data_alteracao`  | DateTime | Last modification date (replication key) |
  </Accordion>

  <Accordion title="Parcelas (Installments)">
    Detailed installment data for both payables (despesas) and receivables (receitas). Includes payment breakdowns, financial account info, billing requests, and attachments. This is a child stream fetched for each parent expense or receivable record.

    | Field                     | Type    | Description                                                                                                 |
    | :------------------------ | :------ | :---------------------------------------------------------------------------------------------------------- |
    | `id`                      | String  | Installment identifier                                                                                      |
    | `evento`                  | Object  | Parent financial event with competence date, payment conditions, reference, apportionment details, and type |
    | `versao`                  | Integer | Record version                                                                                              |
    | `referencia`              | String  | Reference code                                                                                              |
    | `indice`                  | Integer | Installment index                                                                                           |
    | `conciliado`              | Boolean | Whether the installment is reconciled                                                                       |
    | `status`                  | String  | Installment status                                                                                          |
    | `valor_pago`              | Number  | Amount paid                                                                                                 |
    | `perda`                   | Object  | Loss details with date and value                                                                            |
    | `nao_pago`                | Number  | Unpaid amount                                                                                               |
    | `data_vencimento`         | String  | Due date                                                                                                    |
    | `data_pagamento_previsto` | String  | Expected payment date                                                                                       |
    | `descricao`               | String  | Description                                                                                                 |
    | `nota`                    | String  | Notes                                                                                                       |
    | `conta_financeira`        | Object  | Financial account details (bank, name, type, branch, number)                                                |
    | `id_conta_financeira`     | String  | Financial account ID                                                                                        |
    | `valor_composicao`        | Object  | Value breakdown with penalty, interest, gross value, discount, fee, and net value                           |
    | `metodo_pagamento`        | String  | Payment method                                                                                              |
    | `nsu`                     | String  | NSU (unique sequential number)                                                                              |
    | `baixa_agendada`          | Boolean | Whether write-off is scheduled                                                                              |
    | `baixas`                  | Array   | Array of write-off records with payment date, value composition, financial account, and attachments         |
    | `anexos`                  | Array   | Array of attachments with name, description, type, and URL                                                  |
    | `solicitacoes_cobrancas`  | Array   | Array of billing requests with status, values, due date, billing notifications, and payment details         |
    | `fatura`                  | Object  | Invoice details with number, RPS, and invoice type                                                          |
    | `data_alteracao`          | String  | Last modification date (replication key)                                                                    |
    | `valor_total_liquido`     | Number  | Total net value                                                                                             |
    | `renegociacao`            | Object  | Renegotiation details with ID and value                                                                     |
  </Accordion>

  <Accordion title="Contas Financeiras (Financial Accounts)">
    Bank accounts and financial accounts registered in ContaAzul.

    | Field                           | Type    | Description                                        |
    | :------------------------------ | :------ | :------------------------------------------------- |
    | `id`                            | String  | Account identifier                                 |
    | `banco`                         | String  | Bank name                                          |
    | `codigo_banco`                  | Integer | Bank code                                          |
    | `nome`                          | String  | Account name                                       |
    | `ativo`                         | Boolean | Whether the account is active                      |
    | `tipo`                          | String  | Account type                                       |
    | `conta_padrao`                  | Boolean | Whether this is the default account                |
    | `possui_config_boleto_bancario` | Boolean | Whether boleto (bank slip) configuration is set up |
    | `agencia`                       | String  | Branch number                                      |
    | `numero`                        | String  | Account number                                     |
  </Accordion>

  <Accordion title="Categorias (Categories)">
    Financial categories used to classify transactions.

    | Field                 | Type    | Description                                            |
    | :-------------------- | :------ | :----------------------------------------------------- |
    | `id`                  | String  | Category identifier                                    |
    | `versao`              | Integer | Record version                                         |
    | `nome`                | String  | Category name                                          |
    | `categoria_pai`       | String  | Parent category ID                                     |
    | `tipo`                | String  | Category type                                          |
    | `entrada_dre`         | String  | Income statement (DRE) entry                           |
    | `considera_custo_dre` | Boolean | Whether it's considered a cost in the income statement |
  </Accordion>

  <Accordion title="Categorias DRE (Income Statement Categories)">
    Hierarchical income statement (DRE) categories with sub-items and linked financial categories.

    | Field                         | Type    | Description                                                                                        |
    | :---------------------------- | :------ | :------------------------------------------------------------------------------------------------- |
    | `id`                          | String  | Category identifier                                                                                |
    | `descricao`                   | String  | Description                                                                                        |
    | `codigo`                      | String  | Category code                                                                                      |
    | `posicao`                     | Integer | Position in the statement                                                                          |
    | `indica_totalizador`          | Boolean | Whether this is a totalizer row                                                                    |
    | `representa_soma_custo_medio` | Boolean | Whether it represents average cost sum                                                             |
    | `subitens`                    | Array   | Array of sub-items with their own ID, description, code, position, and linked financial categories |
    | `categorias_financeiras`      | Array   | Array of linked financial categories with ID, code, name, and active status                        |
  </Accordion>

  <Accordion title="Centros de Custos (Cost Centers)">
    Cost centers used to allocate expenses and revenues.

    | Field    | Type    | Description            |
    | :------- | :------ | :--------------------- |
    | `id`     | String  | Cost center identifier |
    | `codigo` | String  | Cost center code       |
    | `nome`   | String  | Cost center name       |
    | `ativo`  | Boolean | Whether it is active   |
  </Accordion>

  <Accordion title="Produtos (Products)">
    Product catalog with inventory, pricing, and variant information.

    | Field                        | Type    | Description                                                                                           |
    | :--------------------------- | :------ | :---------------------------------------------------------------------------------------------------- |
    | `id`                         | String  | Product identifier                                                                                    |
    | `id_legado`                  | Integer | Legacy product ID                                                                                     |
    | `nome`                       | String  | Product name                                                                                          |
    | `codigo_sku`                 | String  | SKU code                                                                                              |
    | `codigo_ean`                 | String  | EAN barcode                                                                                           |
    | `tipo`                       | String  | Product type                                                                                          |
    | `status`                     | String  | Product status                                                                                        |
    | `estoque`                    | Number  | Current stock quantity                                                                                |
    | `valor_venda`                | Number  | Sale price                                                                                            |
    | `custo_medio`                | Number  | Average cost                                                                                          |
    | `filhos`                     | Array   | Array of product variants/children with their own ID, name, SKU, stock, pricing, and parent reference |
    | `variacao`                   | Integer | Variation identifier                                                                                  |
    | `nivel_estoque`              | String  | Stock level indicator                                                                                 |
    | `estoque_minimo`             | Number  | Minimum stock threshold                                                                               |
    | `estoque_maximo`             | Number  | Maximum stock threshold                                                                               |
    | `movimentado`                | Boolean | Whether the product has had stock movement                                                            |
    | `id_pai`                     | String  | Parent product ID (for variants)                                                                      |
    | `integracao_ecommerce_ativa` | Boolean | Whether e-commerce integration is active                                                              |
  </Accordion>

  <Accordion title="Servico (Services)">
    Service catalog with pricing and type information.

    | Field          | Type    | Description         |
    | :------------- | :------ | :------------------ |
    | `id`           | String  | Service identifier  |
    | `id_servico`   | Integer | Legacy service ID   |
    | `nome`         | String  | Service name        |
    | `codigo`       | String  | Service code        |
    | `descricao`    | String  | Service description |
    | `preco`        | Number  | Service price       |
    | `custo`        | Number  | Service cost        |
    | `status`       | String  | Service status      |
    | `tipo_servico` | String  | Service type        |
  </Accordion>

  <Accordion title="Pessoas Lista (People List)">
    List of contacts (customers, suppliers, etc.) with basic information and address.

    | Field                | Type    | Description                                                                               |
    | :------------------- | :------ | :---------------------------------------------------------------------------------------- |
    | `uuid`               | String  | Unique identifier                                                                         |
    | `nome`               | String  | Contact name                                                                              |
    | `documento`          | String  | Document number (CPF/CNPJ)                                                                |
    | `inscricao_estadual` | String  | State registration number                                                                 |
    | `email`              | String  | Email address                                                                             |
    | `telefone`           | String  | Phone number                                                                              |
    | `ativo`              | Boolean | Whether the contact is active                                                             |
    | `id_legado`          | Integer | Legacy ID                                                                                 |
    | `uuid_legado`        | String  | Legacy UUID                                                                               |
    | `perfis`             | Array   | Array of profile types (e.g. customer, supplier)                                          |
    | `tipo_pessoa`        | String  | Person type (individual or company)                                                       |
    | `endereco`           | Object  | Address with zip code, street, number, complement, neighborhood, city, state, and country |
  </Accordion>

  <Accordion title="Pessoas Detalhes (People Details)">
    Detailed contact information including financial summaries, multiple addresses, additional contacts, tax data, and custom fields. This is a child stream — one detail record is fetched per contact in the People List.

    | Field                      | Type     | Description                                                                                          |
    | :------------------------- | :------- | :--------------------------------------------------------------------------------------------------- |
    | `uuid`                     | String   | Unique identifier                                                                                    |
    | `nome`                     | String   | Contact name                                                                                         |
    | `documento`                | String   | Document number (CPF/CNPJ)                                                                           |
    | `atrasos_recebimentos`     | Number   | Overdue receivables amount                                                                           |
    | `recebimentos_mes_atual`   | Number   | Current month receivables                                                                            |
    | `atrasos_pagamentos`       | Number   | Overdue payables amount                                                                              |
    | `pagamentos_mes_atual`     | Number   | Current month payables                                                                               |
    | `email`                    | String   | Email address                                                                                        |
    | `telefone_comercial`       | String   | Business phone                                                                                       |
    | `celular`                  | String   | Mobile phone                                                                                         |
    | `criado_em`                | DateTime | Creation date                                                                                        |
    | `codigo`                   | String   | Contact code                                                                                         |
    | `perfis`                   | Array    | Array of profile types                                                                               |
    | `pessoas_legado`           | Array    | Array of legacy person records with ID, UUID, and profile                                            |
    | `enderecos`                | Array    | Array of addresses with zip code, street, number, complement, neighborhood, city, state, and country |
    | `observacoes_gerais`       | String   | General notes                                                                                        |
    | `optante_simples_nacional` | Boolean  | Whether opted into Simples Nacional tax regime                                                       |
    | `orgao_publico`            | Boolean  | Whether it is a public institution                                                                   |
    | `nome_empresa`             | String   | Company name                                                                                         |
    | `tipo_pessoa`              | String   | Person type (individual or company)                                                                  |
    | `lembretes_vencimento`     | Array    | Array of due date reminders with email and status                                                    |
    | `informacoes_adicionais`   | Array    | Array of custom fields with label, value, and type                                                   |
    | `outros_contatos`          | Array    | Array of additional contacts with name, email, phone, and office                                     |
    | `informacoes_fiscais`      | Array    | Array of tax information with state registration, national registration, and SUFRAMA registration    |
  </Accordion>

  <Accordion title="Suppliers">
    Supplier records with contact information and address.

    | Field                       | Type     | Description                                                                      |
    | :-------------------------- | :------- | :------------------------------------------------------------------------------- |
    | `id`                        | String   | Supplier identifier                                                              |
    | `name`                      | String   | Supplier name                                                                    |
    | `company_name`              | String   | Company name                                                                     |
    | `email`                     | String   | Email address                                                                    |
    | `business_phone`            | String   | Business phone                                                                   |
    | `mobile_phone`              | String   | Mobile phone                                                                     |
    | `person_type`               | String   | Person type (NATURAL or LEGAL)                                                   |
    | `document`                  | String   | Document number (CPF/CNPJ)                                                       |
    | `identity_document`         | String   | Identity document (RG)                                                           |
    | `state_registration_number` | String   | State registration number                                                        |
    | `state_registration_type`   | String   | State registration type                                                          |
    | `city_registration_number`  | String   | City registration number                                                         |
    | `date_of_birth`             | DateTime | Date of birth                                                                    |
    | `notes`                     | String   | Notes                                                                            |
    | `foreignId`                 | String   | Foreign/external ID                                                              |
    | `contactName`               | String   | Contact person name                                                              |
    | `address`                   | Object   | Address with street, number, complement, zip code, neighborhood, city, and state |
  </Accordion>

  <Accordion title="Vendas Lista (Sales List)">
    List of sales with summary information, customer data, and status.

    | Field                | Type     | Description                                                                            |
    | :------------------- | :------- | :------------------------------------------------------------------------------------- |
    | `id`                 | String   | Sale identifier                                                                        |
    | `total`              | Number   | Total sale amount                                                                      |
    | `id_legado`          | Integer  | Legacy sale ID                                                                         |
    | `data`               | String   | Sale date                                                                              |
    | `criado_em`          | DateTime | Creation date                                                                          |
    | `data_alteracao`     | DateTime | Last modification date (replication key)                                               |
    | `tipo`               | String   | Sale type                                                                              |
    | `itens`              | String   | Items summary                                                                          |
    | `condicao_pagamento` | Boolean  | Payment condition flag                                                                 |
    | `numero`             | Integer  | Sale number                                                                            |
    | `cliente`            | Object   | Customer info with ID, name, email, phone, address, city, state, country, and zip code |
    | `situacao`           | Object   | Status with status code, description, and date                                         |
    | `versao`             | Integer  | Record version                                                                         |
    | `status_email`       | Object   | Email notification status with status and sent date                                    |
  </Accordion>

  <Accordion title="Vendas Detalhes (Sales Details)">
    Full sale details including customer, financial event, operation type, payment conditions, value breakdown, and pending status. This is a child stream — one detail record is fetched per sale in the Sales List.

    | Field                  | Type     | Description                                                                                                                                                                                                                                                                                                        |
    | :--------------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `sales_id`             | String   | Sale identifier (primary key)                                                                                                                                                                                                                                                                                      |
    | `data_alteracao_venda` | DateTime | Sale last modification date (replication key)                                                                                                                                                                                                                                                                      |
    | `data_alteracao`       | DateTime | Record modification date                                                                                                                                                                                                                                                                                           |
    | `cliente`              | Object   | Customer with UUID, person type, document, and name                                                                                                                                                                                                                                                                |
    | `evento_financeiro`    | Object   | Linked financial event with ID                                                                                                                                                                                                                                                                                     |
    | `notificacao`          | Object   | Email notification with reference ID, recipient, sent date, opened date, and status                                                                                                                                                                                                                                |
    | `natureza_operacao`    | Object   | Operation type with UUID, operation type, template, label, financial impact, and stock change                                                                                                                                                                                                                      |
    | `venda`                | Object   | Detailed sale data with ID, status, legacy ID, negotiation type, sale number, category ID, commitment date, discount settings, value composition (gross, discount, freight, taxes, insurance, net), payment conditions (type, account, installments, card payment details), item counts, notes, and pending status |
  </Accordion>

  <Accordion title="Vendas Itens (Sales Items)">
    Individual line items for each sale. This is a child stream — items are fetched per sale in the Sales List.

    | Field                  | Type     | Description                                   |
    | :--------------------- | :------- | :-------------------------------------------- |
    | `sales_id`             | String   | Parent sale identifier                        |
    | `id`                   | String   | Item record identifier                        |
    | `id_item`              | String   | Product/service identifier                    |
    | `nome`                 | String   | Item name                                     |
    | `descricao`            | String   | Item description                              |
    | `tipo`                 | String   | Item type (product or service)                |
    | `quantidade`           | Number   | Quantity                                      |
    | `valor`                | Number   | Item value                                    |
    | `data_alteracao_venda` | DateTime | Sale last modification date (replication key) |
  </Accordion>
</AccordionGroup>

# Use Cases for Data Analysis

This guide outlines valuable business intelligence use cases when consolidating ContaAzul data, along with ready-to-use SQL queries that you can run on [Explorer](https://app.nekt.ai/explorer).

### 1. Cash Flow Overview

Analyze payables vs. receivables to understand your cash flow position.

**Business Value:**

* Monitor outstanding payables and receivables
* Identify overdue payments
* Track payment efficiency

<Accordion title="SQL query">
  <Tabs>
    <Tab title="AWS">
      ```sql theme={null}
      WITH payables AS (
         SELECT
            'PAYABLE' AS type,
            status,
            COUNT(*) AS record_count,
            SUM(total) AS total_amount,
            SUM(nao_pago) AS unpaid_amount,
            SUM(pago) AS paid_amount
         FROM
            nekt_raw.contaazul_despesas
         GROUP BY
            status
      ),
      receivables AS (
         SELECT
            'RECEIVABLE' AS type,
            status,
            COUNT(*) AS record_count,
            SUM(total) AS total_amount,
            SUM(nao_pago) AS unpaid_amount,
            SUM(pago) AS paid_amount
         FROM
            nekt_raw.contaazul_receitas
         GROUP BY
            status
      )
      SELECT * FROM payables
      UNION ALL
      SELECT * FROM receivables
      ORDER BY
         type, record_count DESC
      ```
    </Tab>

    <Tab title="GCP">
      ```sql theme={null}
      WITH payables AS (
         SELECT
            'PAYABLE' AS type,
            status,
            COUNT(*) AS record_count,
            SUM(total) AS total_amount,
            SUM(nao_pago) AS unpaid_amount,
            SUM(pago) AS paid_amount
         FROM
            `nekt_raw.contaazul_despesas`
         GROUP BY
            status
      ),
      receivables AS (
         SELECT
            'RECEIVABLE' AS type,
            status,
            COUNT(*) AS record_count,
            SUM(total) AS total_amount,
            SUM(nao_pago) AS unpaid_amount,
            SUM(pago) AS paid_amount
         FROM
            `nekt_raw.contaazul_receitas`
         GROUP BY
            status
      )
      SELECT * FROM payables
      UNION ALL
      SELECT * FROM receivables
      ORDER BY
         type, record_count DESC
      ```
    </Tab>
  </Tabs>
</Accordion>

<Accordion title="Sample Result">
  | type       | status   | record\_count | total\_amount | unpaid\_amount | paid\_amount |
  | ---------- | -------- | ------------- | ------------- | -------------- | ------------ |
  | PAYABLE    | PAGO     | 456           | 234,567.89    | 0.00           | 234,567.89   |
  | PAYABLE    | PENDENTE | 89            | 45,230.00     | 45,230.00      | 0.00         |
  | PAYABLE    | VENCIDO  | 12            | 8,900.00      | 8,900.00       | 0.00         |
  | RECEIVABLE | PAGO     | 780           | 567,890.12    | 0.00           | 567,890.12   |
  | RECEIVABLE | PENDENTE | 134           | 98,450.00     | 98,450.00      | 0.00         |
  | RECEIVABLE | VENCIDO  | 23            | 15,670.00     | 15,670.00      | 0.00         |
</Accordion>

### 2. Sales Performance by Customer

Analyze sales volume and revenue by customer to identify top accounts.

**Business Value:**

* Identify highest-value customers
* Track sales trends by customer
* Support customer segmentation

<Accordion title="SQL query">
  <Tabs>
    <Tab title="AWS">
      ```sql theme={null}
      SELECT
         v.cliente.nome AS customer_name,
         v.cliente.email AS customer_email,
         COUNT(*) AS total_sales,
         SUM(v.total) AS total_revenue,
         ROUND(AVG(v.total), 2) AS avg_sale_value,
         MIN(v.data) AS first_sale,
         MAX(v.data) AS last_sale
      FROM
         nekt_raw.contaazul_vendas_lista v
      WHERE
         v.situacao.status != 'CANCELADO'
      GROUP BY
         v.cliente.nome, v.cliente.email
      ORDER BY
         total_revenue DESC
      LIMIT 20
      ```
    </Tab>

    <Tab title="GCP">
      ```sql theme={null}
      SELECT
         v.cliente.nome AS customer_name,
         v.cliente.email AS customer_email,
         COUNT(*) AS total_sales,
         SUM(v.total) AS total_revenue,
         ROUND(AVG(v.total), 2) AS avg_sale_value,
         MIN(v.data) AS first_sale,
         MAX(v.data) AS last_sale
      FROM
         `nekt_raw.contaazul_vendas_lista` v
      WHERE
         v.situacao.status != 'CANCELADO'
      GROUP BY
         v.cliente.nome, v.cliente.email
      ORDER BY
         total_revenue DESC
      LIMIT 20
      ```
    </Tab>
  </Tabs>
</Accordion>

<Accordion title="Sample Result">
  | customer\_name    | customer\_email                                   | total\_sales | total\_revenue | avg\_sale\_value | first\_sale | last\_sale |
  | ----------------- | ------------------------------------------------- | ------------ | -------------- | ---------------- | ----------- | ---------- |
  | Empresa ABC Ltda  | [contato@abc.com.br](mailto:contato@abc.com.br)   | 45           | 123,456.78     | 2,743.48         | 2025-01-15  | 2026-03-08 |
  | Distribuidora XYZ | [vendas@xyz.com.br](mailto:vendas@xyz.com.br)     | 32           | 89,234.50      | 2,788.58         | 2025-03-20  | 2026-03-10 |
  | Comércio Silva    | [silva@email.com](mailto:silva@email.com)         | 28           | 67,890.00      | 2,424.64         | 2025-02-01  | 2026-02-28 |
  | Tech Solutions SA | [compras@tech.com.br](mailto:compras@tech.com.br) | 19           | 45,670.00      | 2,403.68         | 2025-06-10  | 2026-03-05 |
</Accordion>

### 3. Product Inventory Status

Monitor product stock levels and identify items that need replenishment.

**Business Value:**

* Identify low-stock products before they run out
* Track inventory turnover
* Optimize purchasing decisions

<Accordion title="SQL query">
  <Tabs>
    <Tab title="AWS">
      ```sql theme={null}
      SELECT
         nome AS product_name,
         codigo_sku AS sku,
         status,
         estoque AS current_stock,
         estoque_minimo AS min_stock,
         estoque_maximo AS max_stock,
         valor_venda AS sale_price,
         custo_medio AS avg_cost,
         CASE
            WHEN estoque <= estoque_minimo THEN 'CRITICAL'
            WHEN estoque <= estoque_minimo * 1.5 THEN 'LOW'
            ELSE 'OK'
         END AS stock_status
      FROM
         nekt_raw.contaazul_produtos
      WHERE
         status = 'ATIVO'
         AND estoque_minimo IS NOT NULL
      ORDER BY
         estoque ASC
      ```
    </Tab>

    <Tab title="GCP">
      ```sql theme={null}
      SELECT
         nome AS product_name,
         codigo_sku AS sku,
         status,
         estoque AS current_stock,
         estoque_minimo AS min_stock,
         estoque_maximo AS max_stock,
         valor_venda AS sale_price,
         custo_medio AS avg_cost,
         CASE
            WHEN estoque <= estoque_minimo THEN 'CRITICAL'
            WHEN estoque <= estoque_minimo * 1.5 THEN 'LOW'
            ELSE 'OK'
         END AS stock_status
      FROM
         `nekt_raw.contaazul_produtos`
      WHERE
         status = 'ATIVO'
         AND estoque_minimo IS NOT NULL
      ORDER BY
         estoque ASC
      ```
    </Tab>
  </Tabs>
</Accordion>

<Accordion title="Sample Result">
  | product\_name      | sku     | status | current\_stock | min\_stock | max\_stock | sale\_price | avg\_cost | stock\_status |
  | ------------------ | ------- | ------ | -------------- | ---------- | ---------- | ----------- | --------- | ------------- |
  | Cabo USB-C 1m      | SKU-001 | ATIVO  | 5              | 10         | 100        | 29.90       | 12.50     | CRITICAL      |
  | Carregador 20W     | SKU-042 | ATIVO  | 12             | 10         | 80         | 89.90       | 38.00     | LOW           |
  | Película Protetora | SKU-103 | ATIVO  | 8              | 15         | 200        | 19.90       | 5.20      | CRITICAL      |
  | Mouse Sem Fio      | SKU-078 | ATIVO  | 45             | 20         | 150        | 79.90       | 32.00     | OK            |
</Accordion>

## Implementation Notes

<AccordionGroup>
  <Accordion title="Parent-Child Streams">
    Several streams follow a parent-child pattern where a list endpoint provides summary records, and a detail endpoint is called for each individual record:

    * **Pessoas Lista → Pessoas Detalhes**: The people list provides basic contact info; the detail stream fetches full contact data per person.
    * **Vendas Lista → Vendas Detalhes**: The sales list provides summary data; the detail stream fetches full sale info per sale.
    * **Vendas Lista → Vendas Itens**: Line items are fetched per sale from the sales list.
    * **Despesas → Parcelas**: Installment details are fetched for each expense.
    * **Receitas → Parcelas**: Installment details are fetched for each receivable.
  </Accordion>

  <Accordion title="Incremental Sync">
    The connector supports incremental sync for:

    * **Despesas**: Uses `data_alteracao` as the replication key
    * **Receitas**: Uses `data_alteracao` as the replication key
    * **Vendas Lista / Detalhes / Itens**: Uses `data_alteracao` as the replication key

    Streams without a replication key (Categorias, Categorias DRE, Centros de Custos, Contas Financeiras, Produtos, Pessoas, Servico, Suppliers) are always synced as full table.
  </Accordion>

  <Accordion title="Rate Limiting">
    The ContaAzul API enforces rate limits. The connector automatically handles `429 Too Many Requests` responses by waiting 60 seconds before retrying. If you experience frequent rate limit errors, consider reducing the number of streams synced concurrently or adjusting your trigger frequency.
  </Accordion>

  <Accordion title="Authentication and Token Management">
    The connector automatically manages OAuth access token refresh to prevent authentication failures:

    * Access tokens are refreshed proactively before expiration
    * Refresh tokens are stored securely and rotated automatically
    * Basic authentication headers are derived from your client ID and secret
  </Accordion>

  <Accordion title="Nested Data Structures">
    ContaAzul data contains nested structures. When querying:

    * Use dot notation to access nested fields (e.g., `cliente.nome` in the sales list)
    * Use `UNNEST` to flatten arrays (e.g., `parcelas` in sales details, `filhos` in products)

    Example for product variants:

    ```sql theme={null}
    -- AWS Athena
    SELECT p.nome, v.nome AS variant_name, v.estoque, v.valor_venda
    FROM contaazul_produtos p
    CROSS JOIN UNNEST(p.filhos) AS t(v)

    -- GCP BigQuery
    SELECT p.nome, v.nome AS variant_name, v.estoque, v.valor_venda
    FROM `contaazul_produtos` p, UNNEST(p.filhos) AS v
    ```
  </Accordion>
</AccordionGroup>

## Skills for agents

<Snippet file="agent-skills-intro.mdx" />

<Card title="Download ContaAzul skills file" icon="wand-magic-sparkles" href="/sources/contaazul.md">
  ContaAzul connector documentation as plain markdown, for use in AI agent contexts.
</Card>
