Custom code to assign Primary Company

Hi, I need to assign a new company as a primary one. I do this in the automation, via a custom code. At first I start with removing the existing association and later set a new primary company. Everything looks fine in a log, but give no result - the new company is still no a Primary one. It would be great to understand what can be the issue.

I have those two steps

await hubspotClient.apiRequest({
method: ‘POST’,
path: ‘/crm/v4/associations/contacts/companies/batch/archive’,
body: companies.map(c => ({
from: { id: contactId },
to: [{ id: c.toObjectId }]
}))
});
await hubspotClient.apiRequest({
method: ‘PUT’,
path: `/crm/v4/objects/contact/${contactId}/associations/company/${bestCompanyId}`,
body: [
{ associationCategory: ‘HUBSPOT_DEFINED’, associationTypeId: 279 }, // default
{ associationCategory: ‘HUBSPOT_DEFINED’, associationTypeId: 1 } // primary
]
});
Could you suggest what can be wrong?

Hey, @HZaremba :waving_hand: thank for your question. To confirm, you are doing this via a custom coded workflow action, correct? Have you tried breaking these calls up and testing in Postman? — Jaycee

Test 1:

Check current associations

GET https://api.hubapi.com/crm/v4/objects/contact/{contactId}/associations/company

Test 2:

Test the Archive call

POST https://api.hubapi.com/crm/v4/associations/contacts/companies/batch/archive

[{
 "from": { "id": "your-contact-id" },
 "to": { "id": "company-id-to-remove" },
 "associationTypes": [
 { "associationCategory": "HUBSPOT_DEFINED", "associationTypeId": 279 }
 ]
}]

Test 3:

Test the Primary Association

PUT https://api.hubapi.com/crm/v4/objects/contact/{contactId}/associations/company/{bestCompanyId}

I’m sure there are other ways to test this, but it’s how I would start.

Best,

Jaycee