Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertainslie/12314f50a8d2073f64a6ebef65953447 to your computer and use it in GitHub Desktop.
Save robertainslie/12314f50a8d2073f64a6ebef65953447 to your computer and use it in GitHub Desktop.
HubSpot Operations Hub - Count High Value Line Items.
const hubspot = require('@hubspot/api-client');
exports.main = (event, callback) => {
const hubspotClient = new hubspot.Client({
apiKey: process.env.HAPIKEY
});
//First, make a call to get deal associations
hubspotClient.crm.deals.associationsApi.getAll(event.object.objectId, 'line_item').then((results) => {
//Because a separate api call is needed for each associated line item, and each one returns a promise
//where the promise is not dependent on any other call, each can be run using the Promise.all() method
//The map() method takes 2 arguments - an initial array and a function to apply to every item in the initial array
// then, returns an array of the results. in this case, it's an array of promises that each get line item details
let lineItemPromises = results.body.results.map(item => {
return hubspotClient.crm.lineItems.basicApi.getById(item.id, ['amount']).then(results => {
return results.body
})
})
//pass the array of promises into Promise.All, which then returns an array of all results, in this case the details
// of every line item api call request.
Promise.all(lineItemPromises).then(resultsArray => {
console.log(resultsArray)
//use the .filter() method to filter the array of results for just the high value line items
let highValueLineItems = resultsArray.filter(item => parseFloat(item.properties.amount) > 1000.00)
console.log(`Length: ${li.length}`)
//update the original deal with the newly calculated property value
hubspotClient.crm.deals.basicApi.update(event.object.objectId, {
'properties': {
'number_high_value_line_items': highValueLineItems.length.toString()
}
}).then(response => {
console.log(response.body);
callback({})
})
})
}).catch((err) => {
console.error(err)
})
}

This code snippet is illustrative of a common pattern in CRM - getting associated records. This is particularly useful for deals and line items where line items are inherently tied to a specific deal.

This particularly code snippet shows this in context of the following use case: A customer is looking to more easily quantify how many high value items are included on a deal. For every Closed Won deal, they would like to set a property value of the number of line items greater than $1,000 (Note: You can build a similar report like this in the custom report builder...but assume the customer wants to include the value as a deal property)

@jackohm
Copy link

jackohm commented Jan 26, 2022

Hi

Do you know why the following error would return:

ERROR Invoke Error {"errorType":"TypeError","errorMessage":"hubspotClient.crm.companies.associationsApi.getAll(...).then(...) is not a function","stack"

I have tweaked the code to point to companies in order to get a count of associated contacts which i would assume would work the same way by replacing deals with companies and line items with contacts

Appreciate any help

@robertainslie
Copy link
Author

@jackohm

  1. Are you running this in a HubSpot custom coded Workflow action?
  2. If you're looking for Company > Contact associations are you also running this in a Company workflow (not a Deal workflow?)
  3. Did you remember to import the client library (line 1 of this gist) and also set up the client with auth (lines 5-7)?

Otherwise, want to paste in all of your sample code?

@jackohm
Copy link

jackohm commented Jan 26, 2022

Hi

So i did tweak the start bit, as being a complete novice to JS i didn't fully understand so pinched a separate bit of code from some of the API documentation

I'm essentially trying to do similar to what you have achieved but for companies, find how many associated contacts it has and update a total_contacts property

I did have one of our devs look at it who thought it may have been the '>=' so some of the code is tweaked slightly (maybe that's where i went wrong!) and i also got an error from lines 16 on your original as it said 'results' is already defined above

I also obviously have our actualy API key where it says ourkey but have removed for now

Anyway here is my code, appreciate it slightly different user case so no worries if can't help but appreciate you taking the time anyway

`var hubspot = require('@hubspot/api-client');
exports.main = function (event, callback) {
var hubspotClient = new
hubspot.Client({"apiKey":"ourkey"});

hubspotClient.crm.companies.associationsApi.getAll(event.object.objectId, 'contacts').then(function(results) {
 
  var ContactPromises = results.body.results.map(function(contact) {
        return hubspotClient.crm.contacts.basicApi.getById(contact.id, ['contact_id']) .then(function(contactresults) {
            return contactresults.body
        })
    })
 
    Promise.all(ContactPromises).then(function(resultsArray) {
        console.log(resultsArray)
 
      var total_contacts = resultsArray
    
        hubspotClient.crm.companies.basicApi.update(event.object.objectId, {
            'properties': {
                'total_contacts': total_contacts.length.toString()
            }
        }).then(function(response) {
            console.log(response.body);
            callback({})
        })
    })
})(function(error) {
    console.log(error)
})

}`

@rjreiffer
Copy link

Robert, being very new to this, how hard would it be to basically sum up the Monthly Recurring Revenue line items (hs_mrr) and IF the amount = 0 then replace amount with the total of hs_mrr line items?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment