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 - microsoft_dynamics_365_sales #15478

Merged
merged 6 commits into from
Feb 5, 2025
Merged

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented Jan 31, 2025

Resolves #15441

Summary by CodeRabbit

Release Notes for Microsoft Dynamics 365 Sales Integration

  • New Features

    • Added ability to create custom entities in Dynamics 365 Sales.
    • Introduced contact search functionality.
    • Enhanced language code support for internationalization.
  • Improvements

    • Expanded API interaction methods.
    • Added support for dynamic contact and solution selection.
    • Improved metadata handling for entities.
  • Version Update

    • Upgraded package version from 0.0.1 to 0.1.0.
    • Added new dependencies for enhanced functionality.

Copy link

vercel bot commented Jan 31, 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 4, 2025 5:55pm
pipedream-docs ⬜️ Ignored (Inspect) Feb 4, 2025 5:55pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Feb 4, 2025 5:55pm

Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

Walkthrough

This pull request introduces new functionality for Microsoft Dynamics 365 Sales, encompassing actions for finding contacts and creating custom entities. It includes a module for creating custom entities with various configuration options, a component for searching contacts with flexible filtering, and a static array of language codes for internationalization. Additionally, the application methods have been expanded to enhance API interactions, and the package configuration has been updated to reflect new dependencies and versioning.

Changes

File Change Summary
components/microsoft_dynamics_365_sales/actions/create-custom-entity/create-custom-entity.mjs New module for creating custom entities with comprehensive configuration options
components/microsoft_dynamics_365_sales/actions/find-contact/find-contact.mjs New action to search and retrieve contacts with flexible filtering
components/microsoft_dynamics_365_sales/common/language-codes.mjs Added static array of language objects for internationalization
components/microsoft_dynamics_365_sales/microsoft_dynamics_365_sales.app.mjs Extended app methods, added new properties for contacts and solutions, implemented API interaction methods
components/microsoft_dynamics_365_sales/package.json Updated version, added dependencies, modified publish configuration

Assessment against linked issues

Objective Addressed Explanation
Find Contact Action [#15441]
Create Custom Entity Action [#15441]
Support API Calls to EntityDefinitions [#15441]

Suggested labels

ai-assisted

Suggested reviewers

  • lcaresia

Poem

🐰 In Dynamics' digital dance,
Entities leap with code's sweet glance,
Contacts found, custom worlds unfurl,
A rabbit's API magic swirl!
Pipedream's magic, smooth and bright! 🌟

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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.

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

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

6-21: Consider renaming the destructured variable to avoid confusion.

In the contactId prop options, destructuring contactid as value can be confusing since it overlaps with the variable named value returned by this.listContacts(). You might rename them to something more descriptive, e.g. id and contacts.

components/microsoft_dynamics_365_sales/actions/create-custom-entity/create-custom-entity.mjs (1)

64-83: Utility methods are helpful, but revise removeSpaces.

removeSpaces(str.replace(" ", "")) will only remove the first space. To handle all spaces, consider a global replace or a trim if needed.

-    return str.replace(" ", "");
+    return str.replace(/\s+/g, "");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c360726 and 89c7daa.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • components/microsoft_dynamics_365_sales/actions/create-custom-entity/create-custom-entity.mjs (1 hunks)
  • components/microsoft_dynamics_365_sales/actions/find-contact/find-contact.mjs (1 hunks)
  • components/microsoft_dynamics_365_sales/common/language-codes.mjs (1 hunks)
  • components/microsoft_dynamics_365_sales/microsoft_dynamics_365_sales.app.mjs (1 hunks)
  • components/microsoft_dynamics_365_sales/package.json (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/microsoft_dynamics_365_sales/common/language-codes.mjs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Verify TypeScript components
🔇 Additional comments (23)
components/microsoft_dynamics_365_sales/microsoft_dynamics_365_sales.app.mjs (9)

22-35: Looks good!

The solutionId prop definition mirrors contactId and appears correct for retrieving solution data dynamically.


38-40: Base URL logic confirmed.

Constructing the base URL from the org_domain is straightforward and appears correct.


60-65: Implementation confirmed.

Fetching contacts via _makeRequest is consistent with the approach used throughout the module.


66-73: Publisher retrieval looks good.

Short, focused, and consistent with the rest of the code.


74-81: Solution retrieval confirmed.

No issues with constructing the path for getting a solution by its ID.


82-87: List solutions logic is fine.

The approach matches the existing methods for listing resources.


88-95: Entity retrieval is straightforward.

Just ensure that valid entity identifiers are passed in. The method is minimal and consistent.


96-101: Entity creation endpoint usage confirmed.

createCustomEntity properly sets method: "POST" and targets /EntityDefinitions. The pattern aligns with the rest of the code.


104-104: End of export confirmed.

No additional feedback.

components/microsoft_dynamics_365_sales/actions/create-custom-entity/create-custom-entity.mjs (8)

1-4: Imports look good.

Bringing in your Microsoft app, language codes, and the pluralize library is aligned with the requirements.


5-10: Action metadata is well-defined.

The action key, name, description, and version are properly declared.


11-62: Props are comprehensive and well-documented.

You've provided robust property definitions, including a default language code and optional fields for advanced customization.


85-90: Solution lookup is straightforward.

Retrieving the solution by solutionId is consistent with the rest of the module’s pattern.


91-95: Publisher lookup confirmed.

Calling getPublisher with the solution’s publisher ID is correct for referencing the prefix data.


96-101: Creating the custom entity with _makeRequest.

Checks out: the code uses method: "POST" and merges additional configuration properly.


104-145: Metadata object structure is thorough.

You define labels, schema names, default owners, and more. This aligns with the Microsoft Dynamics 365 web API approach.


147-156: Final retrieval and summary are clear.

Extracting the entity’s ID from the headers, fetching it, and exporting a summary is a neat workflow.

components/microsoft_dynamics_365_sales/actions/find-contact/find-contact.mjs (3)

1-2: Imports confirmed.

Bringing in the Microsoft app reference is consistent with your app’s structure.


3-29: Action definition is properly labeled.

Key, name, description, and version fields are accurate. Props reference the contactId definition in the parent app, plus optional name and filter fields.


30-58: Dynamic filter construction is well-executed.

Combining user inputs with logical “and” is straightforward. Ensuring $filter is undefined if no terms are present is a clean approach.

components/microsoft_dynamics_365_sales/package.json (3)

3-3: Version Update Verification

The version has been updated to "0.1.0" which is appropriate for introducing new functionality (e.g., the Microsoft Dynamics 365 Sales components). Ensure that this update aligns with your semantic versioning and release strategy.


14-14: Publish Configuration Update

The "publishConfig": { "access": "public" } update is correct for ensuring public distribution of this package. Please verify that this setting is consistent with your deployment policies.


15-17: Dependency Addition Review

The added dependencies "@pipedream/platform": "^3.0.3" and "pluralize": "^8.0.0" appear to support the new functionality for Microsoft Dynamics 365 Sales. Confirm that these dependency versions are compatible with your existing components and that any changes in behavior are documented.

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 (2)
components/microsoft_dynamics_365_sales/actions/create-custom-entity/create-custom-entity.mjs (2)

64-83: Helper Methods: Ensure Robustness and Consistency

  1. parseAttributes (lines 65-70):
    • The method correctly checks if additionalAttributes exists and whether it is a string or an object.
    • Suggestion: Wrap the JSON parsing in a try/catch block to handle potential JSON parsing errors and report a more descriptive error if the input is malformed.
      Proposed change:
-    parseAttributes() {
-      return this.additionalAttributes
-        ? typeof this.additionalAttributes === "string"
-          ? JSON.parse(this.additionalAttributes)
-          : this.additionalAttributes
-        : [];
-    },
+    parseAttributes() {
+      try {
+        if (!this.additionalAttributes) return [];
+        return typeof this.additionalAttributes === "string"
+          ? JSON.parse(this.additionalAttributes)
+          : this.additionalAttributes;
+      } catch (error) {
+        throw new Error("Invalid JSON format in additionalAttributes");
+      }
+    },
  1. removeSpaces (lines 72-74):
    This one-liner function effectively removes all whitespace from a string.

  2. buildLocalizedLabelArray (lines 75-83):
    The function cleanly wraps a given label into the format expected by the Dynamics 365 API.


85-156: run Method: Logical Flow with API Integration

The asynchronous run method implements the main logic as follows:

  • Solution and Publisher Retrieval (lines 86-94):
    It first retrieves the solution using this.microsoft.getSolution and then the publisher using the solution’s publisher ID. Ensure that both API methods reliably return the expected fields (e.g., _publisherid_value).

  • Parsing Additional Attributes (line 96):
    Uses the helper method to ensure attributes are provided in the correct format.

  • Creating the Custom Entity (lines 98-145):
    The payload is well-constructed. The data object builds:

    • The primary attribute metadata (including schema, display name, and attribute settings).
    • Display names using localized labels and a pluralized version for the collection name.
    • Conditional inclusion of the description.
    • Custom settings for activities/notes and ownership type.

    The use of the spread operator (...attributes) to include additional attributes is appropriate if the expectation is that attributes is an array.

  • Extracting the Entity ID (line 147):
    The code extracts the entity ID using string manipulation on the header.
    Suggestion: Validate that the header odata-entityid exists before using substring operations.
    Proposed change:

-    const entityId = headers["odata-entityid"].substring(headers["odata-entityid"].lastIndexOf("/") + 1);
+    const entityHeader = headers["odata-entityid"];
+    if (!entityHeader) {
+      throw new Error("Missing 'odata-entityid' header in response");
+    }
+    const entityId = entityHeader.substring(entityHeader.lastIndexOf("/") + 1);
  • Entity Retrieval and Summary Export (lines 148-156):
    The subsequent retrieval of the created entity and export of a summary message are clear and concise.

Overall, the method cleanly integrates multiple asynchronous API calls to create and verify a custom entity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 89c7daa and 8ef9ca7.

📒 Files selected for processing (1)
  • components/microsoft_dynamics_365_sales/actions/create-custom-entity/create-custom-entity.mjs (1 hunks)
⏰ 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 (2)
components/microsoft_dynamics_365_sales/actions/create-custom-entity/create-custom-entity.mjs (2)

1-4: Import Statements are Clear and Organized

The imports use clean relative paths and load the necessary modules (the Dynamics 365 app interface, language codes, and the pluralize library). No issues were found.


5-63: Export Object and Props Definition: Well-Structured

The exported object defines the action’s key, name, description, and version clearly. The properties (props) are configured with appropriate types, default values, and helpful descriptions. In particular:

  • The solutionId prop correctly uses the propDefinition from the Microsoft Dynamics 365 app.
  • The languageCode is set with a default of 1033 and marked optional.
  • Additional props like additionalAttributes, hasActivities, and hasNotes are given clear labels and descriptions.

Consider verifying that all prop labels and descriptions fully align with Microsoft's documentation requirements.

jcortes
jcortes previously approved these changes Feb 3, 2025
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 @michelle0927 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: 2

♻️ Duplicate comments (1)
components/microsoft_dynamics_365_sales/microsoft_dynamics_365_sales.app.mjs (1)

41-59: ⚠️ Potential issue

Add error handling to _makeRequest.

The method should handle API errors and provide meaningful error messages.

 _makeRequest({
   $ = this,
   path,
   headers,
   ...opts
 }) {
+  if (!path) {
+    throw new Error('Path is required for API requests');
+  }
+  
   return axios($, {
     url: `${this._baseUrl()}${path}`,
     headers: {
       ...headers,
       "Authorization": `Bearer ${this.$auth.oauth_access_token}`,
       "odata-maxversion": "4.0",
       "odata-version": "4.0",
       "content-type": "application/json",
       "If-None-Match": null,
     },
     ...opts,
-  });
+  }).catch((error) => {
+    const status = error?.response?.status;
+    const message = error?.response?.data?.error?.message || error.message;
+    throw new Error(`Dynamics 365 API request failed: ${status} - ${message}`);
+  });
 },
🧹 Nitpick comments (1)
components/microsoft_dynamics_365_sales/microsoft_dynamics_365_sales.app.mjs (1)

38-102: Refactor API paths into constants and add rate limiting.

Consider the following improvements:

  1. Define API paths as constants for better maintainability
  2. Implement rate limiting to prevent API throttling
  3. Add input validation for method parameters
+const API_PATHS = {
+  CONTACTS: '/contacts',
+  PUBLISHERS: (id) => `/publishers(${id})`,
+  SOLUTIONS: '/solutions',
+  SOLUTION: (id) => `/solutions(${id})`,
+  ENTITY_DEFINITIONS: '/EntityDefinitions',
+};
+
+const RATE_LIMIT = {
+  MAX_REQUESTS: 100,
+  WINDOW_MS: 60000, // 1 minute
+};
+
+let requestCount = 0;
+let windowStart = Date.now();
+
 methods: {
   // ... existing methods ...
+  
+  async _checkRateLimit() {
+    const now = Date.now();
+    if (now - windowStart > RATE_LIMIT.WINDOW_MS) {
+      requestCount = 0;
+      windowStart = now;
+    }
+    if (requestCount >= RATE_LIMIT.MAX_REQUESTS) {
+      throw new Error('Rate limit exceeded. Please try again later.');
+    }
+    requestCount++;
+  },
+
   _makeRequest({
     $ = this,
     path,
     headers,
     ...opts
   }) {
+    await this._checkRateLimit();
     // ... rest of the method ...
   },
   
   listContacts(opts = {}) {
     return this._makeRequest({
-      path: "/contacts",
+      path: API_PATHS.CONTACTS,
       ...opts,
     });
   },
   
   getPublisher({
     publisherId, ...opts
   }) {
+    if (!publisherId) {
+      throw new Error('Publisher ID is required');
+    }
     return this._makeRequest({
-      path: `/publishers(${publisherId})`,
+      path: API_PATHS.PUBLISHERS(publisherId),
       ...opts,
     });
   },
   
   // ... update other methods similarly ...
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ef9ca7 and 88e2593.

📒 Files selected for processing (1)
  • components/microsoft_dynamics_365_sales/microsoft_dynamics_365_sales.app.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Verify TypeScript components

@michelle0927
Copy link
Collaborator Author

/approve

@michelle0927 michelle0927 merged commit da89cd0 into master Feb 5, 2025
11 checks passed
@michelle0927 michelle0927 deleted the issue-15441 branch February 5, 2025 17:10
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.

Dynamics 365
2 participants