import * as z from "zod" import { defineAction } from "../../../automation/actions" import { toGoogleConditionalFormatRule } from "../lib/formatting" import { getGoogleSheetsApi, normalizeConditionalFormatRule, normalizeSpreadsheetId, resolveConditionalFormatRule, resolveSameSheetRangeTargets, } from "../lib/google-sheets" import { GOOGLE_SHEETS_WRITE_REQUIREMENT } from "../lib/scopes" import { CONDITIONAL_FORMAT_RULE_INPUT_SCHEMA, CONDITIONAL_FORMAT_RULE_SCHEMA, RANGE_TARGET_SCHEMA, SPREADSHEET_REFERENCE_SCHEMA, } from "../lib/schemas" /** Adds a boolean or gradient conditional-format rule at a sheet priority. */ export const createGoogleSheetsConditionalFormatRule = defineAction( "Create Google Sheets conditional format rule", ) .describe("Adds a typed conditional-format rule to one sheet.") .account("google", GOOGLE_SHEETS_WRITE_REQUIREMENT) .input( z.object({ /** Zero-based insertion priority. Defaults to highest priority. */ index: z.number().int().nonnegative().optional(), /** Non-empty grid ranges or table sections on one sheet. */ ranges: RANGE_TARGET_SCHEMA.array().min(1), /** Boolean or gradient rule definition. */ rule: CONDITIONAL_FORMAT_RULE_INPUT_SCHEMA, /** Spreadsheet ID or standard Google Sheets URL. */ spreadsheet: SPREADSHEET_REFERENCE_SCHEMA, }), ) .output(CONDITIONAL_FORMAT_RULE_SCHEMA) .retry({ replaySafety: "unsafe" }) .handler(async ({ account, input }) => { const sheetsApi = getGoogleSheetsApi(account.secret) const spreadsheetId = normalizeSpreadsheetId(input.spreadsheet) const { ranges, sheetId } = await resolveSameSheetRangeTargets( sheetsApi, spreadsheetId, input.ranges, ) const index = input.index ?? 0 await sheetsApi.spreadsheets.batchUpdate({ requestBody: { requests: [ { addConditionalFormatRule: { index, rule: toGoogleConditionalFormatRule(input.rule, ranges), }, }, ], }, spreadsheetId, }) return normalizeConditionalFormatRule( ( await resolveConditionalFormatRule( sheetsApi, spreadsheetId, sheetId, index, ) ).rule, index, ) })