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

New Components - wati #14276

Merged
merged 6 commits into from
Oct 16, 2024
Merged

New Components - wati #14276

merged 6 commits into from
Oct 16, 2024

Conversation

luancazarine
Copy link
Collaborator

@luancazarine luancazarine commented Oct 10, 2024

Resolves #13213.

Summary by CodeRabbit

  • New Features

    • Introduced modules for adding contacts, sending WhatsApp template messages, and updating contact attributes.
    • Added event handling for new contact creation and incoming messages.
  • Improvements

    • Enhanced the WATI application module for better API integration related to contact management and messaging.
  • Version Update

    • The version number for the WATI component has been updated to 0.1.0, with modifications to the main entry point and dependencies.

@luancazarine luancazarine added the ai-assisted Content generated by AI, with human refinement and modification label Oct 10, 2024
Copy link

vercel bot commented Oct 10, 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 16, 2024 1:11pm
pipedream-docs ⬜️ Ignored (Inspect) Oct 16, 2024 1:11pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Oct 16, 2024 1:11pm

Actions
 - Add Contact
 - Send Template Message
 - Update Contact Attribute

Source
 - New Contact Created
 - New Incoming Message
@luancazarine luancazarine marked this pull request as ready for review October 14, 2024 15:11
Copy link
Collaborator

@michelle0927 michelle0927 left a comment

Choose a reason for hiding this comment

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

Looks good, just one comment/question.

components/wati/wati.app.mjs Outdated Show resolved Hide resolved
Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Walkthrough

The pull request introduces significant changes to the WATI components, including the addition of new action modules for adding contacts, sending template messages, and updating contact attributes. It also replaces an existing application file with a new module that encapsulates WATI API functionalities. Additionally, new event handling modules for new contact creation and incoming messages are added, along with updates to the package.json file to reflect version changes and new dependencies.

Changes

File Path Change Summary
components/wati/.gitignore Deleted the .gitignore file that ignored .js, .mjs files, and the dist directory.
components/wati/actions/add-contact/add-contact.mjs Introduced a new action module for adding contacts with properties and a run method.
components/wati/actions/send-template-message/send-template-message.mjs Introduced a new action module for sending template messages with properties and a run method.
components/wati/actions/update-contact-attribute/update-contact-attribute.mjs Introduced a new action module for updating contact attributes with properties and a run method.
components/wati/app/wati.app.ts Deleted the old application file and replaced it with a new module for WATI API integration.
components/wati/wati.app.mjs New module for WATI API functionalities, including methods for contact management and message handling.
components/wati/package.json Updated version number, main entry point, and added new dependencies.
components/wati/sources/common/base.mjs New module for handling events related to new contact creation.
components/wati/sources/new-contact-created/new-contact-created.mjs New module for emitting events when a new contact is created.
components/wati/sources/new-incoming-message/new-incoming-message.mjs New module for managing incoming messages in WhatsApp integration.
components/wati/sources/new-contact-created/test-event.mjs New module representing a contact entity for testing purposes.
components/wati/sources/new-incoming-message/test-event.mjs New module representing an incoming message event for testing purposes.

Assessment against linked issues

Objective Addressed Explanation
Emit new event when a contact is created (#[13213])
Emit new event when there is an incoming message (#[13213])
Facilitate the addition of a new contact (#[13213])
Enable sending of WhatsApp messages using a template (#[13213])
Allow updating attributes related to an existing contact (#[13213])

Possibly related PRs

  • New Components - botpenguin #12232: The new BotPenguin components include actions for adding contacts and updating attributes, which relate to the main PR's focus on adding and updating contacts in the WATI platform.
  • New Components - peach #12856: The Peach components also introduce actions for adding contacts and sending messages, similar to the functionalities added in the main PR for the WATI platform.
  • New Components - krispcall #13867: The KrispCall components include actions for adding contacts and sending messages, which are directly related to the new functionalities introduced in the main PR for managing contacts and messages in WATI.
  • New Components - hullo #14271: The Hullo components introduce actions for adding or updating members, which aligns with the main PR's focus on managing contacts in the WATI platform.
  • New Components - chargify #14284: The Chargify components include actions for creating customers and subscriptions, which relate to the main PR's focus on managing contacts and actions in the WATI platform.

Suggested reviewers

  • lcaresia

🐰 Hopping through the code, what a sight to see,
New actions and events, as bright as can be!
Contacts and messages, all in a row,
WATI's now ready, let's watch it all flow!
With each little change, our features do grow,
A leap for the rabbits, let the good times roll! 🐇✨


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

🧹 Outside diff range and nitpick comments (9)
components/wati/package.json (1)

15-17: New dependency looks appropriate.

The addition of "@pipedream/platform" as a dependency is in line with the PR objectives of adding new components and actions. This suggests that the WATI component now leverages core Pipedream functionality.

Consider updating the component's documentation to reflect any new setup steps or requirements introduced by this dependency, if applicable.

components/wati/sources/new-incoming-message/test-event.mjs (1)

1-26: LGTM! Consider grouping related properties

The overall structure of the test event object looks good and appears to align with the WATI API response for a new incoming message. To improve readability and maintainability, consider grouping related properties together.

You could organize the properties as follows:

  1. Message content properties (text, type, data)
  2. Message metadata (timestamp, created, id, conversationId, ticketId, eventType)
  3. User-related properties (owner, avatarUrl, assignedId, operatorName)
  4. Status-related properties (statusString, localMessageId, failedDetail)
  5. Additional data properties (contacts, messageProducts, orderProducts, interactiveData, orderDetailsViewModel)
  6. Reference properties (replySourceMessage, messageReferral, referenceOrderId)

This grouping can make it easier to understand and maintain the test event structure in the future.

components/wati/actions/add-contact/add-contact.mjs (2)

10-31: LGTM: Props are well-defined, with a minor suggestion.

The properties for the action are correctly defined and align with the requirements for adding a contact to WATI. The use of propDefinition for whatsappNumber and customParams promotes consistency and reusability.

Consider adding a brief description for the customParams prop to clarify its purpose and expected format for users.


32-52: LGTM: Run method implementation is solid, with suggestions for improvement.

The run method correctly implements the logic for adding a contact to WATI, including proper error handling and success reporting.

Consider the following improvements:

  1. Add input validation for whatsappNumber to ensure it's in the correct format before making the API call.
  2. Use object destructuring for cleaner code in the customParams transformation:
    customParams: this.customParams && Object.entries(this.customParams).map(([name, value]) => ({
      name,
      value,
    })),
  3. Consider adding more detailed error handling, possibly distinguishing between different types of errors (e.g., network errors, API errors) for better debugging.
components/wati/actions/send-template-message/send-template-message.mjs (2)

18-25: Consider adding validation for customParams.

The customParams prop is well-defined, but it could benefit from additional validation or formatting guidelines to ensure users provide the correct structure for the template parameters.

Consider adding a validation function or providing an example of the expected object structure in the description. For example:

customParams: {
  propDefinition: [
    wati,
    "customParams",
  ],
  label: "Parameters",
  description: "An object with template's custom params. Example: { \"1\": \"John\", \"2\": \"Doe\" }",
  validate: (value) => {
    if (typeof value !== 'object' || Array.isArray(value)) {
      throw new Error("customParams must be an object");
    }
  },
},

56-62: LGTM: Good error handling and response processing.

The error handling and success message export are well implemented. Returning the full response is a good practice for flexibility.

Consider adding more detailed information to the success message, such as the template name used. For example:

$.export("$summary", `Successfully sent template message "${this.templateName}" to ${this.whatsappNumber}`);

This provides more context in the action's execution summary.

components/wati/sources/new-contact-created/new-contact-created.mjs (1)

29-29: Ensure item.wAid is defined in getSummary

In the getSummary method, item.wAid might be undefined or null, which would result in a summary like New contact created: undefined. To prevent this, consider providing a default value or checking if item.wAid exists before including it in the summary.

Apply this diff to provide a default value:

- return `New contact created: ${item.wAid}`;
+ const wAid = item.wAid || "unknown";
+ return `New contact created: ${wAid}`;
components/wati/actions/update-contact-attribute/update-contact-attribute.mjs (1)

45-46: Consider Adding Unit Tests for the Action

To ensure reliability and facilitate future maintenance, consider adding unit tests for this action. This will help in verifying that all functionalities work as expected.

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

112-139: Validate pagination logic in paginate method

The pagination logic assigns hasMore = data.length; and uses it in the loop condition. While this works, it's clearer to convert it to a boolean value.

Apply this diff for clarity:

-          hasMore = data.length;
+          hasMore = data.length > 0;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between edd4923 and bc0fff1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (12)
  • components/wati/.gitignore (0 hunks)
  • components/wati/actions/add-contact/add-contact.mjs (1 hunks)
  • components/wati/actions/send-template-message/send-template-message.mjs (1 hunks)
  • components/wati/actions/update-contact-attribute/update-contact-attribute.mjs (1 hunks)
  • components/wati/app/wati.app.ts (0 hunks)
  • components/wati/package.json (1 hunks)
  • components/wati/sources/common/base.mjs (1 hunks)
  • components/wati/sources/new-contact-created/new-contact-created.mjs (1 hunks)
  • components/wati/sources/new-contact-created/test-event.mjs (1 hunks)
  • components/wati/sources/new-incoming-message/new-incoming-message.mjs (1 hunks)
  • components/wati/sources/new-incoming-message/test-event.mjs (1 hunks)
  • components/wati/wati.app.mjs (1 hunks)
💤 Files with no reviewable changes (2)
  • components/wati/.gitignore
  • components/wati/app/wati.app.ts
🧰 Additional context used
🔇 Additional comments (15)
components/wati/package.json (2)

3-3: Version update looks good.

The version increment from 0.0.1 to 0.1.0 aligns with semantic versioning principles and reflects the addition of new features (components and actions) as described in the PR objectives.


1-18: Overall package.json changes align well with PR objectives.

The updates to version, main entry point, and dependencies in this package.json file accurately reflect the addition of new WATI components and actions as described in the PR objectives. The changes follow good practices in terms of semantic versioning and dependency management.

To ensure all changes are properly reflected, run the following script:

#!/bin/bash
# Description: Verify that all new components mentioned in the PR objectives are present in the codebase.

echo "Checking for new WATI components:"
fd --type f "wati.*\.(js|mjs|ts)" --exec echo "Found: {}"

echo "Checking for specific new components mentioned in PR objectives:"
rg --type js "new-contact-created-instant"
rg --type js "new-incoming-message-instant"
rg --type js "add-contact"
rg --type js "send-template-message"
rg --type js "update-contact-attribute"
components/wati/sources/new-contact-created/test-event.mjs (1)

1-33: Overall structure looks good for testing purposes.

The object structure provides a comprehensive representation of a contact entity, which is suitable for testing the new contact creation event. It includes a variety of data types and states (e.g., null values, booleans, arrays) that can help cover different scenarios in tests.

Consider improving property naming consistency.

For better code readability and maintenance, consider standardizing the property naming conventions. For example:

  • wAid could be changed to waId or whatsappId for clarity.
  • isInFlow follows a different naming pattern compared to other boolean properties like allowBroadcast. Consider using a consistent style across all boolean properties.

Review the necessity of duplicated data in customParams.

The customParams array contains information that is already present in the main object properties (name and phone). While this might be intentional for testing purposes, it's worth considering if this duplication is necessary or if it might lead to confusion in real-world scenarios.

To check if this duplication is consistent across the codebase, you can run the following script:

#!/bin/bash
# Description: Check for similar patterns of data duplication in custom parameters across the codebase.

# Search for patterns where main object properties are duplicated in customParams
rg --type javascript -e 'customParams.*name.*phone' -e 'customParams.*firstName.*phone'
components/wati/actions/add-contact/add-contact.mjs (2)

1-9: LGTM: Imports and action definition are well-structured.

The imports, action key, name, description, and version are correctly defined. The inclusion of the API documentation link in the description is a good practice for maintainability.


1-53: Overall assessment: Well-implemented action with minor improvement opportunities.

This new "Add Contact" action for WATI is well-structured and aligns with the PR objectives. It correctly implements the functionality to add a new contact to the WATI platform using their API.

Key strengths:

  1. Proper use of Pipedream's action structure and best practices.
  2. Good error handling and success reporting.
  3. Flexible prop definitions allowing for optional parameters.

Areas for potential improvement:

  1. Input validation for the WhatsApp number.
  2. More detailed error handling for better debugging.
  3. Minor code readability enhancements.

These suggestions aside, the implementation is solid and ready for integration.

components/wati/actions/send-template-message/send-template-message.mjs (2)

1-9: LGTM: Imports and action metadata are well-defined.

The imports are appropriate, and the action metadata provides clear information about the purpose and version of the action. Including the API documentation link in the description is a good practice.


38-44: LGTM: Run method initialization is well-structured.

The async run method is correctly defined, and the initial structure of the API call looks appropriate. The use of destructuring for $ and the inclusion of whatsappNumber in the params object follow good practices for Pipedream actions.

components/wati/sources/new-contact-created/new-contact-created.mjs (1)

26-26: Verify that this.wati.listContacts is defined

In the getFunction method, you return this.wati.listContacts. Ensure that this.wati is properly initialized and that listContacts is a valid function to prevent runtime errors.

Run the following script to verify the existence of listContacts:

components/wati/sources/new-incoming-message/new-incoming-message.mjs (2)

47-47: Confirm the correct property for message content in getSummary().

In the getSummary() method, item.text is used to extract the message content. Ensure that item.text is the correct property from the API response for the message content. If the property is different (e.g., message or body), update it accordingly.


14-19: ⚠️ Potential issue

Verify the correct usage of propDefinition for contactId.

In the props section, the contactId property uses propDefinition with common.props.wati and "contactId". Ensure that common.props.wati contains the correct definition for contactId. Misconfigurations here might lead to unexpected behavior when the component is used.

components/wati/actions/update-contact-attribute/update-contact-attribute.mjs (3)

1-2: Module Imports are Correct

The necessary modules are correctly imported, ensuring that the action has access to the required functionalities.


4-25: Action Metadata and Properties are Well-Defined

The action is properly defined with accurate metadata:

  • Key: "wati-update-contact-attribute"
  • Name: "Update Contact Attribute"
  • Description: Provides a clear explanation with a link to the documentation.
  • Version and Type: Correctly specified.

The properties whatsappNumber and customParams are correctly defined using propDefinition, ensuring consistency and reusability.


26-46: run Method Implementation is Efficient and Correct

The run method is well-implemented:

  • API Call: Correctly invokes updateContactAttributes with the necessary parameters.
  • Data Transformation: Efficiently transforms customParams into the required format for the API by mapping object entries to an array of { name, value } objects.
  • Error Handling: Appropriately checks the response.result and throws a ConfigurationError with response.info if the API indicates failure.
  • Success Message: Exports a clear summary message upon successful execution.
  • Return Value: Returns the full response for further use.
components/wati/wati.app.mjs (2)

105-105: Ensure consistent parameter naming in API paths

In the updateContactAttributes method, consider verifying that whatsappNumber is the correct parameter used in the API endpoint. Depending on the API specification, it might be necessary to use contactId or another identifier.


89-89: Confirm correctness of API endpoint parameters

In the addContact method, ensure that the whatsappNumber parameter in the path is correctly formatted as per the API requirements. It should include the country code and may need validation.

components/wati/package.json Show resolved Hide resolved
components/wati/sources/common/base.mjs Outdated Show resolved Hide resolved
components/wati/wati.app.mjs Outdated Show resolved Hide resolved
components/wati/wati.app.mjs Outdated Show resolved Hide resolved
components/wati/wati.app.mjs Show resolved Hide resolved
components/wati/wati.app.mjs Show resolved Hide resolved
michelle0927
michelle0927 previously approved these changes Oct 14, 2024
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: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bc0fff1 and d8b8309.

📒 Files selected for processing (4)
  • components/wati/sources/common/base.mjs (1 hunks)
  • components/wati/sources/new-contact-created/new-contact-created.mjs (1 hunks)
  • components/wati/sources/new-incoming-message/new-incoming-message.mjs (1 hunks)
  • components/wati/wati.app.mjs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/wati/sources/common/base.mjs
🧰 Additional context used
🔇 Additional comments (13)
components/wati/sources/new-contact-created/new-contact-created.mjs (7)

1-2: LGTM: Import statements are appropriate.

The import statements are correctly importing the necessary modules for this component.


4-11: LGTM: Exported object properties are well-defined.

The exported object's properties are correctly defined and align with the PR objectives for implementing a new contact created webhook source. The version, type, and dedupe settings are appropriate for this new component.


14-21: LGTM: getPaginateOpts method is well-implemented.

The getPaginateOpts method correctly defines the pagination options for listing contacts. It properly uses the maxResults parameter and specifies the relevant fields for pagination.


22-24: LGTM: getDateField method is correctly implemented.

The getDateField method correctly returns the "created" field, which is appropriate for date-based operations in this context.


28-30: LGTM: getSummary method is correctly implemented.

The getSummary method appropriately generates a summary string for the new contact, using the wAid property as expected.


32-32: LGTM: sampleEmit property is correctly set.

The sampleEmit property is appropriately set to the imported value, which is likely used for testing or documentation purposes.


25-27: ⚠️ Potential issue

Handle potential NaN results from Date.parse

The checkBreak method still doesn't handle potential NaN results from Date.parse(item.created). This issue was previously identified and should be addressed to prevent unexpected behavior.

Please refer to the previous comment and consider implementing the suggested fix:

- return Date.parse(item.created) < lastDate;
+ const itemDate = Date.parse(item.created);
+ if (isNaN(itemDate)) {
+   // Handle invalid date
+   return false; // Adjust based on desired behavior
+ }
+ return itemDate < lastDate;
components/wati/sources/new-incoming-message/new-incoming-message.mjs (5)

1-11: LGTM: Component definition and imports look good.

The component definition is well-structured with appropriate imports, key, name, description, version, type, and deduplication strategy. The use of "unique" for deduplication is suitable for handling incoming messages.


12-20: LGTM: Props definition is correct and well-structured.

The component correctly extends common props and adds a specific "contactId" prop using the propDefinition from the wati common props. This approach maintains consistency and provides the necessary customization for this component.


51-52: LGTM: Sample emit export is correctly implemented.

The inclusion of a sampleEmit property, imported from "test-event.mjs", is a good practice for testing and documentation purposes. This will help developers understand the expected event format and facilitate testing of the component.


44-46: ⚠️ Potential issue

Handle invalid or missing item.timestamp in checkBreak().

The method Date.parse(item.timestamp) assumes that item.timestamp is a valid date string. If item.timestamp is undefined or invalid, Date.parse() will return NaN, causing the comparison to fail. Add a check to handle such cases gracefully.

Apply this diff to handle invalid timestamps:

 checkBreak(item, lastDate) {
-  return Date.parse(item.timestamp) < lastDate;
+  const timestamp = Date.parse(item.timestamp);
+  return !isNaN(timestamp) && timestamp < lastDate;
 }

Likely invalid or redundant comment.


23-32: ⚠️ Potential issue

Normalize contactId to prevent duplicate '+' signs in whatsappNumber.

When constructing whatsappNumber in getPaginateOpts(), the code prepends a '+' to this.contactId. If this.contactId already includes a '+', this will result in '++', which might cause API errors. Consider normalizing contactId to ensure it doesn't already include the '+' sign.

Apply this diff to normalize contactId:

 return {
   fn: this.wati.listContactMessages,
-  whatsappNumber: `+${this.contactId}`,
+  whatsappNumber: `${this.contactId.startsWith('+') ? '' : '+'}${this.contactId}`,
   itemsField: [
     "messages",
   ],
   optsField: "params",
 };

Likely invalid or redundant comment.

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

1-5: LGTM: Imports and module definition

The import statement and module definition are correct and follow Pipedream platform conventions.

@luancazarine
Copy link
Collaborator Author

/approve

@luancazarine luancazarine merged commit dd0bef4 into master Oct 16, 2024
12 checks passed
@luancazarine luancazarine deleted the issue-13213 branch October 16, 2024 19:44
This was referenced Oct 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ai-assisted Content generated by AI, with human refinement and modification
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Components] wati
2 participants