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

# Young Leader hours log

> A Google Form Young Leaders fill in after helping, which logs their hours in Scoutworks, ready for their award or DofE volunteering.

> [!NOTE]
>
> * **For:** Young Leader co-ordinators and Explorer leaders
> * **You get:** a form a Young Leader fills in on their phone, and their hours in Scoutworks a moment later
> * **Time:** about fifteen minutes
> * **Scopes:** `members:read` and `recognition:read` to try it; `recognition:write` to log hours

Young Leaders help on evenings their own section never sees, and the hours they give count towards their award and towards DofE volunteering. Chasing them for a log at the end of term rarely works. This recipe gives them a short form instead: their name, the date, how long and what they did. Each answer is logged straight into Scoutworks as their volunteer hours, the same place a leader would type them.

> [!WARNING]
>
> Logging hours changes Scoutworks, so the read-only [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) can fill the name list but cannot log hours. Use your own key with `recognition:write`, and [try one answer](#5-try-one-answer) 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/volunteer-hours?limit=5" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

A Young Leader’s hours carry their `memberId`; an adult’s carry their `userId`. A Young Leader’s note is free text, so it is never read back through the API.

## 2. Make the form

In Google Forms, make a form called **Young Leader hours** with four questions, named exactly:

| Question | Type |
| - | - |
| Your name | Dropdown (the script fills it in) |
| Date you helped | Date |
| Hours | Short answer, with **Response validation → Number → Between** 0.25 and 24 |
| What you did | Paragraph |

Choose **⋮ → Script editor**. Delete what is there, paste the script below and choose **Save**.

```javascript Code.gs theme={null}
// Scoutworks → Young Leader hours log. https://developers.scoutworks.app/recipes/young-leader-hours

const BASE = 'https://api-demo.scoutworks.app/api/v1';
const SECTION_TYPES = ['explorers', 'network']; // Where Young Leaders are members.

// Fills the "Your name" dropdown with your Explorers and Network members. Run it each term.
function fillNames() {
  const sections = readAll('/sections').filter(function (s) {
    return s.active && SECTION_TYPES.indexOf(s.type) !== -1;
  });
  const ids = {};
  sections.forEach(function (s) {
    readAll('/members?sectionId=' + s.id).forEach(function (m) {
      ids[(m.preferredName || m.firstName) + ' ' + m.lastName] = m.id;
    });
  });
  const names = Object.keys(ids).sort();
  if (names.length === 0) throw new Error('No Explorers or Network members found.');
  PropertiesService.getScriptProperties().setProperty('YOUNG_LEADERS', JSON.stringify(ids));
  const form = FormApp.getActiveForm();
  const question = form.getItems(FormApp.ItemType.LIST).find(function (item) {
    return item.getTitle() === 'Your name';
  });
  question.asListItem().setChoiceValues(names);
}

// Runs on every answer: logs it in Scoutworks.
function onAnswer(e) {
  const answers = {};
  e.response.getItemResponses().forEach(function (r) {
    answers[r.getItem().getTitle()] = r.getResponse();
  });
  const ids = JSON.parse(PropertiesService.getScriptProperties().getProperty('YOUNG_LEADERS') || '{}');
  const memberId = ids[answers['Your name']];
  if (!memberId) throw new Error('Run fillNames again: ' + answers['Your name'] + ' is not in the list.');

  const minutes = Math.round(Number(answers['Hours']) * 60);
  const occurredAt = answers['Date you helped'] + 'T19:00:00Z'; // The form gives a date; log it as the evening.
  const res = post('/volunteer-hours', 'yl-' + e.response.getId(), {
    memberId: memberId,
    occurredAt: occurredAt,
    durationMinutes: Math.min(Math.max(minutes, 1), 1440),
    note: String(answers['What you did'] || '').slice(0, 2000),
  });
  if (!res.ok) throw new Error(res.body.error.code + ': ' + res.body.error.message);
}

// Sends one write. The answer's own id is its Idempotency-Key, so it is never logged twice.
function post(path, idempotencyKey, payload) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  for (let attempt = 0; attempt < 4; attempt++) {
    const res = UrlFetchApp.fetch(BASE + path, {
      method: 'post',
      contentType: 'application/json',
      headers: { Authorization: 'Bearer ' + apiKey, 'Idempotency-Key': idempotencyKey },
      payload: JSON.stringify(payload),
      muteHttpExceptions: true,
    });
    const code = res.getResponseCode();
    const body = JSON.parse(res.getContentText());
    if (code === 200 || code === 201) return { ok: true, body: body };
    if (code === 429) { Utilities.sleep((body.retryAfter || 30) * 1000); continue; }
    if (code === 409 && body.error.code === 'conflict') { Utilities.sleep(5000); continue; }
    return { ok: false, body: body };
  }
  return { ok: false, body: { error: { code: 'busy', message: 'Scoutworks is still busy.' } } };
}

// 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 the names

Choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`. Value: the sandbox key to try the names, or your own key.

Select **fillNames** and choose **Run**. Allow it to edit the form. The **Your name** dropdown now lists your Explorers and Network members. Run it again when new Explorers join.

> [!WARNING]
>
> The dropdown shows young people’s names to anyone with the form’s link. Share the link only with your Young Leaders, and set the form to **Restrict to users in your organisation** if your group uses Google Workspace.

## 4. Log each answer

Choose **Triggers** (the clock) → **Add Trigger**: function **onAnswer**, event source **From form**, event type **On form submit**. Allow it to reach an external service.

## 5. Try one answer

Fill the form in once yourself, as one Young Leader, for 15 minutes. Open that young person in Scoutworks, then **Young Leader → Hours**: the entry is there, with your note. If it was only a test, delete it there.

Each answer’s own id is its `Idempotency-Key`, so if Google retries the trigger, the hours are logged once.

## 6. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and put your own key in Script Properties. It needs `members:read` for the names, `recognition:read`, and `recognition:write` to log hours.

## Variations

* **Adults too.** Send `userId` (an adult’s id from `GET /adults`) in place of `memberId`, and the hours appear in that adult’s volunteer hours.
* **A DofE summary.** `GET /volunteer-hours?memberId=` and the young person’s id lists everything they have logged.

## If something goes wrong

Failed answers show under **Executions** in the script editor. See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code. A `400` naming `memberId` means the young person has left the group: run **fillNames** again.


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