Skip to content
Skip to chapter

Chapter 28

Workspace services

14 min read

Google Tasks and Contacts APIs

Look up contacts with the Advanced People service after ContactsApp retirement, and create idempotent follow-up items with the Advanced Tasks service.

By the end

Enable the Advanced People and Tasks services, resolve optional contact display names with an explicit personFields mask, and create or reconcile two follow-up tasks in a dedicated practice task list without duplicating items across reruns.

Chapter navigation

Turn requests into follow-up tasks without ContactsApp

Preview two fictional follow-up requests, resolve optional requester display names from Google Contacts through the Advanced People service (People), and create two tracked tasks inside a dedicated Apps Script Request Practice list through the Advanced Tasks service (Tasks). The script stores the practice list ID and task IDs in PropertiesService so later runs inspect or patch the existing items instead of creating duplicates.

You need Understand the runtime and permissions for OAuth consent and execution identity, State across runs with PropertiesService for locked state updates, and Inspect a folder with Advanced Drive v3 for Discovery-backed advanced services and Cloud project enablement.

Older Apps Script tutorials often look up people with ContactsApp.getContact() or ContactsApp.getContactsByEmailAddress(). Those calls no longer run. Google deprecated and shut down ContactsApp together with the legacy Google Contacts API, directing Apps Script projects to the Advanced People service. Even where legacy examples still circulate online, calling ContactsApp throws an error at runtime.

Google Tasks has never had a built-in TasksApp wrapper in Apps Script. Every script that reads or writes Google Tasks uses the Advanced Tasks service, which wraps the Google Tasks REST API v1 under the global identifier Tasks.

Install the project and enable People and Tasks

Use a personal test Google account or disposable Workspace test account. Do not run the exercise against an account whose contacts or task lists are subject to compliance retention or shared with production workflows.

  1. At script.google.com, create a standalone Apps Script project named Tasks and Contacts practice.

  2. Replace Code.gs with the complete source below.

  3. In Project Settings, enable Show "appsscript.json" manifest file in editor, return to Editor, replace appsscript.json with the supplied manifest, and save both files.

  4. Keep approvePracticeWrite: false and confirmRemovePracticeList: false in TASKS_CONTACTS_CONFIG for the first run.

  5. In Editor, verify under Services that People API (People) and Google Tasks API (Tasks) appear from enabledAdvancedServices without adding duplicates through Services > Add a service.

  6. Under Overview > Project OAuth Scopes, verify that the project requests https://www.googleapis.com/auth/contacts.readonly and https://www.googleapis.com/auth/tasks.

Code.gs
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<string, string>}
 */
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<string, string>} */
  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<string, string>} 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<string>} */
  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,
  };
}

Download Code.gs

The manifest declares both Discovery wrappers and the two explicit OAuth scopes:

appsscript.json
{
  "timeZone": "Etc/UTC",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "People",
        "serviceId": "peopleapi",
        "version": "v1"
      },
      {
        "userSymbol": "Tasks",
        "serviceId": "tasks",
        "version": "v1"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/contacts.readonly",
    "https://www.googleapis.com/auth/tasks"
  ]
}

Download appsscript.json

Each entry in enabledAdvancedServices binds three values from the manifest dependency specification:

  • People maps userSymbol: "People" to serviceId: "peopleapi" at version: "v1". The Discovery serviceId is "peopleapi", whereas the Drive service in the previous chapter used "drive".

  • Tasks maps userSymbol: "Tasks" to serviceId: "tasks" at version: "v1".

As Inspect a folder with Advanced Drive v3 explained, a standalone script's default Google Cloud project enables the matching APIs automatically when you save enabledAdvancedServices. If your organization links the script to a standard Cloud project, an administrator of that Cloud project must enable both Google People API and Google Tasks API under APIs & Services in Cloud Console before any call can succeed.

Keep contact access read-only and task writes explicit

The manifest requests two narrow scopes rather than full account access:

ScopeServiceWhy this project requests it
https://www.googleapis.com/auth/contacts.readonlyPeople API v1Reads the executing user's personal contacts without permission to create, edit, or delete contacts
https://www.googleapis.com/auth/tasksTasks API v1Creates the dedicated practice task list, inserts and patches the two practice tasks, and removes that practice list during cleanup

The People API authorization guide separates read-only personal contact access (contacts.readonly) from read-write contact access (contacts), "Other contacts" access (contacts.other.readonly), and Workspace directory access (directory.readonly). Because this script never modifies Google Contacts, contacts.readonly is sufficient.

For Google Tasks, https://www.googleapis.com/auth/tasks.readonly supports listing and reading tasks, while creating a dedicated task list and inserting tasks require https://www.googleapis.com/auth/tasks (see tasks.insert). That scope covers every task list owned by the executing user, including the primary My Tasks list. Isolating writes to the dedicated Apps Script Request Practice list is a boundary enforced by Code.gs, not by the OAuth token itself.

Inside the entrypoints, ScriptApp.requireScopes checks granular OAuth consent before calling either API:

  • previewFollowUpTaskPlan requires contacts.readonly only when lookupContacts is true, and does not require tasks because preview performs no Google Tasks reads or writes.

  • syncApprovedPracticeTasks requires tasks, plus contacts.readonly when lookupContacts is true.

  • removePracticeTaskList requires only tasks.

Apps Script can still display the initial project-wide consent screen before entering the first function you run from the editor toolbar (see the authorization guide).

Read the double-namespace Discovery layout

Both services repeat their identifier in method calls such as People.People.Connections.list and Tasks.Tasks.insert. That repetition comes from two separate layers:

  1. The outer People or Tasks identifier is the userSymbol declared in appsscript.json.

  2. The second segment is the capitalized Discovery resource collection: People (with nested Connections), ContactGroups, and OtherContacts in People API v1, and Tasklists and Tasks in Tasks API v1.

The project's calls map directly to these underlying REST endpoints:

REST endpointAdvanced service callArgument order
GET /v1/{resourceName}/connectionsPeople.People.Connections.list(resourceName, optionalArgs)'people/me', then { personFields, pageSize }
POST /tasks/v1/users/@me/listsTasks.Tasklists.insert(resource){ title } request body
GET /tasks/v1/users/@me/lists/{tasklist}Tasks.Tasklists.get(tasklist)Required tasklist ID
PATCH /tasks/v1/users/@me/lists/{tasklist}Tasks.Tasklists.patch(resource, tasklist){ title } body, then tasklist ID
DELETE /tasks/v1/users/@me/lists/{tasklist}Tasks.Tasklists.remove(tasklist)Required tasklist ID (delete becomes remove)
POST /tasks/v1/lists/{tasklist}/tasksTasks.Tasks.insert(resource, tasklist)Task body first, then tasklist ID
GET /tasks/v1/lists/{tasklist}/tasks/{task}Tasks.Tasks.get(tasklist, task)tasklist ID, then task ID
PATCH /tasks/v1/lists/{tasklist}/tasks/{task}Tasks.Tasks.patch(resource, tasklist, task)Partial Task body first, then tasklist ID, then task ID

Watch the argument order on write methods. As documented in the advanced-services guide, a method that accepts a request body takes that resource object before any path parameters. Tasks.Tasks.get(tasklistId, taskId) starts with tasklistId because GET has no request body, whereas Tasks.Tasks.patch(resource, tasklistId, taskId) puts resource first and shifts tasklistId and taskId to positions two and three.

Notice also Tasks.Tasklists.remove(savedListId). The REST method is tasklists.delete, and because delete is a reserved JavaScript keyword, Apps Script renames every Discovery delete method to remove (Tasks.Tasklists.remove and Tasks.Tasks.remove). Calling Tasks.Tasklists.delete throws a TypeError before any network call occurs (see TypeError: X is not a function).

Request explicit contact fields with personFields

In lookupPracticeRequesterNames_, the script reads one bounded page of personal contacts for the authenticated user ('people/me'):

Source
const response = People.People.Connections.list('people/me', {
  personFields: 'names,emailAddresses',
  pageSize: pageSize,
});

Unlike built-in Apps Script classes that load default fields automatically, People API v1 requires the caller to name every Person field family it wants returned. In people.connections.list, personFields is a required query parameter. Requesting 'names,emailAddresses' populates person.names and person.emailAddresses while leaving phone numbers, addresses, birthdays, photos, and biographies unset.

warning

Omitting personFields on People.People.Connections.list or omitting readMask on People.People.searchContacts fails immediately with HTTP 400 (Please specify a personFields mask or read_mask error). Notice that the two endpoints name the mask parameter differently: Connections.list requires personFields, whereas people.searchContacts requires readMask, as in People.People.searchContacts({ query: 'alex.rivera@example.com', readMask: 'names,emailAddresses', pageSize: 5 }).

Why does this example use Connections.list instead of searchContacts? Both methods work under contacts.readonly, and each fits a different workload:

  • People.People.Connections.list reads directly from the user's stored contacts collection in pages (pageSize up to 1,000, continued via nextPageToken). An edit you save in Google Contacts is visible right away on the next Connections.list call.

  • People.People.searchContacts matches prefix queries across contact names, email addresses, and phone numbers, capped at small result pages (pageSize up to 30). As the searchContacts documentation explains, Google maintains that index as a lazy per-user cache that updates asynchronously after a warmup request (People.People.searchContacts({ query: '', readMask: 'names,emailAddresses', pageSize: 1 })). Right after you create or edit a contact during testing, searchContacts can miss the change for several seconds while the cache warms up.

For a bounded exercise of up to 25 contacts (MAX_CONTACT_PAGE_SIZE = 50), Connections.list gives immediate, repeatable results. In a production directory or large address book with hundreds of contacts, either paginate Connections.list with nextPageToken into a short-lived lookup map or send the warmup request before calling searchContacts.

Each element of response.connections is a Person resource where every field is an optional array, because one contact can hold multiple names (for example, a contact record merged with a Google profile) and multiple email addresses (home, work, other):

  • selectPrimaryDisplayName_ checks person.names for an entry with metadata.primary === true and a non-empty displayName, falling back to the first non-empty displayName if none is marked primary.

  • Email matching normalizes entry.value.trim().toLowerCase() against the two configured @example.com addresses (alex.rivera@example.com and sam.chen@example.com).

  • When an account has zero contacts (response.connections === undefined) or no contact matches an @example.com email, lookupPracticeRequesterNames_ returns no entry for that address and buildPlannedPracticeTasks_ uses request.fallbackName (Alex Rivera or Sam Chen). Unmatched personal contacts from your account are never logged, stored in PropertiesService, or written to Google Tasks.

Format due dates at UTC midnight for Google Tasks

Each request in PRACTICE_FOLLOW_UP_REQUESTS declares a calendar date string ('2026-12-01' and '2026-12-03'). Before building the task payload, formatUtcMidnightRfc3339_ checks the YYYY-MM-DD syntax, parses calendarDate + 'T00:00:00.000Z', verifies with toISOString().slice(0, 10) that JavaScript did not roll an invalid calendar day such as '2026-02-30' into March, and returns the RFC 3339 UTC midnight string:

Source
return calendarDate + 'T00:00:00.000Z';

note

In the Google Tasks REST API Task resource, due must be sent as a full RFC 3339 timestamp string ("2026-12-01T00:00:00.000Z"), yet the API discards the time-of-day portion and stores only the UTC calendar date. You cannot read or set a due time-of-day through the Tasks Public API v1. If you construct a Date at 6 PM in America/Los_Angeles (2026-12-01T18:00:00-08:00) and call .toISOString(), JavaScript converts the instant to "2026-12-02T02:00:00.000Z", and Google Tasks saves the task on December 2 instead of December 1. Formatting a validated YYYY-MM-DD label directly at T00:00:00.000Z keeps the stored date aligned with the intended calendar day in every time zone.

When reconcileSinglePracticeTask_ later reads a task back with Tasks.Tasks.get, Google Tasks returns remote.due as an RFC 3339 midnight string such as "2026-12-01T00:00:00.000Z". Comparing remote.due.slice(0, 10) against planned.dueDateUtc checks the stored calendar date without depending on fractional-second formatting (".000Z" versus "Z").

Isolate practice work from the default task list

Google Tasks gives every account a primary list addressable through the special alias '@default'. Passing '@default' to Tasks.Tasks.insert(task, '@default') mixes automated practice items into your real personal task list, and cleanup code that iterates over '@default' risks touching tasks the script did not create.

Instead, ensurePracticeTaskList_ creates and tracks one dedicated list titled Apps Script Request Practice:

  1. Both ensurePracticeTaskList_ and readPracticeTaskState_ reject '@default' if it ever appears in state.tasklistId.

  2. On the first approved sync (state.tasklistId === null), Tasks.Tasklists.insert({ title: desiredTitle }) (tasklists.insert) creates the new list and returns a TaskList object with a server-assigned id.

  3. Right after Tasks.Tasklists.insert returns, ensurePracticeTaskList_ saves state.tasklistId to PropertiesService (book.tasks-and-contacts.state.v1) before inserting the first task so an interrupted run reuses that list instead of creating a duplicate.

  4. On subsequent runs where state.tasklistId is already recorded, Tasks.Tasklists.get(state.tasklistId) (tasklists.get) confirms the list still exists, and Tasks.Tasklists.patch updates its title only if you edited practiceListTitle in TASKS_CONTACTS_CONFIG.

Reconcile saved task IDs instead of duplicating tasks

Unlike PropertiesService keys, Google Tasks does not enforce uniqueness on task titles. Calling Tasks.Tasks.insert twice with [REQ-201] Confirm room setup for Tuesday workshop (Alex Rivera) creates two separate tasks with different server IDs.

To make reruns idempotent, syncApprovedPracticeTasks wraps the entire read-reconcile-write sequence inside LockService.getScriptLock() (lock.waitLock(5000) with lock.releaseLock() in finally) and maps each stable requestId (REQ-201, REQ-202) to its server taskId inside state.tasksByRequestId:

State for requestIdRemote state from Tasks.Tasks.getAction taken
No saved taskIdNot calledCalls Tasks.Tasks.insert, saves returned taskId immediately to PropertiesService, reports 'created'
Saved taskId presentMatches planned title, notes, and dueDateUtc, with deleted !== trueMakes zero write calls, reports 'unchanged'
Saved taskId presenttitle, notes, or dueDateUtc differs, with deleted !== trueCalls Tasks.Tasks.patch on that exact taskId, updates saved state, reports 'updated'
Saved taskId presentremote.deleted === true or 404Stops and throws an error instructing you to inspect or run removePracticeTaskList

Persisting state right after each Tasks.Tasks.insert call narrows the window for partial failure. Suppose REQ-201 is inserted and saved, and a transient network error stops REQ-202. When you rerun syncApprovedPracticeTasks, REQ-201 already has a saved taskId, so the script verifies REQ-201 as 'unchanged' and inserts only REQ-202. As State across runs with PropertiesService noted, the remote Tasks call and the local PropertiesService write are still two separate operations: if Apps Script terminates in the brief instant between Tasks.Tasks.insert returning and properties.setProperty completing, inspect the Apps Script Request Practice list in Google Tasks before rerunning.

tip

Prefer Tasks.Tasks.patch over Tasks.Tasks.update when refreshing task metadata. Tasks.Tasks.update replaces the full Task resource and expects id plus current mutable fields, so omitting status or completed can overwrite a task's completion state or fail validation. Tasks.Tasks.patch({ title, notes, due }, tasklistId, taskId) modifies only title, notes, and due, so if someone already checked off the task in Google Tasks (status: "completed"), patching a display-name typo keeps the task marked completed.

Preview, sync, and test idempotent updates

Run the workflow in three controlled stages from the Apps Script editor:

  1. With approvePracticeWrite: false and confirmRemovePracticeList: false, select previewFollowUpTaskPlan in the toolbar and click Run. Approve the OAuth consent prompt under your test account.

  2. Inspect the JSON report in Execution log:

Preview fieldExpected baseline value
savedTasklistIdnull before the first sync
contactLookupEnabledtrue
matchedContactCount0 when no @example.com contact exists in Google Contacts
items[0].nameSource, items[1].nameSource'fallback' (Alex Rivera and Sam Chen)
items[0].dueTimestamp'2026-12-01T00:00:00.000Z'
items[0].plannedAction'insert'
writesPerformedfalse
  1. In TASKS_CONTACTS_CONFIG, change approvePracticeWrite from false to true and save Code.gs.

  2. Select syncApprovedPracticeTasks and click Run once. Confirm that results[0].action and results[1].action are 'created'.

  3. Open Google Tasks (in the Gmail or Calendar right-hand sidebar or at tasks.google.com) and confirm Apps Script Request Practice holds [REQ-201] and [REQ-202] while My Tasks is unchanged.

  4. Run syncApprovedPracticeTasks a second time. Both entries report action: 'unchanged' with the same taskId strings, and Apps Script Request Practice still shows two items.

Next, test how contact resolution and configuration flags change the behavior:

Change to makePrediction before runningWhat to observe
Set lookupContacts: false, save, and run syncApprovedPracticeTasksSkips People.People.Connections.list, and fallback names still match saved taskscontactLookupEnabled: false, both results report 'unchanged'
Restore lookupContacts: true. In Google Contacts (contacts.google.com), create one test contact named Alex Rivera (Facilities) with email alex.rivera@example.com, then run previewFollowUpTaskPlanConnections.list matches alex.rivera@example.com and plans an update for REQ-201matchedContactCount: 1, items[0].nameSource: 'contacts', items[0].plannedAction: 'inspect_or_patch'
Run syncApprovedPracticeTasks once with that test contact presentPatches REQ-201 title and notes in place and leaves REQ-202 untouchedresults[0].action: 'updated', results[1].action: 'unchanged', task count in Google Tasks stays two
Delete the Alex Rivera (Facilities) test contact in Google Contacts, then run syncApprovedPracticeTasksREQ-201 reverts to fallback name Alex Rivera via Tasks.Tasks.patchresults[0].action: 'updated', results[1].action: 'unchanged'

Notice that if your test account already has more than 25 personal contacts sorted ahead of Alex Rivera (Facilities) in Google Contacts, a single 25-item Connections.list page may not reach the new test contact. Increase contactPageSize up to 50 (or test in a clean test account with fewer than 25 contacts) to observe the match on page one.

Classify People and Tasks API errors

Advanced-service failures throw JavaScript exceptions rather than returning HTTP status objects. Use the message in Executions alongside Apps Script service quotas to choose the right fix:

  • ReferenceError: People is not defined or Tasks is not defined: confirm enabledAdvancedServices in appsscript.json declares serviceId: "peopleapi" (userSymbol: "People") and serviceId: "tasks" (userSymbol: "Tasks"), then save the manifest (see ReferenceError: X is not defined).

  • HTTP 400 Request must specify personFields or Invalid value at 'read_mask': add personFields: 'names,emailAddresses' on People.People.Connections.list (or readMask on People.People.searchContacts).

  • HTTP 400 Invalid value for: Invalid format: "..." on Tasks due: verify due is a full RFC 3339 timestamp (YYYY-MM-DDT00:00:00.000Z), not a bare YYYY-MM-DD string.

  • HTTP 403 People API has not been used in project... or Tasks API has not been used...: on a standard Google Cloud project, enable the missing API in Cloud Console and wait a minute before retrying. On a default Cloud project, re-save appsscript.json.

  • Authorization or insufficient-scope error: run the entrypoint from the editor toolbar under the test account and approve both requested scopes during granular consent.

  • HTTP 404 or Saved practice task ... is marked deleted: someone deleted the practice task or list directly in Google Tasks while book.tasks-and-contacts.state.v1 still held its ID. Run removePracticeTaskList (if only a task was deleted) or delete book.tasks-and-contacts.state.v1 under Project Settings > Script Properties after confirming the practice list is already gone in Google Tasks.

  • HTTP 429 rate-limit or quota error: pause before rerunning. Do not loop retries rapidly inside one execution.

Remove the practice task list cleanly

When you finish testing, remove the dedicated practice list and stored property record:

  1. If you created the optional alex.rivera@example.com test contact during the experiment above, delete that contact in Google Contacts first and confirm your real contacts are untouched.

  2. In TASKS_CONTACTS_CONFIG, set approvePracticeWrite: false and confirmRemovePracticeList: true, then save Code.gs.

  3. Select removePracticeTaskList and click Run once. It verifies savedListId is not '@default', calls Tasks.Tasklists.remove(savedListId) to delete Apps Script Request Practice, and deletes book.tasks-and-contacts.state.v1 from Script Properties.

  4. Run removePracticeTaskList a second time to verify clean idempotence: it reports removed: false because the Script Properties key is already absent.

  5. Restore confirmRemovePracticeList: false in Code.gs and save. Open Google Tasks and Project Settings > Script Properties to confirm both the practice list and the property key are gone.

If you want to retire the standalone project completely, you can also remove enabledAdvancedServices and oauthScopes from appsscript.json and revoke the project's OAuth connection under Google Account > Security > Your connections to third-party apps & services.

Next, move to Part 5 and build interactive spreadsheet tools in Menus, sidebars, and modals.

Project files

Complete source files for this chapter's examples.

Resolve contact names and sync idempotent practice tasks

Code.gs
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<string, string>}
 */
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<string, string>} */
  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<string, string>} 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<string>} */
  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,
  };
}

appsscript.json

Download file
appsscript.json
{
  "timeZone": "Etc/UTC",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "People",
        "serviceId": "peopleapi",
        "version": "v1"
      },
      {
        "userSymbol": "Tasks",
        "serviceId": "tasks",
        "version": "v1"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/contacts.readonly",
    "https://www.googleapis.com/auth/tasks"
  ]
}