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

# Match refunds to payments

> List the money-out lines waiting in your bank inbox, pick the payment each one refunds from a dropdown, and record them all in Scoutworks with one button.

> [!NOTE]
>
> * **For:** treasurers
> * **You get:** a **Refunds** tab with each money-out bank line still to reconcile, a dropdown of the payments it could refund, and a button that records the ones you pick
> * **Time:** about twenty minutes the first time, then a few minutes each month
> * **Scopes:** `accounting:read`, `accounting:write` and `payments:read`. Add `accounting.people:read` to see who each bank line paid, and `payments.people:read` to see which family each payment came from.

When a camp is cancelled, you pay families back by bank transfer. Each refund then arrives in the bank inbox as money out, and the payment it reverses still reads as paid. Scoutworks' reconcile step links the two. This recipe does that for a month's refunds at once: it lists the lines, you choose the payment for each, and one button records them.

**No money moves.** The refund has already left your bank. Recording it links the bank line to the payment, takes the line out of the inbox and nets the payment's income down in the books, exactly as **Match as refund** in the Bank Inbox does. The API never issues a refund through GoCardless.

> [!WARNING]
>
> Recording changes your books, so the read-only [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) cannot run that part. Use your own key, and [try it on one line](#4-try-it-on-one-line) first.

## 1. Try the requests

Paste these into a terminal to see the demo group's bank inbox and payments:

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

curl "https://api-demo.scoutworks.app/api/v1/payments?limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

Each bank inbox line is in the transaction shape: `id`, `date`, `amount` and the `bankAccountId`. A refund is recorded against a **payment** (`GET /payments`: a Direct Debit collection, or a cycle marked paid by hand), or against a **payment request** paid by hand (`GET /payment-requests` with `status=paid_manually`), which has no payment.

## 2. Add the script

Make a Google Sheet for it, choose **Extensions → Apps Script**, delete what is there, paste the script below and choose **Save**. Then add a script property `SCOUTWORKS_API_KEY` with your key, in **Project Settings → Script Properties**.

```javascript Code.gs theme={null}
// Scoutworks → match refunds to payments. https://developers.scoutworks.app/recipes/match-refunds

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

// Step 1: fills the Refunds tab with each money-out line in the inbox.
function listRefunds() {
  const requests = readAll('/payment-requests');
  const forRequest = {};
  requests.forEach(function (r) { forRequest[r.id] = r.description; });

  // Everything a refund could be against: paid payments, and requests paid by hand.
  const options = [];
  readAll('/payments').forEach(function (p) {
    if (['confirmed', 'paid_out'].indexOf(p.status) === -1 && !p.manuallyMarkedPaid) return;
    const what = p.paymentRequestId ? forRequest[p.paymentRequestId] : 'Subscription';
    options.push(label(p.chargeDate, p.amount, what, p.parent) + ' · payment ' + p.id);
  });
  requests.forEach(function (r) {
    if (r.status !== 'paid_manually') return;
    options.push(label((r.paidManuallyAt || '').slice(0, 10), r.amount, r.description, r.parent) + ' · request ' + r.id);
  });
  options.sort().reverse(); // Newest first.
  writeTab('Payments', [['Payment']].concat(options.map(function (o) { return [safe(o)]; })));

  const lines = readAll('/bank-inbox?type=expense');
  const rows = lines.map(function (t) {
    return [t.date, Number(t.amount), safe(t.counterparty || t.description || ''), t.id, '', Number(t.amount), '', ''];
  });
  const header = ['Date', 'Amount (£)', 'Paid to', 'Bank line id', 'Refund of', 'Amount to record (£)', 'Result', 'Key'];
  const sheet = writeTab('Refunds', [header].concat(rows));
  if (rows.length > 0) {
    const pick = SpreadsheetApp.newDataValidation()
      .requireValueInRange(SpreadsheetApp.getActive().getSheetByName('Payments').getRange('A2:A'), true)
      .build();
    sheet.getRange(2, 5, rows.length, 1).setDataValidation(pick);
  }
  SpreadsheetApp.getActive().toast(rows.length + ' money-out lines to look at.');
}

// Step 2: records each row with a payment chosen and no result yet.
function recordRefunds() {
  const sheet = SpreadsheetApp.getActive().getSheetByName('Refunds');
  const rows = sheet.getDataRange().getValues();
  let recorded = 0;
  for (let i = 1; i < rows.length; i++) {
    const [, , , lineId, choice, amount, result, sent] = rows[i];
    if (!choice || result) continue;
    const m = String(choice).match(/· (payment|request) ([0-9a-f-]{36})$/);
    if (!m) { sheet.getRange(i + 1, 7).setValue('Pick a payment from the list.'); continue; }
    const allocation = { amount: Number(amount).toFixed(2) };
    allocation[m[1] === 'payment' ? 'paymentId' : 'paymentRequestId'] = m[2];
    // One key per try, kept in column H: a retry of this try sends it again,
    // so it is never recorded twice. Clear column H to try again after an undo.
    const key = sent || 'refund-' + Utilities.getUuid();
    sheet.getRange(i + 1, 8).setValue(key);

    const res = UrlFetchApp.fetch(BASE + '/refunds/manual', {
      method: 'post',
      contentType: 'application/json',
      headers: {
        Authorization: 'Bearer ' + apiKey(),
        'Idempotency-Key': key,
      },
      payload: JSON.stringify({ transactionId: lineId, allocations: [allocation] }),
      muteHttpExceptions: true,
    });
    const body = JSON.parse(res.getContentText());
    if ((res.getResponseCode() === 200 || res.getResponseCode() === 201) && body.data.refunds.length > 0) {
      sheet.getRange(i + 1, 7).setValue('Recorded: ' + body.data.refunds[0].id);
      recorded++;
    } 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(recorded + ' refunds recorded.');
}

function label(day, amount, what, parent) {
  const who = parent && parent.name ? ' · ' + parent.name : '';
  return day + ' · £' + amount + ' · ' + (what || 'Payment') + who;
}

// 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.clear();
  sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
  sheet.setFrozenRows(1);
  return sheet;
}

function apiKey() {
  const key = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  if (!key) throw new Error('Add SCOUTWORKS_API_KEY in Project Settings → Script Properties.');
  return key;
}

// 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) {
  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. List the lines

Choose **listRefunds** and press **Run**. The first time, Google asks you to allow the script to reach an outside service. The **Refunds** tab fills with each money-out line in the bank inbox. For each one that is a refund, pick the payment it refunds in **Refund of**. Leave the others empty: a card payment to the Scout Shop is not a refund.

**Amount to record** starts at the whole bank line. Make it smaller when one transfer refunds part of a payment.

## 4. Try it on one line

**1. Pick one**

Choose a payment for one line only. Leave the rest empty.

**2. Record it**

Choose **recordRefunds** and press **Run**. **Result** says **Recorded** and the refund's id.

**3. Check it in Scoutworks**

The line has left the Bank Inbox, and the payment shows as refunded on its payments page.

**4. Undo it, if it is wrong**

Send `DELETE /refunds/manual/{id}` with the refund's id from **Result**. The line goes back to the inbox. To record it again, clear **Result** and **Key** on that row, fix the payment or amount, and run it again. Or leave it, if it was right.

## 5. Record the rest

Pick a payment for each refund and choose **Run** on **recordRefunds**. A row that already has a result is skipped, so run it as often as you like. Choose **listRefunds** again next month: the lines you recorded have left the inbox.

## Why nothing is recorded twice

Each row's first try makes an `Idempotency-Key` and keeps it in **Key**. If the network drops after Scoutworks recorded it, the next run sends the same key and gets the same answer back, not a second refund. And a line already matched has left the inbox, so Scoutworks refuses it.

## If something goes wrong

* **`409 over_refund`**: the amount is more than the bank line, or more than is left to refund on that payment (it may have been refunded already). Read `GET /refunds` with the payment's id as `paymentId` to see what is already refunded.
* **`400 invalid_request`**: usually a line that is not money out, was not imported from a statement, or has already been reconciled, or a payment that is not your group's. The message says which.
* **`409 period_closed`**: the bank line is dated in an accounting year that is closed.
* **`403 insufficient_scope`**: recording needs `accounting:write` **and** `payments:read`, as well as `accounting:read`.
* **`409 source_locked`** when undoing: only a refund the API recorded can be unlinked through the API. Unmatch it in the Bank Inbox instead.

The sheet holds who your group paid and, with `payments.people:read`, parents' names. Share it only with the treasurer and the trustees who need it.

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.