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

# Budget transfers this year

> Every move of money between budgets in the current accounting year, with the budget names, in a Google Sheet the trustees can read.

> [!NOTE]
>
> * **For:** trustees and treasurers
> * **You get:** a **Budget transfers** tab listing each move between budgets this year: when, from which budget, to which, and how much
> * **Time:** about ten minutes
> * **Scopes:** `accounting:read`

A budget the trustees agreed at the start of the year changes as the year goes on: the Beavers underspend, the summer trip costs more, and the treasurer moves money between budgets. Trustees should see every move. This recipe lists them, with the budgets' names, for the year that is open now.

No money moves in the bank when a budget changes. A budget transfer only changes what each budget has left to spend.

## 1. Try the request

Paste this into a terminal to see the demo group's budget transfers:

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

Each move has its accounting year (`periodId`), the two budgets (`sourceBudgetId` and `destinationBudgetId`), the `amount` in pounds and when it was made (`createdAt`). The reason the treasurer typed is shown in Scoutworks, on the budget, but the API does not return it.

## 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 → budget transfers this year. https://developers.scoutworks.app/recipes/budget-transfers-log

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

function budgetTransfers() {
  // The accounting year that is open now: the latest one not closed.
  const years = readAll('/accounting-periods').filter(function (p) { return !p.isClosed; });
  if (years.length === 0) throw new Error('There is no open accounting year.');
  years.sort(function (a, b) { return b.startDate.localeCompare(a.startDate); });
  const year = years[0];

  const names = {};
  readAll('/budgets?periodId=' + year.id).forEach(function (b) { names[b.id] = b.name; });

  const moves = readAll('/budget-transfers?periodId=' + year.id);
  const rows = moves.map(function (m) {
    return [
      m.createdAt.slice(0, 10),
      safe(names[m.sourceBudgetId] || 'A budget from another year'),
      safe(names[m.destinationBudgetId] || 'A budget from another year'),
      Number(m.amount),
    ];
  });
  const sheet = writeTab('Budget transfers', [['Date', 'From', 'To', 'Amount (£)']].concat(rows));
  if (rows.length > 0) sheet.getRange(2, 4, rows.length, 1).setNumberFormat('£#,##0.00');

  const total = rows.reduce(function (sum, r) { return sum + r[3]; }, 0);
  SpreadsheetApp.getActive().toast(rows.length + ' moves in ' + year.name + ', £' + total.toFixed(2) + ' in all.');
}

// Replaces a tab's contents with these rows.
function writeTab(name, rows) {
  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName(name) || book.insertSheet(name);
  sheet.clearContents();
  sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
  sheet.setFrozenRows(1);
  return sheet;
}

// 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 a name 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 and run it

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 it, or your own key. Then choose **budgetTransfers** and press **Run**.

## 4. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own. The key needs only `accounting:read`. The sheet holds budget names and amounts, and no one's name, so it is safe to share with every trustee.

## Variations

* **One budget's history:** add `&budgetId=` and the budget's id to the `/budget-transfers` request. It lists moves in and out of that budget.
* **Last year:** pick the closed year from `/accounting-periods` instead of the open one.

## If something goes wrong

* **`403 insufficient_scope`**: the key does not have `accounting:read`.
* **`400 invalid_request`** naming `periodId` or `budgetId`: the id is not one of your group's. Read it again from `/accounting-periods` or `/budgets`.

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.