import * as z from "zod" import { defineAction } from "../../../automation/actions" import { getGoogleSheetsApi, normalizeSheet, normalizeSpreadsheetId, } from "../lib/google-sheets" import { GOOGLE_SHEETS_WRITE_REQUIREMENT } from "../lib/scopes" import { SHEET_SCHEMA, SPREADSHEET_REFERENCE_SCHEMA } from "../lib/schemas" /** Adds a sheet with optional grid and display properties. */ export const createGoogleSheet = defineAction("Create Google sheet") .describe("Adds a sheet to an existing Google spreadsheet.") .account("google", GOOGLE_SHEETS_WRITE_REQUIREMENT) .input( z.object({ /** Initial allocated column count. */ columnCount: z.number().int().positive().optional(), /** Number of initially frozen columns. */ frozenColumnCount: z.number().int().nonnegative().optional(), /** Number of initially frozen rows. */ frozenRowCount: z.number().int().nonnegative().optional(), /** Whether the sheet is hidden. */ hidden: z.boolean().optional(), /** Zero-based insertion position. */ index: z.number().int().nonnegative().optional(), /** Whether columns lay out right-to-left. */ rightToLeft: z.boolean().optional(), /** Initial allocated row count. */ rowCount: z.number().int().positive().optional(), /** Spreadsheet ID or standard Google Sheets URL. */ spreadsheet: SPREADSHEET_REFERENCE_SCHEMA, /** Human-readable sheet title. */ title: z.string().trim().min(1), }), ) .output(SHEET_SCHEMA) .retry({ replaySafety: "unsafe" }) .handler(async ({ account, input }) => { const { data } = await getGoogleSheetsApi( account.secret, ).spreadsheets.batchUpdate({ requestBody: { requests: [ { addSheet: { properties: { gridProperties: { columnCount: input.columnCount, frozenColumnCount: input.frozenColumnCount, frozenRowCount: input.frozenRowCount, rowCount: input.rowCount, }, hidden: input.hidden, index: input.index, rightToLeft: input.rightToLeft, title: input.title, }, }, }, ], }, spreadsheetId: normalizeSpreadsheetId(input.spreadsheet), }) const properties = data.replies?.[0]?.addSheet?.properties if (!properties) throw new Error("Google did not return the created sheet.") return normalizeSheet({ properties, tables: [] }) })