const CONTACTS_READONLY_SCOPE = 'https://www.googleapis.com/auth/contacts.readonly'; const TASKS_WRITE_SCOPE = 'https://www.googleapis.com/auth/tasks'; const PRACTICE_STATE_KEY = 'book.tasks-and-contacts.state.v1'; const MAX_CONTACT_PAGE_SIZE = 50; const MAX_STATE_LENGTH = 4096; const TASKS_CONTACTS_CONFIG = Object.freeze({ practiceListTitle: 'Apps Script Request Practice', lookupContacts: true, contactPageSize: 25, approvePracticeWrite: false, confirmRemovePracticeList: false, }); const PRACTICE_FOLLOW_UP_REQUESTS = Object.freeze([ Object.freeze({ requestId: 'REQ-201', requesterEmail: 'alex.rivera@example.com', fallbackName: 'Alex Rivera', summary: 'Confirm room setup for Tuesday workshop', dueDateUtc: '2026-12-01', }), Object.freeze({ requestId: 'REQ-202', requesterEmail: 'sam.chen@example.com', fallbackName: 'Sam Chen', summary: 'Collect speaker slides before rehearsal', dueDateUtc: '2026-12-03', }), ]); /** * @typedef {{requestId: string, requesterEmail: string, fallbackName: string, summary: string, dueDateUtc: string}} FollowUpRequestSpec_ */ /** * @typedef {{taskId: string, title: string, dueDateUtc: string}} SavedPracticeTask_ */ /** * @typedef {{version: number, tasklistId: string | null, tasklistTitle: string, tasksByRequestId: {[requestId: string]: SavedPracticeTask_}}} PracticeTasksState_ */ /** * @typedef {{requestId: string, requesterName: string, nameSource: 'contacts' | 'fallback', title: string, notes: string, dueDateUtc: string, dueTimestamp: string}} PlannedPracticeTask_ */ /** * Previews the two follow-up tasks and optional read-only People lookup * without creating a task list, inserting tasks, or writing PropertiesService. */ function previewFollowUpTaskPlan() { const config = requireTasksContactsConfig_(); if (config.lookupContacts) { ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, [CONTACTS_READONLY_SCOPE]); } const properties = PropertiesService.getScriptProperties(); const savedState = readPracticeTaskState_(properties); const matchedNames = config.lookupContacts ? lookupPracticeRequesterNames_(config.contactPageSize) : new Map(); const plannedTasks = buildPlannedPracticeTasks_(matchedNames); const items = plannedTasks.map((task) => { const saved = savedState ? savedState.tasksByRequestId[task.requestId] : undefined; return { requestId: task.requestId, requesterName: task.requesterName, nameSource: task.nameSource, title: task.title, dueTimestamp: task.dueTimestamp, savedTaskId: saved ? saved.taskId : null, plannedAction: saved ? 'inspect_or_patch' : 'insert', }; }); const report = { mode: 'preview', practiceListTitle: config.practiceListTitle, savedTasklistId: savedState ? savedState.tasklistId : null, contactLookupEnabled: config.lookupContacts, matchedContactCount: matchedNames.size, items: items, writesPerformed: false, }; console.log(JSON.stringify(report, null, 2)); return report; } /** * Creates or reconciles the dedicated practice task list and two bounded tasks. * Never writes to the @default task list, and saves IDs after each step. */ function syncApprovedPracticeTasks() { const config = requireTasksContactsConfig_(); if (!config.approvePracticeWrite) { throw new Error( 'Run previewFollowUpTaskPlan first, then set TASKS_CONTACTS_CONFIG.approvePracticeWrite to true before syncing.', ); } const requiredScopes = config.lookupContacts ? [CONTACTS_READONLY_SCOPE, TASKS_WRITE_SCOPE] : [TASKS_WRITE_SCOPE]; ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, requiredScopes); const lock = LockService.getScriptLock(); lock.waitLock(5000); try { const properties = PropertiesService.getScriptProperties(); const existingState = readPracticeTaskState_(properties); /** @type {PracticeTasksState_} */ const state = existingState || { version: 1, tasklistId: null, tasklistTitle: config.practiceListTitle, tasksByRequestId: {}, }; const tasklistId = ensurePracticeTaskList_(config.practiceListTitle, state, properties); const matchedNames = config.lookupContacts ? lookupPracticeRequesterNames_(config.contactPageSize) : new Map(); const plannedTasks = buildPlannedPracticeTasks_(matchedNames); /** @type {{requestId: string, taskId: string, action: string, dueTimestamp: string}[]} */ const results = []; for (const planned of plannedTasks) { const outcome = reconcileSinglePracticeTask_(tasklistId, planned, state, properties); results.push(outcome); } const report = { mode: 'sync', tasklist: { id: tasklistId, title: state.tasklistTitle, }, contactLookupEnabled: config.lookupContacts, results: results, statePropertyKey: PRACTICE_STATE_KEY, }; console.log(JSON.stringify(report, null, 2)); return report; } finally { lock.releaseLock(); } } /** * Deletes only the recorded practice task list ID and clears its Script Properties key. */ function removePracticeTaskList() { const config = requireTasksContactsConfig_(); if (!config.confirmRemovePracticeList) { throw new Error( 'Set TASKS_CONTACTS_CONFIG.confirmRemovePracticeList to true before removing the practice task list.', ); } ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, [TASKS_WRITE_SCOPE]); const lock = LockService.getScriptLock(); lock.waitLock(5000); try { const properties = PropertiesService.getScriptProperties(); const state = readPracticeTaskState_(properties); if (!state) { const emptyReport = { removed: false, deletedTasklistId: null, reason: 'No saved practice task state exists in Script Properties.', }; console.log(JSON.stringify(emptyReport, null, 2)); return emptyReport; } const savedListId = state.tasklistId; if (savedListId !== null) { if (savedListId === '@default') { throw new Error('Refusing to remove @default. Only a dedicated practice list ID may be removed.'); } Tasks.Tasklists.remove(savedListId); } properties.deleteProperty(PRACTICE_STATE_KEY); const report = { removed: true, deletedTasklistId: savedListId, deletedPropertyKey: PRACTICE_STATE_KEY, }; console.log(JSON.stringify(report, null, 2)); return report; } finally { lock.releaseLock(); } } /** * Reads one bounded page of personal connections with an explicit personFields mask * and keeps display names only for the configured example email addresses. * @param {number} pageSize * @returns {Map} */ function lookupPracticeRequesterNames_(pageSize) { const targetEmails = new Set( PRACTICE_FOLLOW_UP_REQUESTS.map((item) => item.requesterEmail.toLowerCase()), ); const response = People.People.Connections.list('people/me', { personFields: 'names,emailAddresses', pageSize: pageSize, }); if (!response || typeof response !== 'object') { throw new Error('People API returned an unexpected connections response.'); } const connections = response.connections === undefined ? [] : response.connections; if (!Array.isArray(connections)) { throw new Error('People API returned connections in an unexpected format.'); } /** @type {Map} */ const matched = new Map(); for (const person of connections) { if (!person || typeof person !== 'object') continue; const displayName = selectPrimaryDisplayName_(person); if (!displayName || !Array.isArray(person.emailAddresses)) continue; for (const entry of person.emailAddresses) { if (!entry || typeof entry.value !== 'string') continue; const normalized = entry.value.trim().toLowerCase(); if (targetEmails.has(normalized) && !matched.has(normalized)) { matched.set(normalized, displayName); } } } return matched; } /** * @param {People.Schema.Person} person * @returns {string | null} */ function selectPrimaryDisplayName_(person) { if (!Array.isArray(person.names) || person.names.length === 0) return null; const primary = person.names.find( (candidate) => candidate && candidate.metadata && candidate.metadata.primary === true && typeof candidate.displayName === 'string' && candidate.displayName.trim().length > 0, ); if (primary && typeof primary.displayName === 'string') { return primary.displayName.trim(); } const firstNamed = person.names.find( (candidate) => candidate && typeof candidate.displayName === 'string' && candidate.displayName.trim().length > 0, ); return firstNamed && typeof firstNamed.displayName === 'string' ? firstNamed.displayName.trim() : null; } /** * @param {Map} matchedNames * @returns {PlannedPracticeTask_[]} */ function buildPlannedPracticeTasks_(matchedNames) { return PRACTICE_FOLLOW_UP_REQUESTS.map((request) => { const normalizedEmail = request.requesterEmail.toLowerCase(); const contactName = matchedNames.get(normalizedEmail); const requesterName = contactName !== undefined ? contactName : request.fallbackName; /** @type {'contacts' | 'fallback'} */ const nameSource = contactName !== undefined ? 'contacts' : 'fallback'; const dueTimestamp = formatUtcMidnightRfc3339_(request.dueDateUtc); return { requestId: request.requestId, requesterName: requesterName, nameSource: nameSource, title: '[' + request.requestId + '] ' + request.summary + ' (' + requesterName + ')', notes: 'Practice follow-up for ' + request.requestId + '. Requester: ' + requesterName + ' <' + request.requesterEmail + '>.', dueDateUtc: request.dueDateUtc, dueTimestamp: dueTimestamp, }; }); } /** * Formats a validated YYYY-MM-DD calendar date at UTC midnight so the Tasks API * records the exact intended date when discarding the time-of-day portion. * @param {string} calendarDate * @returns {string} */ function formatUtcMidnightRfc3339_(calendarDate) { if (!/^\d{4}-\d{2}-\d{2}$/.test(calendarDate)) { throw new Error('Due date must use YYYY-MM-DD format: ' + calendarDate); } const timestamp = Date.parse(calendarDate + 'T00:00:00.000Z'); if (Number.isNaN(timestamp)) { throw new Error('Due date is not a valid calendar date: ' + calendarDate); } const iso = new Date(timestamp).toISOString(); if (iso.slice(0, 10) !== calendarDate) { throw new Error('Due date rolled over to another calendar day: ' + calendarDate); } return calendarDate + 'T00:00:00.000Z'; } /** * @param {string} desiredTitle * @param {PracticeTasksState_} state * @param {PropertiesService.Properties} properties * @returns {string} */ function ensurePracticeTaskList_(desiredTitle, state, properties) { if (state.tasklistId !== null) { if (state.tasklistId === '@default') { throw new Error('Saved state must never target the @default task list.'); } const existing = Tasks.Tasklists.get(state.tasklistId); if (!existing || existing.kind !== 'tasks#taskList' || existing.id !== state.tasklistId) { throw new Error('Saved practice task list could not be verified. Inspect Google Tasks before retrying.'); } if (existing.title !== desiredTitle) { const patched = Tasks.Tasklists.patch({ title: desiredTitle }, state.tasklistId); if (!patched || patched.id !== state.tasklistId) { throw new Error('Tasks API returned an unexpected response when updating the practice list title.'); } state.tasklistTitle = desiredTitle; writePracticeTaskState_(properties, state); } return state.tasklistId; } const created = Tasks.Tasklists.insert({ title: desiredTitle }); if ( !created || created.kind !== 'tasks#taskList' || typeof created.id !== 'string' || created.id.length === 0 || created.id === '@default' ) { throw new Error('Tasks API did not return a valid dedicated task list ID.'); } state.tasklistId = created.id; state.tasklistTitle = desiredTitle; // Save the list ID immediately so an interrupted task insert does not orphan the list. writePracticeTaskState_(properties, state); return created.id; } /** * @param {string} tasklistId * @param {PlannedPracticeTask_} planned * @param {PracticeTasksState_} state * @param {PropertiesService.Properties} properties * @returns {{requestId: string, taskId: string, action: string, dueTimestamp: string}} */ function reconcileSinglePracticeTask_(tasklistId, planned, state, properties) { const saved = state.tasksByRequestId[planned.requestId]; if (saved) { const remote = Tasks.Tasks.get(tasklistId, saved.taskId); if (!remote || remote.kind !== 'tasks#task' || remote.id !== saved.taskId) { throw new Error('Saved task ' + saved.taskId + ' returned an unexpected response.'); } if (remote.deleted === true) { throw new Error( 'Saved practice task for ' + planned.requestId + ' is marked deleted in Google Tasks. Run removePracticeTaskList to reset the exercise cleanly.', ); } const remoteDueDate = typeof remote.due === 'string' ? remote.due.slice(0, 10) : ''; const unchanged = remote.title === planned.title && remote.notes === planned.notes && remoteDueDate === planned.dueDateUtc; if (unchanged) { return { requestId: planned.requestId, taskId: saved.taskId, action: 'unchanged', dueTimestamp: planned.dueTimestamp, }; } const patched = Tasks.Tasks.patch( { title: planned.title, notes: planned.notes, due: planned.dueTimestamp, }, tasklistId, saved.taskId, ); if (!patched || typeof patched.id !== 'string' || patched.id !== saved.taskId) { throw new Error('Tasks API returned an unexpected patch response for ' + planned.requestId + '.'); } state.tasksByRequestId[planned.requestId] = { taskId: saved.taskId, title: planned.title, dueDateUtc: planned.dueDateUtc, }; writePracticeTaskState_(properties, state); return { requestId: planned.requestId, taskId: saved.taskId, action: 'updated', dueTimestamp: planned.dueTimestamp, }; } const inserted = Tasks.Tasks.insert( { title: planned.title, notes: planned.notes, due: planned.dueTimestamp, status: 'needsAction', }, tasklistId, ); if (!inserted || inserted.kind !== 'tasks#task' || typeof inserted.id !== 'string' || inserted.id.length === 0) { throw new Error('Tasks API did not return a valid task ID for ' + planned.requestId + '.'); } state.tasksByRequestId[planned.requestId] = { taskId: inserted.id, title: planned.title, dueDateUtc: planned.dueDateUtc, }; writePracticeTaskState_(properties, state); return { requestId: planned.requestId, taskId: inserted.id, action: 'created', dueTimestamp: planned.dueTimestamp, }; } /** * @param {PropertiesService.Properties} properties * @returns {PracticeTasksState_ | null} */ function readPracticeTaskState_(properties) { const raw = properties.getProperty(PRACTICE_STATE_KEY); if (raw === null) return null; if (raw.length === 0 || raw.length > MAX_STATE_LENGTH) { throw new Error('Stored practice task state has an invalid length.'); } /** @type {unknown} */ let parsed; try { parsed = JSON.parse(raw); } catch (_error) { throw new Error('Stored practice task state in Script Properties is not valid JSON.'); } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { throw new Error('Stored practice task state must be a JSON object.'); } const record = /** @type {{[key: string]: unknown}} */ (parsed); if (record.version !== 1) { throw new Error('Unsupported practice task state version.'); } if ( record.tasklistId !== null && (typeof record.tasklistId !== 'string' || record.tasklistId.length === 0 || record.tasklistId === '@default') ) { throw new Error('Stored tasklistId is invalid.'); } if (typeof record.tasklistTitle !== 'string' || record.tasklistTitle.trim().length === 0) { throw new Error('Stored tasklistTitle is invalid.'); } if ( !record.tasksByRequestId || typeof record.tasksByRequestId !== 'object' || Array.isArray(record.tasksByRequestId) ) { throw new Error('Stored tasksByRequestId map is invalid.'); } /** @type {Set} */ const allowedIds = new Set(PRACTICE_FOLLOW_UP_REQUESTS.map((item) => item.requestId)); const rawMap = /** @type {{[key: string]: unknown}} */ (record.tasksByRequestId); /** @type {{[requestId: string]: SavedPracticeTask_}} */ const validatedMap = {}; for (const key of Object.keys(rawMap)) { if (!allowedIds.has(key)) { throw new Error('Stored tasksByRequestId contains an unknown request ID: ' + key); } const entry = rawMap[key]; if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { throw new Error('Stored task entry for ' + key + ' must be an object.'); } const taskRecord = /** @type {{[field: string]: unknown}} */ (entry); if (typeof taskRecord.taskId !== 'string' || taskRecord.taskId.length === 0) { throw new Error('Stored task entry for ' + key + ' is missing taskId.'); } if (typeof taskRecord.title !== 'string' || taskRecord.title.length === 0) { throw new Error('Stored task entry for ' + key + ' is missing title.'); } if (typeof taskRecord.dueDateUtc !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(taskRecord.dueDateUtc)) { throw new Error('Stored task entry for ' + key + ' has an invalid dueDateUtc.'); } validatedMap[key] = { taskId: taskRecord.taskId, title: taskRecord.title, dueDateUtc: taskRecord.dueDateUtc, }; } return { version: 1, tasklistId: record.tasklistId, tasklistTitle: record.tasklistTitle, tasksByRequestId: validatedMap, }; } /** * @param {PropertiesService.Properties} properties * @param {PracticeTasksState_} state */ function writePracticeTaskState_(properties, state) { const serialized = JSON.stringify(state); if (serialized.length > MAX_STATE_LENGTH) { throw new Error('Serialized practice task state exceeds the lesson storage cap.'); } properties.setProperty(PRACTICE_STATE_KEY, serialized); } function requireTasksContactsConfig_() { const title = TASKS_CONTACTS_CONFIG.practiceListTitle; if (typeof title !== 'string' || title.trim().length < 3 || title.trim().length > 80) { throw new Error('practiceListTitle must be a non-empty string between 3 and 80 characters.'); } if (typeof TASKS_CONTACTS_CONFIG.lookupContacts !== 'boolean') { throw new Error('lookupContacts must be true or false.'); } const pageSize = TASKS_CONTACTS_CONFIG.contactPageSize; if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > MAX_CONTACT_PAGE_SIZE) { throw new Error('contactPageSize must be an integer from 1 through ' + MAX_CONTACT_PAGE_SIZE + '.'); } if (typeof TASKS_CONTACTS_CONFIG.approvePracticeWrite !== 'boolean') { throw new Error('approvePracticeWrite must be true or false.'); } if (typeof TASKS_CONTACTS_CONFIG.confirmRemovePracticeList !== 'boolean') { throw new Error('confirmRemovePracticeList must be true or false.'); } return { practiceListTitle: title.trim(), lookupContacts: TASKS_CONTACTS_CONFIG.lookupContacts, contactPageSize: pageSize, approvePracticeWrite: TASKS_CONTACTS_CONFIG.approvePracticeWrite, confirmRemovePracticeList: TASKS_CONTACTS_CONFIG.confirmRemovePracticeList, }; }