Hi,
Im trying to bulk remove the associtaed emails from a company record as we have hit the 50000 limit, im usuing the following code but cant seem to get it to work correctly,
const hubspot = require(‘@hubspot/api-client’);
exports.main = async (event) => {
const token = process.env.Company_token;
const companyId = event.inputFields.hs_object_id;
console.log(‘Using company ID:’, companyId);
// Initialize the HubSpot client
const hubspotClient = new hubspot.Client({ accessToken: token });
// Step 1: Get all engagements associated with the company
async function getEngagementsForCompany(companyId) {
try {
const response = await hubspotClient.crm.objects.searchApi.doSearch(‘engagements’, {
filterGroups: [{
filters: [{
propertyName: ‘associations.company’,
operator: ‘EQ’,
value: companyId
}]
}],
properties: [‘email.id’], //email ID
});
console.log(‘Using emailid:’, email.id);
// Step 2: Delete the association between the email and the company
async function deleteAssociation(emailId, companyId) {
const associationTypeId = ‘engagement_to_company’; // Replace with the actual association type ID if different
try {
await hubspotClient.apiRequest({
method: ‘DELETE’,
path: `/crm/v3/objects/emails/${emailId}/associations/company/${companyId}/${associationTypeId}`,
headers: {
‘Authorization’: `Bearer ${token}`,
‘Content-Type’: ‘application/json’,
}
});
console.log(`Successfully deleted association for email ${emailId} with company ${companyId}`);
} catch (error) {
console.error(`Error deleting association: ${error.response?.status} - ${error.message}`);
}
}
// Step 3: Main function to process email unassociation
async function removeEmailAssociationsFromCompany(companyId) {
const engagements = await getEngagementsForCompany(companyId);
for (const engagement of engagements) {
const engagementId = engagement.id;
const engagementType = engagement.properties?.[‘engagement.type’];
const emailId = engagement.properties?.[‘email.id’]; // Extract email ID
// Log engagement details for debugging
console.log(`Processing engagement ${engagementId} with type ${engagementType} and email ID ${emailId}`);
// Only handle email engagements and ensure email ID is present
if (engagementType === ‘EMAIL’ && emailId) {
await deleteAssociation(emailId, companyId);
}
}
}
// Execute the script
await removeEmailAssociationsFromCompany(companyId);
};
Any ideas?