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

5.5 KB
Raw Blame
import { getHubspotAccessToken, hubspotAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import {
    fromObjectTypeAssociationDropdown,
    associationTypeDropdown,
    toObjectIdsDropdown,
} from '../common/props';
import { OBJECT_TYPE } from '../common/constants';
import { Client } from '@hubspot/api-client';
import { AssociationSpecAssociationCategoryEnum } from '../common/types';
import { chunk } from '@activepieces/pieces-framework';
import { removeAssociationsOutputSchema } from '../output-schemas';

export const removeAssociationsAction = createAction({
    auth: hubspotAuth,
    name: 'remove-associations',
    classification: 'WRITE',
    displayName: 'Remove Associations',
    description: 'Unlinks a record from one or more linked records.',
    audience: 'both',
    aiMetadata: { description: 'Remove the labeled association of a specific type between one source HubSpot object and one or more target objects, batching the targets. Removing an already-absent association is harmless, so it is idempotent on the end state. Use Create Associations to add links.', idempotent: true },
    outputSchema: removeAssociationsOutputSchema,
    propertyGroups: [
        {
            key: 'source',
            display: 'section',
            label: 'From Record',
            icon: 'file',
            props: ['fromObjectId', 'fromObjectType'],
        },
        {
            key: 'target',
            display: 'section',
            label: 'Records to Unlink',
            icon: 'trash',
            props: ['toObjectType', 'associationType', 'toObjectIds'],
        },
    ],
    props: {
        fromObjectId: Property.ShortText({
            displayName: 'From Object ID',
            description: 'Map it from an earlier Find or Get step.',
            required: true,
        }),
        fromObjectType: fromObjectTypeAssociationDropdown({
            objectType: OBJECT_TYPE.COMPANY,
            displayName: 'From Object Type',
            required: true,
            description: 'The object type of that record.',
        }),
        toObjectType: fromObjectTypeAssociationDropdown({
            objectType: OBJECT_TYPE.COMPANY,
            displayName: 'To Object Type',
            required: true,
            description: 'The object type of the linked records.',
        }),
        associationType: associationTypeDropdown,
        toObjectIds: toObjectIdsDropdown({
            objectType: OBJECT_TYPE.COMPANY,
            displayName: 'To Records',
            description: 'The linked records to unlink.',
            required: true,
        }),
    },
    async run(context) {
        const { fromObjectId, fromObjectType, toObjectType, associationType } = context.propsValue;

        const client = new Client({ accessToken: getHubspotAccessToken(context.auth) });

        if(context.propsValue.toObjectIds === undefined) {            
            throw new Error('Please provide To Object IDs');
        }

        let toObjectIds: any[];
        if (Array.isArray(context.propsValue.toObjectIds)) {
            toObjectIds = context.propsValue.toObjectIds;
        } else {
            try {
                toObjectIds = JSON.parse(context.propsValue.toObjectIds);
            } catch {
                throw new Error(
                    `Please provide To Object IDs in a valid format. Provided : ${JSON.stringify(
                        context.propsValue.toObjectIds,
                    )}`,
                );
            }
        }

        // find the association category
        const associationLabels = await client.crm.associations.v4.schema.definitionsApi.getAll(
            fromObjectType as string,
            toObjectType as string,
        );
        const association = associationLabels.results.find(
            (associationLabel) => associationLabel.typeId === associationType,
        );
        if (!association) {
            throw new Error(
                `Association type ${associationType} not found for ${fromObjectType} to ${toObjectType}`,
            );
        }
        const associationCategory = association.category;

        // Batch API limit is 1000, but using 100 for consistency and safety
        const BATCH_SIZE = 100;
        const chunks = chunk(toObjectIds, BATCH_SIZE);
        const responses = [];

        for (const chunkBatch of chunks) {
            const response = await client.crm.associations.v4.batchApi.archiveLabels(
                fromObjectType as string,
                toObjectType as string,
                {
                    inputs: chunkBatch.map((objectId) => {
                        return {
                            _from: {
                                id: fromObjectId,
                            },
                            to: {
                                id: objectId,
                            },
                            types: [
                                {
                                    associationCategory:
                                        associationCategory as unknown as AssociationSpecAssociationCategoryEnum,
                                    associationTypeId: associationType,
                                },
                            ],
                        };
                    }),
                },
            );
            responses.push(response);
        }

        return {
            success: true,
            totalAssociations: toObjectIds.length,
            batchCount: chunks.length,
            responses,
        };
    },
});