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

# Expense claims for the monthly report

> Last month’s expense claims for the treasurer’s report: what came in, what was paid by category, and what is still waiting. In a Google Sheet.

> [!NOTE]
>
> * **For:** treasurers
> * **You get:** an **Expenses** tab with last month's claims, the money paid out by category, and the claims still waiting
> * **Time:** about ten minutes
> * **Scopes:** `expenses:read` and `accounting:read`, plus `expenses.people:read` for who claimed

Most treasurers report to the trustees once a month. One section of that report is always the same: which expense claims came in, what was paid, and what is still waiting. This recipe builds that section in a Google Sheet. Run it on the first of the month and paste it into your report.

## 1. Try the request

Paste this into a terminal to see the claims the demo group received in October 2026:

```bash theme={null}
curl "https://api-demo.scoutworks.app/api/v1/expense-claims?from=2026-10-01T00:00:00Z&to=2026-11-01T00:00:00Z&limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

Each claim has a `status` worked out from its lines, a `total`, and its `lines`. Each line has its own status, and a `settledAt` once it is paid.

## 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 → expense claims for the monthly report. https://developers.scoutworks.app/recipes/expense-claims-report

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

const STATUS = { pending: 'Waiting for approval', approved: 'Approved, not yet paid', reimbursed: 'Paid', rejected: 'Rejected' };

function expensesReport() {
  // Last calendar month, UK time: [start, end).
  const now = new Date();
  const start = Utilities.formatDate(new Date(now.getFullYear(), now.getMonth() - 1, 1), 'Europe/London', 'yyyy-MM-dd');
  const end = Utilities.formatDate(new Date(now.getFullYear(), now.getMonth(), 1), 'Europe/London', 'yyyy-MM-dd');
  // Timestamps are UTC: compare them as UK dates, so 00:30 on the 1st in summer counts in the right month.
  const inMonth = function (ts) {
    if (!ts) return false;
    const day = Utilities.formatDate(new Date(ts), 'Europe/London', 'yyyy-MM-dd');
    return day >= start && day < end;
  };

  const categories = {};
  readAll('/accounting-categories').forEach(function (c) { categories[c.id] = c.name; });
  const claims = readAll('/expense-claims');

  const rows = [['Expense claims, ' + start + ' to ' + end, '', '', ''], ['', '', '', '']];

  rows.push(['Claims received', 'Who', 'Status', 'Total (£)']);
  claims.filter(function (c) { return inMonth(c.submittedAt); }).forEach(function (c) {
    rows.push([c.referenceNumber, safe(c.claimantName || ''), STATUS[c.status], Number(c.total)]);
  });

  rows.push(['', '', '', ''], ['Paid out by category', '', '', 'Paid (£)']);
  const paid = {};
  claims.forEach(function (c) {
    c.lines.forEach(function (l) {
      if (l.status !== 'settled' || !inMonth(l.settledAt)) return;
      const name = categories[l.categoryId] || 'No category';
      paid[name] = (paid[name] || 0) + Number(l.amount);
    });
  });
  let total = 0;
  Object.keys(paid).sort().forEach(function (name) {
    rows.push([safe(name), '', '', paid[name]]);
    total += paid[name];
  });
  rows.push(['Total paid', '', '', total]);

  // Only the lines still to pay: a claim's total also counts lines already paid or rejected.
  rows.push(['', '', '', ''], ['Still waiting', 'Who', 'Status', 'Still to pay (£)']);
  claims.forEach(function (c) {
    const owed = c.lines
      .filter(function (l) { return l.status === 'pending' || l.status === 'approved'; })
      .reduce(function (sum, l) { return sum + Number(l.amount); }, 0);
    if (owed > 0) rows.push([c.referenceNumber, safe(c.claimantName || ''), STATUS[c.status], owed]);
  });

  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName('Expenses') || book.insertSheet('Expenses');
  sheet.clearContents();
  sheet.getRange(1, 1, rows.length, 4).setValues(rows);
  sheet.getRange(1, 4, rows.length, 1).setNumberFormat('£#,##0.00');
  book.toast('Expenses for ' + start.slice(0, 7) + ' are ready.');
}

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

The **Expenses** tab has three parts:

1. **Claims received** last month, with who claimed and where each one stands now.
2. **Paid out by category**: every line paid last month, added up by category. A claim submitted in an earlier month but paid last month counts here.
3. **Still waiting**: every claim with lines not yet approved, or approved but not yet paid, whenever it came in. The figure counts only those lines, not lines already paid or rejected.

## 4. Run it on the first of each month

In the script editor, choose **Triggers** (the clock), then **Add Trigger**. Function: `expensesReport`. Event source: **Time-driven**. Type: **Month timer**. Day: **1**. Time: **6am to 7am**. Choose **Save**.

## 5. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own. The key needs `expenses:read` for the claims and `accounting:read` for category names. Add `expenses.people:read` to fill the **Who** column: without it the column is empty and the report names nobody, which suits a report that leaves the meeting.

## If something goes wrong

* **The Who column is empty**: the key does not have `expenses.people:read`. That may be what you want.
* **No category** in the paid list: a line was paid before anyone chose its category. Choose one in Scoutworks.

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.