/**
* TaskNudge 1.0.0-beta.1: Telegram task reminders from a Google Sheet.
* MIT License.
*
* HOW TO INSTALL: in your Google Sheet open Extensions β Apps Script, replace everything
* in Code.gs with this whole file, add an HTML file named "Sidebar" (see Sidebar.html),
* save, reload the sheet, and use the menu π TaskNudge β Setup & status.
*
* This file is generated from src/ by "npm run build". Edit src/, not this file.
*/
/* ===== Config.js ===== */
/** @OnlyCurrentDoc */
/**
* TaskNudge: Telegram task reminders from a Google Sheet.
* MIT License. https://opensource.org/licenses/MIT
*
* @OnlyCurrentDoc above keeps the permission to "this spreadsheet only", so the
* install works without pasting appsscript.json (see D-019).
*
* All files of an Apps Script project share one global scope. Names that end
* in "_" are private helpers. Names without it are menu items, triggers or
* functions the setup sidebar calls.
*/
const TN = {
NAME: 'TaskNudge',
VERSION: '1.0.0-beta.1',
// Set this to your project page after you publish it (shown in the sidebar and Settings tab).
HELP_URL: 'https://github.com/farukEncoded/tasknudge/blob/main/docs/SETUP.md',
MENU: 'π TaskNudge',
TAB: { TASKS: 'Tasks', PEOPLE: 'People', SETTINGS: 'Settings', ACTIVITY: 'Activity' },
STATUS: ['Not started', 'In progress', 'Blocked', 'Done'],
HOW_OPTIONS: ['Smart', 'Once', 'Daily', 'Every 2 days', 'Weekly', 'Every 4 hours'],
REPEAT_OPTIONS: [
'Daily for 1 month', 'Daily for 2 months', 'Weekdays for 1 month', 'Daily, 10 times',
'Daily, 20 times', 'Every 2 days for 1 month', 'Weekly for 3 months', 'Monthly for 6 months',
],
TIME_OPTIONS: ['06:00', '07:00', '07:30', '08:00', '08:30', '09:00', '09:30', '10:00', '11:00', '12:00'],
STOP_OPTIONS: ['16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00'],
WORKDAY_OPTIONS: ['MonβFri', 'SunβThu', 'SatβThu', 'MonβSat', 'Every day'],
TRIGGER_MINUTES: [1, 5, 10, 15],
MAX_SERIES: 366, // most rows one "Repeat task" may create
MAX_SENDS: 60, // most messages one run sends (Telegram rate limits)
ACTIVITY_KEEP: 1000, // rows kept in the Activity tab
PROP: {
TOKEN: 'TN_TOKEN', BOT: 'TN_BOT', SHEET: 'TN_SHEET_ID', OFFSET: 'TN_OFFSET',
ALERTS_SINCE: 'TN_ALERTS_SINCE', LAST_TICK: 'TN_LAST_TICK', LAST_ERROR: 'TN_LAST_ERROR', COPY: 'TN_COPY',
WAKE: 'TN_WAKE', // the timer skips the sheet until this moment unless Telegram has news
},
FULL_RUN_MINUTES: 15, // the timer reads the whole sheet at least this often
};
/** Columns of the Tasks tab. They are found by header text, so users may reorder or add columns. */
const TASK_COLS = [
{ key: 'id', label: 'ID', width: 80, auto: true,
note: 'Filled in automatically: T-001, T-002 β¦ Repeat rows get T-001.2, T-001.3 β¦' },
{ key: 'task', label: 'Task', width: 300, wrap: true,
note: 'What needs to be done, in one or two lines.' },
{ key: 'person', label: 'Assigned to', width: 140,
note: 'Pick a person from the People tab.' },
{ key: 'due', label: 'Due', width: 120,
note: 'Due date. Double-click the cell for a calendar.' },
{ key: 'status', label: 'Status', width: 115,
note: 'Not started, In progress, Blocked or Done. Done stops reminders. People can also tap β
Done in Telegram.' },
{ key: 'notes', label: 'Notes', width: 220, wrap: true,
note: 'Optional. Sent along with the task.' },
{ key: 'repeat', label: 'Repeat task', width: 175,
note: 'Optional: the task happens again. Pick or type e.g. "Daily for 1 month", "Weekly, 10 times" or "Monthly until 2027-06-30". When you tick π Remind, one row is created for every time, each with its own due date.' },
{ key: 'remind', label: 'π Remind', width: 85,
note: 'Tick to send the task to the person on Telegram right now and start reminders. Untick to stop.' },
{ key: 'how', label: 'Remind how often', width: 140,
note: 'Smart = 3 days before, 1 day before, on the due day, then daily while overdue.\nOr pick Once, Daily, Every 2 days, Weekly, Every 4 hours, or type your own, e.g. "every 3 days" or "every 2 hours".' },
{ key: 'next', label: 'Next reminder', width: 200, auto: true,
note: 'Filled in automatically: when the next reminder goes out, or what is missing.' },
{ key: 'last', label: 'Last sent', width: 150, auto: true,
note: 'Filled in automatically.' },
{ key: 'state', label: '_state', width: 60, auto: true, hidden: true,
note: 'Used by TaskNudge. Please do not edit.' },
];
const PEOPLE_COLS = [
{ key: 'name', label: 'Name', width: 160,
note: 'One person per row. Use the same name in Tasks β Assigned to. Add yourself too if you want alerts.' },
{ key: 'tg', label: 'Telegram', width: 270, auto: true,
note: 'Filled in automatically. Shows β
once the person has connected.' },
{ key: 'link', label: 'Invite link', width: 340, auto: true,
note: 'Send this link to the person (WhatsApp, email, SMS β¦). They tap it and press Start in Telegram. Each link is personal.' },
{ key: 'code', label: '_code', width: 60, auto: true, hidden: true, note: 'Used by TaskNudge.' },
{ key: 'chat', label: '_chat', width: 60, auto: true, hidden: true, note: 'Used by TaskNudge.' },
];
const ACTIVITY_COLS = [
{ key: 'when', label: 'When', width: 140 },
{ key: 'task', label: 'Task', width: 90 },
{ key: 'person', label: 'Person', width: 140 },
{ key: 'what', label: 'What happened', width: 460 },
];
/** Rows of the Settings tab, found by the label in column A. */
const SETTINGS_ROWS = [
{ key: 'bot', label: 'Bot', def: 'Not connected', readOnly: true,
help: 'Connect it in the menu π TaskNudge β Setup & status.' },
{ key: 'sendAt', label: 'Send reminders at', def: '09:00', list: 'TIME_OPTIONS',
help: 'Smart, daily and weekly reminders go out at this time.' },
{ key: 'stopAt', label: 'Hourly reminders stop at', def: '18:00', list: 'STOP_OPTIONS',
help: 'Only for "every N hours" reminders: none after this time.' },
{ key: 'workDays', label: 'Work days', def: 'MonβFri', list: 'WORKDAY_OPTIONS',
help: 'Reminders only go out on these days. You can also type e.g. "Mon, Wed, Fri".' },
{ key: 'overdueDays', label: 'Stop overdue reminders after (days)', def: '14', list: ['3', '7', '14', '30'],
help: 'Smart and repeating reminders stop this many days after the due date.' },
{ key: 'alertsTo', label: 'Done & overdue alerts to', def: '', people: true,
help: 'Optional. A connected person (for example you) who gets a Telegram message when someone taps β
Done or a task becomes overdue. Leave empty for no alerts.' },
{ key: 'every', label: 'Check Telegram every (minutes)', def: '1', list: ['1', '5', '10', '15'],
help: 'How fast taps on Telegram buttons reach the sheet. 1 is best; use 5 or more for very big sheets.' },
{ key: 'paused', label: 'Pause all reminders', def: false, checkbox: true,
help: 'Tick to pause every reminder. Buttons and invite links keep working.' },
{ key: 'tz', label: 'Time zone', def: '', readOnly: true,
help: 'The sheet\'s time zone. Change it in File β Settings.' },
];
/** Lower-case letters and digits only: "π Remind" β "remind". */
function normKey_(s) {
return String(s == null ? '' : s).toLowerCase().replace(/[^a-z0-9]+/g, '');
}
/** How people's names are compared: trimmed, single spaces, case-insensitive. */
function normName_(s) {
return String(s == null ? '' : s).trim().replace(/\s+/g, ' ').toLowerCase();
}
function str_(v) {
return String(v == null ? '' : v).trim();
}
/* ===== Dates.js ===== */
/**
* Dates without time zones are "day keys": "2026-12-05".
* Turning a day key + time into a moment needs the sheet's time zone: see makeTz_().
*/
const DAY_MS = 86400000;
const DOW_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function pad2_(n) {
return (n < 10 ? '0' : '') + n;
}
function keyOf_(y, m, d) {
return y + '-' + pad2_(m) + '-' + pad2_(d);
}
function parseKey_(key) {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(key || ''));
return m ? { y: +m[1], m: +m[2], d: +m[3] } : null;
}
/** Days since 1970-01-01. */
function dayNum_(key) {
const p = parseKey_(key);
return Math.round(Date.UTC(p.y, p.m - 1, p.d) / DAY_MS);
}
function keyFromDayNum_(n) {
const d = new Date(n * DAY_MS);
return keyOf_(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
}
function addDays_(key, n) {
return keyFromDayNum_(dayNum_(key) + n);
}
/** a - b in days. */
function diffDays_(a, b) {
return dayNum_(a) - dayNum_(b);
}
/** 0 = Sunday β¦ 6 = Saturday. 1970-01-01 was a Thursday. */
function dowOf_(key) {
return (((dayNum_(key) + 4) % 7) + 7) % 7;
}
/** Adds months, keeping the anchor day where the month allows (Jan 31 β Feb 28 β Mar 31). */
function addMonths_(key, n, anchorDay) {
const p = parseKey_(key);
const total = p.y * 12 + (p.m - 1) + n;
const y = Math.floor(total / 12);
const m = total - y * 12;
const daysInMonth = new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
return keyOf_(y, m + 1, Math.min(anchorDay || p.d, daysInMonth));
}
/** "09:00", "9", "9.30", "9am", "6:30 pm" β minutes after midnight, or null. */
function parseTime_(v) {
const s = String(v == null ? '' : v).trim().toLowerCase();
const m = /^(\d{1,2})(?:[:.](\d{2}))?(?::\d{2})?\s*(am|pm)?$/.exec(s);
if (!m) return null;
let h = +m[1];
const mi = m[2] ? +m[2] : 0;
if (m[3]) {
if (h < 1 || h > 12) return null;
h = (h % 12) + (m[3] === 'pm' ? 12 : 0);
}
if (h > 23 || mi > 59) return null;
return h * 60 + mi;
}
function fmtTime_(min) {
return pad2_(Math.floor(min / 60)) + ':' + pad2_(min % 60);
}
/** "2027-01-31", "31 Jan 2027", "Jan 31 2027", "31 January" (next such date) β day key or null. */
function parseDateText_(text, todayKey) {
const s = String(text == null ? '' : text).trim().toLowerCase().replace(/,/g, ' ').replace(/\s+/g, ' ');
let m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(s);
if (m) return validKey_(+m[1], +m[2], +m[3]);
const month = function (word) {
const i = MONTH_NAMES.map(function (x) { return x.toLowerCase(); }).indexOf(String(word).slice(0, 3));
return i < 0 ? 0 : i + 1;
};
m = /^(\d{1,2})(?:st|nd|rd|th)? ([a-z]+)(?: (\d{4}))?$/.exec(s);
if (m && month(m[2])) return withYear_(+m[1], month(m[2]), m[3], todayKey);
m = /^([a-z]+) (\d{1,2})(?:st|nd|rd|th)?(?: (\d{4}))?$/.exec(s);
if (m && month(m[1])) return withYear_(+m[2], month(m[1]), m[3], todayKey);
return null;
}
function withYear_(d, mo, year, todayKey) {
if (year) return validKey_(+year, mo, d);
const t = parseKey_(todayKey) || { y: new Date().getUTCFullYear() };
const k = validKey_(t.y, mo, d);
if (k && todayKey && k < todayKey) return validKey_(t.y + 1, mo, d);
return k;
}
function validKey_(y, m, d) {
if (m < 1 || m > 12 || d < 1) return null;
const dim = new Date(Date.UTC(y, m, 0)).getUTCDate();
return d > dim ? null : keyOf_(y, m, d);
}
/**
* Time zone helper built on Utilities.formatDate, cached so a run with many
* rows stays fast.
* tz.parts(ms) β { key: "2026-12-05", min: 540, off: 360 }
* tz.ms(key, minutes) β the moment that is `minutes` after local midnight of `key`
*/
function makeTz_(name) {
const partsCache = {};
const msCache = {};
function parts(ms) {
const minute = Math.floor(ms / 60000);
if (partsCache[minute]) return partsCache[minute];
const s = Utilities.formatDate(new Date(minute * 60000), name, "yyyy-MM-dd'T'HH:mm:ssZ");
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):\d{2}([+-])(\d{2})(\d{2})$/.exec(s);
if (!m) throw new Error('Unexpected date format from Utilities.formatDate: ' + s);
const r = { key: m[1], min: +m[2] * 60 + +m[3], off: (m[4] === '-' ? -1 : 1) * (+m[5] * 60 + +m[6]) };
partsCache[minute] = r;
return r;
}
function ms(key, minutes) {
const ck = key + '|' + minutes;
if (msCache[ck] != null) return msCache[ck];
const p = parseKey_(key);
const guess = Date.UTC(p.y, p.m - 1, p.d) + minutes * 60000;
let t = guess - parts(guess).off * 60000;
t = guess - parts(t).off * 60000; // second pass settles daylight-saving changes
msCache[ck] = t;
return t;
}
return {
name: name,
parts: parts,
ms: ms,
key: function (x) { return parts(x).key; },
};
}
/* ===== Engine.js ===== */
/**
* One run: read Telegram (optional), update People, create repeat rows,
* send what is due, and write back the Next / Last sent columns.
* Callers hold the script lock.
*/
/**
* @param {Object} opts { poll: boolean, sendRows: number[] (force a reminder), seriesRow: number (create repeats without π) }
* @return {Object} the run context (results in ctx.results)
*/
function runEngine_(opts) {
opts = opts || {};
const ss = SpreadsheetApp.getActive();
const ctx = makeCtx_(ss);
if (!ss.getSheetByName(TN.TAB.TASKS) || !ss.getSheetByName(TN.TAB.PEOPLE)) return ctx;
loadPeople_(ctx);
if (ctx.token && opts.poll) pollTelegram_(ctx, opts.updates);
syncPeople_(ctx);
processTasks_(ctx, opts);
flushLog_(ctx);
saveWake_(ctx);
return ctx;
}
/** Remembers the earliest moment something may need sending (see tick's fast path). */
function noteWake_(ctx, at) {
if (at != null && at < ctx.wake) ctx.wake = at;
}
function saveWake_(ctx) {
const wake = ctx.tokenBad ? Infinity : ctx.wake;
props_().setProperty(TN.PROP.WAKE, String(Math.min(wake, ctx.now + TN.FULL_RUN_MINUTES * 60000)));
}
function makeCtx_(ss) {
const conf = loadConf_(ss);
const now = Date.now();
const tz = makeTz_(ss.getSpreadsheetTimeZone() || 'Etc/UTC');
const settings = readSettings_(ss);
return {
ss: ss,
now: now,
tz: tz,
today: tz.key(now),
conf: conf,
token: conf.token,
bot: conf.bot,
settings: settings,
sched: {
tz: tz,
sendMin: settings.sendMin,
endMin: settings.stopMin > settings.sendMin ? settings.stopMin : 1440,
work: settings.work,
overdueDays: settings.overdueDays,
},
sheetName: ss.getName(),
log: [],
sent: 0,
tokenBad: false,
seriesErrors: {},
alerts: [],
wake: Infinity,
results: { sent: [], skipped: [], created: 0 },
};
}
/* ---------- People ---------- */
function loadPeople_(ctx) {
const sh = ctx.ss.getSheetByName(TN.TAB.PEOPLE);
ensureColumns_(sh, PEOPLE_COLS);
const tbl = readTable_(sh, PEOPLE_COLS);
const byName = {};
const byChat = {};
const list = [];
tbl.rows.forEach(function (r) {
const name = str_(cell_(tbl, r, 'name'));
if (!name) return;
const p = {
r: r, name: name, key: normName_(name),
chat: str_(cell_(tbl, r, 'chat')), code: str_(cell_(tbl, r, 'code')),
tg: str_(cell_(tbl, r, 'tg')), link: str_(cell_(tbl, r, 'link')),
};
list.push(p);
if (!byName[p.key]) byName[p.key] = p;
if (p.chat && !byChat[p.chat]) byChat[p.chat] = p;
});
ctx.people = { tbl: tbl, list: list, byName: byName, byChat: byChat };
ctx.owner = ctx.settings.alertsTo ? byName[normName_(ctx.settings.alertsTo)] || null : null;
}
/** Gives every person a code, an invite link and a readable Telegram status. */
function syncPeople_(ctx) {
const tbl = ctx.people.tbl;
ctx.people.list.forEach(function (p) {
if (!p.code) {
p.code = newCode_();
setCell_(tbl, p.r, 'code', p.code);
}
const link = ctx.bot ? 'https://t.me/' + ctx.bot + '?start=' + p.code : 'Connect the bot first: menu π TaskNudge β Setup & status';
if (p.link !== link) {
setCell_(tbl, p.r, 'link', link);
p.link = link;
}
let tg = p.tg;
if (p.chat && tg.indexOf('β
') !== 0) tg = 'β
Connected';
if (!p.chat && tg.indexOf('β οΈ') !== 0) tg = ctx.bot ? 'β³ Not connected yet: send them the invite link' : 'β³ Not connected yet';
if (tg !== p.tg) {
setCell_(tbl, p.r, 'tg', tg);
p.tg = tg;
}
});
}
function connectPerson_(ctx, p, chat, from) {
const chatId = String(chat.id);
const who = [from && from.first_name, from && from.last_name].filter(Boolean).join(' ');
const handle = from && from.username ? ' (@' + from.username + ')' : '';
setCell_(ctx.people.tbl, p.r, 'chat', chatId);
p.chat = chatId;
p.tg = 'β
Connected' + (who || handle ? ' Β· ' + who + handle : '');
setCell_(ctx.people.tbl, p.r, 'tg', p.tg);
ctx.people.byChat[chatId] = p;
ctx.log.push(['', p.name, 'Connected to Telegram' + (who ? ' as ' + who : '') + handle]);
}
function disconnectPerson_(ctx, p, status) {
if (p.chat) delete ctx.people.byChat[p.chat];
p.chat = '';
setCell_(ctx.people.tbl, p.r, 'chat', '');
p.tg = status;
setCell_(ctx.people.tbl, p.r, 'tg', status);
}
/* ---------- Telegram updates ---------- */
/** @param {Object=} fetched a getUpdates reply the timer already has (same offset) */
function pollTelegram_(ctx, fetched) {
const r = fetched || getUpdates_(ctx.token, ctx.conf.offset);
if (!r.ok) {
const kind = tgErrorKind_(r);
if (kind === 'token') {
ctx.tokenBad = true;
recordError_(ctx, 'Telegram no longer accepts the bot token. Connect the bot again in Setup & status.');
} else if (kind === 'conflict') {
recordError_(ctx, 'This bot is also used by another program or webhook. Give TaskNudge its own bot (Setup & status β Change).');
} else {
recordError_(ctx, 'Could not read Telegram: ' + tgShortError_(r));
}
return;
}
let offset = ctx.conf.offset || 0;
(r.result || []).forEach(function (u) {
offset = Math.max(offset, u.update_id + 1);
try {
if (u.message) onMessage_(ctx, u.message);
else if (u.callback_query) onButton_(ctx, u.callback_query);
} catch (err) {
ctx.log.push(['', '', 'Could not handle a Telegram update: ' + (err && err.message ? err.message : err)]);
}
});
if (offset !== (ctx.conf.offset || 0)) {
props_().setProperty(TN.PROP.OFFSET, String(offset));
ctx.conf.offset = offset;
}
}
function onMessage_(ctx, m) {
const chat = m.chat || {};
if (chat.type && chat.type !== 'private') {
if (/^\/(start|tasks|help)/.test(String(m.text || ''))) tgSend_(ctx.token, chat.id, groupText_());
return;
}
const chatId = String(chat.id);
const text = str_(m.text);
const linked = ctx.people.byChat[chatId] || null;
const start = /^\/start(?:@\w+)?(?:\s+([A-Za-z0-9_-]+))?/.exec(text);
if (start) {
const code = start[1];
if (code) {
const p = ctx.people.list.filter(function (x) { return x.code === code; })[0];
if (!p) {
tgSend_(ctx.token, chatId, badInviteText_());
return;
}
connectPerson_(ctx, p, chat, m.from);
tgSend_(ctx.token, chatId, welcomeText_(p.name, ctx.sheetName));
return;
}
tgSend_(ctx.token, chatId, linked ? helpText_(linked.name, ctx.sheetName) : notLinkedText_());
return;
}
if (linked && /^\/tasks\b/.test(text)) {
tgSend_(ctx.token, chatId, taskListText_(openTasksOf_(ctx, linked), ctx.today));
return;
}
tgSend_(ctx.token, chatId, linked ? helpText_(linked.name, ctx.sheetName) : notLinkedText_());
}
function tasksTable_(ctx) {
if (!ctx.tasksTbl) ctx.tasksTbl = readTable_(ctx.ss.getSheetByName(TN.TAB.TASKS), TASK_COLS);
return ctx.tasksTbl;
}
function openTasksOf_(ctx, person) {
const tbl = tasksTable_(ctx);
const out = [];
tbl.rows.forEach(function (r) {
if (!str_(cell_(tbl, r, 'task')) || !str_(cell_(tbl, r, 'id'))) return;
if (normName_(cell_(tbl, r, 'person')) !== person.key) return;
if (/^done$/i.test(str_(cell_(tbl, r, 'status')))) return;
out.push({ id: str_(cell_(tbl, r, 'id')), text: str_(cell_(tbl, r, 'task')), due: readDue_(ctx, cell_(tbl, r, 'due')).key || '' });
});
return out;
}
function onButton_(ctx, q) {
const parts = String(q.data || '').split('|');
if (parts[0] !== 'tn' || parts.length < 3) {
tgAnswer_(ctx.token, q.id, '');
return;
}
const action = parts[1];
const id = parts.slice(2).join('|');
const msg = q.message || {};
const chatId = String(msg.chat ? msg.chat.id : q.from && q.from.id);
const tbl = tasksTable_(ctx);
const r = tbl.rows.filter(function (x) { return str_(cell_(tbl, x, 'id')) === id && str_(cell_(tbl, x, 'task')); })[0];
if (!r) {
tgAnswer_(ctx.token, q.id, 'This task is no longer in the sheet.');
if (msg.message_id) tg_(ctx.token, 'editMessageReplyMarkup', { chat_id: chatId, message_id: msg.message_id, reply_markup: { inline_keyboard: [] } });
return;
}
const personName = str_(cell_(tbl, r, 'person'));
const assignee = ctx.people.byName[normName_(personName)];
const isOwner = !!(ctx.owner && ctx.owner.chat && ctx.owner.chat === chatId);
if (!(assignee && assignee.chat === chatId) && !isOwner) {
tgAnswer_(ctx.token, q.id, 'This task is not assigned to you any more.');
return;
}
const actor = (ctx.people.byChat[chatId] || {}).name || personName;
const st = parseState_(cell_(tbl, r, 'state')) || newState_(id);
const t = {
id: id, text: str_(cell_(tbl, r, 'task')), due: readDue_(ctx, cell_(tbl, r, 'due')).key || '',
notes: str_(cell_(tbl, r, 'notes')), status: str_(cell_(tbl, r, 'status')), st: st,
};
const already = /^done$/i.test(t.status);
let footer;
let mode;
let answer;
if (action === 'd') {
if (!already) {
setCell_(tbl, r, 'status', 'Done');
ctx.log.push([id, actor, 'Marked done in Telegram']);
if (ctx.owner && ctx.owner.chat && ctx.owner.chat !== chatId) {
tgSend_(ctx.token, ctx.owner.chat, alertDoneText_(t, actor, ctx.today));
}
}
footer = footerDone_(ctx.tz, ctx.now, ctx.today);
mode = 'none';
answer = already ? 'Already done β
' : 'Marked done β
';
} else if (already) {
footer = 'β
Already done';
mode = 'none';
answer = 'This task is already done β
';
} else if (action === 'w') {
setCell_(tbl, r, 'status', 'In progress');
t.status = 'In progress';
ctx.log.push([id, actor, 'Marked "In progress" in Telegram']);
footer = footerWorking_(ctx.tz, ctx.now, ctx.today);
mode = 'working';
answer = 'Marked in progress β³';
} else if (action === 's') {
st.sz = sendAtOn_(ctx.sched, nextWork_(ctx.sched, addDays_(ctx.today, 1)));
setCell_(tbl, r, 'state', JSON.stringify(st));
ctx.log.push([id, actor, 'Snoozed until ' + fmtWhen_(ctx.tz, st.sz, ctx.today)]);
footer = footerSnoozed_(ctx.tz, st.sz, ctx.today);
mode = 'snoozed';
answer = 'Snoozed π€';
} else {
tgAnswer_(ctx.token, q.id, '');
return;
}
tgAnswer_(ctx.token, q.id, answer); // may fail if the tap is old; that is fine
if (msg.message_id) tgEdit_(ctx.token, chatId, msg.message_id, taskMessage_(t, 'card', ctx.today, footer), taskKeyboard_(id, mode));
}
/* ---------- Tasks ---------- */
/** Due cell β { key } (may be '' when empty) or { error }. */
function readDue_(ctx, v) {
if (v === '' || v == null) return { key: '' };
if (Object.prototype.toString.call(v) === '[object Date]') {
if (isNaN(v.getTime())) return { error: true };
return { key: ctx.tz.key(v.getTime()) };
}
const k = parseDateText_(v, ctx.today);
return k ? { key: k } : { error: true };
}
function processTasks_(ctx, opts) {
const sh = ctx.ss.getSheetByName(TN.TAB.TASKS);
ensureColumns_(sh, TASK_COLS);
let tbl = readTable_(sh, TASK_COLS);
let states = prepareRows_(ctx, tbl);
if (makeSeries_(ctx, tbl, states, opts)) {
tbl = readTable_(sh, TASK_COLS);
states = prepareRows_(ctx, tbl);
}
ctx.tasksTbl = null;
const out = {};
const force = {};
(opts.sendRows || []).forEach(function (n) { force[n] = true; });
tbl.rows.forEach(function (r) {
const res = taskRow_(ctx, tbl, r, states, !!force[r.row]);
if (res) out[res.id] = res;
});
flushAlerts_(ctx);
writeOutputs_(tbl, out);
}
/**
* Gives new rows (and copied rows) their own ID, and finds each task's state by ID,
* so sorting or moving rows never mixes up states.
*/
function prepareRows_(ctx, tbl) {
let max = 0;
tbl.rows.forEach(function (r) {
const m = /^T-(\d+)/i.exec(str_(cell_(tbl, r, 'id')));
if (m) max = Math.max(max, +m[1]);
});
const stateById = {};
tbl.rows.forEach(function (r) {
const st = parseState_(cell_(tbl, r, 'state'));
if (st && st.id && !stateById[st.id]) stateById[st.id] = st;
});
const seen = {};
const states = {};
tbl.rows.forEach(function (r) {
r.id = '';
if (!str_(cell_(tbl, r, 'task'))) return;
let id = str_(cell_(tbl, r, 'id'));
let fresh = false;
if (!id || seen[id]) {
id = 'T-' + (++max < 100 ? ('00' + max).slice(-3) : max);
setCell_(tbl, r, 'id', id);
fresh = true;
// Show the defaults so people see what will happen.
if (!str_(cell_(tbl, r, 'status'))) setCell_(tbl, r, 'status', 'Not started');
if (!str_(cell_(tbl, r, 'how'))) setCell_(tbl, r, 'how', 'Smart');
}
seen[id] = true;
r.id = id;
const st = !fresh && stateById[id] ? stateById[id] : newState_(id);
st.id = id;
if (fresh) delete st.s;
states[id] = st;
});
return states;
}
/** Creates the repeat rows for rows that ask for them. Returns true if rows were added. */
function makeSeries_(ctx, tbl, states, opts) {
let made = false;
// Bottom-up, so inserting rows does not move rows we have not handled yet.
const rows = tbl.rows.slice().reverse();
rows.forEach(function (r) {
if (!r.id) return;
const wanted = cell_(tbl, r, 'remind') === true || opts.seriesRow === r.row;
if (!wanted || /^done$/i.test(str_(cell_(tbl, r, 'status')))) return;
const rule = parseRepeat_(cell_(tbl, r, 'repeat'), ctx.today);
if (!rule || rule.made || rule.error) return;
const due = readDue_(ctx, cell_(tbl, r, 'due'));
if (!due.key) return; // reported in the Next column
const exp = expandRepeat_(rule, due.key, ctx.settings.work, TN.MAX_SERIES);
if (exp.error) {
ctx.seriesErrors[r.id] = exp.error;
return;
}
createSeries_(ctx, tbl, r, states[r.id], rule, exp.dates);
made = true;
});
return made;
}
function createSeries_(ctx, tbl, r, st, rule, dates) {
const sh = tbl.sh;
const N = dates.length;
const base = r.id;
const fl = freqLabel_(rule.freq);
const width = sh.getLastColumn();
const col = tbl.col;
st.s = { b: base, i: 1, of: N, nx: dates[1] || '', pv: '', fl: fl };
setCell_(tbl, r, 'repeat', rule.text + ' β ' + N + (N === 1 ? ' time' : ' times'));
setCell_(tbl, r, 'state', JSON.stringify(st));
if (N > 1) {
sh.insertRowsAfter(r.row, N - 1);
const src = sh.getRange(r.row, 1, 1, width);
const dest = sh.getRange(r.row + 1, 1, N - 1, width);
src.copyTo(dest, SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
src.copyTo(dest, SpreadsheetApp.CopyPasteType.PASTE_DATA_VALIDATION, false);
const rows = [];
for (let i = 1; i < N; i++) {
const v = r.v.slice(0, width);
while (v.length < width) v.push('');
const id = base + '.' + (i + 1);
const s = newState_(id);
s.s = { b: base, i: i + 1, of: N, nx: dates[i + 1] || '', pv: dates[i - 1], fl: fl };
v[col.id] = id;
if (col.due >= 0) v[col.due] = new Date(ctx.tz.ms(dates[i], 0));
if (col.status >= 0) v[col.status] = 'Not started';
v[col.repeat] = 'β³ ' + base + ' Β· ' + (i + 1) + ' of ' + N;
if (col.remind >= 0) v[col.remind] = cell_(tbl, r, 'remind') === true;
if (col.next >= 0) v[col.next] = '';
if (col.last >= 0) v[col.last] = '';
v[col.state] = JSON.stringify(s);
rows.push(v);
}
dest.setValues(rows);
}
ctx.results.created += N - 1;
ctx.log.push([base, str_(cell_(tbl, r, 'person')), 'Created ' + (N - 1) + ' repeat rows (' + rule.text + ', ' + dates[0] + ' to ' + dates[N - 1] + ')']);
}
/** Switches reminders on for a row. Repeat rows (2nd, 3rd β¦) start quietly. */
function activate_(ctx, st, personKey, due) {
const s = st.s;
if (s && s.i > 1 && s.pv) {
st.a = Math.max(ctx.now, ctx.tz.ms(addDays_(s.pv, 1), 0));
st.q = 1;
} else {
st.a = ctx.now;
st.q = 0;
}
st.p = personKey;
st.d = due;
st.n = 0;
st.ls = 0;
st.sz = 0;
st.rt = 0;
st.f = 0;
st.err = '';
}
/** Decides and sends for one row. Returns { id, next, last, state } for write-back. */
function taskRow_(ctx, tbl, r, states, forced) {
if (!r.id) return null;
const st = states[r.id];
st.r = r.row;
const text = str_(cell_(tbl, r, 'task'));
const personName = str_(cell_(tbl, r, 'person'));
const pKey = normName_(personName);
const person = ctx.people.byName[pKey] || null;
const status = str_(cell_(tbl, r, 'status'));
const done = /^done$/i.test(status);
const remindOn = cell_(tbl, r, 'remind') === true;
const due = readDue_(ctx, cell_(tbl, r, 'due'));
const how = parseHow_(cell_(tbl, r, 'how'));
const rep = parseRepeat_(cell_(tbl, r, 'repeat'), ctx.today);
const out = { id: r.id, next: '', last: lastText_(ctx, st), state: st };
const t = { id: r.id, text: text, due: due.key || '', notes: str_(cell_(tbl, r, 'notes')), status: status, how: how, st: st };
const skip = function (why) {
out.next = why;
if (forced) ctx.results.skipped.push(r.id + ': ' + why.replace(/^\W+\s*/, ''));
return out;
};
overdueAlert_(ctx, t, personName, done);
if (!remindOn) {
st.a = 0;
if (rep && rep.error) return skip('β οΈ ' + rep.error);
if (rep && !rep.made && !rep.error) return skip(due.key ? 'Tick π to create the repeat rows' : 'β οΈ Repeat task needs a Due date (the first time)');
return skip(forced ? 'Tick π Remind first' : '');
}
if (done) return skip('β
Done');
if (rep && rep.error) return skip('β οΈ ' + rep.error);
if (ctx.seriesErrors[r.id]) return skip('β οΈ ' + ctx.seriesErrors[r.id]);
if (rep && !rep.made) return skip('β οΈ Repeat task needs a Due date (the first time)');
if (!personName) return skip('β οΈ Pick who it is assigned to');
if (!person) return skip('β οΈ Add "' + personName + '" to the People tab');
if (due.error) return skip('β οΈ Due must be a date');
if (how.error) return skip('β οΈ ' + how.error);
if (!ctx.token) return skip('Connect the bot: menu π TaskNudge β Setup');
if (ctx.tokenBad) return skip('β οΈ Bot token stopped working: reconnect in Setup');
if (!st.a || st.p !== pKey) activate_(ctx, st, pKey, t.due);
if (!person.chat) return skip('β³ Waiting for ' + person.name + ' to connect');
if (ctx.settings.paused) return skip('βΈ Paused (Settings)');
if (ctx.sent < TN.MAX_SENDS) {
if (st.n > 0 && st.d !== t.due) {
sendTask_(ctx, t, person, 'changed');
} else {
const plan = planTask_(t, ctx.sched, ctx.now);
if (forced || (plan.at != null && plan.at <= ctx.now)) sendTask_(ctx, t, person, st.n ? 'reminder' : 'new', forced);
}
}
out.last = lastText_(ctx, st);
if (!person.chat) out.next = 'β³ Waiting for ' + person.name + ' to connect'; // they blocked the bot just now
else if (ctx.tokenBad) out.next = 'β οΈ Bot token stopped working: reconnect in Setup';
else {
const next = planTask_(t, ctx.sched, ctx.now);
noteWake_(ctx, next.at);
out.next = nextText_(ctx, t, next);
}
return out;
}
function sendTask_(ctx, t, person, kind, forced) {
const st = t.st;
if (ctx.tokenBad) return false;
const r = tgSend_(ctx.token, person.chat, taskMessage_(t, kind, ctx.today), taskKeyboard_(t.id, 'full'));
ctx.sent++;
if (r.ok) {
st.ls = ctx.now;
st.n = (st.n || 0) + 1;
st.d = t.due;
st.mid = r.result && r.result.message_id;
st.f = 0;
st.rt = 0;
st.err = '';
if (st.sz && st.sz <= ctx.now) st.sz = 0;
const what = { new: 'Sent the task', reminder: 'Sent a reminder', changed: 'Sent the new due date' }[kind];
ctx.log.push([t.id, person.name, what + (forced ? ' (sent by hand)' : '')]);
ctx.results.sent.push(t.id);
return true;
}
const kindErr = tgErrorKind_(r);
st.err = tgShortError_(r);
st.f = (st.f || 0) + 1;
if (kindErr === 'blocked') {
disconnectPerson_(ctx, person, 'β οΈ Stopped the bot: send the invite link again');
st.a = 0; // starts fresh once they reconnect
} else if (kindErr === 'rate') {
st.rt = ctx.now + ((r.parameters && r.parameters.retry_after) || 30) * 1000;
} else if (kindErr === 'token') {
ctx.tokenBad = true;
recordError_(ctx, 'Telegram no longer accepts the bot token. Connect the bot again in Setup & status.');
} else {
st.rt = ctx.now + Math.min(60, Math.pow(2, st.f)) * 60000;
}
ctx.log.push([t.id, person.name, 'Not sent: ' + st.err]);
if (forced) ctx.results.skipped.push(t.id + ': ' + st.err);
return false;
}
/**
* Queues one overdue alert per task and due date for the person in "Done & overdue alerts to".
* Only for tasks TaskNudge actually sent: rows never sent (e.g. due on a day off) stay quiet.
*/
function overdueAlert_(ctx, t, personName, done) {
const st = t.st;
const o = ctx.owner;
if (!o || !o.chat || !ctx.token || ctx.tokenBad || done || !t.due || !personName || st.oa === t.due) return;
if (ctx.settings.paused || !st.n) return;
const at = sendAtOn_(ctx.sched, nextWork_(ctx.sched, addDays_(t.due, 1)));
if (ctx.now < at) {
noteWake_(ctx, at);
return;
}
if (at < ctx.conf.alertsSince || ctx.now - at > 7 * DAY_MS) {
st.oa = t.due; // was already overdue before alerts were switched on
return;
}
ctx.alerts.push({ t: t, person: personName });
}
/** Sends the queued overdue alerts: one message, or a short list when several fall due together. */
function flushAlerts_(ctx) {
const items = ctx.alerts;
ctx.alerts = [];
if (!items.length) return;
for (let i = 0; i < items.length; i += 25) {
const part = items.slice(i, i + 25);
const text = part.length === 1 && items.length === 1
? alertOverdueText_(part[0].t, part[0].person, ctx.today)
: alertOverdueListText_(part, ctx.today, items.length);
const r = tgSend_(ctx.token, ctx.owner.chat, text);
if (!r.ok) return;
part.forEach(function (a) {
a.t.st.oa = a.t.due;
ctx.log.push([a.t.id, a.person, 'Overdue alert sent to ' + ctx.owner.name]);
});
}
}
function lastText_(ctx, st) {
if (st.err) return 'β ' + st.err;
return st.ls ? fmtWhen_(ctx.tz, st.ls, ctx.today) + ' β' : '';
}
function nextText_(ctx, t, plan) {
if (plan.at != null) return plan.at <= ctx.now ? 'Now' : fmtWhen_(ctx.tz, plan.at, ctx.today);
if (plan.why === 'stopped') return 'Stopped: ' + ctx.sched.overdueDays + ' days overdue';
if (plan.why === 'series') return 'No more (next repeat is due)';
if (plan.why === 'skipped') return 'Skipped: due on a day off';
return 'No more reminders';
}
/**
* Writes Next reminder, Last sent and _state. Rows are matched by ID again right
* before writing, so a sort during the run cannot put values on the wrong row.
*/
function writeOutputs_(tbl, out) {
const sh = tbl.sh;
const n = sh.getLastRow() - 1;
if (n < 1 || tbl.col.id < 0) return;
const ids = sh.getRange(2, tbl.col.id + 1, n, 1).getValues();
['next', 'last', 'state'].forEach(function (key) {
const ci = tbl.col[key];
if (ci < 0) return;
const rng = sh.getRange(2, ci + 1, n, 1);
const cur = rng.getValues();
let changed = false;
const vals = cur.map(function (row, i) {
const o = out[str_(ids[i][0])];
if (!o) return row;
const v = key === 'state' ? JSON.stringify(o.state) : (o[key] == null ? '' : o[key]);
if (String(row[0]) !== String(v)) changed = true;
return [v];
});
if (changed) rng.setValues(vals);
});
}
/* ---------- Activity tab ---------- */
function flushLog_(ctx) {
if (!ctx.log.length) return;
const sh = ctx.ss.getSheetByName(TN.TAB.ACTIVITY);
if (!sh) return;
const when = fmtStamp_(ctx.tz, ctx.now);
const rows = ctx.log.slice().reverse().map(function (e) {
return [when, e[0] || '', e[1] || '', clip_(e[2] || '', 500)];
});
sh.insertRowsAfter(1, rows.length);
sh.getRange(2, 1, rows.length, 4).setValues(rows)
.setFontWeight('normal').setBackground(null).setFontColor('#3c4043');
const last = sh.getLastRow();
const keep = TN.ACTIVITY_KEEP + 1;
if (last > keep + 100) sh.deleteRows(keep + 1, last - keep);
ctx.log = [];
}
/* ===== Layout.js ===== */
/**
* Builds and repairs the four tabs: headers, dropdowns, checkboxes, colours.
* Safe to run again at any time: it never deletes your rows.
*/
const COLORS_ = {
headBg: '#e8f0fe', headFg: '#174ea6', autoBg: '#f8f9fa', autoFg: '#5f6368', text: '#3c4043',
doneFg: '#9aa0a6', overdueBg: '#fce8e6', overdueFg: '#c5221f', todayBg: '#fef7e0', todayFg: '#b06000',
greenBg: '#e6f4ea', greenFg: '#137333', blueBg: '#e8f0fe', blueFg: '#1967d2', greyBg: '#f1f3f4', greyFg: '#5f6368',
};
const PROTECT_NOTE_ = 'TaskNudge fills this in';
function buildLayout_(ss) {
const hadTasks = !!ss.getSheetByName(TN.TAB.TASKS);
const tasks = ensureSheet_(ss, TN.TAB.TASKS, 0);
const people = ensureSheet_(ss, TN.TAB.PEOPLE, 1);
const settings = ensureSheet_(ss, TN.TAB.SETTINGS, 2);
const activity = ensureSheet_(ss, TN.TAB.ACTIVITY, 3);
const freshTasks = writeHeaders_(tasks, TASK_COLS);
writeHeaders_(people, PEOPLE_COLS);
writeHeaders_(activity, ACTIVITY_COLS);
ensureSettingsRows_(ss, settings);
stylePeople_(people);
styleTasks_(tasks, people);
styleSettings_(settings, people);
styleActivity_(activity);
if (freshTasks) addExamples_(ss, tasks);
if (!hadTasks) removeEmptyDefaultSheets_(ss);
SpreadsheetApp.flush(); // without it the sheet can stay on the last new tab
tasks.activate();
}
function ensureSheet_(ss, name, index) {
return ss.getSheetByName(name) || ss.insertSheet(name, Math.min(index, ss.getSheets().length));
}
/** Writes the header row on an empty tab (returns true), or adds missing columns. */
function writeHeaders_(sh, cols) {
if (sh.getLastRow() === 0 && sh.getLastColumn() === 0) {
sh.getRange(1, 1, 1, cols.length).setValues([cols.map(function (c) { return c.label; })]);
return true;
}
ensureColumns_(sh, cols);
return false;
}
/** Deletes Sheet1 & co. when they are completely empty (only on first setup). */
function removeEmptyDefaultSheets_(ss) {
const ours = [TN.TAB.TASKS, TN.TAB.PEOPLE, TN.TAB.SETTINGS, TN.TAB.ACTIVITY];
ss.getSheets().forEach(function (s) {
if (ours.indexOf(s.getName()) >= 0) return;
if (s.getLastRow() === 0 && s.getLastColumn() === 0 && ss.getSheets().length > 1) ss.deleteSheet(s);
});
}
function colLetter_(n) {
let s = '';
while (n > 0) {
const m = (n - 1) % 26;
s = String.fromCharCode(65 + m) + s;
n = Math.floor((n - 1) / 26);
}
return s;
}
function dataRows_(sh) {
return Math.max(sh.getMaxRows() - 1, 1);
}
function styleHeader_(sh, tbl, cols) {
const width = sh.getLastColumn();
sh.getRange(1, 1, 1, width)
.setFontWeight('bold').setBackground(COLORS_.headBg).setFontColor(COLORS_.headFg)
.setVerticalAlignment('middle').setWrap(true);
sh.setRowHeight(1, 36);
sh.setFrozenRows(1);
cols.forEach(function (c) {
const i = tbl.col[c.key];
if (i < 0) return;
if (c.width) sh.setColumnWidth(i + 1, c.width);
if (c.note) sh.getRange(1, i + 1).setNote(c.note);
const body = sh.getRange(2, i + 1, dataRows_(sh), 1);
body.setVerticalAlignment('top');
if (c.wrap) body.setWrap(true);
if (c.auto) body.setFontColor(COLORS_.autoFg).setBackground(COLORS_.autoBg);
if (c.hidden) sh.hideColumns(i + 1);
});
}
function protectAuto_(sh, tbl, cols) {
sh.getProtections(SpreadsheetApp.ProtectionType.RANGE).forEach(function (p) {
if (p.getDescription() === PROTECT_NOTE_) p.remove();
});
cols.forEach(function (c) {
const i = tbl.col[c.key];
if (!c.auto || i < 0 || c.key === 'id') return;
sh.getRange(2, i + 1, dataRows_(sh), 1).protect().setDescription(PROTECT_NOTE_).setWarningOnly(true);
});
}
function listRule_(items, allowOthers, help) {
return SpreadsheetApp.newDataValidation().requireValueInList(items, true)
.setAllowInvalid(allowOthers).setHelpText(help).build();
}
function styleTasks_(sh, people) {
const tbl = readTable_(sh, TASK_COLS);
styleHeader_(sh, tbl, TASK_COLS);
sh.setFrozenColumns(2);
sh.setTabColor('#1a73e8');
const n = dataRows_(sh);
const col = function (k) { return tbl.col[k] + 1; };
const body = function (k) { return sh.getRange(2, col(k), n, 1); };
const ptbl = readTable_(people, PEOPLE_COLS);
const peopleRange = people.getRange(2, ptbl.col.name + 1, dataRows_(people), 1);
body('person').setDataValidation(SpreadsheetApp.newDataValidation().requireValueInRange(peopleRange, true)
.setAllowInvalid(true).setHelpText('Pick a person from the People tab.').build());
body('due').setDataValidation(SpreadsheetApp.newDataValidation().requireDate().setAllowInvalid(false)
.setHelpText('Enter a date. Double-click for a calendar.').build()).setNumberFormat('ddd d mmm yyyy');
body('status').setDataValidation(listRule_(TN.STATUS, false, 'Not started, In progress, Blocked or Done.'));
body('remind').setDataValidation(SpreadsheetApp.newDataValidation().requireCheckbox().build())
.setHorizontalAlignment('center');
body('how').setDataValidation(listRule_(TN.HOW_OPTIONS, true, 'Pick one, or type your own, e.g. "every 3 days" or "every 2 hours".'));
body('repeat').setDataValidation(listRule_(TN.REPEAT_OPTIONS, true, 'Pick one, or type your own, e.g. "Weekly, 8 times" or "Monthly until 2027-06-30".'));
body('next').setNumberFormat('@');
body('last').setNumberFormat('@');
body('id').setNumberFormat('@');
// Colours: status chips first (they win), then done rows, then due dates.
const L = function (k) { return colLetter_(col(k)); };
const all = sh.getRange(2, 1, n, sh.getLastColumn());
const statusCell = body('status');
const rules = [];
const chip = function (text, bg, fg) {
rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextEqualTo(text)
.setBackground(bg).setFontColor(fg).setRanges([statusCell]).build());
};
chip('Done', COLORS_.greenBg, COLORS_.greenFg);
chip('In progress', COLORS_.blueBg, COLORS_.blueFg);
chip('Blocked', COLORS_.todayBg, COLORS_.todayFg);
chip('Not started', COLORS_.greyBg, COLORS_.greyFg);
const S = '$' + L('status') + '2';
const D = '$' + L('due') + '2';
rules.push(SpreadsheetApp.newConditionalFormatRule().whenFormulaSatisfied('=' + S + '="Done"')
.setFontColor(COLORS_.doneFg).setStrikethrough(true).setRanges([body('task')]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule().whenFormulaSatisfied('=' + S + '="Done"')
.setFontColor(COLORS_.doneFg).setRanges([all]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied('=AND(ISNUMBER(' + D + '),' + D + '"Done")')
.setBackground(COLORS_.overdueBg).setFontColor(COLORS_.overdueFg).setRanges([body('due')]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied('=AND(ISNUMBER(' + D + '),' + D + '=TODAY(),' + S + '<>"Done")')
.setBackground(COLORS_.todayBg).setFontColor(COLORS_.todayFg).setRanges([body('due')]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextStartsWith('β οΈ')
.setFontColor(COLORS_.overdueFg).setRanges([body('next')]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextStartsWith('β³')
.setFontColor(COLORS_.todayFg).setRanges([body('next')]).build());
rules.push(SpreadsheetApp.newConditionalFormatRule().whenTextStartsWith('β')
.setFontColor(COLORS_.overdueFg).setRanges([body('last')]).build());
sh.setConditionalFormatRules(rules);
protectAuto_(sh, tbl, TASK_COLS);
if (!sh.getFilter()) sh.getRange(1, 1, sh.getMaxRows(), sh.getLastColumn()).createFilter();
}
function stylePeople_(sh) {
const tbl = readTable_(sh, PEOPLE_COLS);
styleHeader_(sh, tbl, PEOPLE_COLS);
sh.setTabColor('#188038');
const n = dataRows_(sh);
const tg = sh.getRange(2, tbl.col.tg + 1, n, 1);
sh.setConditionalFormatRules([
SpreadsheetApp.newConditionalFormatRule().whenTextStartsWith('β
').setFontColor(COLORS_.greenFg).setRanges([tg]).build(),
SpreadsheetApp.newConditionalFormatRule().whenTextStartsWith('β³').setFontColor(COLORS_.todayFg).setRanges([tg]).build(),
SpreadsheetApp.newConditionalFormatRule().whenTextStartsWith('β οΈ').setFontColor(COLORS_.overdueFg).setRanges([tg]).build(),
]);
protectAuto_(sh, tbl, PEOPLE_COLS);
}
function ensureSettingsRows_(ss, sh) {
if (sh.getLastRow() === 0) {
sh.getRange(1, 1, 1, 3).setValues([['Setting', 'Value', 'What it does']]);
}
const have = {};
sh.getRange(1, 1, Math.max(sh.getLastRow(), 1), 1).getDisplayValues().forEach(function (r) {
const k = settingKeyByLabel_(r[0]);
if (k) have[k] = true;
});
const missing = SETTINGS_ROWS.filter(function (r) { return !have[r.key]; });
if (missing.length) {
const start = settingsTableEnd_(sh) + 1;
sh.insertRowsAfter(start - 1, missing.length);
missing.forEach(function (r, i) {
// Text format keeps "09:00" as typed instead of turning it into a time value.
if (!r.checkbox) sh.getRange(start + i, 2).setNumberFormat('@');
});
sh.getRange(start, 1, missing.length, 3).setValues(missing.map(function (r) {
return [r.label, r.checkbox ? false : r.def, r.help];
}));
}
writeSetting_(ss, 'tz', ss.getSpreadsheetTimeZone());
}
/** Last row of the settings table (rows that have a known label). */
function settingsTableEnd_(sh) {
const labels = sh.getRange(1, 1, Math.max(sh.getLastRow(), 1), 1).getDisplayValues();
let end = 1;
labels.forEach(function (r, i) { if (settingKeyByLabel_(r[0])) end = i + 1; });
return end;
}
function styleSettings_(sh, people) {
sh.setTabColor('#5f6368');
const last = settingsTableEnd_(sh);
sh.getRange(1, 1, 1, 3).setFontWeight('bold').setBackground(COLORS_.headBg).setFontColor(COLORS_.headFg);
sh.setFrozenRows(1);
sh.setColumnWidth(1, 260);
sh.setColumnWidth(2, 170);
sh.setColumnWidth(3, 520);
sh.getRange(2, 1, last - 1, 3).setFontWeight('normal').setBackground(null).setFontColor(COLORS_.text)
.setVerticalAlignment('middle');
sh.getRange(2, 1, last - 1, 1).setFontWeight('bold');
sh.getRange(2, 3, last - 1, 1).setFontColor(COLORS_.autoFg).setWrap(true);
const ptbl = readTable_(people, PEOPLE_COLS);
const labels = sh.getRange(1, 1, last, 1).getDisplayValues();
labels.forEach(function (r, i) {
const def = settingRowByKey_(settingKeyByLabel_(r[0]));
if (!def) return;
const cell = sh.getRange(i + 1, 2);
if (def.readOnly) {
cell.setFontColor(COLORS_.autoFg).setBackground(COLORS_.autoBg).clearDataValidations();
} else if (def.checkbox) {
cell.setDataValidation(SpreadsheetApp.newDataValidation().requireCheckbox().build());
} else if (def.people) {
cell.setDataValidation(SpreadsheetApp.newDataValidation()
.requireValueInRange(people.getRange(2, ptbl.col.name + 1, dataRows_(people), 1), true)
.setAllowInvalid(true).setHelpText('Pick a connected person, or leave empty.').build());
} else if (def.list) {
const items = Array.isArray(def.list) ? def.list : TN[def.list];
cell.setNumberFormat('@').setDataValidation(listRule_(items, true, def.help));
}
});
// Short guide under the table.
const g = last + 2;
const guide = [
['How to use TaskNudge'],
['1. Menu π TaskNudge β Setup & status: connect your Telegram bot (one time).'],
['2. People tab: add each person, send them their invite link, they press Start in Telegram.'],
['3. Tasks tab: write the task, pick the person and due date, tick π Remind.'],
['4. People tap β
Done in Telegram, or you set Status to Done. Reminders stop.'],
[TN.HELP_URL ? 'Full guide: ' + TN.HELP_URL : 'Version ' + TN.VERSION + ' Β· MIT License'],
];
sh.getRange(g, 1, guide.length, 1).setValues(guide).setFontColor(COLORS_.autoFg).setFontWeight('normal');
sh.getRange(g, 1).setFontWeight('bold').setFontColor(COLORS_.text);
}
function styleActivity_(sh) {
const tbl = readTable_(sh, ACTIVITY_COLS);
styleHeader_(sh, tbl, ACTIVITY_COLS);
sh.setTabColor('#9aa0a6');
sh.getRange(1, 1).setNote('Newest first. TaskNudge keeps the last ' + TN.ACTIVITY_KEEP + ' rows.');
}
function addExamples_(ss, sh) {
const tbl = readTable_(sh, TASK_COLS);
const tz = makeTz_(ss.getSpreadsheetTimeZone() || 'Etc/UTC');
const today = tz.key(Date.now());
const width = sh.getLastColumn();
const row = function (id, task, dueKey, notes, repeat) {
const v = [];
for (let i = 0; i < width; i++) v.push('');
v[tbl.col.id] = id;
v[tbl.col.task] = task;
v[tbl.col.due] = new Date(tz.ms(dueKey, 0));
v[tbl.col.status] = 'Not started';
v[tbl.col.notes] = notes;
v[tbl.col.repeat] = repeat;
v[tbl.col.remind] = false;
v[tbl.col.how] = 'Smart';
return v;
};
sh.getRange(2, 1, 2, width).setValues([
row('T-001', 'Send the monthly report to the client', addDays_(today, 3),
'Example: pick a person, then tick π Remind', ''),
row('T-002', 'Water the office plants', addDays_(today, 1),
'Example of a repeating task: ticking π creates one row per day', 'Daily for 1 month'),
]);
}
/* ===== Main.js ===== */
/**
* Entry points: the menu, the two triggers, and the functions the sidebar calls.
*/
/* ---------- Menu ---------- */
function onOpen() {
SpreadsheetApp.getUi().createMenu(TN.MENU)
.addItem('Setup & status', 'tnMenuSetup')
.addSeparator()
.addItem('Send reminder now (selected rows)', 'tnMenuSendNow')
.addItem('Create repeat rows (selected task)', 'tnMenuCreateRepeats')
.addItem('Delete repeat rows (selected task)', 'tnMenuDeleteRepeats')
.addItem('New invite link (selected person)', 'tnMenuNewInvite')
.addSeparator()
.addItem('Repair sheet layout', 'tnMenuRepair')
.addToUi();
try {
const ss = SpreadsheetApp.getActive();
if (!ss.getSheetByName(TN.TAB.TASKS) || !props_().getProperty(TN.PROP.TOKEN)) {
ss.toast('Open the menu π TaskNudge β Setup & status to connect Telegram.', 'TaskNudge', 15);
}
} catch (e) {
// Simple triggers may not read properties before the first authorization.
}
}
function tnMenuSetup() {
const ss = SpreadsheetApp.getActive();
if (!ss.getSheetByName(TN.TAB.TASKS)) withLock_(function () { buildLayout_(ss); });
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('Sidebar').setTitle('TaskNudge'));
}
function tnMenuRepair() {
withLock_(function () {
buildLayout_(SpreadsheetApp.getActive());
runEngine_({});
});
toast_('Sheet layout repaired. Your rows were not changed.');
}
function tnMenuSendNow() {
const rows = selectedRows_(TN.TAB.TASKS);
if (!rows) return;
const ctx = withLock_(function () { return runEngine_({ sendRows: rows }); });
const res = ctx.results;
const lines = [];
if (res.sent.length) lines.push('Sent: ' + res.sent.join(', '));
if (res.skipped.length) lines.push('Not sent:\n' + res.skipped.join('\n'));
if (!lines.length) lines.push('Nothing to send in the selected rows.');
SpreadsheetApp.getUi().alert('Send reminder now', lines.join('\n\n'), SpreadsheetApp.getUi().ButtonSet.OK);
}
function tnMenuCreateRepeats() {
const rows = selectedRows_(TN.TAB.TASKS);
if (!rows) return;
const ctx = withLock_(function () { return runEngine_({ seriesRow: rows[0] }); });
const ids = Object.keys(ctx.seriesErrors);
if (ctx.results.created) toast_('Created ' + ctx.results.created + ' repeat rows.');
else if (ids.length) toast_(ctx.seriesErrors[ids[0]]);
else toast_('Nothing to create. Fill in "Repeat task" (e.g. Daily for 1 month) and a Due date first.');
}
function tnMenuDeleteRepeats() {
const ui = SpreadsheetApp.getUi();
const rows = selectedRows_(TN.TAB.TASKS);
if (!rows) return;
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName(TN.TAB.TASKS);
const tbl = readTable_(sh, TASK_COLS);
const picked = tbl.rows.filter(function (r) { return r.row === rows[0]; })[0];
const st = picked && parseState_(cell_(tbl, picked, 'state'));
const base = st && st.s ? st.s.b : picked ? str_(cell_(tbl, picked, 'id')) : '';
const extra = tbl.rows.filter(function (r) {
const s = parseState_(cell_(tbl, r, 'state'));
return s && s.s && s.s.b === base && s.s.i > 1;
});
if (!base || !extra.length) {
toast_('The selected task has no repeat rows.');
return;
}
const answer = ui.alert('Delete repeat rows',
'Delete the ' + extra.length + ' repeat rows of ' + base + '? The first row (' + base + ') stays.', ui.ButtonSet.YES_NO);
if (answer !== ui.Button.YES) return;
withLock_(function () {
const fresh = readTable_(sh, TASK_COLS);
const del = fresh.rows.filter(function (r) {
const s = parseState_(cell_(fresh, r, 'state'));
return s && s.s && s.s.b === base && s.s.i > 1;
}).map(function (r) { return r.row; }).sort(function (a, b) { return b - a; });
// Delete runs of neighbouring rows in one call each (bottom-up keeps row numbers valid).
for (let i = 0; i < del.length;) {
let j = i;
while (j + 1 < del.length && del[j + 1] === del[j] - 1) j++;
sh.deleteRows(del[j], j - i + 1);
i = j + 1;
}
const again = readTable_(sh, TASK_COLS);
again.rows.forEach(function (r) {
if (str_(cell_(again, r, 'id')) !== base) return;
const s = parseState_(cell_(again, r, 'state'));
if (s) {
delete s.s;
setCell_(again, r, 'state', JSON.stringify(s));
}
setCell_(again, r, 'repeat', str_(cell_(again, r, 'repeat')).replace(/\s*β.*$/, ''));
setCell_(again, r, 'remind', false);
});
const ctx = makeCtx_(ss);
ctx.log.push([base, '', 'Deleted ' + del.length + ' repeat rows']);
flushLog_(ctx);
});
toast_('Deleted the repeat rows. π Remind is off for ' + base + ' so nothing is re-created.');
}
function tnMenuNewInvite() {
const rows = selectedRows_(TN.TAB.PEOPLE);
if (!rows) return;
const names = withLock_(function () {
const sh = SpreadsheetApp.getActive().getSheetByName(TN.TAB.PEOPLE);
const tbl = readTable_(sh, PEOPLE_COLS);
const done = [];
tbl.rows.forEach(function (r) {
if (rows.indexOf(r.row) < 0 || !str_(cell_(tbl, r, 'name'))) return;
setCell_(tbl, r, 'code', newCode_());
setCell_(tbl, r, 'chat', '');
setCell_(tbl, r, 'tg', 'β³ New link made: send it to them again');
done.push(str_(cell_(tbl, r, 'name')));
});
runEngine_({});
return done;
});
toast_(names.length ? 'New invite link for ' + names.join(', ') + '. The old link no longer works.' : 'Select a person on the People tab first.');
}
/** Row numbers of the current selection on the given tab, or null (with a message). */
function selectedRows_(tabName) {
const range = SpreadsheetApp.getActiveRange();
if (!range || range.getSheet().getName() !== tabName) {
toast_('First click a row on the ' + tabName + ' tab.');
return null;
}
const rows = [];
for (let i = 0; i < range.getNumRows(); i++) {
const n = range.getRow() + i;
if (n > 1) rows.push(n);
}
if (!rows.length) {
toast_('Select a row below the header.');
return null;
}
return rows;
}
function toast_(msg) {
SpreadsheetApp.getActive().toast(msg, 'TaskNudge', 8);
}
function withLock_(fn) {
const lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
return fn();
} finally {
lock.releaseLock();
}
}
/* ---------- Triggers (installed by Setup) ---------- */
/** Runs on every edit (installable trigger, so it may send Telegram messages). */
function handleEdit(e) {
const lock = LockService.getScriptLock();
if (!lock.tryLock(25000)) {
props_().deleteProperty(TN.PROP.WAKE); // the next timer run picks the change up
return;
}
try {
const sheet = e && e.range ? e.range.getSheet() : null;
const name = sheet ? sheet.getName() : '';
if (name === TN.TAB.SETTINGS) settingsEdited_(e.range);
if (name === TN.TAB.TASKS || name === TN.TAB.PEOPLE || name === TN.TAB.SETTINGS) runEngine_({});
} catch (err) {
recordError_(null, 'Edit: ' + (err && err.stack ? err.stack : err));
} finally {
lock.releaseLock();
}
}
/** Runs every few minutes: reads Telegram, sends what is due. */
function tick() {
const lock = LockService.getScriptLock();
if (!lock.tryLock(5000)) return;
try {
const p = props_();
const now = Date.now();
const peek = peekTelegram_(p, now);
if (peek.quiet) {
p.setProperty(TN.PROP.LAST_TICK, String(now));
return;
}
const ctx = runEngine_({ poll: true, updates: peek.updates });
p.setProperty(TN.PROP.LAST_TICK, String(ctx.now));
} catch (err) {
recordError_(null, 'Timer: ' + (err && err.stack ? err.stack : err));
} finally {
lock.releaseLock();
}
}
/**
* The timer's fast path. Free Google accounts get 90 minutes of timer time a day, so a run
* that has nothing to do must be quick: until TN_WAKE (the earliest moment anything can be
* due, saved by the last full run) it only asks Telegram for news and skips the sheet.
* @return {{quiet: boolean, updates: (Object|undefined)}}
*/
function peekTelegram_(p, now) {
const all = p.getProperties();
const wake = Number(all[TN.PROP.WAKE] || 0);
const token = all[TN.PROP.TOKEN];
if (!token || !wake || now >= wake) return { quiet: false };
const r = getUpdates_(token, Number(all[TN.PROP.OFFSET] || 0));
if (r.ok && r.result && r.result.length) return { quiet: false, updates: r };
return { quiet: true }; // nothing new (Telegram errors are reported by the next full run)
}
function settingsEdited_(range) {
const labels = range.getSheet().getRange(range.getRow(), 1, range.getNumRows(), 1).getDisplayValues();
labels.forEach(function (r) {
const key = settingKeyByLabel_(r[0]);
if (key === 'every' && triggerState_().tick) installTriggers_(readSettings_(SpreadsheetApp.getActive()).every, true);
if (key === 'alertsTo') props_().setProperty(TN.PROP.ALERTS_SINCE, String(Date.now()));
});
}
/* ---------- Sidebar API (called with google.script.run) ---------- */
function tnGetStatus() {
const ss = SpreadsheetApp.getActive();
const conf = loadConf_(ss);
const settings = readSettings_(ss);
const tz = makeTz_(ss.getSpreadsheetTimeZone() || 'Etc/UTC');
const now = Date.now();
const people = [];
const pSheet = ss.getSheetByName(TN.TAB.PEOPLE);
if (pSheet) {
const tbl = readTable_(pSheet, PEOPLE_COLS);
tbl.rows.forEach(function (r) {
const name = str_(cell_(tbl, r, 'name'));
if (!name) return;
people.push({
name: name,
connected: !!str_(cell_(tbl, r, 'chat')),
status: str_(cell_(tbl, r, 'tg')),
link: conf.bot && str_(cell_(tbl, r, 'code')) ? 'https://t.me/' + conf.bot + '?start=' + str_(cell_(tbl, r, 'code')) : '',
});
});
}
let active = 0;
const tSheet = ss.getSheetByName(TN.TAB.TASKS);
if (tSheet) {
const t = readTable_(tSheet, TASK_COLS);
t.rows.forEach(function (r) {
if (str_(cell_(t, r, 'task')) && cell_(t, r, 'remind') === true && !/^done$/i.test(str_(cell_(t, r, 'status')))) active++;
});
}
const trig = triggerState_();
const agoMin = conf.lastTick ? Math.round((now - conf.lastTick) / 60000) : null;
// Triggers belong to whoever connected the bot; others see that it runs from the last check time.
const ticking = trig.tick || (agoMin != null && agoMin <= settings.every * 2 + 5);
return {
name: TN.NAME,
version: TN.VERSION,
helpUrl: TN.HELP_URL,
sheetName: ss.getName(),
layout: !!tSheet,
copy: conf.copy && !conf.token,
bot: conf.bot,
connected: !!conf.token,
running: !!conf.token && ticking,
triggers: trig,
people: people,
activeTasks: active,
settings: {
sendAt: fmtTime_(settings.sendMin),
workDays: settings.raw.workDays,
every: settings.every,
paused: settings.paused,
alertsTo: settings.alertsTo,
timeZone: tz.name,
problems: settings.problems,
},
options: { times: TN.TIME_OPTIONS, workDays: TN.WORKDAY_OPTIONS },
lastTick: conf.lastTick ? fmtWhen_(tz, conf.lastTick, tz.key(now)) : '',
lastTickAgoMin: agoMin,
lastError: conf.lastError,
};
}
function tnConnectBot(token) {
token = str_(token);
if (!/^\d{5,}:[A-Za-z0-9_-]{30,}$/.test(token)) {
throw new Error('That does not look like a bot token. It looks like 123456789:AAH4β¦ (copy the whole line BotFather sent).');
}
const me = tg_(token, 'getMe', {});
if (!me.ok) {
throw new Error(me.http === 401 ? 'Telegram did not accept this token. Copy it again from BotFather.' : 'Could not reach Telegram: ' + tgShortError_(me));
}
const username = me.result.username;
const ss = SpreadsheetApp.getActive();
const p = props_();
const prevBot = (p.getProperty(TN.PROP.BOT) || str_(readSettings_(ss).raw.bot)).replace(/^@/, '');
const sameBot = prevBot.toLowerCase() === username.toLowerCase() && p.getProperty(TN.PROP.COPY) !== '1';
// Polling needs the webhook off. A new bot starts clean; the same bot keeps its unread updates.
tg_(token, 'deleteWebhook', { drop_pending_updates: !sameBot });
tg_(token, 'setMyCommands', { commands: [
{ command: 'tasks', description: 'My open tasks' },
{ command: 'help', description: 'How this bot works' },
] });
withLock_(function () {
if (!ss.getSheetByName(TN.TAB.TASKS)) buildLayout_(ss);
if (!sameBot) resetConnections_(ss);
const values = {};
values[TN.PROP.TOKEN] = token;
values[TN.PROP.BOT] = username;
values[TN.PROP.SHEET] = ss.getId();
values[TN.PROP.ALERTS_SINCE] = p.getProperty(TN.PROP.ALERTS_SINCE) || String(Date.now());
if (!sameBot) values[TN.PROP.OFFSET] = '0';
p.setProperties(values);
p.deleteProperty(TN.PROP.COPY);
clearError_();
writeSetting_(ss, 'bot', '@' + username);
writeSetting_(ss, 'tz', ss.getSpreadsheetTimeZone());
installTriggers_(readSettings_(ss).every, false);
runEngine_({});
});
return tnGetStatus();
}
/** A different bot (or a copied sheet) cannot reach people who started the old bot. */
function resetConnections_(ss) {
const sh = ss.getSheetByName(TN.TAB.PEOPLE);
if (!sh) return;
const tbl = readTable_(sh, PEOPLE_COLS);
tbl.rows.forEach(function (r) {
if (!str_(cell_(tbl, r, 'name'))) return;
setCell_(tbl, r, 'code', newCode_());
setCell_(tbl, r, 'chat', '');
setCell_(tbl, r, 'tg', '');
});
}
function tnDisconnectBot() {
withLock_(function () {
removeTriggers_();
const p = props_();
[TN.PROP.TOKEN, TN.PROP.OFFSET, TN.PROP.LAST_TICK, TN.PROP.LAST_ERROR, TN.PROP.WAKE].forEach(function (k) { p.deleteProperty(k); });
writeSetting_(SpreadsheetApp.getActive(), 'bot', 'Not connected');
});
return tnGetStatus();
}
function tnSaveBasics(values) {
const ss = SpreadsheetApp.getActive();
values = values || {};
if (values.sendAt != null) {
if (parseTime_(values.sendAt) == null) throw new Error('Pick a time like 09:00.');
writeSetting_(ss, 'sendAt', fmtTime_(parseTime_(values.sendAt)));
}
if (values.workDays != null) {
if (!parseWorkDays_(values.workDays)) throw new Error('Work days: use e.g. MonβFri or SunβThu.');
writeSetting_(ss, 'workDays', values.workDays);
}
if (values.alertsTo != null) {
writeSetting_(ss, 'alertsTo', values.alertsTo);
props_().setProperty(TN.PROP.ALERTS_SINCE, String(Date.now()));
}
withLock_(function () { runEngine_({}); });
return tnGetStatus();
}
function tnSetPaused(paused) {
writeSetting_(SpreadsheetApp.getActive(), 'paused', !!paused);
withLock_(function () { runEngine_({}); });
return tnGetStatus();
}
function tnSendTest(name) {
const ss = SpreadsheetApp.getActive();
const conf = loadConf_(ss);
if (!conf.token) throw new Error('Connect the bot first.');
const sh = ss.getSheetByName(TN.TAB.PEOPLE);
const tbl = readTable_(sh, PEOPLE_COLS);
const r = tbl.rows.filter(function (x) { return normName_(cell_(tbl, x, 'name')) === normName_(name); })[0];
const chat = r ? str_(cell_(tbl, r, 'chat')) : '';
if (!chat) throw new Error(name + ' has not connected yet: send them their invite link.');
const res = tgSend_(conf.token, chat, testText_(ss.getName()));
if (!res.ok) throw new Error('Telegram: ' + tgShortError_(res));
return 'Test sent to ' + name + '.';
}
/** Runs one check right now (same as the timer). */
function tnCheckNow() {
const before = tnGetStatus();
if (before.connected && !before.running) {
// Nobody's timer has run for a while: start one (as the person clicking).
withLock_(function () { installTriggers_(readSettings_(SpreadsheetApp.getActive()).every); });
}
props_().deleteProperty(TN.PROP.WAKE); // a full check, not the quick one
tick();
return tnGetStatus();
}
function tnOpenTab(name) {
const sh = SpreadsheetApp.getActive().getSheetByName(name);
if (sh) sh.activate();
}
/* ===== Messages.js ===== */
/**
* Everything the bot says. Telegram HTML: only , , , are used.
* Pure functions.
*/
function esc_(s) {
return String(s == null ? '' : s).replace(/&/g, '&').replace(//g, '>');
}
function clip_(s, n) {
s = String(s == null ? '' : s);
return s.length > n ? s.slice(0, n - 1) + 'β¦' : s;
}
/** "Thu 12 Dec", with the year when it is not this year. */
function fmtDay_(key, todayKey) {
const p = parseKey_(key);
if (!p) return '';
let s = DOW_NAMES[dowOf_(key)] + ' ' + p.d + ' ' + MONTH_NAMES[p.m - 1];
if (todayKey && key.slice(0, 4) !== String(todayKey).slice(0, 4)) s += ' ' + p.y;
return s;
}
/** "Thu 12 Dec Β· 09:00" */
function fmtWhen_(tz, ms, todayKey) {
const p = tz.parts(ms);
return fmtDay_(p.key, todayKey) + ' Β· ' + fmtTime_(p.min);
}
/** "2026-12-05 09:00" for the Activity tab (sorts well). */
function fmtStamp_(tz, ms) {
const p = tz.parts(ms);
return p.key + ' ' + fmtTime_(p.min);
}
/** "today", "tomorrow", "in 3 days", "1 day overdue", "4 days overdue" */
function dueWords_(due, todayKey) {
const d = diffDays_(due, todayKey);
if (d === 0) return 'today';
if (d === 1) return 'tomorrow';
if (d > 1) return 'in ' + d + ' days';
return (-d) + (d === -1 ? ' day' : ' days') + ' overdue';
}
/**
* The task message.
* t = { id, text, due, notes, status, st: { s: repeat info } }
* kind = 'new' | 'reminder' | 'changed' | 'card'
*/
function taskMessage_(t, kind, todayKey, footer) {
const id = esc_(t.id);
let head;
if (kind === 'new') head = 'π New task Β· ' + id;
else if (kind === 'changed') head = 'π Due date changed Β· ' + id;
else if (kind === 'card') head = 'π Task Β· ' + id;
else if (t.due) {
const d = diffDays_(t.due, todayKey);
if (d > 1) head = 'β° Reminder Β· ' + id + ' Β· due in ' + d + ' days';
else if (d === 1) head = 'β° Due tomorrow Β· ' + id;
else if (d === 0) head = 'β οΈ Due today Β· ' + id;
else head = 'π΄ Overdue Β· ' + id + ' Β· ' + dueWords_(t.due, todayKey);
} else head = 'β° Reminder Β· ' + id;
const lines = [head, '' + esc_(clip_(t.text, 600)) + ''];
if (t.due) lines.push('π
Due ' + fmtDay_(t.due, todayKey) + ' (' + dueWords_(t.due, todayKey) + ')');
if (t.notes) lines.push('π ' + esc_(clip_(t.notes, 1200)));
const s = t.st && t.st.s;
if (s && s.of > 1) lines.push('π ' + s.i + ' of ' + s.of + (s.fl ? ' Β· repeats ' + esc_(s.fl) : ''));
if (kind !== 'card' && kind !== 'new' && /^in progress$/i.test(String(t.status || ''))) lines.push('β³ You marked this as in progress');
let text = lines.join('\n');
if (footer) text += '\n\n' + footer;
return text;
}
/** Buttons under a task message. mode: 'full' | 'working' | 'snoozed' | 'none' */
function taskKeyboard_(id, mode) {
if (mode === 'none') return { inline_keyboard: [] };
const data = function (a) { return 'tn|' + a + '|' + id; };
if (data('d').length > 64) return null; // Telegram limit; very long custom IDs get no buttons
const done = { text: 'β
Done', callback_data: data('d') };
const onIt = { text: 'β³ On it', callback_data: data('w') };
const later = { text: 'π€ Tomorrow', callback_data: data('s') };
if (mode === 'working') return { inline_keyboard: [[done, later]] };
if (mode === 'snoozed') return { inline_keyboard: [[done, onIt]] };
return { inline_keyboard: [[done, onIt, later]] };
}
function footerDone_(tz, now, todayKey) {
return 'β
Marked done Β· ' + fmtWhen_(tz, now, todayKey);
}
function footerWorking_(tz, now, todayKey) {
return 'β³ On it Β· ' + fmtWhen_(tz, now, todayKey);
}
function footerSnoozed_(tz, until, todayKey) {
return 'π€ Snoozed until ' + fmtWhen_(tz, until, todayKey);
}
function welcomeText_(name, sheetName) {
return 'π Hi ' + esc_(name) + '! You are connected to ' + esc_(sheetName) + '.\n\n' +
'I will send your tasks and reminders here. Tap β
Done under a task when it is finished.\n' +
'Send /tasks any time to see your open tasks.';
}
function notLinkedText_() {
return 'π Hi! I send task reminders for a team sheet.\n' +
'To connect, open the personal invite link you were sent and press Start.';
}
function badInviteText_() {
return 'This invite link does not work any more. Please ask for a new one.';
}
function helpText_(name, sheetName) {
return 'Hi ' + esc_(name) + ', I send you tasks and reminders from ' + esc_(sheetName) + '.\n\n' +
'/tasks: your open tasks\n' +
'Under each task: β
Done Β· β³ On it Β· π€ Tomorrow';
}
function testText_(sheetName) {
return 'π Test message from ' + esc_(sheetName) + '. Task reminders will arrive here.';
}
function groupText_() {
return 'I only work in private chats. Please message me directly.';
}
/** tasks = [{ id, text, due }] already filtered to open tasks of this person. */
function taskListText_(tasks, todayKey) {
if (!tasks.length) return 'π You have no open tasks.';
const sorted = tasks.slice().sort(function (a, b) {
return (a.due || '9999') < (b.due || '9999') ? -1 : (a.due || '9999') > (b.due || '9999') ? 1 : 0;
});
const lines = ['π Your open tasks (' + tasks.length + ')'];
sorted.slice(0, 30).forEach(function (t) {
const when = t.due ? ' Β· ' + (t.due < todayKey ? 'π΄ ' : '') + dueWords_(t.due, todayKey) : '';
lines.push('β’ ' + esc_(t.id) + ' ' + esc_(clip_(t.text, 80)) + when);
});
if (sorted.length > 30) lines.push('β¦ and ' + (sorted.length - 30) + ' more');
return lines.join('\n');
}
function alertDoneText_(t, personName, todayKey) {
return 'β
Done Β· ' + esc_(t.id) + '\n' + esc_(clip_(t.text, 300)) + '\n' +
'π€ ' + esc_(personName) + ' marked it done in Telegram' +
(t.due ? '\nπ
Was due ' + fmtDay_(t.due, todayKey) : '');
}
function alertOverdueListText_(items, todayKey, total) {
const lines = ['π΄ ' + total + ' tasks are now overdue'];
items.forEach(function (a) {
lines.push('β’ ' + esc_(a.t.id) + ' ' + esc_(clip_(a.t.text, 70)) + ' Β· π€ ' + esc_(a.person) + ' Β· ' + dueWords_(a.t.due, todayKey));
});
return lines.join('\n');
}
function alertOverdueText_(t, personName, todayKey) {
return 'π΄ Overdue Β· ' + esc_(t.id) + '\n' + esc_(clip_(t.text, 300)) + '\n' +
'π€ ' + esc_(personName) + '\nπ
Was due ' + fmtDay_(t.due, todayKey) + ' (' + dueWords_(t.due, todayKey) + ')';
}
/* ===== Rules.js ===== */
/**
* Reading what people type: "Remind how often", "Repeat task" and "Work days".
* Pure functions: no Apps Script services, so they can be unit-tested in Node.
*/
function cleanText_(v) {
return String(v == null ? '' : v).trim().toLowerCase()
.replace(/[ββ]/g, '-')
.replace(/\s+/g, ' ');
}
const NUMBER_WORDS_ = { a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, twelve: 12 };
function wordNum_(w) {
return /^\d+$/.test(w) ? +w : (NUMBER_WORDS_[w] || 0);
}
/**
* "Remind how often" β { type: 'smart' } | { type: 'once' } | { type: 'days', n } | { type: 'hours', n } | { error }
* Empty means Smart.
*/
function parseHow_(v) {
const s = cleanText_(v);
if (!s || /^smart\b/.test(s)) return { type: 'smart' };
if (/^(once|one time|1 time|just once|no repeats?|never|only once)$/.test(s)) return { type: 'once' };
if (/^(daily|every ?day|each day)$/.test(s)) return { type: 'days', n: 1 };
if (/^every other day$/.test(s)) return { type: 'days', n: 2 };
if (/^(weekly|every ?week|each week)$/.test(s)) return { type: 'days', n: 7 };
if (/^(hourly|every ?hour)$/.test(s)) return { type: 'hours', n: 1 };
const m = /^(?:every )?(\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten|twelve) ?(days?|d|weeks?|wks?|w|hours?|hrs?|h)$/.exec(s);
if (m) {
const n = wordNum_(m[1]);
const u = m[2].charAt(0);
if (n >= 1) {
if (u === 'h' && n <= 24) return { type: 'hours', n: n };
if (u === 'd' && n <= 90) return { type: 'days', n: n };
if (u === 'w' && n <= 12) return { type: 'days', n: n * 7 };
}
}
return { error: 'Remind how often: try Smart, Daily, Every 2 days, Weekly or Every 4 hours' };
}
/** Short words for a "Remind how often" rule, used in the sidebar and messages. */
function howLabel_(how) {
if (!how || how.type === 'smart') return 'Smart';
if (how.type === 'once') return 'Once';
if (how.type === 'hours') return how.n === 1 ? 'Every hour' : 'Every ' + how.n + ' hours';
if (how.n === 1) return 'Daily';
if (how.n === 7) return 'Weekly';
if (how.n % 7 === 0) return 'Every ' + (how.n / 7) + ' weeks';
return 'Every ' + how.n + ' days';
}
/**
* "Repeat task" β null (empty) | { made: true } (rows already created) | { error }
* | { text, freq: { unit: 'day'|'work'|'month', n }, count | span: { unit, n } | until }
*/
function parseRepeat_(v, todayKey) {
const raw = String(v == null ? '' : v).trim();
if (!raw) return null;
if (raw.indexOf('β') >= 0 || raw.charAt(0) === 'β³') return { made: true };
const s = cleanText_(raw);
const FREQS = [
[/^(weekdays|workdays|every (?:week|work) ?days?|each (?:week|work) ?day)\b/, function () { return { unit: 'work', n: 1 }; }],
[/^(daily|every ?day|each day)\b/, function () { return { unit: 'day', n: 1 }; }],
[/^every other day\b/, function () { return { unit: 'day', n: 2 }; }],
[/^(fortnightly|bi-?weekly|every other week)\b/, function () { return { unit: 'day', n: 14 }; }],
[/^(weekly|every ?week|each week)\b/, function () { return { unit: 'day', n: 7 }; }],
[/^(monthly|every ?month|each month)\b/, function () { return { unit: 'month', n: 1 }; }],
[/^quarterly\b/, function () { return { unit: 'month', n: 3 }; }],
[/^(yearly|annually|every ?year)\b/, function () { return { unit: 'month', n: 12 }; }],
[/^every (\d+) ?(days?|weeks?|months?)\b/, function (m) {
const n = +m[1];
if (m[2].charAt(0) === 'w') return { unit: 'day', n: n * 7 };
if (m[2].charAt(0) === 'm') return { unit: 'month', n: n };
return { unit: 'day', n: n };
}],
];
let freq = null;
let rest = '';
for (let i = 0; i < FREQS.length && !freq; i++) {
const m = FREQS[i][0].exec(s);
if (m) {
freq = FREQS[i][1](m);
rest = s.slice(m[0].length);
}
}
const example = 'try "Daily for 1 month" or "Weekly, 10 times"';
if (!freq || freq.n < 1) return { error: 'Repeat task: ' + example };
rest = rest.replace(/^[\s,;:-]+/, '').trim();
if (!rest) return { error: 'Repeat task: say how long, ' + example };
const out = { text: raw, freq: freq };
let m;
if ((m = /^(?:for )?(\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten|twelve) ?(days?|weeks?|months?|years?)$/.exec(rest))) {
const n = wordNum_(m[1]);
const u = m[2].charAt(0);
out.span = u === 'y' ? { unit: 'month', n: n * 12 } : u === 'm' ? { unit: 'month', n: n } : { unit: 'day', n: u === 'w' ? n * 7 : n };
} else if ((m = /^(?:for )?(\d+) ?(?:times|x|Γ|occurrences|repeats)$/.exec(rest)) || (m = /^[xΓ] ?(\d+)$/.exec(rest))) {
out.count = +m[1];
} else if ((m = /^(?:until|till|til|to|through|ending|ends|up to) (.+)$/.exec(rest))) {
out.until = parseDateText_(m[1], todayKey);
if (!out.until) return { error: 'Repeat task: write the end date like 2027-06-30' };
} else {
return { error: 'Repeat task: ' + example };
}
if ((out.span && out.span.n < 1) || out.count === 0) return { error: 'Repeat task: ' + example };
return out;
}
/** "daily", "every 2 weeks" β¦ for messages. */
function freqLabel_(freq) {
if (freq.unit === 'work') return 'every work day';
if (freq.unit === 'month') return freq.n === 1 ? 'monthly' : freq.n === 12 ? 'yearly' : 'every ' + freq.n + ' months';
if (freq.n === 1) return 'daily';
if (freq.n === 7) return 'weekly';
if (freq.n % 7 === 0) return 'every ' + (freq.n / 7) + ' weeks';
return 'every ' + freq.n + ' days';
}
/**
* The due dates of every occurrence, starting with startKey.
* work: array of 7 booleans (Sun β¦ Sat) used by "weekdays".
*/
function expandRepeat_(rule, startKey, work, max) {
max = max || TN.MAX_SERIES;
let endExcl = null;
if (rule.span) {
endExcl = rule.span.unit === 'month' ? addMonths_(startKey, rule.span.n) : addDays_(startKey, rule.span.n);
}
if (rule.until && rule.until < startKey) return { error: 'Repeat task: the end date is before the first due date' };
const anchorDay = parseKey_(startKey).d;
const dates = [];
let key = startKey;
for (let i = 0; i <= max; i++) {
if (i > 0) {
if (rule.freq.unit === 'day') key = addDays_(startKey, i * rule.freq.n);
else if (rule.freq.unit === 'month') key = addMonths_(startKey, i * rule.freq.n, anchorDay);
else {
key = addDays_(key, 1);
let guard = 0;
while (!work[dowOf_(key)] && guard++ < 7) key = addDays_(key, 1);
}
}
if (endExcl && key >= endExcl) break;
if (rule.until && key > rule.until) break;
if (rule.count && dates.length >= rule.count) break;
dates.push(key);
}
if (dates.length > max) return { error: 'Repeat task: that is more than ' + max + ' times; pick a shorter period' };
return { dates: dates };
}
/**
* "MonβFri", "Sun-Thu", "Mon, Wed, Fri", "Every day" β [Sun β¦ Sat] booleans, or null if unreadable.
*/
function parseWorkDays_(v) {
const s = cleanText_(v);
if (!s || /^(every ?day|all( days)?|daily|7 days|any day|everyday)$/.test(s)) return [true, true, true, true, true, true, true];
const names = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const out = [false, false, false, false, false, false, false];
let any = false;
const parts = s.split(/,|;|&|\/| and /);
for (let i = 0; i < parts.length; i++) {
const p = parts[i].trim();
if (!p) continue;
const r = /^([a-z]{3})[a-z]*\s*(?:-|to|until|through)\s*([a-z]{3})[a-z]*$/.exec(p);
if (r) {
const a = names.indexOf(r[1]);
const b = names.indexOf(r[2]);
if (a < 0 || b < 0) return null;
for (let d = a, guard = 0; guard < 7; d = (d + 1) % 7, guard++) {
out[d] = true;
if (d === b) break;
}
any = true;
continue;
}
const one = /^([a-z]{3})[a-z]*$/.exec(p);
if (one && names.indexOf(one[1]) >= 0) {
out[names.indexOf(one[1])] = true;
any = true;
continue;
}
return null;
}
return any ? out : null;
}
/* ===== Schedule.js ===== */
/**
* When does the next message for a task go out?
* Pure functions: the caller passes the time zone helper and the current time.
*
* c (schedule config) = { tz, sendMin, endMin, work: [Sun β¦ Sat], overdueDays }
* t (task) = { due: "2026-12-12" | "", how: parseHow_() result, st: state }
* st (state, stored per row in the hidden _state column):
* a activated at (ms) q 1 = quiet start: first message waits for the schedule (repeat rows)
* n messages sent ls last sent (ms) sz snoozed until (ms)
* rt retry not before (ms) s repeat info { b: first ID, i, of, nx: next due, pv: previous due, fl }
*/
function isWork_(c, key) {
return !!c.work[dowOf_(key)];
}
function prevWork_(c, key) {
for (let i = 0; i < 7; i++) {
const k = addDays_(key, -i);
if (isWork_(c, k)) return k;
}
return key;
}
function nextWork_(c, key) {
for (let i = 0; i < 7; i++) {
const k = addDays_(key, i);
if (isWork_(c, k)) return k;
}
return key;
}
function sendAtOn_(c, key) {
return c.tz.ms(key, c.sendMin);
}
function uniqSorted_(arr) {
const out = arr.slice().sort(function (a, b) { return a - b; });
return out.filter(function (x, i) { return i === 0 || x !== out[i - 1]; });
}
function firstAfter_(points, after) {
for (let i = 0; i < points.length; i++) if (points[i] > after) return points[i];
return null;
}
function firstAtOrAfter_(points, at) {
for (let i = 0; i < points.length; i++) if (points[i] >= at) return points[i];
return null;
}
/**
* Smart reminders: 3 days before, 1 day before and on the due day (moved back to the
* previous work day when they fall on a day off), then every work day while overdue.
*/
function smartPoints_(c, due) {
const pts = [];
[3, 1, 0].forEach(function (back) {
pts.push(sendAtOn_(c, prevWork_(c, addDays_(due, -back))));
});
for (let i = 1; i <= c.overdueDays; i++) {
const k = addDays_(due, i);
if (isWork_(c, k)) pts.push(sendAtOn_(c, k));
}
return uniqSorted_(pts);
}
/** The earliest moment at or after ms that is inside the sending window of a work day. */
function windowFit_(c, ms) {
const p = c.tz.parts(ms);
if (isWork_(c, p.key)) {
if (p.min < c.sendMin) return sendAtOn_(c, p.key);
if (p.min < c.endMin) return ms;
}
return sendAtOn_(c, nextWork_(c, addDays_(p.key, 1)));
}
/** Every n days at the send time, counted from the day the reminders were switched on. */
function everyDays_(t, c, n, after) {
const anchor = c.tz.key(t.st.a);
const gap = diffDays_(c.tz.key(after), anchor);
const k0 = Math.max(1, Math.floor(gap / n));
for (let k = k0; k < k0 + 60; k++) {
let key = addDays_(anchor, k * n);
if (!isWork_(c, key)) {
if (n === 1) continue;
key = nextWork_(c, key);
}
const p = sendAtOn_(c, key);
if (p > after) return p;
}
return null;
}
function nextRulePoint_(t, c, after) {
const how = t.how;
if (how.type === 'once') return null;
if (how.type === 'smart') {
// At most one Smart reminder per day: skip moments later on the day of the last message.
if (t.due) return firstAfter_(smartPoints_(c, t.due), c.tz.ms(addDays_(c.tz.key(after), 1), 0) - 1);
return everyDays_(t, c, 2, after);
}
if (how.type === 'days') return everyDays_(t, c, how.n, after);
if (how.type === 'hours') return windowFit_(c, after + how.n * 3600000);
return null;
}
/** Moment from which no more reminders go out (exclusive), or null for never. */
function overdueEnd_(t, c) {
return t.due ? c.tz.ms(addDays_(t.due, c.overdueDays + 1), 0) : null;
}
function seriesEnd_(t, c) {
const s = t.st.s;
return s && s.nx ? sendAtOn_(c, s.nx) : null;
}
/** First message of a repeat row: the first Smart moment after the previous one was due. */
function firstQuiet_(t, c) {
const a = t.st.a;
if (t.due) {
const p = firstAtOrAfter_(smartPoints_(c, t.due), a);
if (p != null) return p;
}
const k = c.tz.key(a);
let p = sendAtOn_(c, nextWork_(c, k));
if (p < a) p = sendAtOn_(c, nextWork_(c, addDays_(k, 1)));
return p;
}
/**
* @return {{at: number|null, why: string}} at = when to send next (may be <= now: send now).
* why when at is null: 'none' (no more reminders), 'stopped' (overdue limit), 'series' (next repeat took over),
* 'skipped' (a repeat row that is never sent: due on a day off, and the next repeat starts first)
*/
function planTask_(t, c, now) {
const st = t.st;
const oEnd = overdueEnd_(t, c);
const sEnd = seriesEnd_(t, c);
const ended = function (at) {
if (sEnd != null && at >= sEnd) return 'series';
if (oEnd != null && at >= oEnd) return 'stopped';
return '';
};
let at;
if (!st.n) {
if (!st.q) {
at = st.a || now; // switched on by hand: send right away, any time of day
} else {
at = firstQuiet_(t, c);
const why = ended(at);
// A repeat row whose whole turn falls on days off is never sent.
if (why) return { at: null, why: why === 'series' ? 'skipped' : why };
if (at < now) at = windowFit_(c, now);
}
} else if (st.sz && st.sz > st.ls) {
at = st.sz; // snoozed: wins over the normal schedule
} else {
at = nextRulePoint_(t, c, st.ls);
if (at == null) return { at: null, why: t.how.type === 'smart' && t.due ? 'stopped' : 'none' };
const why = ended(at);
if (why) return { at: null, why: why };
if (at < now) at = windowFit_(c, now); // missed while paused or stopped: catch up in the window
}
if (st.rt && st.rt > at) at = st.rt;
return { at: at, why: '' };
}
/* ===== Store.js ===== */
/**
* Reading and writing the tabs, settings, script properties and triggers.
*/
/**
* Reads a whole tab. Columns are matched by header text (row 1).
* @return {{sh, col: Object, width: number, rows: Array<{row: number, v: Array}>}}
* col[key] is a 0-based column index or -1 when the column is missing.
*/
function readTable_(sh, cols) {
const lastRow = sh.getLastRow();
const lastCol = Math.max(sh.getLastColumn(), 1);
const values = lastRow ? sh.getRange(1, 1, lastRow, lastCol).getValues() : [[]];
const header = values[0].map(normKey_);
const col = {};
cols.forEach(function (c) { col[c.key] = header.indexOf(normKey_(c.label)); });
const rows = [];
for (let i = 1; i < values.length; i++) rows.push({ row: i + 1, v: values[i] });
return { sh: sh, col: col, width: lastCol, rows: rows };
}
function cell_(tbl, r, key) {
const i = tbl.col[key];
return i >= 0 ? r.v[i] : '';
}
function setCell_(tbl, r, key, value) {
const i = tbl.col[key];
if (i < 0) return;
tbl.sh.getRange(r.row, i + 1).setValue(value);
r.v[i] = value;
}
/** Adds any missing columns at the right end. Returns true if something was added. */
function ensureColumns_(sh, cols) {
const lastCol = sh.getLastColumn();
const header = lastCol ? sh.getRange(1, 1, 1, lastCol).getValues()[0].map(normKey_) : [];
const missing = cols.filter(function (c) { return header.indexOf(normKey_(c.label)) < 0; });
if (!missing.length) return false;
const start = lastCol + 1;
if (sh.getMaxColumns() < lastCol + missing.length) sh.insertColumnsAfter(sh.getMaxColumns(), lastCol + missing.length - sh.getMaxColumns());
sh.getRange(1, start, 1, missing.length).setValues([missing.map(function (c) { return c.label; })]);
return true;
}
function parseState_(v) {
const s = String(v == null ? '' : v).trim();
if (s.charAt(0) !== '{') return null;
try {
const o = JSON.parse(s);
return o && typeof o === 'object' ? o : null;
} catch (e) {
return null;
}
}
function newState_(id) {
return { id: id, a: 0, q: 0, p: '', d: '', n: 0, ls: 0, sz: 0, rt: 0, f: 0 };
}
/* ---------- Settings ---------- */
function settingRowByKey_(key) {
for (let i = 0; i < SETTINGS_ROWS.length; i++) if (SETTINGS_ROWS[i].key === key) return SETTINGS_ROWS[i];
return null;
}
function settingKeyByLabel_(label) {
const n = normKey_(label);
for (let i = 0; i < SETTINGS_ROWS.length; i++) if (normKey_(SETTINGS_ROWS[i].label) === n) return SETTINGS_ROWS[i].key;
return '';
}
function readSettings_(ss) {
const raw = {};
SETTINGS_ROWS.forEach(function (r) { raw[r.key] = r.def; });
const sh = ss.getSheetByName(TN.TAB.SETTINGS);
if (sh && sh.getLastRow() >= 2) {
sh.getRange(1, 1, sh.getLastRow(), 2).getDisplayValues().forEach(function (row) {
const k = settingKeyByLabel_(row[0]);
if (k) raw[k] = row[1];
});
}
const sendMin = parseTime_(raw.sendAt);
const stopMin = parseTime_(raw.stopAt);
const work = parseWorkDays_(raw.workDays);
return {
raw: raw,
sendMin: sendMin == null ? 9 * 60 : sendMin,
stopMin: stopMin == null ? 18 * 60 : stopMin,
work: work || parseWorkDays_('Mon-Fri'),
problems: [
sendMin == null ? '"Send reminders at" is not a time; using 09:00' : '',
stopMin == null ? '"Hourly reminders stop at" is not a time; using 18:00' : '',
work ? '' : '"Work days" is unclear; using MonβFri',
].filter(String),
overdueDays: clampInt_(raw.overdueDays, 0, 365, 14),
alertsTo: str_(raw.alertsTo),
every: nearestMinutes_(raw.every),
paused: String(raw.paused).toUpperCase() === 'TRUE',
};
}
function writeSetting_(ss, key, value) {
const sh = ss.getSheetByName(TN.TAB.SETTINGS);
if (!sh) return false;
const labels = sh.getRange(1, 1, Math.max(sh.getLastRow(), 1), 1).getDisplayValues();
for (let i = 0; i < labels.length; i++) {
if (settingKeyByLabel_(labels[i][0]) === key) {
sh.getRange(i + 1, 2).setValue(value);
props_().deleteProperty(TN.PROP.WAKE); // the next timer run reads the sheet with the new setting
return true;
}
}
return false;
}
function clampInt_(v, lo, hi, def) {
const n = parseInt(v, 10);
if (isNaN(n)) return def;
return Math.max(lo, Math.min(hi, n));
}
function nearestMinutes_(v) {
const n = parseInt(v, 10);
if (isNaN(n)) return 1;
let best = TN.TRIGGER_MINUTES[0];
TN.TRIGGER_MINUTES.forEach(function (m) { if (Math.abs(m - n) < Math.abs(best - n)) best = m; });
return best;
}
/* ---------- Script properties (bot token, offsets) ---------- */
function props_() {
return PropertiesService.getScriptProperties();
}
/**
* The saved bot connection. If this script runs in a copy of the original
* spreadsheet, the copy forgets the bot: two sheets must never share one bot.
*/
function loadConf_(ss) {
const p = props_();
const all = p.getProperties();
const P = TN.PROP;
const conf = {
token: all[P.TOKEN] || '',
bot: all[P.BOT] || '',
sheetId: all[P.SHEET] || '',
offset: Number(all[P.OFFSET] || 0),
alertsSince: Number(all[P.ALERTS_SINCE] || 0),
lastTick: Number(all[P.LAST_TICK] || 0),
lastError: all[P.LAST_ERROR] || '',
copy: all[P.COPY] === '1',
};
if (conf.token && conf.sheetId && conf.sheetId !== ss.getId()) {
[P.TOKEN, P.BOT, P.SHEET, P.OFFSET, P.ALERTS_SINCE, P.LAST_TICK, P.LAST_ERROR].forEach(function (k) { p.deleteProperty(k); });
p.setProperty(P.COPY, '1');
return { token: '', bot: '', sheetId: '', offset: 0, alertsSince: 0, lastTick: 0, lastError: '', copy: true };
}
return conf;
}
function recordError_(ctxOrNull, message) {
try {
const stamp = ctxOrNull && ctxOrNull.tz ? fmtStamp_(ctxOrNull.tz, ctxOrNull.now) : new Date().toISOString();
props_().setProperty(TN.PROP.LAST_ERROR, stamp + ' Β· ' + clip_(message, 300));
} catch (e) {
// nothing else we can do
}
console.error(message);
}
function clearError_() {
props_().deleteProperty(TN.PROP.LAST_ERROR);
}
/* ---------- Triggers ---------- */
function ourTriggers_() {
return ScriptApp.getProjectTriggers().filter(function (t) {
const f = t.getHandlerFunction();
return f === 'tick' || f === 'handleEdit';
});
}
/** Re-creates the edit trigger and the timer (as the user running this). */
function installTriggers_(minutes, timerOnly) {
ourTriggers_().forEach(function (t) {
if (!timerOnly || t.getHandlerFunction() === 'tick') ScriptApp.deleteTrigger(t);
});
if (!timerOnly) ScriptApp.newTrigger('handleEdit').forSpreadsheet(SpreadsheetApp.getActive()).onEdit().create();
ScriptApp.newTrigger('tick').timeBased().everyMinutes(nearestMinutes_(minutes)).create();
}
function removeTriggers_() {
ourTriggers_().forEach(function (t) { ScriptApp.deleteTrigger(t); });
}
function triggerState_() {
const t = ourTriggers_();
return {
edit: t.some(function (x) { return x.getHandlerFunction() === 'handleEdit'; }),
tick: t.some(function (x) { return x.getHandlerFunction() === 'tick'; }),
};
}
/** A short random code for invite links (letters and digits only). */
function newCode_() {
return Utilities.getUuid().replace(/-/g, '').slice(0, 14);
}
/* ===== Telegram.js ===== */
/**
* Tiny Telegram Bot API client. Every call returns Telegram's JSON reply plus
* `http` (the status code); it never throws.
*/
const TG_API_ = 'https://api.telegram.org/bot';
function getUpdates_(token, offset) {
return tg_(token, 'getUpdates', { offset: offset || 0, timeout: 0, limit: 100, allowed_updates: ['message', 'callback_query'] });
}
function tg_(token, method, payload) {
let res;
try {
res = UrlFetchApp.fetch(TG_API_ + token + '/' + method, {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload || {}),
muteHttpExceptions: true,
});
} catch (err) {
return { ok: false, http: 0, description: 'Network error: ' + (err && err.message ? err.message : err) };
}
const code = res.getResponseCode();
let body;
try {
body = JSON.parse(res.getContentText());
} catch (e) {
body = { ok: false, description: 'Unexpected reply from Telegram (HTTP ' + code + ')' };
}
body.http = code;
return body;
}
function tgSend_(token, chatId, text, keyboard) {
const p = { chat_id: chatId, text: text, parse_mode: 'HTML', disable_web_page_preview: true };
if (keyboard) p.reply_markup = keyboard;
return tg_(token, 'sendMessage', p);
}
function tgEdit_(token, chatId, messageId, text, keyboard) {
return tg_(token, 'editMessageText', {
chat_id: chatId,
message_id: messageId,
text: text,
parse_mode: 'HTML',
disable_web_page_preview: true,
reply_markup: keyboard || { inline_keyboard: [] },
});
}
function tgAnswer_(token, callbackId, text) {
return tg_(token, 'answerCallbackQuery', { callback_query_id: callbackId, text: text || '' });
}
/** '' (ok) | 'token' | 'blocked' | 'rate' | 'conflict' | 'bad' | 'retry' */
function tgErrorKind_(r) {
if (r.ok) return '';
const d = String(r.description || '');
if (r.http === 401 || r.http === 404) return 'token';
if (r.http === 403 || /chat not found|bot was blocked|user is deactivated|bot can't initiate/i.test(d)) return 'blocked';
if (r.http === 429) return 'rate';
if (r.http === 409) return 'conflict';
if (r.http === 400) return 'bad';
return 'retry';
}
/** Telegram's error text, shortened for a cell. */
function tgShortError_(r) {
const d = String(r.description || 'Unknown error').replace(/^(Bad Request|Forbidden|Unauthorized|Conflict): /, '');
return clip_(d, 90);
}