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

# Etsy ledger

> Keep your own copy of a shop's Etsy payment account ledger and add up what each order earned, without losing or double-counting money.

`GET /v1/workspace/ledger` serves a connected shop's Etsy payment account ledger, entry by entry, as Etsy booked it: sales, fees, taxes, refunds, advertising fees and payouts, each with the balance after it. Each entry says which order it belongs to. It needs an [API key](https://docs.alura.io/authentication.md) with the `workspace:read` and `orders:read` scopes, which only a workspace owner or admin can create; AI assistants cannot reach it over an MCP connection. This page covers how to keep a correct copy and compute profit per order from it.

## Copy the ledger

1. Start with `after=0`.
2. Call `GET /v1/workspace/ledger?shop_id=<shop>&after=<after>`.
3. Upsert every entry by `id`. A later sync can rewrite an entry, so never insert blindly.
4. Set `after` to the last entry's `sequence_number` and repeat until a page comes back empty.

```bash cURL theme={null}
curl --fail-with-body -sS -G https://api.alura.io/v1/workspace/ledger \
  -H "Authorization: Bearer $ALURA_API_KEY" \
  --data-urlencode "shop_id=22841907" \
  --data-urlencode "after=0"
```

```typescript TypeScript theme={null}
interface Entry {
  id: string;
  sequence_number: number;
  order_id: string | null;
  order_link: 'order' | 'listing' | 'none' | 'unknown';
  amount: { amount: string; currency: string } | null;
}
interface Page {
  data: Entry[];
  summary: { not_stored: { from: number; to: number; after: number } | null };
}

// Your copy of the ledger, by entry id: a later sync can rewrite an entry, so upsert.
const entries = new Map<string, Entry>();
let after = 0;
for (;;) {
  const res = await fetch(`https://api.alura.io/v1/workspace/ledger?shop_id=22841907&after=${after}`, { headers: { Authorization: `Bearer ${process.env.ALURA_API_KEY}` } });
  if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
  const page = (await res.json()) as Page;
  for (const entry of page.data) entries.set(entry.id, entry);
  const hole = page.summary.not_stored;
  if (hole !== null) {
    // Hold here and read again later from the same `after`.
    console.log(`stopped before sequence numbers ${hole.from} to ${hole.to}`);
    break;
  }
  if (page.data.length === 0) break;
  after = page.data.at(-1)!.sequence_number;
}

// What each order earned after Etsy's fees and taxes, per currency, in minor units. An entry without an amount is never
// counted as 0: it leaves its order incomplete. An `unknown` entry may belong to any order, so while one remains, no
// total is complete.
const orders = new Map<string, { cents: Map<string, number>; missing: number }>();
let unknown = 0;
let noAmount = 0;
for (const entry of entries.values()) {
  if (entry.order_link === 'unknown') unknown++;
  if (entry.amount === null) noAmount++;
  if (entry.order_link !== 'order' || entry.order_id === null) continue;
  const order = orders.get(entry.order_id) ?? { cents: new Map<string, number>(), missing: 0 };
  orders.set(entry.order_id, order);
  if (entry.amount === null) {
    order.missing++;
    continue;
  }
  const { amount, currency } = entry.amount;
  order.cents.set(currency, (order.cents.get(currency) ?? 0) + Math.round(Number(amount) * 100));
}
console.log(`${entries.size} entries, ${unknown} not tied to an order yet, ${noAmount} without an amount`);
for (const [id, order] of orders) {
  const sums = [...order.cents].map(([currency, cents]) => `${(cents / 100).toFixed(2)} ${currency}`).join(' + ');
  console.log(`order ${id}: ${sums}${order.missing > 0 ? ` (incomplete: ${order.missing} entries without an amount)` : ''}`);
}
if (unknown > 0) console.log(`totals incomplete: ${unknown} entries are not tied to an order yet; read them again later`);
```

```python Python theme={null}
import json
import os
import urllib.parse
import urllib.request

# Your copy of the ledger, by entry id: a later sync can rewrite an entry, so upsert.
entries = {}
after = 0
while True:
    query = urllib.parse.urlencode({"shop_id": "22841907", "after": after})
    request = urllib.request.Request(
        f"https://api.alura.io/v1/workspace/ledger?{query}",
        headers={"Authorization": f"Bearer {os.environ['ALURA_API_KEY']}"},
    )
    with urllib.request.urlopen(request) as response:
        page = json.load(response)
    for entry in page["data"]:
        entries[entry["id"]] = entry
    hole = page["summary"]["not_stored"]
    if hole is not None:
        # Hold here and read again later from the same `after`.
        print(f"stopped before sequence numbers {hole['from']} to {hole['to']}")
        break
    if not page["data"]:
        break
    after = page["data"][-1]["sequence_number"]

# What each order earned after Etsy's fees and taxes, per currency, in minor units. An entry without an amount is never
# counted as 0: it leaves its order incomplete. An `unknown` entry may belong to any order, so while one remains, no
# total is complete.
orders = {}
unknown = 0
no_amount = 0
for entry in entries.values():
    if entry["order_link"] == "unknown":
        unknown += 1
    if entry["amount"] is None:
        no_amount += 1
    if entry["order_link"] != "order" or entry["order_id"] is None:
        continue
    order = orders.setdefault(entry["order_id"], {"cents": {}, "missing": 0})
    if entry["amount"] is None:
        order["missing"] += 1
        continue
    currency = entry["amount"]["currency"]
    order["cents"][currency] = order["cents"].get(currency, 0) + round(float(entry["amount"]["amount"]) * 100)
print(f"{len(entries)} entries, {unknown} not tied to an order yet, {no_amount} without an amount")
for order_id, order in orders.items():
    sums = " + ".join(f"{cents / 100:.2f} {currency}" for currency, cents in order["cents"].items())
    note = f" (incomplete: {order['missing']} entries without an amount)" if order["missing"] > 0 else ""
    print(f"order {order_id}: {sums}{note}")
if unknown > 0:
    print(f"totals incomplete: {unknown} entries are not tied to an order yet; read them again later")
```

Then keep it current: call again from the last `sequence_number` you stored, and read the whole shop again from `after=0` now and then.

## Stop at a hole

A page never passes sequence numbers Alura has not stored. It stops before them with `has_more: false` and `next_cursor: null`, names them in `summary.not_stored`, and adds one of two notices:

* `ledger_gap`: entries are stored on both sides of the range.
* `ledger_history_pending`: nothing is stored up to the range yet, as while a shop's older history is still being fetched. Older entries can still arrive, so read from `after=0` again later.

Hold there and read again later from the same `after`. Send `not_stored.after` only to skip the range on purpose: a copy that skips it never gets those entries.

## Add up an order

Group entries by `order_id` where `order_link` is `order`. The sum is what the order earned after Etsy's fees, taxes and refunds.

* Treat an order's sum as final only once its refunds have had time to arrive. A transaction fee refund can arrive a day or more after the refund it belongs to.
* An entry with `order_link: "unknown"` is one Alura can't tie to an order yet. It never means "no order". Read it again later.
* Entries with `order_link: "listing"` are per-listing fees, such as listing fees and renewals after a sale. Attribute them by `listing_id` if your profit calculation spreads listing costs.
* Entries with `order_link: "none"` name neither an order nor a listing, such as advertising fees and payouts. Some of them are still costs of selling, such as VAT on seller fees (`vat_seller_services`), which Etsy books directly after the fee it applies to and without a reference. Count them in your profit even though they name no order.

## Money

`amount` and `balance` are in the entry's own `currency`. When a payment account changed currency, the running balance does not carry across the change, so never add balances of two currencies. An entry with `amount_error: "currency_unknown"` has `null` amounts: Alura has not verified how Etsy counts that currency in the ledger yet.


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