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.7 KB
Raw Blame
import { createAction, Property } from '@activepieces/pieces-framework';
import { isNil } from '@activepieces/pieces-framework';
import { sheets as googleSheets } from '@googleapis/sheets';
import {
	areSheetIdsValid,
	createGoogleClient,
	Dimension,
	googleSheetsAuth,
	objectToArray,
	stringifyArray,
	ValueInputOption,
} from '../common/common';
import { commonProps, isFirstRowHeaderProp, rowValuesProp } from '../common/props';
import { getWorkSheetName } from '../triggers/helpers';
import { insertRowAtTopActionOutputSchema } from '../output-schemas';

export const insertRowAtTopAction = createAction({
	auth: googleSheetsAuth,
	name: 'insert-row-at-top',
	classification: 'WRITE',
	displayName: 'Add Row at Top',
	description: 'Inserts a new row at the top of a worksheet, just below the header row.',
	audience: 'human',
	aiMetadata: {
		description:
			'Inserts a blank row near the top of a worksheet and writes the supplied values into it, shifting every existing row below it down by one; the insertion point defaults to just under row 1 but can be moved with Insert After Row. Use when newest-first ordering matters — prefer Add Row to append at the bottom, which is cheaper and does not renumber existing rows. Not idempotent: each call inserts another row and shifts the rest down again.',
		idempotent: false,
	},
	propertyGroups: [
		{
			key: 'spreadsheet',
			display: 'section',
			label: 'Spreadsheet',
			icon: 'file',
			props: ['spreadsheetId', 'sheetId'],
		},
		{
			key: 'new_row',
			display: 'section',
			label: 'New Row',
			icon: 'text',
			props: ['insertAfterRow', 'first_row_headers', 'values'],
		},
	],
	props: {
		...commonProps,
		first_row_headers: isFirstRowHeaderProp(),
		as_string: Property.Checkbox({
			displayName: 'As String',
			description:
				'Store dates and formulas as plain text instead of evaluating them.',
			required: false,
			advanced: true,
		}),
		insertAfterRow: Property.Number({
			displayName: 'Insert After Row',
			description:
				'Insert the new row below this row. Defaults to 1, the header row.',
			required: false,
			defaultValue: 1,
		}),
		values: rowValuesProp(),
	},
	outputSchema: insertRowAtTopActionOutputSchema,
	async run({ auth, propsValue }) {
		const {
			spreadsheetId: inputSpreadsheetId,
			sheetId: inputSheetId,
			as_string,
			first_row_headers,
			insertAfterRow,
			values,
		} = propsValue;

		if (!areSheetIdsValid(inputSpreadsheetId, inputSheetId)) {
			throw new Error('Please select a spreadsheet and sheet first.');
		}

		const spreadsheetId = inputSpreadsheetId as string;
		const sheetId = Number(inputSheetId);

		const afterRow = insertAfterRow && insertAfterRow > 0 ? insertAfterRow : 1;
		const targetRow = afterRow + 1;

		const formattedValues = first_row_headers
			? objectToArray(values).map((val) => (isNil(val) ? '' : val))
			: (values.values as unknown[]);

		const sheetName = await getWorkSheetName(auth, spreadsheetId, sheetId);
		const authClient = await createGoogleClient(auth);
		const sheets = googleSheets({ version: 'v4', auth: authClient });

		await sheets.spreadsheets.batchUpdate({
			spreadsheetId,
			requestBody: {
				requests: [
					{
						insertDimension: {
							range: {
								sheetId,
								dimension: 'ROWS',
								startIndex: afterRow,
								endIndex: afterRow + 1,
							},
							inheritFromBefore: afterRow > 0,
						},
					},
				],
			},
		});

		const updateResponse = await sheets.spreadsheets.values.update({
			spreadsheetId,
			range: `${sheetName}!A${targetRow}:ZZZ${targetRow}`,
			valueInputOption: as_string ? ValueInputOption.RAW : ValueInputOption.USER_ENTERED,
			requestBody: {
				majorDimension: Dimension.ROWS,
				values: [stringifyArray(formattedValues)],
			},
		});

		return {
			row: targetRow,
			updates: updateResponse.data,
		};
	},
});