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

# DBS checks tracker

> Every adult volunteer with their DBS check status and expiry, coloured red, amber or green, and a monthly email of the checks about to expire. For group lead volunteers.

> [!NOTE]
>
> * **For:** group lead volunteers and group admins
> * **You get:** every adult's DBS check, red, amber or green, and a monthly email of what runs out in the next 60 days
> * **Time:** about ten minutes
> * **Scopes:** `adults:read` and `adults.compliance:read`

This recipe adds a **DBS checks** tab to a Google Sheet. It lists every adult volunteer in your group with their DBS check status and expiry date, and colours each row:

* **Red**: the check has expired, or no check is recorded.
* **Amber**: the check expires within 60 days, or a new one is applied for.
* **Green**: the check is fine.

On the first of each month, it can email the group lead volunteer the checks that expire in the next 60 days.

It uses Google Apps Script. It takes about ten minutes.

> [!NOTE]
>
> Scoutworks does not hold training records yet, so this sheet covers DBS checks only. Keep tracking training where you track it today.

## 1. Add the script

In your Google Sheet, choose **Extensions → Apps Script**. Delete what is there, paste the script below and choose **Save**.

```javascript Code.gs theme={null}
// 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;
}
```

## 2. Add your key

In the script editor, choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`. Value: the [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) to try it, or your own key.

Add a second property, `SEND_TO`, with the group lead volunteer's email address. Put a comma between addresses to send it to more than one person. Without it, the email goes to you.

## 3. Run it

Choose **dbsChecks** in the toolbar and press **Run**. Open the **DBS checks** tab.

To get the email too, run **emailExpiringChecks** once, so Google asks for permission to send email. Then choose **Triggers** (the clock), then **Add Trigger**. Function: `emailExpiringChecks`. Event source: **Time-driven**. Type: **Month timer**. Day: **1st**. Choose **Save**.

The email lists the checks that expire in the next 60 days, and any that have already expired.

## 4. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own. Your key needs `adults:read` and `adults.compliance:read`. The second scope adds each adult's DBS check status and expiry date. Give it no other scope.

> [!WARNING]
>
> DBS status is sensitive. Keep the sheet private to the people who manage checks, and send the email only to them. The API never returns a certificate number or anything a disclosure says.

## Notes

* The list holds everyone with a current group admin, leader or trustee role, as your **Team** page shows them. Young leaders are under 18 and need no DBS check, so one with no other role is left off. A parent with no such role is not on it either.
* The sheet works out the 60 days itself, from the expiry date. The API's own `expiring` status starts 90 days before expiry. To warn earlier, change `WARN_DAYS`.
* A check is recorded in Scoutworks. Fix a wrong date or status in Scoutworks, not in the sheet: the next run overwrites the sheet.


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