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

# Load next term's programme as draft events

> Plan a term in a spreadsheet, then add every meeting to Scoutworks as a draft for leaders to check and publish.

> [!NOTE]
>
> * **For:** section leaders, with a group admin to create the key
> * **You get:** a term's programme from a spreadsheet, as draft events to check and publish
> * **Time:** about fifteen minutes
> * **Scopes:** `events:read` and `events:write`

Many sections plan a term in a spreadsheet: a date and an activity per week. This recipe adds each row to Scoutworks as a **draft event**. Leaders check the drafts and publish them in Scoutworks, which is when families hear about them. It takes about fifteen minutes.

It is for a **section leader** working with a group admin, who creates the key.

## 1. Create a key

A group admin opens **Settings → Integrations → API keys** and creates a key called **Programme planner**, with the scopes **`events:read`** and **`events:write`**. Drafts the key adds show that admin as their creator.

The API can only add drafts and change what a draft says. It never publishes, cancels or prices an event, and it never emails families.

## 2. Lay out the sheet

Make a tab called **Programme** with these columns:

| A | B | C | D | E | F |
| - | - | - | - | - | - |
| Date | Starts | Ends | Activity | Where | Scoutworks id |

Format column A as a date and columns B and C as times, for example `18:30`. Leave column F empty: the script fills it in. Put the section's id in cell **H1**: find it with `GET /sections`, or ask the group admin.

## 3. Add the script

Choose **Extensions → Apps Script**, paste the script below, and choose **Save**. Add the key in **Project Settings → Script Properties** as `SCOUTWORKS_API_KEY`. Reload the sheet.

```javascript Code.gs theme={null}
// Spreadsheet → Scoutworks draft events.
// https://developers.scoutworks.app/recipes/programme-as-drafts

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Scoutworks')
    .addItem('Add new rows as drafts', 'addDrafts')
    .addToUi();
}

// The sheet's date and time, as a moment in UK time with its offset.
function at(date, time) {
  const day = Utilities.formatDate(date, 'Europe/London', 'yyyy-MM-dd');
  const clock = Utilities.formatDate(time, 'Europe/London', 'HH:mm');
  const local = new Date(day + 'T' + clock + ':00Z');
  const offset = Utilities.formatDate(local, 'Europe/London', 'XXX');
  return day + 'T' + clock + ':00' + offset;
}

// A short fingerprint of what a row sends. The same row sends the same key,
// so a retry after a timeout cannot add a twin; a corrected row gets a new
// key, so it is added afresh.
function fingerprint(body) {
  const bytes = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, JSON.stringify(body));
  return Utilities.base64EncodeWebSafe(bytes).slice(0, 22);
}

function addDrafts() {
  const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  const sheet = SpreadsheetApp.getActive().getSheetByName('Programme');
  const sectionId = sheet.getRange('H1').getValue();
  const rows = sheet.getDataRange().getValues();

  for (let i = 1; i < rows.length; i++) {
    const [date, starts, ends, activity, where, id] = rows[i];
    if (!(date instanceof Date) || !activity || id) continue;

    const event = {
      title: String(activity),
      type: 'programme_meeting',
      startsAt: at(date, starts),
      endsAt: at(date, ends),
      location: where ? String(where) : null,
      sectionIds: [sectionId],
    };
    const res = UrlFetchApp.fetch('https://api.scoutworks.app/api/v1/events', {
      method: 'post',
      contentType: 'application/json',
      headers: {
        Authorization: 'Bearer ' + apiKey,
        // What the row says: a re-run cannot add the same meeting twice, and
        // a row you corrected is sent as new.
        'Idempotency-Key': 'programme-' + fingerprint(event),
      },
      payload: JSON.stringify(event),
      muteHttpExceptions: true,
    });
    const body = JSON.parse(res.getContentText());
    sheet.getRange(i + 1, 6).setValue(res.getResponseCode() < 300 ? body.data.id : 'Error: ' + body.error.message);
    Utilities.sleep(2100); // The API takes 30 changes a minute.
  }
}
```

## 4. Try one row, then the rest

Fill in one row and choose **Scoutworks → Add new rows as drafts**. Open **Events** in Scoutworks: the meeting is there as a draft. Check the date and time. If it is wrong, delete it there, correct the row, clear column F and run it again: a corrected row is sent as a new request. Sent unchanged within 24 hours, it would answer with the draft you deleted. When it is right, fill in the rest of the term and run it again. Rows that already have an id are skipped.

## 5. Change a draft from the sheet

To move a meeting after you added it, change the event with `PATCH /events/{eventId}`, using the id in column F. Send only what changed, for example `{"location": "Hayes Common"}`. Read the event first and send its `ETag` as `If-Match`, so you never overwrite a change a leader made in Scoutworks: see [Writing data](https://developers.scoutworks.app/guides/writing-data.md).

The API answers `409 source_locked` if you send a `status`: publishing and cancelling stay in Scoutworks, because both tell families.

## If something goes wrong

* **`400 invalid_request`**: for example an end before the start, or a section id that is not your group's. The message says which.
* **`403 insufficient_scope`**: the key needs `events:read` and `events:write`.
* **`402 subscription_required`**: the group's subscription has lapsed.

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.