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

# Reorder badges and uniform

> A weekly email of the badges and uniform running low, and a sheet tab that records each delivery in Scoutworks when it arrives.

> [!NOTE]
>
> * **For:** quartermasters, and the leader who orders badges
> * **You get:** an email every Monday listing what to reorder, and a **Deliveries** tab that adds what arrives to the stock in Scoutworks
> * **Time:** about fifteen minutes
> * **Scopes:** `badge-stock:read` and `uniform:read` for the email; `badge-stock:write` and `uniform:write` to record deliveries

Running out of Chief Scout’s Silver badges the week before an award night is avoidable. This recipe emails you each Monday with every badge and uniform size at or below its reorder level. A badge counts what young people have already earned but not been given, so you see what you are short of before the award night, not on it. When the order arrives, type it into a **Deliveries** tab and the sheet adds it to the stock in Scoutworks.

Stock is in units. The API never reads or writes a price.

> [!WARNING]
>
> Recording a delivery changes your stock, so the read-only [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) can send the email but cannot record a delivery. Use your own key with `badge-stock:write` and `uniform:write`, and [try one delivery](#5-try-one-delivery) first.

## 1. Try the requests

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

curl "https://api-demo.scoutworks.app/api/v1/uniform-items?limit=5" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

A badge’s `status` is `low` at or below its reorder level and `short` when more are owed than are on the shelf. A uniform size is `low` the same way. See [Data definitions](https://developers.scoutworks.app/guides/data-definitions.md#group-figures).

## 2. Add the script

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 → reorder badges and uniform. https://developers.scoutworks.app/recipes/stock-reorder

const BASE = 'https://api-demo.scoutworks.app/api/v1';
const DELIVERIES = 'Deliveries';
const HEADER = ['Badge id, or uniform:stockId', 'Section id (badges, or blank)', 'How many', 'Note', 'Result', 'Request key (leave it)'];

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Scoutworks')
    .addItem('Email the reorder list now', 'reorderEmail')
    .addItem('Record deliveries', 'recordDeliveries')
    .addToUi();
}

// Emails you what is at or below its reorder level.
function reorderEmail() {
  const lines = [];
  readAll('/badge-stock').forEach(function (s) {
    if (s.status === 'sufficient') return;
    lines.push(
      s.badge.name + (s.sectionId ? '' : ' (central store)') + ': ' + s.onHand + ' on hand, ' +
        s.owed + ' owed' + (s.status === 'short' ? ', SHORT by ' + -s.available : '') +
        '. Badge id ' + s.badge.id +
        (s.sectionId ? ', section id ' + s.sectionId : ', section id blank (central store)')
    );
  });
  readAll('/uniform-items').forEach(function (item) {
    item.variants.forEach(function (v) {
      v.stock.forEach(function (line) {
        if (!line.low) return;
        lines.push(item.name + ' ' + v.label + ': ' + line.onHand + ' left. Reorder id uniform:' + line.stockId);
      });
    });
  });
  const to = Session.getEffectiveUser().getEmail();
  MailApp.sendEmail(
    to,
    'Badges and uniform to reorder (' + lines.length + ')',
    lines.length ? lines.join('\n') : 'Nothing is low this week.'
  );
}

// Adds each new row on the Deliveries tab to the stock, once.
function recordDeliveries() {
  const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName(DELIVERIES) || book.insertSheet(DELIVERIES);
  if (sheet.getLastRow() === 0) {
    sheet.appendRow(HEADER);
    sheet.setFrozenRows(1);
    return;
  }
  const rows = sheet.getDataRange().getValues();
  let recorded = 0;
  for (let i = 1; i < rows.length; i++) {
    const [target, sectionId, quantity, note, result, savedKey] = rows[i];
    if (!target || result === 'Recorded') continue;
    // Uniform rows start `uniform:`. Anything else is a badge id: built-in
    // (`badge_123`) or a custom badge's own id.
    const isBadge = !/^uniform:/.test(String(target));
    const body = isBadge
      ? { badgeId: String(target), sectionId: sectionId || null, type: 'delivery', quantity: Number(quantity), reason: String(note || 'Delivery') }
      : { stockId: String(target).slice('uniform:'.length), type: 'delivery', quantity: Number(quantity), reason: String(note || 'Delivery') };
    // Each entry gets its own key the first time it is sent, kept in column F. A retry of
    // that entry sends the same key, so it is never added twice; a new entry typed into a
    // cleared row gets a new key, so it is never mistaken for the old one.
    let key = String(savedKey || '');
    if (!key) {
      key = 'delivery-' + Utilities.getUuid();
      sheet.getRange(i + 1, 6).setValue(key);
    }
    const res = post(isBadge ? '/badge-stock/transactions' : '/uniform-stock/transactions', apiKey, key, body);
    sheet.getRange(i + 1, 5).setValue(
      res.ok ? 'Recorded' : res.body.error.code + ': ' + res.body.error.message
    );
    if (res.ok) recorded++;
    Utilities.sleep(2100); // Stay under 30 changes a minute.
  }
  book.toast(recorded + ' deliveries recorded.');
}

// Sends one write. Waits and tries again if it is rate limited or still running.
function post(path, apiKey, idempotencyKey, payload) {
  for (let attempt = 0; attempt < 4; attempt++) {
    const res = UrlFetchApp.fetch(BASE + path, {
      method: 'post',
      contentType: 'application/json',
      headers: { Authorization: 'Bearer ' + apiKey, 'Idempotency-Key': idempotencyKey },
      payload: JSON.stringify(payload),
      muteHttpExceptions: true,
    });
    const code = res.getResponseCode();
    const body = JSON.parse(res.getContentText());
    if (code === 200 || code === 201) return { ok: true, body: body };
    if (code === 429) { Utilities.sleep((body.retryAfter || 30) * 1000); continue; }
    if (code === 409 && body.error.code === 'conflict') { Utilities.sleep(5000); continue; }
    return { ok: false, body: body };
  }
  return { ok: false, body: { error: { code: 'busy', message: 'Scoutworks is still busy. Run it again in a minute.' } } };
}

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

## 3. Add your key

Choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`. Value: the sandbox key to try the email, or your own key.

## 4. Send the email every Monday

Choose **Run** with **reorderEmail** selected once, and allow it to send email as you. Then choose **Triggers** (the clock) → **Add Trigger**: function **reorderEmail**, event source **Time-driven**, **Week timer**, **Every Monday**.

## 5. Try one delivery

Reload the sheet. A **Scoutworks** menu appears. Choose **Scoutworks → Record deliveries** once: it adds the **Deliveries** tab. On it, enter one row: a badge’s id from the email (such as `badge_123`, or a custom badge’s id) or a uniform line’s reorder id (`uniform:` and its `stockId`), the section id from the same email line (leave it blank for the central store), how many, and a note. Choose **Record deliveries** again.

The row reads **Recorded**. Open **Badges → Stock** or **Uniform** in Scoutworks and check the count went up. If it was only a test, correct it there. Then enter the real delivery.

A row that reads **Recorded** is never sent again. Each row keeps its own `Idempotency-Key` in column F, so a retried row is never counted twice. To reuse a row for a new delivery, clear the whole row, column F included.

## 6. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and use your own key in Script Properties. For the email alone, your key needs `badge-stock:read` and `uniform:read`. To record deliveries, add `badge-stock:write` and `uniform:write`.

## Variations

* **Correct a stock take.** Change `type: 'delivery'` to `type: 'adjustment'` and enter a negative number for badges that went missing. Stock never goes below 0: a correction that would answers `insufficient_stock`.
* **Only one section.** Add `?sectionId=` and the section’s id to `/badge-stock`.

## If something goes wrong

See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code. `insufficient_stock` means the change would take stock below 0. A `400` naming `badgeId` means that badge is not one you can stock: check its id in `GET /badge-catalogue`.


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