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

# Categorise the uncategorised

> List every transaction without a category in a Google Sheet, choose one from a dropdown, and save your choices back to Scoutworks in one go.

> [!NOTE]
>
> * **For:** treasurers
> * **You get:** an **Uncategorised** tab with a category dropdown on each line, and a menu command that saves your choices
> * **Time:** about fifteen minutes the first time
> * **Scopes:** `accounting:read`, `accounting.people:read` and `accounting:write`

Lines from a bank feed or a statement arrive in the books without a category. Choosing one for each line in the app is slow when there are a hundred of them. This recipe puts every uncategorised line for the accounting year in a sheet. You pick a category from a dropdown on each row, sort and filter as you like, then save them all at once.

> [!WARNING]
>
> Saving changes your books, so the read-only [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) can load the list but cannot save it. Use your own key with `accounting:write` to save, and [try it on one row](#5-try-it-on-one-row) first.

## 1. Try the requests

The sheet uses two lists. Paste these into a terminal to see them for the demo group:

```bash theme={null}
curl "https://api-demo.scoutworks.app/api/v1/accounting-categories?limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"

curl "https://api-demo.scoutworks.app/api/v1/transactions?from=2026-04-01&limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

A transaction with no category has `"categoryId": null`. A line split across several categories has its categories on its `splits`, so the script leaves split lines alone.

## 2. Add the script

In your Google Sheet, choose **Extensions → Apps Script**. Delete what is there, paste the script below and choose **Save**.

```javascript Code.gs theme={null}
// Scoutworks → categorise the uncategorised. https://developers.scoutworks.app/recipes/categorise-transactions

const BASE = 'https://api-demo.scoutworks.app/api/v1';
const TAB = 'Uncategorised';
const HEADER = ['Date', 'In or out', 'Amount (£)', 'Description', 'Paid to or by', 'Category', 'Result', 'id', 'updatedAt'];

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Scoutworks')
    .addItem('Load uncategorised lines', 'loadUncategorised')
    .addItem('Save categories', 'saveCategories')
    .addToUi();
}

function loadUncategorised() {
  const today = Utilities.formatDate(new Date(), 'Europe/London', 'yyyy-MM-dd');
  const year = readAll('/accounting-periods').find(function (p) {
    return p.startDate.slice(0, 10) <= today && today <= p.endDate.slice(0, 10);
  });
  if (!year) throw new Error('No accounting year includes today. Set one up in Scoutworks under Finance.');

  // Category names for each direction, for the dropdowns.
  const names = { income: [], expense: [] };
  readAll('/accounting-categories').forEach(function (c) {
    if (!c.isHidden) names[c.type].push(c.name);
  });

  const lines = readAll('/transactions?from=' + year.startDate.slice(0, 10)).filter(function (t) {
    return !t.categoryId && t.splits.length === 0 && !t.isTransfer;
  });
  const rows = lines.map(function (t) {
    return [
      t.date.slice(0, 10),
      t.type === 'income' ? 'In' : 'Out',
      Number(t.amount),
      safe(t.description || ''),
      safe(t.counterparty || ''),
      '',
      '',
      t.id,
      t.updatedAt,
    ];
  });

  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName(TAB) || book.insertSheet(TAB);
  sheet.clear();
  sheet.getRange(1, 1, 1, HEADER.length).setValues([HEADER]);
  sheet.setFrozenRows(1);
  sheet.hideColumns(8, 2);
  if (rows.length > 0) {
    sheet.getRange(2, 1, rows.length, HEADER.length).setValues(rows);
    sheet.getRange(2, 3, rows.length, 1).setNumberFormat('£#,##0.00');
    // Money in gets income categories; money out gets spending ones.
    const rule = function (list) {
      return SpreadsheetApp.newDataValidation().requireValueInList(list.sort(), true).setAllowInvalid(false).build();
    };
    lines.forEach(function (t, i) {
      sheet.getRange(i + 2, 6).setDataValidation(rule(names[t.type]));
    });
  }
  book.toast(rows.length + ' lines need a category.');
}

function saveCategories() {
  const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  const ids = {};
  readAll('/accounting-categories').forEach(function (c) {
    ids[c.type + '|' + c.name] = c.id;
  });

  const sheet = SpreadsheetApp.getActive().getSheetByName(TAB);
  const rows = sheet.getDataRange().getValues();
  let saved = 0;
  for (let i = 1; i < rows.length; i++) {
    const [, direction, , , , category, result, id, updatedAt] = rows[i];
    if (!category || result === 'Saved') continue;
    const categoryId = ids[(direction === 'In' ? 'income' : 'expense') + '|' + category];
    if (!categoryId) {
      sheet.getRange(i + 1, 7).setValue('No such category. Load again to refresh the list.');
      continue;
    }
    const res = UrlFetchApp.fetch(BASE + '/transactions/' + id, {
      method: 'patch',
      contentType: 'application/json',
      headers: { Authorization: 'Bearer ' + apiKey },
      payload: JSON.stringify({ updatedAt: updatedAt, categoryId: categoryId }),
      muteHttpExceptions: true,
    });
    const body = JSON.parse(res.getContentText());
    if (res.getResponseCode() === 200) {
      sheet.getRange(i + 1, 7, 1, 3).setValues([['Saved', id, body.data.updatedAt]]);
      saved++;
    } else if (res.getResponseCode() === 412) {
      sheet.getRange(i + 1, 7).setValue('Changed in Scoutworks since you loaded it. Load again.');
    } else {
      sheet.getRange(i + 1, 7).setValue(body.error.code + ': ' + body.error.message);
    }
    Utilities.sleep(2100); // Stay under 30 changes a minute.
  }
  SpreadsheetApp.getActive().toast(saved + ' categories saved.');
}

// Every item in a list, following nextCursor to the last page.
function readAll(path) {
  const items = [];
  let cursor = null;
  do {
    let url = BASE + path + (path.indexOf('?') === -1 ? '?' : '&') + 'limit=200';
    if (cursor) url += '&cursor=' + encodeURIComponent(cursor);
    const body = fetchScoutworks(url);
    items.push.apply(items, body.data);
    cursor = body.nextCursor;
  } while (cursor);
  return items;
}

// Calls the API. Waits and tries again if the rate limit is reached.
function fetchScoutworks(url) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  if (!apiKey) throw new Error('Add SCOUTWORKS_API_KEY in Project Settings → Script Properties.');
  for (let attempt = 0; attempt < 3; attempt++) {
    const res = UrlFetchApp.fetch(url, {
      headers: { Authorization: 'Bearer ' + apiKey },
      muteHttpExceptions: true,
    });
    const body = JSON.parse(res.getContentText());
    if (res.getResponseCode() === 200) return body;
    if (res.getResponseCode() === 429) {
      Utilities.sleep((body.retryAfter || 30) * 1000);
      continue;
    }
    throw new Error(body.error.code + ': ' + body.error.message);
  }
  throw new Error('Scoutworks is still busy. Try again in a minute.');
}

// Stops text that starts with = + - or @ from running as a formula.
function safe(value) {
  const text = String(value);
  return /^\s*[=+\-@]/.test(text) ? "'" + text : text;
}
```

## 3. Add your key

Choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`. Value: the [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) to try loading, or your own key.

## 4. Load the lines

Reload the sheet. A **Scoutworks** menu appears. Choose **Scoutworks → Load uncategorised lines**. The first time, Google asks you to allow the script to reach an outside service.

Each row is one line from this accounting year with no category. Money in offers income categories, and money out offers spending categories. Sort and filter the tab however helps: by who was paid, say, so you can fill a run of rows at once.

## 5. Try it on one row

Before you save many rows, check that one saves as you expect.

**1. Choose one category**

Choose a category on one row only.

**2. Save it**

Choose **Scoutworks → Save categories**. The row says **Saved**.

**3. Check it in Scoutworks**

Find that line in Scoutworks. It shows the category you chose, and nothing else about it has changed. If it is not what you meant, change it back there.

## 6. Save your choices

Choose a category on as many rows as you like, then **Scoutworks → Save categories**. Each row says **Saved** or why it was not. Rows you left blank are not touched. Run **Load uncategorised lines** again to start afresh with what is left.

## 7. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own. The key needs:

* `accounting:read` to read the lines and categories;
* `accounting.people:read` to show each line's description and who it was paid to or by. Without it, those columns are empty;
* `accounting:write` to save.

## Safe to use alongside the app

Each row remembers the line's `updatedAt` from when you loaded it. If someone changes the line in Scoutworks before you save, the save for that row is refused with `412 stale_write`, and the row says so. Nobody's change is overwritten. Load again to see the line as it is now. [Writing data](https://developers.scoutworks.app/guides/writing-data.md) explains how this works for every record.

The script changes only the category. The amount, date and description stay exactly as the bank or the treasurer recorded them.

## If something goes wrong

* **`412 stale_write`**: the line changed after you loaded it. Load again.
* **`409 period_closed`**: the line is in a closed accounting year, which cannot change.
* **`403 insufficient_scope`**: the key cannot write. Add `accounting:write`, or use your own key in place of the sandbox key.

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.