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

# Restricted funds statement for trustees

> Every restricted fund with what it was given, what it has spent and what is left, in a Google Sheet the trustees can read at a glance.

> [!NOTE]
>
> * **For:** treasurers and trustees
> * **You get:** a **Restricted funds** tab with one row per fund, and a **Fund movements** tab with every transfer in and out
> * **Time:** about ten minutes
> * **Scopes:** `accounting:read`

Money given for a purpose, such as a grant for new tents, can only be spent on that purpose. Trustees must be able to show where each restricted fund stands. This recipe lists every fund with what came in, what was spent and what is left, as the **Restricted funds** page in Scoutworks shows it.

## 1. Try the request

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

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

Each fund carries these figures, in pounds:

| Field | What it is |
| - | - |
| `allocated` | What the fund was set up with. |
| `income` | Income lines given to the fund, such as a grant payment. |
| `spent` | Spending lines charged to the fund. |
| `released` | Moved out to general funds, for example what is left once the project is done. |
| `allocatedIn` | Moved in from general funds. |
| `remaining` | `allocated + income − spent − released + allocatedIn`. Negative when the fund is overspent. |

## 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 → restricted funds statement. https://developers.scoutworks.app/recipes/restricted-funds

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

function restrictedFunds() {
  const funds = readAll('/restricted-funds').sort(function (a, b) {
    return Number(b.isActive) - Number(a.isActive) || a.name.localeCompare(b.name);
  });

  const rows = funds.map(function (f) {
    const remaining = Number(f.remaining);
    return [
      safe(f.name),
      f.isActive ? 'Open' : 'Closed ' + (f.closedAt || '').slice(0, 10),
      Number(f.allocated),
      Number(f.income),
      Number(f.spent),
      Number(f.allocatedIn) - Number(f.released),
      remaining,
      remaining < 0 ? 'Overspent' : '',
    ];
  });
  const header = ['Fund', 'Status', 'Set up with (£)', 'Income (£)', 'Spent (£)', 'Moved in or out (£)', 'Left (£)', 'Check'];
  const sheet = writeTab('Restricted funds', [header].concat(rows));
  if (rows.length > 0) sheet.getRange(2, 3, rows.length, 5).setNumberFormat('£#,##0.00;-£#,##0.00');

  // Every transfer in and out of each fund, oldest first.
  const movements = [];
  funds.forEach(function (f) {
    readAll('/restricted-funds/' + f.id + '/movements').forEach(function (m) {
      movements.push([
        m.date.slice(0, 10),
        safe(f.name),
        m.kind === 'release' ? 'Moved out to general funds' : 'Moved in from general funds',
        Number(m.amount),
      ]);
    });
  });
  movements.sort(function (a, b) { return a[0].localeCompare(b[0]); });
  writeTab('Fund movements', [['Date', 'Fund', 'What', 'Amount (£)']].concat(movements));

  SpreadsheetApp.getActive().toast(funds.length + ' funds.');
}

// 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 **restrictedFunds** and press **Run**.

Open funds come first. A fund that has spent more than it holds says **Overspent**: the overspend has come out of general funds, and the trustees should know.

## 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 no names, so it is safe to share with every trustee.

## For the annual accounts

The figures are for the whole life of each fund, not for one accounting year. For the restricted funds note in your annual accounts, you need each fund's balance at the start and end of the year, and what came in and went out in between:

* **In and out during the year:** read the [transactions](https://developers.scoutworks.app/api-reference/introduction.md) with `from` and `to` set to the year. Keep each line whose `restrictedFundId` is the fund. A split line carries its fund on each entry in `splits` instead, so add up the split amounts whose `restrictedFundId` is the fund too. Then add the fund's movements dated in the year.
* **The opening balance:** the fund's `allocated`, plus every line and movement dated before the year starts. A read with `from` and `to` gives only the year itself.

## If something goes wrong

* **`403 insufficient_scope`**: the key does not have `accounting:read`.
* **A fund is missing**: every fund is listed, open and closed. Check the fund was set up as a restricted fund in Scoutworks, not as a budget.

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.