Created
April 29, 2024 18:10
-
-
Save greatwitenorth/9777ed3bf0512d43094c76e0d5c70c0e to your computer and use it in GitHub Desktop.
Quickbooks to Hubspot invoice sync - Associate company to invoice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use this in the custom code action (only in Ops Pro) | |
const hubspot = require('@hubspot/api-client'); | |
exports.main = async (event, callback) => { | |
const hubspotClient = new hubspot.Client({ | |
accessToken: process.env.HS_TOKEN | |
}); | |
const invoiceId = event.inputFields['hs_object_id']; | |
try { | |
const associatedContacts = await hubspotClient.crm.associations.v4.batchApi.getPage( | |
'invoice', | |
'contact', | |
{inputs: [{id: invoiceId}]} | |
); | |
// get all associated contact ids | |
const contactsIds = associatedContacts.results.reduce((acc, result) => { | |
result.to.map(curr => acc.push({id: curr.toObjectId})) | |
return acc | |
}, []); | |
const associatedCompanies = await hubspotClient.crm.associations.v4.batchApi.getPage( | |
'contact', | |
'company', | |
{inputs: contactsIds} | |
); | |
// find the first contact with an associated Primary company | |
const company = associatedCompanies.results.map(result => { | |
return result.to.find(r => { | |
return r.associationTypes.find(t => t.label === 'Primary') | |
}) | |
}).filter(t => t); | |
if(company.length !== 0) { | |
const companyId = company[0].toObjectId; | |
// Associate this company to the invoice | |
const BatchInputPublicAssociation = { | |
inputs: [{ | |
"_from": {"id": companyId}, | |
"to": {"id": invoiceId}, | |
"type": 'company_to_invoice' | |
}] | |
}; | |
const apiResponse = await hubspotClient.crm.associations.batchApi.create( | |
'company', | |
'invoice', | |
BatchInputPublicAssociation | |
); | |
} | |
} catch (e) { | |
e.message === 'HTTP request failed' | |
? console.error(JSON.stringify(e.response, null, 2)) | |
: console.error(e) | |
throw e; | |
} | |
callback({ | |
outputFields: {} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment