<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Custom code and Company deduplication in APIs &amp; Integrations</title>
    <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/900174#M70071</link>
    <description>&lt;P&gt;Hi,&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/600153"&gt;@GJakobTriad&lt;/a&gt;... thanks so much for posting your solution - it was enormously helpful!&lt;BR /&gt;&lt;BR /&gt;I also used the contact dedupe snippet from &lt;A href="https://github.com/HubSpot/sample-workflow-custom-code/tree/main/samples" target="_blank" rel="noopener"&gt;GitHub&lt;/A&gt; and combined that with your revisions. The code executed successfully but wasn't doing anything (the companies weren't merging).&amp;nbsp;&lt;BR /&gt;&lt;BR /&gt;I found that I had a discrepancy further down in my combined code, so I'm reposting the full, working code block here for other folks who may be runing into the same issue.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="javascript"&gt;/**
 * Searches for another company with the same value of DEDUPE_PROPERTY.
 * - If no matches are found, nothing happens
 * - If one match is found, the enrolled company is merged into the matching company
 * - If more than one match is found, the action fails
 */

const DEDUPE_PROPERTY = 'domain';

const hubspot = require('@hubspot/api-client');

exports.main = (event, callback) =&amp;gt; {
  // Make sure to add your API key under "Secrets" above.
  const hubspotClient = new hubspot.Client({
    accessToken: process.env.[INSERT ACCESS TOKEN]
  });

  hubspotClient.crm.companies.basicApi
    .getById(event.object.objectId, [DEDUPE_PROPERTY])
    .then(companyResult =&amp;gt; {
      let dedupePropValue = companyResult.properties[DEDUPE_PROPERTY];

      console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY} = ${dedupePropValue}`);
      hubspotClient.crm.companies.searchApi
        .doSearch({
          filterGroups: [{
            filters: [{
              propertyName: DEDUPE_PROPERTY,
              operator: 'EQ',
              value: dedupePropValue
            }]
          }]
        })
        .then(searchResults =&amp;gt; {
          let idsToMerge = searchResults.results
            .map(object =&amp;gt; object.id)
            .filter(vid =&amp;gt; Number(vid) !== Number(event.object.objectId));

          if (idsToMerge.length == 0) {
            console.log('No matching company, nothing to merge');
            return;
          } else if (idsToMerge.length &amp;gt; 1) {
            console.log(`Found multiple potential company IDs ${idsToMerge.join(', ')} to merge`);
            throw new Error("Ambiguous merge; more than one matching company");
          }

          let idToMerge = idsToMerge[0];
          console.log(`Merging enrolled company id=${event.object.objectId} into company id=${idToMerge}`);
          hubspotClient
            .apiRequest({
              method: 'POST',
              path: `/crm/v3/objects/companies/merge`,
              body: {
                objectIdToMerge: idToMerge,
                primaryObjectId: event.object.objectId
              }
            })
            .then(mergeResult =&amp;gt; {
              console.log('Companies merged!');
            });
        });
    });

    callback({
      outputFields: {
        company_id: event.object.objectId
      }
    });
};&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
    <pubDate>Wed, 03 Jan 2024 14:36:49 GMT</pubDate>
    <dc:creator>Clare_HS</dc:creator>
    <dc:date>2024-01-03T14:36:49Z</dc:date>
    <item>
      <title>Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/882799#M69218</link>
      <description>&lt;P&gt;Hey guys. I'm looking for some help with this. I'm trying to unlock the potential of the custom code element present in workflows, the one granted by Operations Hub.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I'm basically trying to adapt the following sample code to work with Companies, and use their names as the deduplication property:&lt;/P&gt;&lt;P&gt;&lt;A href="https://github.com/HubSpot/sample-workflow-custom-code/blob/main/samples/dedupe_contact.js" target="_blank"&gt;https://github.com/HubSpot/sample-workflow-custom-code/blob/main/samples/dedupe_contact.js&lt;/A&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;But I get the following, basic-looking error pointing at line 20, which is the first time the code tries to search by ID. For some reason, it fails.&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;ERROR Invoke Error {"errorType":"TypeError","errorMessage":"Cannot read properties of undefined (reading 'getById')","stack":["TypeError: Cannot read properties of undefined (reading 'getById')"," at Object.exports.main (/var/task/file.js:20:6)"," at Runtime.exports.hubspot_handler [as handler] (/var/task/hubspotHandler.js:6:21)"," at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1173:29)"]}&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here's the full code. I tried both referencing the ID using the sample's "event.object.objectId" and also feeding it as an input field on the workflow. The error remains the same.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;/**
 * Searches for another company with the same value of DEDUPE_PROPERTY.
 * - If no matches are found, nothing happens
 * - If one match is found, the enrolled company is merged into the matching company
 * - If more than one match is found, the action fails
 */

const DEDUPE_PROPERTY = 'name';

const hubspot = require('@hubspot/api-client');

exports.main = (event, callback) =&amp;gt; {

  // Make sure to add your API key under "Secrets" above.
  const hubspotClient = new hubspot.Client({
    accessToken: process.env.CompanyAssocCreateToken
  });

  hubspotClient.crm.companies.defaultApi
    .getById(event.object.objectId, [DEDUPE_PROPERTY])
    .then(companyResult =&amp;gt; {
      let dedupePropValue = companyResult.body.properties[DEDUPE_PROPERTY];

      console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY} = ${dedupePropValue}`);
      hubspotClient.crm.companies.defaultApi
        .doSearch({
          filterGroups: [{
            filters: [{
              propertyName: DEDUPE_PROPERTY,
              operator: 'EQ',
              value: dedupePropValue
            }]
          }]
        })
        .then(searchResults =&amp;gt; {
          let idsToMerge = searchResults.body.results
            .map(object =&amp;gt; object.id)
            .filter(vid =&amp;gt; Number(vid) !== Number(event.object.objectId));

          if (idsToMerge.length == 0) {
            console.log('No matching company, nothing to merge');
            return;
          } else if (idsToMerge.length &amp;gt; 1) {
            console.log(`Found multiple potential company IDs ${idsToMerge.join(', ')} to merge`);
            throw new Error("Ambiguous merge; more than one matching company");
          }

          let idToMerge = idsToMerge[0];
          console.log(`Merging enrolled company id=${event.object.objectId} into company id=${idToMerge}`);
          hubspotClient
            .apiRequest({
              method: 'POST',
              path: `/crm/v3/objects/companies/merge`,
              body: {
                objectIdToMerge: idToMerge,
                primaryObjectId: event.object.objectId
              }
            })
            .then(mergeResult =&amp;gt; {
              console.log('Companies merged!');
            });
        });
    });

    callback({
      outputFields: {
        company_id: event.object.objectId
      }
    });

};&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Tue, 21 Nov 2023 16:35:29 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/882799#M69218</guid>
      <dc:creator>GJakobTriad</dc:creator>
      <dc:date>2023-11-21T16:35:29Z</dc:date>
    </item>
    <item>
      <title>Re: Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/883199#M69250</link>
      <description>&lt;P&gt;Hi&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/600153"&gt;@GJakobTriad&lt;/a&gt;,&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Thank you for reaching out to the Community!&amp;nbsp;&lt;/P&gt;
&lt;P&gt;I wanted to tag in a couple of subject matter experts to see if they have any input on this matter:&lt;/P&gt;
&lt;P&gt;Hi&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/101258"&gt;@Teun&lt;/a&gt;,&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/148101"&gt;@ChristinaKay&lt;/a&gt;,&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/533153"&gt;@DanielJeal&lt;/a&gt;, do you have any tips for&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/600153"&gt;@GJakobTriad&lt;/a&gt;? Thank you!&amp;nbsp;&lt;span class="lia-unicode-emoji" title=":star:"&gt;⭐&lt;/span&gt; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Cheers&lt;BR /&gt;Mia, Community Team&lt;/P&gt;</description>
      <pubDate>Wed, 22 Nov 2023 11:32:11 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/883199#M69250</guid>
      <dc:creator>MiaSrebrnjak</dc:creator>
      <dc:date>2023-11-22T11:32:11Z</dc:date>
    </item>
    <item>
      <title>Re: Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/883312#M69255</link>
      <description>&lt;P&gt;After a bunch of troubleshooting, I found the two issues which were breaking the code:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;OL&gt;&lt;LI&gt;I was calling the wrong APIs, which should be &lt;STRONG&gt;basicApi&lt;/STRONG&gt; and &lt;STRONG&gt;searchApi&lt;/STRONG&gt; instead of DefaultApi. The &lt;A href="https://developers.hubspot.com/docs/api/crm/companies" target="_blank" rel="noopener"&gt;Company Endpoints documentation&lt;/A&gt; was misleading in this regard.&lt;BR /&gt;&lt;BR /&gt;&lt;/LI&gt;&lt;LI&gt;The &lt;A href="https://github.com/HubSpot/sample-workflow-custom-code/blob/main/samples/dedupe_contact.js" target="_blank" rel="noopener"&gt;sample code&lt;/A&gt; refers to "body.properties" when trying to look into the &lt;EM&gt;properties&lt;/EM&gt; clause of a response, and "body" throws it off, so that's inaccurate too. The reference should only be "properties", as in&amp;nbsp;&lt;STRONG&gt;companyResult.properties[DEDUPE_PROPERTY]&lt;/STRONG&gt;.&lt;/LI&gt;&lt;/OL&gt;</description>
      <pubDate>Wed, 22 Nov 2023 15:14:22 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/883312#M69255</guid>
      <dc:creator>GJakobTriad</dc:creator>
      <dc:date>2023-11-22T15:14:22Z</dc:date>
    </item>
    <item>
      <title>Re: Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/883920#M69278</link>
      <description>&lt;P&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/600153"&gt;@GJakobTriad&lt;/a&gt;&amp;nbsp;you're a&amp;nbsp;&lt;span class="lia-unicode-emoji" title=":star:"&gt;⭐&lt;/span&gt;, kudos to you!&lt;/P&gt;
&lt;P&gt;Thank you for sharing the solution with the Community&amp;nbsp;&lt;span class="lia-unicode-emoji" title=":yellow_heart:"&gt;💛&lt;/span&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 23 Nov 2023 18:46:07 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/883920#M69278</guid>
      <dc:creator>MiaSrebrnjak</dc:creator>
      <dc:date>2023-11-23T18:46:07Z</dc:date>
    </item>
    <item>
      <title>Re: Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/900174#M70071</link>
      <description>&lt;P&gt;Hi,&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/600153"&gt;@GJakobTriad&lt;/a&gt;... thanks so much for posting your solution - it was enormously helpful!&lt;BR /&gt;&lt;BR /&gt;I also used the contact dedupe snippet from &lt;A href="https://github.com/HubSpot/sample-workflow-custom-code/tree/main/samples" target="_blank" rel="noopener"&gt;GitHub&lt;/A&gt; and combined that with your revisions. The code executed successfully but wasn't doing anything (the companies weren't merging).&amp;nbsp;&lt;BR /&gt;&lt;BR /&gt;I found that I had a discrepancy further down in my combined code, so I'm reposting the full, working code block here for other folks who may be runing into the same issue.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="javascript"&gt;/**
 * Searches for another company with the same value of DEDUPE_PROPERTY.
 * - If no matches are found, nothing happens
 * - If one match is found, the enrolled company is merged into the matching company
 * - If more than one match is found, the action fails
 */

const DEDUPE_PROPERTY = 'domain';

const hubspot = require('@hubspot/api-client');

exports.main = (event, callback) =&amp;gt; {
  // Make sure to add your API key under "Secrets" above.
  const hubspotClient = new hubspot.Client({
    accessToken: process.env.[INSERT ACCESS TOKEN]
  });

  hubspotClient.crm.companies.basicApi
    .getById(event.object.objectId, [DEDUPE_PROPERTY])
    .then(companyResult =&amp;gt; {
      let dedupePropValue = companyResult.properties[DEDUPE_PROPERTY];

      console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY} = ${dedupePropValue}`);
      hubspotClient.crm.companies.searchApi
        .doSearch({
          filterGroups: [{
            filters: [{
              propertyName: DEDUPE_PROPERTY,
              operator: 'EQ',
              value: dedupePropValue
            }]
          }]
        })
        .then(searchResults =&amp;gt; {
          let idsToMerge = searchResults.results
            .map(object =&amp;gt; object.id)
            .filter(vid =&amp;gt; Number(vid) !== Number(event.object.objectId));

          if (idsToMerge.length == 0) {
            console.log('No matching company, nothing to merge');
            return;
          } else if (idsToMerge.length &amp;gt; 1) {
            console.log(`Found multiple potential company IDs ${idsToMerge.join(', ')} to merge`);
            throw new Error("Ambiguous merge; more than one matching company");
          }

          let idToMerge = idsToMerge[0];
          console.log(`Merging enrolled company id=${event.object.objectId} into company id=${idToMerge}`);
          hubspotClient
            .apiRequest({
              method: 'POST',
              path: `/crm/v3/objects/companies/merge`,
              body: {
                objectIdToMerge: idToMerge,
                primaryObjectId: event.object.objectId
              }
            })
            .then(mergeResult =&amp;gt; {
              console.log('Companies merged!');
            });
        });
    });

    callback({
      outputFields: {
        company_id: event.object.objectId
      }
    });
};&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Wed, 03 Jan 2024 14:36:49 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/900174#M70071</guid>
      <dc:creator>Clare_HS</dc:creator>
      <dc:date>2024-01-03T14:36:49Z</dc:date>
    </item>
    <item>
      <title>Re: Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/911783#M70587</link>
      <description>&lt;P&gt;hey - I was SO HAPPY when I saw this; I've attempted to use this on my own for a client and get an error. Any advice? Am I missing something? &lt;span class="lia-unicode-emoji" title=":sad_but_relieved_face:"&gt;😥&lt;/span&gt;&lt;/P&gt;&lt;PRE&gt;WARNING: The logs for this function have exceeded the 4KB limit.
...
2024-01-25T21:08:06.071Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected token '['","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token '['","    at _loadUserApp (file:///var/runtime/index.mjs:1084:17)","    at async Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)","    at async start (file:///var/runtime/index.mjs:1282:23)","    at async file:///var/runtime/index.mjs:1288:1"]}
INIT_REPORT Init Duration: 172.64 ms	Phase: init	Status: error	Error Type: Runtime.ExitError
2024-01-25T21:08:07.463Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected token '['","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token '['","    at _loadUserApp (file:///var/runtime/index.mjs:1084:17)","    at async Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)","    at async start (file:///var/runtime/index.mjs:1282:23)","    at async file:///var/runtime/index.mjs:1288:1"]}
INIT_REPORT Init Duration: 1622.43 ms	Phase: invoke	Status: error	Error Type: Runtime.ExitError
START RequestId: ee8cb700-9ee8-411a-a750-0d62c8409311 Version: $LATEST
Unknown application error occurred
Runtime.UserCodeSyntaxErroran &lt;/PRE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 25 Jan 2024 21:13:33 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/911783#M70587</guid>
      <dc:creator>BreannahGladden</dc:creator>
      <dc:date>2024-01-25T21:13:33Z</dc:date>
    </item>
    <item>
      <title>Re: Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/1137679#M81652</link>
      <description>&lt;P&gt;Based on all this, I did this repo:&amp;nbsp;&lt;A href="https://github.com/romeoman/hubspot-company-dedup" target="_blank"&gt;https://github.com/romeoman/hubspot-company-dedup&lt;/A&gt;&lt;BR /&gt;&lt;BR /&gt;Enhanced it a bit with some tracking.&lt;BR /&gt;&lt;BR /&gt;hope it helps.&lt;/P&gt;</description>
      <pubDate>Thu, 17 Apr 2025 18:00:27 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/1137679#M81652</guid>
      <dc:creator>romeonoi</dc:creator>
      <dc:date>2025-04-17T18:00:27Z</dc:date>
    </item>
    <item>
      <title>Re: Custom code and Company deduplication</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/1139760#M81724</link>
      <description>&lt;P&gt;Thanks for sharing &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/88208"&gt;@romeonoi&lt;/a&gt;&lt;/SPAN&gt; &lt;span class="lia-unicode-emoji" title=":raising_hands:"&gt;🙌&lt;/span&gt; — Jaycee&lt;/P&gt;</description>
      <pubDate>Wed, 23 Apr 2025 16:32:10 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/1139760#M81724</guid>
      <dc:creator>Jaycee_Lewis</dc:creator>
      <dc:date>2025-04-23T16:32:10Z</dc:date>
    </item>
  </channel>
</rss>

