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 2 commits into
base: master
Choose a base branch
from
Open

[Components] engage #13410 #15656

wants to merge 2 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 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 ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview Feb 18, 2025 5:29pm
pipedream-docs ⬜️ Ignored (Inspect) Feb 18, 2025 5:29pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Feb 18, 2025 5:29pm

Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

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

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!
🐇💻

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

components/engage/actions/add-customer/add-customer.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

components/engage/actions/add-event/add-event.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

components/engage/actions/create-user/create-user.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

  • 1 others
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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
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}`);
}
},

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