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

Sync new customers from the WF service to the Unified API #2786

Merged
merged 2 commits into from
Oct 20, 2024
Merged

Conversation

MatanYadaev
Copy link
Collaborator

@MatanYadaev MatanYadaev commented Oct 15, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new controller for external business reports, enhancing reporting capabilities.
    • Added methods for customer management: create, update, and delete.
  • Improvements

    • Enhanced transaction handling in customer repository methods for better database interaction.
    • Updated customer service to utilize transaction management and improved database interactions.
  • Dependency Updates

    • Updated package version and added a new dependency for retry functionality to improve reliability in asynchronous operations.

Copy link

changeset-bot bot commented Oct 15, 2024

⚠️ No Changeset found

Latest commit: ea9aa62

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Walkthrough

This pull request introduces several updates to the workflows service. The version of the service is incremented to 0.7.58, and a new dependency, "p-retry": "^6.2.0", is added. A new controller, BusinessReportControllerExternal, is introduced to handle GET requests for business reports. Additionally, the UnifiedApiClient class is enhanced with new customer management methods, while the CustomerRepository class is updated to support transaction management and improved type definitions.

Changes

File Path Change Summary
services/workflows-service/package.json Version updated to 0.7.58, added dependency "p-retry": "^6.2.0"
services/workflows-service/src/business-report/business-report.controller.external.ts Added BusinessReportControllerExternal class with list method for GET requests
services/workflows-service/src/business-report/business-report.module.ts Updated BusinessReportModule to include BusinessReportControllerExternal
services/workflows-service/src/common/utils/unified-api-client/unified-api-client.ts Enhanced UnifiedApiClient with createCustomer, updateCustomer, and deleteCustomer methods; updated imports
services/workflows-service/src/customer/customer.repository.ts Updated CustomerRepository methods for transaction handling

Possibly related PRs

  • Fix "create customer" flow #2419: This PR addresses the "create customer" flow, which may relate to the changes in the CustomerRepository class in the main PR, as both involve customer management functionalities.
  • Limit reports generation per customer #2582: This PR introduces a limit on report generation per customer, which connects to the overall customer management context and may relate to the new BusinessReportControllerExternal added in the main PR.
  • Not showing unfinished ongoing reports #2773: This PR modifies the BusinessReportControllerInternal to refine the filtering logic for business reports, which is relevant to the new BusinessReportControllerExternal introduced in the main PR.

Suggested reviewers

  • tomer-shvadron

Poem

In the garden where we play,
New reports come out to sway,
With retries to help us through,
Customer paths now clearer too.
Hops and jumps, we celebrate,
Changes here, oh what a fate! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 88f63fb and ea9aa62.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • services/workflows-service/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • services/workflows-service/package.json

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

🧹 Outside diff range and nitpick comments (13)
services/workflows-service/src/business-report/business-report.module.ts (1)

18-21: Reminder: Consider follow-up tasks for the new external controller.

With the addition of BusinessReportControllerExternal, please ensure the following:

  1. Update API documentation to reflect any new endpoints.
  2. Verify that appropriate authentication and authorization are in place for the new external routes.
  3. If this introduces breaking changes to the API, consider versioning and communicate changes to API consumers.
  4. Update any relevant tests to cover the new controller.
services/workflows-service/src/common/utils/unified-api-client/unified-api-client.ts (4)

120-122: LGTM: createCustomer method implemented correctly.

The createCustomer method is well-implemented, following RESTful API practices for creating a new resource. The use of the Customer type ensures type safety for the payload.

Consider adding specific error handling for this method to provide more detailed error information or perform custom error handling if needed. For example:

public async createCustomer(payload: Customer) {
  try {
    return await this.axiosInstance.post('/customers', payload);
  } catch (error) {
    this.logger.error('Error creating customer', error);
    throw error;
  }
}

124-126: LGTM: updateCustomer method implemented correctly.

The updateCustomer method is well-implemented, following RESTful API practices for updating an existing resource. The use of the Customer type ensures type safety for the payload.

Consider adding specific error handling for this method to provide more detailed error information or perform custom error handling if needed. For example:

public async updateCustomer(id: string, payload: Customer) {
  try {
    return await this.axiosInstance.put(`/customers/${id}`, payload);
  } catch (error) {
    this.logger.error(`Error updating customer with id ${id}`, error);
    throw error;
  }
}

128-130: LGTM: deleteCustomer method implemented correctly.

The deleteCustomer method is well-implemented, following RESTful API practices for deleting an existing resource.

Consider adding specific error handling for this method to provide more detailed error information or perform custom error handling if needed. For example:

public async deleteCustomer(id: string) {
  try {
    return await this.axiosInstance.delete(`/customers/${id}`);
  } catch (error) {
    this.logger.error(`Error deleting customer with id ${id}`, error);
    throw error;
  }
}

120-130: LGTM: Customer management methods added successfully.

The addition of createCustomer, updateCustomer, and deleteCustomer methods enhances the functionality of the UnifiedApiClient class, providing essential CRUD operations for customer management. The implementation is consistent across all three methods.

Consider adding getCustomer and listCustomers methods to complete the set of CRUD operations:

public async getCustomer(id: string) {
  return await this.axiosInstance.get(`/customers/${id}`);
}

public async listCustomers(params?: { limit?: number; offset?: number }) {
  return await this.axiosInstance.get('/customers', { params });
}

This would provide a comprehensive set of customer management operations in the UnifiedApiClient class.

services/workflows-service/package.json (1)

Line range hint 1-100: Consider performing a dependency audit and cleanup

The package.json file contains a large number of dependencies. Consider the following suggestions:

  1. Run npm audit to check for any security vulnerabilities in the dependencies.
  2. Use a tool like npm-check-updates to identify outdated packages that could be updated.
  3. Review the list of dependencies and devDependencies to remove any that are no longer used in the project.
  4. Consider standardizing the version specifiers (e.g., using ^ for all non-critical dependencies) for consistency.

These steps can help maintain a cleaner and more secure dependency tree.

Also applies to: 101-200

services/workflows-service/src/business-report/business-report.controller.external.ts (3)

9-12: Review Swagger decorators on an excluded controller

Since the controller is excluded from Swagger documentation using @ApiExcludeController(), the other Swagger decorators (@ApiBearerAuth(), @ApiTags('Business Reports')) will not have any effect.

Consider removing these unnecessary decorators to keep the code clean:

-@ApiBearerAuth()
-@ApiTags('Business Reports')
...
-@ApiExcludeController()
+@ApiExcludeController()

11-11: Reevaluate the route path for the controller

Mapping the controller to 'external/business-reports' while using AdminAuthGuard suggests that it's intended for internal use by administrators. Using the term 'external' in the route might be misleading.

Consider changing the route to better reflect its purpose and enhance clarity:

-@Controller('external/business-reports')
+@Controller('admin/business-reports')

Or, if it's meant for external admins:

-@Controller('external/business-reports')
+@Controller('external/admin/business-reports')

21-29: Handle potential performance issues with deep nested includes

The findMany query includes nested relations (project and customer). Deep nesting can lead to performance issues due to complex SQL queries.

Consider selecting only the necessary fields or using lazy loading if supported. Alternatively, fetch related data in separate queries if appropriate.

Example:

return await this.prisma.businessReport.findMany({
  select: {
    id: true,
    name: true,
    project: {
      select: {
        id: true,
        name: true,
        customer: {
          select: {
            id: true,
            name: true,
          },
        },
      },
    },
  },
});
services/workflows-service/src/customer/customer.service.ts (1)

83-92: Consider using static import for 'p-retry'

Using dynamic import('p-retry') within the retry function may introduce unnecessary overhead every time the function is called. Importing p-retry statically at the top of the file can improve performance.

Apply this change:

+ import pRetry from 'p-retry';

 const retry = async (fn: () => Promise<unknown>) => {
-   const { default: pRetry } = await import('p-retry');

   return await pRetry(fn, {
     retries: 5,
     randomize: true,
     minTimeout: 100,
     maxTimeout: 10_000,
   });
 };
services/workflows-service/src/customer/customer.repository.ts (3)

2-2: Question on the necessity of importing PrismaClient

The PrismaClient is imported but not used directly in this file. Since PrismaService extends PrismaClient, and you already have PrismaTransaction for transaction types, consider removing the unused PrismaClient import to keep the code clean.


Line range hint 12-125: Action Required: Update method calls to include transaction where necessary

With the addition of the transaction parameter to several methods, please ensure that all calls to these methods are updated accordingly. Missing the transaction parameter in calls that require transactional context might lead to inconsistent data states.


111-111: Type Assertion in Update Method

In the updateById method, there's a type assertion:

return transaction.customer.update<T & { where: { id: string } }>({ ... });

Ensure that this type assertion is necessary and doesn't mask any underlying type issues. If possible, refactor to eliminate the need for explicit type assertions to maintain type safety.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 17d9fd4 and 88f63fb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • services/workflows-service/package.json (1 hunks)
  • services/workflows-service/src/business-report/business-report.controller.external.ts (1 hunks)
  • services/workflows-service/src/business-report/business-report.module.ts (1 hunks)
  • services/workflows-service/src/common/utils/unified-api-client/unified-api-client.ts (2 hunks)
  • services/workflows-service/src/customer/customer.repository.ts (3 hunks)
  • services/workflows-service/src/customer/customer.service.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (12)
services/workflows-service/src/business-report/business-report.module.ts (2)

18-18: LGTM: New controller import added correctly.

The import statement for BusinessReportControllerExternal follows the existing naming conventions and import structure of the file.


21-21: LGTM: New controller added to the module.

The BusinessReportControllerExternal has been correctly added to the controllers array in the @Module decorator.

To ensure that the new controller is properly implemented and doesn't conflict with existing routes, let's verify its contents:

services/workflows-service/src/common/utils/unified-api-client/unified-api-client.ts (1)

4-4: LGTM: Import statement updated correctly.

The import statement has been appropriately updated to include the Customer type from @prisma/client, which is consistent with the new customer management methods added to the class.

services/workflows-service/package.json (2)

Line range hint 3-3: LGTM: Version update

The version update to 0.7.54 follows semantic versioning conventions. This patch version increment suggests bug fixes or minor changes have been made.


100-100: Verify usage of new dependency

The addition of p-retry (^6.2.0) is a good choice for improving the reliability of promise-based operations. However, please ensure that this library is actually used in the codebase to avoid unnecessary dependencies.

To verify the usage of p-retry, run the following script:

services/workflows-service/src/business-report/business-report.controller.external.ts (1)

17-17: Ensure proper authentication and authorization

Using @UseGuards(AdminAuthGuard) secures the endpoint, but verify that the guard correctly checks for admin privileges and that unauthorized access is appropriately handled.

Run the following script to check for other endpoints using AdminAuthGuard and ensure consistency:

✅ Verification successful

AdminAuthGuard is correctly implemented and consistently applied

The AdminAuthGuard effectively checks for admin privileges across all secured endpoints, and unauthorized access is appropriately handled.

  • Verified in the following files:
    • workflow.controller.internal.ts
    • alert.controller.internal.ts
    • user.controller.internal.ts
    • customer.controller.internal.ts
    • business-report.controller.external.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of AdminAuthGuard to verify its implementation and consistency.

# Search for AdminAuthGuard usage in the codebase
rg 'AdminAuthGuard' --type ts -A 5 -B 2

Length of output: 10872

services/workflows-service/src/customer/customer.service.ts (2)

7-8: Imports added correctly

The imports for UnifiedApiClient and PrismaService are correctly added and will allow for proper interaction with the external API and database transactions.


15-15: PrismaService injected successfully

The PrismaService is properly injected into the constructor, enabling transactional database operations.

services/workflows-service/src/customer/customer.repository.ts (4)

4-4: Verify the definition and usage of PrismaTransaction

Ensure that PrismaTransaction from @/types accurately represents the Prisma transaction client. This verification is important for type safety when the transaction parameter is used across methods.


12-14: Enhancement: Added transaction support to create method

Adding the transaction parameter to the create method enhances flexibility by allowing database operations to be part of a transaction context when needed. This is a good practice for maintaining data consistency.


106-111: Consistent transaction handling in updateById method

Including the transaction parameter and utilizing it in the updateById method aligns with transactional best practices. This consistency across methods ensures that updates can be properly managed within transactions.


123-125: Addition of transaction parameter in deleteById method

By introducing the transaction parameter to the deleteById method and using it for the delete operation, you're enabling transactional control over deletions. This is beneficial for operations that require atomicity.

@MatanYadaev MatanYadaev merged commit 56238f0 into dev Oct 20, 2024
10 checks passed
@MatanYadaev MatanYadaev deleted the bal-2861 branch October 20, 2024 09:46
@Omri-Levy Omri-Levy mentioned this pull request Nov 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants