// 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;
}