> ## 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 against actual

> Each budget for this accounting year, what it has spent or raised so far, and what is left. In a Google Sheet that refreshes every morning.

> [!NOTE]
>
> * **For:** treasurers, and the trustees they report to
> * **You get:** a **Budgets** tab with one row per budget, refreshed every morning
> * **Time:** about ten minutes
> * **Scopes:** `accounting:read`

Trustees ask the same question at every meeting: are we on budget? This recipe answers it in a Google Sheet. It reads every budget for the accounting year you are in now, with what each has spent (or, for an income target, raised) and what is left. The figures are the ones the **Budgets** page in Scoutworks shows.

## 1. Try the request

Paste this into a terminal to see the budgets in the demo group:

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

Each budget has its `amount`, what is `available` once budget transfers are counted, what it has `spent`, and what is `remaining`. Money is always a string in pounds, such as `"125.50"`, so it never loses a penny.

## 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 against actual. https://developers.scoutworks.app/recipes/budget-vs-actual

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

function budgetAgainstActual() {
  // The accounting year that today falls in.
  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.');

  const rows = readAll('/budgets?periodId=' + year.id)
    .sort(function (a, b) { return a.type.localeCompare(b.type) || a.name.localeCompare(b.name); })
    .map(function (b) {
      const amount = Number(b.available); // After any budget transfers.
      const used = Number(b.spent);
      return [
        safe(b.name),
        b.type === 'income' ? 'Income target' : 'Spending',
        amount,
        used,
        Number(b.remaining),
        amount > 0 ? used / amount : '',
        b.type === 'expense' && used > amount ? 'Over budget' : '',
      ];
    });

  const header = ['Budget', 'Kind', 'Budget (£)', 'Spent or raised (£)', 'Left (£)', 'Used', 'Check'];
  const sheet = writeTab('Budgets', [header].concat(rows));
  if (rows.length > 0) {
    sheet.getRange(2, 3, rows.length, 3).setNumberFormat('£#,##0.00');
    sheet.getRange(2, 6, rows.length, 1).setNumberFormat('0%');
  }
  SpreadsheetApp.getActive().toast(rows.length + ' budgets for ' + year.name + '.');
}

// 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

In the script editor, 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.

## 4. Run it

Choose **budgetAgainstActual** in the toolbar and press **Run**. The first time, Google asks you to allow the script to reach an outside service. Open the **Budgets** tab. Spending budgets come first. A spending budget that has spent more than its amount says **Over budget**.

## 5. Refresh it every morning

**1. Add a trigger**

In the script editor, choose **Triggers** (the clock), then **Add Trigger**.

**2. Set the timer**

Function: `budgetAgainstActual`. Event source: **Time-driven**. Type: **Day timer**. Time: **6am to 7am**. Choose **Save**.

## 6. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own. A group admin creates the key in **Settings → Integrations → API keys** with the `accounting:read` scope.

## Variations

* **Last year.** Change the `find` to pick the year by name, for example `p.name === '2025-26'`, to compare this year with last.
* **One section.** Each budget lists its `sectionIds`. Keep only the budgets for one section to give its leader their own sheet.
* **Bank balances too.** Add a tab from `/bank-accounts`. Each account has its `balance`, so the trustees see the cash next to the budgets.

## If something goes wrong

* **`403 insufficient_scope`**: the key does not have `accounting:read`. A group admin can add it to the key.
* **No accounting year includes today**: the group has not set up this year in Scoutworks yet, or the last one has ended. A treasurer adds it under **Finance**.

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.