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.9 KB
Raw Blame
import { createAction, Property } from '@activepieces/pieces-framework';
import { outsetaAuth } from '../auth';
import { OutsetaClient } from '../common/client';

export const manageAccountMembershipAction = createAction({
  name: 'manage_account_membership',
  classification: 'WRITE',
  auth: outsetaAuth,
  displayName: 'Manage Account Membership',
  description: 'Add or remove a person from an account.',
  audience: 'both',
  aiMetadata: {
    description:
      'Adds or removes a person on an account (membership), by account and person UID. Use to attach or detach a contact; to change an existing member\'s primary-contact flag use Update Account Membership. Idempotent: re-adding an existing member or removing a non-member is a no-op.',
    idempotent: true,
  },
  props: {
    action: Property.StaticDropdown({
      displayName: 'Action',
      required: true,
      options: {
        disabled: false,
        options: [
          { label: 'Add Person to Account', value: 'add' },
          { label: 'Remove Person from Account', value: 'remove' },
        ],
      },
    }),
    accountUid: Property.ShortText({
      displayName: 'Account UID',
      required: true,
      description: 'The UID of the account.',
    }),
    personUid: Property.ShortText({
      displayName: 'Person UID',
      required: true,
      description: 'The UID of the person to add or remove.',
    }),
    isPrimary: Property.Checkbox({
      displayName: 'Is Primary Contact',
      required: false,
      defaultValue: false,
      description:
        'Only used when adding: whether this person should be the primary contact for the account.',
    }),
  },
  async run(context) {
    const client = new OutsetaClient({
      domain: context.auth.props.domain,
      apiKey: context.auth.props.apiKey,
      apiSecret: context.auth.props.apiSecret,
    });

    // Expand every nested collection that might be on an Account so the PUT
    // doesn't echo back a partial body and let the server wipe billing,
    // subscriptions, addresses, etc. Mirrors the same expansion as
    // update-account.ts.
    const account = await client.get<any>(
      `/api/v1/crm/accounts/${context.propsValue.accountUid}?fields=*,BillingAddress.*,MailingAddress.*,PrimaryContact.*,PersonAccount.*,PersonAccount.Person.*,Subscriptions.*`
    );
    const existingMemberships: any[] =
      account.PersonAccount?.items ??
      account.PersonAccount?.Items ??
      (Array.isArray(account.PersonAccount) ? account.PersonAccount : []);

    if (context.propsValue.action === 'add') {
      const alreadyLinked = existingMemberships.some(
        (pa: any) => pa.Person?.Uid === context.propsValue.personUid
      );
      if (alreadyLinked) {
        return {
          action: 'already_member',
          account_uid: context.propsValue.accountUid,
          person_uid: context.propsValue.personUid,
        };
      }
      const updatedMemberships = [
        ...existingMemberships.map((pa: any) => ({
          Uid: pa.Uid,
          Person: { Uid: pa.Person?.Uid },
          IsPrimary: pa.IsPrimary ?? false,
        })),
        {
          Person: { Uid: context.propsValue.personUid },
          IsPrimary: context.propsValue.isPrimary ?? false,
        },
      ];
      // Defensive: flatten any enveloped Subscriptions collection before
      // the PUT so the server doesn't misread {items:[…]} as "no
      // subscriptions" and wipe billing state. Mirrors update-account.ts.
      const flatSubscriptions =
        account.Subscriptions && !Array.isArray(account.Subscriptions)
          ? (account.Subscriptions.items ?? account.Subscriptions.Items ?? [])
          : account.Subscriptions;

      const result = await client.put<any>(
        `/api/v1/crm/accounts/${context.propsValue.accountUid}`,
        { ...account, PersonAccount: updatedMemberships, Subscriptions: flatSubscriptions }
      );
      return {
        action: 'added',
        account_uid: result.Uid ?? null,
        account_name: result.Name ?? null,
        person_count: Array.isArray(result.PersonAccount) ? result.PersonAccount.length : null,
      };
    }

    const membership = existingMemberships.find(
      (pa: any) => pa.Person?.Uid === context.propsValue.personUid
    );
    if (!membership) {
      return {
        action: 'not_a_member',
        account_uid: context.propsValue.accountUid,
        person_uid: context.propsValue.personUid,
      };
    }
    // DELETE endpoint shape verified live on the Outseta API:
    //   DELETE /api/v1/crm/accounts/{accountUid}/memberships/{membershipUid}
    //   With a fake membership UID the API returns 400 "Invalid uid"
    //   (instead of 404 / 405), confirming the path is correctly routed.
    await client.delete<any>(
      `/api/v1/crm/accounts/${context.propsValue.accountUid}/memberships/${membership.Uid}`
    );
    return {
      action: 'removed',
      account_uid: context.propsValue.accountUid,
      membership_uid: membership.Uid,
      person_uid: context.propsValue.personUid,
    };
  },
});