SWIM is a Google spreadsheet that helps a YSA ward keep track of its members, appointments and messages.
Use the button below to make your own copy of the current template in your Google Drive.
Personal texts to your whole ward, sent from your phone
SWIM builds a personalized text message for each member from your ward data, then queues them so you
can send them from your phone in just a few taps.
1BuildWrite a message once, with placeholders like
<FIRST NAME>, and SWIM fills them in for each member.
2QueueThe finished messages wait in your spreadsheet,
ready to go.
3SendOpen the Send Messages page on your phone and tap
each one. It opens in your texting app, ready to send.
“Hi Emma, this is Bishop Smith from the ward. Can you schedule a time for us to meet?”
Before you start
Open the setup guide in another
tab or on another device, and follow along with the instructional video there as you make your copy and set it up.
It walks through each step, so you'll be up and running quickly.
Works best with Ward Photo Directory
Although SWIM is capable as a stand-alone tool, it is designed to work with the
Ward Photo Directory
Chrome extension.
The extension turns your ward's page in the Church's online directory (and the member tables in
Leader and Clerk Resources) into a browsable photo grid, so you can quickly put names to faces.
It can also export member contact information as a spreadsheet file. Connected to SWIM, it lets you
queue text messages and record notes for members right from the photo grid.
Open your copy of the spreadsheet (it is saved in your Google Drive).
From the SWIM menu, choose System Setup and allow the permissions it asks for.
Use SWIM > System > Settings to enter your ward's details, and SWIM > Links to get your links.
Already using SWIM?
Choose SWIM > System > Check for Updates in your spreadsheet. If there is a newer version, it shows the
steps: copy the code with the button below and paste it over Code.gs in SWIM's script editor.
Current version:
First release.
2026-10-10 22:59
/**
* SWIM (Singles Ward Information Manager), version 2026-10-10 22:59.
* Generated by build.js from the files in src/. To update SWIM, replace
* all of this file with the newest version from
* https://tools.ysaward.org/
*/
const SWIM_VERSION = "2026-10-10 22:59";
// ---- Template.js (makeTemplate, moved to the top so it's easy to find) ----
/**
* Copies this spreadsheet (and its bound script) into a new "SWIM Template"
* file in the same folder, then strips everything ward-specific from the
* copy: data rows, form response sheets and their copied forms, the old
* Configuration sheet, check-ins and any other sheets. The landing sheet
* (LANDING_SHEET_NAME, left as the first tab) and the saved message templates
* (MESSAGE_TEMPLATES_SHEET) are kept as-is. The working spreadsheet is never
* changed. If anything fails, the partial copy is moved to the trash.
*
* Settings in TEMPLATE_KEPT_SETTINGS (the appointment types) are kept as the
* template's starting values.
*
* The copy is marked as a pending template: when it is first opened it
* offers to "Initialize and share", which clears the settings it inherited,
* makes it viewable by anyone with the link and shows that link.
*/
function makeTemplate() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
stampSettingsOwner_();
const originalFormIds = ss.getSheets().map(linkedFormId).filter(id => id);
const name = "SWIM Template " +
Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd");
const copyFile = DriveApp.getFileById(ss.getId()).makeCopy(name);
if (copyFile.getId() === ss.getId()) {
throw new Error("The copy has the same ID as this spreadsheet; stopping.");
}
const copy = SpreadsheetApp.openById(copyFile.getId());
// Kept unchanged: the landing page and the saved message templates.
const keptSheets = [LANDING_SHEET_NAME, MESSAGE_TEMPLATES_SHEET];
const kept = [];
const removed = [];
const cleared = [];
let defaults;
try {
// Form response sheets: unlink and trash the copied form, then delete.
copy.getSheets().forEach(sheet => {
const formId = linkedFormId(sheet);
if (!formId) return;
if (originalFormIds.indexOf(formId) !== -1) {
throw new Error('Sheet "' + sheet.getName() + '" of the template is linked to ' +
"this spreadsheet's own form. Stopping so that form is not unlinked.");
}
FormApp.openById(formId).removeDestination();
DriveApp.getFileById(formId).setTrashed(true);
SpreadsheetApp.flush();
removed.push(sheet.getName() + " (and its form)");
deleteSheetKeepingOne_(copy, sheet);
});
copy.getSheets().forEach(sheet => {
const sheetName = sheet.getName();
if (keptSheets.indexOf(sheetName) !== -1) {
kept.push(sheetName);
return;
}
if (TEMPLATE_CLEARED_SHEETS.indexOf(sheetName) === -1) {
removed.push(sheetName);
deleteSheetKeepingOne_(copy, sheet);
return;
}
deleteDataRows_(sheet);
// A sheet without a header row (such as an unlabeled Log) has data in row 1.
const firstRow = sheet.getRange(1, 1, 1, Math.max(sheet.getLastColumn(), 1));
if (firstRow.getValues()[0].some(value => value instanceof Date)) {
firstRow.clearContent();
}
cleared.push(sheetName);
});
keepLandingSheetFirst_(copy);
const props = PropertiesService.getScriptProperties();
defaults = {};
TEMPLATE_KEPT_SETTINGS.forEach(key => {
const value = props.getProperty(key);
if (value) defaults[key] = value;
});
copy.createDeveloperMetadataFinder().withKey(TEMPLATE_DEFAULTS_KEY).find()
.forEach(metadata => metadata.remove());
copy.addDeveloperMetadata(TEMPLATE_DEFAULTS_KEY, JSON.stringify(defaults),
SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT);
copy.addDeveloperMetadata(TEMPLATE_PENDING_KEY, "yes",
SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT);
} catch (error) {
discardFailedTemplate_(copy, originalFormIds);
throw new Error("Making the template failed, so the partial copy was moved to " +
"the trash: " + error.message);
}
console.log([
'Template "' + name + '" created (not yet shared):',
" " + copy.getUrl(),
"Kept sheets: " + (kept.join(", ") || "(none)"),
"Cleared data rows on: " + (cleared.join(", ") || "(none)"),
"Removed sheets: " + (removed.join(", ") || "(none)"),
"Kept settings: " + (Object.keys(defaults).join(", ") || "(none)"),
"",
"NEXT: open the template and click Initialize and share.",
].join("\n"));
}
// ---- Appointments.js ---------------------------------------------------
// Member self-scheduling and check-in for appointments (merged from the
// appointment-tools project).
//
// Availability comes from events titled with the availability title (by
// default "Open for Appointments") on the appointment calendar; booking
// creates a new event that overlaps that block rather than editing or
// splitting it. The scheduling, check-in and listen pages are hosted on
// PAGES_BASE_URL and call this web app with fetch. There can be several
// appointment calendars (one per person members can meet with), each with its
// own scheduling link, availability title, appointment types, note and
// address, set in SWIM > Calendar.
const DEFAULT_AVAILABILITY_TITLE = "Open for Appointments";
// Appointments start every N minutes, where N is the shortest of these that
// fits the appointment (so starts stay on even times like :00, :15, :30).
// Longer appointments start on the hour.
const SLOT_STEP_CHOICES = [5, 10, 12, 15, 20, 30, 60];
const MIN_LEAD_TIME_HOURS = 24;
const BOOKING_WINDOW_DAYS = 60;
// Tab in this spreadsheet where arrivals are logged, newest in row 1.
const CHECK_IN_SHEET_NAME = "Appointment Check In";
// Script property holding the latest check-in; the listen page polls it.
const LATEST_CHECK_IN_PROPERTY = "latestCheckIn";
// The check-in page lists whoever has an appointment starting this many
// minutes before or after the check-in.
const CHECK_IN_EARLY_MINUTES = 30;
const CHECK_IN_LATE_MINUTES = 60;
// Tag set on events this system creates, so they can be told apart from the
// calendar's other events even if the appointment type list changes later.
// Kept from appointment-tools so its bookings can still be canceled here.
const APPOINTMENT_TAG_KEY = "appointmentTools";
// Tag holding the key of the appointment calendar a booking was made on, so
// people sharing one Google calendar don't block or get each other's bookings.
const APPOINTMENT_CALENDAR_TAG_KEY = "appointmentCalendar";
/**
* Runs an appointment mode and returns its JSON response. Errors become
* { status: "error", mode, message } so the pages can tell what happened.
* @param {string} mode - The mode, for the error response.
* @param {function(): Object} fn - Returns the mode's response.
*/
function appointmentResponse_(mode, fn) {
let response;
try {
response = fn();
} catch (error) {
console.error("Error for mode " + mode + ": " + error.message);
response = { status: "error", mode: mode, message: error.message };
}
return jsonResponse(response);
}
// Link key of the calendar made from the single-calendar settings of earlier
// versions, so its cancel links keep working after the first save.
const DEFAULT_CALENDAR_KEY = "main";
/**
* Returns the appointment calendars set in SWIM > Calendar. Each has its own
* scheduling link ("&cal=<key>"), name shown to members, calendar,
* availability title, appointment types, note, address and reminder email.
* Until they are first saved, the single-calendar settings of earlier
* versions make up the only one.
* @param {Object=} settings - As returned by getSettings.
* @return {Array<{key: string, name: string, calendarId: string,
* availabilityTitle: string, types: Array<{label: string, minutes: number}>,
* note: string, address: string, reminderEmail: string}>}
*/
function getAppointmentCalendars_(settings) {
settings = settings || getSettings();
const entries = settings.appointmentCalendars.length ? settings.appointmentCalendars : [{
key: DEFAULT_CALENDAR_KEY,
name: "",
calendarId: settings.appointmentCalendarId,
availabilityTitle: settings.availabilityTitle,
types: settings.appointmentTypes,
note: settings.appointmentNote,
address: settings.appointmentAddress,
reminderEmail: settings.reminderEmail,
}];
// A calendar without its own name is shown with the owner name.
return entries.map(entry => Object.assign({}, entry, { name: entry.name || settings.ownerName }));
}
/**
* Returns the appointment calendar with the given link key, or the first one
* if key is blank (links from before there could be several).
* @param {string} key - The "cal" parameter of a scheduling link.
*/
function getCalendarEntry_(key) {
const entries = getAppointmentCalendars_();
if (!key) return entries[0];
const entry = entries.find(e => e.key === key);
if (!entry) throw new Error("This scheduling link isn't valid. Please ask for a new one.");
return entry;
}
/**
* Splits an appointment type's name into what members see and the title its
* calendar events get. A name ending in parentheses, such as "Engage the
* process of repentance (Meeting with Bishop)", is shown to members without
* them and booked under the title inside them, so people who can see the
* calendar, such as clerks, don't see the reason for the appointment.
* @param {string} label - The type's name as saved.
* @return {{label: string, calendarTitle: string}}
*/
function splitTypeLabel_(label) {
const match = String(label).match(/^(.*?)\s*\(([^()]*)\)\s*$/);
if (!match || !match[1].trim() || !match[2].trim()) {
return { label: String(label), calendarTitle: String(label) };
}
return { label: match[1].trim(), calendarTitle: match[2].trim() };
}
/**
* Returns a calendar's appointment types, with any private calendar title
* left out of the label. The full name is the key the scheduling page sends
* back when booking.
* @param {Object} entry - From getAppointmentCalendars_.
* @return {Array<{key: string, label: string, minutes: number}>}
*/
function getAppointmentTypes(entry) {
return entry.types.map(t => ({ key: t.label, label: splitTypeLabel_(t.label).label,
minutes: t.minutes }));
}
function getAppointmentType_(entry, typeKey) {
const type = getAppointmentTypes(entry).find(t => t.key === typeKey);
if (!type) throw new Error("Unrecognized appointment type: " + typeKey);
return type;
}
/**
* Returns the Google calendar an appointment calendar uses, or the primary
* calendar if none has been chosen.
* @param {Object} entry - From getAppointmentCalendars_.
*/
function getAppointmentCalendar_(entry) {
if (!entry.calendarId) return CalendarApp.getDefaultCalendar();
const calendar = CalendarApp.getCalendarById(entry.calendarId);
if (!calendar) {
throw new Error("The appointment calendar" + (entry.name ? " for " + entry.name : "") +
" can't be found. Choose a calendar in SWIM > Calendar.");
}
return calendar;
}
let defaultCalendarId_ = "";
/**
* Returns the id of the Google calendar an appointment calendar uses, with
* blank (the primary calendar) replaced by the primary calendar's id.
* @param {Object} entry - From getAppointmentCalendars_.
*/
function resolvedCalendarId_(entry) {
if (entry.calendarId) return entry.calendarId;
if (!defaultCalendarId_) defaultCalendarId_ = CalendarApp.getDefaultCalendar().getId();
return defaultCalendarId_;
}
/**
* Returns the other appointment calendars that use the same Google calendar
* as entry, such as a bishop and a counselor sharing one.
* @param {Object} entry - From getAppointmentCalendars_.
* @param {Array<Object>} entries - Every appointment calendar.
*/
function calendarSharers_(entry, entries) {
const id = resolvedCalendarId_(entry);
return entries.filter(e => e.key !== entry.key && resolvedCalendarId_(e) === id);
}
/**
* Returns the key of the appointment calendar a booking was made on, or ""
* for bookings made before this was recorded.
* @param {CalendarEvent} event
*/
function appointmentCalendarKey_(event) {
return event.getTag(APPOINTMENT_CALENDAR_TAG_KEY) || "";
}
/**
* Returns whether a booked appointment belongs to entry. On a shared Google
* calendar it belongs to the appointment calendar its tag names; one without
* a tag (or naming a removed calendar) belongs to the first one listed.
* @param {CalendarEvent} event - A booked appointment.
* @param {Object} entry - From getAppointmentCalendars_.
* @param {Array<Object>} entries - Every appointment calendar.
*/
function isOwnAppointment_(event, entry, entries) {
const id = resolvedCalendarId_(entry);
const group = entries.filter(e => resolvedCalendarId_(e) === id);
if (group.length < 2) return true;
const key = appointmentCalendarKey_(event);
const owner = group.find(e => e.key === key) || group[0];
return owner.key === entry.key;
}
function bookingWindow_() {
const now = new Date();
const start = new Date(now.getTime() + MIN_LEAD_TIME_HOURS * 60 * 60 * 1000);
const end = new Date(now.getTime() + BOOKING_WINDOW_DAYS * 24 * 60 * 60 * 1000);
return { start, end };
}
/**
* Returns free sub-intervals (as {start, end} Date pairs) inside the
* availability blocks (events titled with the availability title, in any
* case), after subtracting every other overlapping event. When people share
* the Google calendar, the others' availability blocks and bookings don't
* count as busy; everything else on it does.
* @param {Object} entry - The appointment calendar, from getAppointmentCalendars_.
*/
function getFreeIntervals_(calendar, rangeStart, rangeEnd, entry) {
const titleKey = title => String(title).trim().toLowerCase();
const sharers = calendarSharers_(entry, getAppointmentCalendars_());
const otherTitles = sharers.map(e => titleKey(e.availabilityTitle));
const otherKeys = sharers.map(e => e.key);
const openTitle = titleKey(entry.availabilityTitle);
const isOpen = e => titleKey(e.getTitle()) === openTitle;
const isOthers = e => sharers.length > 0 &&
(otherTitles.indexOf(titleKey(e.getTitle())) !== -1 ||
otherKeys.indexOf(appointmentCalendarKey_(e)) !== -1);
const events = calendar.getEvents(rangeStart, rangeEnd);
const openBlocks = events.filter(isOpen);
const busyBlocks = events.filter(e => !isOpen(e) && !isOthers(e));
const intervals = [];
for (const block of openBlocks) {
let free = [{ start: block.getStartTime(), end: block.getEndTime() }];
for (const busy of busyBlocks) {
const busyStart = busy.getStartTime();
const busyEnd = busy.getEndTime();
const next = [];
for (const seg of free) {
if (busyEnd <= seg.start || busyStart >= seg.end) {
next.push(seg);
continue;
}
if (busyStart > seg.start) next.push({ start: seg.start, end: busyStart });
if (busyEnd < seg.end) next.push({ start: busyEnd, end: seg.end });
}
free = next;
}
intervals.push(...free);
}
return intervals;
}
/**
* Returns the minutes between start times for an appointment: the smallest
* divisor of 60 at least as long as it, or 60 for appointments over an hour.
* A 5-minute appointment starts every 5 minutes, a 7-minute one every 10 and
* a 13-minute one every 15.
* @param {number} minutes - The appointment length.
*/
function slotStepMinutes_(minutes) {
return SLOT_STEP_CHOICES.find(step => step >= minutes) || 60;
}
/**
* @param {Object} entry - From getAppointmentCalendars_.
* @param {string} typeKey - The appointment type's key.
*/
function getAvailableSlots(entry, typeKey) {
const type = getAppointmentType_(entry, typeKey);
const durationMs = type.minutes * 60 * 1000;
// Steps divide an hour, so rounding to them in UTC also lands on even local
// times in time zones offset by whole hours.
const stepMs = slotStepMinutes_(type.minutes) * 60 * 1000;
const { start: rangeStart, end: rangeEnd } = bookingWindow_();
const calendar = getAppointmentCalendar_(entry);
const intervals = getFreeIntervals_(calendar, rangeStart, rangeEnd, entry);
const slots = [];
for (const interval of intervals) {
let slotStart = new Date(Math.ceil(interval.start.getTime() / stepMs) * stepMs);
while (slotStart.getTime() + durationMs <= interval.end.getTime()) {
if (slotStart.getTime() >= rangeStart.getTime()) {
slots.push({
startIso: slotStart.toISOString(),
endIso: new Date(slotStart.getTime() + durationMs).toISOString(),
});
}
slotStart = new Date(slotStart.getTime() + stepMs);
}
}
slots.sort((a, b) => a.startIso.localeCompare(b.startIso));
return slots;
}
// The member's id is looked up on this sheet when an appointment is booked
// and written to the description as "Member Id: <id>".
const DIRECTORY_SHEET_NAME = "Directory";
const MEMBER_ID_LABEL = "Member Id";
const MEMBER_ID_NOT_FOUND = "Not Found";
// Calendar color (the API's colorId; "11" is Tomato) for an appointment whose
// phone or email differs from the member's Directory row, so their Church
// record can be updated.
const RECORD_UPDATE_COLOR_ID = "11";
/**
* Finds the person booking on the Directory sheet. A row matches on phone
* (digits only), then on email (any case), then on name: the first word of
* "Given" and all of "Surname" both appear in the name given (any case).
* @param {string} name - The full name entered when booking.
* @param {string} phone - The phone number entered when booking.
* @param {string} email - The email entered when booking.
* @return {?{memberId: string, phoneDiffers: boolean, emailDiffers: boolean}}
* null if there is no Directory sheet or no row matches. phoneDiffers and
* emailDiffers are true when one was entered that isn't the row's
* (including when the row has none).
*/
function findDirectoryMember_(name, phone, email) {
try {
const sheet = SpreadsheetApp.getActive().getSheetByName(DIRECTORY_SHEET_NAME);
if (!sheet || sheet.getLastRow() < 2) return null;
const values = sheet.getDataRange().getDisplayValues();
const headers = values[0].map(h => String(h).trim().toLowerCase());
const col = header => headers.indexOf(header);
const idCol = col("member id");
if (idCol === -1) return null;
const rows = values.slice(1).filter(row => String(row[idCol]).trim());
const cell = (row, c) => (c === -1 ? "" : String(row[c]).trim());
const digits = value => String(value || "").replace(/\D/g, "");
const phoneCol = col("phone");
const phoneDigits = digits(phone);
const emailCol = col("email");
const emailKey = String(email || "").trim().toLowerCase();
const givenCol = col("given");
const surnameCol = col("surname");
const nameKey = String(name || "").toLowerCase();
let row;
if (phoneDigits && phoneCol !== -1) {
row = rows.find(r => digits(r[phoneCol]) === phoneDigits);
}
if (!row && emailKey && emailCol !== -1) {
row = rows.find(r => cell(r, emailCol).toLowerCase() === emailKey);
}
if (!row && nameKey.trim() && givenCol !== -1 && surnameCol !== -1) {
row = rows.find(r => {
const given = cell(r, givenCol).toLowerCase().split(/\s+/)[0];
const surname = cell(r, surnameCol).toLowerCase();
return Boolean(given && surname) &&
nameKey.indexOf(given) !== -1 && nameKey.indexOf(surname) !== -1;
});
}
if (!row) return null;
return {
memberId: cell(row, idCol),
phoneDiffers: Boolean(phoneDigits) && digits(cell(row, phoneCol)) !== phoneDigits,
emailDiffers: Boolean(emailKey) && cell(row, emailCol).toLowerCase() !== emailKey,
};
} catch (error) {
// A Directory problem shouldn't stop the booking.
console.warn("Could not look up the member in the Directory: " + error.message);
return null;
}
}
/**
* @param {{key: string}} type - From getAppointmentType_. Its key is the full
* name, with any private calendar title; its label has that removed.
*/
function appointmentEventTitle_(type, firstName, lastName) {
return splitTypeLabel_(type.key).calendarTitle + " - " + firstName + " " + lastName;
}
/**
* @param {Object} entry - From getAppointmentCalendars_.
* @param {{typeKey: string, startIso: string, firstName: string,
* lastName: string, phone: string, email: string}} payload
*/
function bookAppointment(entry, payload) {
const { typeKey, startIso, firstName, lastName, phone, email } = payload;
const type = getAppointmentType_(entry, typeKey);
const start = new Date(startIso);
const end = new Date(start.getTime() + type.minutes * 60 * 1000);
const settings = getSettings();
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
const calendar = getAppointmentCalendar_(entry);
const stillFree = getFreeIntervals_(calendar, start, end, entry)
.some(seg => seg.start.getTime() <= start.getTime() && seg.end.getTime() >= end.getTime());
if (!stillFree) {
return { status: "conflict", message: "That time was just taken. Please pick another." };
}
const member = findDirectoryMember_(firstName + " " + lastName, phone, email);
const descriptionLines = [
"Name: " + firstName + " " + lastName,
"Phone: " + phone,
"Email: " + email,
MEMBER_ID_LABEL + ": " + ((member && member.memberId) || MEMBER_ID_NOT_FOUND),
];
const differs = member ? [member.phoneDiffers ? "phone" : "", member.emailDiffers ? "email" : ""]
.filter(Boolean) : [];
if (differs.length) {
descriptionLines.push("Update Church record: the " + differs.join(" and ") +
" given differs from the Directory.");
}
// The member is added as a guest, so Calendar's invite email is their
// confirmation. The event id is chosen up front so the cancel link can be
// in the description before the invite goes out. CalendarApp ids are the
// API id plus "@google.com".
const apiEventId = Utilities.getUuid().replace(/-/g, "");
const cancelUrl = getScheduleUrl_(settings, entry.key) +
"&cancel=" + encodeURIComponent(apiEventId + "@google.com");
if (entry.note) descriptionLines.push("", entry.note);
descriptionLines.push("", "Need to cancel? " + cancelUrl);
const eventTitle = appointmentEventTitle_(type, firstName, lastName);
Calendar.Events.insert({
id: apiEventId,
summary: eventTitle,
description: descriptionLines.join("\n"),
location: entry.address,
start: { dateTime: start.toISOString() },
end: { dateTime: end.toISOString() },
attendees: [{ email: email }],
// Only this calendar's copy is colored; the member's invite isn't.
colorId: differs.length ? RECORD_UPDATE_COLOR_ID : undefined,
}, calendar.getId(), { sendUpdates: "all" });
calendar.getEventById(apiEventId + "@google.com")
.setTag(APPOINTMENT_TAG_KEY, "true")
.setTag(APPOINTMENT_CALENDAR_TAG_KEY, entry.key);
return { status: "success", startIso: start.toISOString(), endIso: end.toISOString() };
} finally {
lock.releaseLock();
}
}
/**
* Finds a booked appointment by event id, looking first on the appointment
* calendar with the given link key and then on the others. Cancel links from
* before there could be several calendars have no key.
* @param {string} key - The cancel link's "cal" parameter, or blank.
* @param {string} eventId - The CalendarApp event id.
* @return {?{entry: Object, calendar: Calendar, event: CalendarEvent}}
*/
function findAppointment_(key, eventId) {
if (!eventId) return null;
const entries = getAppointmentCalendars_();
const named = entries.filter(e => e.key === key);
const ordered = named.concat(entries.filter(e => e.key !== key));
for (const entry of ordered) {
let calendar;
try {
calendar = getAppointmentCalendar_(entry);
} catch (error) {
continue; // A missing calendar can't hold the appointment.
}
const event = calendar.getEventById(eventId);
if (event && isCancelableAppointment_(event, entry)) {
// On a shared Google calendar, report whose appointment it is.
const owner = ordered.find(e => isOwnAppointment_(event, e, entries) &&
resolvedCalendarId_(e) === resolvedCalendarId_(entry)) || entry;
return { entry: owner, calendar, event };
}
}
return null;
}
function getAppointmentForCancel(key, eventId) {
const found = findAppointment_(key, eventId);
if (!found) return { status: "not_found" };
const timeZone = Session.getScriptTimeZone();
return {
status: "found",
calendarKey: found.entry.key,
title: found.event.getTitle(),
when: Utilities.formatDate(found.event.getStartTime(), timeZone, "EEEE, MMMM d 'at' h:mm a"),
};
}
function cancelAppointment(key, eventId) {
const found = findAppointment_(key, eventId);
if (!found) return { status: "not_found" };
// Deleted through the API so the guest is sent a cancellation too.
const apiEventId = found.event.getId().replace(/@google\.com$/, "");
Calendar.Events.remove(found.calendar.getId(), apiEventId, { sendUpdates: "all" });
return { status: "canceled", calendarKey: found.entry.key };
}
/**
* Returns the appointment calendars with a booked appointment starting from
* CHECK_IN_EARLY_MINUTES before now to CHECK_IN_LATE_MINUTES after, for the
* check-in page's "Here to see" list. Only keys and names are returned.
* @return {Array<{key: string, name: string}>}
*/
function getCheckInInterviewers() {
const now = Date.now();
return calendarsWithAppointments_(new Date(now - CHECK_IN_EARLY_MINUTES * 60 * 1000),
new Date(now + CHECK_IN_LATE_MINUTES * 60 * 1000));
}
/**
* Returns the appointment calendars with a booked appointment starting today,
* for the listen page's choice of who is listening.
* @return {Array<{key: string, name: string}>}
*/
function getTodaysInterviewers() {
// Apps Script runs in the script's time zone, so this is its midnight.
const from = new Date();
from.setHours(0, 0, 0, 0);
const to = new Date(from);
to.setDate(to.getDate() + 1);
return calendarsWithAppointments_(from, to);
}
/**
* Returns the key and name of each appointment calendar with a booked
* appointment starting from `from` up to `to`.
* @param {Date} from
* @param {Date} to
* @return {Array<{key: string, name: string}>}
*/
function calendarsWithAppointments_(from, to) {
const entries = getAppointmentCalendars_();
// People sharing a Google calendar read its events once.
const eventsById = {};
return entries.filter(entry => {
const id = resolvedCalendarId_(entry);
if (!eventsById[id]) {
try {
eventsById[id] = getAppointmentCalendar_(entry).getEvents(from, to);
} catch (error) {
eventsById[id] = []; // A missing calendar has no appointments.
}
}
return eventsById[id].some(event => event.getStartTime() >= from && event.getStartTime() < to &&
isCancelableAppointment_(event, entry) && isOwnAppointment_(event, entry, entries));
}).map(entry => ({ key: entry.key, name: entry.name }));
}
/**
* Logs an arrival at A1:C1 (name, time, who they're here to see) of the
* check-in sheet, creating the sheet if needed and pushing earlier arrivals
* down a row. The new row 1 copies the formatting of the row below it so the
* time displays the same way. The latest arrival is also kept in script
* properties, overall and for whoever they're here to see, which the listen
* page polls via mode=latest-check-in.
* @param {string} name - Who arrived.
* @param {string=} calendarKey - The appointment calendar of the person
* they're here to see, from getCheckInInterviewers, or blank.
*/
function checkIn(name, calendarKey) {
name = String(name || "").trim();
if (!name) return { status: "error", message: "Name is required" };
const entry = calendarKey ? getCalendarEntry_(calendarKey) : null;
const interviewer = entry ? entry.name : "";
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName(CHECK_IN_SHEET_NAME) ||
ss.insertSheet(CHECK_IN_SHEET_NAME, ss.getNumSheets());
const hadData = sheet.getLastRow() > 0;
const now = new Date();
sheet.getRange("A1:C1").insertCells(SpreadsheetApp.Dimension.ROWS);
if (hadData) {
sheet.getRange("A2:C2").copyFormatToRange(sheet, 1, 3, 1, 1);
}
sheet.getRange("A1:C1").setValues([[name, now, interviewer]]);
const latest = JSON.stringify({ name, timeIso: now.toISOString(), interviewer });
PropertiesService.getScriptProperties().setProperties({
[LATEST_CHECK_IN_PROPERTY]: latest,
[latestCheckInProperty_(entry ? entry.key : "")]: latest,
});
return { status: "success" };
} finally {
lock.releaseLock();
}
}
/**
* Returns the script property holding the latest check-in to see the
* appointment calendar with the given key, or blank for check-ins that
* didn't name anyone.
* @param {string} calendarKey
*/
function latestCheckInProperty_(calendarKey) {
return LATEST_CHECK_IN_PROPERTY + ":" + calendarKey;
}
/**
* Returns { name, timeIso, interviewer } for the most recent check-in, or
* null if none. interviewer is blank if they didn't choose one.
* @param {string=} calendarKey - Only check-ins to see this appointment
* calendar's person, or that didn't name anyone (so a listener still
* hears about them). Blank for every check-in.
*/
function getLatestCheckIn(calendarKey) {
const props = PropertiesService.getScriptProperties();
if (!calendarKey) {
const value = props.getProperty(LATEST_CHECK_IN_PROPERTY);
return value ? JSON.parse(value) : null;
}
const latest = [latestCheckInProperty_(calendarKey), latestCheckInProperty_("")]
.map(property => props.getProperty(property))
.filter(Boolean)
.map(value => JSON.parse(value));
latest.sort((a, b) => b.timeIso.localeCompare(a.timeIso));
return latest[0] || null;
}
/**
* Only allows canceling events this system created (never the "open for
* appointments" blocks or other calendar events). Events booked before
* tagging was added are recognized by their title.
* @param {CalendarEvent} event
* @param {Object} entry - The appointment calendar it's on.
*/
function isCancelableAppointment_(event, entry) {
if (event.getTag(APPOINTMENT_TAG_KEY) === "true") return true;
const title = event.getTitle();
return entry.types.some(type => title.indexOf(splitTypeLabel_(type.label).calendarTitle + " - ") === 0);
}
// ---- Calendar.js -------------------------------------------------------
// The SWIM > Calendar sidebar: the appointment calendars, each with its
// scheduling link, Google calendar, availability title, appointment types,
// note and address, and the daily email that lists tomorrow's appointments
// with text-reminder links.
// Runs daily (about 1 AM, script time zone) while a reminder email is set.
const REMINDER_TRIGGER_HANDLER = "sendAppointmentReminders";
const REMINDER_HOUR = 1;
/**
* Returns the calendars the user can add events to, primary first.
* @return {Array<{id: string, name: string, primary: boolean}>}
*/
function getWritableCalendars_() {
const calendars = [];
let pageToken;
do {
const page = Calendar.CalendarList.list({ minAccessRole: "writer", pageToken: pageToken });
(page.items || []).forEach(item => calendars.push({
id: item.id,
name: item.summaryOverride || item.summary || item.id,
primary: Boolean(item.primary),
}));
pageToken = page.nextPageToken;
} while (pageToken);
calendars.sort((a, b) => (b.primary - a.primary) || a.name.localeCompare(b.name));
return calendars;
}
function isReminderScheduled_() {
return ScriptApp.getProjectTriggers()
.some(trigger => trigger.getHandlerFunction() === REMINDER_TRIGGER_HANDLER);
}
/**
* Installs the daily reminder trigger if enabled and missing, or removes it
* if not enabled. Triggers belong to whoever creates them, so the email is
* sent as the person who saved the reminder address.
* @param {boolean} enabled - Whether a reminder email is set.
*/
function syncReminderTrigger_(enabled) {
const existing = ScriptApp.getProjectTriggers()
.filter(trigger => trigger.getHandlerFunction() === REMINDER_TRIGGER_HANDLER);
if (!enabled) {
existing.forEach(trigger => ScriptApp.deleteTrigger(trigger));
return;
}
if (existing.length) return;
ScriptApp.newTrigger(REMINDER_TRIGGER_HANDLER)
.timeBased()
.atHour(REMINDER_HOUR)
.everyDays(1)
.inTimezone(Session.getScriptTimeZone())
.create();
}
/**
* Returns the appointment calendars, each with its scheduling link (blank
* until the web app is deployed), and the calendar list for the Calendar
* sidebar.
*/
function getCalendarView() {
const settings = getSettings();
const calendars = getWritableCalendars_();
const primary = calendars.find(c => c.primary);
const several = getAppointmentCalendars_(settings).length > 1;
const entries = getAppointmentCalendars_(settings).map(entry => {
let calendarId = entry.calendarId;
if (!calendarId) {
calendarId = primary ? primary.id : "";
} else if (!calendars.some(c => c.id === calendarId)) {
calendars.push({ id: calendarId, name: calendarId + " (not available)", primary: false });
}
return Object.assign({}, entry, {
calendarId: calendarId,
// A single calendar keeps the plain link it has always had.
url: getScheduleUrl_(settings, several ? entry.key : ""),
});
});
return {
calendars: calendars,
entries: entries,
chooserUrl: several ? getScheduleUrl_(settings, "") : "",
reminderScheduled: isReminderScheduled_(),
// The script's date, the default day for Copy Appointments.
today: Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd"),
};
}
/**
* Returns a link key made from a calendar's name ("Brother Smith" ->
* "brother-smith"), different from every key in used.
* @param {string} name
* @param {string[]} used - Keys already taken.
*/
function newCalendarKey_(name, used) {
const base = String(name).toLowerCase().replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "").slice(0, 30) || "calendar";
let key = base;
for (let n = 2; used.indexOf(key) !== -1; n++) key = base + "-" + n;
return key;
}
/**
* Validates and saves the Calendar sidebar's appointment calendars, then
* turns the daily reminder email on or off to match. Each keeps its link key,
* so links already shared keep working; new ones get a key from their name.
* @param {{entries: Array<{key: string, name: string, calendarId: string,
* availabilityTitle: string,
* types: Array<{label: string, minutes: string}>, note: string,
* address: string, reminderEmail: string}>}} values - The new values.
* @return {Object} The updated getCalendarView().
*/
function saveCalendarSettings(values) {
const rows = (values && values.entries) || [];
if (!rows.length) throw new Error("Add at least one calendar.");
const writable = getWritableCalendars_();
const names = [];
const keys = [];
const entries = rows.map(row => {
const name = String(row.name || "").trim();
if (!name && rows.length > 1) {
throw new Error("Each calendar needs a name to show members.");
}
if (name && names.indexOf(name.toLowerCase()) !== -1) {
throw new Error('There are two calendars named "' + name + '".');
}
names.push(name.toLowerCase());
const forName = name ? ' for "' + name + '"' : "";
const calendarId = String(row.calendarId || "").trim();
if (calendarId && !writable.some(c => c.id === calendarId)) {
throw new Error("You can't add events to the calendar chosen" + forName +
". Please choose another.");
}
let types;
try {
types = parseAppointmentTypeRows_(row.types);
} catch (error) {
throw new Error(error.message + (rows.length > 1 ? " (" + name + ")" : ""));
}
const email = String(row.reminderEmail || "").trim();
if (email && !/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(email)) {
throw new Error('"' + email + '" doesn\'t look like an email address.');
}
let key = String(row.key || "").trim();
if (!/^[a-z0-9-]+$/.test(key) || keys.indexOf(key) !== -1) key = newCalendarKey_(name, keys);
keys.push(key);
const title = String(row.availabilityTitle || "").trim();
return {
key: key,
name: name,
calendarId: calendarId,
// The default title is left unstored so it can change in a later release.
availabilityTitle: title === DEFAULT_AVAILABILITY_TITLE ? "" : title,
types: types,
note: String(row.note || "").trim(),
address: String(row.address || "").trim(),
reminderEmail: email,
};
});
// People sharing a Google calendar are told apart by their availability
// titles, so those must differ.
const primary = writable.find(c => c.primary);
const calendarOf = e => e.calendarId || (primary ? primary.id : "");
const titleOf = e => (e.availabilityTitle || DEFAULT_AVAILABILITY_TITLE).toLowerCase();
entries.forEach((a, i) => entries.slice(i + 1).forEach(b => {
if (calendarOf(a) === calendarOf(b) && titleOf(a) === titleOf(b)) {
throw new Error('"' + a.name + '" and "' + b.name + '" use the same calendar, so ' +
"they need different availability titles.");
}
}));
setSetting_(SETTINGS.APPOINTMENT_CALENDARS, JSON.stringify(entries));
syncReminderTrigger_(entries.some(e => e.reminderEmail));
return getCalendarView();
}
/**
* Returns plain text from an event description, which Calendar may have
* saved as HTML if it was edited there.
* @param {string} description
*/
function descriptionText_(description) {
return String(description || "")
.replace(/<br\s*\/?>/gi, "\n")
.replace(/<\/(p|div)>/gi, "\n")
.replace(/<[^>]*>/g, "")
.replace(/ /g, " ")
.replace(/&/g, "&");
}
/**
* Returns what the reminder email shows for a booked appointment. Booking
* titles events "<type> - <first> <last>" and puts "Name:", "Phone:", "Email:"
* and "Member Id:" lines in the description (see bookAppointment).
* @param {CalendarEvent} event
* @param {Object} entry - The appointment calendar, from getAppointmentCalendars_.
* @return {{start: Date, name: string, firstName: string, type: string,
* phone: string, email: string, location: string}}
*/
function describeAppointment_(event, entry) {
const title = event.getTitle();
// A type with a private calendar title is shown by that title, never its
// real name, since the reminder email may go to someone else. Events booked
// before the type had a private title begin with its full or shown name
// instead, so those are matched too (longest first) and shown by the title.
const names = [];
entry.types.forEach(t => {
const split = splitTypeLabel_(t.label);
[t.label, split.label, split.calendarTitle].forEach(name =>
names.push({ prefix: name.toLowerCase() + " - ", title: split.calendarTitle }));
});
names.sort((a, b) => b.prefix.length - a.prefix.length);
const known = names.find(n => title.toLowerCase().indexOf(n.prefix) === 0);
const dash = known ? known.prefix.length - 3 : title.indexOf(" - ");
const typeLabel = known ? known.title : (dash === -1 ? "" : title.slice(0, dash));
const lines = descriptionText_(event.getDescription()).split("\n");
const field = label => {
const line = lines.find(l => l.trim().toLowerCase().indexOf(label + ":") === 0);
return line ? line.trim().slice(label.length + 1).trim() : "";
};
const name = field("name") || (dash === -1 ? title : title.slice(dash + 3)).trim();
return {
start: event.getStartTime(),
name: name,
firstName: name.split(/\s+/)[0] || name,
type: typeLabel,
phone: field("phone"),
email: field("email"),
location: event.getLocation() || entry.address,
};
}
/**
* Returns the text message reminding someone of their appointment. It says
* "today" or "tomorrow" when the appointment is then.
* @param {Object} appt - As returned by describeAppointment_.
* @param {Object} entry - The appointment calendar, from getAppointmentCalendars_.
*/
function reminderText_(appt, entry) {
const timeZone = Session.getScriptTimeZone();
const when = Utilities.formatDate(appt.start, timeZone, "EEEE, MMMM d 'at' h:mm a");
const dayOf = date => Utilities.formatDate(date, timeZone, "yyyy-MM-dd");
// Apps Script's local time is the script's time zone.
const now = new Date();
const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
const relative = dayOf(appt.start) === dayOf(now) ? "today, "
: dayOf(appt.start) === dayOf(tomorrow) ? "tomorrow, " : "";
return "Hi " + appt.firstName + ", this is a reminder of your " +
(appt.type ? appt.type + " " : "") + "appointment with " +
(entry.name || "the Bishop") + " " + relative + when +
(appt.location ? " at " + appt.location : "") +
". Please let us know if you need to reschedule.";
}
// The daily email links to the Text Reminders page with a code that opens
// one appointment calendar's appointments for one day. The email may go to
// someone else, such as a clerk, so it never carries the owner key.
/**
* Returns the code in a Text Reminders link for one appointment calendar and
* day. It is made from the secretary key, so the executive secretaries' Links
* page can make these links too, and resetting the owner key (SWIM > System >
* Settings) also stops the reminder links already sent.
* @param {string} calendarKey - The appointment calendar's key.
* @param {string} day - The day, as "yyyy-MM-dd" in the script's time zone.
*/
function reminderCode_(calendarKey, day) {
const signature = Utilities.computeHmacSha256Signature(calendarKey + "|" + day, getSecretaryKey_());
return Utilities.base64EncodeWebSafe(signature).replace(/=+$/, "").slice(0, 32);
}
/**
* Returns true if code is the Text Reminders code for this calendar and day.
* Compares hashes, like isOwnerKey_.
*/
function isReminderCode_(calendarKey, day, code) {
return Boolean(code) &&
hashSecret_(code) === hashSecret_(reminderCode_(calendarKey, day));
}
/**
* Returns the Text Reminders page link for an appointment calendar's
* appointments on one day, or "" when there is no Deployment ID. Like the
* private links, its code follows "#" so it is never sent to the page's site.
* @param {Object} settings - As returned by getSettings.
* @param {Object} entry - The appointment calendar, from getAppointmentCalendars_.
* @param {string} day - The day, as "yyyy-MM-dd" in the script's time zone.
*/
function getRemindersUrl_(settings, entry, day) {
if (!settings.deploymentId) return "";
return PAGES_BASE_URL + "reminders.html#token=" + encodeURIComponent(settings.deploymentId) +
"~" + reminderCode_(entry.key, day) + "&cal=" + encodeURIComponent(entry.key) +
"&day=" + day;
}
/**
* mode=reminder-list: an appointment calendar's booked appointments on one
* day, each with the reminder text to send, for the Text Reminders page.
* Needs the code from that day's link, and only works until the day is over.
* @param {string} calendarKey - The appointment calendar's key.
* @param {string} day - The day, as "yyyy-MM-dd" in the script's time zone.
* @param {string} code - From the link; see reminderCode_.
*/
function getReminderList(calendarKey, day, code) {
const allEntries = getAppointmentCalendars_();
const entry = allEntries.find(e => e.key === calendarKey);
const parts = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day || ""));
if (!entry || !parts || !isReminderCode_(calendarKey, day, code)) {
return { status: "error", message: "This reminders link isn't valid. Open the link " +
"in the newest daily appointment email." };
}
// Apps Script's local time is the script's time zone.
const start = new Date(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]));
const end = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 1);
if (end <= new Date()) {
return { status: "error", message: "These appointments are over, so this link no " +
"longer works." };
}
const timeZone = Session.getScriptTimeZone();
return {
status: "success",
data: {
name: entry.name,
dayLabel: Utilities.formatDate(start, timeZone, "EEEE, MMMM d"),
appointments: appointmentsBetween_(entry, allEntries, start, end).map(appt => ({
time: Utilities.formatDate(appt.start, timeZone, "h:mm a"),
name: appt.name,
type: appt.type,
phone: appt.phone.replace(/[^\d+]/g, ""),
text: reminderText_(appt, entry),
})),
},
};
}
/**
* Returns the booked appointments on an appointment calendar starting from
* start up to end, in time order.
* @param {Object} entry - The appointment calendar, from getAppointmentCalendars_.
* @param {Array<Object>} allEntries - Every appointment calendar.
* @param {Date} start
* @param {Date} end
* @return {Array<Object>} As returned by describeAppointment_.
*/
function appointmentsBetween_(entry, allEntries, start, end) {
return getAppointmentCalendar_(entry).getEvents(start, end)
.filter(e => !e.isAllDayEvent() && e.getStartTime() >= start &&
isCancelableAppointment_(e, entry) && isOwnAppointment_(e, entry, allEntries))
.sort((a, b) => a.getStartTime() - b.getStartTime())
.map(e => describeAppointment_(e, entry));
}
/**
* Returns the reminder email's HTML. Styles are inline because email apps
* drop style sheets; buttons are large so they're easy to tap on a phone.
* @param {Array<Object>} appts - As returned by describeAppointment_.
* @param {string} dayLabel - Such as "Friday, October 10".
* @param {Object} entry - The appointment calendar, from getAppointmentCalendars_.
* @param {string} remindersUrl - The Text Reminders page for the day, from
* getRemindersUrl_. Without one (no Deployment ID yet), each appointment
* gets its own sms: button instead, which some email apps remove.
*/
function reminderEmailHtml_(appts, dayLabel, entry, remindersUrl) {
const timeZone = Session.getScriptTimeZone();
const cards = appts.map(appt => {
const time = Utilities.formatDate(appt.start, timeZone, "h:mm a");
const digits = appt.phone.replace(/[^\d+]/g, "");
let html = '<div style="border:1px solid #dadce0;border-radius:8px;padding:12px 14px;' +
'margin:0 0 12px;">' +
'<div style="font-size:18px;font-weight:bold;">' + htmlEscape_(time) + " · " +
htmlEscape_(appt.name) + "</div>";
if (appt.type) {
html += '<div style="color:#5f6368;margin-top:2px;">' + htmlEscape_(appt.type) + "</div>";
}
if (digits && remindersUrl) {
html += '<div style="margin-top:4px;"><a href="tel:' + htmlEscape_(digits) +
'" style="color:#1a73e8;">' + htmlEscape_(appt.phone) + "</a></div>";
} else if (digits) {
// "?&body=" works in both the iPhone and Android messaging apps.
const smsUrl = "sms:" + digits + "?&body=" + encodeURIComponent(reminderText_(appt, entry));
html += '<div style="margin-top:4px;"><a href="tel:' + htmlEscape_(digits) +
'" style="color:#1a73e8;">' + htmlEscape_(appt.phone) + "</a></div>" +
'<a href="' + htmlEscape_(smsUrl) + '" style="display:block;margin-top:10px;' +
"padding:14px;background:#1a73e8;color:#ffffff;text-align:center;font-size:17px;" +
'font-weight:bold;text-decoration:none;border-radius:8px;">Text reminder</a>';
} else {
html += '<div style="color:#c5221f;margin-top:4px;">No phone number on this appointment.</div>';
}
return html + "</div>";
});
const intro = remindersUrl
? '<p style="color:#5f6368;margin:0 0 10px;">Tap <b>Send text reminders</b> to open a ' +
"page with a button that texts each person a reminder.</p>" +
'<a href="' + htmlEscape_(remindersUrl) + '" style="display:block;margin:0 0 16px;' +
"padding:14px;background:#1a73e8;color:#ffffff;text-align:center;font-size:17px;" +
'font-weight:bold;text-decoration:none;border-radius:8px;">Send text reminders</a>'
: '<p style="color:#5f6368;margin:0 0 16px;">Tap <b>Text reminder</b> to send each ' +
"person a reminder that their appointment is tomorrow.</p>";
return '<div style="font-family:Arial,sans-serif;font-size:16px;color:#202124;' +
'max-width:520px;">' +
'<h2 style="font-size:20px;margin:0 0 4px;">Appointments for ' + htmlEscape_(dayLabel) + "</h2>" +
intro + cards.join("") + "</div>";
}
/**
* Emails each appointment calendar's booked appointments for tomorrow to its
* reminder address. Nothing is sent for a calendar with no address or no
* appointments tomorrow. A calendar that fails doesn't stop the others; the
* failures are thrown together at the end.
* @return {string} What happened, for the sidebar.
*/
function emailTomorrowsAppointments_() {
const settings = getSettings();
const allEntries = getAppointmentCalendars_(settings);
const entries = allEntries.filter(e => e.reminderEmail);
if (!entries.length) return "No reminder email address is saved.";
// Apps Script's local time is the script's time zone.
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 2);
const dayLabel = Utilities.formatDate(start, Session.getScriptTimeZone(), "EEEE, MMMM d");
const day = Utilities.formatDate(start, Session.getScriptTimeZone(), "yyyy-MM-dd");
const results = [];
const failures = [];
entries.forEach(entry => {
const prefix = entries.length > 1 ? entry.name + ": " : "";
try {
const appts = appointmentsBetween_(entry, allEntries, start, end);
if (!appts.length) {
results.push(prefix + "No appointments tomorrow, so nothing was sent.");
return;
}
if (MailApp.getRemainingDailyQuota() < 1) {
throw new Error("The daily email quota has been reached; try again tomorrow.");
}
MailApp.sendEmail({
to: entry.reminderEmail,
subject: "Appointments tomorrow, " + dayLabel + " (" + appts.length + ")",
htmlBody: reminderEmailHtml_(appts, dayLabel, entry, getRemindersUrl_(settings, entry, day)),
name: entry.name || undefined,
});
results.push(prefix + "Sent " + appts.length + " appointment" +
(appts.length === 1 ? "" : "s") + " to " + entry.reminderEmail + ".");
} catch (error) {
failures.push(prefix + error.message);
}
});
if (failures.length) throw new Error(results.concat(failures).join(" "));
return results.join(" ");
}
/**
* Trigger handler: emails tomorrow's appointments each morning.
*/
function sendAppointmentReminders() {
console.log(emailTomorrowsAppointments_());
}
/**
* Sends tomorrow's list right away, from the Calendar sidebar.
* @return {string} What happened.
*/
function sendAppointmentRemindersNow() {
return emailTomorrowsAppointments_();
}
const APPOINTMENT_COPY_HEADERS = ["Member ID", "Name", "Phone", "Email", "Reason", "Time"];
/**
* Returns the member id from an appointment's "LCR Record" link: the part of
* the URL after the last "/". The link may be plain text ("LCR Record:
* https://...") or, if the event was edited in Calendar, an HTML link whose
* text is "LCR Record".
* @param {string} description - The event description.
* @return {string} The member id, or "" if there is no LCR Record link.
*/
function lcrMemberId_(description) {
const raw = String(description || "");
const line = descriptionText_(raw).split("\n")
.find(l => /^\s*lcr record/i.test(l));
let url = line ? (line.match(/https?:\/\/\S+/) || [""])[0] : "";
if (!url) {
const link = raw.match(/href="([^"]+)"[^>]*>\s*LCR Record/i) ||
raw.match(/LCR Record[\s\S]*?href="([^"]+)"/i);
url = link ? link[1].replace(/&/g, "&") : "";
}
const path = url.replace(/[?#].*$/, "").replace(/\/+$/, "");
return path ? decodeURIComponent(path.slice(path.lastIndexOf("/") + 1)) : "";
}
/**
* Returns the member id of an appointment: its "Member Id:" line (written
* when it was booked; see findDirectoryMember_), else its "LCR Record"
* link (see lcrMemberId_).
* @param {string} description - The event description.
* @return {string} The member id, or "" if neither gives one.
*/
function appointmentMemberId_(description) {
const prefix = MEMBER_ID_LABEL.toLowerCase() + ":";
const line = descriptionText_(description).split("\n")
.find(l => l.trim().toLowerCase().indexOf(prefix) === 0);
const id = line ? line.trim().slice(prefix.length).trim() : "";
if (id && id.toLowerCase() !== MEMBER_ID_NOT_FOUND.toLowerCase()) return id;
return lcrMemberId_(description);
}
/**
* Returns the appointments on an appointment calendar for one day, in time
* order, as tab-separated text with a header row, for the Calendar sidebar's
* Copy Appointments button. For today, only those that haven't started yet.
* Booked appointments and any other event with a member id ("Member Id:"
* line or "LCR Record" link) count as appointments.
* @param {string} key - The appointment calendar's key.
* @param {string} day - The day, as "yyyy-MM-dd" in the script's time zone.
* @return {{count: number, tsv: string}}
*/
function getAppointmentsTsv(key, day) {
const entries = getAppointmentCalendars_();
const entry = entries.find(e => e.key === key);
if (!entry) throw new Error("Save this calendar first.");
const parts = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day || ""));
if (!parts) throw new Error("Choose a day.");
// Apps Script's local time is the script's time zone.
const now = new Date();
const dayStart = new Date(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]));
const end = new Date(dayStart.getFullYear(), dayStart.getMonth(), dayStart.getDate() + 1);
const start = now > dayStart && now < end ? now : dayStart;
const timeZone = Session.getScriptTimeZone();
const rows = copiedAppointments_(entries, entry, start, end).map(appt =>
[appt.memberId, appt.name, appt.phone, appt.email, appt.type,
Utilities.formatDate(appt.start, timeZone, "h:mm a")]);
return { count: rows.length, tsv: appointmentsTsv_(APPOINTMENT_COPY_HEADERS, rows) };
}
const UPCOMING_APPOINTMENT_COPY_HEADERS = ["Member ID", "Name", "Phone", "Email", "Reason",
"Date", "Time"];
// How far ahead Copy All Upcoming looks. Booking is limited to
// BOOKING_WINDOW_DAYS, but appointments added in Calendar can be later.
const UPCOMING_APPOINTMENT_DAYS = 366;
/**
* Returns every appointment still to come on an appointment calendar, in
* time order, as tab-separated text with a header row, for the Calendar
* sidebar's Copy All Upcoming button. Like getAppointmentsTsv, with a Date
* column since the appointments span many days.
* @param {string} key - The appointment calendar's key.
* @return {{count: number, tsv: string}}
*/
function getUpcomingAppointmentsTsv(key) {
const entries = getAppointmentCalendars_();
const entry = entries.find(e => e.key === key);
if (!entry) throw new Error("Save this calendar first.");
const now = new Date();
const end = new Date(now.getTime() + UPCOMING_APPOINTMENT_DAYS * 24 * 60 * 60 * 1000);
const timeZone = Session.getScriptTimeZone();
const rows = copiedAppointments_(entries, entry, now, end).map(appt =>
[appt.memberId, appt.name, appt.phone, appt.email, appt.type,
Utilities.formatDate(appt.start, timeZone, "yyyy-MM-dd"),
Utilities.formatDate(appt.start, timeZone, "h:mm a")]);
return { count: rows.length, tsv: appointmentsTsv_(UPCOMING_APPOINTMENT_COPY_HEADERS, rows) };
}
/**
* Returns the appointments on an appointment calendar starting from start up
* to end, in time order, for the Copy Appointments panel. Booked appointments
* and any other event with a member id ("Member Id:" line or "LCR Record"
* link) count as appointments.
* @param {Array<Object>} entries - Every appointment calendar.
* @param {Object} entry - The appointment calendar, from getAppointmentCalendars_.
* @param {Date} start
* @param {Date} end
* @return {Array<Object>} As returned by describeAppointment_, plus memberId.
*/
function copiedAppointments_(entries, entry, start, end) {
return getAppointmentCalendar_(entry).getEvents(start, end)
.filter(e => !e.isAllDayEvent() && e.getStartTime() >= start &&
(isCancelableAppointment_(e, entry) || appointmentMemberId_(e.getDescription())) &&
isOwnAppointment_(e, entry, entries))
.sort((a, b) => a.getStartTime() - b.getStartTime())
.map(e => Object.assign(describeAppointment_(e, entry),
{ memberId: appointmentMemberId_(e.getDescription()) }));
}
/**
* Returns rows as tab-separated text under a header row. Tabs and line breaks
* inside a value become spaces so each row stays one spreadsheet row.
* @param {string[]} headers
* @param {Array<Array<string>>} rows
*/
function appointmentsTsv_(headers, rows) {
const clean = value => String(value || "").replace(/[\t\r\n]+/g, " ").trim();
return [headers].concat(rows).map(row => row.map(clean).join("\t")).join("\n");
}
/**
* Opens the Calendar sidebar.
*/
function showCalendar() {
const html = HtmlService.createHtmlOutput(`
<style>
body { font-family: Arial, sans-serif; font-size: 13px; line-height: 1.4;
color: #202124; margin: 0; padding: 12px; }
h3 { font-size: 13px; margin: 20px 0 2px; }
h3.first { margin-top: 0; }
h4 { font-size: 12px; margin: 12px 0 2px; }
.hint { color: #5f6368; font-size: 12px; margin: 2px 0 6px; }
input[type=text], input[type=email], input[type=number], textarea, select {
width: 100%; box-sizing: border-box; font: inherit; padding: 4px 6px; }
textarea { resize: vertical; }
.row { display: flex; justify-content: flex-end; align-items: center; gap: 8px;
margin-top: 6px; }
.status { font-size: 12px; flex: 1; }
.ok { color: #137333; }
.error { color: #c5221f; }
hr { border: none; border-top: 1px solid #e0e0e0; margin: 16px 0 0; }
.item { display: flex; align-items: center; gap: 8px; padding: 4px 0;
border-bottom: 1px solid #eee; }
.type-row input.type-label { flex: 1; min-width: 0; }
details.entry { border: 1px solid #dadce0; border-radius: 8px; margin: 8px 0;
padding: 0 10px; }
details.entry[open] { padding-bottom: 10px; }
details.entry summary { cursor: pointer; padding: 8px 0; font-weight: bold; }
details.entry summary .copy-appts { float: right; margin-top: -2px; font-weight: normal; }
.copy-panel { clear: both; border: 1px solid #d2e3fc; background: #e8f0fe;
border-radius: 8px; margin: 8px 0 0; padding: 8px 10px; font-weight: normal;
cursor: default; }
.copy-panel .row { margin-top: 0; justify-content: flex-start; }
.copy-panel .all-row { margin-top: 8px; padding-top: 8px; border-top: 1px solid #d2e3fc; }
.copy-panel input[type=date] { font: inherit; padding: 3px 6px; }
.copy-panel .status { display: block; margin-top: 6px; }
.copy-panel .status:empty { display: none; }
.link-row { display: flex; gap: 6px; }
.link-row input { flex: 1; min-width: 0; color: #1a73e8; }
${UNSAVED_BAR_CSS}
</style>
${UNSAVED_BAR_HTML}
<div id="loading">
<div id="loadingText">Loading calendars…</div>
<div class="row" id="retryRow" style="display: none; justify-content: flex-start;">
<button onclick="load()">Try again</button>
</div>
</div>
<div id="main" style="display: none;">
<h3 class="first">Appointment calendars</h3>
<div class="hint">Add a calendar for each person members can book with. Each one
gets its own scheduling link.</div>
<div id="chooser" style="display: none;">
<h4>Link for everyone</h4>
<div class="hint">Members choose who to meet with first. <SCHEDULE LINK>
in messages uses this link.</div>
<div class="link-row">
<input type="text" id="chooserUrl" readonly onclick="this.select()">
<button onclick="copyLink(el('chooserUrl'), this)">Copy</button>
</div>
</div>
<div id="entries"></div>
<div class="row"><button onclick="addEntry(null, true); changed()">Add calendar</button></div>
<div class="row">
<span id="saveStatus" class="status"></span>
<button id="saveBtn" onclick="save()">Save</button>
</div>
<hr>
<h3>Send tomorrow's list now</h3>
<div class="hint">Emails tomorrow's appointments to each calendar's daily email
address right away.</div>
<div id="reminderState" class="hint"></div>
<div class="row">
<span id="sendStatus" class="status"></span>
<button id="sendBtn" onclick="sendNow()">Send now</button>
</div>
</div>
<script>
var dirty = false;
var hasEmail = false;
var calendars = [];
var today = "";
// A Copy Appointments panel hides after this long without use.
var COPY_PANEL_SECONDS = 10;
// The day copyAppointments takes to copy every appointment to come.
var ALL_UPCOMING = "all";
function el(id) { return document.getElementById(id); }
function setStatus(id, text, cls) {
el(id).textContent = text;
el(id).className = "status " + (cls || "");
}
function setBusy(busy) {
el("saveBtn").disabled = busy;
el("unsavedSaveBtn").disabled = busy;
}
function updateSendButton() {
el("sendBtn").disabled = dirty || !hasEmail;
}
// Marks the fields as edited, showing the unsaved-changes bar.
function setDirty(value) {
dirty = value;
document.body.className = value ? "dirty" : "";
updateSendButton();
}
function changed() {
setDirty(true);
setStatus("saveStatus", "");
}
// Asks before the panel closes with unsaved edits. Browsers may skip
// this for a sidebar, so the bar above is the main reminder.
window.addEventListener("beforeunload", function (event) {
if (!dirty) return;
event.preventDefault();
event.returnValue = "";
});
// Copies through the link's own text box; the clipboard API isn't
// reliably allowed inside the sidebar's frame.
function copyLink(input, button) {
input.select();
var copied = false;
try { copied = document.execCommand("copy"); } catch (e) {}
var label = button.textContent;
button.textContent = copied ? "Copied" : "Press Ctrl+C";
setTimeout(function () { button.textContent = label; }, 1500);
}
// Copies text through a hidden text area. Returns false if the browser
// refused.
function copyText(text) {
var area = document.createElement("textarea");
area.value = text;
area.style.position = "fixed";
area.style.opacity = "0";
document.body.appendChild(area);
area.select();
var copied = false;
try { copied = document.execCommand("copy"); } catch (e) {}
document.body.removeChild(area);
return copied;
}
function describeCopied(count) {
return "Copied " + count + " appointment" + (count === 1 ? "" : "s") +
" to the clipboard. Paste it into a spreadsheet.";
}
// Builds the panel shown under a calendar's card by its Copy
// Appointments button: a day (today to start) and a Copy button.
function buildCopyPanel(key) {
var panel = document.createElement("div");
panel.className = "copy-panel";
panel.style.display = "none";
var row = document.createElement("div");
row.className = "row";
var label = document.createElement("label");
label.textContent = "Day";
var day = document.createElement("input");
day.type = "date";
day.value = today;
var copy = document.createElement("button");
copy.textContent = "Copy";
row.appendChild(label);
row.appendChild(day);
row.appendChild(copy);
var allRow = document.createElement("div");
allRow.className = "row all-row";
var copyAll = document.createElement("button");
copyAll.textContent = "Copy All Upcoming";
copyAll.title = "Every appointment still to come, with its date";
allRow.appendChild(copyAll);
var status = document.createElement("div");
status.className = "status";
panel.appendChild(row);
panel.appendChild(allRow);
panel.appendChild(status);
// The panel is inside the card's summary, where a click would open or
// close the card. Clicks on the date box and its label are left alone
// (the browser doesn't toggle the card for those); the Copy button's
// own handler still runs.
panel.onclick = function (event) {
if (event.target !== day && event.target !== label) event.preventDefault();
};
// Keeps keys typed in the date box from reaching the summary.
panel.onkeydown = panel.onkeyup = function (event) { event.stopPropagation(); };
day.onchange = function () {
copy.pending = null;
copy.textContent = "Copy";
status.textContent = "";
};
copy.onclick = function () { copyAppointments(key, day.value, copy, status, wait); };
copyAll.onclick = function () { copyAppointments(key, ALL_UPCOMING, copyAll, status, wait); };
function reset() {
[copy, copyAll].forEach(function (button) {
button.pending = null;
button.textContent = button.label;
});
}
copy.label = copy.textContent;
copyAll.label = copyAll.textContent;
// Hides the panel after COPY_PANEL_SECONDS without use. Using it, or a
// message arriving, starts the count again; it doesn't hide while
// copying or while the date box has focus (its picker may be open).
var timer = null;
function wait() {
clearTimeout(timer);
timer = setTimeout(function () {
if (copy.disabled || copyAll.disabled || document.activeElement === day) wait();
else panel.hide();
}, COPY_PANEL_SECONDS * 1000);
}
["click", "keydown", "change", "focusin"].forEach(function (type) {
panel.addEventListener(type, wait);
});
panel.isShowing = function () { return panel.style.display !== "none"; };
panel.show = function () {
reset();
status.textContent = "";
panel.style.display = "block";
wait();
};
panel.hide = function () {
clearTimeout(timer);
panel.style.display = "none";
};
return panel;
}
// Copies a calendar's appointments for a day as tab-separated rows
// (for today, only those still to come), or with day ALL_UPCOMING,
// every appointment still to come. The browser may refuse to copy once
// the server answers, since the click is no longer recent; then the
// next click copies the rows already fetched. onMessage is called after
// each message is shown.
function copyAppointments(key, day, button, status, onMessage) {
var all = day === ALL_UPCOMING;
function show(text, cls) {
status.textContent = text;
status.className = "status " + (cls || "");
onMessage();
}
if (button.pending) {
var pending = button.pending;
button.pending = null;
button.textContent = button.label;
if (copyText(pending.tsv)) show(describeCopied(pending.count), "ok");
else show("The browser wouldn't copy to the clipboard. Please try again.", "error");
return;
}
if (!day) {
show("Choose a day.", "error");
return;
}
button.disabled = true;
show("Copying\\u2026");
var run = google.script.run
.withSuccessHandler(function (result) {
button.disabled = false;
if (!result.count) {
show(all ? "There are no upcoming appointments."
: day === today ? "There are no more appointments today."
: "There are no appointments that day.");
return;
}
if (!copyText(result.tsv)) {
button.pending = result;
button.textContent = "Click to copy";
show("Found " + result.count + " appointment" + (result.count === 1 ? "" : "s") +
". Click the button again to copy.");
return;
}
show(describeCopied(result.count), "ok");
})
.withFailureHandler(function (error) {
button.disabled = false;
show("Could not copy the appointments: " + error.message, "error");
});
if (all) run.getUpcomingAppointmentsTsv(key);
else run.getAppointmentsTsv(key, day);
}
function render(view) {
el("loading").style.display = "none";
el("main").style.display = "block";
calendars = view.calendars;
today = view.today;
el("chooser").style.display = view.chooserUrl ? "block" : "none";
el("chooserUrl").value = view.chooserUrl;
el("entries").innerHTML = "";
view.entries.forEach(function (entry) { addEntry(entry, view.entries.length === 1); });
hasEmail = view.entries.some(function (e) { return e.reminderEmail; });
el("reminderState").textContent = !hasEmail ? "Daily email: off." : view.reminderScheduled
? "Daily email: on, at about 1 AM." : "Daily email: not scheduled yet. Click Save to schedule it.";
setDirty(false);
}
// Adds a labeled field to a calendar's card and returns the field.
function addField(card, title, hint, field) {
var h = document.createElement("h4");
h.textContent = title;
card.appendChild(h);
if (hint) {
var div = document.createElement("div");
div.className = "hint";
div.textContent = hint;
card.appendChild(div);
}
card.appendChild(field);
return field;
}
function input(type, value, className) {
var field = document.createElement(type === "textarea" ? "textarea" : "input");
if (type === "textarea") field.rows = 3; else field.type = type;
field.value = value || "";
field.className = className;
field.oninput = changed;
return field;
}
// Adds a card for one appointment calendar. entry is null for a new one.
function addEntry(entry, open) {
entry = entry || { key: "", name: "", calendarId: "", availabilityTitle: "",
types: [], note: "", address: "", reminderEmail: "", url: "" };
var card = document.createElement("details");
card.className = "entry";
card.open = open;
card.dataset.key = entry.key;
var summary = document.createElement("summary");
var title = document.createElement("span");
title.textContent = entry.name || "New calendar";
// In the summary so it shows while the card is closed. It opens a
// panel, also in the summary, under the calendar's name. Only saved
// calendars have appointments to copy.
var copyPanel = null;
if (entry.key) {
copyPanel = buildCopyPanel(entry.key);
var copyAppts = document.createElement("button");
copyAppts.className = "copy-appts";
copyAppts.textContent = "Copy Appointments";
copyAppts.title = "Copy a day's appointments to paste into a spreadsheet";
copyAppts.onclick = function (event) {
event.preventDefault(); // Don't open or close the card.
if (copyPanel.isShowing()) copyPanel.hide(); else copyPanel.show();
};
summary.appendChild(copyAppts);
}
summary.appendChild(title);
if (copyPanel) summary.appendChild(copyPanel);
card.appendChild(summary);
var name = addField(card, "Name shown to members",
"Such as \\"Bishop Smith\\". Members see it on the scheduling page and in reminders.",
input("text", entry.name, "f-name"));
name.addEventListener("input", function () {
title.textContent = name.value.trim() || "New calendar";
});
var select = document.createElement("select");
select.className = "f-calendar";
select.onchange = changed;
calendars.forEach(function (c) {
var option = document.createElement("option");
option.value = c.id;
option.textContent = c.name + (c.primary ? " (primary)" : "");
select.appendChild(option);
});
select.value = entry.calendarId || (calendars[0] ? calendars[0].id : "");
addField(card, "Google calendar",
"Bookings are added to this calendar, and the open times come from it.", select);
var link = document.createElement("div");
if (entry.url) {
link.className = "link-row";
var url = input("text", entry.url, "f-url");
url.readOnly = true;
url.onclick = function () { url.select(); };
var copy = document.createElement("button");
copy.textContent = "Copy";
copy.onclick = function () { copyLink(url, copy); };
link.appendChild(url);
link.appendChild(copy);
} else {
link.className = "hint";
link.textContent = entry.key
? "Deploy the web app (steps in SWIM > System > Settings) to get this link."
: "Click Save to get this calendar's link.";
}
addField(card, "Scheduling link", "Share this so members can book with this calendar.", link);
addField(card, "Calendar entry for availability",
"Members book times inside events with exactly this title (upper and lower case don't matter). " +
"People can share a calendar if each uses a different title; other events on a shared " +
"calendar block everyone who uses it.",
input("text", entry.availabilityTitle || "${DEFAULT_AVAILABILITY_TITLE}", "f-title"));
var types = document.createElement("div");
types.className = "types";
addField(card, "Appointment types", "Each type needs a name and a length in minutes. " +
"To keep the reason private on the calendar, end the name with the title to use " +
"there in parentheses, such as \\"Engage the process of repentance (Meeting with " +
"Bishop)\\". Members see the name without the parentheses.", types);
entry.types.forEach(function (t) { addTypeRow(types, t.label, t.minutes); });
if (!entry.types.length) addTypeRow(types, "", "");
var addRow = document.createElement("div");
addRow.className = "row";
var addType = document.createElement("button");
addType.textContent = "Add type";
addType.onclick = function () { addTypeRow(types, "", ""); changed(); };
addRow.appendChild(addType);
card.appendChild(addRow);
addField(card, "Appointment note", "Added to the description of every appointment. Optional.",
input("textarea", entry.note, "f-note"));
addField(card, "Appointment address", "Used as the location of every appointment. Optional.",
input("text", entry.address, "f-address"));
var email = addField(card, "Daily appointment email",
"Each morning at about 1 AM, this address gets a list of the next day's appointments " +
"on this calendar, with a button to text each person a reminder. Leave it blank to " +
"turn this off.", input("email", entry.reminderEmail, "f-email"));
email.spellcheck = false;
var removeRow = document.createElement("div");
removeRow.className = "row";
var remove = document.createElement("button");
remove.textContent = "Remove this calendar";
remove.onclick = function () {
if (document.querySelectorAll("#entries details.entry").length < 2) {
setStatus("saveStatus", "There must be at least one calendar.", "error");
return;
}
if (entry.key && !confirm("Remove \\"" + (entry.name || "this calendar") +
"\\"? Its scheduling link will stop working.")) return;
card.parentNode.removeChild(card);
changed();
};
removeRow.appendChild(remove);
card.appendChild(removeRow);
el("entries").appendChild(card);
}
// Returns the next slot length above (direction 1) or below (direction -1) minutes.
var SLOT_STEPS = ${JSON.stringify(SLOT_STEP_CHOICES)};
function stepSlotMinutes(minutes, direction) {
var n = Number(minutes) || 0;
var i;
if (direction > 0) {
for (i = 0; i < SLOT_STEPS.length; i++) if (SLOT_STEPS[i] > n) return SLOT_STEPS[i];
return SLOT_STEPS[SLOT_STEPS.length - 1];
}
for (i = SLOT_STEPS.length - 1; i >= 0; i--) if (SLOT_STEPS[i] < n) return SLOT_STEPS[i];
return SLOT_STEPS[0];
}
// Adds an editable appointment type row: name, minutes and a remove button.
function addTypeRow(container, label, minutes) {
var row = document.createElement("div");
row.className = "item type-row";
var name = document.createElement("input");
name.type = "text";
name.placeholder = "Name";
name.value = label;
name.className = "type-label";
name.oninput = changed;
var length = document.createElement("input");
length.type = "number";
length.min = "1";
length.placeholder = "Min";
length.value = minutes;
length.className = "type-minutes";
length.style.width = "64px";
// The arrow keys and spinner step through the slot lengths instead of by 1.
var last = length.value;
length.onkeydown = function (e) {
if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;
e.preventDefault();
length.value = stepSlotMinutes(length.value, e.key === "ArrowUp" ? 1 : -1);
last = length.value;
changed();
};
length.oninput = function (e) {
// Spinner clicks fire input without an inputType; typing has one.
if (!e.inputType && length.value !== "") {
length.value = stepSlotMinutes(last, Number(length.value) > Number(last || 0) ? 1 : -1);
}
last = length.value;
changed();
};
var remove = document.createElement("button");
remove.textContent = "\\u00d7";
remove.title = "Remove this type";
remove.onclick = function () {
row.parentNode.removeChild(row);
changed();
};
row.appendChild(name);
row.appendChild(length);
row.appendChild(remove);
container.appendChild(row);
}
function readEntries() {
return Array.prototype.map.call(document.querySelectorAll("#entries details.entry"),
function (card) {
function value(cls) { return card.querySelector("." + cls).value; }
return {
key: card.dataset.key,
name: value("f-name"),
calendarId: value("f-calendar"),
availabilityTitle: value("f-title"),
types: Array.prototype.map.call(card.querySelectorAll(".type-row"), function (row) {
return {
label: row.querySelector(".type-label").value,
minutes: row.querySelector(".type-minutes").value
};
}),
note: value("f-note"),
address: value("f-address"),
reminderEmail: value("f-email")
};
});
}
function save() {
setBusy(true);
setStatus("saveStatus", "Saving\\u2026");
google.script.run
.withSuccessHandler(function (view) {
setBusy(false);
render(view);
setStatus("saveStatus", "Saved.", "ok");
})
.withFailureHandler(function (error) {
setBusy(false);
setStatus("saveStatus", error.message, "error");
})
.saveCalendarSettings({ entries: readEntries() });
}
function sendNow() {
el("sendBtn").disabled = true;
setStatus("sendStatus", "Sending\\u2026");
google.script.run
.withSuccessHandler(function (message) {
updateSendButton();
setStatus("sendStatus", message, "ok");
})
.withFailureHandler(function (error) {
updateSendButton();
setStatus("sendStatus", error.message, "error");
})
.sendAppointmentRemindersNow();
}
// Loads the calendars. If that fails, shows why with a Try again
// button that runs this again.
function load() {
el("loadingText").textContent = "Loading calendars\\u2026";
el("loadingText").className = "";
el("retryRow").style.display = "none";
google.script.run
.withSuccessHandler(render)
.withFailureHandler(function (error) {
// Some failures (such as a dropped connection) come without a message.
var reason = (error && error.message) || String(error || "") || "unknown error";
if (reason === "undefined") reason = "unknown error";
el("loadingText").textContent = "Could not load the calendar settings: " + reason;
el("loadingText").className = "error";
el("retryRow").style.display = "flex";
})
.getCalendarView();
}
load();
</script>
`).setTitle("Calendar");
SpreadsheetApp.getUi().showSidebar(html);
}
// ---- Code.js -----------------------------------------------------------
/**
* Handles GET requests to the web app (the appointment pages).
* - Public: appointment-calendars (each one's key and name),
* appointment-types (also returns the calendar's name as ownerName),
* appointment-slots (type), owner-name, appointment-cancel-info (id),
* checkin-interviewers (who has an appointment around now).
* - With the code from a daily email's Text Reminders link ("code"):
* reminder-list (cal, day), that calendar's appointments that day.
* The appointment modes take "cal", the appointment calendar's key from
* its scheduling link; without it they use the first calendar.
* - With the owner or secretary key ("key"): latest-check-in, which names whoever
* checked in last (with "cal", to see that calendar's person or no one
* in particular), and listen-interviewers (who has appointments today).
* @param {Object} e - The event object for the GET request.
*/
function doGet(e) {
const params = (e && e.parameter) || {};
const mode = params.mode;
return appointmentResponse_(mode, () => {
switch (mode) {
case "appointment-calendars":
// Only the keys and names; calendar ids and emails stay private.
return { status: "success",
data: getAppointmentCalendars_().map(entry => ({ key: entry.key, name: entry.name })) };
case "appointment-types": {
const entry = getCalendarEntry_(params.cal);
return { status: "success", data: getAppointmentTypes(entry),
ownerName: entry.name, calendarKey: entry.key };
}
case "appointment-slots":
return { status: "success",
data: getAvailableSlots(getCalendarEntry_(params.cal), params.type) };
case "owner-name":
return { status: "success", data: getSettings().ownerName };
case "checkin-interviewers":
return { status: "success", data: getCheckInInterviewers() };
case "appointment-cancel-info":
return getAppointmentForCancel(params.cal, params.id);
case "reminder-list":
return getReminderList(params.cal, params.day, params.code);
case "latest-check-in":
case "listen-interviewers":
if (!isOwnerKey_(params.key) && !isSecretaryKey_(params.key)) {
return { status: "error", message: notAuthorizedMessage_(params.key,
"the Listen for Check-Ins link under Appointments") };
}
return { status: "success", data: mode === "latest-check-in"
? getLatestCheckIn(params.cal) : getTodaysInterviewers() };
default:
return { status: "error", message: "Unrecognized Mode: " + mode };
}
});
}
/**
* Handles POST requests to the web app.
* Accepts "mode" as a form/query parameter or in a JSON request body (sent
* as application/json, or as text/plain to avoid a CORS preflight).
*
* The Deployment ID may be public, so it grants nothing by itself. Every mode
* is authorized here, before it runs:
* - Public, for the appointment pages: book-appointment, cancel-appointment
* (id), each with the appointment calendar's "cal" key; check-in (name,
* and "cal" for who they're here to see).
* - With the owner key ("key", from the links in SWIM > Links):
* get-message-list, record-message-sent (messageid), get-notes (memberid;
* includes notes from every SWIM in grantedNoteAccess).
* - With the secretary key ("key"): get-message-list, record-message-sent.
* - With a reader code ("readerCode", see ReaderAccess.js): get-notes
* (memberid; this sheet's own notes only).
* - Checked by the mode itself against a request token or reader code:
* describe-notes-request, accept-notes-access, release-notes-access.
* @param {Object} e - The event object for the POST request.
*/
function doPost(e) {
try {
const params = Object.assign({}, e && e.parameter);
const postType = String((e && e.postData && e.postData.type) || "");
if (/^(application\/json|text\/plain)/.test(postType)) {
Object.assign(params, JSON.parse(e.postData.contents));
}
const mode = params.mode;
if (mode === "book-appointment") {
return appointmentResponse_(mode, () => bookAppointment(getCalendarEntry_(params.cal), params));
}
if (mode === "cancel-appointment") {
return appointmentResponse_(mode, () => cancelAppointment(params.cal, params.id));
}
if (mode === "check-in") {
return appointmentResponse_(mode, () => checkIn(params.name, params.cal));
}
if (mode === "describe-notes-request") {
return jsonResponse(describeNotesRequest_(params));
}
if (mode === "accept-notes-access") {
return jsonResponse(acceptNotesAccess_(params));
}
if (mode === "release-notes-access") {
return jsonResponse(releaseNotesAccess_(params));
}
const isOwner = isOwnerKey_(params.key);
if (mode === "get-notes" && !isOwner && params.readerCode) {
return jsonResponse(getNotesForReader_(params));
}
const isMessageMode = mode === "get-message-list" || mode === "record-message-sent";
if (!isOwner && !(isMessageMode && isSecretaryKey_(params.key))) {
const link = isMessageMode
? "the Send Messages link under Messages"
: mode === "get-notes" ? "the View Notes link under Notes" : "the links";
return jsonResponse({
success: false,
error: notAuthorizedMessage_(params.key, link),
});
}
if (mode === "get-message-list") {
return jsonResponse(getMessageList());
}
if (mode === "record-message-sent") {
return jsonResponse(recordMessageSent(params.messageid));
}
if (mode === "get-notes") {
return jsonResponse(getAllNotes_(params.memberid));
}
return jsonResponse({ success: false, error: "Unknown mode: " + mode });
} catch (error) {
return jsonResponse({ success: false, error: error.toString() });
}
}
/**
* Reads the contiguous block of data starting at A1 on the "messagesToSend"
* sheet and converts it to an array of objects keyed by the header row.
*/
function getMessageList() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("messagesToSend");
if (!sheet) {
throw new Error('Sheet "messagesToSend" not found');
}
return rowsToObjects(sheet.getRange("A1").getDataRegion().getValues());
}
/**
* Returns every row on the notes ingest sheet whose Member Id matches
* memberId, as an array of objects keyed by the header row, followed by the
* member's sent messages from "messagesSent" in the same shape.
* @param {string} memberId - The Member Id to match.
*/
function getNotes(memberId) {
if (memberId === undefined || memberId === null || String(memberId).trim() === "") {
return { success: false, error: "Missing memberid parameter" };
}
const sheetName = NOTES_INGEST_FORM.name;
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (!sheet) {
throw new Error('Sheet "' + sheetName + '" not found');
}
const values = sheet.getDataRange().getValues();
const headers = values[0];
const col = headers.indexOf(NOTES_MEMBER_ID_FIELD);
if (col === -1) {
throw new Error('Column "' + NOTES_MEMBER_ID_FIELD + '" not found on "' + sheetName + '"');
}
const id = String(memberId).trim();
const matches = values.slice(1).filter(row => String(row[col]).trim() === id);
return rowsToObjects([headers].concat(matches)).concat(getSentMessagesAsNotes(id));
}
/**
* Maps note fields (as returned by getNotes) to the "messagesSent" columns
* they are read from.
*/
const SENT_MESSAGE_NOTE_SOURCES = {
"Timestamp": "Time Sent",
"Member Id": "MemberId",
"Name": "Member Name",
"Phone": "Phone",
"Interviewer": "Sent By",
"Message Title": "Title",
"Message": "Message",
};
/**
* Returns the rows on "messagesSent" whose MemberId matches memberId,
* reshaped into note objects keyed like the "Ingest Notes" sheet, each with
* "Kind": "message" so the notes page can tell them from recorded notes.
* @param {string} memberId - The trimmed Member Id to match.
*/
function getSentMessagesAsNotes(memberId) {
const sheetName = "messagesSent";
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (!sheet) {
throw new Error('Sheet "' + sheetName + '" not found');
}
const values = sheet.getDataRange().getValues();
const headers = values[0];
const memberCol = headers.indexOf(SENT_MESSAGE_NOTE_SOURCES[NOTES_MEMBER_ID_FIELD]);
if (memberCol === -1) {
throw new Error('Column "' + SENT_MESSAGE_NOTE_SOURCES[NOTES_MEMBER_ID_FIELD] +
'" not found on "' + sheetName + '"');
}
const fieldCols = Object.keys(SENT_MESSAGE_NOTE_SOURCES).map(field =>
[field, headers.indexOf(SENT_MESSAGE_NOTE_SOURCES[field])]);
return values.slice(1)
.filter(row => String(row[memberCol]).trim() === memberId)
.map(row => {
const note = { "Kind": "message" };
fieldCols.forEach(([field, col]) => {
note[field] = col === -1 ? "" : row[col];
});
return note;
});
}
/**
* Converts a 2-D array whose first row is headers into an array of objects
* keyed by those headers.
* @param {Array<Array>} values - Header row followed by data rows.
*/
function rowsToObjects(values) {
const headers = values[0];
return values.slice(1).map(row => {
const entry = {};
headers.forEach((header, i) => {
entry[header] = row[i];
});
return entry;
});
}
const SENT_VIA_COLUMN = 10; // Column J of "messagesSent".
const SENT_VIA_SMS = "SMS";
const SENT_VIA_EMAIL = "Email";
/**
* Moves the row whose column A matches messageId from "messagesToSend" to
* "messagesSent", stamping the current date/time in the "Time Sent" column
* and how it was sent in column J (SENT_VIA_COLUMN).
* @param {string} messageId - The value to match in column A.
* @param {string} [sentVia="SMS"] - How the message was sent: SENT_VIA_SMS or
* SENT_VIA_EMAIL. Only the email procedure sends by email.
* @return {Object} { success: true, messageid, timeSent } on success, or
* { success: false, messageid, error } describing what failed.
*/
function recordMessageSent(messageId, sentVia = SENT_VIA_SMS) {
const fail = error => ({ success: false, messageid: messageId, error: error });
if (messageId === undefined || messageId === null || messageId === "") {
return fail("Missing messageid parameter");
}
const lock = LockService.getScriptLock();
if (!lock.tryLock(10000)) {
return fail("Timed out waiting for another request to finish; try again");
}
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const toSend = ss.getSheetByName("messagesToSend");
const sent = ss.getSheetByName("messagesSent");
if (!toSend) return fail('Sheet "messagesToSend" not found');
if (!sent) return fail('Sheet "messagesSent" not found');
const values = toSend.getDataRange().getValues();
const rowIndex = values.findIndex(
(row, i) => i > 0 && String(row[0]) === String(messageId)
);
if (rowIndex === -1) {
return fail('No row with messageid "' + messageId + '" found on "messagesToSend"');
}
const sentHeaders = sent.getRange(1, 1, 1, sent.getLastColumn()).getValues()[0];
const timeSentCol = sentHeaders.indexOf("Time Sent");
if (timeSentCol === -1) {
return fail('Column "Time Sent" not found on "messagesSent"');
}
if (timeSentCol === SENT_VIA_COLUMN - 1) {
return fail('Column "Time Sent" is in column J of "messagesSent", where the sent-via ' +
"value goes; move one of them");
}
const timeSent = new Date();
const newRow = values[rowIndex].slice();
while (newRow.length < Math.max(sentHeaders.length, SENT_VIA_COLUMN)) newRow.push("");
newRow[timeSentCol] = timeSent;
newRow[SENT_VIA_COLUMN - 1] = sentVia;
try {
sent.appendRow(newRow);
} catch (error) {
return fail('Could not add row to "messagesSent": ' + error.message);
}
try {
toSend.deleteRow(rowIndex + 1);
} catch (error) {
// Undo the append so the message isn't recorded in both sheets.
try {
sent.deleteRow(sent.getLastRow());
} catch (undoError) {
return fail('Row was added to "messagesSent" but could not be removed from ' +
'"messagesToSend" (' + error.message + '), and undoing the add also failed (' +
undoError.message + '); the message is now on both sheets');
}
return fail('Could not remove row from "messagesToSend": ' + error.message +
'; no changes were made');
}
return { success: true, messageid: messageId, timeSent: timeSent.toISOString() };
} catch (error) {
return fail("Unexpected error: " + error.message);
} finally {
lock.releaseLock();
}
}
/**
* Maps "messagesToSend" columns to the "Ingest Messages" form response
* columns they are copied from. Columns not listed are copied from a response
* column with the same name, if any.
*/
const MESSAGE_COLUMN_SOURCES = {
"Member Name": "Name",
"Title": "Message Title",
};
/**
* Installable form-submit trigger: appends each "Ingest Messages" response to
* "messagesToSend" with a newly generated MessageId. Responses from other
* forms linked to the spreadsheet (such as "Ingest Notes") are ignored.
* @param {Object} e - The form submit event.
*/
function onFormSubmit(e) {
if (!e || !e.range || !e.namedValues) {
throw new Error("onFormSubmit must be run by a form submit trigger");
}
if (e.range.getSheet().getName() !== MESSAGE_INGEST_FORM.name) return;
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
// Column A of the response row is the form's Timestamp, as a Date.
const timestamp = e.range.getValues()[0][0];
const timeLogged = timestamp instanceof Date ? timestamp : new Date();
queueMessage_(SpreadsheetApp.getActiveSpreadsheet(), column => {
const values = e.namedValues[MESSAGE_COLUMN_SOURCES[column] || column];
return values ? String(values[0]).trim() : "";
}, timeLogged);
} finally {
lock.releaseLock();
}
}
/**
* Appends one message to "messagesToSend" with a newly generated MessageId.
* The caller must hold the script lock.
* @param {Spreadsheet} ss - The spreadsheet.
* @param {function(string): string} valueFor - Returns the value for a
* "messagesToSend" column, given its header.
* @param {Date=} timeLogged - The "Time Logged" value; defaults to now.
* @return {string} The new MessageId.
*/
function queueMessage_(ss, valueFor, timeLogged) {
return queueMessages_(ss, [valueFor], timeLogged)[0];
}
/**
* Appends several messages to "messagesToSend" in a single write, each with a
* newly generated MessageId. The caller must hold the script lock.
* @param {Spreadsheet} ss - The spreadsheet.
* @param {Array<function(string): string>} valueFors - One per message;
* each returns the value for a "messagesToSend" column, given its header.
* @param {Date=} timeLogged - The "Time Logged" value; defaults to now.
* @return {Array<string>} The new MessageIds, in order.
*/
function queueMessages_(ss, valueFors, timeLogged) {
const toSend = ss.getSheetByName("messagesToSend");
if (!toSend) {
throw new Error('Sheet "messagesToSend" not found');
}
if (!valueFors.length) return [];
const headers = toSend.getRange(1, 1, 1, toSend.getLastColumn()).getValues()[0];
const used = usedMessageIds_(ss);
const logged = timeLogged || new Date();
const messageIds = [];
const rows = valueFors.map(valueFor => {
const messageId = newMessageId_(used);
used.add(messageId);
messageIds.push(messageId);
return headers.map(header => {
if (header === "MessageId") return messageId;
if (header === "Time Logged") return logged;
return valueFor(header);
});
});
const firstRow = toSend.getLastRow() + 1;
const lastRow = firstRow + rows.length - 1;
if (lastRow > toSend.getMaxRows()) {
toSend.insertRowsAfter(toSend.getMaxRows(), lastRow - toSend.getMaxRows());
}
toSend.getRange(firstRow, 1, rows.length, headers.length).setValues(rows);
return messageIds;
}
/**
* Returns a 4-character MessageId (a letter followed by three letters or
* digits) not already used on "messagesToSend" or "messagesSent".
* @param {Spreadsheet} ss - The spreadsheet.
*/
function generateMessageId(ss) {
return newMessageId_(usedMessageIds_(ss));
}
/**
* Returns the set of (upper-cased) MessageIds on "messagesToSend" and
* "messagesSent".
* @param {Spreadsheet} ss - The spreadsheet.
* @return {Set<string>}
*/
function usedMessageIds_(ss) {
const used = new Set();
["messagesToSend", "messagesSent"].forEach(name => {
const sheet = ss.getSheetByName(name);
if (sheet && sheet.getLastRow() > 1) {
sheet.getRange(2, 1, sheet.getLastRow() - 1, 1).getValues()
.forEach(row => used.add(String(row[0]).toUpperCase()));
}
});
return used;
}
/**
* Returns a random 4-character MessageId not in used.
* @param {Set<string>} used - MessageIds already taken.
*/
function newMessageId_(used) {
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const chars = letters + "0123456789";
const pick = set => set.charAt(Math.floor(Math.random() * set.length));
for (let attempt = 0; attempt < 1000; attempt++) {
const id = pick(letters) + pick(chars) + pick(chars) + pick(chars);
if (!used.has(id)) return id;
}
throw new Error("Could not generate a unique MessageId");
}
/**
* Confirms with the user, then emails every message in the "messagesToSend"
* queue one at a time (via getEmailQueue and emailQueuedMessage), listing
* each recipient as it goes with the most recent at the top.
*/
function showProcessMessagesByEmail() {
const html = HtmlService.createHtmlOutput(`
<style>
body { font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5; }
#progress { height: 180px; overflow-y: auto; border: 1px solid #ccc;
border-radius: 4px; padding: 4px 8px; margin-top: 8px; }
#progress div { padding: 2px 0; border-bottom: 1px solid #eee; }
.sending { color: #555; }
.sent { color: #137333; }
.skipped { color: #b06000; }
.failed { color: #c5221f; }
</style>
<div id="confirm">
<p>You are about to email the messages in the Send Messages Queue (the
"messagesToSend" sheet). Each message will be emailed to its member and then
moved to the "messagesSent" sheet.</p>
<p>Messages without an email address will be left in the queue.</p>
<div style="text-align: right; margin-top: 16px;">
<button onclick="google.script.host.close()">Cancel</button>
<button onclick="start()">Continue</button>
</div>
</div>
<div id="run" style="display: none;">
<div id="status">Getting the queue…</div>
<div id="progress"></div>
<div style="text-align: right; margin-top: 12px;">
<button id="close" disabled onclick="google.script.host.close()">Close</button>
</div>
</div>
<script>
var queue = [];
var index = 0;
var counts = { sent: 0, skipped: 0, failed: 0 };
function start() {
document.getElementById("confirm").style.display = "none";
document.getElementById("run").style.display = "block";
google.script.run
.withSuccessHandler(function (items) {
queue = items;
next();
})
.withFailureHandler(function (error) {
finish("Error: " + error.message);
})
.getEmailQueue();
}
// Adds a line to the top of the progress list and returns it.
function addLine(text, cls) {
var line = document.createElement("div");
line.textContent = text;
line.className = cls;
var list = document.getElementById("progress");
list.insertBefore(line, list.firstChild);
list.scrollTop = 0;
return line;
}
function next() {
if (index >= queue.length) {
finish(queue.length === 0
? "There were no messages in the queue."
: "Done. Emailed " + counts.sent + " of " + queue.length + " message" +
(queue.length === 1 ? "" : "s") +
(counts.skipped ? ", " + counts.skipped + " left in the queue" : "") +
(counts.failed ? ", " + counts.failed + " with problems" : "") + ".");
return;
}
var item = queue[index++];
document.getElementById("status").textContent =
"Sending " + index + " of " + queue.length + "…";
var line = addLine("Sending to " + item.name + "…", "sending");
google.script.run
.withSuccessHandler(function (result) {
counts[result.status]++;
line.className = result.status;
line.textContent = item.name + " — " + result.detail;
next();
})
.withFailureHandler(function (error) {
counts.failed++;
line.className = "failed";
line.textContent = item.name + " — " + error.message;
next();
})
.emailQueuedMessage(item.id);
}
function finish(text) {
document.getElementById("status").textContent = text;
document.getElementById("close").disabled = false;
}
</script>
`).setWidth(460).setHeight(340);
SpreadsheetApp.getUi().showModalDialog(html, "Process Messages by Email");
}
/**
* Returns the messages currently queued on "messagesToSend" as
* [{ id, name }], in sheet order, for the email progress dialog.
*/
function getEmailQueue() {
return getMessageList().map(message => ({
id: String(message["MessageId"]),
name: String(message["Member Name"] || "unknown member"),
}));
}
/**
* Emails one queued message (To: Email, Subject: Title, Body: Message,
* sender name: Sent By) and moves it to "messagesSent" with
* recordMessageSent. A message without an email address, or that fails to
* send, stays in the queue.
* @param {string} messageId - The MessageId to send.
* @return {{status: string, detail: string}} status is "sent", "skipped" or
* "failed"; detail describes what happened.
*/
function emailQueuedMessage(messageId) {
const message = getMessageList().find(m => String(m["MessageId"]) === String(messageId));
if (!message) {
return { status: "skipped", detail: "no longer in the queue" };
}
const email = String(message["Email"] || "").trim();
if (!email) {
return { status: "skipped", detail: "no email address; left in the queue" };
}
if (MailApp.getRemainingDailyQuota() < 1) {
return { status: "skipped", detail: "daily email quota reached; left in the queue" };
}
try {
MailApp.sendEmail({
to: email,
subject: String(message["Title"] || ""),
body: String(message["Message"] || ""),
name: String(message["Sent By"] || "") || undefined,
});
} catch (error) {
return { status: "failed", detail: "could not send email (" + error.message + ")" };
}
const result = recordMessageSent(messageId, SENT_VIA_EMAIL);
if (!result.success) {
return {
status: "failed",
detail: "emailed, but not moved to messagesSent (" + result.error + ")",
};
}
return { status: "sent", detail: "sent to " + email };
}
function jsonResponse(data) {
return ContentService
.createTextOutput(JSON.stringify(data))
.setMimeType(ContentService.MimeType.JSON);
}
/**
* Receives data from the mobile form and appends it to the Google Sheet.
* @param {Object} formData - The data object sent from the browser.
*/
function recordRequest(formData) {
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Log") || ss.getSheets()[0];
// Append Timestamp, Name, and Notes to the next available row
sheet.appendRow([
new Date(),
formData.userName,
"SMS Generated"
]);
return { success: true };
} catch(error) {
return { success: false, message: error.toString() };
}
}
const PAGES_BASE_URL = "https://tools.ysaward.org/p/";
const DIRECTORY_URL = "https://directory.churchofjesuschrist.org";
const EXTENSION_URL ="https://chromewebstore.google.com/detail/ward-photo-directory/fnpmhjiejafbihlececcklglpadhpipk";
/**
* Ingestion forms the SMS menu can build. Each form's responses land on a
* sheet with the same name. ownerField is prefilled with the sheet owner's
* name; every other question is prefilled with its own title. linkSetting is
* the SETTINGS key (see Settings.js) the prefilled link is saved under. key
* names the form to the Setup dialog, which shows label in its progress log.
*/
const MESSAGE_INGEST_FORM = {
key: "messages",
label: "messages",
name: "Ingest Messages",
textFields: ["MemberId", "Name", "Phone", "Email", "Sent By", "Message Title"],
paragraphFields: ["Message"],
ownerField: "Sent By",
linkSetting: "MESSAGE_FORM_LINK",
purpose: "messages to be brought into this sheet and queued for sending",
};
const NOTES_MEMBER_ID_FIELD = "Member Id";
const NOTES_INGEST_FORM = {
key: "notes",
label: "notes",
name: "Ingest Notes",
textFields: [NOTES_MEMBER_ID_FIELD, "Name", "Phone", "Interviewer", "Message Title"],
paragraphFields: ["Message"],
ownerField: "Interviewer",
linkSetting: "NOTES_FORM_LINK",
purpose: "interview notes to be brought into this sheet",
};
const INGEST_FORMS = [MESSAGE_INGEST_FORM, NOTES_INGEST_FORM];
const SYSTEM_SETUP_TITLE = "Setup";
const SETUP_GUIDE_URL = "https://tools.ysaward.org/2000/10/setup.html";
const FIRST_NOTE_GUIDE_URL = "https://tools.ysaward.org/2000/10/first-note.html";
const FEEDBACK_FORM_URL = "https://docs.google.com/forms/d/e/1FAIpQLSeqJsabLHFTe879ZTeoqdRFkPlMZ248EMXcNrRlv6hRSMdhNA/viewform";
const MANUAL_URL = "https://tools.ysaward.org/2000/10/manual.html";
/**
* Adds the SWIM menu when the spreadsheet is opened.
*/
function onOpen() {
resetSettingsIfCopied_();
try {
keepLandingSheetFirst_(SpreadsheetApp.getActiveSpreadsheet());
} catch (error) {
console.warn("Could not move the landing sheet first: " + error.message);
}
// A new template offers only Initialize and share until that has run.
if (isPendingTemplate_()) {
SpreadsheetApp.getUi().createMenu("SWIM Template")
.addItem("Initialize and share", "initializeTemplateFromMenu")
.addToUi();
try {
showInitializeTemplateDialog();
} catch (error) {
// Not allowed before this copy is authorized; the menu above still works.
}
return;
}
addSwimMenu_();
}
/**
* True once System Setup has built both ingest forms (their links are saved).
*/
function isSystemSetUp_() {
try {
const settings = getSettings();
return Boolean(settings.messageFormLink && settings.notesFormLink);
} catch (error) {
// Settings can't be read (such as before authorization); don't hide the menu.
console.warn("Could not read settings: " + error.message);
return true;
}
}
/**
* Adds (or replaces) the SWIM menu. Until System Setup has been run, it
* offers only System > Setup and System > About.
*/
function addSwimMenu_() {
const ui = SpreadsheetApp.getUi();
if (!isSystemSetUp_()) {
ui.createMenu("SWIM")
.addSubMenu(ui.createMenu("System")
.addItem(SYSTEM_SETUP_TITLE, "systemSetup")
.addItem("About", "showAbout"))
.addToUi();
return;
}
ui.createMenu("SWIM")
.addItem("Links", "showLinks")
.addItem("Calendar", "showCalendar")
.addItem("Compose Messages", "showComposeMessages")
.addItem("Process Messages by Email", "showProcessMessagesByEmail")
.addItem("Generate list of most recent contacts", "showMostRecentContacts")
.addSubMenu(ui.createMenu(READER_ACCESS_TITLE)
.addItem("Request Notes Access", "requestNotesAccess")
.addItem("Grant Notes Access", "showGrantNotesAccess")
.addItem("Revoke Notes Access", "showRevokeNotesAccess"))
.addSubMenu(ui.createMenu("System")
.addItem("Settings", "showSettings")
.addItem(SYSTEM_SETUP_TITLE, "systemSetup")
.addItem(CHECK_FOR_UPDATES_TITLE, "checkForUpdates")
.addItem("About", "showAbout"))
.addItem("Help", "showHelp")
.addItem("Feedback", "showFeedback")
.addToUi();
}
/**
* SWIM > Help. Opens the SWIM manual in a new tab.
*/
function showHelp() {
openUrlInNewTab_(MANUAL_URL, "the manual", "Help");
}
/**
* SWIM > Feedback. Opens the feedback form in a new tab.
*/
function showFeedback() {
openUrlInNewTab_(FEEDBACK_FORM_URL, "the feedback form", "Feedback");
}
/**
* Menu items can't open URLs directly, so this shows a small dialog that opens
* the URL in a new tab and closes itself. If the browser blocks the pop-up,
* the dialog stays open with a link to click.
*/
function openUrlInNewTab_(url, description, title) {
const html = HtmlService.createHtmlOutput(
'<div style="font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5;">' +
'<p>Opening ' + description + '… If it didn\'t open, ' +
'<a href="' + url + '" target="_blank" ' +
'onclick="setTimeout(function () { google.script.host.close(); }, 100)">' +
'click here</a>.</p>' +
'</div>' +
'<script>' +
'if (window.open(' + JSON.stringify(url) + ', "_blank")) {' +
'google.script.host.close();' +
'}' +
'</script>'
).setWidth(320).setHeight(90);
SpreadsheetApp.getUi().showModalDialog(html, title);
}
/**
* Shows a dialog describing what this spreadsheet is for.
*/
function showAbout() {
const html = HtmlService.createHtmlOutput(
'<div style="font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5;">' +
'<p>This spreadsheet is meant to work with the ' +
'<a href="' + EXTENSION_URL + '" target="_blank">Ward Photo Directory</a> ' +
'Chrome extension.</p>' +
'<p>It holds a queued list of messages so they can be easily sent as text ' +
'messages from a phone.</p>' +
'<p style="color: #555;">Version: ' +
(currentReleaseVersion_() ||
(isDevelopmentCopy_() ? "development copy" : "unknown (use Check for Updates)")) +
'</p>' +
'<div style="text-align: right; margin-top: 16px;">' +
'<button onclick="window.open(\'https://tools.ysaward.org\', \'_blank\')">' +
'More information</button> ' +
'<button onclick="google.script.host.close()">Close</button>' +
'</div>' +
'</div>'
).setWidth(400).setHeight(230);
SpreadsheetApp.getUi().showModalDialog(html, "About");
}
/**
* SWIM > System > Setup. Opens a dialog that stays open for the whole setup:
* it points to the Setup guide, asks for the owner's name and whether to
* rebuild any existing form that holds data, then builds both ingest forms
* (messages and notes) one at a time, logging progress as it goes. Then it
* asks for the web app Deployment ID, has the user copy the message templates
* into the Ward Photo Directory extension, and ends with a large "complete"
* message.
*
* The dialog asks every question itself: an alert or prompt shown from the
* server while it is open would replace it.
*/
function systemSetup() {
const html = HtmlService.createHtmlOutput(`
<style>
body { font-family: Arial, sans-serif; font-size: 13px; line-height: 1.4;
color: #202124; margin: 0; padding: 4px 12px 12px; overflow-x: hidden; }
h3 { font-size: 13px; margin: 16px 0 2px; }
.hint { color: #5f6368; font-size: 12px; margin: 2px 0 6px; }
input[type=text] { width: 100%; box-sizing: border-box; font: inherit; padding: 4px 6px; }
.row { display: flex; justify-content: flex-end; align-items: center; gap: 8px;
margin-top: 8px; }
.status { font-size: 12px; flex: 1; }
.ok { color: #137333; }
.error { color: #c5221f; }
.guide { border: 1px solid #f9d77e; background: #fef7e0; border-radius: 4px;
padding: 8px 10px; }
.steps { border: 1px solid #d2e3fc; background: #e8f0fe; border-radius: 4px;
padding: 6px 8px; margin-top: 6px; font-size: 12px; }
.steps li { margin-bottom: 3px; }
.notice { border: 1px solid #f3c7c4; background: #fce8e6; border-radius: 4px;
padding: 6px 8px; margin-top: 6px; font-size: 12px; }
ol { padding-left: 18px; margin: 6px 0; }
ul { padding-left: 18px; margin: 4px 0; }
#log { list-style: none; padding: 0; }
#log li { padding: 2px 0; }
#log .result { margin-left: 6px; }
label.check { display: flex; gap: 6px; align-items: flex-start; }
button.primary { background: #1a73e8; color: #fff; border: 1px solid #1a73e8;
border-radius: 4px; padding: 6px 12px; font: inherit; font-weight: bold;
cursor: pointer; }
button.primary:disabled { opacity: 0.6; cursor: default; }
#complete { text-align: center; padding: 40px 12px 12px; }
#complete .badge { width: 120px; height: 120px; margin: 0 auto; border-radius: 50%;
background: #137333; color: #fff; font-size: 76px; line-height: 120px;
animation: pop 0.6s ease-out; }
#complete h1 { font-size: 30px; color: #137333; margin: 24px 0 8px; }
#complete .lead { font-size: 17px; line-height: 1.5; margin: 0 auto 20px;
max-width: 440px; }
#complete .hint { max-width: 400px; margin: 0 auto 20px; }
@keyframes pop { 0% { transform: scale(0); } 70% { transform: scale(1.15); }
100% { transform: scale(1); } }
.confetti { position: fixed; top: -12px; width: 8px; height: 14px; opacity: 0.9;
pointer-events: none; animation: fall linear forwards; }
@keyframes fall { to { transform: translateY(680px) rotate(720deg); opacity: 0.6; } }
[hidden] { display: none !important; }
</style>
<div id="loading">Loading…</div>
<div id="welcome" hidden>
<div class="guide">
<b>Please follow along with the Setup guide.</b> We strongly recommend opening
it now and following it step by step as you set up SWIM. It shows each screen
you will see.
<div class="row"><button id="guideBtn">Open the Setup guide</button></div>
</div>
<p>Setup will build two Google Forms:</p>
<ul id="formList"></ul>
<h3>Your name</h3>
<div class="hint">Used as "Sent By" on messages and "Interviewer" on notes.</div>
<input type="text" id="ownerName">
<div id="existing"></div>
<div class="row">
<span id="startStatus" class="status"></span>
<button onclick="google.script.host.close()">Cancel</button>
<button id="startBtn" onclick="start()">Start setup</button>
</div>
</div>
<div id="progress" hidden>
<h3>Progress</h3>
<ul id="log"></ul>
</div>
<div id="deploy" hidden>
<h3>Web app Deployment ID</h3>
<div class="hint">Your page links (SWIM > Links) are built from it.</div>
<div class="steps">
<b>Deploy your web app (one time, about 2 minutes)</b>
${DEPLOY_STEPS_HTML}
<div class="hint">Pasting the Web app URL instead works too.</div>
</div>
<input type="text" id="deploymentId" spellcheck="false" style="margin-top: 8px;"
placeholder="Paste the Deployment ID here">
<div class="row">
<span id="deployStatus" class="status"></span>
<button onclick="skipDeployment()">Skip for now</button>
<button id="deployBtn" class="primary" onclick="saveDeployment()">Save</button>
</div>
</div>
<div id="extension" hidden>
<h3>Ward Photo Directory Chrome extension</h3>
<div class="hint">You record notes and send messages from the extension.</div>
<div class="steps">
<ol>
<li><a href="${EXTENSION_URL}" target="_blank">Open the Ward Photo Directory
extension in the Chrome Web Store</a>.</li>
<li>Click <b>Add to Chrome</b>.</li>
<li>Come back here and click <b>I've installed it</b>.</li>
</ol>
</div>
<div class="hint">Already installed it? Click <b>I've installed it</b> now.</div>
<div class="row">
<button class="primary" onclick="extensionInstalled()">I've installed it</button>
</div>
</div>
<div id="templates" hidden>
<h3>Message templates</h3>
<div class="hint">SWIM comes with a set of starter message and note templates. Add
them to the Ward Photo Directory Chrome extension so you can use them there.</div>
<div class="steps">
<ol>
<li>Click <b>Copy templates</b> below.</li>
<li><a href="${DIRECTORY_URL}" target="_blank">Open your ward directory</a>, log
in, then click the Ward Photo Directory extension icon in Chrome's toolbar.</li>
<li>In the Ward Photo Directory extension, choose <b>Menu → Instructions
& Tools → Messages → Paste Messages</b>, and paste the
templates.</li>
<li>Come back here and click <b>I've added the templates</b>.</li>
</ol>
</div>
<div class="hint">You can change these templates at any time in SWIM > Compose
Messages, then click <b>Copy templates for extension</b> there to export them to
the extension again.</div>
<div id="noIdNote" class="notice" hidden>Without a Deployment ID, templates that
include your schedule link will have it left blank. After you add the ID in
SWIM > System > Settings, export the templates again.</div>
<div class="row">
<span id="copyStatus" class="status"></span>
<button id="copyBtn" onclick="copyTemplates()">Copy templates</button>
<button id="templatesDoneBtn" class="primary" onclick="complete()">I've added the
templates</button>
</div>
</div>
<div id="complete" hidden>
<div class="badge">✓</div>
<h1>Basic configuration is complete!</h1>
<p class="lead">You're ready to record notes and send messages using the Ward Photo
Directory Chrome extension.</p>
<p class="lead"><a href="${FIRST_NOTE_GUIDE_URL}" target="_blank">Next: Recording and
viewing my first note →</a></p>
<p id="completeNote" class="hint" hidden>You skipped the web app Deployment ID. Add it
in SWIM > System > Settings to turn on your page links.</p>
<button class="primary" onclick="google.script.host.close()">Done</button>
</div>
<div id="closeRow" class="row" hidden>
<span id="closeHint" class="status hint"></span>
<button id="closeBtn" onclick="google.script.host.close()">Close</button>
</div>
<script>
var state = null;
function el(id) { return document.getElementById(id); }
function show(id, visible) { el(id).hidden = !visible; }
function setStatus(id, text, cls) {
el(id).textContent = text;
el(id).className = "status " + (cls || "");
}
// Runs a server function and returns a Promise of its result.
function call(name, args) {
return new Promise(function (resolve, reject) {
var runner = google.script.run.withSuccessHandler(resolve).withFailureHandler(reject);
runner[name].apply(runner, args || []);
});
}
// Adds a line to the progress log and returns the span for its result.
function addLine(text) {
var line = document.createElement("li");
var label = document.createElement("span");
label.textContent = text;
var result = document.createElement("span");
result.className = "result";
line.appendChild(label);
line.appendChild(result);
el("log").appendChild(line);
return result;
}
// Adds a line to the progress log, runs a server function, then shows
// describe(result) (or "Done.") next to the line, or the error.
function step(text, name, args, describe) {
var result = addLine(text);
return call(name, args).then(function (value) {
result.textContent = "\\u2713 " + (describe ? describe(value) : "Done.");
result.className = "result ok";
return value;
}, function (error) {
result.textContent = error.message;
result.className = "result error";
throw error;
});
}
function render(view) {
state = view;
show("loading", false);
show("welcome", true);
el("guideBtn").onclick = function () { window.open(view.guideUrl, "_blank"); };
el("ownerName").value = view.ownerName;
el("deploymentId").value = view.deploymentId;
Array.prototype.forEach.call(document.querySelectorAll(".editorLink"), function (a) {
a.href = view.scriptEditorUrl;
});
view.forms.forEach(function (form) {
var item = document.createElement("li");
item.textContent = '"' + form.name + '": allows ' + form.purpose + ".";
el("formList").appendChild(item);
if (!form.exists) return;
var box = document.createElement("div");
box.className = "notice";
if (form.dataRows > 0) {
var label = document.createElement("label");
label.className = "check";
var check = document.createElement("input");
check.type = "checkbox";
check.id = "rebuild-" + form.key;
var text = document.createElement("span");
text.innerHTML = '<b>"' + escapeHtml(form.name) + '" already exists.</b> ' +
"Delete it and build it again? Leave this unchecked to keep it. " +
"<b>Warning:</b> its " + form.dataRows + " row" +
(form.dataRows === 1 ? "" : "s") + " of data will be permanently deleted.";
label.appendChild(check);
label.appendChild(text);
box.appendChild(label);
} else {
box.textContent = '"' + form.name + '" already exists but holds no data, ' +
"so it will be deleted and built again.";
}
el("existing").appendChild(box);
});
el("ownerName").focus();
}
function escapeHtml(text) {
var div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
function start() {
var name = el("ownerName").value.trim();
if (!name) {
setStatus("startStatus", "Please enter your name.", "error");
el("ownerName").focus();
return;
}
show("welcome", false);
show("progress", true);
var chain = step("Saving your name\\u2026", "saveSetupOwnerName", [name]);
state.forms.forEach(function (form) {
var check = el("rebuild-" + form.key);
var rebuild = !check || check.checked;
chain = chain.then(function () {
var text = form.exists && rebuild
? "Removing the old form and building the form to ingest " + form.label + "\\u2026"
: form.exists
? "Keeping the form to ingest " + form.label + "\\u2026"
: "Building form to ingest " + form.label + "\\u2026";
return step(text, "setupIngestForm", [form.key, rebuild], function (result) {
return result.note;
});
});
});
chain
.then(function () {
return step("Updating the SWIM menu\\u2026", "finishSystemSetup", []);
})
.then(function () {
showPanel("deploy");
el("deploymentId").focus();
}, function () {
el("closeHint").textContent = "Setup stopped. Fix the problem above, then run " +
"SWIM > System > Setup again.";
el("closeHint").className = "status error";
show("closeRow", true);
});
}
// Shows one step's panel below the progress log and scrolls to it.
function showPanel(id) {
["deploy", "extension", "templates"].forEach(function (panel) { show(panel, panel === id); });
el(id).scrollIntoView({ behavior: "smooth", block: "start" });
}
function saveDeployment() {
if (!el("deploymentId").value.trim()) {
setStatus("deployStatus", "Paste the Deployment ID, or click Skip for now.", "error");
el("deploymentId").focus();
return;
}
el("deployBtn").disabled = true;
setStatus("deployStatus", "Saving\\u2026");
call("saveDeploymentId", [el("deploymentId").value]).then(function (id) {
el("deployBtn").disabled = false;
state.deploymentId = id;
var result = addLine("Saving the web app Deployment ID\\u2026");
result.textContent = "\\u2713 Done.";
result.className = "result ok";
showPanel("extension");
}, function (error) {
el("deployBtn").disabled = false;
setStatus("deployStatus", error.message, "error");
});
}
function skipDeployment() {
var result = addLine("Web app Deployment ID:");
result.textContent = state.deploymentId
? "kept the saved one."
: "skipped. Add it later in SWIM > System > Settings.";
el("noIdNote").hidden = Boolean(state.deploymentId);
showPanel("extension");
}
function extensionInstalled() {
var result = addLine("Installing the Ward Photo Directory extension\\u2026");
result.textContent = "\\u2713 Done.";
result.className = "result ok";
showPanel("templates");
}
// Copies through a hidden text area; the clipboard API isn't reliably
// allowed inside the dialog's frame. Returns false if the browser refused.
function copy(text) {
var area = document.createElement("textarea");
area.value = text;
area.style.position = "fixed";
area.style.opacity = "0";
document.body.appendChild(area);
area.select();
var copied = false;
try { copied = document.execCommand("copy"); } catch (e) {}
document.body.removeChild(area);
return copied;
}
function copyTemplates() {
el("copyBtn").disabled = true;
setStatus("copyStatus", "Building\\u2026");
call("getExtensionTemplates").then(function (result) {
el("copyBtn").disabled = false;
if (!result.items.length) {
setStatus("copyStatus", result.problems.join(" ") || "There are no saved templates.",
"error");
return;
}
if (!copy(JSON.stringify(result.items, null, 2))) {
setStatus("copyStatus", "Could not copy to the clipboard.", "error");
return;
}
setStatus("copyStatus", "Copied " + result.items.length + " template" +
(result.items.length === 1 ? "" : "s") + ". Now paste them into the extension." +
(result.problems.length ? " " + result.problems.join(" ") : ""),
result.problems.length ? "error" : "ok");
}, function (error) {
el("copyBtn").disabled = false;
setStatus("copyStatus", "Could not build the templates: " + error.message, "error");
});
}
// Replaces the dialog with a large "complete" message and confetti.
function complete() {
["progress", "deploy", "extension", "templates"].forEach(function (id) { show(id, false); });
el("completeNote").hidden = Boolean(state.deploymentId);
show("complete", true);
window.scrollTo(0, 0);
var colors = ["#1a73e8", "#137333", "#f9ab00", "#d93025", "#a142f4"];
for (var i = 0; i < 90; i++) {
var piece = document.createElement("div");
piece.className = "confetti";
piece.style.left = Math.random() * 97 + "%";
piece.style.background = colors[i % colors.length];
piece.style.animationDuration = 2 + Math.random() * 2 + "s";
piece.style.animationDelay = Math.random() * 0.8 + "s";
document.body.appendChild(piece);
}
}
el("deploymentId").addEventListener("keydown", function (event) {
if (event.key === "Enter") saveDeployment();
});
el("ownerName").addEventListener("keydown", function (event) {
if (event.key === "Enter") start();
});
call("getSetupState").then(render, function (error) {
el("loading").textContent = "Could not start Setup: " + error.message;
el("loading").className = "error";
show("closeRow", true);
});
</script>
`).setWidth(560).setHeight(620);
SpreadsheetApp.getUi().showModalDialog(html, SYSTEM_SETUP_TITLE);
}
/**
* Returns what the Setup dialog needs to start: the saved name and
* Deployment ID, and whether each ingest form already exists.
* @return {{ownerName: string, deploymentId: string, scriptEditorUrl: string,
* guideUrl: string, forms: Array<{key: string, name: string,
* label: string, purpose: string, exists: boolean, dataRows: number}>}}
*/
function getSetupState() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const settings = getSettings();
return {
ownerName: settings.ownerName,
deploymentId: settings.deploymentId,
scriptEditorUrl: "https://script.google.com/d/" + ScriptApp.getScriptId() + "/edit",
guideUrl: SETUP_GUIDE_URL,
forms: INGEST_FORMS.map(spec => {
const existing = findExistingIngestForm_(ss, spec);
return {
key: spec.key,
name: spec.name,
label: spec.label,
purpose: spec.purpose,
exists: existing.exists,
dataRows: existing.dataRows,
};
}),
};
}
/**
* Saves the owner name entered in the Setup dialog.
* @param {string} name - The name as entered.
*/
function saveSetupOwnerName(name) {
const trimmed = String(name || "").trim();
if (!trimmed) throw new Error("Please enter your name.");
setSetting_(SETTINGS.OWNER_NAME, trimmed);
}
/**
* Builds one ingest form for the Setup dialog. An existing form that holds
* data is kept unless rebuild is true; otherwise any existing form and sheet
* are deleted first.
* @param {string} key - The form spec's key ("messages" or "notes").
* @param {boolean} rebuild - Whether to replace an existing form with data.
* @return {{kept: boolean, note: string}} note is shown in the progress log.
*/
function setupIngestForm(key, rebuild) {
const spec = INGEST_FORMS.find(form => form.key === key);
if (!spec) throw new Error('Unknown form "' + key + '".');
const ss = SpreadsheetApp.getActiveSpreadsheet();
const existing = findExistingIngestForm_(ss, spec);
if (existing.dataRows > 0 && !rebuild) {
return {
kept: true,
note: "Kept the existing form.",
};
}
removeExistingIngestForm(ss, spec, existing);
const built = buildIngestForm_(ss, spec, getSettings().ownerName);
return {
kept: false,
note: built.responseSheet
? 'Form complete. Responses will appear on the "' + spec.name + '" sheet.'
: 'Form complete, but its responses sheet could not be found to rename it; ' +
'look for a new "Form Responses" sheet.',
};
}
/**
* Called by the Setup dialog once both forms are built: shows the full SWIM
* menu.
*/
function finishSystemSetup() {
addSwimMenu_();
}
/**
* Saves the web app Deployment ID entered in the Setup dialog.
* @param {string} text - A Deployment ID or web app URL, as pasted.
* @return {string} The saved Deployment ID ("" if cleared).
*/
function saveDeploymentId(text) {
const deploymentId = parseDeploymentId_(text);
validateDeploymentId_(deploymentId);
setSetting_(SETTINGS.DEPLOYMENT_ID, deploymentId);
return deploymentId;
}
/**
* Creates the Google Form described by spec with responses landing on a
* sheet of the same name, then saves its prefilled link in Settings.
* @param {Spreadsheet} ss - The spreadsheet.
* @param {Object} spec - MESSAGE_INGEST_FORM or NOTES_INGEST_FORM.
* @param {string} ownerName - The sheet owner's name.
* @return {{url: string, responseSheet: (Sheet|undefined)}} The prefilled
* link and the renamed response sheet, if it was found.
*/
function buildIngestForm_(ss, spec, ownerName) {
const form = FormApp.create(spec.name);
spec.textFields.forEach(field => form.addTextItem().setTitle(field));
spec.paragraphFields.forEach(field => form.addParagraphTextItem().setTitle(field));
const responseSheet = linkFormToSpreadsheet_(form, ss);
if (responseSheet) {
responseSheet.setName(spec.name);
}
if (spec === MESSAGE_INGEST_FORM) ensureFormSubmitTrigger(ss);
const url = generatePrefilledLink(form, spec.ownerField, ownerName);
setSetting_(spec.linkSetting, url);
return { url: url, responseSheet: responseSheet };
}
/**
* Sends a form's responses to a spreadsheet (unlinking it from any other)
* and returns the response sheet Google adds for it.
* @param {Form} form - The form.
* @param {Spreadsheet} ss - The spreadsheet.
* @return {Sheet|null} The new response sheet, or null if it didn't appear.
*/
function linkFormToSpreadsheet_(form, ss) {
const sheetIdsBefore = ss.getSheets().map(sheet => sheet.getSheetId());
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
// The response sheet can take a moment to show up after linking.
let responseSheet = null;
for (let attempt = 0; attempt < 10 && !responseSheet; attempt++) {
SpreadsheetApp.flush();
responseSheet = SpreadsheetApp.openById(ss.getId()).getSheets().find(
sheet => sheetIdsBefore.indexOf(sheet.getSheetId()) === -1 && sheet.getFormUrl()
);
if (!responseSheet) Utilities.sleep(500);
}
// Linking a form inserts its response sheet as the first tab.
keepLandingSheetFirst_(ss);
return responseSheet;
}
/**
* Installs the onFormSubmit trigger for the spreadsheet unless it already
* exists. Installable triggers are not carried over when the spreadsheet is
* copied, so each copy of the template gets its own here.
* @param {Spreadsheet} ss - The spreadsheet.
*/
function ensureFormSubmitTrigger(ss) {
const exists = ScriptApp.getProjectTriggers().some(trigger =>
trigger.getHandlerFunction() === "onFormSubmit" &&
trigger.getEventType() === ScriptApp.EventType.ON_FORM_SUBMIT &&
trigger.getTriggerSourceId() === ss.getId()
);
if (exists) return;
ScriptApp.newTrigger("onFormSubmit")
.forSpreadsheet(ss)
.onFormSubmit()
.create();
}
/**
* Returns the sheet owner name from Settings. If it is blank, asks the user
* for it and saves it there.
* @return {string} The name, or "" if the user cancelled.
*/
function getOwnerName_() {
let name = getSettings().ownerName;
if (name) return name;
const ui = SpreadsheetApp.getUi();
const response = ui.prompt(
"Enter Your Name",
"Please enter your name. It will be used to mark who has recorded notes or " +
"sent messages.",
ui.ButtonSet.OK_CANCEL
);
if (response.getSelectedButton() !== ui.Button.OK) return "";
name = response.getResponseText().trim();
if (!name) {
ui.alert("Enter Your Name", "No name was entered. No changes were made.",
ui.ButtonSet.OK);
return "";
}
setSetting_(SETTINGS.OWNER_NAME, name);
return name;
}
/**
* Finds the existing form and sheet(s) for spec, if any.
* @param {Spreadsheet} ss - The spreadsheet.
* @param {Object} spec - MESSAGE_INGEST_FORM or NOTES_INGEST_FORM.
* @return {{form: (Form|null), sheets: Sheet[], exists: boolean,
* dataRows: number}} dataRows counts the rows below the header on every
* sheet found.
*/
function findExistingIngestForm_(ss, spec) {
const form = findIngestForm(ss, spec.name);
const sheets = ss.getSheets().filter(sheet =>
sheet.getName() === spec.name || (form && linkedFormId(sheet) === form.getId())
);
const dataRows = sheets.reduce(
(total, sheet) => total + Math.max(sheet.getLastRow() - 1, 0), 0);
return { form: form, sheets: sheets, exists: Boolean(form || sheets.length), dataRows: dataRows };
}
/**
* Deletes any existing form and sheet for spec so they can be rebuilt. Asks
* nothing; the Setup dialog has already confirmed any loss of data.
* @param {Spreadsheet} ss - The spreadsheet.
* @param {Object} spec - MESSAGE_INGEST_FORM or NOTES_INGEST_FORM.
* @param {Object} [existing] - findExistingIngestForm_(ss, spec), if already
* looked up.
* @throws {Error} If the form or sheet could not be deleted.
*/
function removeExistingIngestForm(ss, spec, existing) {
const found = existing || findExistingIngestForm_(ss, spec);
if (!found.exists) return;
try {
if (found.form) {
found.form.removeDestination();
DriveApp.getFileById(found.form.getId()).setTrashed(true);
}
SpreadsheetApp.flush();
found.sheets.forEach(sheet => ss.deleteSheet(sheet));
} catch (error) {
throw new Error('Could not delete the existing "' + spec.name + '" form or sheet: ' +
error.message);
}
}
/**
* Returns the ID of the form linked to a sheet, or null if none.
* @param {Sheet} sheet - The sheet to check.
*/
function linkedFormId(sheet) {
const url = sheet.getFormUrl();
const match = url && url.match(/\/forms\/d\/([^/]+)/);
return match ? match[1] : null;
}
/**
* Returns the form named formName linked to the spreadsheet, or null.
* @param {Spreadsheet} ss - The spreadsheet to search.
* @param {string} formName - The form (and response sheet) name to find.
*/
function findIngestForm(ss, formName) {
for (const sheet of ss.getSheets()) {
const url = sheet.getFormUrl();
if (!url) continue;
try {
// Open by ID; openByUrl rejects some of the URL shapes getFormUrl returns.
const id = linkedFormId(sheet);
const form = id ? FormApp.openById(id) : FormApp.openByUrl(url);
// The form title can be edited independently of the response sheet name,
// so accept either one matching.
if (sheet.getName() === formName || form.getTitle().trim() === formName) {
return form;
}
} catch (error) {
console.warn('Could not open form linked to sheet "' + sheet.getName() + '": ' +
error.message);
}
}
return null;
}
/**
* Builds a prefilled link for a form where each question is filled with its
* own title, except ownerField, which is filled with ownerName.
* @param {Form} form - The ingest form.
* @param {string} ownerField - Title of the question to fill with ownerName.
* @param {string} ownerName - The sheet owner's name.
* @return {string} The prefilled form URL.
*/
function generatePrefilledLink(form, ownerField, ownerName) {
const response = form.createResponse();
form.getItems().forEach(item => {
const title = item.getTitle();
const value = title === ownerField ? ownerName : title;
if (item.getType() === FormApp.ItemType.TEXT) {
response.withItemResponse(item.asTextItem().createResponse(value));
} else if (item.getType() === FormApp.ItemType.PARAGRAPH_TEXT) {
response.withItemResponse(item.asParagraphTextItem().createResponse(value));
}
});
return response.toPrefilledUrl();
}
/**
* Shows a dialog listing each member's most recent interview (from the notes
* ingest sheet) and most recent sent message (from "messagesSent"), with a
* button to copy the table as tab-separated text.
*/
function showMostRecentContacts() {
const rows = getMostRecentContacts();
const template = HtmlService.createTemplate(`
<style>
body { font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5; }
.table-wrap { max-height: 300px; overflow-y: auto; border: 1px solid #ccc;
border-radius: 4px; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid #eee;
white-space: nowrap; }
th { position: sticky; top: 0; background: #f1f3f4; }
.note { color: #555; font-size: 13px; }
</style>
<p class="note">This data can be used in the "Import Values" feature of the Ward Photo
Directory (Menu → Instructions & Tools → Messages → Import Values).</p>
<? if (rows.length === 0) { ?>
<p>No interviews or sent messages were found.</p>
<? } else { ?>
<div class="table-wrap">
<table>
<tr><? headers.forEach(function (h) { ?><th><?= h ?></th><? }); ?></tr>
<? rows.forEach(function (row) { ?>
<tr><? row.forEach(function (cell) { ?><td><?= cell ?></td><? }); ?></tr>
<? }); ?>
</table>
</div>
<? } ?>
<textarea id="tsv" readonly style="position: absolute; left: -9999px;"><?= tsv ?></textarea>
<div style="text-align: right; margin-top: 12px;">
<span id="copied" style="color: green; margin-right: 8px;"></span>
<button onclick="copyTable()" <?= rows.length ? "" : "disabled" ?>>Copy</button>
<button onclick="google.script.host.close()">Close</button>
</div>
<script>
function copyTable() {
var box = document.getElementById("tsv");
box.select();
document.execCommand("copy");
document.getElementById("copied").textContent =
"Copied! Paste it into a spreadsheet.";
}
</script>
`);
template.headers = MOST_RECENT_CONTACT_HEADERS;
template.rows = rows;
template.tsv = [MOST_RECENT_CONTACT_HEADERS].concat(rows)
.map(row => row.map(cell => String(cell).replace(/[\t\r\n]+/g, " ")).join("\t"))
.join("\n");
SpreadsheetApp.getUi().showModalDialog(
template.evaluate().setWidth(620).setHeight(460), "Most Recent Contacts");
}
const MOST_RECENT_CONTACT_HEADERS = ["Member Id", "Name", "Last Interview", "Last Message"];
/**
* Returns one row per member ([Member Id, Name, Last Interview,
* Last Message]) sorted by name. Dates are formatted yyyy-MM-dd and are blank
* when the member has no interview or no sent message.
*/
function getMostRecentContacts() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const members = new Map();
// Records a dated contact for a member, keeping the latest date and the
// name from the most recent contact of either kind.
const record = (id, name, when, kind) => {
id = String(id).trim();
const date = toDate(when);
if (!id || !date) return;
const member = members.get(id) || { name: "", nameDate: null, interview: null, message: null };
if (!member[kind] || date > member[kind]) member[kind] = date;
if (String(name).trim() && (!member.nameDate || date > member.nameDate)) {
member.name = String(name).trim();
member.nameDate = date;
}
members.set(id, member);
};
readColumns(ss, NOTES_INGEST_FORM.name, [NOTES_MEMBER_ID_FIELD, "Name", "Timestamp"])
.forEach(([id, name, when]) => record(id, name, when, "interview"));
readColumns(ss, "messagesSent", ["MemberId", "Member Name", "Time Sent"])
.forEach(([id, name, when]) => record(id, name, when, "message"));
const tz = ss.getSpreadsheetTimeZone();
const format = date => date ? Utilities.formatDate(date, tz, "yyyy-MM-dd") : "";
return Array.from(members, ([id, m]) => [id, m.name, format(m.interview), format(m.message)])
.sort((a, b) => a[1].localeCompare(b[1]) || a[0].localeCompare(b[0]));
}
/**
* Returns the data rows of a sheet reduced to the named columns, in order.
* Returns [] if the sheet is missing; throws if a column is missing.
* @param {Spreadsheet} ss - The spreadsheet.
* @param {string} sheetName - The sheet to read.
* @param {string[]} columns - Header names of the columns to return.
*/
function readColumns(ss, sheetName, columns) {
const sheet = ss.getSheetByName(sheetName);
if (!sheet) return [];
const values = sheet.getDataRange().getValues();
const cols = columns.map(column => {
const col = values[0].indexOf(column);
if (col === -1) {
throw new Error('Column "' + column + '" not found on "' + sheetName + '"');
}
return col;
});
return values.slice(1).map(row => cols.map(col => row[col]));
}
/**
* Returns value as a valid Date, or null if it is blank or not a date.
*/
function toDate(value) {
if (value === "" || value === null || value === undefined) return null;
const date = value instanceof Date ? value : new Date(value);
return isNaN(date.getTime()) ? null : date;
}
// ---- Compose.js --------------------------------------------------------
/**
* The SWIM > Compose Messages sidebar: write one message (optionally from a
* saved template) with placeholders such as <FIRST NAME>, pick recipients by
* selecting rows in any sheet, and queue one personalized message per
* recipient on "messagesToSend" for the Send Messages page or email to send.
* It also copies the saved templates as JSON for the Ward Photo Directory
* extension, each with the message or notes form link from Settings.
*/
const MESSAGE_TEMPLATES_SHEET = "messageTemplates";
const MESSAGE_TEMPLATE_HEADERS = ["Title", "Message", "Type"];
const TEMPLATE_TYPE_MESSAGE = "Message";
const TEMPLATE_TYPE_NOTE = "Note";
/**
* Matches anything in angle brackets, such as "<FIRST NAME>". Only the
* built-in placeholders and the column placeholders read from the sheet are
* filled (any case, extra spaces ignored); the rest, such as the extension's
* <ROOMMATES>, are left as written. Shared with the sidebar as a string.
*/
const PLACEHOLDER_PATTERN = "<([^<>]+)>";
/**
* The built-in placeholders offered as chips. <SENDER NAME> is the owner name
* from Settings; the older <SENT BY> is still filled the same way.
* <SCHEDULE LINK> is this copy's own "Schedule an Appointment" page, so a
* shared template links each bishop's members to that bishop's schedule. It
* is left as written until the web app has been deployed.
*/
const PLACEHOLDERS = ["<FIRST NAME>", "<LAST NAME>", "<FULL NAME>", "<SENDER NAME>",
"<SCHEDULE LINK>"];
/**
* Header spellings (lowercase, letters and digits only) that identify each
* recipient field on the selected sheet.
*/
const RECIPIENT_COLUMNS = {
memberId: ["memberid", "uuid"],
name: ["name", "membername", "preferredname", "displayname", "fullname"],
firstName: ["given", "givenname", "firstname", "givennames"],
lastName: ["surname", "lastname", "familyname"],
phone: ["phone", "phonenumber", "mobile", "mobilephone", "cell", "cellphone"],
email: ["email", "emailaddress"],
};
/**
* Returns the key a placeholder or column header is matched by: trimmed,
* single-spaced and upper case ("Move-in date" -> "MOVE-IN DATE").
* @param {string} text - The placeholder's inner text or a header.
*/
function placeholderKey_(text) {
return String(text).trim().replace(/\s+/g, " ").toUpperCase();
}
/**
* Replaces the placeholders in text with the recipient's details. The
* built-in placeholders come first; then any key in recipient.fields (the
* recipient's row, keyed by placeholderKey_ of each header).
* @param {string} text - The title or message.
* @param {{name: string, firstName: string, lastName: string,
* fields: (Object<string, string>|undefined)}} recipient
* @param {string} sentBy - The sender's name.
* @param {string} scheduleLink - From getScheduleLink_(); "" if not deployed.
* @return {string}
*/
function fillPlaceholders_(text, recipient, sentBy, scheduleLink) {
const fields = recipient.fields || {};
return String(text || "").replace(new RegExp(PLACEHOLDER_PATTERN, "g"), (match, inner) => {
const key = placeholderKey_(inner);
switch (key) {
case "FIRST NAME": return recipient.firstName || "";
case "LAST NAME": return recipient.lastName || "";
case "FULL NAME": return recipient.name || "";
case "SENDER NAME":
case "SENT BY": return sentBy || "";
case "SCHEDULE LINK": return scheduleLink || match;
}
return Object.prototype.hasOwnProperty.call(fields, key) ? fields[key] : match;
});
}
/**
* Replaces only <SENDER NAME> (or <SENT BY>) and <SCHEDULE LINK>, leaving the
* placeholders the extension fills.
* @param {string} text - The template text.
* @param {string} sentBy - The sender's name.
* @param {string} scheduleLink - From getScheduleLink_(); "" if not deployed.
*/
function fillSentBy_(text, sentBy, scheduleLink) {
let filled = String(text || "").replace(/< *(sender +name|sent +by) *>/gi, sentBy || "");
if (scheduleLink) filled = filled.replace(/< *schedule +link *>/gi, scheduleLink);
return filled;
}
/**
* Returns this copy's public "Schedule an Appointment" page link, or "" if the
* web app hasn't been deployed yet.
* @param {Object} settings - From getSettings().
*/
function getScheduleLink_(settings) {
try {
const schedule = getPageUrls_(settings).find(link => link.id === "schedule");
return schedule ? schedule.url : "";
} catch (error) {
console.warn("Could not build the schedule link: " + error.message);
return "";
}
}
/**
* Opens the Compose Messages sidebar.
*/
function showComposeMessages() {
const html = HtmlService.createHtmlOutput(`
<style>
body { font-family: Arial, sans-serif; font-size: 13px; line-height: 1.4;
color: #202124; margin: 0; padding: 12px; }
h3 { font-size: 13px; margin: 18px 0 6px; }
h3:first-child { margin-top: 0; }
label { display: block; font-weight: bold; margin: 10px 0 3px; }
input[type=text], select, textarea { width: 100%; box-sizing: border-box;
font: inherit; padding: 5px 6px; border: 1px solid #dadce0; border-radius: 4px; }
textarea { min-height: 140px; resize: vertical; }
button { font: inherit; padding: 5px 10px; border: 1px solid #dadce0;
border-radius: 4px; background: #fff; color: #1a73e8; cursor: pointer; }
button:hover { background: #f1f6fe; }
button:disabled { color: #9aa0a6; background: #fff; cursor: default; }
button.primary { background: #1a73e8; border-color: #1a73e8; color: #fff; }
button.primary:hover { background: #1765cc; }
button.primary:disabled { background: #9aa0a6; border-color: #9aa0a6; color: #fff; }
button.danger { color: #c5221f; }
.row { display: flex; gap: 6px; align-items: center; }
.row input { flex: 1; min-width: 0; }
.hint { color: #5f6368; font-size: 12px; margin: 3px 0; }
.error { color: #c5221f; }
.ok { color: #137333; }
.chips { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
.chip { font-size: 12px; padding: 2px 8px; border-radius: 12px; }
#recipients { border: 1px solid #dadce0; border-radius: 4px; max-height: 180px;
overflow-y: auto; margin-top: 6px; }
#recipients:empty { display: none; }
.recipient { display: flex; align-items: center; gap: 6px; padding: 3px 6px;
border-bottom: 1px solid #eee; }
.recipient:last-child { border-bottom: none; }
.recipient .who { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap; }
.recipient .via { color: #5f6368; font-size: 11px; }
.recipient.unreachable .who, .recipient.unreachable .via { color: #9aa0a6; }
.recipient button { border: none; padding: 0 4px; color: #5f6368; }
#preview { border: 1px solid #dadce0; border-radius: 4px; background: #f8f9fa;
padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; }
#previewTitle { font-weight: bold; margin-bottom: 4px; }
.footer { position: sticky; bottom: 0; background: #fff; margin-top: 16px;
padding: 10px 0 4px; border-top: 1px solid #e0e0e0; }
.footer button.primary { width: 100%; }
${UNSAVED_BAR_CSS}
</style>
${UNSAVED_BAR_HTML}
<h3>Template</h3>
<div class="row">
<select id="templateSelect" onchange="loadTemplate()" style="flex: 1; min-width: 0;"></select>
<button id="saveBtn" onclick="saveTemplate()" title="Save under this title, replacing any template with the same title">Save</button>
<button id="deleteBtn" class="danger" onclick="deleteTemplate()" disabled>Delete</button>
</div>
<div class="hint">Templates are saved under their title.</div>
<div id="templateStatus" class="hint"></div>
<div style="margin-top: 6px;">
<button onclick="copyForExtension()" id="copyBtn">Copy templates for extension</button>
</div>
<div class="hint">Copies every saved template, with its form link, to paste into the
Ward Photo Directory extension (Menu → Instructions & Tools → Messages
→ Paste Messages).</div>
<div id="copyStatus" class="hint"></div>
<h3>Message</h3>
<label for="title">Title</label>
<input type="text" id="title" oninput="refresh()">
<label for="type">Type</label>
<select id="type" onchange="refresh()">
<option value="Message">Message (Ingest Messages form)</option>
<option value="Note">Note (Ingest Notes form)</option>
</select>
<label for="message">Message</label>
<textarea id="message" oninput="refresh()"></textarea>
<div class="hint">Insert a placeholder:</div>
<div class="chips" id="chips"></div>
<div style="margin-top: 6px;">
<button onclick="readSheetPlaceholders()" id="readPlaceholdersBtn">Read placeholders from sheet</button>
</div>
<div id="sheetPlaceholderStatus" class="hint"></div>
<div class="hint" style="margin-top: 10px;">Sent by <b id="sentBy">…</b> (your name
in <a href="#" onclick="google.script.run.showSettings(); return false;">Settings</a>)</div>
<h3>Recipients</h3>
<div class="hint">Go to the sheet of people to message. Use the rows you've selected
(Ctrl-click for several ranges) or every row below the header row:</div>
<div class="row">
<button onclick="useRows('selected')" id="useRowsBtn">Use selected rows</button>
<button onclick="useRows('all')" id="useAllRowsBtn"
title="Every row of the current sheet below the header row">Use All Rows</button>
</div>
<div id="recipientStatus" class="hint"></div>
<div id="recipients"></div>
<h3>Preview</h3>
<div class="row" style="margin-bottom: 6px;">
<button id="prevBtn" onclick="step(-1)">‹</button>
<span id="previewWho" class="hint" style="flex: 1; text-align: center;"></span>
<button id="nextBtn" onclick="step(1)">›</button>
</div>
<div id="preview"><div id="previewTitle"></div><div id="previewBody"></div></div>
<div class="footer">
<button class="primary" id="queueBtn" onclick="queueMessages()" disabled>Queue messages</button>
<div id="queueStatus" class="hint"></div>
</div>
<script>
var PLACEHOLDER_PATTERN = ${JSON.stringify(PLACEHOLDER_PATTERN)};
var PLACEHOLDERS = ${JSON.stringify(PLACEHOLDERS)};
var templates = [];
var recipients = [];
var previewIndex = 0;
var smsUrl = "";
var sentBy = "";
var scheduleLink = "";
var deleteArmed = false;
// The title, type and message as last loaded, saved or queued; edits
// that differ from it show the unsaved-changes bar.
var savedFields = "";
var dirty = false;
function el(id) { return document.getElementById(id); }
function setStatus(id, text, cls) {
el(id).textContent = text;
el(id).className = "hint" + (cls ? " " + cls : "");
}
function currentFields() {
return JSON.stringify([el("title").value, el("type").value, el("message").value]);
}
function markSaved() {
savedFields = currentFields();
updateDirty();
}
function updateDirty() {
dirty = currentFields() !== savedFields;
document.body.className = dirty ? "dirty" : "";
}
function setBusy(busy) {
el("saveBtn").disabled = busy;
el("unsavedSaveBtn").disabled = busy;
}
// Called by the unsaved-changes bar's Save button.
function save() { saveTemplate(); }
// Asks before the panel closes with unsaved edits. Browsers may skip
// this for a sidebar, so the bar above is the main reminder.
window.addEventListener("beforeunload", function (event) {
if (!dirty) return;
event.preventDefault();
event.returnValue = "";
});
// Same as placeholderKey_ on the server.
function placeholderKey(text) {
return String(text).trim().split(" ").filter(Boolean).join(" ").toUpperCase();
}
// Same as fillPlaceholders_ on the server, for the preview.
function fill(text, r, sentBy) {
var fields = r.fields || {};
return String(text || "").replace(new RegExp(PLACEHOLDER_PATTERN, "g"), function (m, inner) {
var key = placeholderKey(inner);
switch (key) {
case "FIRST NAME": return r.firstName || "";
case "LAST NAME": return r.lastName || "";
case "FULL NAME": return r.name || "";
case "SENDER NAME":
case "SENT BY": return sentBy || "";
case "SCHEDULE LINK": return scheduleLink || m;
}
return Object.prototype.hasOwnProperty.call(fields, key) ? fields[key] : m;
});
}
function reachable(r) { return !!(r.phone || r.email); }
// ---- Templates ----
function renderTemplates(selectTitle) {
templates = templates.slice().sort(function (a, b) {
return a.title.toLowerCase() < b.title.toLowerCase() ? -1 : 1;
});
var select = el("templateSelect");
select.innerHTML = "";
var blank = document.createElement("option");
blank.value = "";
blank.textContent = templates.length ? "— New message —" : "— No saved templates —";
select.appendChild(blank);
templates.forEach(function (t) {
var option = document.createElement("option");
option.value = t.title;
option.textContent = t.title;
select.appendChild(option);
});
var match = findTemplate(selectTitle || "");
select.value = match ? match.title : "";
el("deleteBtn").disabled = !select.value;
disarmDelete();
}
function findTemplate(title) {
for (var i = 0; i < templates.length; i++) {
if (templates[i].title.toLowerCase() === String(title).toLowerCase()) return templates[i];
}
return null;
}
function loadTemplate() {
var title = el("templateSelect").value;
el("deleteBtn").disabled = !title;
disarmDelete();
setStatus("templateStatus", "");
var t = findTemplate(title);
el("title").value = t ? t.title : "";
el("message").value = t ? t.message : "";
el("type").value = t ? t.type : "Message";
markSaved();
refresh();
}
function saveTemplate() {
var title = el("title").value.trim();
if (!title) {
setStatus("templateStatus", "Enter a title first; templates are saved under it.", "error");
el("title").focus();
return;
}
if (!el("message").value.trim()) {
setStatus("templateStatus", "Write a message before saving it.", "error");
return;
}
setStatus("templateStatus", "Saving…");
setBusy(true);
var fields = currentFields();
google.script.run
.withSuccessHandler(function (list) {
setBusy(false);
templates = list;
renderTemplates(title);
savedFields = fields;
updateDirty();
setStatus("templateStatus", "Saved \\"" + title + "\\".", "ok");
})
.withFailureHandler(function (error) {
setBusy(false);
setStatus("templateStatus", "Could not save: " + error.message, "error");
})
.saveMessageTemplate({
title: title,
message: el("message").value,
type: el("type").value,
});
}
// Copies through a hidden text area; the clipboard API isn't reliably
// allowed inside the sidebar's frame.
function copy(text) {
var area = document.createElement("textarea");
area.value = text;
area.style.position = "fixed";
area.style.opacity = "0";
document.body.appendChild(area);
area.select();
var ok = document.execCommand("copy");
document.body.removeChild(area);
return ok;
}
function copyForExtension() {
el("copyBtn").disabled = true;
setStatus("copyStatus", "Building…");
google.script.run
.withSuccessHandler(function (result) {
el("copyBtn").disabled = false;
if (!result.items.length) {
setStatus("copyStatus", result.problems.join(" ") || "There are no saved templates.",
"error");
return;
}
if (!copy(JSON.stringify(result.items, null, 2))) {
setStatus("copyStatus", "Could not copy to the clipboard.", "error");
return;
}
setStatus("copyStatus", "Copied " + result.items.length + " template" +
(result.items.length === 1 ? "" : "s") + "." +
(result.problems.length ? " " + result.problems.join(" ") : ""),
result.problems.length ? "error" : "ok");
})
.withFailureHandler(function (error) {
el("copyBtn").disabled = false;
setStatus("copyStatus", "Could not build the templates: " + error.message, "error");
})
.getExtensionTemplates();
}
function disarmDelete() {
deleteArmed = false;
el("deleteBtn").textContent = "Delete";
}
// The first click asks for confirmation; the second deletes.
function deleteTemplate() {
var title = el("templateSelect").value;
if (!title) return;
if (!deleteArmed) {
deleteArmed = true;
el("deleteBtn").textContent = "Sure?";
return;
}
disarmDelete();
setStatus("templateStatus", "Deleting…");
google.script.run
.withSuccessHandler(function (list) {
templates = list;
renderTemplates("");
setStatus("templateStatus", "Deleted \\"" + title + "\\".", "ok");
})
.withFailureHandler(function (error) {
setStatus("templateStatus", "Could not delete: " + error.message, "error");
})
.deleteMessageTemplate(title);
}
// ---- Placeholders ----
function insertAtCursor(text) {
var area = el("message");
var start = area.selectionStart, end = area.selectionEnd;
area.value = area.value.slice(0, start) + text + area.value.slice(end);
area.focus();
area.selectionStart = area.selectionEnd = start + text.length;
refresh();
}
function renderChips(boxId, placeholders) {
var box = el(boxId);
box.innerHTML = "";
placeholders.forEach(function (p) {
var chip = document.createElement("button");
chip.className = "chip";
chip.textContent = p;
chip.onclick = function () { insertAtCursor(p); };
box.appendChild(chip);
});
}
// Replaces the placeholder chips with one for each row-1 header of the
// active sheet, if the sheet has a MemberId column; otherwise leaves
// the chips as they are.
function readSheetPlaceholders() {
el("readPlaceholdersBtn").disabled = true;
setStatus("sheetPlaceholderStatus", "Reading row 1…");
google.script.run
.withSuccessHandler(function (result) {
el("readPlaceholdersBtn").disabled = false;
if (result.warning) {
setStatus("sheetPlaceholderStatus", result.warning, "error");
return;
}
renderChips("chips", result.placeholders);
setStatus("sheetPlaceholderStatus", "Placeholders are now the columns of \\"" +
result.sheetName + "\\", filled from each recipient's row (the extension won't " +
"fill these).");
})
.withFailureHandler(function (error) {
el("readPlaceholdersBtn").disabled = false;
setStatus("sheetPlaceholderStatus", "Could not read the sheet: " + error.message, "error");
})
.getSheetPlaceholders();
}
// ---- Recipients ----
// which is "selected" (the selected rows) or "all" (every row below the
// header row) of the current sheet.
function useRows(which) {
function enable(on) {
el("useRowsBtn").disabled = !on;
el("useAllRowsBtn").disabled = !on;
}
enable(false);
setStatus("recipientStatus", which === "all" ? "Reading all rows…" : "Reading the selected rows…");
var run = google.script.run
.withSuccessHandler(function (result) {
enable(true);
recipients = result.recipients;
previewIndex = 0;
setStatus("recipientStatus", result.warning || describeRecipients(result.sheetName),
result.warning ? "error" : "");
refresh();
})
.withFailureHandler(function (error) {
enable(true);
setStatus("recipientStatus", "Could not read the rows: " + error.message, "error");
});
if (which === "all") run.getAllRecipients();
else run.getSelectedRecipients();
}
function describeRecipients(sheetName) {
var missing = recipients.filter(function (r) { return !reachable(r); }).length;
return recipients.length + " from \\"" + sheetName + "\\"" +
(missing ? " (" + missing + " without a phone or email will be skipped)" : "") + ".";
}
function renderRecipients() {
var box = el("recipients");
box.innerHTML = "";
recipients.forEach(function (r, i) {
var row = document.createElement("div");
row.className = "recipient" + (reachable(r) ? "" : " unreachable");
var who = document.createElement("span");
who.className = "who";
who.textContent = r.name || "(no name)";
who.title = [r.name, r.phone, r.email].filter(Boolean).join(" · ");
var via = document.createElement("span");
via.className = "via";
via.textContent = [r.phone ? "SMS" : "", r.email ? "Email" : ""].filter(Boolean).join(" / ") ||
"no contact";
var remove = document.createElement("button");
remove.textContent = "×";
remove.title = "Remove";
remove.onclick = function () {
recipients.splice(i, 1);
if (previewIndex >= recipients.length) previewIndex = Math.max(0, recipients.length - 1);
refresh();
};
row.appendChild(who);
row.appendChild(via);
row.appendChild(remove);
box.appendChild(row);
});
}
// ---- Preview and queueing ----
function step(delta) {
previewIndex = Math.min(Math.max(0, previewIndex + delta), recipients.length - 1);
refresh();
}
function refresh() {
updateDirty();
renderRecipients();
var r = recipients[previewIndex];
var sample = r || { name: "Alex Example", firstName: "Alex", lastName: "Example" };
el("previewWho").textContent = r
? (previewIndex + 1) + " of " + recipients.length + ": " + (r.name || "(no name)")
: "Sample recipient";
el("prevBtn").disabled = !r || previewIndex === 0;
el("nextBtn").disabled = !r || previewIndex >= recipients.length - 1;
el("previewTitle").textContent = fill(el("title").value, sample, sentBy);
el("previewBody").textContent = fill(el("message").value, sample, sentBy);
if (el("type").value === "Note") {
el("queueBtn").textContent = "Notes are recorded through the extension";
el("queueBtn").disabled = true;
return;
}
var count = recipients.filter(reachable).length;
el("queueBtn").textContent = "Queue " + count + " message" + (count === 1 ? "" : "s");
el("queueBtn").disabled = !count || !el("message").value.trim();
}
function queueMessages() {
el("queueBtn").disabled = true;
setStatus("queueStatus", "Queueing…");
google.script.run
.withSuccessHandler(function (result) {
var text = "Queued " + result.queued + " message" + (result.queued === 1 ? "" : "s");
if (result.skipped.length) {
text += " (skipped: " + result.skipped.map(function (s) {
return s.name + " — " + s.reason;
}).join("; ") + ")";
}
setStatus("queueStatus", text + ".", "ok");
if (smsUrl && result.queued) {
var link = document.createElement("a");
link.href = smsUrl;
link.target = "_blank";
link.rel = "noopener";
link.textContent = " Open Send Messages";
el("queueStatus").appendChild(link);
}
recipients = [];
previewIndex = 0;
setStatus("recipientStatus", "");
refresh();
})
.withFailureHandler(function (error) {
setStatus("queueStatus", "Could not queue: " + error.message, "error");
refresh();
})
.queueComposedMessages({
title: el("title").value,
message: el("message").value,
recipients: recipients,
});
}
renderChips("chips", PLACEHOLDERS);
markSaved();
refresh();
google.script.run
.withSuccessHandler(function (view) {
templates = view.templates;
smsUrl = view.smsUrl;
sentBy = view.ownerName;
scheduleLink = view.scheduleLink;
el("sentBy").textContent = sentBy || "(no name set)";
renderTemplates("");
refresh();
})
.withFailureHandler(function (error) {
setStatus("templateStatus", "Could not load templates: " + error.message, "error");
})
.getComposeView();
</script>
`).setTitle("Compose Messages");
SpreadsheetApp.getUi().showSidebar(html);
}
/**
* Returns what the sidebar needs when it opens.
* @return {{templates: Array<{title: string, message: string, type: string}>,
* ownerName: string, scheduleLink: string, smsUrl: string}}
*/
function getComposeView() {
const settings = getSettings();
let smsUrl = "";
try {
const sms = getPageUrls_(settings).find(link => link.id === "sms");
smsUrl = sms ? sms.url : "";
} catch (error) {
console.warn("Could not build the Send Messages link: " + error.message);
}
return {
templates: getMessageTemplates_(),
ownerName: settings.ownerName,
scheduleLink: getScheduleLink_(settings),
smsUrl: smsUrl,
};
}
/**
* Reads the recipients from the rows selected on the active sheet.
* @return {{recipients: Array<Object>, sheetName: string, warning: string}}
* As described at readRecipients_.
*/
function getSelectedRecipients() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
const lastRow = sheet.getLastRow();
const rangeList = ss.getActiveRangeList();
if (!rangeList || lastRow < 2) {
return { recipients: [], sheetName: sheet.getName(),
warning: "Select the rows of the people to message first." };
}
const rows = new Set();
rangeList.getRanges().forEach(range => {
const last = Math.min(range.getLastRow(), lastRow);
for (let row = Math.max(range.getRow(), 2); row <= last; row++) rows.add(row);
});
if (!rows.size) {
return { recipients: [], sheetName: sheet.getName(),
warning: "Select rows below the header row of \"" + sheet.getName() + "\"." };
}
return readRecipients_(sheet, rows);
}
/**
* Reads the recipients from every row of the active sheet below row 1.
* @return {{recipients: Array<Object>, sheetName: string, warning: string}}
* As described at readRecipients_.
*/
function getAllRecipients() {
const sheet = SpreadsheetApp.getActiveSheet();
const lastRow = sheet.getLastRow();
const rows = new Set();
for (let row = 2; row <= lastRow; row++) rows.add(row);
if (!rows.size) {
return { recipients: [], sheetName: sheet.getName(),
warning: "\"" + sheet.getName() + "\" has no rows below the header row." };
}
return readRecipients_(sheet, rows);
}
/**
* Reads the recipients from the given rows of sheet. Row 1 is the header row
* and identifies the columns (see RECIPIENT_COLUMNS). Blank rows are skipped.
* @param {Sheet} sheet - The sheet to read.
* @param {Set<number>} rows - Row numbers, all 2 or more and within the data.
* @return {{recipients: Array<{memberId: string, name: string,
* firstName: string, lastName: string, phone: string, email: string,
* fields: Object<string, string>, row: number}>, sheetName: string,
* warning: string}}
*/
function readRecipients_(sheet, rows) {
const result = { recipients: [], sheetName: sheet.getName(), warning: "" };
const lastRow = sheet.getLastRow();
const lastColumn = sheet.getLastColumn();
const values = sheet.getRange(1, 1, lastRow, lastColumn).getDisplayValues();
const columns = findRecipientColumns_(values[0]);
if (columns.name < 0 && columns.firstName < 0) {
result.warning = "Couldn't find a name column on \"" + sheet.getName() + "\". Row 1 " +
"needs headers such as Name (or Given and Surname), Phone and Email.";
return result;
}
const fieldKeys = values[0].map(header => placeholderKey_(header));
Array.from(rows).sort((a, b) => a - b).forEach(row => {
const cells = values[row - 1];
const cell = field => (columns[field] >= 0 ? String(cells[columns[field]]).trim() : "");
if (!cells.some(value => String(value).trim())) return;
let name = cell("name");
// Church exports list names as "Surname, Given".
if (name.indexOf(",") >= 0) {
const parts = name.split(",");
name = (parts.slice(1).join(",").trim() + " " + parts[0].trim()).trim();
}
const words = name.split(/\s+/).filter(Boolean);
const firstName = cell("firstName") || words[0] || "";
const lastName = cell("lastName") || (words.length > 1 ? words[words.length - 1] : "");
if (!name) name = (firstName + " " + lastName).trim();
const fields = {};
fieldKeys.forEach((key, index) => {
if (key && !(key in fields)) fields[key] = String(cells[index]).trim();
});
result.recipients.push({
memberId: cell("memberId"),
name: name,
firstName: firstName,
lastName: lastName,
phone: cell("phone"),
email: cell("email"),
fields: fields,
row: row,
});
});
return result;
}
/**
* Returns every row-1 header of the active sheet as a placeholder (such as
* "<MOVE-IN DATE>"), but only if the sheet has a MemberId column (a header
* that is "memberid" once lowercased with spaces removed).
* @return {{sheetName: string, placeholders: string[], warning: string}}
*/
function getSheetPlaceholders() {
const sheet = SpreadsheetApp.getActiveSheet();
const result = { sheetName: sheet.getName(), placeholders: [], warning: "" };
const headers = sheet.getLastColumn() < 1 ? []
: sheet.getRange(1, 1, 1, sheet.getLastColumn()).getDisplayValues()[0];
if (!headers.some(h => String(h).toLowerCase().replace(/\s/g, "") === "memberid")) {
result.warning = "Row 1 of \"" + sheet.getName() + "\" has no MemberId column, so no " +
"placeholders were read.";
return result;
}
headers.forEach(header => {
const key = placeholderKey_(header);
// Brackets in a header would break the placeholder.
if (!key || /[<>]/.test(key)) return;
const placeholder = "<" + key + ">";
if (result.placeholders.indexOf(placeholder) < 0) result.placeholders.push(placeholder);
});
return result;
}
/**
* Returns the column index of each recipient field in headers, or -1.
* @param {Array} headers - The header row.
* @return {Object<string, number>}
*/
function findRecipientColumns_(headers) {
const normalized = headers.map(h => String(h).toLowerCase().replace(/[^a-z0-9]/g, ""));
const columns = {};
Object.keys(RECIPIENT_COLUMNS).forEach(field => {
columns[field] = normalized.findIndex(h => RECIPIENT_COLUMNS[field].indexOf(h) >= 0);
});
return columns;
}
/**
* Returns the saved templates from the "messageTemplates" sheet. Each
* template is identified by its title.
* @return {Array<{title: string, message: string, type: string}>}
*/
function getMessageTemplates_() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(MESSAGE_TEMPLATES_SHEET);
if (!sheet || sheet.getLastRow() < 2) return [];
return sheet.getRange(2, 1, sheet.getLastRow() - 1, MESSAGE_TEMPLATE_HEADERS.length)
.getValues()
.filter(row => String(row[0]).trim())
.map(row => ({
title: String(row[0]).trim(),
message: String(row[1]),
type: normalizeTemplateType_(row[2]),
}));
}
/**
* Returns "Note" for a type starting with "note" (any case), else "Message".
* @param {*} type - The Type cell or the sidebar's value.
*/
function normalizeTemplateType_(type) {
return /^\s*note/i.test(String(type || "")) ? TEMPLATE_TYPE_NOTE : TEMPLATE_TYPE_MESSAGE;
}
/**
* Returns the "messageTemplates" sheet, creating it if needed and making sure
* its header row is current (older sheets lack the Type column).
* @param {Spreadsheet} ss - The spreadsheet.
*/
function getMessageTemplatesSheet_(ss) {
let sheet = ss.getSheetByName(MESSAGE_TEMPLATES_SHEET);
if (!sheet) {
sheet = ss.insertSheet(MESSAGE_TEMPLATES_SHEET);
sheet.setFrozenRows(1);
sheet.setColumnWidth(2, 400);
}
sheet.getRange(1, 1, 1, MESSAGE_TEMPLATE_HEADERS.length)
.setValues([MESSAGE_TEMPLATE_HEADERS])
.setFontWeight("bold");
return sheet;
}
/**
* Returns the saved templates in the Ward Photo Directory extension's format.
* Each formLink is the Settings form link for the template's type, and
* <SENDER NAME> (or <SENT BY>) is filled with the owner name and
* <SCHEDULE LINK> with this copy's schedule page; the extension fills the
* other placeholders. Templates whose form link isn't set are left out.
* @return {{items: Array<{messageName: string, messageText: string,
* formLink: string}>, problems: string[]}}
*/
function getExtensionTemplates() {
const settings = getSettings();
const links = {};
links[TEMPLATE_TYPE_MESSAGE] = settings.messageFormLink;
links[TEMPLATE_TYPE_NOTE] = settings.notesFormLink;
const scheduleLink = getScheduleLink_(settings);
const result = { items: [], problems: [] };
const missing = {};
getMessageTemplates_().forEach(template => {
const link = links[template.type];
if (!link) {
(missing[template.type] = missing[template.type] || []).push(template.title);
return;
}
result.items.push({
messageName: template.title,
messageText: fillSentBy_(template.message, settings.ownerName, scheduleLink),
formLink: link,
});
});
Object.keys(missing).forEach(type => {
result.problems.push("Left out " + missing[type].map(t => "\"" + t + "\"").join(", ") +
": there is no " + type.toLowerCase() + " form link yet (SWIM > System > " + SYSTEM_SETUP_TITLE + ").");
});
return result;
}
/**
* Returns the row of the template with this title (ignoring case), or -1.
* @param {Sheet} sheet - The "messageTemplates" sheet.
* @param {string} title - The template title.
*/
function findTemplateRow_(sheet, title) {
if (sheet.getLastRow() < 2) return -1;
const titles = sheet.getRange(2, 1, sheet.getLastRow() - 1, 1).getValues();
const index = titles.findIndex(row =>
String(row[0]).trim().toLowerCase() === title.toLowerCase());
return index < 0 ? -1 : index + 2;
}
/**
* Saves a template, replacing any template with the same title.
* @param {{title: string, message: string, type: string}} template - type
* is "Message" or "Note".
* @return {Array<{title: string, message: string, type: string}>} All templates.
*/
function saveMessageTemplate(template) {
const title = String(template.title || "").trim();
if (!title) throw new Error("A template needs a title");
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
const sheet = getMessageTemplatesSheet_(SpreadsheetApp.getActiveSpreadsheet());
const values = [[title, String(template.message || ""), normalizeTemplateType_(template.type)]];
const row = findTemplateRow_(sheet, title);
// Write as plain text so a message starting with "=" isn't read as a formula.
const target = row > 0
? sheet.getRange(row, 1, 1, MESSAGE_TEMPLATE_HEADERS.length)
: sheet.getRange(sheet.getLastRow() + 1, 1, 1, MESSAGE_TEMPLATE_HEADERS.length);
target.setNumberFormat("@").setValues(values);
} finally {
lock.releaseLock();
}
return getMessageTemplates_();
}
/**
* Deletes the template with this title.
* @param {string} title - The template title.
* @return {Array<{title: string, message: string, type: string}>} All templates.
*/
function deleteMessageTemplate(title) {
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(MESSAGE_TEMPLATES_SHEET);
const row = sheet ? findTemplateRow_(sheet, String(title || "").trim()) : -1;
if (row > 0) sheet.deleteRow(row);
} finally {
lock.releaseLock();
}
return getMessageTemplates_();
}
/**
* Queues one personalized message per recipient on "messagesToSend".
* "Sent By" is the owner name from Settings. Recipients with neither a phone
* nor an email are skipped.
* @param {{title: string, message: string, recipients: Array<Object>}}
* request - recipients as returned by getSelectedRecipients.
* @return {{queued: number, skipped: Array<{name: string, reason: string}>}}
*/
function queueComposedMessages(request) {
const message = String(request.message || "");
if (!message.trim()) throw new Error("The message is empty");
const title = String(request.title || "");
const settings = getSettings();
const sentBy = settings.ownerName;
const scheduleLink = getScheduleLink_(settings);
const result = { queued: 0, skipped: [] };
const valueFors = [];
(request.recipients || []).forEach(raw => {
const r = {};
["memberId", "name", "firstName", "lastName", "phone", "email"].forEach(key => {
r[key] = String(raw[key] || "").trim();
});
r.fields = {};
Object.keys(raw.fields || {}).forEach(key => {
r.fields[placeholderKey_(key)] = String(raw.fields[key]);
});
if (!r.phone && !r.email) {
result.skipped.push({ name: r.name || "(no name)", reason: "no phone or email" });
return;
}
const values = {
"MemberId": r.memberId,
"Member Id": r.memberId,
"Member Name": r.name,
"Name": r.name,
"Phone": r.phone,
"Email": r.email,
"Sent By": sentBy,
"Title": fillPlaceholders_(title, r, sentBy, scheduleLink),
"Message": fillPlaceholders_(message, r, sentBy, scheduleLink),
};
valueFors.push(header => values[header] || "");
});
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
result.queued = queueMessages_(SpreadsheetApp.getActiveSpreadsheet(), valueFors).length;
} finally {
lock.releaseLock();
}
return result;
}
// ---- Links.js ----------------------------------------------------------
/**
* The SWIM > Links sidebar: one place to open the Church websites and this
* sheet's pages (built from the Deployment ID and owner key).
*/
const CHURCH_LINKS = [
{
label: "Member Directory",
detail: "directory.churchofjesuschrist.org",
url: "https://directory.churchofjesuschrist.org/",
},
{
label: "Leader and Clerk Resources",
detail: "lcr.churchofjesuschrist.org",
url: "https://lcr.churchofjesuschrist.org/",
},
];
/**
* Returns the links for the sidebar, grouped under headings. Groups whose
* links aren't set up yet say what to do instead.
* @return {Array<{title: string, links: Array<{label: string, detail: string,
* url: string}>, missing: string}>}
*/
function getLinksView() {
const settings = getSettings();
const pages = {};
getPageUrls_(settings).forEach(link => { pages[link.id] = link; });
const entries = getAppointmentCalendars_(settings);
const noDeployment = "Deploy the web app (steps in SWIM > System > Settings) to make these links.";
function page(id, label, detail) {
const link = pages[id];
return link && { label: label, detail: detail, url: link.url };
}
const notes = page("notes", "View Notes",
"Notes from you and everyone under \"Notes I can read\". Opens the member in the " +
"selected row, if it has a member id.");
// Opening the link looks up the member in the active cell's row.
if (notes) notes.forMember = true;
const groups = [
{
title: "Church websites",
links: CHURCH_LINKS,
},
{
title: "Notes",
links: [notes],
missing: noDeployment,
},
{
title: "Appointments",
links: [
page("schedule", "Book an Appointment", entries.length > 1
? "Members use this to choose who to book a time with."
: "Members use this to book a time with you."),
].concat(entries.length > 1 ? entries.map(entry =>
page("schedule:" + entry.key, "Book with " + entry.name,
"Members use this to book a time with " + entry.name + ".")) : [], [
page("check-in", "Check In", "Members use this when they arrive."),
page("checkin-sign", "Print Check-In Sign", "A QR code sign that opens Check In."),
page("listen", "Listen for Check-Ins", "Plays a sound when someone checks in."),
], remindersLinks_(settings, entries)),
missing: noDeployment,
},
{
title: "Messages",
links: [
page("sms", "Send Messages", "Send the queued messages from your phone."),
],
missing: noDeployment,
},
{
title: "All links",
links: [
page("links", "Links Page", "These links on one page, to bookmark on your phone."),
page("links-light", "Links for Executive Secretaries",
"These links without View Notes or this spreadsheet. It can't open your notes."),
],
missing: noDeployment,
},
];
groups.forEach(group => { group.links = group.links.filter(link => link); });
return groups;
}
/**
* Returns a Text Reminders link for tomorrow's appointments on each
* appointment calendar, the same one the daily email sends. A reminders link
* only works for its own day, so these are made each time the sidebar opens.
* @param {Object} settings - As returned by getSettings.
* @param {Array<Object>} entries - From getAppointmentCalendars_.
* @return {Array<{label: string, detail: string, url: string}>} Empty
* without a Deployment ID.
*/
function remindersLinks_(settings, entries) {
// Apps Script's local time is the script's time zone.
const now = new Date();
const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
const timeZone = Session.getScriptTimeZone();
const day = Utilities.formatDate(tomorrow, timeZone, "yyyy-MM-dd");
const dayLabel = Utilities.formatDate(tomorrow, timeZone, "EEEE, MMMM d");
return entries.map(entry => ({
label: "Text Reminders" + (entries.length > 1 ? " for " + entry.name : ""),
detail: "Text a reminder to each person with an appointment tomorrow (" + dayLabel +
"). Works through that day.",
url: getRemindersUrl_(settings, entry, day),
})).filter(link => link.url);
}
const MEMBER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/**
* Returns the member id in the active cell's row, found under the column
* whose first-row header is "Member Id" (or "MemberId", "member_id", ...).
* @return {string} The member id, or "" when the row has none.
*/
function getActiveMemberId() {
const cell = SpreadsheetApp.getActiveSpreadsheet().getCurrentCell();
if (!cell || cell.getRow() < 2) return "";
const sheet = cell.getSheet();
const lastColumn = sheet.getLastColumn();
if (!lastColumn) return "";
const headers = sheet.getRange(1, 1, 1, lastColumn).getDisplayValues()[0];
const col = headers.findIndex(header =>
String(header).toLowerCase().replace(/[^a-z]/g, "") === "memberid");
if (col === -1) return "";
const id = String(sheet.getRange(cell.getRow(), col + 1).getDisplayValue()).trim();
return MEMBER_ID_PATTERN.test(id) ? id : "";
}
/**
* Opens the Links sidebar.
*/
function showLinks() {
const html = HtmlService.createHtmlOutput(`
<style>
body { font-family: Arial, sans-serif; font-size: 13px; line-height: 1.4;
color: #202124; margin: 0; padding: 12px; }
h3 { font-size: 13px; margin: 18px 0 6px; }
h3:first-child { margin-top: 0; }
.hint { color: #5f6368; font-size: 12px; margin: 2px 0 6px; }
.error { color: #c5221f; }
.link { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }
.link a { flex: 1; min-width: 0; display: block; padding: 6px 8px;
border: 1px solid #dadce0; border-radius: 6px; text-decoration: none;
color: #1a73e8; }
.link a:hover { background: #f1f6fe; border-color: #1a73e8; }
.link a b { display: block; }
.link a small { display: block; color: #5f6368; overflow-wrap: anywhere; }
.copy { flex: none; display: flex; align-items: center; justify-content: center;
width: 32px; height: 32px; padding: 0; border: none; border-radius: 6px;
background: #1a73e8; color: #fff; cursor: pointer; }
.copy:hover { background: #1765cc; }
.copy.copied { background: #137333; }
.copy svg { width: 18px; height: 18px; fill: currentColor; }
.copy:disabled { opacity: 0.6; cursor: default; }
.manual-copy { box-sizing: border-box; width: 100%; margin: 0 0 6px;
padding: 4px 6px; font-size: 12px; border: 1px solid #1a73e8; border-radius: 6px; }
</style>
<div id="links">Loading links…</div>
<script>
function el(id) { return document.getElementById(id); }
function addHint(parent, text) {
var hint = document.createElement("div");
hint.className = "hint";
hint.textContent = text;
parent.appendChild(hint);
}
// Copies text through a hidden text area; the clipboard API isn't
// reliably allowed inside the sidebar's frame.
// Returns false if the browser refused.
function copy(text) {
var area = document.createElement("textarea");
area.value = text;
area.style.position = "fixed";
area.style.opacity = "0";
document.body.appendChild(area);
area.select();
var copied = false;
try { copied = document.execCommand("copy"); } catch (e) {}
document.body.removeChild(area);
return copied;
}
// Returns url with "memberid" added to its query string, ahead of any
// "#" fragment.
function addMemberId(url, memberId) {
var hashAt = url.indexOf("#");
var base = hashAt === -1 ? url : url.slice(0, hashAt);
var hash = hashAt === -1 ? "" : url.slice(hashAt);
return base + (base.indexOf("?") === -1 ? "?" : "&") +
"memberid=" + encodeURIComponent(memberId) + hash;
}
// Calls back with url plus the active row's member id as a "memberid"
// query parameter, or url alone when the row has none.
function withMember(url, callback) {
google.script.run
.withSuccessHandler(function (memberId) {
callback(memberId ? addMemberId(url, memberId) : url);
})
.withFailureHandler(function () { callback(url); })
.getActiveMemberId();
}
var COPY_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>';
var CHECK_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>';
// Opens url for the active row's member. The tab is opened now, while
// the click still counts, and pointed at the page once the member id
// comes back.
function openForMember(url) {
var tab = window.open("", "_blank");
if (!tab) return true; // Blocked; let the link open without a member.
withMember(url, function (memberUrl) { tab.location.href = memberUrl; });
return false;
}
function buildLink(link) {
var row = document.createElement("div");
row.className = "link";
var a = document.createElement("a");
a.href = link.url;
a.target = "_blank";
a.rel = "noopener";
var label = document.createElement("b");
label.textContent = link.label;
var detail = document.createElement("small");
detail.textContent = link.detail;
a.appendChild(label);
a.appendChild(detail);
if (link.forMember) a.onclick = function () { return openForMember(link.url); };
row.appendChild(a);
var button = document.createElement("button");
button.className = "copy";
button.innerHTML = COPY_ICON;
button.title = "Copy link";
button.setAttribute("aria-label", "Copy " + link.label + " link");
// Shown when the browser won't copy after the member lookup, so the
// link can be copied by hand.
var manual = document.createElement("input");
manual.className = "manual-copy";
manual.readOnly = true;
manual.style.display = "none";
function copied() {
button.innerHTML = CHECK_ICON;
button.className = "copy copied";
button.title = "Copied";
setTimeout(function () {
button.innerHTML = COPY_ICON;
button.className = "copy";
button.title = "Copy link";
}, 2000);
}
button.onclick = function () {
manual.style.display = "none";
if (!link.forMember) {
copy(link.url);
copied();
return;
}
button.disabled = true;
withMember(link.url, function (memberUrl) {
button.disabled = false;
if (copy(memberUrl)) {
copied();
return;
}
manual.value = memberUrl;
manual.title = "Press Ctrl+C to copy";
manual.style.display = "";
manual.focus();
manual.select();
});
};
row.appendChild(button);
var wrapper = document.createElement("div");
wrapper.appendChild(row);
wrapper.appendChild(manual);
return wrapper;
}
function render(groups) {
var box = el("links");
box.innerHTML = "";
groups.forEach(function (group) {
var heading = document.createElement("h3");
heading.textContent = group.title;
box.appendChild(heading);
if (!group.links.length) {
addHint(box, group.missing);
return;
}
group.links.forEach(function (link) { box.appendChild(buildLink(link)); });
});
}
google.script.run
.withSuccessHandler(render)
.withFailureHandler(function (error) {
el("links").textContent = "Could not load links: " + error.message;
el("links").className = "error";
})
.getLinksView();
</script>
`).setTitle("Links");
SpreadsheetApp.getUi().showSidebar(html);
}
// ---- ReaderAccess.js ---------------------------------------------------
/**
* Reader Access: lets one SWIM read another SWIM's notes.
*
* The requester (A) emails an Access Authorization Code
* ("<A's Deployment ID>~<one-time request token>") to the grantor (B). B
* pastes it into SWIM > Reader Access > Grant Notes Access, which sends A a
* newly generated reader code. A keeps the code in grantedNoteAccess and
* sends it with each notes request; B keeps only its hash in
* authorizedNoteReaders. Access is one level deep: a reader gets B's own
* notes, never the notes B has been granted.
*/
const NOTE_REQUEST_LIFETIME_DAYS = 14;
const WEB_APP_BASE_URL = "https://script.google.com/macros/s/";
const READER_ACCESS_TITLE = "Reader Access";
/**
* Returns a long random secret (about 244 random bits).
*/
function newSecret_() {
return (Utilities.getUuid() + Utilities.getUuid()).replace(/-/g, "");
}
/**
* Returns the hex SHA-256 hash of a secret.
* @param {string} secret - The secret to hash.
*/
function hashSecret_(secret) {
return Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, String(secret),
Utilities.Charset.UTF_8)
.map(b => ((b + 256) % 256).toString(16).padStart(2, "0"))
.join("");
}
/**
* Returns the JSON array stored under a script property, or [] if it is
* missing or unreadable.
* @param {string} key - A SETTINGS key holding a JSON array.
*/
function readList_(key) {
try {
const list = JSON.parse(PropertiesService.getScriptProperties().getProperty(key) || "[]");
return Array.isArray(list) ? list : [];
} catch (error) {
return [];
}
}
/**
* Stores a JSON array under a script property, deleting it when empty.
* @param {string} key - A SETTINGS key.
* @param {Array} list - The list to store.
*/
function writeList_(key, list) {
setSetting_(key, list.length ? JSON.stringify(list) : "");
}
/**
* Runs fn while holding the script lock, so read-modify-write changes to the
* stored lists don't overwrite each other.
* @param {function(): *} fn - The work to do.
* @return {*} What fn returns.
*/
function withScriptLock_(fn) {
const lock = LockService.getScriptLock();
lock.waitLock(10000);
try {
return fn();
} finally {
lock.releaseLock();
}
}
/**
* Returns the owner key used in this sheet's own page links, creating it the
* first time.
*/
function getOwnerKey_() {
const props = PropertiesService.getScriptProperties();
let key = props.getProperty(SETTINGS.OWNER_KEY);
if (!key) {
key = newSecret_();
props.setProperty(SETTINGS.OWNER_KEY, key);
}
return key;
}
/**
* Returns true if key is this sheet's owner key. Compares hashes so the
* comparison doesn't depend on how much of the key matches.
* @param {string} key - The key sent with a request.
*/
function isOwnerKey_(key) {
const stored = PropertiesService.getScriptProperties().getProperty(SETTINGS.OWNER_KEY);
return Boolean(key && stored && hashSecret_(key) === hashSecret_(stored));
}
// The secretary key is in the executive secretaries' Links page link. It
// opens Send Messages, Listen for Check-Ins and Text Reminders, but not notes.
// It is made from the owner key, so resetting that key resets this one too.
const SECRETARY_KEY_LENGTH = 32;
/**
* Returns the secretary key made from an owner key: the first 32 characters
* of the web-safe base64 HMAC-SHA256 of "secretary". The Links page
* (links.html) makes it the same way to link to the secretaries' page.
* @param {string} ownerKey - The owner key.
*/
function secretaryKeyFrom_(ownerKey) {
const signature = Utilities.computeHmacSha256Signature("secretary", ownerKey);
return Utilities.base64EncodeWebSafe(signature).replace(/=+$/, "").slice(0, SECRETARY_KEY_LENGTH);
}
/**
* Returns the secretary key, creating the owner key the first time.
*/
function getSecretaryKey_() {
return secretaryKeyFrom_(getOwnerKey_());
}
/**
* Returns true if key is this sheet's secretary key. Compares hashes, like
* isOwnerKey_.
* @param {string} key - The key sent with a request.
*/
function isSecretaryKey_(key) {
const stored = PropertiesService.getScriptProperties().getProperty(SETTINGS.OWNER_KEY);
return Boolean(key && stored &&
hashSecret_(key) === hashSecret_(secretaryKeyFrom_(stored)));
}
/**
* Returns the error for a request whose owner key was refused, saying
* whether the key was missing, the wrong length (cut short or changed when
* the link was copied) or simply different (an old link, from before the key
* was reset). Says nothing about the stored key beyond its length.
* @param {string} key - The key sent with the request.
* @param {string} link - Which link to copy again, such as "the Send Messages
* link under Messages".
*/
function notAuthorizedMessage_(key, link) {
const stored = PropertiesService.getScriptProperties().getProperty(SETTINGS.OWNER_KEY);
key = String(key || "");
let reason;
if (!stored) {
reason = "This SWIM has no link key yet, so links made before now don't work.";
} else if (!key) {
reason = "This link has no key.";
} else if (key.length !== stored.length && key.length !== SECRETARY_KEY_LENGTH) {
reason = "The key in this link is " + key.length + " characters long instead of " +
stored.length + " (or " + SECRETARY_KEY_LENGTH + " in an executive secretary's " +
"link), so it was probably cut short or changed when it was copied.";
} else {
reason = "The key in this link doesn't match. The link was probably made before " +
"the key was reset.";
}
return "Not authorized. " + reason + " Copy " + link + " again from SWIM > Links.";
}
/**
* Returns true if readerCode belongs to someone this sheet has granted access
* and "Allow others to read my notes" is on.
* @param {string} readerCode - The code sent with a request.
*/
function isAuthorizedReader_(readerCode) {
if (!readerCode || !getSettings().allowNoteReaders) return false;
const hash = hashSecret_(readerCode);
return readList_(SETTINGS.AUTHORIZED_NOTE_READERS).some(reader => reader.codeHash === hash);
}
/**
* Returns the pending note requests that haven't expired.
*/
function livePendingRequests_() {
const cutoff = Date.now() - NOTE_REQUEST_LIFETIME_DAYS * 24 * 60 * 60 * 1000;
return readList_(SETTINGS.PENDING_NOTE_REQUESTS)
.filter(request => new Date(request.created).getTime() > cutoff);
}
/**
* Returns the live pending request with the given token, or null.
* @param {string} token - The request token from an Access Authorization Code.
*/
function findPendingRequest_(token) {
if (!token) return null;
return livePendingRequests_().find(request => request.token === String(token)) || null;
}
/**
* Splits an Access Authorization Code into its Deployment ID and request
* token. Ignores any whitespace picked up when copying it.
* @param {string} code - The pasted code.
* @return {{deploymentId: string, token: string}}
*/
function parseAccessCode_(code) {
const parts = String(code || "").replace(/\s+/g, "").split("~");
if (parts.length !== 2 || !DEPLOYMENT_ID_PATTERN.test(parts[0]) || parts[1].length < 32) {
throw new Error("That doesn't look like an Access Authorization Code. Copy the whole " +
"code from the request email and try again.");
}
return { deploymentId: parts[0], token: parts[1] };
}
/**
* Returns UrlFetchApp request options for a POST to another SWIM's web app.
* @param {string} deploymentId - The other SWIM's Deployment ID.
* @param {Object<string, string>} params - The form fields to send.
*/
function swimRequest_(deploymentId, params) {
return {
url: WEB_APP_BASE_URL + encodeURIComponent(deploymentId) + "/exec",
method: "post",
payload: params,
muteHttpExceptions: true,
};
}
/**
* Parses another SWIM's JSON response.
* @param {HTTPResponse} response - The response.
* @throws {Error} If the response isn't JSON.
*/
function parseSwimResponse_(response) {
const status = response.getResponseCode();
try {
return JSON.parse(response.getContentText());
} catch (error) {
throw new Error(status === 200
? "its SWIM sent back an unexpected response (its web app may need updating)"
: "its SWIM returned an error (" + status + ")");
}
}
/**
* POSTs to another SWIM's web app and returns its parsed response.
* @param {string} deploymentId - The other SWIM's Deployment ID.
* @param {Object<string, string>} params - The form fields to send.
*/
function callSwim_(deploymentId, params) {
const request = swimRequest_(deploymentId, params);
return parseSwimResponse_(UrlFetchApp.fetch(request.url, request));
}
/**
* Escapes text for use in HTML.
* @param {string} text - The text to escape.
*/
function htmlEscape_(text) {
return String(text).replace(/[&<>"']/g, c =>
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
}
/* ---------------------------------------------------------------------------
* Menu: Request Notes Access (run by the requester)
* ------------------------------------------------------------------------- */
/**
* Asks for an email address, records a pending request and emails that
* person an Access Authorization Code with instructions for granting access.
*/
function requestNotesAccess() {
const ui = SpreadsheetApp.getUi();
const title = "Request Notes Access";
const settings = getSettings();
if (!settings.deploymentId) {
ui.alert(title, "Your web app must be deployed first. Open SWIM > System > Settings and follow " +
"the steps under Web app Deployment ID.", ui.ButtonSet.OK);
return;
}
const ownerName = getOwnerName_();
if (!ownerName) return;
const response = ui.prompt(title,
"Enter the email address of the person whose notes you'd like to read. They'll get an " +
"email explaining how to grant you access.",
ui.ButtonSet.OK_CANCEL);
if (response.getSelectedButton() !== ui.Button.OK) return;
const email = response.getResponseText().trim();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
ui.alert(title, '"' + email + '" isn\'t a valid email address. No request was sent.',
ui.ButtonSet.OK);
return;
}
if (MailApp.getRemainingDailyQuota() < 1) {
ui.alert(title, "You've reached today's email limit. Try again tomorrow.", ui.ButtonSet.OK);
return;
}
const token = newSecret_();
withScriptLock_(() => {
const pending = livePendingRequests_();
pending.push({ token: token, email: email, created: new Date().toISOString() });
writeList_(SETTINGS.PENDING_NOTE_REQUESTS, pending);
});
try {
sendNotesRequestEmail_(email, ownerName, settings.deploymentId + "~" + token);
} catch (error) {
removePendingRequest_(request => request.token === token);
ui.alert(title, "The request email could not be sent: " + error.message, ui.ButtonSet.OK);
return;
}
ui.alert(title, "Your request was sent to " + email + ". When they grant it, their " +
"notes will appear on your View Notes page and they'll be listed under Notes access in " +
"SWIM > System > Settings. The request expires in " + NOTE_REQUEST_LIFETIME_DAYS + " days.",
ui.ButtonSet.OK);
}
/**
* Emails the Access Authorization Code and grant instructions.
* @param {string} email - The grantor's email address.
* @param {string} ownerName - The requester's name.
* @param {string} code - The Access Authorization Code.
*/
function sendNotesRequestEmail_(email, ownerName, code) {
const name = htmlEscape_(ownerName);
const htmlBody = `
<div style="font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5; max-width: 560px;">
<p>${name} is asking for permission to read the notes you record in your SWIM
(Singles Ward Information Manager) spreadsheet.</p>
<p style="border: 1px solid #f3c7c4; background: #fce8e6; border-radius: 4px; padding: 8px 12px;">
<b>Important:</b> if you grant this request, ${name} will be able to read
<b>all</b> of your notes, not just some of them. Do not grant access if your
notes contain confidential information.</p>
<p>To grant access:</p>
<ol>
<li>Open your SWIM spreadsheet.</li>
<li>Choose <b>SWIM > Reader Access > Grant Notes Access</b>.</li>
<li>Copy the Access Authorization Code below and paste it into the box.</li>
</ol>
<p style="margin-bottom: 4px;"><b>Access Authorization Code</b></p>
<div style="font-family: monospace; font-size: 15px; padding: 12px; border: 1px solid #ccc;
border-radius: 4px; background: #f8f9fa; word-break: break-all;">${htmlEscape_(code)}</div>
<p style="color: #5f6368; font-size: 12px;">The code works once and expires in
${NOTE_REQUEST_LIFETIME_DAYS} days. You can revoke access at any time in
SWIM > System > Settings. If you weren't expecting this request, ignore this email.</p>
</div>`;
const body =
ownerName + " is asking for permission to read the notes you record in your SWIM " +
"(Singles Ward Information Manager) spreadsheet.\n\n" +
"IMPORTANT: if you grant this request, " + ownerName + " will be able to read ALL of " +
"your notes. Do not grant access if your notes contain confidential information.\n\n" +
"To grant access, open your SWIM spreadsheet, choose SWIM > Reader Access > Grant " +
"Notes Access, and paste this Access Authorization Code:\n\n" + code + "\n\n" +
"The code works once and expires in " + NOTE_REQUEST_LIFETIME_DAYS + " days.";
MailApp.sendEmail({
to: email,
subject: ownerName + " is asking to read your SWIM notes",
body: body,
htmlBody: htmlBody,
name: ownerName,
});
}
/**
* Removes the pending requests matching a test.
* @param {function(Object): boolean} test - Returns true for requests to remove.
*/
function removePendingRequest_(test) {
withScriptLock_(() => {
writeList_(SETTINGS.PENDING_NOTE_REQUESTS,
livePendingRequests_().filter(request => !test(request)));
});
}
/* ---------------------------------------------------------------------------
* Menu: Grant Notes Access (run by the grantor)
* ------------------------------------------------------------------------- */
/**
* Throws unless this sheet can grant access: sharing allowed, web app
* deployed and a name set.
* @return {Object} The settings.
*/
function requireCanGrant_() {
const settings = getSettings();
if (!settings.allowNoteReaders) {
throw new Error('"Allow others to read my notes" is off in SWIM > System > Settings.');
}
if (!settings.deploymentId) {
throw new Error("Deploy your web app first (see SWIM > System > Settings).");
}
if (!settings.ownerName) {
throw new Error('Enter "Your name" in SWIM > System > Settings first.');
}
return settings;
}
/**
* Asks the requester's SWIM who sent an Access Authorization Code.
* @param {string} code - The pasted code.
* @return {{name: string, email: string}}
*/
function checkNotesRequest(code) {
const settings = requireCanGrant_();
const parsed = parseAccessCode_(code);
if (parsed.deploymentId === settings.deploymentId) {
throw new Error("That code came from your own SWIM.");
}
let data;
try {
data = callSwim_(parsed.deploymentId,
{ mode: "describe-notes-request", requestToken: parsed.token });
} catch (error) {
throw new Error("Could not reach the requester's SWIM: " + error.message);
}
if (!data || !data.success) {
throw new Error(data && data.error === "invalid-request"
? "This code has already been used, has expired or was cancelled. Ask the person to " +
"send a new request."
: "The requester's SWIM said: " + ((data && data.error) || "unknown error"));
}
return { name: String(data.name || ""), email: String(data.email || "") };
}
/**
* Grants the sender of an Access Authorization Code read access to this
* sheet's notes: records the hash of a new reader code, then sends the code
* to the requester's SWIM. Undoes the record if the requester's SWIM doesn't
* accept it.
* @param {string} code - The pasted code.
* @return {{name: string, email: string}} Who was granted access.
*/
function grantNotesAccess(code) {
const settings = requireCanGrant_();
const parsed = parseAccessCode_(code);
const requester = checkNotesRequest(code);
const readerCode = newSecret_();
const reader = {
name: requester.name || requester.email,
email: requester.email,
codeHash: hashSecret_(readerCode),
granted: new Date().toISOString(),
};
withScriptLock_(() => {
const readers = readList_(SETTINGS.AUTHORIZED_NOTE_READERS);
readers.push(reader);
writeList_(SETTINGS.AUTHORIZED_NOTE_READERS, readers);
});
let data;
try {
data = callSwim_(parsed.deploymentId, {
mode: "accept-notes-access",
requestToken: parsed.token,
deploymentId: settings.deploymentId,
readerCode: readerCode,
name: settings.ownerName,
});
if (!data || !data.success) {
throw new Error(data && data.error === "invalid-request"
? "the code has already been used, has expired or was cancelled"
: (data && data.error) || "unknown error");
}
} catch (error) {
removeNoteReader_(reader.codeHash);
throw new Error("Access was not granted: " + error.message);
}
// The requester's SWIM reports its "Your name" setting.
const name = String(data.name || "").trim();
if (name && name !== reader.name) {
withScriptLock_(() => {
writeList_(SETTINGS.AUTHORIZED_NOTE_READERS,
readList_(SETTINGS.AUTHORIZED_NOTE_READERS).map(r =>
r.codeHash === reader.codeHash ? Object.assign({}, r, { name: name }) : r));
});
reader.name = name;
}
return { name: reader.name, email: reader.email };
}
/**
* Removes a reader from authorizedNoteReaders.
* @param {string} codeHash - The hash of the reader's code.
*/
function removeNoteReader_(codeHash) {
withScriptLock_(() => {
writeList_(SETTINGS.AUTHORIZED_NOTE_READERS,
readList_(SETTINGS.AUTHORIZED_NOTE_READERS).filter(r => r.codeHash !== codeHash));
});
}
/**
* Opens the Grant Notes Access dialog.
*/
function showGrantNotesAccess() {
const settings = getSettings();
const blocked = !settings.allowNoteReaders
? 'Your SWIM doesn\'t allow others to read your notes. If your notes aren\'t ' +
'confidential, you can turn on "Allow others to read my notes" in Settings.'
: !settings.deploymentId
? "Your web app must be deployed before you can grant access. See SWIM > System > Settings for the steps."
: !settings.ownerName
? 'Enter "Your name" in Settings before granting access.'
: "";
const html = HtmlService.createHtmlOutput(`
<style>
body { font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5; }
textarea { width: 100%; box-sizing: border-box; font-family: monospace; font-size: 12px; }
.warning { border: 1px solid #f3c7c4; background: #fce8e6; border-radius: 4px;
padding: 8px 12px; }
.who { border: 1px solid #c6dafc; background: #e8f0fe; border-radius: 4px;
padding: 8px 12px; margin-top: 10px; }
.error { color: #c5221f; }
.ok { color: #137333; }
.buttons { text-align: right; margin-top: 14px; }
</style>
<p class="warning"><b>Read this first.</b> Pasting an Access Authorization Code gives
the person who sent it permission to read <b>all</b> of your notes. Don't grant
access unless that person has a valid reason to read them.</p>
<div id="blocked" class="error" style="display: none;"></div>
<div id="form">
<label for="code"><b>Access Authorization Code</b></label>
<textarea id="code" rows="3" spellcheck="false" oninput="codeChanged()"></textarea>
<div id="who" class="who" style="display: none;"></div>
<div id="status"></div>
</div>
<div class="buttons">
<button id="cancelBtn" onclick="google.script.host.close()">Cancel</button>
<button id="settingsBtn" style="display: none;" onclick="openSettings()">Open Settings</button>
<button id="checkBtn" onclick="check()">Check code</button>
<button id="grantBtn" style="display: none;" onclick="grant()">Grant access</button>
</div>
<script>
var blocked = ${JSON.stringify(blocked)};
function el(id) { return document.getElementById(id); }
function setStatus(text, cls) {
el("status").textContent = text;
el("status").className = cls || "";
}
function setBusy(busy) {
el("checkBtn").disabled = busy;
el("grantBtn").disabled = busy;
el("code").disabled = busy;
}
function codeChanged() {
el("who").style.display = "none";
el("grantBtn").style.display = "none";
el("checkBtn").style.display = "";
setStatus("");
}
function openSettings() {
google.script.run.withSuccessHandler(function () {
google.script.host.close();
}).showSettings("notesAccess");
}
function check() {
setBusy(true);
setStatus("Checking\\u2026");
google.script.run
.withSuccessHandler(function (who) {
setBusy(false);
setStatus("");
el("who").textContent = "This request is from " + (who.name || "an unnamed SWIM") +
(who.email ? " (" + who.email + ")" : "") + ". Grant access only if you " +
"recognize this person and they have a valid reason to read your notes.";
el("who").style.display = "block";
el("checkBtn").style.display = "none";
el("grantBtn").style.display = "";
})
.withFailureHandler(function (error) {
setBusy(false);
setStatus(error.message, "error");
})
.checkNotesRequest(el("code").value);
}
function grant() {
setBusy(true);
setStatus("Granting access\\u2026");
google.script.run
.withSuccessHandler(function (reader) {
el("form").style.display = "none";
el("grantBtn").style.display = "none";
el("cancelBtn").textContent = "Close";
setStatus("");
var done = document.createElement("p");
done.className = "ok";
done.textContent = reader.name + " can now read your notes. You can revoke " +
"this at any time in SWIM > System > Settings.";
document.body.insertBefore(done, document.querySelector(".buttons"));
})
.withFailureHandler(function (error) {
setBusy(false);
setStatus(error.message, "error");
})
.grantNotesAccess(el("code").value);
}
if (blocked) {
el("blocked").textContent = blocked;
el("blocked").style.display = "block";
el("form").style.display = "none";
el("checkBtn").style.display = "none";
el("settingsBtn").style.display = "";
}
</script>
`).setWidth(480).setHeight(400);
SpreadsheetApp.getUi().showModalDialog(html, "Grant Notes Access");
}
/**
* Opens Settings at the Notes access section, where access can be revoked.
*/
function showRevokeNotesAccess() {
showSettings("notesAccess");
}
/* ---------------------------------------------------------------------------
* Settings sidebar actions
* ------------------------------------------------------------------------- */
/**
* Turns "Allow others to read my notes" on or off.
* @param {boolean} allow - The new value.
* @return {Object} The updated getSettingsView().
*/
function setAllowNoteReaders(allow) {
setSetting_(SETTINGS.ALLOW_NOTE_READERS, allow ? "yes" : "");
return getSettingsView();
}
/**
* Revokes a reader's access to this sheet's notes.
* @param {string} codeHash - The hash of the reader's code.
* @return {Object} The updated getSettingsView().
*/
function revokeNoteReader(codeHash) {
removeNoteReader_(codeHash);
return getSettingsView();
}
/**
* Stops reading another SWIM's notes and tells that SWIM to forget the
* reader code (best effort; it is removed here either way).
* @param {string} deploymentId - The other SWIM's Deployment ID.
* @return {Object} The updated getSettingsView().
*/
function removeGrantedNoteAccess(deploymentId) {
let removed = null;
withScriptLock_(() => {
const granted = readList_(SETTINGS.GRANTED_NOTE_ACCESS);
removed = granted.find(g => g.deploymentId === deploymentId) || null;
writeList_(SETTINGS.GRANTED_NOTE_ACCESS, granted.filter(g => g !== removed));
});
if (removed) {
try {
callSwim_(removed.deploymentId, { mode: "release-notes-access", readerCode: removed.code });
} catch (error) {
console.warn("Could not tell " + removed.name + "'s SWIM to remove access: " +
error.message);
}
}
return getSettingsView();
}
/**
* Cancels a pending note request so its code no longer works.
* @param {string} tokenHash - The hash of the request token.
* @return {Object} The updated getSettingsView().
*/
function cancelNoteRequest(tokenHash) {
removePendingRequest_(request => hashSecret_(request.token) === tokenHash);
return getSettingsView();
}
/**
* Returns the Notes access lists for the sidebar, without any secrets.
*/
function getNotesAccessView_(settings) {
return {
allow: settings.allowNoteReaders,
readers: readList_(SETTINGS.AUTHORIZED_NOTE_READERS).map(r => ({
name: r.name, email: r.email, granted: r.granted, id: r.codeHash,
})),
granted: readList_(SETTINGS.GRANTED_NOTE_ACCESS).map(g => ({
name: g.name, granted: g.granted, id: g.deploymentId,
})),
pending: livePendingRequests_().map(p => ({
email: p.email, created: p.created, id: hashSecret_(p.token),
})),
};
}
/* ---------------------------------------------------------------------------
* Web app modes (called from doPost)
* ------------------------------------------------------------------------- */
/**
* mode=describe-notes-request: tells a would-be grantor who is asking. Answers
* only for a live request token. The email is this sheet owner's Google
* account (the web app runs as the owner), so it can't be faked.
* @param {Object} params - Request parameters: requestToken.
*/
function describeNotesRequest_(params) {
if (!findPendingRequest_(params.requestToken)) {
return { success: false, error: "invalid-request" };
}
return {
success: true,
name: getSettings().ownerName,
email: Session.getEffectiveUser().getEmail(),
};
}
/**
* mode=accept-notes-access: stores the reader code a grantor's SWIM sends
* and uses up the request token.
* @param {Object} params - Request parameters: requestToken, deploymentId
* (the grantor's), readerCode, name (the grantor's).
*/
function acceptNotesAccess_(params) {
return withScriptLock_(() => {
const pending = livePendingRequests_();
const request = pending.find(r => r.token === String(params.requestToken || ""));
if (!request) return { success: false, error: "invalid-request" };
const deploymentId = String(params.deploymentId || "").trim();
const readerCode = String(params.readerCode || "").trim();
if (!DEPLOYMENT_ID_PATTERN.test(deploymentId) || readerCode.length < 32) {
return { success: false, error: "Missing or invalid deploymentId or readerCode" };
}
const granted = readList_(SETTINGS.GRANTED_NOTE_ACCESS)
.filter(g => g.deploymentId !== deploymentId);
granted.push({
name: String(params.name || "").trim() || request.email,
deploymentId: deploymentId,
code: readerCode,
granted: new Date().toISOString(),
});
writeList_(SETTINGS.GRANTED_NOTE_ACCESS, granted);
writeList_(SETTINGS.PENDING_NOTE_REQUESTS, pending.filter(r => r !== request));
return { success: true, name: getSettings().ownerName };
});
}
/**
* mode=release-notes-access: a reader no longer wants this sheet's notes.
* @param {Object} params - Request parameters: readerCode.
*/
function releaseNotesAccess_(params) {
if (!params.readerCode) return { success: false, error: "Missing readerCode" };
removeNoteReader_(hashSecret_(params.readerCode));
return { success: true };
}
/**
* mode=get-notes with readerCode: this sheet's own notes for a member, for
* an authorized reader's SWIM.
* @param {Object} params - Request parameters: readerCode, memberid.
*/
function getNotesForReader_(params) {
if (!isAuthorizedReader_(params.readerCode)) return { success: false, error: "revoked" };
const notes = getNotes(params.memberid);
return Array.isArray(notes) ? { notes: notes } : notes;
}
/**
* mode=get-notes with the owner key: this sheet's notes for a member plus the
* notes of every SWIM in grantedNoteAccess, fetched in parallel.
* @param {string} memberId - The Member Id to match.
* @return {{notes: Object[], errors: string[]}} errors describes each source
* that couldn't be read.
*/
function getAllNotes_(memberId) {
const own = getNotes(memberId);
if (!Array.isArray(own)) return own;
const sources = readList_(SETTINGS.GRANTED_NOTE_ACCESS);
const requests = sources.map(source => swimRequest_(source.deploymentId,
{ mode: "get-notes", readerCode: source.code, memberid: String(memberId) }));
let notes = own;
const errors = [];
fetchEach_(requests).forEach((result, i) => {
const name = sources[i].name;
try {
if (result.error) throw result.error;
const data = parseSwimResponse_(result.response);
if (data && Array.isArray(data.notes)) {
notes = notes.concat(data.notes);
} else if (data && data.error === "revoked") {
errors.push(name + " no longer shares notes with you");
} else {
throw new Error((data && data.error) || "unexpected response");
}
} catch (error) {
errors.push("Could not load notes from " + name + ": " + error.message);
}
});
return { notes: notes, errors: errors };
}
/**
* Fetches requests in parallel. If that fails outright (fetchAll throws when
* any one request can't be made), fetches them one at a time so one bad
* source doesn't hide the others.
* @param {Object[]} requests - UrlFetchApp request objects.
* @return {Array<{response: HTTPResponse}|{error: Error}>} One per request.
*/
function fetchEach_(requests) {
if (!requests.length) return [];
try {
return UrlFetchApp.fetchAll(requests).map(response => ({ response: response }));
} catch (error) {
return requests.map(request => {
try {
return { response: UrlFetchApp.fetch(request.url, request) };
} catch (fetchError) {
return { error: fetchError };
}
});
}
}
// ---- Settings.js -------------------------------------------------------
/**
* Script Properties keys for the settings edited in the SWIM > System > Settings
* sidebar. Code that runs when files load (such as the ingest form specs in
* Code.js) uses these key strings directly, since SETTINGS may not be defined
* yet at that point.
*/
const SETTINGS = {
OWNER_NAME: "OWNER_NAME",
DEPLOYMENT_ID: "DEPLOYMENT_ID",
// Retired: JSON array of Deployment IDs from the old Configuration sheet,
// kept only so the sidebar can say they need to grant access again.
OTHER_DEPLOYMENT_IDS: "OTHER_DEPLOYMENT_IDS",
MESSAGE_FORM_LINK: "MESSAGE_FORM_LINK",
NOTES_FORM_LINK: "NOTES_FORM_LINK",
CONFIG_SHEET_MIGRATED: "CONFIG_SHEET_MIGRATED",
// Reader Access (see ReaderAccess.js).
OWNER_KEY: "OWNER_KEY", // Secret in this sheet's own page links.
ALLOW_NOTE_READERS: "ALLOW_NOTE_READERS", // "yes" lets others be granted access.
PENDING_NOTE_REQUESTS: "pendingNoteRequests", // JSON [{token, email, created}]
AUTHORIZED_NOTE_READERS: "authorizedNoteReaders", // JSON [{name, email, codeHash, granted}]
GRANTED_NOTE_ACCESS: "grantedNoteAccess", // JSON [{name, deploymentId, code, granted}]
// Appointments (see Appointments.js).
APPOINTMENT_TYPES: "APPOINTMENT_TYPES", // JSON [{label, minutes}]
APPOINTMENT_NOTE: "APPOINTMENT_NOTE", // Added to every appointment's description.
APPOINTMENT_ADDRESS: "APPOINTMENT_ADDRESS", // Every appointment's location.
// Calendar (see Calendar.js).
// JSON [{key, name, calendarId, availabilityTitle, types, note, address,
// reminderEmail}], one per appointment calendar. Once saved, it replaces the
// single-calendar settings above and below, which earlier versions used.
APPOINTMENT_CALENDARS: "APPOINTMENT_CALENDARS",
APPOINTMENT_CALENDAR_ID: "APPOINTMENT_CALENDAR_ID", // Blank means the primary calendar.
AVAILABILITY_TITLE: "AVAILABILITY_TITLE", // Title of the events members book inside.
REMINDER_EMAIL: "REMINDER_EMAIL", // Gets tomorrow's appointments each morning.
// ID of the spreadsheet these properties belong to; a copy that finds a
// different ID clears them (see Template.js).
SETTINGS_SHEET_ID: "SETTINGS_SHEET_ID",
};
/**
* Cells of the old "Configuration" sheet that settings are copied from the
* first time they are read. The sheet itself is never changed.
*/
const CONFIG_SHEET_NAME = "Configuration";
const CONFIG_SHEET_CELLS = {
OWNER_NAME: "C4",
MESSAGE_FORM_LINK: "C6",
NOTES_FORM_LINK: "C8",
DEPLOYMENT_ID: "C10",
OTHER_DEPLOYMENT_IDS: "C12",
};
const DEPLOYMENT_ID_PATTERN = /^[A-Za-z0-9_-]{20,}$/;
/**
* Returns the settings as a plain object, first copying any values from the
* old "Configuration" sheet if that hasn't been done yet.
* @return {{ownerName: string, deploymentId: string,
* otherDeploymentIds: string[], messageFormLink: string,
* notesFormLink: string,
* allowNoteReaders: boolean,
* appointmentTypes: Array<{label: string, minutes: number}>,
* appointmentNote: string, appointmentAddress: string,
* appointmentCalendarId: string, availabilityTitle: string,
* reminderEmail: string, appointmentCalendars: Array<Object>}}
* Use getAppointmentCalendars_ rather than the single-calendar values.
*/
function getSettings() {
resetSettingsIfCopied_();
const props = PropertiesService.getScriptProperties();
let stored = props.getProperties();
if (!stored[SETTINGS.CONFIG_SHEET_MIGRATED]) {
migrateConfigSheet_(props, stored);
stored = props.getProperties();
}
return {
ownerName: stored[SETTINGS.OWNER_NAME] || "",
deploymentId: stored[SETTINGS.DEPLOYMENT_ID] || "",
otherDeploymentIds: parseStoredIds_(stored[SETTINGS.OTHER_DEPLOYMENT_IDS]),
messageFormLink: stored[SETTINGS.MESSAGE_FORM_LINK] || "",
notesFormLink: stored[SETTINGS.NOTES_FORM_LINK] || "",
allowNoteReaders: stored[SETTINGS.ALLOW_NOTE_READERS] === "yes",
appointmentTypes: parseAppointmentTypes_(stored[SETTINGS.APPOINTMENT_TYPES]),
appointmentNote: stored[SETTINGS.APPOINTMENT_NOTE] || "",
appointmentAddress: stored[SETTINGS.APPOINTMENT_ADDRESS] || "",
appointmentCalendarId: stored[SETTINGS.APPOINTMENT_CALENDAR_ID] || "",
availabilityTitle: stored[SETTINGS.AVAILABILITY_TITLE] || DEFAULT_AVAILABILITY_TITLE,
reminderEmail: stored[SETTINGS.REMINDER_EMAIL] || "",
appointmentCalendars: parseAppointmentCalendars_(stored[SETTINGS.APPOINTMENT_CALENDARS]),
};
}
/**
* Returns the stored APPOINTMENT_TYPES value as an array, skipping any
* entries without a name or a positive length.
* @param {string} value - A JSON array, or blank.
*/
function parseAppointmentTypes_(value) {
try {
return cleanAppointmentTypes_(JSON.parse(value || "[]"));
} catch (error) {
return [];
}
}
/**
* Returns the appointment types in a parsed array, skipping any without a
* name or a positive length.
* @param {*} types - Should be an array of {label, minutes}.
*/
function cleanAppointmentTypes_(types) {
if (!Array.isArray(types)) return [];
return types
.map(t => ({ label: String(t.label || "").trim(), minutes: Number(t.minutes) }))
.filter(t => t.label && t.minutes > 0);
}
/**
* Returns the stored APPOINTMENT_CALENDARS value as an array, skipping any
* entries without a key.
* @param {string} value - A JSON array, or blank.
*/
function parseAppointmentCalendars_(value) {
let entries;
try {
entries = JSON.parse(value || "[]");
} catch (error) {
return [];
}
if (!Array.isArray(entries)) return [];
return entries
.filter(e => e && e.key)
.map(e => ({
key: String(e.key),
name: String(e.name || ""),
calendarId: String(e.calendarId || ""),
availabilityTitle: String(e.availabilityTitle || "") || DEFAULT_AVAILABILITY_TITLE,
types: cleanAppointmentTypes_(e.types),
note: String(e.note || ""),
address: String(e.address || ""),
reminderEmail: String(e.reminderEmail || ""),
}));
}
/**
* Copies the non-blank values of the old "Configuration" sheet into any
* settings that are still blank, then marks the migration done. Leaves the
* sheet as it is.
* @param {Properties} props - The script properties.
* @param {Object} stored - The properties as currently stored.
*/
function migrateConfigSheet_(props, stored) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (!ss) return; // Not running from the spreadsheet; try again next time.
const updates = {};
const sheet = ss.getSheetByName(CONFIG_SHEET_NAME);
if (sheet) {
Object.keys(CONFIG_SHEET_CELLS).forEach(key => {
if (stored[key]) return;
const value = sheet.getRange(CONFIG_SHEET_CELLS[key]).getDisplayValue().trim();
if (!value) return;
if (key === SETTINGS.OTHER_DEPLOYMENT_IDS) {
const ids = splitIds_(value);
if (ids.length) updates[key] = JSON.stringify(ids);
} else {
updates[key] = value;
}
});
}
updates[SETTINGS.CONFIG_SHEET_MIGRATED] = new Date().toISOString();
props.setProperties(updates);
}
/**
* Splits text into Deployment IDs on commas and whitespace, dropping blanks
* and duplicates.
* @param {string} text - The IDs as typed or stored on the old sheet.
*/
function splitIds_(text) {
const ids = String(text || "").split(/[\s,]+/).filter(id => id);
return ids.filter((id, i) => ids.indexOf(id) === i);
}
/**
* Returns the stored OTHER_DEPLOYMENT_IDS value as an array.
* @param {string} value - A JSON array, or blank.
*/
function parseStoredIds_(value) {
if (!value) return [];
try {
const ids = JSON.parse(value);
if (Array.isArray(ids)) return ids.map(String);
} catch (error) {
// Not JSON; fall through and treat it as a typed list.
}
return splitIds_(value);
}
/**
* Writes settings, deleting any whose value is blank.
* @param {Object<string, *>} values - SETTINGS keys and their new values.
*/
function writeSettings_(values) {
const props = PropertiesService.getScriptProperties();
const toSet = {};
Object.keys(values).forEach(key => {
const value = values[key] === null || values[key] === undefined ? "" : String(values[key]);
if (value) {
toSet[key] = value;
} else {
props.deleteProperty(key);
}
});
if (Object.keys(toSet).length) props.setProperties(toSet);
}
/**
* Sets one setting; a blank value deletes it.
* @param {string} key - A SETTINGS key.
* @param {string} value - The new value.
*/
function setSetting_(key, value) {
writeSettings_({ [key]: value });
}
/**
* Takes a Deployment ID as typed or pasted. A pasted web app URL
* (".../macros/s/<Deployment ID>/exec") is reduced to its Deployment ID.
* @param {string} text
* @return {string}
*/
function parseDeploymentId_(text) {
const value = String(text || "").trim();
const match = value.match(/\/macros\/s\/([A-Za-z0-9_-]+)/);
return match ? match[1] : value;
}
/**
* Throws unless deploymentId is blank or looks like a Deployment ID.
* @param {string} deploymentId - As returned by parseDeploymentId_.
*/
function validateDeploymentId_(deploymentId) {
if (deploymentId && !DEPLOYMENT_ID_PATTERN.test(deploymentId)) {
throw new Error('"' + deploymentId + '" doesn\'t look like a Deployment ID. ' +
"It should be a long string of letters, digits, - and _.");
}
}
/**
* Steps for deploying the web app, shown in the Settings sidebar and the
* Setup dialog. Each page fills in the .editorLink hrefs.
*/
const DEPLOY_STEPS_HTML = `
<ol>
<li><a class="editorLink" href="#" target="_blank">Open SWIM's script editor</a>
(or choose <b>Extensions > Apps Script</b>).</li>
<li>At the top right, click the blue <b>Deploy</b> button, then
<b>New deployment</b>.</li>
<li>Next to <b>Select type</b>, click the gear icon and choose <b>Web app</b>.</li>
<li>Check that <b>Execute as</b> is <b>Me</b> and <b>Who has access</b> is
<b>Anyone</b>. (Not "Anyone with Google account".)</li>
<li>Click <b>Deploy</b>. If Google asks you to authorize access, choose your
account, click <b>Advanced</b>, then the <b>Go to…</b> link, then
<b>Allow</b>.</li>
<li>Under <b>Deployment ID</b>, click <b>Copy</b>, then click <b>Done</b>.</li>
<li>Come back here, paste it in the <b>Deployment ID</b> box and click
<b>Save</b>.</li>
</ol>`;
/**
* The unsaved-changes bar shared by the Settings, Calendar and Compose Messages
* sidebars. A sidebar shows it by giving body the "dirty" class; its Save
* button calls the sidebar's save().
*/
const UNSAVED_BAR_CSS = `
#unsaved { position: fixed; left: 0; right: 0; top: 0; z-index: 1; display: none;
align-items: center; gap: 8px; padding: 8px 12px; background: #fef7e0;
border-bottom: 1px solid #f9d77e; font-size: 12px; }
#unsaved span { flex: 1; }
body.dirty { padding-top: 52px; }
body.dirty #unsaved { display: flex; }`;
const UNSAVED_BAR_HTML = `
<div id="unsaved">
<span><b>Unsaved changes.</b> Click Save before closing this panel.</span>
<button id="unsavedSaveBtn" onclick="save()">Save</button>
</div>`;
/**
* Validates appointment type rows as edited in the Calendar sidebar. Rows
* with no name and no length are ignored.
* @param {Array<{label: string, minutes: string}>} rows - The rows.
* @return {Array<{label: string, minutes: number}>}
*/
function parseAppointmentTypeRows_(rows) {
const types = (rows || [])
.map(t => ({ label: String(t.label || "").trim(), minutes: String(t.minutes || "").trim() }))
.filter(t => t.label || t.minutes)
.map(t => {
const minutes = Number(t.minutes);
if (!t.label) throw new Error("Each appointment type needs a name.");
if (!(minutes > 0) || Math.floor(minutes) !== minutes) {
throw new Error('The length of "' + t.label + '" must be a whole number of minutes.');
}
return { label: t.label, minutes: minutes };
});
const labels = types.map(t => t.label.toLowerCase());
const repeated = labels.find((label, i) => labels.indexOf(label) !== i);
if (repeated) throw new Error('There are two appointment types named "' + repeated + '".');
return types;
}
/**
* Validates and saves the editable settings from the sidebar. Appointment
* settings are saved from the Calendar sidebar instead (saveCalendarSettings).
* @param {{ownerName: string, deploymentId: string}} values - The new values.
* @return {Object} The updated getSettingsView().
*/
function saveSettings(values) {
const ownerName = String(values.ownerName || "").trim();
const deploymentId = parseDeploymentId_(values.deploymentId);
validateDeploymentId_(deploymentId);
writeSettings_({
[SETTINGS.OWNER_NAME]: ownerName,
[SETTINGS.DEPLOYMENT_ID]: deploymentId,
});
return getSettingsView();
}
/**
* Returns the page links, or [] when there is no Deployment ID. Private links
* carry "<Deployment ID>~<owner key>" after "#", so the key is never sent to
* the page's server or passed on as a referrer. Public links, for members,
* carry only the Deployment ID.
* @param {Object} settings - As returned by getSettings.
* @return {Array<{id: string, label: string, detail: string, url: string,
* shared: (boolean|undefined)}>} shared is true for the public links.
*/
function getPageUrls_(settings) {
if (!settings.deploymentId) return [];
// With several appointment calendars, "schedule" lets members choose who
// to meet with, and "schedule:<key>" books with one of them.
const entries = getAppointmentCalendars_(settings);
const publicToken = "?token=" + encodeURIComponent(settings.deploymentId);
const privateToken = "#token=" + encodeURIComponent(settings.deploymentId) + "~" +
getOwnerKey_();
return [
{
id: "sms",
label: "Send Messages",
detail: "Use this to send the queued messages from your phone. Keep it private: " +
"it opens your message queue.",
url: PAGES_BASE_URL + "sms.html" + privateToken,
},
{
id: "notes",
label: "View Notes",
detail: "Use this to view your notes and the notes of everyone listed under " +
"\"Notes I can read\". Keep it private: it opens your notes.",
url: PAGES_BASE_URL + "interview-notes.html" + privateToken,
},
{
id: "listen",
label: "Listen for Check-Ins",
detail: "Plays a sound and shows the name when someone checks in. SWIM > Links " +
"opens it. Keep it private: it shows who is arriving.",
url: PAGES_BASE_URL + "listen.html" + privateToken,
},
{
id: "links",
label: "Links",
detail: "All of these links on one page, to bookmark on your phone. Keep it " +
"private: it holds your private links.",
// The page links to the spreadsheet from its id.
url: PAGES_BASE_URL + "links.html" + privateToken + "&sheet=" +
encodeURIComponent(SpreadsheetApp.getActiveSpreadsheet().getId()),
},
{
id: "links-light",
label: "Links for Executive Secretaries",
detail: "These links without View Notes or this spreadsheet, so an executive " +
"secretary can send messages and text reminders. It can't open your notes.",
url: PAGES_BASE_URL + "links-light.html#token=" +
encodeURIComponent(settings.deploymentId) + "~" + getSecretaryKey_(),
},
{
id: "schedule",
label: "Schedule an Appointment",
detail: entries.length > 1
? "Share this with members so they can choose who to book a time with."
: "Share this with members so they can book a time with you.",
url: getScheduleUrl_(settings, ""),
shared: true,
},
].concat(entries.length > 1 ? entries.map(entry => ({
id: "schedule:" + entry.key,
label: "Schedule with " + entry.name,
detail: "Share this with members so they can book a time with " + entry.name + ".",
url: getScheduleUrl_(settings, entry.key),
shared: true,
})) : [], [
{
id: "check-in",
label: "Check In",
detail: "Members use this to let you know they've arrived for an appointment.",
url: PAGES_BASE_URL + "check-in.html" + publicToken,
shared: true,
},
{
id: "checkin-sign",
label: "Print Check-In Sign",
detail: "Prints a sign with a QR code that opens Check In, for anyone or for one person.",
url: PAGES_BASE_URL + "checkin-page.html" + publicToken,
},
]);
}
/**
* Returns the "Schedule an Appointment" page link for an appointment
* calendar, or "" when there is no Deployment ID. Without a key, members
* choose who to meet with when there are several calendars.
* @param {Object} settings - As returned by getSettings.
* @param {string} key - The appointment calendar's key, or blank.
*/
function getScheduleUrl_(settings, key) {
if (!settings.deploymentId) return "";
return PAGES_BASE_URL + "schedule.html?token=" + encodeURIComponent(settings.deploymentId) +
(key ? "&cal=" + encodeURIComponent(key) : "");
}
/**
* Replaces the owner key, so page links built before now stop working.
* @return {Object} The updated getSettingsView().
*/
function resetOwnerKey() {
setSetting_(SETTINGS.OWNER_KEY, newSecret_());
return getSettingsView();
}
/**
* Forgets the Deployment IDs carried over from the old Configuration sheet.
* @return {Object} The updated getSettingsView().
*/
function clearOldDeploymentIds() {
setSetting_(SETTINGS.OTHER_DEPLOYMENT_IDS, "");
return getSettingsView();
}
/**
* Returns the settings plus the Notes access lists, for the sidebar.
*/
function getSettingsView() {
const settings = getSettings();
return Object.assign({}, settings, {
scriptEditorUrl: "https://script.google.com/d/" + ScriptApp.getScriptId() + "/edit",
notesAccess: getNotesAccessView_(settings),
});
}
/**
* Opens the Settings sidebar.
* @param {string} [section] - Id of a section to scroll to, such as
* "notesAccess".
*/
function showSettings(section) {
const initialSection = typeof section === "string" ? section : "";
const html = HtmlService.createHtmlOutput(`
<style>
body { font-family: Arial, sans-serif; font-size: 13px; line-height: 1.4;
color: #202124; margin: 0; padding: 12px; }
h3 { font-size: 13px; margin: 20px 0 2px; }
h3.first { margin-top: 0; }
.hint { color: #5f6368; font-size: 12px; margin: 2px 0 6px; }
input[type=text], input[type=number], textarea { width: 100%; box-sizing: border-box; font: inherit;
padding: 4px 6px; }
textarea { resize: vertical; }
.row { display: flex; justify-content: flex-end; align-items: center; gap: 8px;
margin-top: 6px; }
.status { font-size: 12px; flex: 1; }
.ok { color: #137333; }
.error { color: #c5221f; }
.steps { border: 1px solid #d2e3fc; background: #e8f0fe; border-radius: 4px;
padding: 6px 8px; margin-top: 6px; font-size: 12px; }
.steps li { margin-bottom: 3px; }
.notice { border: 1px solid #f3c7c4; background: #fce8e6; border-radius: 4px;
padding: 6px 8px; margin-top: 6px; font-size: 12px; }
details { margin-top: 6px; font-size: 12px; }
summary { cursor: pointer; color: #1a73e8; }
ol { padding-left: 18px; margin: 6px 0; }
hr { border: none; border-top: 1px solid #e0e0e0; margin: 16px 0 0; }
h4 { font-size: 12px; margin: 14px 0 2px; color: #3c4043; }
label.check { display: flex; gap: 6px; align-items: flex-start; margin-top: 4px; }
.item { display: flex; align-items: center; gap: 8px; padding: 4px 0;
border-bottom: 1px solid #eee; }
.item div { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.item small { color: #5f6368; }
${UNSAVED_BAR_CSS}
</style>
${UNSAVED_BAR_HTML}
<div id="loading">Loading settings…</div>
<div id="main" style="display: none;">
<h3 class="first">Your name</h3>
<div class="hint">Used as "Sent By" on messages and "Interviewer" on notes. The
ingestion forms fill it in, so rebuild them after changing it.</div>
<input type="text" id="ownerName" oninput="changed()">
<h3>Web app Deployment ID</h3>
<div class="hint">Identifies this spreadsheet's web app. Your links in SWIM > Links
are built from it.</div>
<input type="text" id="deploymentId" spellcheck="false" oninput="changed()">
<div id="firstDeploy" class="steps">
<b>Deploy your web app (one time, about 2 minutes)</b>
${DEPLOY_STEPS_HTML}
<div class="hint">Pasting the Web app URL instead works too.</div>
</div>
<details id="updateDeploy">
<summary>After updating SWIM, update your web app</summary>
<div class="hint">Your web app keeps running the code it was deployed with
until you do this. Your Deployment ID and links stay the same.</div>
<ol>
<li><a class="editorLink" href="#" target="_blank">Open SWIM's script editor</a>.</li>
<li>Click <b>Deploy</b>, then <b>Manage deployments</b>.</li>
<li>Click the pencil icon (<b>Edit</b>) at the top right of the dialog.</li>
<li>Under <b>Version</b>, choose <b>New version</b>.</li>
<li>Click <b>Deploy</b>, then <b>Done</b>.</li>
</ol>
<div class="hint">Don't use <b>New deployment</b> for this: it makes a new
Deployment ID, and your old links would stop working.</div>
</details>
<div class="hint">Appointment settings are in SWIM > Calendar.</div>
<div class="row">
<span id="saveStatus" class="status"></span>
<button id="saveBtn" onclick="save()">Save</button>
</div>
<hr>
<h3 id="notesAccess">Notes access</h3>
<div id="oldIds" class="notice" style="display: none;">
<span id="oldIdsText"></span>
<div class="row"><button onclick="act('clearOldDeploymentIds')">Clear</button></div>
</div>
<label class="check">
<input type="checkbox" id="allowReaders" onchange="act('setAllowNoteReaders', this.checked)">
<span>Allow others to read my notes</span>
</label>
<div class="hint">Leave this off if your notes are confidential. While it's off,
no one can be granted access and everyone under "People who can read my notes"
is blocked.</div>
<h4>People who can read my notes</h4>
<div id="readers"></div>
<h4>Notes I can read</h4>
<div id="granted"></div>
<h4>Pending requests</h4>
<div id="pending"></div>
<div class="row"><span id="accessStatus" class="status"></span></div>
<div class="hint">Use SWIM > Reader Access to request or grant access.</div>
<div id="resetKey">
<h4>Link key</h4>
<div class="hint">Your private links in SWIM > Links (Send Messages, View Notes,
Listen, Links pages) include this key or are made from it, as are the Text
Reminders links in the daily appointment emails. If one has been shared by mistake, reset
the key. Links made before the reset stop working.</div>
<div class="row">
<span id="keyStatus" class="status"></span>
<button id="resetKeyBtn">Reset key</button>
</div>
</div>
</div>
<script>
var dirty = false;
var initialSection = ${JSON.stringify(initialSection)};
function el(id) { return document.getElementById(id); }
function setStatus(id, text, cls) {
el(id).textContent = text;
el(id).className = "status " + (cls || "");
}
function setBusy(busy) {
el("saveBtn").disabled = busy;
el("unsavedSaveBtn").disabled = busy;
}
// Marks the fields above Save as edited, showing the unsaved-changes bar.
function setDirty(value) {
dirty = value;
document.body.className = value ? "dirty" : "";
}
function changed() {
setDirty(true);
setStatus("saveStatus", "");
}
// Asks before the panel closes with unsaved edits. Browsers may skip
// this for a sidebar, so the bar above is the main reminder.
window.addEventListener("beforeunload", function (event) {
if (!dirty) return;
event.preventDefault();
event.returnValue = "";
});
function render(view) {
el("loading").style.display = "none";
el("main").style.display = "block";
el("ownerName").value = view.ownerName;
el("deploymentId").value = view.deploymentId;
Array.prototype.forEach.call(document.querySelectorAll(".editorLink"), function (a) {
a.href = view.scriptEditorUrl;
});
el("firstDeploy").style.display = view.deploymentId ? "none" : "block";
el("updateDeploy").style.display = view.deploymentId ? "" : "none";
el("resetKey").style.display = view.deploymentId ? "" : "none";
renderNotesAccess(view);
setDirty(false);
}
function formatDate(value) {
var date = new Date(value);
return isNaN(date.getTime()) ? "" : date.toLocaleDateString();
}
function renderNotesAccess(view) {
var access = view.notesAccess;
var oldCount = view.otherDeploymentIds.length;
el("oldIds").style.display = oldCount ? "block" : "none";
el("oldIdsText").textContent = oldCount + " Deployment ID" + (oldCount === 1 ? "" : "s") +
" from the old Configuration sheet no longer share notes. Ask each interviewer to " +
"grant you access again: use SWIM > Reader Access > Request Notes Access.";
el("allowReaders").checked = access.allow;
renderItems("readers", access.readers, "No one can read your notes.", "Revoke",
"revokeNoteReader", function (r) {
return [r.name, (r.email ? r.email + " \\u00b7 " : "") + "since " + formatDate(r.granted)];
});
renderItems("granted", access.granted, "You aren't reading anyone else's notes.",
"Remove", "removeGrantedNoteAccess", function (g) {
return [g.name, "since " + formatDate(g.granted)];
});
renderItems("pending", access.pending, "No pending requests.", "Cancel",
"cancelNoteRequest", function (p) {
return [p.email, "sent " + formatDate(p.created)];
});
}
// Lists items with a button that runs a server action on item.id. The
// button asks for a second click to confirm.
function renderItems(containerId, items, emptyText, buttonLabel, action, describe) {
var box = el(containerId);
box.innerHTML = "";
if (!items.length) {
addHint(box, emptyText);
return;
}
items.forEach(function (item) {
var lines = describe(item);
var row = document.createElement("div");
row.className = "item";
var text = document.createElement("div");
var name = document.createElement("b");
name.textContent = lines[0];
var detail = document.createElement("small");
detail.textContent = lines[1];
text.appendChild(name);
text.appendChild(document.createElement("br"));
text.appendChild(detail);
var button = document.createElement("button");
button.textContent = buttonLabel;
confirmButton(button, buttonLabel, function () { act(action, item.id); });
row.appendChild(text);
row.appendChild(button);
box.appendChild(row);
});
}
// Makes button run onConfirm only on a second click within 5 seconds.
function confirmButton(button, label, onConfirm) {
var timer = null;
button.onclick = function () {
if (timer) {
clearTimeout(timer);
timer = null;
button.textContent = label;
onConfirm();
return;
}
button.textContent = "Click to confirm";
timer = setTimeout(function () {
timer = null;
button.textContent = label;
}, 5000);
};
}
// Runs a Notes access action that returns the updated settings view.
// Only that section is redrawn, so unsaved edits above are kept.
function act(action, arg) {
setStatus("accessStatus", "Saving\\u2026");
google.script.run
.withSuccessHandler(function (view) {
renderNotesAccess(view);
setStatus("accessStatus", "Saved.", "ok");
})
.withFailureHandler(function (error) {
setStatus("accessStatus", error.message, "error");
})[action](arg);
}
confirmButton(el("resetKeyBtn"), "Reset key", function () {
setStatus("keyStatus", "Resetting\\u2026");
google.script.run
.withSuccessHandler(function () {
setStatus("keyStatus", "New key made. Copy your links again from SWIM > Links.", "ok");
})
.withFailureHandler(function (error) {
setStatus("keyStatus", error.message, "error");
})
.resetOwnerKey();
});
function addHint(parent, text) {
var hint = document.createElement("div");
hint.className = "hint";
hint.textContent = text;
parent.appendChild(hint);
}
function save() {
setBusy(true);
setStatus("saveStatus", "Saving\\u2026");
google.script.run
.withSuccessHandler(function (view) {
setBusy(false);
render(view);
setStatus("saveStatus", "Saved.", "ok");
})
.withFailureHandler(function (error) {
setBusy(false);
setStatus("saveStatus", error.message, "error");
})
.saveSettings({
ownerName: el("ownerName").value,
deploymentId: el("deploymentId").value
});
}
google.script.run
.withSuccessHandler(function (view) {
render(view);
if (initialSection && el(initialSection)) el(initialSection).scrollIntoView();
})
.withFailureHandler(function (error) {
el("loading").textContent = "Could not load settings: " + error.message;
el("loading").className = "error";
})
.getSettingsView();
</script>
`).setTitle("Settings");
SpreadsheetApp.getUi().showSidebar(html);
}
// ---- Template.js -------------------------------------------------------
/**
* Builds a shareable SWIM template from this working copy, and keeps copies
* of a SWIM spreadsheet from inheriting the original's settings.
*
* makeTemplate() is run by hand from the Apps Script editor; it is not on the
* SWIM menu. The template it makes offers to initialize and share itself the
* first time it is opened.
*/
/** Sheets whose header row is kept in the template and data rows cleared. */
const TEMPLATE_CLEARED_SHEETS = ["messagesToSend", "messagesSent", "Log", DIRECTORY_SHEET_NAME];
/**
* The landing page sheet. It is kept in the template unchanged and is always
* moved back to the first tab (see keepLandingSheetFirst_).
*/
const LANDING_SHEET_NAME = "SWIM";
/**
* Developer metadata key marking a template that makeTemplate made and that
* hasn't been initialized and shared yet.
*/
const TEMPLATE_PENDING_KEY = "SWIM_TEMPLATE_PENDING";
/**
* Settings that are not ward-specific and so are carried into the template
* as starting values for whoever copies it.
*/
const TEMPLATE_KEPT_SETTINGS = ["APPOINTMENT_TYPES"];
/**
* Developer metadata key holding the kept settings as a JSON object. It stays
* with the spreadsheet through later copies, and each copy starts its own
* settings from it (see stampSettingsOwner_).
*/
const TEMPLATE_DEFAULTS_KEY = "SWIM_TEMPLATE_DEFAULTS";
/**
* Blogger feed of the tools.ysaward.org "message-templates" page, whose body
* is a JSON array of generic message templates
* ([{messageName, messageText, type?}]). Initializing a template replaces the
* working copy's own (personal) templates with these.
*/
const GENERIC_TEMPLATES_FEED_URL =
"https://tools.ysaward.org/feeds/pages/default/6831485531462497852?alt=json";
/**
* True if this spreadsheet is a template made by makeTemplate that hasn't
* been initialized and shared yet.
*/
function isPendingTemplate_() {
try {
return SpreadsheetApp.getActiveSpreadsheet().createDeveloperMetadataFinder()
.withKey(TEMPLATE_PENDING_KEY).find().length > 0;
} catch (error) {
return false;
}
}
/**
* Replaces the message templates with the generic ones from
* tools.ysaward.org, clears any settings this template inherited (then
* restores the kept ones from the template's defaults), records the current
* date and time as its version (see TEMPLATE_VERSION_KEY), makes it viewable
* by anyone with the link, and removes its pending-template marker so copies made from
* it are ordinary SWIM spreadsheets. Refuses to run anywhere else, so it can
* never wipe or share a working SWIM spreadsheet.
* @return {string} The link that gives whoever opens it their own copy.
*/
function initializeTemplate() {
if (!isPendingTemplate_()) {
throw new Error("This spreadsheet is not a new template made by makeTemplate, " +
"so it was not changed.");
}
const ss = SpreadsheetApp.getActiveSpreadsheet();
// Before sharing, swap the personal message templates for the generic ones.
// If they can't be loaded this stops here, leaving the template unshared.
replaceMessageTemplates_(ss, getGenericMessageTemplates_());
PropertiesService.getScriptProperties().deleteAllProperties();
stampSettingsOwner_();
// The template's code is the dev code as of now, so copies of it should be
// offered only releases published after this.
stampTemplateVersion_(ss);
DriveApp.getFileById(ss.getId())
.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
ss.createDeveloperMetadataFinder().withKey(TEMPLATE_PENDING_KEY).find()
.forEach(metadata => metadata.remove());
try {
addSwimMenu_();
} catch (error) {
// The SWIM menu appears the next time the spreadsheet is opened.
}
return ss.getUrl().replace(/\/edit.*$/, "/copy");
}
/**
* Reads the generic message templates from GENERIC_TEMPLATES_FEED_URL.
* @return {Array<{title: string, message: string, type: string}>} type is ""
* when the page doesn't give one.
*/
function getGenericMessageTemplates_() {
const response = UrlFetchApp.fetch(GENERIC_TEMPLATES_FEED_URL, { muteHttpExceptions: true });
if (response.getResponseCode() !== 200) {
throw new Error("Could not load the generic message templates (HTTP " +
response.getResponseCode() + " from " + GENERIC_TEMPLATES_FEED_URL + ").");
}
let items;
try {
items = JSON.parse(JSON.parse(response.getContentText()).entry.content.$t);
} catch (error) {
throw new Error("The generic message templates page isn't a valid JSON list: " +
error.message);
}
if (!Array.isArray(items)) {
throw new Error("The generic message templates page isn't a JSON list.");
}
return items
.map(item => ({
title: String(item.messageName || "").trim(),
message: String(item.messageText || ""),
type: item.type ? normalizeTemplateType_(item.type) : "",
}))
.filter(template => template.title);
}
/**
* Replaces every row of the "messageTemplates" sheet with templates. A
* template without a type keeps the type of the existing row with the same
* title (such as "Interview Notes" being a Note), else is a Message.
* @param {Spreadsheet} ss - The spreadsheet.
* @param {Array<{title: string, message: string, type: string}>} templates
*/
function replaceMessageTemplates_(ss, templates) {
const existingTypes = {};
getMessageTemplates_().forEach(t => { existingTypes[t.title.toLowerCase()] = t.type; });
const sheet = getMessageTemplatesSheet_(ss);
deleteDataRows_(sheet);
if (!templates.length) return;
const values = templates.map(t => [t.title, t.message,
t.type || existingTypes[t.title.toLowerCase()] || TEMPLATE_TYPE_MESSAGE]);
// Write as plain text so a message starting with "=" isn't read as a formula.
sheet.getRange(2, 1, values.length, MESSAGE_TEMPLATE_HEADERS.length)
.setNumberFormat("@").setValues(values);
}
/**
* SWIM Template > Initialize and share. Running from the menu lets Google ask
* for authorization, which the dialog's button cannot do.
*/
function initializeTemplateFromMenu() {
showInitializeTemplateDialog(initializeTemplate());
}
/**
* Shows the "Initialize and share" dialog, or, given shareLink, the dialog
* already showing that link.
* @param {string=} shareLink - The template's copy link, once initialized.
*/
function showInitializeTemplateDialog(shareLink) {
const html = HtmlService.createHtmlOutput(
'<div style="font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5;">' +
'<div id="start">' +
'<p>This is a new SWIM template. Initializing replaces the message templates ' +
'with the generic ones, clears the settings copied from the original ' +
'spreadsheet and makes this template viewable by anyone with the link.</p>' +
'<button id="go" onclick="initialize()">Click to initialize and share</button>' +
'<p id="error" style="color: #b00020;"></p>' +
'</div>' +
'<div id="done" style="display: none;">' +
'<p>The template is ready. Share this link; it gives whoever opens it ' +
'their own copy:</p>' +
'<input id="link" readonly style="width: 100%; box-sizing: border-box;">' +
'<p><button onclick="copyLink()">Copy link</button> <span id="copied"></span></p>' +
'</div>' +
'<div style="text-align: right; margin-top: 16px;">' +
'<button onclick="google.script.host.close()">Close</button>' +
'</div>' +
'</div>' +
'<script>' +
'function showLink(link) {' +
'document.getElementById("start").style.display = "none";' +
'document.getElementById("done").style.display = "block";' +
'document.getElementById("link").value = link;' +
'}' +
'function initialize() {' +
'document.getElementById("go").disabled = true;' +
'document.getElementById("error").textContent = "Working...";' +
'google.script.run' +
'.withSuccessHandler(showLink)' +
'.withFailureHandler(function (error) {' +
'document.getElementById("go").disabled = false;' +
'document.getElementById("error").textContent = error.message + ' +
'" If Google has not authorized this template yet, use the menu ' +
'SWIM Template > Initialize and share instead.";' +
'})' +
'.initializeTemplate();' +
'}' +
'function copyLink() {' +
'var input = document.getElementById("link");' +
'var done = function () { document.getElementById("copied").textContent = "Copied"; };' +
'var fallback = function () { input.select(); document.execCommand("copy"); done(); };' +
'if (navigator.clipboard) {' +
'navigator.clipboard.writeText(input.value).then(done, fallback);' +
'} else { fallback(); }' +
'}' +
(shareLink ? 'showLink(' + JSON.stringify(shareLink) + ');' : '') +
'</script>'
).setWidth(460).setHeight(260);
SpreadsheetApp.getUi().showModalDialog(html, "SWIM Template");
}
/**
* Moves the landing sheet (LANDING_SHEET_NAME) to the first tab if it exists
* and isn't there already, leaving the previously active sheet active.
* @param {Spreadsheet} ss - The spreadsheet.
*/
function keepLandingSheetFirst_(ss) {
const landing = ss.getSheetByName(LANDING_SHEET_NAME);
if (!landing || landing.getIndex() === 1) return;
const active = ss.getActiveSheet();
ss.setActiveSheet(landing);
ss.moveActiveSheet(1);
if (active && active.getSheetId() !== landing.getSheetId()) ss.setActiveSheet(active);
}
/**
* Moves a partly cleaned template to the trash, along with any forms that
* were copied with it, so a copy still holding ward data (and possibly this
* spreadsheet's settings) isn't left behind. Forms belonging to the working
* spreadsheet are never touched. Best effort: problems are only logged.
* @param {Spreadsheet} copy - The partial template.
* @param {string[]} originalFormIds - IDs of the working spreadsheet's forms.
*/
function discardFailedTemplate_(copy, originalFormIds) {
copy.getSheets().forEach(sheet => {
const formId = linkedFormId(sheet);
if (!formId || originalFormIds.indexOf(formId) !== -1) return;
try {
DriveApp.getFileById(formId).setTrashed(true);
} catch (error) {
console.warn("Could not trash copied form " + formId + ": " + error.message);
}
});
try {
DriveApp.getFileById(copy.getId()).setTrashed(true);
} catch (error) {
console.warn("Could not trash the partial template " + copy.getUrl() + ": " +
error.message);
}
}
/**
* Deletes every row below the header row. Sheets refuses to delete all of a
* sheet's unfrozen rows, so a blank row is added first when needed.
* @param {Sheet} sheet - The sheet.
*/
function deleteDataRows_(sheet) {
const lastRow = sheet.getLastRow();
if (lastRow < 2) return;
if (lastRow >= sheet.getMaxRows()) sheet.insertRowAfter(lastRow);
sheet.deleteRows(2, lastRow - 1);
}
/**
* Deletes sheet, first adding an empty "Sheet1" if it is the last one.
* @param {Spreadsheet} ss - The spreadsheet holding the sheet.
* @param {Sheet} sheet - The sheet to delete.
*/
function deleteSheetKeepingOne_(ss, sheet) {
if (ss.getSheets().length === 1) ss.insertSheet("Sheet1");
ss.deleteSheet(sheet);
}
/**
* Records the active spreadsheet as the owner of the script properties if no
* owner is recorded yet. When it does, it also fills in any blank settings
* from defaults saved by makeTemplate, so a copy of a template starts with
* the template's appointment types.
*/
function stampSettingsOwner_() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (!ss) return;
const props = PropertiesService.getScriptProperties();
if (props.getProperty(SETTINGS.SETTINGS_SHEET_ID)) return;
const updates = { [SETTINGS.SETTINGS_SHEET_ID]: ss.getId() };
const defaults = getTemplateDefaults_(ss);
Object.keys(defaults).forEach(key => {
if (TEMPLATE_KEPT_SETTINGS.indexOf(key) !== -1 && !props.getProperty(key)) {
updates[key] = defaults[key];
}
});
props.setProperties(updates);
}
/**
* Returns the settings makeTemplate saved on this spreadsheet, or {} if none.
* @param {Spreadsheet} ss - The spreadsheet.
*/
function getTemplateDefaults_(ss) {
try {
const found = ss.createDeveloperMetadataFinder().withKey(TEMPLATE_DEFAULTS_KEY).find();
return found.length ? JSON.parse(found[0].getValue() || "{}") : {};
} catch (error) {
return {};
}
}
/**
* Deletes every script property if they were recorded as belonging to a
* different spreadsheet, meaning this spreadsheet is a copy and must not use
* the original's settings (its owner key, deployment, reader grants, ...).
* Then records this spreadsheet as the owner.
*/
function resetSettingsIfCopied_() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (!ss) return;
const props = PropertiesService.getScriptProperties();
const owner = props.getProperty(SETTINGS.SETTINGS_SHEET_ID);
if (owner && owner !== ss.getId()) {
props.deleteAllProperties();
}
stampSettingsOwner_();
}
// ---- Update.js ---------------------------------------------------------
/**
* Updates. A release is a single Code.gs, built by build.js from the files in
* src/ and published on UPDATE_PAGE_URL. Updating means pasting it over this
* copy's Code.gs and making a new version of the same web app deployment, so
* the Deployment ID and every link stay the same.
*
* build.js defines SWIM_VERSION at the top of Code.gs: "dev" in the working
* copy, or the release's date and time ("yyyy-MM-dd HH:mm"), which sorts in
* release order.
*/
/**
* The page with the current release: the blog's home page, which shows the
* newest release post (one post per page in the blog's settings).
*/
const UPDATE_PAGE_URL = "https://tools.ysaward.org/";
const CHECK_FOR_UPDATES_TITLE = "Check for Updates";
/**
* Script ID of the development copy. Copies of it (such as spreadsheets made
* from a template built by makeTemplate) also carry SWIM_VERSION "dev" but
* have their own script IDs, and are offered the published release.
*/
const DEV_SCRIPT_ID = "1RRLPxR4Matcuggibno0K14hg6zhODooDGJy2FRmUpFrBw3jHYjgUX0ie";
/**
* Developer metadata key holding the version of a template's dev code: the
* date and time it was initialized ("yyyy-MM-dd HH:mm", like a release). It
* stays with the spreadsheet through copies, so copies of the template are
* offered only releases published after it.
*/
const TEMPLATE_VERSION_KEY = "SWIM_TEMPLATE_VERSION";
/**
* The release this copy is running, or "" for dev code. Dev code in a copy of
* an initialized template uses the template's version instead.
* @return {string}
*/
function currentReleaseVersion_() {
const version = typeof SWIM_VERSION === "undefined" ? "dev" : String(SWIM_VERSION);
return version === "dev" ? getTemplateVersion_() : version;
}
/**
* Returns the version initializeTemplate saved on this spreadsheet, or "".
*/
function getTemplateVersion_() {
try {
const found = SpreadsheetApp.getActiveSpreadsheet().createDeveloperMetadataFinder()
.withKey(TEMPLATE_VERSION_KEY).find();
return found.length ? String(found[0].getValue() || "") : "";
} catch (error) {
return "";
}
}
/**
* Saves the current date and time as this spreadsheet's template version,
* replacing any version it inherited.
* @param {Spreadsheet} ss - The template.
*/
function stampTemplateVersion_(ss) {
ss.createDeveloperMetadataFinder().withKey(TEMPLATE_VERSION_KEY).find()
.forEach(metadata => metadata.remove());
ss.addDeveloperMetadata(TEMPLATE_VERSION_KEY,
Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm"),
SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT);
}
/**
* True if this is the development copy itself, not a copy of its code.
*/
function isDevelopmentCopy_() {
return !currentReleaseVersion_() && ScriptApp.getScriptId() === DEV_SCRIPT_ID;
}
/**
* Reads the current release's version and notes from UPDATE_PAGE_URL.
* @return {{version: string, notes: string}}
*/
function getPublishedRelease_() {
const response = UrlFetchApp.fetch(UPDATE_PAGE_URL, { muteHttpExceptions: true });
if (response.getResponseCode() !== 200) {
throw new Error("The update page couldn't be loaded (HTTP " +
response.getResponseCode() + ").");
}
const page = response.getContentText();
const version = page.match(/id="swim-version">([^<]*)</);
if (!version) throw new Error("The update page doesn't list a version.");
const notes = page.match(/id="swim-release-notes">([\s\S]*?)<\/div>/);
return {
version: htmlDecode_(version[1]).trim(),
notes: notes ? htmlDecode_(notes[1].replace(/<br\s*\/?>/gi, "\n")).trim() : "",
};
}
/**
* Turns the few entities build.js writes back into text.
* @param {string} html
*/
function htmlDecode_(html) {
return String(html)
.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"')
.replace(/'/g, "'").replace(/&/g, "&");
}
/**
* SWIM > System > Check for Updates. Compares this copy's version with the published
* one and, if there is a newer one, shows how to install it.
*/
function checkForUpdates() {
const ui = SpreadsheetApp.getUi();
if (isDevelopmentCopy_()) {
ui.alert(CHECK_FOR_UPDATES_TITLE, "This is the development copy. Releases are made " +
"from it with build.js --release, and it is never updated from one.",
ui.ButtonSet.OK);
return;
}
// A copy of dev code from a template made before templates recorded a
// version has none, so any release is newer.
const current = currentReleaseVersion_();
let release;
try {
release = getPublishedRelease_();
} catch (error) {
ui.alert(CHECK_FOR_UPDATES_TITLE, "Could not check for updates: " + error.message,
ui.ButtonSet.OK);
return;
}
if (current && release.version <= current) {
ui.alert(CHECK_FOR_UPDATES_TITLE, "SWIM is up to date (version " + current + ").",
ui.ButtonSet.OK);
return;
}
showUpdateSteps_(current || "unknown (copied from a template)", release);
}
/**
* Shows the steps for installing a newer release.
* @param {string} current - This copy's version.
* @param {{version: string, notes: string}} release - The published release.
*/
function showUpdateSteps_(current, release) {
const editorUrl = "https://script.google.com/d/" + ScriptApp.getScriptId() + "/edit";
const html = HtmlService.createHtmlOutput(`
<div style="font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5;">
<p>A new version of SWIM is available.<br>
Installed: ${htmlEscape_(current)}<br>Available: ${htmlEscape_(release.version)}</p>
${release.notes
? '<p style="white-space: pre-wrap;">' + htmlEscape_(release.notes) + "</p>"
: ""}
<p><b>To update</b> (your settings, sheets and links stay the same):</p>
<ol style="padding-left: 20px;">
<li>Open the <a href="${UPDATE_PAGE_URL}" target="_blank">SWIM home page</a> and
click <b>Copy code</b> under <b>Already using SWIM?</b></li>
<li>Open <a href="${editorUrl}" target="_blank">SWIM's script editor</a>.</li>
<li>Click <b>Code.gs</b>, select everything in it (Ctrl+A, or Cmd+A on a Mac),
paste (Ctrl+V or Cmd+V) and save (Ctrl+S or Cmd+S). If there are other files
besides Code.gs and appsscript.json, delete them.</li>
<li>Click <b>Deploy > Manage deployments</b>, click the pencil icon, choose
<b>New version</b> under Version, then click <b>Deploy</b>.</li>
<li>Reload this spreadsheet. <b>SWIM > System > About</b> should show the new version.</li>
</ol>
<div style="text-align: right; margin-top: 16px;">
<button onclick="google.script.host.close()">Close</button>
</div>
</div>
`).setWidth(500).setHeight(release.notes ? 480 : 400);
SpreadsheetApp.getUi().showModalDialog(html, CHECK_FOR_UPDATES_TITLE);
}