import * as z from "zod" import { defineAction } from "../../../automation/actions" import { getGoogleSheetsApi, normalizeSpreadsheet, normalizeSpreadsheetId, } from "../lib/google-sheets" import { GOOGLE_SHEETS_WRITE_REQUIREMENT } from "../lib/scopes" import { SPREADSHEET_REFERENCE_SCHEMA, SPREADSHEET_SCHEMA, } from "../lib/schemas" const RECALCULATION_INTERVALS = { hourly: "HOUR", minutely: "MINUTE", onChange: "ON_CHANGE", } as const /** Updates top-level Google spreadsheet properties. */ export const updateGoogleSpreadsheet = defineAction("Update Google spreadsheet") .describe("Updates spreadsheet title, locale, timezone, or recalculation.") .account("google", GOOGLE_SHEETS_WRITE_REQUIREMENT) .input( z .object({ /** Formula recalculation policy. */ autoRecalc: z.enum(["onChange", "minutely", "hourly"]).optional(), /** Spreadsheet locale, such as `en_US`. */ locale: z.string().min(1).optional(), /** Spreadsheet ID or standard Google Sheets URL. */ spreadsheet: SPREADSHEET_REFERENCE_SCHEMA, /** Spreadsheet timezone, such as `America/New_York`. */ timeZone: z.string().min(1).optional(), /** Human-readable spreadsheet title. */ title: z.string().trim().min(1).optional(), }) .refine( ({ autoRecalc, locale, timeZone, title }) => autoRecalc !== undefined || locale !== undefined || timeZone !== undefined || title !== undefined, "At least one spreadsheet property must be updated.", ), ) .output(SPREADSHEET_SCHEMA) .retry({ replaySafety: "unsafe" }) .handler(async ({ account, input }) => { const spreadsheetId = normalizeSpreadsheetId(input.spreadsheet) const sheetsApi = getGoogleSheetsApi(account.secret) await sheetsApi.spreadsheets.batchUpdate({ requestBody: { requests: [ { updateSpreadsheetProperties: { fields: [ input.autoRecalc === undefined ? undefined : "autoRecalc", input.locale === undefined ? undefined : "locale", input.timeZone === undefined ? undefined : "timeZone", input.title === undefined ? undefined : "title", ] .filter((field) => field !== undefined) .join(","), properties: { autoRecalc: input.autoRecalc ? RECALCULATION_INTERVALS[input.autoRecalc] : undefined, locale: input.locale, timeZone: input.timeZone, title: input.title, }, }, }, ], }, spreadsheetId, }) const { data } = await sheetsApi.spreadsheets.get({ includeGridData: false, spreadsheetId, }) return normalizeSpreadsheet(data) })