import * as z from "zod" import { defineAction } from "../../../automation/actions" import { getGoogleFormsApi, normalizeForm, toGoogleFormItem, toGoogleFormSettings, } from "@automate.ax/integration-contracts/google-forms" import { GOOGLE_FORMS_WRITE_REQUIREMENT } from "../lib/scopes" import { FORM_ITEM_INPUT_SCHEMA, FORM_SCHEMA, FORM_SETTINGS_INPUT_SCHEMA, } from "@automate.ax/integration-contracts/google-forms" /** Creates a form and optionally configures its contents and settings. */ export const createGoogleForm = defineAction("Create Google form") .describe("Creates and configures a Google Form.") .account("google", GOOGLE_FORMS_WRITE_REQUIREMENT) .input( z.object({ /** Description visible to respondents. */ description: z.string().optional(), /** Drive document title. Defaults to the respondent-facing title. */ documentTitle: z.string().trim().min(1).optional(), /** Initial form items in display order. */ items: FORM_ITEM_INPUT_SCHEMA.array().optional(), /** Initial quiz and email-collection settings. */ settings: FORM_SETTINGS_INPUT_SCHEMA.optional(), /** Respondent-facing form title. */ title: z.string().trim().min(1), /** Creates the form without publishing or accepting responses. */ unpublished: z.boolean().optional(), }), ) .output(FORM_SCHEMA) .retry({ replaySafety: "unsafe" }) .handler(async ({ account, input }) => { const formsApi = getGoogleFormsApi(account.secret) const { data: created } = await formsApi.forms.create({ requestBody: { info: { documentTitle: input.documentTitle ?? input.title, title: input.title, }, }, unpublished: input.unpublished, }) if (!created.formId) throw new Error("Google Forms returned no form ID.") const requests = [ ...(input.description === undefined ? [] : [ { updateFormInfo: { info: { description: input.description }, updateMask: "description", }, }, ]), ...(input.settings ? [ { updateSettings: { settings: toGoogleFormSettings(input.settings), updateMask: [ input.settings.emailCollection === undefined ? undefined : "emailCollectionType", input.settings.isQuiz === undefined ? undefined : "quizSettings.isQuiz", ] .filter((field): field is string => Boolean(field)) .join(","), }, }, ] : []), ...(input.items ?? []).map((item, index) => ({ createItem: { item: toGoogleFormItem(item), location: { index }, }, })), ] if (requests.length === 0) return normalizeForm(created) const { data } = await formsApi.forms.batchUpdate({ formId: created.formId, requestBody: { includeFormInResponse: true, requests, }, }) return normalizeForm(data.form ?? created) })