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

4.8 KB
Raw Blame
import { getHubspotAccessToken, HubspotAuthValue, hubspotAuth } from '../auth';
import {
	AuthenticationType,
	DedupeStrategy,
	httpClient,
	HttpMethod,
	Polling,
	pollingHelper,
	QueryParams,
} from '@activepieces/pieces-common';
import {
	createTrigger,
	TriggerStrategy,
	Property,
} from '@activepieces/pieces-framework';
import { formDropdown } from '../common/props';
import { newFormSubmissionTriggerOutputSchema } from '../output-schemas';
import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';

type Props = {
	formId: string;
	allowMultipleFiles: boolean;
};

type FormSubmissionResponse = {
	results: Array<{
		conversionId: string;
		submittedAt: number;
		pageUrl: string;
		values: Array<{ name: string; value: string }>;
	}>;
	paging?: {
		next?: {
			after: string;
		};
	};
};

type FormField = {
	name: string;
	label: string;
	fieldType: string;
};

const polling: Polling<AppConnectionValueForAuthProperty<typeof hubspotAuth>, Props> = {
	strategy: DedupeStrategy.TIMEBASED,
	async items({ auth, propsValue, lastFetchEpochMS }) {
		const authValue = auth as HubspotAuthValue;
		const formId = propsValue.formId;

		const submissions = [];
		let after;
		do {
			const qs: QueryParams = { limit: '50' };
			if (after) {
				qs.after = after;
			}
			const response = await httpClient.sendRequest<FormSubmissionResponse>({
				method: HttpMethod.GET,
				url: `https://api.hubapi.com/form-integrations/v1/submissions/forms/${formId}`,
				queryParams: qs,
				authentication: {
					type: AuthenticationType.BEARER_TOKEN,
					token: getHubspotAccessToken(authValue),
				},
			});
			after = response.body.paging?.next?.after;
			submissions.push(...response.body.results);
		} while (after);

		const formFields = await httpClient.sendRequest<FormField[]>({
			method: HttpMethod.GET,
			url: `https://api.hubapi.com/forms/v2/fields/${formId}`,
			authentication: {
				type: AuthenticationType.BEARER_TOKEN,
				token: getHubspotAccessToken(authValue),
			},
		});

		const fieldMapping = formFields.body.reduce((acc, field) => {
			acc[field.name] = { label: field.label, fieldType: field.fieldType };
			return acc;
		}, {} as Record<string, { label: string; fieldType: string }>);

		const items = [];

		for (const submission of submissions) {
			const formattedValues: Record<string, any> = {};

			const submissionData = submission.values ?? [];
			for (const fieldValue of submissionData) {
				const field = fieldMapping[fieldValue.name];

				if (field) {
					const { label, fieldType } = field;

					// return an array
					if (
						fieldType === 'checkbox' ||
						(fieldType === 'file' && propsValue.allowMultipleFiles)
					) {
						formattedValues[label] = formattedValues[label] || [];
						formattedValues[label].push(fieldValue.value);
					} else {
						formattedValues[label] = fieldValue.value;
					}
				} else {
					formattedValues[fieldValue.name] = fieldValue.value;
				}
			}
			items.push({
				...submission,
				values: formattedValues,
			});
		}

		return items.map((item) => ({
			epochMilliSeconds: item.submittedAt,
			data: item,
		}));
	},
};

export const newFormSubmissionTrigger = createTrigger({
	auth: hubspotAuth,
	name: 'new-form-submission',
	classification: 'READ',
	displayName: 'New Form Submission',
	description: 'Triggers when a form is submitted.',
	aiMetadata: {
		description:
			'Fires when the selected HubSpot form receives a submission. Each event represents one submission, with field values mapped to their human-readable form labels plus metadata such as submission timestamp, conversion ID, and page URL. Polls the form-integrations submissions API.',
	},
	outputSchema: newFormSubmissionTriggerOutputSchema,
	type: TriggerStrategy.POLLING,
	propertyGroups: [
		{
			key: 'form',
			display: 'section',
			label: 'Form',
			icon: 'file',
			props: ['formId'],
		},
		{
			key: 'files',
			display: 'section',
			label: 'Uploaded Files',
			icon: 'paperclip',
			props: ['allowMultipleFiles'],
		},
	],
	props: {
		formId: formDropdown,
		allowMultipleFiles: Property.Checkbox({
			displayName: 'Allow Multiple Files',
			description: 'Returns every uploaded file as a list; off keeps only the last one.',
			required: true,
			defaultValue: false,
		}),
	},
	async onEnable(context) {
		await pollingHelper.onEnable(polling, context);
	},
	async onDisable(context) {
		await pollingHelper.onDisable(polling, context);
	},
	async test(context) {
		return await pollingHelper.test(polling, context);
	},
	async run(context) {
		return await pollingHelper.poll(polling, context);
	},
	sampleData: {
		conversionId: '82800398-30af-48a0-942a-1d0623fce08c',
		submittedAt: 1735216921730,
		values: {
            "First Name": "John",
            "Last Name": "Doe",
            "Email": "[email protected]",
        },
		pageUrl: 'https://share.hsforms.com/1VXAvM044Tcyaa3Y5XRQFSQsuf7d',
	},
});