> ## 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.

# Loja Integrada as a data source

> Bring your Loja Integrada store data to Nekt: orders with their items, payments, shipments and status history, products and variations, stock, prices, customers, coupons and store catalogs.

Loja Integrada is a Brazilian e-commerce platform for building and running online stores. This connector reads your store through the official Loja Integrada API, so you can analyze orders, products, stock, prices and customers together with the rest of your data.

> [!NOTE]
>
> The connector only reads data. It never creates, changes or deletes anything in your store.

## Before you start

* **A paid Loja Integrada plan.** The Loja Integrada API is only available on paid plans.
* **The store owner.** The connector authenticates with a **Personal Token**, and only the store's owner user can create one. Users with the Administrator, Member or any other profile do not see the option.

## Getting your Personal Token

These steps follow Loja Integrada's help article [Como gerar chaves de API e o personal token](https://ajuda.lojaintegrada.com.br/pt-BR/articles/931152-como-gerar-chaves-de-api-e-o-personal-token-chave-de-aplicacao-da-minha-loja).

**1. Open the API keys screen**

Signed in as the store owner, open **Configurações > Chave para API** in the Loja Integrada panel and click **Personal token**.

**2. Generate the token**

Click **Gerar personal token**, give it a name you will recognize (for example, "Nekt") and click **Gerar**.

**3. Copy the token**

The token is shown **only once**. Copy it now and paste it in the **Personal Token** field in Nekt. If you lose it, Loja Integrada cannot recover it: generate a new one.

> [!WARNING]
>
> A Personal Token is valid for **3 months**. About a month before it expires, Loja Integrada shows a **Renovar** button next to the token (in **Configurações > Chave para API > Personal token**) and a notice in the panel. Clicking **Renovar** keeps the same token for 3 more months, so nothing changes in Nekt. If the token is not renewed in time, Loja Integrada revokes it and the syncs fail with a message saying the token was rejected: generate a new token and update the source in Nekt.

## Configuring Loja Integrada 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 Loja Integrada option from the list of connectors.

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

### 1. Add account access

The following configurations are available:

* **Personal Token**: the Personal Token of your store, created as described in [Getting your Personal Token](#getting-your-personal-token).
* **Start Date**: orders changed since this date are read on the first sync and on Full syncs. Products, customers and the other tables are always read in full on those syncs.
* **API Rate Share (%)** (advanced, default 50): the share of the store's API limit (100 requests per minute, shared by every integration of the store) this source may use, from 10 to 90. A higher value makes syncs faster but leaves less room for your ERP, hub or marketplace integrations.
* **Status Check Window (days)** (advanced, default 30): every sync lists the orders created in this many days and re-reads the ones whose status changed since the previous sync (for example shipped to delivered). It costs about 1 API request per 49 orders created in the window on every sync: a store with 30,000 orders in 30 days spends about 610 requests (about 12 minutes at the default rate share). Lower it for a very busy store; 0 turns it off.

> [!TIP]
>
> Loja Integrada has no bulk export for orders, so each order is read with its own request, within this source's share of the store's 100 requests per minute. With the default 50% share that is about 50 orders per minute (25 with the `order_status_history` stream): 10,000 orders take about 3.5 hours on the first sync (7 hours with the history) and 50,000 about 17 hours (35 hours). The first sync is all-or-nothing, so start with a recent Start Date (for example the last 3 to 6 months) and widen it later with a Full sync if you need more history. Later syncs read only what changed.

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/runs/scheduling-and-triggers.md), 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. A Full sync reads every order since the Start Date again, one request per order, so it takes as long as the first sync.

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.

# Streams and Fields

## Available streams

The table below lists every stream, its **slug** (the exact identifier to pass when creating the source via API) and a short description.

| Stream | Slug | Description |
| - | - | - |
| Orders | `orders` | One row per order, with totals, current status, customer, coupon and delivery address. Incremental on the order's last modification, which includes status changes. |
| Order Items | `order_items` | One row per product or variation sold in each order. |
| Order Payments | `order_payments` | One row per payment of each order (method, card brand, installments, amounts). |
| Order Shipments | `order_shipments` | One row per shipment of each order (shipping method, cost, deadline, tracking code). |
| Order Status History | `order_status_history` | Every status change of each order, with who changed it and when. Costs one extra API request per order. |
| Products | `products` | Products and their variations (a variation is a product of type `atributo_opcao`), with SKU, brand, categories, dimensions and images. |
| Product Stocks | `product_stocks` | Current stock of every product and variation. Read in full on every sync. |
| Product Prices | `product_prices` | Current full, promotional and cost prices of every product and variation. Read in full on every sync. |
| Customers | `customers` | Registered customers. |
| Categories | `categories` | Product categories and their hierarchy. |
| Brands | `brands` | Product brands. |
| Coupons | `coupons` | Discount coupons and their rules. |
| Order Statuses | `order_statuses` | The order statuses of the store (paid, shipped, cancelled...). |
| Payment Methods | `payment_methods` | Payment methods available to the store. |
| Shipping Methods | `shipping_methods` | Shipping methods available to the store. |
| Customer Groups | `customer_groups` | Customer groups (default, VIP, wholesale...). |
| Variation Grids | `variation_grids` | The attributes variations are built from (size, color, voltage...). |
| Variation Grid Values | `variation_grid_values` | The values of each variation grid (P, M, G; Blue, Red...). |

Every table also has an `extra_fields` column with any field Loja Integrada returned that is not mapped to a column yet (JSON). Amounts are in BRL and dates and times are in UTC.

## Fields by stream

> [accordion] Orders
>
> **Key Fields:**
>
> * `numero` - Order number, unique in the store (primary key)
> * `data_criacao` - When the order was placed
> * `data_modificacao` - When the order was last modified, including status changes (replication key)
> * `data_expiracao` - When an unpaid order expires
> * `id_externo` / `id_anymarket` - Identifiers set by integrations (ERP, hub, AnyMarket)
>
> **Status:**
>
> * `situacao_id`, `situacao_codigo`, `situacao_nome` - Current status (e.g. `pedido_pago`, `pedido_enviado`, `pedido_cancelado`)
> * `situacao_aprovado`, `situacao_cancelado`, `situacao_final` - Whether the status counts as approved, cancelled, or final
>
> **Amounts (BRL):**
>
> * `valor_subtotal` - Sum of the items
> * `valor_envio` - Shipping charged
> * `valor_desconto` - Discount applied
> * `valor_total` - Order total
> * `peso_real` - Total weight (kg)
>
> **Customer:**
>
> * `cliente_id`, `cliente_nome`, `cliente_email`, `cliente_cpf`, `cliente_cnpj`, `cliente_razao_social`, `cliente_sexo`, `cliente_data_nascimento`, `cliente_telefone_celular`, `cliente_telefone_principal`
> * `cliente_obs` - Note the buyer left on the order
>
> **Other:**
>
> * `cupom_id`, `cupom_codigo`, `cupom_desconto` - Coupon used (the last one as JSON)
> * `utm_campaign` - UTM campaign of the order
> * `endereco_entrega` - Delivery address (JSON)
> * `itens`, `pagamentos`, `envios` - Items, payments and shipments as returned by the API (JSON); also available as their own streams

> [accordion] Order Items
>
> * `id` - Unique identifier of the order item (primary key)
> * `pedido_numero` - Order number
> * `pedido_data_modificacao` - Last modification of the order (replication key)
> * `linha` - Line number in the order
> * `produto_id` - Loja Integrada identifier of the product sold
> * `produto_id_externo` - External identifier of the product, when the API addresses it that way (then `produto_id` is empty)
> * `produto_pai_id` - Parent product, when the item is a variation
> * `sku`, `nome`, `tipo` - SKU, name and type of the product at the time of the order
> * `quantidade` - Quantity sold
> * `preco_cheio`, `preco_promocional`, `preco_venda`, `preco_subtotal`, `preco_custo` - Prices (BRL)
> * `peso`, `altura`, `largura`, `profundidade` - Weight (kg) and dimensions (cm)
> * `disponibilidade` - Shipping lead time in days

> [accordion] Order Payments
>
> * `id` - Unique identifier of the payment (primary key)
> * `pedido_numero`, `pedido_data_modificacao` - Order number and its last modification (replication key)
> * `forma_pagamento_id`, `forma_pagamento_codigo`, `forma_pagamento_nome` - Payment method
> * `pagamento_tipo` - Payment type (e.g. `creditCard`)
> * `bandeira`, `banco` - Card brand and bank
> * `valor`, `valor_pago` - Payment amount and amount paid (BRL)
> * `parcelamento_numero_parcelas`, `parcelamento_valor_parcela` - Installments
> * `transacao_id`, `identificador_id`, `authorization_code`, `codigo_retorno_gateway`, `mensagem_gateway` - Gateway details

> [accordion] Order Shipments
>
> * `id` - Unique identifier of the shipment (primary key)
> * `pedido_numero`, `pedido_data_modificacao` - Order number and its last modification (replication key)
> * `forma_envio_id`, `forma_envio_codigo`, `forma_envio_nome`, `forma_envio_tipo` - Shipping method and service (e.g. `PAC`, `SEDEX`)
> * `objeto` - Tracking code
> * `prazo` - Delivery deadline in days
> * `valor` - Shipping cost (BRL)
> * `data_criacao`, `data_modificacao` - When the shipment was created and last modified

> [accordion] Order Status History
>
> * `id` - Unique identifier of the status change (primary key)
> * `pedido_numero`, `pedido_data_modificacao` - Order number and its last modification (replication key)
> * `data` - When the status changed
> * `situacao_id`, `situacao_codigo`, `situacao_nome` - Status the order moved to
> * `situacao_anterior_id`, `situacao_anterior_codigo`, `situacao_anterior_nome` - Status the order left
> * `alterado_por`, `alterado_por_nome` - Who changed it (e.g. the payment gateway, the API, a user)
> * `obs` - Note recorded with the change

> [accordion] Products
>
> * `id` - Unique identifier of the product or variation (primary key)
> * `sku`, `nome`, `apelido`, `id_externo` - SKU, name, URL slug and external identifier
> * `tipo` - `normal` (no variations), `atributo` (product with variations) or `atributo_opcao` (one variation)
> * `pai_id` - For a variation: its parent product
> * `filhos_ids` - For a product with variations: its variations (JSON list)
> * `variacoes_ids` - For a variation: the grid values that define it (JSON list, see `variation_grid_values`)
> * `grades_ids`, `categorias_ids` - Variation grids and categories (JSON lists)
> * `marca_id` - Brand
> * `ativo`, `bloqueado`, `removido`, `destaque`, `usado` - Status flags (`removido` is true for products deleted in the panel)
> * `gtin`, `mpn`, `ncm` - Barcode, manufacturer part number and tax classification
> * `peso`, `altura`, `largura`, `profundidade` - Weight (kg) and dimensions (cm)
> * `url`, `url_video_youtube`, `seo_id`, `descricao_completa` - Store page, video, SEO settings and full description (HTML)
> * `imagem_principal`, `imagens`, `tags` - Images and tags (JSON)
> * `data_criacao`, `data_modificacao` - When the product was created and last modified (replication key)
>
> Prices and stock are in the `product_prices` and `product_stocks` streams.

> [accordion] Product Stocks
>
> * `id` - Unique identifier of the stock record (primary key)
> * `produto_id` - Product or variation
> * `gerenciado` - Whether Loja Integrada manages the stock (when false, quantities are 0)
> * `quantidade`, `quantidade_disponivel`, `quantidade_reservada` - In stock, available for sale, reserved by open orders
> * `situacao_em_estoque`, `situacao_sem_estoque` - Shipping lead time in days with and without stock (-1 = unavailable)

> [accordion] Product Prices
>
> * `id` - Unique identifier of the price record (primary key)
> * `produto_id` - Product or variation
> * `cheio`, `promocional`, `custo` - Full, promotional and cost prices (BRL)
> * `sob_consulta` - Whether the price is shown as "on request"

> [accordion] Customers
>
> * `id` - Unique identifier of the customer (primary key)
> * `nome`, `email`, `tipo` (PF or PJ), `cpf`, `cnpj`, `razao_social`, `ie`, `rg`, `sexo`, `data_nascimento`
> * `data_criacao`, `data_modificacao` - When the customer registered and was last modified (replication key)

> [accordion] Catalogs
>
> * **Categories:** `id`, `nome`, `descricao`, `id_externo`, `url`, `seo_id`, `categoria_pai_id`
> * **Brands:** `id`, `nome`, `apelido`, `descricao`, `ativo`, `id_externo`, `imagem`
> * **Coupons:** `id`, `codigo`, `descricao`, `tipo`, `valor`, `valor_minimo`, `ativo`, `cumulativo`, `aplicar_no_total`, `condicao_cliente`, `condicao_produto`, `quantidade`, `quantidade_por_cliente`, `quantidade_usada`, `validade`, `id_externo`, `data_criacao`, `data_modificacao`
> * **Order Statuses:** `id`, `codigo`, `nome`, `aprovado`, `cancelado`, `final`, `notificar_comprador`, `padrao`
> * **Payment Methods:** `id`, `codigo`, `nome`, `ativo`, `disponivel`, `imagem`
> * **Shipping Methods:** `id`, `codigo`, `nome`, `tipo`, `ativo`, `disponivel`, `imagem`
> * **Customer Groups:** `id`, `nome`, `padrao`
> * **Variation Grids:** `id`, `nome`, `nome_visivel`, `id_externo`
> * **Variation Grid Values:** `id`, `grade_id`, `nome`, `id_externo`

# Data Model

```mermaid theme={null}
graph TD;
    Orders("Orders");
    OrderItems("Order Items");
    OrderPayments("Order Payments");
    OrderShipments("Order Shipments");
    OrderStatusHistory("Order Status History");
    Products("Products");
    ProductStocks("Product Stocks");
    ProductPrices("Product Prices");
    Customers("Customers");
    Brands("Brands");
    Categories("Categories");
    GridValues("Variation Grid Values");
    Grids("Variation Grids");

    OrderItems -- "pedido_numero → numero" --> Orders;
    OrderPayments -- "pedido_numero → numero" --> Orders;
    OrderShipments -- "pedido_numero → numero" --> Orders;
    OrderStatusHistory -- "pedido_numero → numero" --> Orders;
    Orders -- "cliente_id → id" --> Customers;
    OrderItems -- "produto_id → id" --> Products;
    ProductStocks -- "produto_id → id" --> Products;
    ProductPrices -- "produto_id → id" --> Products;
    Products -- "marca_id → id" --> Brands;
    Products -- "categorias_ids" --> Categories;
    Products -- "variacoes_ids" --> GridValues;
    GridValues -- "grade_id → id" --> Grids;
```

# Use Cases for Data Analysis

The queries below run on [Explorer](https://app.nekt.ai/explorer). Replace the table names with the ones you chose for this source.

### 1. Daily revenue of approved orders

```sql theme={null}
SELECT
  DATE(data_criacao) AS dia,
  COUNT(*) AS pedidos,
  SUM(valor_total) AS receita,
  SUM(valor_total) / COUNT(*) AS ticket_medio
FROM loja_integrada_orders
WHERE situacao_aprovado = true
GROUP BY 1
ORDER BY 1 DESC
```

### 2. Best-selling SKUs

```sql theme={null}
SELECT
  i.sku,
  MAX(i.nome) AS produto,
  SUM(i.quantidade) AS unidades,
  SUM(i.preco_subtotal) AS receita
FROM loja_integrada_order_items i
JOIN loja_integrada_orders o ON o.numero = i.pedido_numero
WHERE o.situacao_aprovado = true
GROUP BY i.sku
ORDER BY receita DESC
LIMIT 20
```

## Implementation Notes

### Data Quality Considerations

* Dates and times are converted from Brasília time (how Loja Integrada stores them) to UTC.
* An order status change updates the order's last modification date, so the next sync reads the order again and refreshes its status, items, payments and shipments.
* `product_stocks` and `product_prices` hold the current values and are read in full on every sync. Price and stock changes do not necessarily update a product's modification date, so use these two streams for prices and stock.
* Products deleted in the panel stay in the `products` table with `removido` set to true.
* Rows removed from an order after it was synced (an item taken out of the order, a replaced payment) stay in `order_items`, `order_payments`, `order_shipments` and `order_status_history` until a Full sync, because these tables are updated by row identifier.
* Besides the order's last modification date, every sync checks the status of the orders created in the last **Status Check Window** days and re-reads the ones whose status changed, so a status change is never missed in that window.

### API Limits & Performance

* Loja Integrada allows 100 API requests per minute per store, shared with the store's other integrations (ERP, hub, marketplaces). The connector uses only its **API Rate Share** of that limit (50% by default), slows down further when Loja Integrada says the limit was reached and waits up to 30 minutes for it before failing, so a sync can take longer when other integrations are busy.
* Each order and each changed product is read with its own request; `order_status_history` adds one request per order. Deselect it if you do not need the full history of status changes.
* A stream selected for the first time among `order_items`, `order_payments`, `order_shipments` and `order_status_history` makes the next sync read every order since the Start Date again, so that its table is complete.

## Troubleshooting

| Error or symptom | What it means | What to do |
| :- | :- | :- |
| "Loja Integrada rejected the Personal Token of this source" | The token is wrong, was removed, or expired (3 months after it was created or last renewed), or the store's plan no longer includes API access. | Generate a new Personal Token as the store owner and update the source. Renew the token before it expires to avoid this. |
| A table ends as failed with "Loja Integrada refused the Personal Token access" | The token cannot read that data. The other tables keep syncing when skipping that table cannot empty it. | Check that the token was generated by the store owner and that the plan includes the data, or deselect that table. |
| The sync fails with "Skipping ... in this sync would empty those tables" | The token cannot read a table that is replaced on every sync (or this is the first sync or a Full sync). Skipping it would leave the table empty, so the sync stops before reading anything. | If a table is refused on the first sync, deselect it (or fix the token's permissions). Otherwise fix the token or the plan, or deselect those tables. |
| "Loja Integrada is limiting how fast this sync may read" | The store reached its limit of 100 requests per minute, often because of other integrations. | Nothing to do: the connector waits and continues. If syncs fail because of it, schedule them when the other integrations are quieter. |
| The first sync takes hours | Every order since the Start Date is read one by one. | Expected. Use a later Start Date for a shorter first sync, or raise the API Rate Share if the store's other integrations allow it; later syncs read only what changed. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.