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

# Kit store QR check-out

> Print a QR label for every item of kit, scan one with your phone to check it out or back in, and get an email each morning about kit that is overdue.

> [!NOTE]
>
> * **For:** quartermasters and leaders who borrow kit
> * **You get:** a sheet of QR labels, a phone shortcut that checks kit out and in with one scan, and a morning email of overdue kit
> * **Time:** about twenty minutes
> * **Scopes:** `equipment:read` for the labels and the email; `equipment:write` for the shortcut; `adults:read` to name who has overdue kit

The kit store works on trust and a clipboard that nobody fills in. With this recipe, each tent, stove and first aid kit carries a QR label with its asset number. A leader scans it with their phone: if the item is in, it is checked out to them for a week; if it is out, it is checked back in. Scoutworks then knows who has what, and you get an email each morning listing anything overdue.

> [!WARNING]
>
> Checking kit out and in changes Scoutworks, so the read-only [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) can print labels but cannot run the shortcut. Use your own key with `equipment:write`, and [try one item](#5-try-one-item) first.

## 1. Try the requests

```bash theme={null}
curl "https://api-demo.scoutworks.app/api/v1/equipment?limit=5" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"

curl "https://api-demo.scoutworks.app/api/v1/equipment-checkouts?status=overdue&limit=5" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

Each item has an `assetNumber`, the number on its label. `GET /equipment?assetNumber=` finds the item a scan read.

## 2. Print the labels

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

```javascript Code.gs theme={null}
// Scoutworks → kit store QR check-out. https://developers.scoutworks.app/recipes/kit-store-qr

const BASE = 'https://api-demo.scoutworks.app/api/v1';

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Scoutworks')
    .addItem('Make QR labels', 'makeLabels')
    .addItem('Email overdue kit now', 'overdueEmail')
    .addToUi();
}

// One row per item, with a QR code of its asset number.
function makeLabels() {
  const kit = readAll('/equipment').filter(function (e) {
    return e.status !== 'retired' && e.status !== 'lost';
  });
  const rows = kit.map(function (e) {
    return [
      '=IMAGE("https://quickchart.io/qr?size=200&text=" & ENCODEURL("' + safe(e.assetNumber) + '"))',
      safe(e.assetNumber),
      safe(e.name),
      e.location ? safe(e.location.name) : '',
    ];
  });
  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName('Labels') || book.insertSheet('Labels');
  sheet.clear();
  sheet.getRange(1, 1, 1, 4).setValues([['QR code', 'Asset number', 'Item', 'Kept in']]);
  if (rows.length) sheet.getRange(2, 1, rows.length, 4).setValues(rows);
  sheet.setRowHeights(2, Math.max(rows.length, 1), 110);
  sheet.setColumnWidth(1, 120);
  book.toast(rows.length + ' labels made. Print the tab and stick each on its item.');
}

// Emails you the kit that is out past its due date, and who has it.
function overdueEmail() {
  const kit = {};
  readAll('/equipment').forEach(function (e) { kit[e.id] = e.assetNumber + ' ' + e.name; });
  const people = {};
  try {
    readAll('/adults').forEach(function (a) { people[a.id] = a.firstName + ' ' + a.lastName; });
  } catch (err) {
    // Without adults:read the email names nobody. It still lists the kit.
  }
  const lines = readAll('/equipment-checkouts?status=overdue').map(function (c) {
    return (kit[c.equipmentId] || c.equipmentId) + ': due back ' + c.dueBackAt.slice(0, 10) +
      ', with ' + (people[c.checkedOutToUserId] || 'someone on the team');
  });
  if (lines.length === 0) return; // Nothing overdue: no email.
  MailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'Overdue kit (' + lines.length + ')', lines.join('\n'));
}

// Stops text that starts with = + - or @ from running as a formula.
function safe(value) {
  const text = String(value);
  return /^\s*[=+\-@]/.test(text) ? "'" + text : text.replace(/"/g, '');
}

// 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.');
}
```

Add your key in **Project Settings → Script Properties** as `SCOUTWORKS_API_KEY`. Reload the sheet and choose **Scoutworks → Make QR labels**. Print the **Labels** tab on label paper. The QR code holds the asset number and nothing else.

For the morning email, choose **Triggers** (the clock) → **Add Trigger**: function **overdueEmail**, **Time-driven**, **Day timer**, **7am to 8am**.

Prefer a message the moment kit is late? Subscribe a [webhook](https://developers.scoutworks.app/guides/webhooks.md) to `equipment.overdue`: Scoutworks sends it once for each check-out that passes its due date, with the item and the adult who has it. Point it at a Zapier, Power Automate or n8n flow that posts in your leaders’ chat.

## 3. Make the phone shortcut

On an iPhone, open **Shortcuts** and choose **+**. Call it **Kit store**. Add these actions in order:

1. **Scan QR or Barcode**.
2. **Get Contents of URL**: your API address, `https://api.scoutworks.app/api/v1`, then `/equipment?assetNumber=` and the **QR/Barcode** result. Under **Headers**, add `Authorization` with the value `Bearer ` and your key.
3. **Get Dictionary Value** `data`, then **Get Item from List**: **First Item**. Name it **Item**.
4. **If** the **Item**’s `status` **is** `available`:
   * **Date**: **Adjust Date** to add 7 days. Name it **Due**.
   * **Get Contents of URL**: the API address then `/equipment-checkouts`, **Method** `POST`, headers `Authorization` as above and `Idempotency-Key` set to the **Item**’s `id` followed by the **Current Date** in ISO 8601 format, so each check-out has its own key, **Request Body** JSON: `equipmentId` the **Item**’s `id`, `dueBackAt` the **Due** date in ISO 8601 format.
   * **Show Notification**: “Checked out: ” and the **Item**’s `name`.
5. **Otherwise**:
   * **Get Contents of URL**: the API address then `/equipment-checkouts?status=active&equipmentId=` and the **Item**’s `id`, with the `Authorization` header. Take the first item of its `data`: the open check-out.
   * **Get Contents of URL**: the API address then `/equipment-checkouts/`, the check-out’s `id` and `/return`, **Method** `POST`, headers `Authorization` and `Idempotency-Key` set to the check-out’s `id`, **Request Body** JSON empty.
   * **Show Notification**: “Checked in: ” and the **Item**’s `name`.

Leave out `checkedOutToUserId` and kit is checked out to the admin who created the key. To record who really has it, give each leader their own shortcut with `checkedOutToUserId` set to their id from `GET /adults`.

> [!WARNING]
>
> The shortcut holds your key. Give it only `equipment:read` and `equipment:write`, so a lost phone can check kit in and out but read nothing else. If a phone goes missing, revoke the key in **Settings → Integrations → API keys** and make a new one.

## 4. Report damage on return

To say how an item came back, add `condition` to the return’s **Request Body**: `good`, `fair`, `poor`, `damaged` or `needs_repair`. Poor, damaged or needs repair puts the item in for repair, as Scoutworks does. Add `"notify": true` and Scoutworks tells your quartermasters, as it does when a leader reports damage in the app. Without it, nobody is notified.

## 5. Try one item

Scan one item’s label. You see “Checked out”. Open **Equipment** in Scoutworks: the item is out, to you, due back in a week. Scan it again: “Checked in”, and the item is available again.

## 6. Switch to your group

The shortcut already uses `api.scoutworks.app`. In the script, change `api-demo.scoutworks.app` to `api.scoutworks.app`, and put your own key in Script Properties. The labels and the email need `equipment:read`, plus `adults:read` to name who has overdue kit. The shortcut needs `equipment:write` too.

## If something goes wrong

See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code. `not_available` means the item is out, in repair, retired or lost: open it in Scoutworks to see which. `insufficient_stock` on a consumable, such as gas canisters, means fewer are left than you asked for.


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