Skip to content

Conversation

@luancazarine
Copy link
Collaborator

@luancazarine luancazarine commented Oct 31, 2024

Resolves #14268

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new action for creating or updating contacts in the Intercom integration.
    • Added new methods for searching, creating, and updating contacts.
  • Version Updates

    • Incremented version numbers for multiple components and actions to reflect updates.
  • Enhancements

    • Improved error handling and clarity in the new-topic module.
    • Added a constant for predefined role options to streamline role management.

Actions
 - Upsert Contact
@luancazarine luancazarine linked an issue Oct 31, 2024 that may be closed by this pull request
@vercel
Copy link

vercel bot commented Oct 31, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview Oct 31, 2024 6:45pm
pipedream-docs ⬜️ Ignored (Inspect) Oct 31, 2024 6:45pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Oct 31, 2024 6:45pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The changes in this pull request involve updates to various files within the Intercom component. Key modifications include the introduction of a new action for upserting contacts, the addition of a constant for role options, and multiple version increments across existing modules. The functionality of the existing methods remains unchanged, with enhancements primarily focused on version updates and new method implementations for improved contact management.

Changes

File Change Summary
components/intercom/actions/create-note/create-note.mjs Version updated from "0.0.3" to "0.0.4"
components/intercom/actions/send-incoming-message/send-incoming-message.mjs Version updated from "0.0.3" to "0.0.4"
components/intercom/actions/upsert-contact/upsert-contact.mjs New action added for creating/updating contacts
components/intercom/common/constants.mjs New constant ROLE_OPTIONS added
components/intercom/intercom.app.mjs Method signature of makeRequest updated; new methods for contact management added
components/intercom/package.json Version updated from "0.4.0" to "0.5.0"
components/intercom/sources/conversation-closed/conversation-closed.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/lead-added-email/lead-added-email.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-admin-reply/new-admin-reply.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-company/new-company.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-conversation-rating-added/new-conversation-rating-added.mjs Version updated from "0.0.1" to "0.0.2"
components/intercom/sources/new-conversation/new-conversation.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-event/new-event.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-lead/new-lead.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-topic/new-topic.mjs Version updated from "0.0.2" to "0.0.3"; error handling improvements made
components/intercom/sources/new-unsubscription/new-unsubscription.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-user-reply/new-user-reply.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/new-user/new-user.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/tag-added-to-conversation/tag-added-to-conversation.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/tag-added-to-lead/tag-added-to-lead.mjs Version updated from "0.0.5" to "0.0.6"
components/intercom/sources/tag-added-to-user/tag-added-to-user.mjs Version updated from "0.0.5" to "0.0.6"

Assessment against linked issues

Objective Addressed Explanation
Implement Upsert Contact action

Possibly related PRs

Suggested labels

User submitted

Suggested reviewers

  • jcortes

Poem

In the garden of code, we hop and play,
With new actions and roles brightening the day.
Version numbers rise, like bunnies in bloom,
Each change a step, dispelling the gloom.
So let’s celebrate with a joyful cheer,
For every new feature that brings us near! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b6e0d2 and bff82ae.

📒 Files selected for processing (1)
  • components/intercom/actions/upsert-contact/upsert-contact.mjs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/intercom/actions/upsert-contact/upsert-contact.mjs

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (9)
components/intercom/common/constants.mjs (1)

1-10: Add documentation and prevent mutations.

The implementation correctly defines the role options for Intercom contacts. Consider these improvements:

Add JSDoc documentation and freeze the array to prevent mutations:

+/**
+ * Valid role options for Intercom contacts.
+ * @see https://developers.intercom.com/docs/references/rest-api/api.intercom.io/Contacts/
+ */
-export const ROLE_OPTIONS = [
+export const ROLE_OPTIONS = Object.freeze([
   {
     label: "User",
     value: "user",
   },
   {
     label: "Lead",
     value: "lead",
   },
-];
+]);
components/intercom/sources/new-topic/new-topic.mjs (2)

Line range hint 36-42: Fix extra brace in summary string.

The summary string contains an extra closing brace that should be removed.

Apply this fix:

       this.$emit(body, {
         id: id ?? uuid(),
-        summary: `${eventType} - id: ${id ?? "(no id found)"}}`,
+        summary: `${eventType} - id: ${id ?? "(no id found)"}`,
         ts: new Date().getTime(),
       });

Line range hint 23-26: Consider revising error handling approach.

The error messages suggest events are being skipped, but throwing an error actually terminates execution. Consider either:

  1. Actually skipping events by returning early instead of throwing
  2. Revising the error messages to remove "Skipping event..."

Also, consider making the error messages consistent across both validation checks.

Here's a suggested implementation:

     isSignatureValid(body, signature) {
       if (!signature) {
-        throw new Error("Signature is missing in the request header. Skipping event...");
+        throw new Error("Signature is missing in the request header");
       }
       const hmac = crypto.createHmac("sha1", this.clientSecret);
       hmac.update(body);
       const digest = hmac.digest("hex");
       return `sha1=${digest}` === signature;
     },

     async run(event) {
       if (this.clientSecret && !this.isSignatureValid(event.bodyRaw, event.headers["x-hub-signature"])) {
-        throw new Error("Signature is not valid. Skipping event...");
+        throw new Error("Signature is not valid");
       }
       this.emit(event.body);
     },

Alternatively, if you want to skip invalid events instead of throwing:

     isSignatureValid(body, signature) {
       if (!signature) {
-        throw new Error("Signature is missing in the request header. Skipping event...");
+        console.log("Signature is missing in the request header. Skipping event...");
+        return false;
       }
       const hmac = crypto.createHmac("sha1", this.clientSecret);
       hmac.update(body);
       const digest = hmac.digest("hex");
       return `sha1=${digest}` === signature;
     },

     async run(event) {
       if (this.clientSecret && !this.isSignatureValid(event.bodyRaw, event.headers["x-hub-signature"])) {
-        throw new Error("Signature is not valid. Skipping event...");
+        console.log("Signature is not valid. Skipping event...");
+        return;
       }
       this.emit(event.body);
     },

Also applies to: 44-47

components/intercom/actions/upsert-contact/upsert-contact.mjs (2)

8-8: Consider starting with version 1.0.0

Since this is a new production-ready action being added to handle critical contact data, consider starting with version 1.0.0 following semantic versioning best practices.


7-7: Enhance documentation reference

The current documentation link points to the general contact creation endpoint. Consider adding links to both create and update endpoints since this action handles both operations.

-  description: "Create a new contact. If there is already a contact with the email provided, the existing contact will be updated. [See the docs here](https://developers.intercom.com/docs/references/rest-api/api.intercom.io/contacts/createcontact)",
+  description: "Create a new contact or update an existing one based on the email provided. [See the create docs](https://developers.intercom.com/docs/references/rest-api/api.intercom.io/contacts/createcontact) and [update docs](https://developers.intercom.com/docs/references/rest-api/api.intercom.io/contacts/updatecontact)",
components/intercom/intercom.app.mjs (4)

48-62: LGTM! Consider adding TypeScript-style param types in JSDoc.

The refactoring to use destructuring improves the method's flexibility while maintaining backward compatibility. The documentation is comprehensive.

Consider enhancing the JSDoc by adding TypeScript-style param types:

/**
 * @param {Object} opts
 * @param {string} opts.method - HTTP method
 * @param {string} [opts.url] - Full URL (optional)
 * @param {string} [opts.endpoint] - API endpoint
 * @param {import("@pipedream/platform").$.Interface} [opts.$] - Pipedream axios instance
 */

212-218: Add JSDoc documentation for searchContact method.

The implementation is correct, but documentation would improve maintainability.

Add JSDoc documentation:

+/**
+ * Search for a contact using specified criteria
+ * @param {Object} opts - Search options
+ * @param {Object} [opts.query] - Search query parameters
+ * @returns {Promise<Object>} Search results
+ */
 searchContact(opts = {}) {

226-234: Add JSDoc documentation and error handling for updateContact method.

The implementation is correct but needs documentation and error handling guidance.

Add documentation and validation:

+/**
+ * Update an existing contact
+ * @param {Object} params - Update parameters
+ * @param {string} params.contactId - Contact ID to update
+ * @param {Object} params.data - Contact data to update
+ * @throws {Error} When contactId is not provided
+ * @returns {Promise<Object>} Updated contact
+ */
 updateContact({
   contactId, ...opts
 }) {
+  if (!contactId) {
+    throw new Error("Contact ID is required for updates");
+  }
   return this.makeRequest({

212-234: Consider implementing a contact service layer.

The current implementation directly exposes API methods. Consider introducing a service layer that:

  1. Implements the upsert logic by combining search, create, and update operations
  2. Handles common error cases
  3. Provides retry logic for rate limits
  4. Implements proper logging

This would improve maintainability and reusability.

Would you like me to provide an example implementation of the contact service layer?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9037ee3 and 2b6e0d2.

📒 Files selected for processing (21)
  • components/intercom/actions/create-note/create-note.mjs (1 hunks)
  • components/intercom/actions/send-incoming-message/send-incoming-message.mjs (1 hunks)
  • components/intercom/actions/upsert-contact/upsert-contact.mjs (1 hunks)
  • components/intercom/common/constants.mjs (1 hunks)
  • components/intercom/intercom.app.mjs (2 hunks)
  • components/intercom/package.json (1 hunks)
  • components/intercom/sources/conversation-closed/conversation-closed.mjs (1 hunks)
  • components/intercom/sources/lead-added-email/lead-added-email.mjs (1 hunks)
  • components/intercom/sources/new-admin-reply/new-admin-reply.mjs (1 hunks)
  • components/intercom/sources/new-company/new-company.mjs (1 hunks)
  • components/intercom/sources/new-conversation-rating-added/new-conversation-rating-added.mjs (1 hunks)
  • components/intercom/sources/new-conversation/new-conversation.mjs (1 hunks)
  • components/intercom/sources/new-event/new-event.mjs (1 hunks)
  • components/intercom/sources/new-lead/new-lead.mjs (1 hunks)
  • components/intercom/sources/new-topic/new-topic.mjs (1 hunks)
  • components/intercom/sources/new-unsubscription/new-unsubscription.mjs (1 hunks)
  • components/intercom/sources/new-user-reply/new-user-reply.mjs (1 hunks)
  • components/intercom/sources/new-user/new-user.mjs (1 hunks)
  • components/intercom/sources/tag-added-to-conversation/tag-added-to-conversation.mjs (1 hunks)
  • components/intercom/sources/tag-added-to-lead/tag-added-to-lead.mjs (1 hunks)
  • components/intercom/sources/tag-added-to-user/tag-added-to-user.mjs (1 hunks)
✅ Files skipped from review due to trivial changes (17)
  • components/intercom/actions/create-note/create-note.mjs
  • components/intercom/actions/send-incoming-message/send-incoming-message.mjs
  • components/intercom/package.json
  • components/intercom/sources/conversation-closed/conversation-closed.mjs
  • components/intercom/sources/lead-added-email/lead-added-email.mjs
  • components/intercom/sources/new-admin-reply/new-admin-reply.mjs
  • components/intercom/sources/new-company/new-company.mjs
  • components/intercom/sources/new-conversation-rating-added/new-conversation-rating-added.mjs
  • components/intercom/sources/new-conversation/new-conversation.mjs
  • components/intercom/sources/new-event/new-event.mjs
  • components/intercom/sources/new-lead/new-lead.mjs
  • components/intercom/sources/new-unsubscription/new-unsubscription.mjs
  • components/intercom/sources/new-user-reply/new-user-reply.mjs
  • components/intercom/sources/new-user/new-user.mjs
  • components/intercom/sources/tag-added-to-conversation/tag-added-to-conversation.mjs
  • components/intercom/sources/tag-added-to-lead/tag-added-to-lead.mjs
  • components/intercom/sources/tag-added-to-user/tag-added-to-user.mjs
🔇 Additional comments (4)
components/intercom/common/constants.mjs (1)

1-10: Verify role options against Intercom's API documentation.

Let's verify that these are all the valid role types supported by Intercom's API.

components/intercom/sources/new-topic/new-topic.mjs (2)

9-9: LGTM! Version bump is appropriate.

The version increment from 0.0.2 to 0.0.3 correctly reflects the patch-level changes made to improve error handling.


Line range hint 23-47: Verify webhook implementation against Intercom's documentation.

Please ensure the webhook implementation aligns with Intercom's latest API specifications:

  1. Signature validation should match Intercom's webhook security documentation.
  2. The event payload structure (event.body.data?.item) should handle all possible webhook event types.
✅ Verification successful

Let me search for more information about the webhook implementation.


Let me search for more implementation details to verify the webhook security and payload structure.


Based on the gathered information, I can now provide a final response about the webhook implementation verification.

Webhook implementation correctly follows Intercom's specifications

The implementation correctly follows Intercom's webhook security and payload handling requirements:

  • The signature validation uses SHA1 HMAC with the client secret, matching Intercom's security requirements
  • The payload structure handles both standard and notification events through proper null coalescing:
    • body.data?.item.type ?? body.type ?? "notification_event"
    • body.data?.item.id ?? body.data?.item.external_id
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other Intercom webhook implementations to compare
rg -l "x-hub-signature" components/intercom/

Length of output: 96


Script:

#!/bin/bash
# Search for webhook payload handling patterns in Intercom components
rg -A 5 "data\?.item" components/intercom/

# Look for any documentation or comments about webhook handling
rg -i "webhook" components/intercom/ --type md

Length of output: 766


Script:

#!/bin/bash
# Look for app.mjs or similar files that might contain webhook configuration
fd -e mjs -e js . components/intercom/ --exec head -n 20 {}

# Search for any security-related imports or configurations
rg -A 3 "createHmac|crypto" components/intercom/

Length of output: 11694

components/intercom/intercom.app.mjs (1)

219-225: Add JSDoc documentation and input validation for createContact method.

The implementation is correct but could benefit from documentation and validation.

Add documentation and validation:

+/**
+ * Create a new contact
+ * @param {Object} opts - Contact creation options
+ * @param {Object} opts.role - Contact role (user or lead)
+ * @param {string} [opts.email] - Contact's email
+ * @param {string} [opts.phone] - Contact's phone
+ * @returns {Promise<Object>} Created contact
+ */
 createContact(opts = {}) {
+  if (!opts.role) {
+    throw new Error("Contact role is required");
+  }
   return this.makeRequest({

Let's verify the required fields in the Intercom API:

Comment on lines +74 to +84

data = Object.entries(data).filter(([
,
value,
]) => (value != "" && value != undefined))
.reduce((obj, [
key,
value,
]) => Object.assign(obj, {
[key]: value,
}), {});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Simplify object filtering

The current object filtering logic could be simplified using Object.fromEntries for better readability.

-    data = Object.entries(data).filter(([
-      ,
-      value,
-    ]) => (value != "" && value != undefined))
-      .reduce((obj, [
-        key,
-        value,
-      ]) => Object.assign(obj, {
-        [key]: value,
-      }), {});
+    data = Object.fromEntries(
+      Object.entries(data).filter(([, value]) => 
+        value !== "" && value !== undefined
+      )
+    );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
data = Object.entries(data).filter(([
,
value,
]) => (value != "" && value != undefined))
.reduce((obj, [
key,
value,
]) => Object.assign(obj, {
[key]: value,
}), {});
data = Object.fromEntries(
Object.entries(data).filter(([, value]) =>
value !== "" && value !== undefined
)
);

luancazarine and others added 3 commits October 31, 2024 15:45
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Collaborator

@jcortes jcortes left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @luancazarine lgtm! Ready for QA!

@luancazarine luancazarine merged commit 02197b3 into master Nov 1, 2024
12 checks passed
@luancazarine luancazarine deleted the 14268-action-intercom-upsert-contact branch November 1, 2024 15:16
lcaresia pushed a commit that referenced this pull request Dec 3, 2024
* [ACTION] Intercom Upsert Contact #14268
Actions
 - Upsert Contact

* Update components/intercom/actions/upsert-contact/upsert-contact.mjs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update components/intercom/actions/upsert-contact/upsert-contact.mjs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update components/intercom/actions/upsert-contact/upsert-contact.mjs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@coderabbitai coderabbitai bot mentioned this pull request Dec 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[ACTION] Intercom Upsert Contact

3 participants