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

# Patrol scoreboard on the hut screen

> A live patrol scoreboard for the screen in your hut, and a phone shortcut that adds points from anywhere in the room.

> [!NOTE]
>
> * **For:** Scout and Cub leaders
> * **You get:** a full-screen scoreboard that updates every minute, and a phone shortcut that adds points to a patrol
> * **Time:** about twenty minutes
> * **Scopes:** `recognition:read` and `members:read` for the board; `recognition:write` for the shortcut

Points mean more when the patrols can see them. This recipe puts your section’s patrol standings on the hut’s screen or projector, biggest score first, and refreshes it every minute. A leader adds points from their phone with two taps, and the board catches up within the minute. The points are the same ones Scoutworks shows on the section’s scoreboard, so nothing needs copying back.

> [!WARNING]
>
> Adding points changes Scoutworks, so the read-only [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) can show the board but cannot run the shortcut. Use your own key with `recognition:write`, and [try one award](#5-try-one-award) first.

## 1. Try the requests

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

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

Then ask for the standings. You get one entry for each section that has patrols. Add `sectionId` and a section `id` from the first list to get just that section:

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

Each patrol has an `id`, a `name`, a `colour` and its `points`. Points a young person earns count for the patrol they were in when they earned them.

## 2. Add the script

Go to [script.google.com](https://script.google.com) and choose **New project**. Call it **Scoutworks scoreboard**. Paste the script below and choose **Save**.

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

const BASE = 'https://api-demo.scoutworks.app/api/v1';
const DAY = 24 * 60 * 60 * 1000;

// Open …/exec?section=scouts for the Scouts' board. Add &from=2027-01-05 for this term only.
function doGet(e) {
  const word = ((e && e.parameter && e.parameter.section) || '').toLowerCase();
  const section = readAll('/sections').find(function (s) {
    return s.active && s.name.toLowerCase().indexOf(word) !== -1;
  });
  if (!section) return HtmlService.createHtmlOutput('<p>No section matches “' + escapeHtml(word) + '”.</p>');

  const from = /^\d{4}-\d{2}-\d{2}$/.test((e.parameter && e.parameter.from) || '')
    ? new Date(e.parameter.from + 'T00:00:00Z')
    : new Date(Date.now() - 90 * DAY);
  // One entry per section; asking for one section gives a list of one, or none
  // when the section has no patrols yet.
  const standings = fetchScoutworks(
    BASE + '/patrol-standings?sectionId=' + section.id + '&from=' + encodeURIComponent(from.toISOString())
  ).data[0];
  if (!standings) return HtmlService.createHtmlOutput('<p>' + escapeHtml(section.name) + ' has no patrols yet.</p>');

  const rows = standings.patrols.map(function (p) {
    return '<tr><td>' + p.rank + '</td><td style="border-left:16px solid ' + colour(p.colour) + '">' +
      escapeHtml(p.name) + '</td><td>' + p.points + '</td></tr>';
  }).join('');
  const html =
    '<meta http-equiv="refresh" content="60">' +
    '<style>body{font:48px system-ui;background:#111;color:#fff;margin:40px}' +
    'td{padding:12px 32px}td:last-child{text-align:right;font-weight:bold}</style>' +
    '<h1>' + escapeHtml(section.name) + '</h1><table>' + rows + '</table>';
  return HtmlService.createHtmlOutput(html).setTitle('Scoreboard');
}

// A patrol's colour, or grey when it has none or it is not a plain colour.
function colour(value) {
  return /^#[0-9a-f]{3,8}$|^[a-z]+$/i.test(value || '') ? value : '#666';
}

// Names are shown on a page, so < > & and quotes are written as text.
function escapeHtml(value) {
  return String(value).replace(/[&<>"']/g, function (c) {
    return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
  });
}

// 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.');
}
```

## 3. Add your key and publish the board

Choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`. Value: the sandbox key to try it, or a key with `recognition:read` and `members:read`.

Choose **Deploy → New deployment → Web app**, **Execute as: Me**, **Who has access: Anyone**, and copy the address. On the hut’s screen, open it with `?section=scouts` (or a word from your section’s name) on the end, and make the browser full screen.

> [!WARNING]
>
> Anyone with the address sees your patrols’ names and scores. The board never shows a young person’s name.

## 4. Make the points shortcut

Read your patrols’ ids from the standings request in step 1. Then, on an iPhone, open **Shortcuts**, choose **+** and call it **Patrol points**:

1. **Choose from Menu** with one item per patrol: Eagles, Owls and so on.
2. In each patrol’s branch, a **Text** action holding that patrol’s `id`.
3. **Ask for Input**, type **Number**, prompt “How many points?”. Negative numbers take points away.
4. **Current Date**, then **Format Date** as `yyyyMMddHHmmss`. This makes the award’s `reference`.
5. **Get Contents of URL**: your API address, `https://api.scoutworks.app/api/v1`, then `/patrol-scores`. **Method** `POST`. **Headers**: `Authorization` set to `Bearer ` and your key. **Request Body** JSON: `items`, a list holding one dictionary with `reference` (the formatted date and the patrol’s id), `sectionId`, `patrolId` (the **Text**) and `points` (the number).
6. **Show Notification**: “Points added”.

Each award carries its `reference`. If the hut’s Wi-Fi drops and the shortcut sends it again, Scoutworks answers `unchanged` and adds nothing twice.

> [!WARNING]
>
> The shortcut holds your key. Give that key only `recognition:read` and `recognition:write`, so a lost phone can add points and read nothing else.

## 5. Try one award

Run the shortcut and give one patrol 1 point. Within a minute the board shows it, and so does the section’s scoreboard in Scoutworks, marked as added by the key. To take it back, undo it on the scoreboard in Scoutworks.

## 6. Switch to your group

The shortcut already uses `api.scoutworks.app`. In the script, change `api-demo.scoutworks.app` to `api.scoutworks.app`, and put your own key with `recognition:read` and `members:read` in Script Properties. Then choose **Deploy → Manage deployments → Edit**, **Version: New version**, **Deploy**: the board’s address stays the same.

## Variations

* **Points for one young person.** Send `memberId` in place of `patrolId`: the points count for them and for their patrol.
* **A whole evening at once.** One request takes up to 100 awards, each with its own `reference`.

## If something goes wrong

See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code. An award with an error in the answer’s `data` names what was wrong with it, such as a patrol from another section. The other awards in the request are still added.


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