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

Feaat pagination #429

Conversation

rajesh-jonnalagadda
Copy link
Contributor

No description provided.

Copy link

changeset-bot bot commented May 15, 2024

⚠️ No Changeset found

Latest commit: 8f34e8b

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

vercel bot commented May 15, 2024

@rajeshj11 is attempting to deploy a commit to the Panora Team on Vercel.

A member of the Team first needs to authorize it.

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

Copy link

gitguardian bot commented May 15, 2024

⚠️ GitGuardian has uncovered 3 secrets following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secrets in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
- Generic High Entropy Secret 7ffe07f .env.example View secret
- Generic High Entropy Secret 3ea4955 .env.example View secret
- Generic High Entropy Secret caecd3a .env.example View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secrets safely. Learn here the best practices.
  3. Revoke and rotate these secrets.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Copy link
Contributor

coderabbitai bot commented May 15, 2024

Walkthrough

The updates bring a harmonious blend of code enhancements, configuration additions, and utility function introductions across the codebase. From refining code formatting to integrating Gitlab ticketing cloud settings, optimizing OAuth flows, and improving pagination handling, these changes aim to enhance the codebase's functionality and maintainability.

Changes

Files/Directories Change Summary
.env.example Added Gitlab ticketing cloud integration variables.
apps/magic-link/Dockerfile.dev Added a blank line for formatting.
apps/magic-link/src/hooks/queries/useLinkedUser.tsx, useUniqueMagicLink.tsx Corrected indentation and formatting.
apps/magic-link/src/lib/ProviderModal.tsx Adjusted spacing, formatting, and imports.
packages/api/src/@core/auth/auth.service.ts Updated string literals, added trailing commas, and adjusted logging statements.
packages/api/src/@core/connections/connections.controller.ts Made handleCallback function asynchronous.
packages/api/src/.../ticketing/services/gitlab/gitlab.service.ts Added OAuth code generation and related fields.
packages/api/src/.../ticketing/services/jira/jira.service.ts, jira_service_mgmt/jira.service.ts Updated requests, URLs, and code structure for Jira services.
packages/api/src/@core/encryption/encryption.service.ts Added generateRandomString and generateHash methods.
packages/api/src/@core/utils/types/index.ts Added various utility methods for user UUIDs, remote data, pagination, and request retries.
packages/api/src/crm/user/sync/sync.service.ts Adjusted user fetching logic for single user queries.
packages/api/src/ticketing/account/sync/sync.service.ts Added Pagination import, Utils property, and refactored methods.
packages/api/src/ticketing/collection/services/collection.service.ts Removed a console.log statement.
packages/api/src/.../services/gitlab/index.ts, mappers.ts Added pagination handling, logging updates, and adjusted field mappings.
packages/api/src/.../services/jira/index.ts, mappers.ts Adjusted imports, null value handling, and spread syntax.
packages/api/src/.../services/front/index.ts, mappers.ts Removed extra semicolons and adjusted spread syntax.
packages/api/src/.../ticket/services/gitlab/index.ts Added Utils import, pagination handling, and request retry logic.
packages/api/src/.../ticket/sync/sync.service.ts Added Utils import, pagination support, and refactored methods for service responses.
packages/api/src/.../user/services/gitlab/mappers.ts, sync/sync.service.ts Adjusted field mappings, added Utils import, and initialized Utils in the constructor.

Poem

In code's embrace, we find our way,
With lines aligned, both night and day.
Gitlab's secrets now unveiled,
Pagination's tale detailed.
A rabbit's hop through fields of code,
Brings harmony to our abode.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 25

Out of diff range and nitpick comments (14)
packages/api/src/ticketing/collection/services/gitlab/index.ts (1)

6-11: Ensure all imported modules are necessary.

Please verify that all imported modules are used within the file to avoid unnecessary imports.

packages/api/src/ticketing/ticket/services/gitlab/index.ts (1)

7-11: Ensure all imported modules are necessary.

Please verify that all imported modules are used within the file to avoid unnecessary imports.

packages/api/src/ticketing/ticket/services/gitlab/mappers.ts (1)

4-5: Ensure all imported modules are necessary.

Please verify that all imported modules are used within the file to avoid unnecessary imports.

apps/magic-link/src/lib/ProviderModal.tsx (1)

4-4: Ensure all imported modules are necessary.

Please verify that all imported modules are used within the file to avoid unnecessary imports.

packages/api/src/ticketing/@lib/@utils/index.ts (9)

Line range hint 20-28: Add a warning log when no user is found for the given remote ID and platform.

if (!res) {
  this.logger.warn(`No user found for remote ID ${remote_id} and platform ${remote_platform}`);
  return;
}

Line range hint 64-67: Add a warning log when no user is found for the given UUID.

if (!res) {
  this.logger.warn(`No user found for UUID ${uuid}`);
  throw new Error(`tcg_user not found for uuid ${uuid}`);
}

Line range hint 80-83: Add a warning log when no contact is found for the given remote ID and platform.

if (!res) {
  this.logger.warn(`No contact found for remote ID ${remote_id} and platform ${remote_platform}`);
  return;
}

Line range hint 90-93: Add a warning log when no contact is found for the given UUID.

if (!res) {
  this.logger.warn(`No contact found for UUID ${uuid}`);
  throw new Error(`tcg_contact not found for uuid ${uuid}`);
}

Line range hint 115-118: Add a warning log when no user is found for the given UUID.

if (!res) {
  this.logger.warn(`No user found for UUID ${uuid}`);
  return;
}

Line range hint 128-131: Add a warning log when no user is found for the given UUID.

if (!res) {
  this.logger.warn(`No user found for UUID ${uuid}`);
  throw new Error(`tcg_user not found for uuid ${uuid}`);
}

Line range hint 156-159: Add a warning log when no collection is found for the given UUID.

if (!res) {
  this.logger.warn(`No collection found for UUID ${uuid}`);
  throw new Error(`tcg_contact not found for uuid ${uuid}`);
}

Line range hint 166-169: Add a warning log when no ticket is found for the given remote ID and platform.

if (!res) {
  this.logger.warn(`No ticket found for remote ID ${remote_id} and platform ${remote_platform}`);
  return;
}

Line range hint 176-179: Add a warning log when no ticket is found for the given UUID.

if (!res) {
  this.logger.warn(`No ticket found for UUID ${uuid}`);
  throw new Error(`tcg_contact not found for uuid ${uuid}`);
}
packages/api/src/ticketing/collection/sync/sync.service.ts (1)

Line range hint 202-203: Add a warning log when no collections are found.

if (!collections || collections.length === 0) {
  this.logger.warn(`No collections found for saving in the database`);
  return [];
}
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between ae8128f and 3ea4955.
Files ignored due to path filters (3)
  • docker-compose.dev.yml is excluded by !**/*.yml
  • docker-compose.source.yml is excluded by !**/*.yml
  • docker-compose.yml is excluded by !**/*.yml
Files selected for processing (52)
  • .env.example (1 hunks)
  • apps/magic-link/Dockerfile.dev (1 hunks)
  • apps/magic-link/src/hooks/queries/useLinkedUser.tsx (1 hunks)
  • apps/magic-link/src/hooks/queries/useUniqueMagicLink.tsx (1 hunks)
  • apps/magic-link/src/lib/ProviderModal.tsx (3 hunks)
  • packages/api/src/@core/auth/auth.service.ts (2 hunks)
  • packages/api/src/@core/connections/connections.controller.ts (1 hunks)
  • packages/api/src/@core/connections/ticketing/services/gitlab/gitlab.service.ts (2 hunks)
  • packages/api/src/@core/connections/ticketing/services/jira/jira.service.ts (4 hunks)
  • packages/api/src/@core/connections/ticketing/services/jira_service_mgmt/jira.service.ts (3 hunks)
  • packages/api/src/@core/connections/ticketing/services/ticketing.connection.service.ts (2 hunks)
  • packages/api/src/@core/encryption/encryption.service.ts (1 hunks)
  • packages/api/src/@core/utils/types/index.ts (2 hunks)
  • packages/api/src/@core/utils/types/original/original.ticketing.ts (9 hunks)
  • packages/api/src/crm/user/sync/sync.service.ts (1 hunks)
  • packages/api/src/ticketing/@lib/@utils/index.ts (6 hunks)
  • packages/api/src/ticketing/account/sync/sync.service.ts (1 hunks)
  • packages/api/src/ticketing/collection/services/collection.service.ts (1 hunks)
  • packages/api/src/ticketing/collection/services/gitlab/index.ts (1 hunks)
  • packages/api/src/ticketing/collection/services/gitlab/mappers.ts (1 hunks)
  • packages/api/src/ticketing/collection/services/gitlab/types.ts (1 hunks)
  • packages/api/src/ticketing/collection/services/jira/index.ts (2 hunks)
  • packages/api/src/ticketing/collection/sync/sync.service.ts (7 hunks)
  • packages/api/src/ticketing/collection/types/index.ts (1 hunks)
  • packages/api/src/ticketing/collection/types/model.unified.ts (1 hunks)
  • packages/api/src/ticketing/comment/services/comment.service.ts (1 hunks)
  • packages/api/src/ticketing/comment/services/gitlab/index.ts (1 hunks)
  • packages/api/src/ticketing/comment/services/gitlab/mappers.ts (1 hunks)
  • packages/api/src/ticketing/comment/services/gitlab/types.ts (1 hunks)
  • packages/api/src/ticketing/comment/services/gorgias/index.ts (1 hunks)
  • packages/api/src/ticketing/comment/services/gorgias/mappers.ts (2 hunks)
  • packages/api/src/ticketing/comment/services/jira/index.ts (2 hunks)
  • packages/api/src/ticketing/comment/services/jira/mappers.ts (2 hunks)
  • packages/api/src/ticketing/comment/services/zendesk/mappers.ts (2 hunks)
  • packages/api/src/ticketing/comment/sync/sync.service.ts (7 hunks)
  • packages/api/src/ticketing/comment/types/index.ts (2 hunks)
  • packages/api/src/ticketing/contact/sync/sync.service.ts (1 hunks)
  • packages/api/src/ticketing/tag/services/jira/index.ts (1 hunks)
  • packages/api/src/ticketing/tag/sync/sync.service.ts (2 hunks)
  • packages/api/src/ticketing/tag/types/mappingsTypes.ts (1 hunks)
  • packages/api/src/ticketing/team/sync/sync.service.ts (1 hunks)
  • packages/api/src/ticketing/ticket/services/front/index.ts (1 hunks)
  • packages/api/src/ticketing/ticket/services/gitlab/index.ts (1 hunks)
  • packages/api/src/ticketing/ticket/services/gitlab/mappers.ts (1 hunks)
  • packages/api/src/ticketing/ticket/services/gitlab/types.ts (1 hunks)
  • packages/api/src/ticketing/ticket/services/jira/index.ts (3 hunks)
  • packages/api/src/ticketing/ticket/services/jira/mappers.ts (2 hunks)
  • packages/api/src/ticketing/ticket/sync/sync.service.ts (7 hunks)
  • packages/api/src/ticketing/ticket/types/index.ts (2 hunks)
  • packages/api/src/ticketing/ticket/types/model.unified.ts (1 hunks)
  • packages/api/src/ticketing/user/services/gitlab/index.ts (1 hunks)
  • packages/api/src/ticketing/user/services/gitlab/mappers.ts (1 hunks)
Files not processed due to max files limit (6)
  • packages/api/src/ticketing/user/services/gitlab/types.ts
  • packages/api/src/ticketing/user/services/gorgias/mappers.ts
  • packages/api/src/ticketing/user/sync/sync.service.ts
  • packages/api/src/ticketing/user/types/index.ts
  • packages/api/src/ticketing/user/types/mappingsTypes.ts
  • packages/shared/src/authUrl.ts
Files not reviewed due to errors (6)
  • .env.example (no review received)
  • packages/api/src/ticketing/ticket/services/jira/mappers.ts (no review received)
  • packages/api/src/ticketing/ticket/types/model.unified.ts (no review received)
  • packages/api/src/ticketing/user/services/gitlab/index.ts (no review received)
  • packages/api/src/ticketing/collection/services/gitlab/types.ts (no review received)
  • packages/api/src/@core/connections/ticketing/services/gitlab/gitlab.service.ts (no review received)
Files skipped from review due to trivial changes (17)
  • apps/magic-link/Dockerfile.dev
  • apps/magic-link/src/hooks/queries/useLinkedUser.tsx
  • apps/magic-link/src/hooks/queries/useUniqueMagicLink.tsx
  • packages/api/src/@core/auth/auth.service.ts
  • packages/api/src/@core/connections/ticketing/services/ticketing.connection.service.ts
  • packages/api/src/ticketing/account/sync/sync.service.ts
  • packages/api/src/ticketing/collection/services/collection.service.ts
  • packages/api/src/ticketing/comment/services/comment.service.ts
  • packages/api/src/ticketing/comment/services/gorgias/index.ts
  • packages/api/src/ticketing/comment/services/gorgias/mappers.ts
  • packages/api/src/ticketing/comment/services/jira/index.ts
  • packages/api/src/ticketing/comment/services/jira/mappers.ts
  • packages/api/src/ticketing/comment/services/zendesk/mappers.ts
  • packages/api/src/ticketing/contact/sync/sync.service.ts
  • packages/api/src/ticketing/tag/types/mappingsTypes.ts
  • packages/api/src/ticketing/ticket/services/front/index.ts
  • packages/api/src/ticketing/ticket/services/jira/index.ts
Additional comments not posted (52)
packages/api/src/ticketing/comment/services/gitlab/types.ts (3)

1-27: The BaseComment type definition looks good and follows TypeScript conventions.


29-29: The GitlabCommentInput type definition is correct and useful for input scenarios.


31-33: The GitlabCommentOutput type definition is correct and follows TypeScript conventions.

packages/api/src/ticketing/collection/types/index.ts (2)

6-16: The addition of the pageMeta parameter to the syncCollections method in the ICollectionService interface is appropriate for handling pagination.


Line range hint 18-28: No changes are made to the ICollectionMapper interface.

packages/api/src/ticketing/ticket/types/index.ts (2)

Line range hint 3-15: The addition of the pageMeta parameter to the syncTickets method in the ITicketService interface is appropriate for handling pagination.


Line range hint 17-29: No changes are made to the ITicketMapper interface.

packages/api/src/ticketing/comment/types/index.ts (2)

Line range hint 3-17: The addition of the pageMeta parameter to the syncComments method in the ICommentService interface is appropriate for handling pagination.


Line range hint 19-31: No changes are made to the ICommentMapper interface.

packages/api/src/ticketing/collection/types/model.unified.ts (2)

Line range hint 1-32: The addition of the field_mappings property to the UnifiedCollectionInput class is appropriate for handling custom field mappings.


Line range hint 34-54: No changes are made to the UnifiedCollectionOutput class.

packages/api/src/@core/utils/types/index.ts (2)

30-35: The Pagination type definition is correct and useful for handling pagination.


Line range hint 37-46: The addition of the pageMeta property to the ApiResponse class is appropriate for including pagination metadata in API responses.

packages/api/src/@core/encryption/encryption.service.ts (1)

60-63: The generateHash method looks good and follows best practices.

packages/api/src/ticketing/collection/services/gitlab/mappers.ts (2)

35-48: The unify method looks good and follows best practices.


50-64: The mapSingleCollectionToUnified method looks good and follows best practices.

packages/api/src/ticketing/user/services/gitlab/mappers.ts (2)

34-47: The unify method looks good and follows best practices.


49-72: The mapSingleUserToUnified method looks good and follows best practices.

packages/api/src/ticketing/ticket/services/gitlab/types.ts (2)

1-16: The GitlabTicketInput type looks good and follows best practices.


53-87: The GitlabTicketOutput type looks good and follows best practices.

packages/api/src/ticketing/comment/services/gitlab/mappers.ts (4)

15-17: Constructor changes look good.


19-25: desunify method changes look good.


27-36: unify method changes look good.


43-60: Usage of Utils methods looks good.

packages/api/src/@core/utils/types/original/original.ticketing.ts (2)

85-88: Ensure that the newly added JiraCollectionInput and GitlabCollectionInput types are correctly defined and used in the codebase.

Verification successful

Definitions and Usage of JiraCollectionInput and GitlabCollectionInput Verified

The types JiraCollectionInput and GitlabCollectionInput are correctly defined and used in the codebase.

  • JiraCollectionInput is defined in packages/api/src/ticketing/collection/services/jira/types.ts and used in multiple files including mappers.ts and original.ticketing.ts.
  • GitlabCollectionInput is defined in packages/api/src/ticketing/collection/services/gitlab/types.ts and used in multiple files including mappers.ts and original.ticketing.ts.
  • OriginalCollectionInput includes these new types and is used in relevant files.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the definitions and usage of `JiraCollectionInput` and `GitlabCollectionInput`.

# Test: Search for the type definitions. Expect: Definitions in the appropriate files.
rg --type types $'JiraCollectionInput'
rg --type types $'GitlabCollectionInput'

# Test: Search for the usage of the new types. Expect: Usage in relevant files.
rg --type types $'OriginalCollectionInput'

Length of output: 209



Script:

#!/bin/bash
# Description: Verify the definitions and usage of `JiraCollectionInput` and `GitlabCollectionInput`.

# Test: Search for the type definitions. Expect: Definitions in the appropriate files.
rg 'JiraCollectionInput'
rg 'GitlabCollectionInput'

# Test: Search for the usage of the new types. Expect: Usage in relevant files.
rg 'OriginalCollectionInput'

Length of output: 1765


260-262: Ensure that the newly added JiraCollectionOutput and GitlabCollectionOutput types are correctly defined and used in the codebase.

Verification successful

The newly added JiraCollectionOutput and GitlabCollectionOutput types are correctly defined and used in the codebase.

  • JiraCollectionOutput is defined in packages/api/src/ticketing/collection/services/jira/types.ts.
  • GitlabCollectionOutput is defined in packages/api/src/ticketing/collection/services/gitlab/types.ts.
  • OriginalCollectionOutput is used in multiple files, including:
    • packages/api/src/ticketing/collection/types/index.ts
    • packages/api/src/ticketing/collection/sync/sync.service.ts
    • packages/api/src/@core/utils/types/original/original.ticketing.ts
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the definitions and usage of `JiraCollectionOutput` and `GitlabCollectionOutput`.

# Test: Search for the type definitions. Expect: Definitions in the appropriate files.
rg --type types $'JiraCollectionOutput'
rg --type types $'GitlabCollectionOutput'

# Test: Search for the usage of the new types. Expect: Usage in relevant files.
rg --type types $'OriginalCollectionOutput'

Length of output: 212



Script:

#!/bin/bash
# Description: Verify the definitions and usage of `JiraCollectionOutput` and `GitlabCollectionOutput`.

# Test: Search for the type definitions. Expect: Definitions in the appropriate files.
rg 'type JiraCollectionOutput'
rg 'type GitlabCollectionOutput'

# Test: Search for the usage of the new types. Expect: Usage in relevant files.
rg 'OriginalCollectionOutput'

Length of output: 1362

packages/api/src/@core/connections/ticketing/services/jira/jira.service.ts (2)

120-122: Ensure that process.env.JIRA_API_VERSION is correctly set and used in the account_url field.

Verification successful

The usage of process.env.JIRA_API_VERSION in the account_url field is correctly handled with a fallback value of 2. The environment variable is referenced in several docker-compose files, ensuring it can be set as needed.

  • docker-compose.yml
  • docker-compose.source.yml
  • docker-compose.dev.yml
  • packages/api/src/@core/connections/ticketing/services/jira_service_mgmt/jira.service.ts
  • packages/api/src/@core/connections/ticketing/services/jira/jira.service.ts
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `process.env.JIRA_API_VERSION` in the codebase.

# Test: Search for the usage of `process.env.JIRA_API_VERSION`. Expect: Usage in relevant files.
rg --type js $'process.env.JIRA_API_VERSION'

Length of output: 43



Script:

#!/bin/bash
# Description: Verify the presence of `JIRA_API_VERSION` in environment configuration files.

# Test: Search for `JIRA_API_VERSION` in environment configuration files.
rg --type env 'JIRA_API_VERSION'

# Description: Verify if there are any default values or fallbacks for `JIRA_API_VERSION` in the codebase.

# Test: Search for default values or fallbacks for `JIRA_API_VERSION` in the codebase.
rg --type js 'JIRA_API_VERSION'

# Description: Inspect the `jira.service.ts` file for the usage of `JIRA_API_VERSION`.

# Test: Search for `JIRA_API_VERSION` in the `jira.service.ts` file.
rg --type js 'JIRA_API_VERSION' packages/api/src/@core/connections/ticketing/services/jira/jira.service.ts

Length of output: 295



Script:

#!/bin/bash
# Description: Search for environment configuration files.

# Test: List potential environment configuration files.
fd -e env -e dotenv -e env.local -e env.production -e env.development

# Description: Search for `JIRA_API_VERSION` in environment configuration files.

# Test: Search for `JIRA_API_VERSION` in all potential environment configuration files.
rg 'JIRA_API_VERSION' $(fd -e env -e dotenv -e env.local -e env.production -e env.development)

# Description: Verify if there are any other references to `JIRA_API_VERSION` in the codebase.

# Test: Search for `JIRA_API_VERSION` in the codebase.
rg 'JIRA_API_VERSION'

Length of output: 1624


138-140: Ensure that process.env.JIRA_API_VERSION is correctly set and used in the account_url field.

packages/api/src/@core/connections/ticketing/services/jira_service_mgmt/jira.service.ts (2)

130-132: Ensure that process.env.JIRA_API_VERSION is correctly set and used in the account_url field.


150-152: Ensure that process.env.JIRA_API_VERSION is correctly set and used in the account_url field.

Verification successful

Several files in the codebase define or reference JIRA_API_VERSION:

  • docker-compose.yml
  • docker-compose.source.yml
  • docker-compose.dev.yml
  • .env.example
  • packages/api/src/@core/connections/ticketing/services/jira_service_mgmt/jira.service.ts
  • packages/api/src/@core/connections/ticketing/services/jira/jira.service.ts

These references confirm that process.env.JIRA_API_VERSION is correctly set and used in the account_url field.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `process.env.JIRA_API_VERSION` in the codebase.

# Test: Search for the usage of `process.env.JIRA_API_VERSION`. Expect: Usage in relevant files.
rg --type js $'process.env.JIRA_API_VERSION'

Length of output: 43



Script:

#!/bin/bash
# Description: Verify the definition and setting of `process.env.JIRA_API_VERSION` in the codebase.

# Test 1: Search for the definition of `JIRA_API_VERSION` in environment configuration files.
rg --type env 'JIRA_API_VERSION'

# Test 2: Search for the usage of `process.env.JIRA_API_VERSION` in TypeScript files.
rg --type ts 'process.env.JIRA_API_VERSION'

# Test 3: Search for the usage of `process.env.JIRA_API_VERSION` in JavaScript files.
rg --type js 'process.env.JIRA_API_VERSION'

Length of output: 666



Script:

#!/bin/bash
# Description: Verify the definition and setting of `process.env.JIRA_API_VERSION` in the codebase.

# Test: Search for the definition of `JIRA_API_VERSION` in environment configuration files.
rg 'JIRA_API_VERSION' --glob '*.env'

Length of output: 185



Script:

#!/bin/bash
# Description: Verify the definition and setting of `process.env.JIRA_API_VERSION` in the codebase.

# Test: Search for the definition of `JIRA_API_VERSION` in environment configuration files with debug information.
rg 'JIRA_API_VERSION' --glob '*.env' --debug

Length of output: 212264



Script:

#!/bin/bash
# Description: Verify the definition and setting of `process.env.JIRA_API_VERSION` in the codebase.

# Test: Search for the definition of `JIRA_API_VERSION` in environment configuration files, including hidden files and directories.
rg 'JIRA_API_VERSION' --glob '**/*' --hidden

Length of output: 794

packages/api/src/ticketing/team/sync/sync.service.ts (4)

Line range hint 20-24: Initialization method looks good.


Line range hint 26-39: Job scheduling method looks good.


Line range hint 77-126: Syncing teams for linked user method looks good.


Line range hint 128-211: Saving teams to database method looks good.

packages/api/src/crm/user/sync/sync.service.ts (4)

Line range hint 20-24: Initialization method looks good.


Line range hint 26-39: Job scheduling method looks good.


Line range hint 77-126: Syncing users for linked user method looks good.


Line range hint 128-211: Saving users to database method looks good.

packages/api/src/ticketing/tag/sync/sync.service.ts (4)

Line range hint 20-24: Initialization method looks good.


Line range hint 26-39: Job scheduling method looks good.


Line range hint 77-126: Syncing tags for linked user method looks good.


Line range hint 128-211: Saving tags to database method looks good.

packages/api/src/ticketing/ticket/sync/sync.service.ts (5)

6-6: The import statement for Utils is correctly added.

Also applies to: 20-20


23-23: The initialization of the Utils instance in the constructor is correctly done.

Also applies to: 33-33


72-77: The changes to the user fetching logic in the syncTickets method improve readability.


156-166: The use of utility methods for handling service and saving data to the database in the syncTicketsForLinkedUser method is a good practice and improves code modularity.

Also applies to: 210-211


223-223: The changes to the data handling logic in the saveTicketsInDb method improve readability.

Also applies to: 225-225

packages/api/src/ticketing/comment/sync/sync.service.ts (5)

6-6: The import statement for Utils is correctly added.

Also applies to: 20-20


24-24: The initialization of the Utils instance in the constructor is correctly done.

Also applies to: 34-34


73-78: The changes to the user fetching logic in the syncComments method improve readability.

Also applies to: 80-80


172-214: The use of utility methods for handling service and saving data to the database in the syncCommentsForLinkedUser method is a good practice and improves code modularity.

Also applies to: 222-223


257-265: The changes to the data handling logic in the saveCommentsInDb method improve readability.

packages/api/src/ticketing/@lib/@utils/index.ts Outdated Show resolved Hide resolved
Comment on lines 69 to +75
? [
await this.prisma.users.findUnique({
where: {
id_user: user_id,
},
}),
]
await this.prisma.users.findUnique({
where: {
id_user: user_id,
},
}),
]
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid using map with async functions.

Using map with async functions does not wait for the promises to resolve. Use a for...of loop instead.

- linkedUsers.map(async (linkedUser) => {
+ for (const linkedUser of linkedUsers) {
+   await (async (linkedUser) => {
      try {
        const providers = TICKETING_PROVIDERS;
        for (const provider of providers) {
          try {
            await this.syncTeamsForLinkedUser(
              provider,
              linkedUser.id_linked_user,
              id_project,
            );
          } catch (error) {
            handleServiceError(error, this.logger);
          }
        }
      } catch (error) {
        handleServiceError(error, this.logger);
      }
+   })(linkedUser);
+ }

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.

Suggested change
? [
await this.prisma.users.findUnique({
where: {
id_user: user_id,
},
}),
]
await this.prisma.users.findUnique({
where: {
id_user: user_id,
},
}),
]
? [
await this.prisma.users.findUnique({
where: {
id_user: user_id,
},
}),
]
for (const linkedUser of linkedUsers) {
await (async (linkedUser) => {
try {
const providers = TICKETING_PROVIDERS;
for (const provider of providers) {
try {
await this.syncTeamsForLinkedUser(
provider,
linkedUser.id_linked_user,
id_project,
);
} catch (error) {
handleServiceError(error, this.logger);
}
}
} catch (error) {
handleServiceError(error, this.logger);
}
})(linkedUser);
}

packages/api/src/@core/encryption/encryption.service.ts Outdated Show resolved Hide resolved
Comment on lines 10 to 32
desunify(
source: UnifiedCollectionInput,
customFieldMappings?: {
slug: string;
remote_id: string;
}[],
): GitlabCollectionInput {
const result: GitlabCollectionInput = {
name: source.name,
description: source.description ?? '',
path: source.name,
};
if (customFieldMappings && source.field_mappings) {
for (const [k, v] of Object.entries(source.field_mappings)) {
const mapping = customFieldMappings.find(
(mapping) => mapping.slug === k,
);
if (mapping) {
result[mapping.remote_id] = v;
}

return result;
}
}
return result;
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using reduce for better readability when handling custom field mappings.

-    if (customFieldMappings && source.field_mappings) {
-      for (const [k, v] of Object.entries(source.field_mappings)) {
-        const mapping = customFieldMappings.find(
-          (mapping) => mapping.slug === k,
-        );
-        if (mapping) {
-          result[mapping.remote_id] = v;
-        }
-      }
-    }
+    if (customFieldMappings && source.field_mappings) {
+      result = Object.entries(source.field_mappings).reduce((acc, [k, v]) => {
+        const mapping = customFieldMappings.find((mapping) => mapping.slug === k);
+        if (mapping) {
+          acc[mapping.remote_id] = v;
+        }
+        return acc;
+      }, result);
+    }

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.

Suggested change
desunify(
source: UnifiedCollectionInput,
customFieldMappings?: {
slug: string;
remote_id: string;
}[],
): GitlabCollectionInput {
const result: GitlabCollectionInput = {
name: source.name,
description: source.description ?? '',
path: source.name,
};
if (customFieldMappings && source.field_mappings) {
for (const [k, v] of Object.entries(source.field_mappings)) {
const mapping = customFieldMappings.find(
(mapping) => mapping.slug === k,
);
if (mapping) {
result[mapping.remote_id] = v;
}
return result;
}
}
return result;
desunify(
source: UnifiedCollectionInput,
customFieldMappings?: {
slug: string;
remote_id: string;
}[],
): GitlabCollectionInput {
const result: GitlabCollectionInput = {
name: source.name,
description: source.description ?? '',
path: source.name,
};
if (customFieldMappings && source.field_mappings) {
result = Object.entries(source.field_mappings).reduce((acc, [k, v]) => {
const mapping = customFieldMappings.find((mapping) => mapping.slug === k);
if (mapping) {
acc[mapping.remote_id] = v;
}
return acc;
}, result);
}
return result;

Comment on lines 10 to 25
const provider = findProviderByName(providerName);
return (
<div className="fixed inset-0 flex justify-center items-center">
<div className="text-center p-6 bg-[#1d1d1d] rounded-lg">
<div className='icon-wrapper'>
<img src={provider!.logoPath} alt={provider!.name} className="mx-auto mb-4 w-14 h-14 rounded-xl" />
</div>

<h4 className="text-lg font-bold mb-2">Continue in {provider!.name}</h4>
<p className="text-gray-400 mb-4">Accepting oAuth access to Panora</p>
<div className='flex justify-center items-center'>

</div>
</div>
);
</div>
);
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance error handling in LoadingOverlay.

Consider adding error handling for cases where the provider information is not available or invalid.

const LoadingOverlay = ({ providerName }: { providerName: string }) => {
  const provider = findProviderByName(providerName);
  if (!provider) {
    console.error(`Provider not found: ${providerName}`);
    return null;
  }
  return (
    <div className="fixed inset-0 flex justify-center items-center">
      <div className="text-center p-6 bg-[#1d1d1d] rounded-lg">
        <div className='icon-wrapper'>
          <img src={provider.logoPath} alt={provider.name} className="mx-auto mb-4 w-14 h-14 rounded-xl" />
        </div>
        <h4 className="text-lg font-bold mb-2">Continue in {provider.name}</h4>
        <p className="text-gray-400 mb-4">Accepting oAuth access to Panora</p>
        <div className='flex justify-center items-center'>
        </div>
      </div>
    </div>
  );
};

Comment on lines +119 to +197
async syncComments(
linkedUserId: string,
id_ticket: string,
_?: string[],
pageMeta?: Pagination,
): Promise<ApiResponse<GitlabCommentOutput[]>> {
try {
pageMeta = pageMeta || ({ isFirstPage: true } as Pagination);
let baseUrl = pageMeta?.baseUrl;
const connection =
pageMeta?.connection ||
(await this.prisma.connections.findFirst({
where: {
id_linked_user: linkedUserId,
provider_slug: 'gitlab',
vertical: 'ticketing',
},
}));
if (!baseUrl) {
//retrieve ticket remote id so we can retrieve the comments in the original software
// const ticket = await this.prisma.tcg_tickets.findUnique({
// where: {
// id_tcg_ticket: id_ticket,
// },
// select: {
// remote_id: true,
// // project_remote_id: true,
// },
// });

const remoteTicketData = await this.prisma.remote_data.findFirst({
where: {
ressource_owner_id: id_ticket,
},
});
const remotedata = JSON.parse(remoteTicketData.data);
baseUrl =
pageMeta?.baseUrl ||
`${connection.account_url}/projects/${remotedata.project_id}/issues/${remotedata.iid}/notes`;
pageMeta = {
...pageMeta,
baseUrl,
};
}
const apiurl = this.utils.getPaginateUrl(baseUrl, 'gitlab', pageMeta);
const resp = await this.utils.sendRequestWithRetry({
url: apiurl,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.cryptoService.decrypt(
connection.access_token,
)}`,
},
});
this.logger.log(`Synced gitlab comments !`);
const links = this.utils.extractPaginationDetailsFromResponse(
resp,
'gitlab',
);
const comments = resp.data?.filter((comment) => !comment.system);
const newPageMeta = { ...pageMeta, isFirst: false, connection, links };
newPageMeta.isLastPage = this.utils.getLastPageStatus(
newPageMeta,
'gitlab',
);
this.logger.log(
`fetched the gitlab comments of size ${resp?.data?.length}. ${
newPageMeta?.isLastPage
? 'This is this last page.'
: 'Syncing into system and waiting for next page results....'
}}`,
);
return {
data: comments,
message: 'Gitlab comments retrieved',
statusCode: 200,
pageMeta: newPageMeta,
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Several files in the codebase still use the old function signature.

  • The syncComments method in packages/api/src/ticketing/comment/services/gitlab/index.ts has pagination handling logic, but there are no tests found for this method.

Please ensure that tests are added to verify the pagination handling logic in the syncComments method.

Analysis chain

Ensure that the pagination handling logic in the syncComments method is correctly implemented and tested.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the implementation and testing of pagination handling in the `syncComments` method.

# Test: Search for the usage of the `syncComments` method. Expect: Usage in relevant files.
rg --type js $'syncComments'

# Test: Search for the tests related to the `syncComments` method. Expect: Tests in the appropriate test files.
rg --type js $'syncComments' --files-with-matches | xargs -I {} rg --type js $'test' {}

Length of output: 115



Script:

#!/bin/bash
# Description: Verify the implementation and testing of pagination handling in the `syncComments` method.

# Test: Search for the implementation of the `syncComments` method in the codebase.
ast-grep --lang typescript --pattern $'class $_ {
  $$$
  async syncComments($_, $_, $_, $_): Promise<$_> {
    $$$
  }
  $$$
}'

# Test: Search for test files that might contain tests for the `syncComments` method.
fd --type f --name '*test*.ts'

# Test: Verify the pagination handling logic within the `syncComments` method.
rg --type ts 'pageMeta' packages/api/src/ticketing/comment/services/gitlab/index.ts

Length of output: 924



Script:

#!/bin/bash
# Description: Verify the implementation and testing of pagination handling in the `syncComments` method.

# Corrected Test: Search for test files that might contain tests for the `syncComments` method.
fd --type f 'test'

# Test: Search for tests related to the `syncComments` method.
rg --type ts 'syncComments' $(fd --type f 'test')

Length of output: 276



Script:

#!/bin/bash
# Description: Verify the implementation and testing of pagination handling in the `syncComments` method.

# Test: Search for any test files that might contain tests for the `syncComments` method.
fd --type f 'test' --exec rg 'syncComments' {}

# Test: Verify the pagination handling logic within the `syncComments` method.
rg --type ts 'pageMeta' packages/api/src/ticketing/comment/services/gitlab/index.ts

Length of output: 557

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

Out of diff range and nitpick comments (2)
packages/api/src/ticketing/@lib/@utils/index.ts (2)

Line range hint 23-25: Add a warning log when no user is found for the given remote ID and platform.

if (!res) {
  this.logger.warn(`No user found for remote ID ${remote_id} and platform ${remote_platform}`);
  return;
}

Line range hint 83-85: Add a warning log when no contact is found for the given remote ID and platform.

if (!res) {
  this.logger.warn(`No contact found for remote ID ${remote_id} and platform ${remote_platform}`);
  return;
}
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 3ea4955 and 48dcedc.
Files selected for processing (10)
  • packages/api/src/ticketing/@lib/@utils/index.ts (6 hunks)
  • packages/api/src/ticketing/collection/services/gitlab/index.ts (1 hunks)
  • packages/api/src/ticketing/collection/sync/sync.service.ts (7 hunks)
  • packages/api/src/ticketing/comment/services/front/index.ts (1 hunks)
  • packages/api/src/ticketing/comment/services/front/mappers.ts (3 hunks)
  • packages/api/src/ticketing/comment/sync/sync.service.ts (7 hunks)
  • packages/api/src/ticketing/ticket/services/gitlab/index.ts (1 hunks)
  • packages/api/src/ticketing/ticket/sync/sync.service.ts (7 hunks)
  • packages/api/src/ticketing/user/services/gitlab/mappers.ts (1 hunks)
  • packages/api/src/ticketing/user/sync/sync.service.ts (6 hunks)
Files skipped from review due to trivial changes (2)
  • packages/api/src/ticketing/comment/services/front/index.ts
  • packages/api/src/ticketing/comment/services/front/mappers.ts
Files skipped from review as they are similar to previous changes (3)
  • packages/api/src/ticketing/collection/services/gitlab/index.ts
  • packages/api/src/ticketing/ticket/services/gitlab/index.ts
  • packages/api/src/ticketing/user/services/gitlab/mappers.ts
Additional comments not posted (10)
packages/api/src/ticketing/ticket/sync/sync.service.ts (5)

20-20: Import statement for Utils added.


23-23: Addition of Utils instance.


33-33: Initialization of Utils instance in the constructor.


156-209: Pagination handling in syncTicketsForLinkedUser method looks good.


210-211: Usage of fetchDataRecursively for pagination.

packages/api/src/ticketing/comment/sync/sync.service.ts (5)

20-20: Import statement for Utils added.


24-24: Addition of Utils instance.


34-34: Initialization of Utils instance in the constructor.


172-213: Pagination handling in syncCommentsForLinkedUser method looks good.


214-223: Usage of fetchDataRecursively for pagination.

@@ -7,7 +11,7 @@ export class Utils {
constructor() {
this.prisma = new PrismaClient();
/*this.cryptoService = new EncryptionService(
new EnvironmentService(new ConfigService()),
new EnvironmentService(new ConfigService()),
Copy link
Contributor

Choose a reason for hiding this comment

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

TODO: Add tests.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 48dcedc and 738a24c.
Files selected for processing (3)
  • apps/magic-link/src/lib/ProviderModal.tsx (3 hunks)
  • packages/api/src/ticketing/@lib/@utils/index.ts (6 hunks)
  • packages/api/src/ticketing/comment/services/gitlab/mappers.ts (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • apps/magic-link/src/lib/ProviderModal.tsx
  • packages/api/src/ticketing/comment/services/gitlab/mappers.ts
Additional comments not posted (15)
packages/api/src/ticketing/@lib/@utils/index.ts (15)

14-14: LGTM! The function fetchFileStreamFromURL is correctly implemented.


Line range hint 17-30: LGTM! The function getUserUuidFromRemoteId is correctly implemented.


Line range hint 62-75: LGTM! The function getUserRemoteIdFromUuid is correctly implemented.


Line range hint 78-91: LGTM! The function getContactUuidFromRemoteId is correctly implemented.


Line range hint 94-107: LGTM! The function getContactRemoteIdFromUuid is correctly implemented.


Line range hint 114-127: LGTM! The function getAsigneeRemoteIdFromUserUuid is correctly implemented.


Line range hint 130-143: LGTM! The function getAssigneeMetadataFromUuid is correctly implemented.


Line range hint 146-159: LGTM! The function getCollectionUuidFromRemoteId is correctly implemented.


Line range hint 162-175: LGTM! The function getCollectionRemoteIdFromUuid is correctly implemented.


Line range hint 178-191: LGTM! The function getTicketUuidFromRemoteId is correctly implemented.


Line range hint 194-207: LGTM! The function getTicketRemoteIdFromUuid is correctly implemented.


226-248: LGTM! The function getPaginateUrl is correctly implemented.


249-279: LGTM! The function extractPaginationDetailsFromResponse is correctly implemented.


281-295: LGTM! The function getLastPageStatus is correctly implemented.


324-337: LGTM! The function sendRequestWithRetry is correctly implemented.

Comment on lines 207 to 223
async getAssigneFromUuids(uuids: string[]) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
id_tcg_user: {
in: uuids,
},
},
distinct: ['id_tcg_user'],
});
if (!res || res?.length === 0) {
return [];
}
return res;
} catch (err) {
throw new Error(err);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the typo in the function name getAssigneFromUuids to getAssigneeFromUuids.

-  async getAssigneFromUuids(uuids: string[]) {
+  async getAssigneeFromUuids(uuids: string[]) {

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.

Suggested change
async getAssigneFromUuids(uuids: string[]) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
id_tcg_user: {
in: uuids,
},
},
distinct: ['id_tcg_user'],
});
if (!res || res?.length === 0) {
return [];
}
return res;
} catch (err) {
throw new Error(err);
}
async getAssigneeFromUuids(uuids: string[]) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
id_tcg_user: {
in: uuids,
},
},
distinct: ['id_tcg_user'],
});
if (!res || res?.length === 0) {
return [];
}
return res;
} catch (err) {
throw new Error(err);
}

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 738a24c and 1ef6070.
Files selected for processing (3)
  • packages/api/src/ticketing/@lib/@utils/index.ts (6 hunks)
  • packages/api/src/ticketing/collection/services/gitlab/mappers.ts (1 hunks)
  • packages/api/src/ticketing/ticket/services/gitlab/mappers.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/ticketing/collection/services/gitlab/mappers.ts
Additional comments not posted (4)
packages/api/src/ticketing/@lib/@utils/index.ts (4)

324-337: LGTM! The sendRequestWithRetry method is well-structured and includes proper error handling.


226-248: LGTM! The getPaginateUrl method is well-structured and handles pagination logic appropriately.


249-279: LGTM! The extractPaginationDetailsFromResponse method is well-structured and handles pagination details appropriately.


281-295: LGTM! The getLastPageStatus method is well-structured and handles last page status appropriately.

Comment on lines +10 to +14
private readonly utils: Utils;

constructor() {
this.utils = new Utils();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider injecting Utils for better testability.

Instead of creating a new instance of Utils within the constructor, consider injecting it as a dependency. This will make the class easier to test and follow the dependency injection pattern used for other services.

constructor(private utils: Utils) {}

Comment on lines 38 to 84
async desunify(
source: UnifiedTicketInput,
customFieldMappings?: {
slug: string;
remote_id: string;
}[],
): Promise<GitlabTicketInput> {
if (!source.project_id) {
// we are getting remote_id from the user.
throw new Error('For gitlab provider, project_id is mandatory!');
}
const projectRemoteId = await this.utils.getCollectionRemoteIdFromUuid(
source.project_id,
);

const result: GitlabTicketInput = {
id: parseInt(projectRemoteId),
title: source.name ?? '',
description: source.description ?? '',
issue_type: this.getIssueType(source.type?.toLowerCase()),
};

// Assuming that 'assigned_to' contains user UUIDs that need to be converted to GitHub usernames
if (source.assigned_to && source.assigned_to.length > 0) {
const assingesTo = await this.utils.getAssigneeFromUuids(
source.assigned_to,
);
const remoteIds = assingesTo.map((user) => Number(user.remote_id));
if (assingesTo.length) {
result.assignee_ids = remoteIds;
result.assignee_id = remoteIds[0];
}
}

private async mapSingleTicketToUnified(
ticket: GitlabTicketOutput,
customFieldMappings?: {
slug: string;
remote_id: string;
}[],
): Promise<UnifiedTicketOutput> {
const field_mappings: { [key: string]: any } = {};
if (customFieldMappings) {
for (const mapping of customFieldMappings) {
field_mappings[mapping.slug] = ticket[mapping.remote_id];
}
}

let opts: any;
if (ticket.type) {
opts = { ...opts, type: ticket.type === "opened" ? "OPEN" : "CLOSED" }
}
if (source.due_date) {
result.due_date = new Date(source.due_date).toLocaleDateString('en-GB', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
});
}
if (source.tags) {
result.labels = (source.tags || []).join(',');
}

if (ticket.assignee) {
//fetch the right assignee uuid from remote id
const user_id = await this.utils.getUserUuidFromRemoteId(
String(ticket.assignee),
'gitlab',
return result;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance logging and error handling in desunify.

Consider adding more detailed logging at various stages of the desunify method to help with debugging and monitoring. Additionally, ensure that all potential error points are covered with appropriate error handling.

try {
  this.logger.log(`Desunifying ticket for project: ${source.project_id}`);
  // Existing code...
  if (!source.project_id) {
    this.logger.error(`Project ID is mandatory for GitLab provider`);
    throw new Error('For gitlab provider, project_id is mandatory!');
  }
  // Existing code...
  this.logger.log(`Desunified ticket successfully for project: ${source.project_id}`);
  return result;
} catch (error) {
  this.logger.error(`Error in desunify: ${error.message}`, error.stack);
  throw error;
}

Comment on lines +86 to +140
async unify(
source: GitlabTicketOutput | GitlabTicketOutput[],
): Promise<UnifiedTicketOutput | UnifiedTicketOutput[]> {
// If the source is not an array, convert it to an array for mapping
try {
const sourcesArray = Array.isArray(source) ? source : [source];
return Promise.all(
sourcesArray.map(async (ticket) => {
const field_mappings: { [key: string]: any } = {};

let opts: any = {};

if (ticket.assignees && ticket.assignees.length > 0) {
opts.assigned_to = await this.utils.getUsersUUidFromRemoteIds(
ticket.assignees.map((user) => `${user.id ?? ''}`),
'gitlab',
);
if (user_id) {
opts = { ...opts, assigned_to: [user_id] };
}
}
}

if (ticket.project_id) {
const tcg_collection_id = await this.utils.getCollectionUuidFromRemoteId(
if (ticket.project_id) {
const tcg_collection_id =
await this.utils.getCollectionUuidFromRemoteId(
String(ticket.project_id),
'gitlab'
);
'gitlab',
);
if (tcg_collection_id) {
opts = { ...opts, project_id: tcg_collection_id }
opts = { ...opts, project_id: tcg_collection_id };
}
}



const unifiedTicket: UnifiedTicketOutput = {
}

if (ticket.closed_at) {
opts.completed_at = new Date(ticket.closed_at).toISOString();
}
if (ticket.due_date) {
opts.due_date = new Date(ticket.due_date).toISOString();
}
const unifiedTicket: UnifiedTicketOutput = {
remote_id: String(ticket.id),
name: ticket.title,
description: ticket.description ? ticket.description : '',
due_date: new Date(ticket.created_at),
tags: ticket.labels ? ticket.labels : [],
field_mappings,
...opts

}

return unifiedTicket;


description: ticket.description ?? '',
status: ticket.state,
tags: ticket.labels || [],
type: this.getIssueType(ticket.issue_type?.toLowerCase(), true),
state: ticket.state?.toUpperCase() ?? '',
priority: ticket.severity,
field_mappings: field_mappings,
...opts,
};
return unifiedTicket;
}),
);
} catch (err) {
throw err;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance logging and error handling in unify.

Consider adding more detailed logging at various stages of the unify method to help with debugging and monitoring. Additionally, ensure that all potential error points are covered with appropriate error handling.

try {
  this.logger.log(`Unifying ticket(s) from GitLab`);
  // Existing code...
  const unifiedTickets = await Promise.all(
    sourcesArray.map(async (ticket) => {
      // Existing code...
      this.logger.log(`Unified ticket successfully: ${ticket.id}`);
      return unifiedTicket;
    }),
  );
  this.logger.log(`Unification completed for ${sourcesArray.length} ticket(s)`);
  return unifiedTickets;
} catch (error) {
  this.logger.error(`Error in unify: ${error.message}`, error.stack);
  throw error;
}

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

Out of diff range and nitpick comments (10)
packages/api/src/ticketing/@lib/@utils/index.ts (10)

Line range hint 17-26: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching user UUID for remote ID ${remote_id} and platform ${remote_platform}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 62-71: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching user remote ID for UUID ${uuid}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 73-82: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching contact UUID for remote ID ${remote_id} and platform ${remote_platform}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 84-93: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching contact remote ID for UUID ${uuid}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 114-123: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching assignee remote ID for user UUID ${uuid}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 125-134: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching assignee metadata for UUID ${uuid}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 145-154: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching collection UUID for remote ID ${remote_id} and platform ${remote_platform}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 156-165: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching collection remote ID for UUID ${uuid}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 167-176: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching ticket UUID for remote ID ${remote_id} and platform ${remote_platform}: ${error.message}`);
+      throw new Error(error);
    }

Line range hint 178-187: Add logging for error cases.

-    } catch (error) {
-      throw new Error(error);
+    } catch (error) {
+      this.logger.error(`Error fetching ticket remote ID for UUID ${uuid}: ${error.message}`);
+      throw new Error(error);
    }
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 1ef6070 and 6f58559.
Files selected for processing (2)
  • packages/api/src/ticketing/@lib/@utils/index.ts (6 hunks)
  • packages/api/src/ticketing/collection/types/index.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/ticketing/collection/types/index.ts
Additional comments not posted (6)
packages/api/src/ticketing/@lib/@utils/index.ts (6)

14-15: LGTM!


225-247: LGTM!


248-278: LGTM!


280-293: LGTM!


296-321: LGTM!


323-336: LGTM!

Comment on lines 105 to 112
async getRemoteDataByResourceOwnerId(uuid: string) {
const remoteData = await this.prisma.remote_data.findFirst({
where: {
ressource_owner_id: uuid,
},
});
return remoteData;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling to the function getRemoteDataByResourceOwnerId.

  async getRemoteDataByResourceOwnerId(uuid: string) {
-    const remoteData = await this.prisma.remote_data.findFirst({
-      where: {
-        ressource_owner_id: uuid,
-      },
-    });
-    return remoteData;
+    try {
+      const remoteData = await this.prisma.remote_data.findFirst({
+        where: {
+          ressource_owner_id: uuid,
+        },
+      });
+      return remoteData;
+    } catch (error) {
+      this.logger.error(`Error fetching remote data for resource owner ID ${uuid}: ${error.message}`);
+      throw new Error(error);
+    }
  }

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.

Suggested change
async getRemoteDataByResourceOwnerId(uuid: string) {
const remoteData = await this.prisma.remote_data.findFirst({
where: {
ressource_owner_id: uuid,
},
});
return remoteData;
}
async getRemoteDataByResourceOwnerId(uuid: string) {
try {
const remoteData = await this.prisma.remote_data.findFirst({
where: {
ressource_owner_id: uuid,
},
});
return remoteData;
} catch (error) {
this.logger.error(`Error fetching remote data for resource owner ID ${uuid}: ${error.message}`);
throw new Error(error);
}
}

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 6f58559 and 8f34e8b.
Files selected for processing (2)
  • packages/api/src/ticketing/@lib/@utils/index.ts (6 hunks)
  • packages/api/src/ticketing/ticket/services/gitlab/mappers.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/ticketing/ticket/services/gitlab/mappers.ts
Additional comments not posted (6)
packages/api/src/ticketing/@lib/@utils/index.ts (6)

231-253: The function getPaginateUrl looks good.


254-284: The function extractPaginationDetailsFromResponse looks good.


286-300: The function getLastPageStatus looks good.


302-327: The function fetchDataRecursively looks good.


329-342: The function sendRequestWithRetry looks good.


1-4: The imports look good.

Comment on lines +36 to +60
async getUsersUUidFromRemoteIds(
remoteIds: string[],
remote_platform: string,
) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
remote_id: {
in: remoteIds,
},
remote_platform: remote_platform,
},
select: {
id_tcg_user: true,
},
distinct: ['id_tcg_user'],
});
if (!res || res.length === 0) {
return [];
}
return res?.map((user) => user.id_tcg_user);
} catch (error) {
throw new Error(error);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the typo in the function name getUsersUUidFromRemoteIds to getUsersUuidFromRemoteIds.

-  async getUsersUUidFromRemoteIds(
+  async getUsersUuidFromRemoteIds(

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.

Suggested change
async getUsersUUidFromRemoteIds(
remoteIds: string[],
remote_platform: string,
) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
remote_id: {
in: remoteIds,
},
remote_platform: remote_platform,
},
select: {
id_tcg_user: true,
},
distinct: ['id_tcg_user'],
});
if (!res || res.length === 0) {
return [];
}
return res?.map((user) => user.id_tcg_user);
} catch (error) {
throw new Error(error);
}
}
async getUsersUuidFromRemoteIds(
remoteIds: string[],
remote_platform: string,
) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
remote_id: {
in: remoteIds,
},
remote_platform: remote_platform,
},
select: {
id_tcg_user: true,
},
distinct: ['id_tcg_user'],
});
if (!res || res.length === 0) {
return [];
}
return res?.map((user) => user.id_tcg_user);
} catch (error) {
throw new Error(error);
}
}

Comment on lines +105 to +118
async getRemoteDataByResourceOwnerId(uuid: string) {
try {
const remoteData = await this.prisma.remote_data.findFirst({
where: {
ressource_owner_id: uuid,
},
});
if (!remoteData)
throw new Error(`ressource_owner_id not found for uuid ${uuid}`);
return remoteData;
} catch (err) {
throw new Error(err);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error logging to the function getRemoteDataByResourceOwnerId.

  async getRemoteDataByResourceOwnerId(uuid: string) {
    try {
      const remoteData = await this.prisma.remote_data.findFirst({
        where: {
          ressource_owner_id: uuid,
        },
      });
      if (!remoteData)
        throw new Error(`ressource_owner_id not found for uuid ${uuid}`);
      return remoteData;
    } catch (err) {
+      this.logger.error(`Error fetching remote data for resource owner ID ${uuid}: ${err.message}`);
      throw new Error(err);
    }
  }

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.

Suggested change
async getRemoteDataByResourceOwnerId(uuid: string) {
try {
const remoteData = await this.prisma.remote_data.findFirst({
where: {
ressource_owner_id: uuid,
},
});
if (!remoteData)
throw new Error(`ressource_owner_id not found for uuid ${uuid}`);
return remoteData;
} catch (err) {
throw new Error(err);
}
}
async getRemoteDataByResourceOwnerId(uuid: string) {
try {
const remoteData = await this.prisma.remote_data.findFirst({
where: {
ressource_owner_id: uuid,
},
});
if (!remoteData)
throw new Error(`ressource_owner_id not found for uuid ${uuid}`);
return remoteData;
} catch (err) {
this.logger.error(`Error fetching remote data for resource owner ID ${uuid}: ${err.message}`);
throw new Error(err);
}
}

Comment on lines +212 to +229
async getAssigneeFromUuids(uuids: string[]) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
id_tcg_user: {
in: uuids,
},
},
distinct: ['id_tcg_user'],
});
if (!res || res?.length === 0) {
return [];
}
return res;
} catch (err) {
throw new Error(err);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the typo in the function name getAssigneFromUuids to getAssigneeFromUuids.

-  async getAssigneFromUuids(uuids: string[]) {
+  async getAssigneeFromUuids(uuids: string[]) {

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.

Suggested change
async getAssigneeFromUuids(uuids: string[]) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
id_tcg_user: {
in: uuids,
},
},
distinct: ['id_tcg_user'],
});
if (!res || res?.length === 0) {
return [];
}
return res;
} catch (err) {
throw new Error(err);
}
}
async getAssigneeFromUuids(uuids: string[]) {
try {
const res = await this.prisma.tcg_users.findMany({
where: {
id_tcg_user: {
in: uuids,
},
},
distinct: ['id_tcg_user'],
});
if (!res || res?.length === 0) {
return [];
}
return res;
} catch (err) {
throw new Error(err);
}
}

Comment on lines 12 to +13
/*this.cryptoService = new EncryptionService(
new EnvironmentService(new ConfigService()),
new EnvironmentService(new ConfigService()),
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove commented-out code if not needed.

- /*this.cryptoService = new EncryptionService(
- new EnvironmentService(new ConfigService()), 
- );*/

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.

Suggested change
/*this.cryptoService = new EncryptionService(
new EnvironmentService(new ConfigService()),
new EnvironmentService(new ConfigService()),

@rflihxyz rflihxyz closed this May 16, 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.

3 participants