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

# Badge evening sheet

> A Google Sheet with a tick box for each young person and each requirement of a badge. One command signs every tick off in Scoutworks.

On a badge evening, leaders tick off requirements as young people complete them. This recipe gives you a Google Sheet to tick in: one row for each young person, one column for each requirement of the badge. When the evening is over, one command sends the ticks to Scoutworks, and any badge whose last requirement was ticked is ready to award.

It takes about ten minutes to set up.

## 1. Add the script

In a new Google Sheet, choose **Extensions → Apps Script**. Delete what is there, paste the script below and choose **Save**.

```javascript Code.gs theme={null}
// Scoutworks → badge evening sheet. https://developers.scoutworks.app/recipes/badge-evening

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

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Scoutworks')
    .addItem('Build the sheet for a badge', 'buildSheet')
    .addItem('Send ticks to Scoutworks', 'sendTicks')
    .addToUi();
}

// Builds the grid: a row for each young person, a tick box for each requirement.
function buildSheet() {
  const ui = SpreadsheetApp.getUi();
  const badgeId = ui.prompt('Badge id from GET /badge-catalogue, for example badge_050').getResponseText().trim();
  const sectionId = ui.prompt('Section id from GET /sections (leave blank for everyone)').getResponseText().trim();

  const badge = readAll('/badge-catalogue').filter(function (b) { return b.id === badgeId; })[0];
  if (!badge) throw new Error('No badge with the id ' + badgeId + '.');
  const members = readAll(sectionId ? '/members?sectionId=' + encodeURIComponent(sectionId) : '/members')
    .sort(function (a, b) { return (a.lastName + a.firstName).localeCompare(b.lastName + b.firstName); });

  // What is signed off already, so the sheet starts from Scoutworks.
  const done = signedOff(badgeId);

  const reqs = badge.requirements;
  const rows = [
    ['memberId', badge.name].concat(reqs.map(function (q) { return safe((q.description || q.id).slice(0, 60)); })),
    ['', 'requirementId'].concat(reqs.map(function (q) { return q.id; })),
  ];
  members.forEach(function (m) {
    rows.push([m.id, safe(m.firstName + ' ' + m.lastName)].concat(reqs.map(function (q) {
      return !!done[m.id + '|' + q.id];
    })));
  });

  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName(SHEET) || book.insertSheet(SHEET);
  sheet.clear();
  sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
  if (members.length > 0 && reqs.length > 0) {
    sheet.getRange(3, 3, members.length, reqs.length).insertCheckboxes();
  }
  sheet.setFrozenRows(2);
  sheet.setFrozenColumns(2);
  sheet.hideColumns(1);
  sheet.hideRows(2);
  // Only the badge id is kept: what is signed off is read again when sending.
  PropertiesService.getDocumentProperties().setProperty('badge', badgeId);
  book.toast(members.length + ' young people, ' + reqs.length + ' requirements.');
}

// Sends every tick that differs from what Scoutworks holds now.
function sendTicks() {
  const badgeId = PropertiesService.getDocumentProperties().getProperty('badge');
  if (!badgeId) throw new Error('Build the sheet first.');
  // Read fresh, so a sign-off made in Scoutworks since is not sent back.
  const done = signedOff(badgeId);
  const values = SpreadsheetApp.getActive().getSheetByName(SHEET).getDataRange().getValues();
  const reqIds = values[1].slice(2);

  const items = [];
  values.slice(2).forEach(function (row) {
    reqIds.forEach(function (requirementId, i) {
      const ticked = row[i + 2] === true;
      if (ticked !== !!done[row[0] + '|' + requirementId]) {
        items.push({ memberId: row[0], badgeId: badgeId, requirementId: requirementId, completed: ticked });
      }
    });
  });
  if (items.length === 0) return SpreadsheetApp.getActive().toast('Nothing has changed.');

  const problems = [];
  for (let start = 0; start < items.length; start += 100) {
    const batch = items.slice(start, start + 100);
    const body = callScoutworks('post', BASE + '/badge-requirements/bulk', { items: batch });
    body.data.forEach(function (result) {
      const item = batch[result.index];
      if (result.status === 'error') {
        problems.push(item.requirementId + ': ' + result.error.message);
      }
    });
  }
  SpreadsheetApp.getUi().alert(
    'Sent ' + (items.length - problems.length) + ' of ' + items.length + '.' +
    (problems.length ? '\n\nNot sent:\n' + problems.slice(0, 20).join('\n') : '')
  );
}

// Each young person's completed requirements for one badge, as Scoutworks
// holds them now: 'memberId|requirementId' → true.
function signedOff(badgeId) {
  const done = {};
  readAll('/badges').forEach(function (r) {
    if (r.badge.id !== badgeId) return;
    r.requirements.forEach(function (q) {
      if (q.status === 'completed') done[r.member.id + '|' + q.id] = true;
    });
  });
  return done;
}

// 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 = callScoutworks('get', 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 callScoutworks(method, url, payload) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  if (!apiKey) throw new Error('Add SCOUTWORKS_API_KEY in Project Settings → Script Properties.');
  const options = { method: method, headers: { Authorization: 'Bearer ' + apiKey }, muteHttpExceptions: true };
  if (payload) {
    options.contentType = 'application/json';
    options.payload = JSON.stringify(payload);
  }
  for (let attempt = 0; attempt < 3; attempt++) {
    const res = UrlFetchApp.fetch(url, options);
    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;
}
```

## 2. Add your key

In the script editor, choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`.

To see how the sheet works, use the [sandbox key](https://developers.scoutworks.app/guides/sandbox.md): it builds the sheet, but it is read-only, so sending ticks answers `403`. To send ticks, use your own key with these scopes: `members:read` and `badges:read` to build the sheet, and `badges:write` to send it. Then change `api-demo.scoutworks.app` to `api.scoutworks.app`.

## 3. Build the sheet

Reload the Google Sheet. A **Scoutworks** menu appears. Choose **Build the sheet for a badge**, and give the badge’s `id` (for example `badge_050` for the Squirrels’ Be Active badge) and, if you like, a section’s `id`. The sheet starts with what is already signed off in Scoutworks.

## 4. Tick, then send

Tick the requirements each young person completes. Untick a box to take a sign-off back. When you are done, choose **Scoutworks → Send ticks to Scoutworks**. Only the boxes that differ from Scoutworks are sent, up to 100 in each request: the script reads what is signed off again first, so a sign-off a leader made in Scoutworks meanwhile is not undone.

**Try it with one tick first.** Tick one box, send it, and check the young person’s badge in Scoutworks. Then tick the rest.

When the last requirement of a badge is signed off, Scoutworks completes the badge, just as when a leader ticks it in the app. It then appears in [Badges to order](https://developers.scoutworks.app/recipes/badges-to-order.md).

## Notes

* **Some requirements cannot be ticked.** A requirement completed by recording activities, such as nights away or hikes, completes on its own when the activities are recorded. Ticking it comes back as not sent, with the reason.
* **Who signed it off.** Scoutworks records the sign-off as made by the admin who created the key.
* **Nobody is told.** No parent is emailed. A Young Leader’s module or Mission sign-off sends them no notice either, unless you add `notify: true` to the request body next to `items`.
* **Ticking twice is fine.** A requirement already signed off answers `unchanged`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.