Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Components] engage #13410 #15656

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open

[Components] engage #13410 #15656

wants to merge 6 commits into from

Conversation

lcaresia
Copy link
Collaborator

@lcaresia lcaresia commented Feb 18, 2025

WHY

Summary by CodeRabbit

  • New Features

    • Introduced new actions to add customers, log events, and create users, expanding platform capabilities for managing user data and activity.
  • Chores

    • Upgraded the application release version to 0.1.0 with improvements to the main module structure and dependency management.
    • Removed outdated configuration settings to streamline repository organization.

@lcaresia lcaresia self-assigned this Feb 18, 2025
Copy link

vercel bot commented Feb 18, 2025

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

Name Status Preview Comments Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 28, 2025 0:18am
2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
pipedream-docs ⬜️ Ignored (Inspect) Feb 28, 2025 0:18am
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Feb 28, 2025 0:18am

Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request removes the .gitignore file from the Engage component and introduces several new action modules for adding customers, events, and creating users. A new Engage application module is provided with comprehensive property definitions and API methods. In addition, the package configuration file is updated, reflecting a version bump, main entry point change, and a new dependency.

Changes

File(s) Change Summary
components/engage/.gitignore Removed the file that ignored .js, .mjs files and the dist directory.
components/engage/actions/add-customer/add-customer.mjs
components/engage/actions/add-event/add-event.mjs
components/engage/actions/create-user/create-user.mjs
Added new action modules to add customers, add events, and create users with associated metadata and asynchronous run methods.
components/engage/app/engage.app.ts
components/engage/engage.app.mjs
Deleted the TS application file and introduced a new Engage app module including updated property definitions and methods (_makeRequest, createUser, addCustomer, addEvent, getUsers).
components/engage/package.json Updated version from 0.0.2 to 0.1.0, changed the main entry point to engage.app.mjs, removed the files array, and added a dependency on @pipedream/platform.

Sequence Diagram(s)

sequenceDiagram
    participant U as User/Context
    participant A as Action Module
    participant E as Engage App Module

    U->>A: Trigger action (e.g., create user, add customer, add event)
    A->>E: Call corresponding API method
    E-->>A: Return response data
    A-->>U: Return summary message and response
Loading

Possibly related PRs

  • [Components] listen_notes #15178 #15289: The changes in the main PR, which involve the deletion of a .gitignore file affecting JavaScript files and directories, are related to the retrieved PR's similar deletion of a .gitignore file that also targeted JavaScript files and directories, indicating a common concern with version control management.
  • [Components] lessonspace #13378 #15576: The changes in the main PR and the retrieved PR are related as both involve the deletion of a .gitignore file that contained rules for ignoring JavaScript files and directories, impacting version control practices.

Suggested labels

ai-assisted

Suggested reviewers

  • jcortes

Poem

I'm a rabbit with a hop and a cheer,
In code meadows where changes appear.
New actions jump and apps evolve,
In sequences and checks they solve.
With ASCII hops and bytes so bright,
I celebrate these changes tonight!
🐇💻


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 generate docstrings to generate docstrings for this 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.

@lcaresia lcaresia linked an issue Feb 18, 2025 that may be closed by this pull request
luancazarine
luancazarine previously approved these changes Feb 18, 2025
Copy link
Collaborator

@luancazarine luancazarine left a comment

Choose a reason for hiding this comment

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

Hi @lcaresia, LGTM! Ready for QA!

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: 4

🧹 Nitpick comments (2)
components/engage/engage.app.mjs (1)

41-50: Avoid duplicate code in options functions.

The options functions in uid and customerId properties are identical. Consider extracting this into a shared method.

+  methods: {
+    async _getUserOptions() {
+      const response = await this.getUsers();
+      const usersIds = response.data;
+      return usersIds.map(({
+        uid, first_name, last_name,
+      }) => ({
+        label: `${first_name} ${last_name}`,
+        value: uid,
+      }));
+    },
   },
   propDefinitions: {
     uid: {
       // ...
       async options() {
-        const response = await this.getUsers();
-        const usersIds = response.data;
-        return usersIds.map(({
-          uid, first_name, last_name,
-        }) => ({
-          label: `${first_name} ${last_name}`,
-          value: uid,
-        }));
+        return this._getUserOptions();
       },
     },
     customerId: {
       // ...
       async options() {
-        const response = await this.getUsers();
-        const usersIds = response.data;
-        return usersIds.map(({
-          uid, first_name, last_name,
-        }) => ({
-          label: `${first_name} ${last_name}`,
-          value: uid,
-        }));
+        return this._getUserOptions();
       },
     },
   },

Also applies to: 56-65

components/engage/actions/add-event/add-event.mjs (1)

36-47: Add timestamp validation and default handling.

The timestamp field should be validated if provided, or default to current time if not provided.

 async run({ $ }) {
+  const eventData = {
+    event: this.event,
+    properties: this.properties,
+  };
+
+  if (this.timestamp) {
+    // Validate timestamp format
+    if (!Date.parse(this.timestamp)) {
+      throw new Error("Invalid timestamp format");
+    }
+    eventData.timestamp = this.timestamp;
+  }
+
   const response = await this.app.addEvent({
     $,
     uid: this.uid,
-    data: {
-      event: this.event,
-      timestamp: this.timestamp,
-      properties: this.properties,
-    },
+    data: eventData,
   });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b38f664 and 5f4d07e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • components/engage/.gitignore (0 hunks)
  • components/engage/actions/add-customer/add-customer.mjs (1 hunks)
  • components/engage/actions/add-event/add-event.mjs (1 hunks)
  • components/engage/actions/create-user/create-user.mjs (1 hunks)
  • components/engage/app/engage.app.ts (0 hunks)
  • components/engage/engage.app.mjs (1 hunks)
  • components/engage/package.json (1 hunks)
💤 Files with no reviewable changes (2)
  • components/engage/app/engage.app.ts
  • components/engage/.gitignore
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Publish TypeScript components
🔇 Additional comments (2)
components/engage/package.json (2)

3-5: Version and Main Entry Update Validation

  • The package version has been updated to "0.1.0", which signifies a new release. Please ensure that any breaking changes or new features introduced are documented in the changelog or release notes.
  • The "main" entry point has been updated to "engage.app.mjs". Confirm that this file exists in the project directory and that all module consumers are updated accordingly.

14-16: PublishConfig and Dependencies Block Review

  • The "publishConfig" block now correctly terminates, ensuring proper package publishing settings.
  • The new dependency "@pipedream/platform": "^3.0.3" is added. Make sure that this dependency is intended for use in the project and is compatible with the rest of the codebase.

Comment on lines +87 to +103
async _makeRequest(opts = {}) {
const {
$ = this,
path,
auth,
...otherOpts
} = opts;
return axios($, {
...otherOpts,
url: this._baseUrl() + path,
auth: {
...auth,
username: `${this.$auth.public_key}`,
password: `${this.$auth.secret_key}`,
},
});
},
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

Consider adding error handling and request validation.

The _makeRequest method should include:

  • Error handling for network failures
  • Request validation
  • Rate limiting considerations
 async _makeRequest(opts = {}) {
   const {
     $ = this,
     path,
     auth,
     ...otherOpts
   } = opts;
+  if (!path) {
+    throw new Error("Path is required");
+  }
+  try {
     return axios($, {
       ...otherOpts,
       url: this._baseUrl() + path,
       auth: {
         ...auth,
         username: `${this.$auth.public_key}`,
         password: `${this.$auth.secret_key}`,
       },
     });
+  } catch (error) {
+    const errorMessage = error.response?.data?.message || error.message;
+    throw new Error(`Request failed: ${errorMessage}`);
+  }
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 77 to 81
properties: {
type: "object",
label: "Properties",
description: "The properties of the event",
},
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Consider adding schema validation for properties object.

The properties field accepts any object structure. Consider adding schema validation to ensure the properties match expected format.


🌐 Web query:

What is the expected format for event properties in Engage.so?

💡 Result:

In Engage.so, event properties are structured as key-value pairs associated with user actions, allowing granular tracking and segmentation. Here's the breakdown based on available documentation:

Event Properties Format

  1. Event Structure
    Each event consists of:

    • Event Name: A descriptive label for the user action (e.g., button_clicked, order_placed).
    • Properties: Customizable key-value pairs providing context (e.g., plan_type: "premium", button_color: "blue").
  2. Data Types
    Events support dynamic property values, including:

    • Strings ("success")
    • Numbers (42)
    • Booleans (true/false)
    • Timestamps (automatically recorded for each event)[10].
  3. Usage Guidelines

    • Timestamps: Automatically attached to events for historical analysis[10].
    • Overwriting Behavior: Unlike attributes (which store only the latest value), events retain all historical instances[10].
    • Segmentation: Properties enable filtering users based on past actions (e.g., "users who clicked ‘Upgrade’ in the last 30 days")[10].

Example Implementation

// Tracking a plan upgrade event with properties
Engage.track('plan_upgraded', {
  plan_name: "Pro",
  previous_plan: "Basic",
  payment_method: "credit_card"
});

Key Differences from Attributes

Feature Events Attributes
Storage Historical records with timestamps[10] Latest value only[10]
Use Case Tracking actions over time Storing static user traits
Example plan_upgraded with details current_plan: "Pro"

For optimal results, use events when you need to analyze temporal patterns or count occurrences (e.g., logins per week), and attributes for fixed user states (e.g., subscription tier)[10].

Citations:


Action Required: Enhance Schema Validation for Event Properties

The current definition for the properties field only specifies it as an object without enforcing the key-value structure demanded by Engage.so. According to the documentation, event properties should be dynamic key-value pairs with values limited to strings, numbers, booleans, or timestamps. Please add schema validation (for example, using JSON Schema with appropriate patternProperties or additionalProperties constraints) to ensure that properties strictly adhere to this format.

  • Location: components/engage/engage.app.mjs (lines 77-81)
  • Action: Enhance the validation logic for the properties object by enforcing allowed types and structure.

Comment on lines +48 to +62
async run({ $ }) {
const response = await this.app.createUser({
$,
data: {
id: this.userId,
first_name: this.firstName,
last_name: this.lastName,
is_account: this.isAccount,
number: this.number,
email: this.email,
},
});
$.export("$summary", `Successfully created user with ID: ${response.id}`);
return response;
},
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

Add input validation and error handling.

The run method should validate inputs and handle potential errors from the API call.

 async run({ $ }) {
+  // Validate required fields
+  if (!this.userId || !this.email) {
+    throw new Error("User ID and email are required fields");
+  }
+
+  try {
     const response = await this.app.createUser({
       $,
       data: {
         id: this.userId,
         first_name: this.firstName,
         last_name: this.lastName,
         is_account: this.isAccount,
         number: this.number,
         email: this.email,
       },
     });
     $.export("$summary", `Successfully created user with ID: ${response.id}`);
     return response;
+  } catch (error) {
+    throw new Error(`Failed to create user: ${error.message}`);
+  }
 }
📝 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
async run({ $ }) {
const response = await this.app.createUser({
$,
data: {
id: this.userId,
first_name: this.firstName,
last_name: this.lastName,
is_account: this.isAccount,
number: this.number,
email: this.email,
},
});
$.export("$summary", `Successfully created user with ID: ${response.id}`);
return response;
},
async run({ $ }) {
// Validate required fields
if (!this.userId || !this.email) {
throw new Error("User ID and email are required fields");
}
try {
const response = await this.app.createUser({
$,
data: {
id: this.userId,
first_name: this.firstName,
last_name: this.lastName,
is_account: this.isAccount,
number: this.number,
email: this.email,
},
});
$.export("$summary", `Successfully created user with ID: ${response.id}`);
return response;
} catch (error) {
throw new Error(`Failed to create user: ${error.message}`);
}
},

Comment on lines +24 to +38
async run({ $ }) {
const response = await this.app.addCustomer({
$,
uid: this.uid,
data: {
accounts: [
{
id: this.customerId,
},
],
},
});
$.export("$summary", "add-customer executed successfully");
return response;
},
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

Add validation for customer ID and improve error handling.

The run method should validate inputs and handle potential errors from the API call.

 async run({ $ }) {
+  if (!this.uid || !this.customerId) {
+    throw new Error("User ID and Customer ID are required");
+  }
+
+  try {
     const response = await this.app.addCustomer({
       $,
       uid: this.uid,
       data: {
         accounts: [
           {
             id: this.customerId,
           },
         ],
       },
     });
     $.export("$summary", "add-customer executed successfully");
     return response;
+  } catch (error) {
+    throw new Error(`Failed to add customer: ${error.message}`);
+  }
 }
📝 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
async run({ $ }) {
const response = await this.app.addCustomer({
$,
uid: this.uid,
data: {
accounts: [
{
id: this.customerId,
},
],
},
});
$.export("$summary", "add-customer executed successfully");
return response;
},
async run({ $ }) {
if (!this.uid || !this.customerId) {
throw new Error("User ID and Customer ID are required");
}
try {
const response = await this.app.addCustomer({
$,
uid: this.uid,
data: {
accounts: [
{
id: this.customerId,
},
],
},
});
$.export("$summary", "add-customer executed successfully");
return response;
} catch (error) {
throw new Error(`Failed to add customer: ${error.message}`);
}
},

Copy link
Collaborator

@luancazarine luancazarine left a comment

Choose a reason for hiding this comment

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

Hio @lcaresia, I just added a suggestion.

key: "engage-add-event",
name: "Add Event",
description: "Adds user events to Engage. [See the documentation](https://docs.engage.so/en-us/a/62bbdd015bfea4dca4834042-users#track-user-event)",
version: "0.0.21",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
version: "0.0.21",
version: "0.0.1",

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: 0

🧹 Nitpick comments (6)
components/engage/engage.app.mjs (6)

37-51: Consider renaming uid property for clarity.

The property is labeled as "User ID", which is duplicative with the userId property defined earlier. Consider renaming to userUid to better differentiate between these identifiers and improve code readability.


72-77: Add timestamp format validation.

The timestamp is defined as a string without any format validation. Consider adding a description of the expected format (e.g., ISO 8601) and potentially adding validation to ensure the timestamp is properly formatted.


118-126: Validate uid parameter in addCustomer method.

The addCustomer method doesn't validate that the uid parameter is provided before attempting to use it in the path. Consider adding validation to ensure the required parameter is present.

 async addCustomer({
   uid, ...args
 }) {
+  if (!uid) {
+    throw new Error("User ID is required");
+  }
   return this._makeRequest({
     path: `/users/${uid}/accounts`,
     method: "post",
     ...args,
   });
 }

127-135: Validate uid parameter in addEvent method.

Similar to the addCustomer method, the addEvent method should validate the uid parameter before using it in the API path.

 async addEvent({
   uid, ...args
 }) {
+  if (!uid) {
+    throw new Error("User ID is required");
+  }
   return this._makeRequest({
     path: `/users/${uid}/events`,
     method: "post",
     ...args,
   });
 }

111-117: Consider adding data validation in createUser method.

The createUser method forwards all arguments directly to _makeRequest without any validation. Consider adding validation for required fields such as email or user ID.

 async createUser(args = {}) {
+  const { data } = args;
+  if (data && (!data.email && !data.user_id)) {
+    throw new Error("Either email or user_id is required");
+  }
   return this._makeRequest({
     path: "/users",
     method: "post",
     ...args,
   });
 }

136-141: Consider adding pagination handling in getUsers method.

The getUsers method doesn't handle pagination, which could be an issue if there are many users. Consider adding pagination support to fetch all users if needed.

 async getUsers(args = {}) {
   return this._makeRequest({
     path: "/users",
+    params: {
+      limit: 100,
+      ...args.params,
+    },
     ...args,
   });
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f4d07e and 42f25ed.

📒 Files selected for processing (2)
  • components/engage/actions/add-event/add-event.mjs (1 hunks)
  • components/engage/engage.app.mjs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/engage/actions/add-event/add-event.mjs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Publish TypeScript components
🔇 Additional comments (4)
components/engage/engage.app.mjs (4)

1-6: Module structure looks good.

The app is correctly defined with the appropriate imports and configuration. The module type and app name are properly set up for the Engage integration.


52-66: Verify customerId implementation.

The options function for customerId fetches and returns user IDs (uids), not customer IDs, despite the property description stating "ID of the customer that will be added to the user". This could lead to confusion or incorrect data being passed to the API.

Either:

  1. Update the options implementation to fetch actual customer IDs, or
  2. Clarify in the description that this represents a user ID that will be linked as a customer.

78-83: Add schema validation for properties object.

The properties field accepts any object structure without validation. Consider adding schema validation to ensure the properties match the expected format required by the Engage API.

According to Engage.so documentation, event properties should be key-value pairs with values limited to strings, numbers, booleans, or timestamps. Consider adding validation to enforce this structure.


94-110: Add error handling and request validation to _makeRequest method.

The _makeRequest method lacks error handling for network failures, request validation, and rate limiting considerations as previously suggested.

Add path validation and try-catch block to handle potential errors:

 async _makeRequest(opts = {}) {
   const {
     $ = this,
     path,
     auth,
     ...otherOpts
   } = opts;
+  if (!path) {
+    throw new Error("Path is required");
+  }
+  try {
     return axios($, {
       ...otherOpts,
       url: this._baseUrl() + path,
       auth: {
         ...auth,
         username: `${this.$auth.public_key}`,
         password: `${this.$auth.secret_key}`,
       },
     });
+  } catch (error) {
+    const errorMessage = error.response?.data?.message || error.message;
+    throw new Error(`Request failed: ${errorMessage}`);
+  }
 }

@lcaresia
Copy link
Collaborator Author

/approve

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.

[Components] engage
2 participants