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

# Bank statement into the books

> Paste a bank statement into a Google Sheet and add each line to the books in Scoutworks. Run it twice and nothing is added twice.

> [!NOTE]
>
> * **For:** treasurers
> * **You get:** every line of a bank statement added to the books, with the Scoutworks id written next to it
> * **Time:** about twenty minutes the first time, then a minute each month
> * **Scopes:** `accounting:read` and `accounting:write`

Some banks cannot connect to Scoutworks, and some groups keep a cash book or a second account by hand. This recipe takes a statement you paste into a Google Sheet and adds each line to the books in Scoutworks. It writes the new transaction's id next to each line, so a second run skips the lines already added.

> [!WARNING]
>
> This recipe changes your books, so the read-only [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) cannot run it. Use your own key with `accounting:write`, and [try it on one made-up line](#5-try-it-on-one-line) before the whole statement. Use it **or** the bank import in Scoutworks for an account, not both: the same payment added both ways appears twice.

## 1. Create a key

A group admin creates a key in **Settings → Integrations → API keys** with the scopes **`accounting:read`** and **`accounting:write`**. Transactions the key adds show that admin as the person who added them, and Scoutworks marks them as added by the key. See [Authentication](https://developers.scoutworks.app/guides/authentication.md).

## 2. Find the bank account

The script needs the id of the account the statement is for. List your accounts:

```bash theme={null}
curl https://api.scoutworks.app/api/v1/bank-accounts \
  -H "Authorization: Bearer $SCOUTWORKS_API_KEY"
```

Copy the `id` of the account. You add it to the script in step 4.

## 3. Lay out the sheet

Make a tab called **Statement**. Row 1 holds headings. From row 2, paste the statement so that:

| Column | Holds | Example |
| - | - | - |
| A | The date | `03/11/2026` |
| B | What the bank says the line is | `CARD PAYMENT SCOUT SHOP` |
| C | The amount. Money in is positive, money out is negative. | `-42.50` |
| D | Leave empty. The script writes the Scoutworks id here. | |
| E | Leave empty. The script writes any problem here. | |

Before you paste, select column A and choose **Format → Number → Plain text**. Otherwise a sheet set to the United States locale reads `03/11/2026` as 11 March, and the line goes into the books on the wrong date with no warning. As plain text, every date is read as day, month, year.

If your bank gives **Paid in** and **Paid out** columns, put `=paid_in - paid_out` in column C, or combine them before you paste.

## 4. Add the script

Choose **Extensions → Apps Script**. Delete what is there, paste the script below and choose **Save**.

```javascript Code.gs theme={null}
// Scoutworks → bank statement into the books. https://developers.scoutworks.app/recipes/bank-statement

const BASE = 'https://api.scoutworks.app/api/v1';

function addStatementToBooks() {
  const props = PropertiesService.getScriptProperties();
  const apiKey = props.getProperty('SCOUTWORKS_API_KEY');
  const bankAccountId = props.getProperty('SCOUTWORKS_BANK_ACCOUNT_ID');
  if (!apiKey || !bankAccountId) {
    throw new Error('Add SCOUTWORKS_API_KEY and SCOUTWORKS_BANK_ACCOUNT_ID in Project Settings → Script Properties.');
  }

  const sheet = SpreadsheetApp.getActive().getSheetByName('Statement');
  const rows = sheet.getDataRange().getValues();
  const seen = {};
  let added = 0;

  for (let i = 1; i < rows.length; i++) {
    const [date, description, amount, id] = rows[i];
    if (date === '' || amount === '' || Number(amount) === 0) continue;
    let day;
    try {
      day = toIsoDate(date);
    } catch (e) {
      sheet.getRange(i + 1, 5).setValue(e.message);
      continue;
    }

    // The same line can appear twice on one day (two £5 subs, say), so
    // count repeats and make each one's key different.
    const line = [bankAccountId, day, description, Number(amount).toFixed(2)].join('|');
    seen[line] = (seen[line] || 0) + 1;
    if (id) continue; // Already in the books.

    const res = post('/transactions', apiKey, 'bank-' + hash(line + '|' + seen[line]), {
      date: day,
      type: Number(amount) < 0 ? 'expense' : 'income',
      amount: Math.abs(Number(amount)).toFixed(2),
      bankAccountId: bankAccountId,
      description: String(description).slice(0, 500) || 'Bank statement line',
    });
    if (res.ok) {
      sheet.getRange(i + 1, 4, 1, 2).setValues([[res.body.data.id, '']]);
      added++;
    } else {
      sheet.getRange(i + 1, 5).setValue(res.body.error.code + ': ' + res.body.error.message);
    }
    Utilities.sleep(2100); // Stay under 30 changes a minute.
  }
  SpreadsheetApp.getActive().toast(added + ' lines added to the books.');
}

// Sends one write. Waits and tries again if it is rate limited or still running.
function post(path, apiKey, idempotencyKey, payload) {
  for (let attempt = 0; attempt < 4; attempt++) {
    const res = UrlFetchApp.fetch(BASE + path, {
      method: 'post',
      contentType: 'application/json',
      headers: { Authorization: 'Bearer ' + apiKey, 'Idempotency-Key': idempotencyKey },
      payload: JSON.stringify(payload),
      muteHttpExceptions: true,
    });
    const code = res.getResponseCode();
    const body = JSON.parse(res.getContentText());
    if (code === 200 || code === 201) return { ok: true, body: body };
    if (code === 429) { Utilities.sleep((body.retryAfter || 30) * 1000); continue; }
    if (code === 409 && body.error.code === 'conflict') { Utilities.sleep(5000); continue; }
    return { ok: false, body: body };
  }
  return { ok: false, body: { error: { code: 'busy', message: 'Scoutworks is still busy. Run it again in a minute.' } } };
}

// A sheet date, or text like 03/11/2026, as 2026-11-03.
function toIsoDate(value) {
  if (value instanceof Date) return Utilities.formatDate(value, 'Europe/London', 'yyyy-MM-dd');
  const m = String(value).match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
  if (!m) throw new Error('Cannot read the date "' + value + '". Use DD/MM/YYYY.');
  return m[3] + '-' + ('0' + m[2]).slice(-2) + '-' + ('0' + m[1]).slice(-2);
}

// A short fingerprint of a line, used as its Idempotency-Key.
function hash(text) {
  return Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, text)
    .map(function (b) { return ('0' + (b & 0xff).toString(16)).slice(-2); })
    .join('')
    .slice(0, 40);
}
```

Then choose **Project Settings** (the cog), **Script Properties → Add script property**, and add two:

* `SCOUTWORKS_API_KEY`: your key.
* `SCOUTWORKS_BANK_ACCOUNT_ID`: the `id` from step 2.

## 5. Try it on one line

Before you add a whole statement, check that one line arrives as you expect.

**1. Add one made-up line**

On the **Statement** tab, leave only one row under the headings: today's date, `TEST from the Scoutworks recipe` in column B, and `-0.01` in column C.

**2. Run it**

Choose **addStatementToBooks** and press **Run**. The first time, Google asks you to allow the script to reach an outside service. Column D gets an id.

**3. Check it in Scoutworks**

Open the bank account in Scoutworks. The test line is there, on today's date, for 1p out, with no category.

**4. Delete the test line**

Delete it in Scoutworks. Then delete the test row from the sheet.

Use a made-up line, not one from your statement. Scoutworks remembers each line's `Idempotency-Key` for 24 hours, so a real line you add, delete and add again the same day would not come back.

## 6. Run it

Paste the statement into the **Statement** tab and choose **Run**. Each line gets an id in column D as it is added. A line Scoutworks refuses gets the reason in column E, and the others carry on.

The script adds about 28 lines a minute, because writes are limited to 30 a minute. Google stops a script after six minutes. If a long statement stops part way, press **Run** again: lines that already have an id are skipped.

## 7. Categorise the new lines

The lines arrive in the books without a category. Choose one for each in Scoutworks, or with the [Categorise the uncategorised](https://developers.scoutworks.app/recipes/categorise-transactions.md) recipe.

## Why nothing is added twice

Two things stop a line being added twice:

1. **The id in column D.** A line with an id is skipped. Do not clear column D.
2. **The `Idempotency-Key`.** Each line is sent with a key made from its account, date, description, amount and how many times that exact line appears. If the network drops after Scoutworks saved a line but before the sheet heard back, the next run sends the same key and Scoutworks answers with the transaction it already made. It remembers a key for 24 hours. [Writing data](https://developers.scoutworks.app/guides/writing-data.md) explains the rules.

## If something goes wrong

* **`409 period_closed`** in column E: the date falls in an accounting year that is closed. A closed year cannot change.
* **`400 invalid_request`**: usually a bank account id that is wrong or closed. The message says which.
* **Cannot read the date** in column E: the script reads dates as the sheet's own dates or as `DD/MM/YYYY`. Fix the date and run it again.
* **`402 subscription_required`**: the group's subscription has lapsed. The key can still read, but not change anything.
* **`403 insufficient_scope`**: the key needs both `accounting:read` and `accounting:write`.

A line added by mistake can be deleted in Scoutworks, or with `DELETE /transactions/{id}` while it is not yet reconciled. Any other line answers `409 source_locked`: the API deletes only lines it added. See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code.


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