// Scoutworks → who hasn't paid. https://developers.scoutworks.app/recipes/who-hasnt-paid
const BASE = 'https://api-demo.scoutworks.app/api/v1';
// Payment request statuses that still need money, in plain words.
const OUTSTANDING = {
pending: 'Not paid',
failed: 'Payment failed',
processing: 'Being collected',
payment_created: 'Being collected',
};
// Direct Debit statuses that mean the money did not arrive.
const FAILED = {
failed: 'Failed',
customer_approval_denied: 'Refused by the bank',
charged_back: 'Charged back',
};
function whoHasntPaid() {
const today = Utilities.formatDate(new Date(), 'Europe/London', 'yyyy-MM-dd');
const members = {};
// Leavers too: a family can still owe money after a young person leaves.
readAll('/members').concat(readAll('/members?status=archived')).forEach(function (m) {
members[m.id] = (m.preferredName || m.firstName) + ' ' + m.lastName;
});
// Published events. For a camp now archived, the request's own description names it.
const events = {};
readAll('/events').forEach(function (e) {
events[e.id] = e.title;
});
// Unpaid requests: oldest due first.
const requests = readAll('/payment-requests');
const notPaid = requests
.filter(function (r) { return OUTSTANDING[r.status]; })
.sort(function (a, b) { return a.dueDate.localeCompare(b.dueDate); })
.map(function (r) {
return [
safe(members[r.memberId] || ''),
safe(events[r.eventId] || r.description),
Number(r.amount),
r.dueDate.slice(0, 10),
r.dueDate.slice(0, 10) < today ? 'Overdue' : 'Due',
OUTSTANDING[r.status],
safe(r.parent ? r.parent.name || '' : ''),
safe(r.parent ? r.parent.email || '' : ''),
];
});
writeTab('Not paid', [['Young person', 'For', 'Amount (£)', 'Due', 'When', 'Status', 'Parent', 'Email']].concat(notPaid));
// Direct Debits that failed or were charged back.
const byRequest = {};
requests.forEach(function (r) { byRequest[r.id] = r; });
const failed = readAll('/payments')
.filter(function (p) { return FAILED[p.status]; })
.sort(function (a, b) { return b.chargeDate.localeCompare(a.chargeDate); })
.map(function (p) {
const request = p.paymentRequestId ? byRequest[p.paymentRequestId] : null;
return [
p.chargeDate.slice(0, 10),
Number(p.amount),
FAILED[p.status],
p.subscriptionId ? 'Regular subscription' : safe(request ? request.description : 'One-off payment'),
safe(request ? members[request.memberId] || '' : ''),
safe(p.parent ? p.parent.name || '' : ''),
safe(p.parent ? p.parent.email || '' : ''),
];
});
writeTab('Failed Direct Debits', [['Date', 'Amount (£)', 'What happened', 'For', 'Young person', 'Parent', 'Email']].concat(failed));
SpreadsheetApp.getActive().toast(notPaid.length + ' not paid, ' + failed.length + ' failed Direct Debits.');
}
// Replaces a tab's contents with these rows.
function writeTab(name, rows) {
const book = SpreadsheetApp.getActive();
const sheet = book.getSheetByName(name) || book.insertSheet(name);
sheet.clearContents();
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
sheet.setFrozenRows(1);
}
// 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 text that starts with = + - or @ from running as a formula.
function safe(value) {
const text = String(value);
return /^\s*[=+\-@]/.test(text) ? "'" + text : text;
}