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

export const updateRowAction = createAction({
  auth: googleSheetsAuth,
  name: 'update_row',
  classification: 'WRITE',
  description: 'Update the data in an existing row.',
  audience: 'human',
  aiMetadata: {
    description:
      'Overwrites the cell values of one existing row, identified by its row number, in a selected worksheet. Use when an agent already knows the target row (e.g. from a Find or Get action) and wants to change its contents. Idempotent — re-running with the same row number and values leaves the sheet in the same state; empty values skip (do not clear) those cells.',
    idempotent: true,
  },
  displayName: 'Update Row',
  propertyGroups: [
    {
      key: 'spreadsheet',
      display: 'section',
      label: 'Spreadsheet',
      icon: 'file',
      props: ['spreadsheetId', 'sheetId'],
    },
    {
      key: 'target_row',
      display: 'section',
      label: 'Row',
      icon: 'markdown',
      props: ['row_id'],
    },
    {
      key: 'changes',
      display: 'section',
      label: 'Changes',
      icon: 'text',
      props: ['empty_fields_info', 'first_row_headers', 'values'],
    },
  ],
  props: {
    ...commonProps,
    row_id: Property.Number({
      displayName: 'Row Number',
      description: 'The row number to update',
      required: true,
    }),
    empty_fields_info: Property.MarkDown({
      value: 'Empty fields keep their current value.',
      variant: MarkdownVariant.INFO,
    }),
    first_row_headers: isFirstRowHeaderProp(),
    values: rowValuesProp(),
  },
  outputSchema: updateRowActionOutputSchema,
  async run(context) {
    const inputSpreadsheetId = context.propsValue.spreadsheetId;
    const inputSheetId = context.propsValue.sheetId;
    const rowId = context.propsValue.row_id;
    const isFirstRowHeaders = context.propsValue.first_row_headers;
    const rowValuesInput = context.propsValue.values;

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

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

    const authClient = await createGoogleClient(context.auth);

    const sheets = googleSheets({ version: 'v4', auth: authClient });

    const sheetName = await getWorkSheetName(
      context.auth,
      spreadsheetId,
      sheetId
    );

    // replace empty string with null to skip the cell value
    const formattedValues = (
      isFirstRowHeaders
        ? objectToArray(rowValuesInput)
        : rowValuesInput['values']
    ).map((value: string | null | undefined) => {
      if (value === '' || value === null || value === undefined) {
        return null;
      }
      if (isString(value)) {
        return value;
      }
      return JSON.stringify(value, null, 2);
    });


    if (formattedValues.length > 0) {
      const response = await sheets.spreadsheets.values.update({
        range: `${sheetName}!A${rowId}:ZZZ${rowId}`,
        spreadsheetId: spreadsheetId,
        valueInputOption: ValueInputOption.USER_ENTERED,
        requestBody: {
          values: [formattedValues],
          majorDimension: Dimension.ROWS,
        },
      });

      //Split the updatedRange string to extract the row number
      const updatedRangeParts = response.data.updatedRange?.split(
        '!'
      );
      const updatedRowRange = updatedRangeParts?.[1];
      const updatedRowNumber = parseInt(
        updatedRowRange?.split(':')[0].substring(1) ?? '0',
        10
      );

      return { updates: { ...response.data }, row: updatedRowNumber };
    } else {
      throw Error(
        'Values passed are empty or not array ' +
        JSON.stringify(formattedValues)
      );
    }
  },
});