import * as z from "zod" import { defineAction } from "../../../automation/actions" import { getGoogleSheetsApi, normalizeConditionalFormatRule, normalizeSpreadsheetId, resolveSheet, } from "../lib/google-sheets" import { GOOGLE_SHEETS_WRITE_REQUIREMENT } from "../lib/scopes" import { CONDITIONAL_FORMAT_RULE_SCHEMA, SHEET_REFERENCE_SCHEMA, SPREADSHEET_REFERENCE_SCHEMA, } from "../lib/schemas" /** Moves a conditional-format rule to a different sheet priority. */ export const moveGoogleSheetsConditionalFormatRule = defineAction( "Move Google Sheets conditional format rule", ) .describe("Moves a conditional-format rule between zero-based indexes.") .account("google", GOOGLE_SHEETS_WRITE_REQUIREMENT) .input( z.object({ /** Current zero-based rule index. */ fromIndex: z.number().int().nonnegative(), /** Sheet title or immutable numeric sheet ID. */ sheet: SHEET_REFERENCE_SCHEMA, /** Spreadsheet ID or standard Google Sheets URL. */ spreadsheet: SPREADSHEET_REFERENCE_SCHEMA, /** New zero-based rule index. */ toIndex: z.number().int().nonnegative(), }), ) .output(CONDITIONAL_FORMAT_RULE_SCHEMA) .retry({ replaySafety: "unsafe" }) .handler(async ({ account, input }) => { const sheetsApi = getGoogleSheetsApi(account.secret) const spreadsheetId = normalizeSpreadsheetId(input.spreadsheet) const { data } = await sheetsApi.spreadsheets.batchUpdate({ requestBody: { requests: [ { updateConditionalFormatRule: { index: input.fromIndex, newIndex: input.toIndex, sheetId: ( await resolveSheet(sheetsApi, spreadsheetId, input.sheet) ).properties!.sheetId!, }, }, ], }, spreadsheetId, }) const reply = data.replies?.[0]?.updateConditionalFormatRule const rule = reply?.newRule if (!rule) throw new Error("Google did not return the moved rule.") return normalizeConditionalFormatRule(rule, reply.newIndex ?? input.toIndex) })