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