// Scoutworks → DBS checks tracker. https://developers.scoutworks.app/recipes/adult-compliance-tracker
const BASE = 'https://api-demo.scoutworks.app/api/v1';
const WARN_DAYS = 60;
const DAY = 24 * 60 * 60 * 1000;
const RED = '#f4c7c3';
const AMBER = '#fce8b2';
const GREEN = '#d9ead3';
// Fills the DBS checks tab. Returns the rows, so the email can use them too.
function dbsChecks() {
const today = new Date();
today.setHours(0, 0, 0, 0);
const adults = readAll('/adults');
// A key without adults.compliance:read gets no criminalRecordCheck field at all.
if (adults.length && !('criminalRecordCheck' in adults[0])) {
throw new Error('This key needs the adults.compliance:read scope to read DBS checks.');
}
// Young leaders are under 18 and do not need a DBS check, so a young
// leader with no other role is left off the sheet.
const needsCheck = adults.filter(function (a) {
return a.roles.some(function (r) { return r !== 'young_leader'; });
});
const rows = needsCheck.map(function (a) {
const check = a.criminalRecordCheck;
const expires = check.expiresOn ? dateOnly(check.expiresOn) : null;
const days = expires ? Math.round((expires - today) / DAY) : null;
return {
cells: [
safe(a.firstName || ''),
safe(a.lastName || ''),
a.roles.join(', '),
safe(a.sections.map(function (s) { return s.name; }).join(', ') || 'Whole group'),
STATUS[check.status] || check.status,
check.expiresOn || '',
days === null ? '' : days,
],
colour: colourFor(check.status, days),
days: days,
};
});
// Red first, then amber, then green. Soonest expiry first within each.
const order = {};
order[RED] = 0;
order[AMBER] = 1;
order[GREEN] = 2;
rows.sort(function (a, b) {
return order[a.colour] - order[b.colour] || (a.days === null ? -1 : a.days) - (b.days === null ? -1 : b.days);
});
const header = ['First name', 'Last name', 'Roles', 'Sections', 'DBS check', 'Expires', 'Days left'];
const book = SpreadsheetApp.getActive();
const sheet = book.getSheetByName('DBS checks') || book.insertSheet('DBS checks');
sheet.clear();
sheet.getRange(1, 1, 1, header.length).setValues([header]).setFontWeight('bold');
if (rows.length) {
sheet.getRange(2, 1, rows.length, header.length)
.setValues(rows.map(function (r) { return r.cells; }))
.setBackgrounds(rows.map(function (r) { return header.map(function () { return r.colour; }); }));
}
sheet.setFrozenRows(1);
return rows;
}
// Red: expired or no check. Amber: expires within WARN_DAYS, or applied for. Green: fine.
function colourFor(status, days) {
if (status === 'none' || status === 'expired' || (days !== null && days < 0)) return RED;
if (status === 'in_progress' || (days !== null && days <= WARN_DAYS)) return AMBER;
return GREEN;
}
const STATUS = {
none: 'No check recorded',
in_progress: 'Applied for',
valid: 'Valid',
expiring: 'Valid',
expired: 'Expired',
};
// Optional: emails the checks that expire soon. Run it from a monthly trigger.
function emailExpiringChecks() {
const to = PropertiesService.getScriptProperties().getProperty('SEND_TO') ||
Session.getEffectiveUser().getEmail();
const rows = dbsChecks();
const expired = rows.filter(function (r) { return r.days !== null && r.days < 0; });
const soon = rows.filter(function (r) { return r.days !== null && r.days >= 0 && r.days <= WARN_DAYS; });
const line = function (r) { return '- ' + r.cells[0] + ' ' + r.cells[1] + ': ' + r.cells[5]; };
const parts = [];
parts.push(soon.length
? 'Expires in the next ' + WARN_DAYS + ' days:\n' + soon.map(line).join('\n')
: 'No DBS check expires in the next ' + WARN_DAYS + ' days.');
if (expired.length) parts.push('Already expired:\n' + expired.map(line).join('\n'));
parts.push('The full list is in the DBS checks tab: ' + SpreadsheetApp.getActive().getUrl());
MailApp.sendEmail(to, 'DBS checks expiring in the next ' + WARN_DAYS + ' days', parts.join('\n\n'));
}
// 2027-01-31 → a Date at midnight, local time.
function dateOnly(text) {
const p = text.split('-').map(Number);
return new Date(p[0], p[1] - 1, p[2]);
}
// 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.');
}
// 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;
}