Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

3.8 KB
Raw Blame
import {
  DedupeStrategy,
  httpClient,
  HttpMethod,
  Polling,
  pollingHelper,
} from '@activepieces/pieces-common';
import {
  AppConnectionValueForAuthProperty,
  createTrigger,
  MarkdownVariant,
  Property,
  TriggerStrategy,
} from '@activepieces/pieces-framework';
import dayjs from 'dayjs';
import { googleFormsCommon, googleFormsAuth, getAccessToken, GoogleFormsAuthValue } from '../common/common';
import { newResponseTriggerOutputSchema } from '../output-schemas';

export const newResponse = createTrigger({
  auth: googleFormsAuth,
  name: 'new_response',
  classification: 'READ',
  displayName: 'New Response',
  description: 'Triggers when someone submits or edits a response to the form.',
  aiMetadata: {
    description:
      'Fires when a respondent submits a new response to the specified Google Form. Each event represents a single form submission, including the response ID, submission timestamps, and the respondent\'s answers keyed by question ID.',
  },
  outputSchema: newResponseTriggerOutputSchema,
  props: {
    info: Property.MarkDown({
      value:
        'Checks the form every few minutes. A response starts the flow when it is sent or edited after the flow is published.',
      variant: MarkdownVariant.INFO,
    }),
    form_id: googleFormsCommon.form_id,
    include_team_drives: googleFormsCommon.include_team_drives,
  },
  sampleData: {
    responseId:
      'ACYDBNhZI4SENjOwT4QIcXOhgco3JhuLftjpLspxETYljVZofOWuqH7bxKQqJWDwGw2IFqE',
    createTime: '2023-04-01T03:19:28.889Z',
    lastSubmittedTime: '2023-04-01T03:19:28.889881Z',
    answers: {
      '5bdc4001': {
        questionId: '5bdc4001',
        textAnswers: {
          answers: [
            {
              value: 'test',
            },
          ],
        },
      },
      '283d759e': {
        questionId: '283d759e',
        textAnswers: {
          answers: [
            {
              value: 'نعم',
            },
          ],
        },
      },
      '46f3e9cf': {
        questionId: '46f3e9cf',
        textAnswers: {
          answers: [
            {
              value: 'test',
            },
          ],
        },
      },
    },
  },
  type: TriggerStrategy.POLLING,
  async test(ctx) {
    return await pollingHelper.test(polling, ctx);
  },
  async onEnable(ctx) {
    await pollingHelper.onEnable(polling, ctx);
  },
  async onDisable(ctx) {
    await pollingHelper.onDisable(polling, ctx);
  },
  async run(ctx) {
    return await pollingHelper.poll(polling, ctx);
  },
});

const polling: Polling<AppConnectionValueForAuthProperty<typeof googleFormsAuth>, { form_id: string }> = {
  strategy: DedupeStrategy.TIMEBASED,
  items: async ({ auth, propsValue, lastFetchEpochMS }) => {
    const items = await getResponse(
      auth,
      propsValue.form_id,
      lastFetchEpochMS === 0 ? null : dayjs(lastFetchEpochMS).toISOString()
    );

    return items
      .sort(
        (a, b) =>
          new Date(b.lastSubmittedTime).getTime() -
          new Date(a.lastSubmittedTime).getTime()
      )
      .map((item) => ({
        epochMilliSeconds: dayjs(item.lastSubmittedTime).valueOf(),
        data: item,
      }));
  },
};

const getResponse = async (
  authentication: GoogleFormsAuthValue,
  form_id: string,
  startDate: string | null
) => {
  let filter = {};
  if (startDate) {
    filter = {
      filter: 'timestamp > ' + startDate,
    };
  }
  const accessToken = await getAccessToken(authentication);
  const response = await httpClient.sendRequest<{
    responses: { lastSubmittedTime: string }[];
  }>({
    url: `https://forms.googleapis.com/v1/forms/${form_id}/responses`,
    method: HttpMethod.GET,
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    queryParams: filter,
  });

  const formResponses = response.body.responses;
  if (formResponses && Array.isArray(formResponses)) {
    return formResponses;
  }
  return [];
};